text:
import os
import sys
import h5py

import numpy as np
import pandas as pd

from tronn.plot.visualization import scale_scores
from tronn.plot.visualization import plot_weights_group
from tronn.util.formats import array_to_bed

SECOND_PASS_KEEP = [
    "UNKNOWN",
    "MUC15",
    "LYPD5",
    "PIK3C2B"
]

idx_to_letter = {
    0: "A",
    1: "C",
    2: "G",
    3: "T"
}

def get_vignettes(
        h5_file,
        bed_file,
        out_dir,
        tmp_dir=".",
        importance_filter=True,
        interpretation_task_indices=[0,1,2,3,4,5,6,9,10,12],
        rsid_to_genes=None,
        ensembl_to_hgnc=None):
    """get the example indices at the locations of interest
    """
    # prefix (scanmotifs)
    dirname = h5_file.split("/")[-2]
    print dirname

    # get a bed file from the h5 file and overlap
    metadata_bed_file = "{}/{}.metadata.tmp.bed.gz".format(
        tmp_dir, dirname)
    with h5py.File(h5_file, "r") as hf:
        metadata = hf["example_metadata"][:,0]
    array_to_bed(metadata, metadata_bed_file, name_key="all", merge=False)

    # overlap and read back in
    overlap_file = "{}/{}.overlap.bed.gz".format(
        tmp_dir, os.path.basename(metadata_bed_file).split(".bed")[0])
    overlap_cmd = (
        "zcat {} | "
        "awk -F '\t' 'BEGIN{{OFS=\"\t\"}}{{ $2=$2+20; $3=$3-20; print }}' | " # offset
        "bedtools intersect -wo -a stdin -b {} | "
        "gzip -c > {}").format(metadata_bed_file, bed_file, overlap_file)
    print overlap_cmd
    os.system(overlap_cmd)
    try:
        overlap_data = pd.read_csv(overlap_file, sep="\t", header=None)
    except pd.errors.EmptyDataError:
        return 0
    print overlap_data.shape

    # for each, go back in and find the index, then check importance scores
    total = 0
    for overlap_i in range(overlap_data.shape[0]):
        metadata_i = overlap_data[3][overlap_i]
        metadata_string = metadata_i.split("features=")[-1].replace(":", "_")
        h5_i = np.where(metadata == metadata_i)[0][0]
        rsid_i = overlap_data[9][overlap_i]
        variant_pos = overlap_data[7][overlap_i] - overlap_data[1][overlap_i]
        variant_pos -= 1 # offset by 1

        # continue if variant not actually in active region
        if variant_pos < 0:
            continue

        # filter here, if using rsid to genes
        if (rsid_to_genes is not None) and (len(rsid_to_genes.keys()) > 0):
            try:
                gene_id = rsid_to_genes[rsid_i]
            except:
                continue
        else:
            gene_id = "UNKNOWN"

        # and get hgnc
        hgnc_id = ensembl_to_hgnc.get(gene_id, "UNKNOWN")

        # manual filtering
        manual_keep = False
        for keep_id in SECOND_PASS_KEEP:
            if hgnc_id in keep_id:
                manual_keep = True
        if not manual_keep:
            continue

        # and get importance score at variant position
        with h5py.File(h5_file, "r") as hf:
            if False:
                variant_impt = hf["sequence-weighted.active"][h5_i,:,variant_pos,:]
            else:
                start_pos = max(variant_pos - 1, 0)
                stop_pos = min(variant_pos + 1, hf["sequence-weighted.active"].shape[2])
                variant_impt = hf["sequence-weighted.active"][h5_i,:,start_pos:stop_pos,:]
            variant_val = hf["sequence.active"][h5_i,:,variant_pos,:]
            variant_ref_bp = idx_to_letter[np.argmax(variant_val)]

        # variant scoring
        variant_impt_max = np.max(np.abs(variant_impt))
        if variant_impt_max > 0:

            # plot out
            if True:
                # tODO variant pos needs to bne updated!
                plot_prefix = "{}/{}-{}.{}.{}.{}.{}.{}".format(
                    out_dir, gene_id, hgnc_id, dirname, h5_i, metadata_string, rsid_i,
                    variant_ref_bp)
                # remember to add position to plot prefix after adjusments!!
                    #out_dir, dirname, gene_id, hgnc_id, h5_i, rsid_i,
                    #variant_pos, variant_ref_bp, metadata_string)

                with h5py.File(h5_file, "r") as hf:
                    #for key in sorted(hf.keys()): print key, hf[key].shape
                    mut_indices = hf["sequence-weighted.active.pwm-scores.thresh.max.idx.motif_mut"][h5_i,3]

                    # get labels
                    signals = hf["labels"][h5_i]
                    total_tasks = signals.shape[0]
                    signals = signals[interpretation_task_indices]

                    # get logits
                    logits = hf["logits.motif_mut"][h5_i]
                    logits = logits[:,interpretation_task_indices]

                    # best idx
                    best_task_idx = np.argmax(logits[0])
                    best_orig_task_idx = range(total_tasks)[best_task_idx]

                    # filter for best idx
                    logits_best_task = logits[:,best_task_idx]

                    # check and make sure the outputs is synergy (for good vignettes)
                    if not np.all(logits_best_task[0] >= logits_best_task):
                        continue
                    if not np.all(logits_best_task[3] <= logits_best_task):
                        continue
                    observed = logits_best_task[0] - logits_best_task[3]
                    expected = logits_best_task[1] + logits_best_task[2] - 2*logits_best_task[3]
                    if observed < expected:
                        continue

                    # grab importances and plot
                    orig_importances = hf["sequence-weighted"][h5_i][:,420:580]
                    match_importances = hf["sequence-weighted.active"][h5_i]
                    importances = scale_scores(orig_importances, match_importances)
                    plot_file = "{}.pos-{}.impts-task.pdf".format(plot_prefix, variant_pos)
                    print plot_file
                    #plot_weights_group(importances, plot_file)

                    # grab interaction importances and plot
                    orig_interact_impts = np.mean(
                        hf["sequence-weighted.motif_mut.ci"][h5_i], axis=1)
                    orig_interact_impts = np.expand_dims(orig_interact_impts, axis=-1)
                    mut_seqs = hf["sequence.motif_mut"][h5_i][:,:,420:580]
                    orig_interact_impts = np.multiply(orig_interact_impts, mut_seqs)
                    mut_mask = hf["sequence.motif_mut.mask"][h5_i] == 0
                    orig_interact_impts = np.multiply(orig_interact_impts, mut_mask)
                    orig_interact_impts = orig_interact_impts[:,best_task_idx]

                    # also grab actual v predicted
                    keep_indices = [0,1,2,3,4,5,6,9,10,12]
                    actual = hf["ATAC_SIGNALS.NORM"][h5_i][keep_indices]
                    #actual = hf["labels"][h5_i][keep_indices]
                    predicted = hf["logits.norm"][h5_i][keep_indices]

                # test
                orig_interact_impts[0] = importances[best_task_idx]

                # scale appropriately
                if False:
                    match_interact_impts = hf["sequence-weighted.motif_mut"][h5_i]
                    match_interact_impts = match_interact_impts[:,best_task_idx]
                    interaction_impts = scale_scores(
                        orig_interact_impts,
                        match_interact_impts)
                else:
                    orig_interact_impts = np.divide(
                        orig_interact_impts,
                        np.sum(abs(orig_interact_impts), axis=(1,2), keepdims=True))
                    interaction_impts = orig_interact_impts

                # To consider - multiply by logits?
                if True:
                    logit_factors = np.reshape(logits_best_task, (-1,1,1))
                    interaction_impts = np.multiply(interaction_impts, logit_factors)

                # clip negative
                flattened_vals = np.abs(interaction_impts).flatten()
                sort_indices = np.argsort(flattened_vals)
                thresh = flattened_vals[sort_indices][-7] # clip worst two
                #thresh = np.percentile(np.abs(interaction_impts), 99.99)
                interaction_impts[np.where(interaction_impts > thresh)] = thresh
                interaction_impts[np.where(interaction_impts < -thresh)] = -thresh

                # clip the importances for better fig
                if np.abs(mut_indices[0] - mut_indices[1]) < 10:
                    continue
                clip_extend = 60
                midpoint = int(np.sum(mut_indices) / 2) - 420
                start = max(midpoint - clip_extend, 0)
                end = start + clip_extend*2
                if end > interaction_impts.shape[1]:
                    end = interaction_impts.shape[1]
                    start = end - clip_extend*2

                interaction_impts = interaction_impts[:,start:end]
                print interaction_impts.shape

                # TODO plot out ATAC vs predicted
                actual_v_predicted = pd.DataFrame({
                    "timepoint": ["d0.0", "d0.5", "d1.0", "d1.5", "d2.0", "d2.5", "d3.0", "d4.5", "d5.0", "d6.0"],
                    "ATAC": actual,
                    "predicted": predicted}).set_index("timepoint")
                plot_data_file = "{}.atac.actual_v_predicted.txt".format(plot_prefix)
                actual_v_predicted.to_csv(plot_data_file, header=True, index=True, sep="\t")
                plot_file = "{}.atac.actual_v_predicted.pdf".format(plot_prefix)
                fig2_dir = "/users/dskim89/git/ggr-project/figs/fig_2.modelling"
                plot_cmd = "{}/plot.atac.actual_v_pred.R {} {}".format(
                    fig2_dir, plot_data_file, plot_file)
                print plot_cmd
                os.system(plot_cmd)

                # plot interaction impts
                plot_file = "{}.pos-{}.impts-interact.task-{}.pdf".format(
                    plot_prefix, variant_pos - start, best_orig_task_idx)
                print plot_file
                plot_weights_group(interaction_impts, plot_file)

                # plot logits
                #logits_df = pd.DataFrame(np.expand_dims(logits_best_task, axis=0))
                logits_tmp_file = "{}.logits.tmp.txt.gz".format(plot_prefix)
                logits_df = pd.DataFrame({
                    "logits": logits_best_task,
                    "mut_type": ["endog", "motif,scr", "scr,motif", "scr,scr"]})
                logits_df.to_csv(logits_tmp_file, sep="\t", compression="gzip", index=False)
                git_dir = "/users/dskim89/git/ggr-project/figs/fig_3.interactions"
                plot_cmd = "{}/plot.interaction.logits.R {} {}.logits.pdf".format(
                    git_dir, logits_tmp_file, plot_prefix)
                print plot_cmd
                os.system(plot_cmd)

                # if there was an associated gene, need the gene rna bar
                if gene_id != "UNKNOWN":
                    # plot rna bar
                    plot_file = "{}/gene_vals.{}.pdf".format(out_dir, hgnc_id)
                    git_dir = "/users/dskim89/git/ggr-project/figs/fig_1.datasets"
                    GGR_DIR = "/mnt/lab_data/kundaje/users/dskim89/ggr/integrative/v1.0.0a"
                    rna_file = "{}/results/rna/timeseries/matrices/ggr.rna.counts.pc.expressed.timeseries_adj.pooled.rlog.mat.txt.gz".format(GGR_DIR)
                    if not os.path.isfile(plot_file):
                        plot_cmd = "{}/plot.rna_bar.R {} {} {}".format(
                            git_dir, rna_file, gene_id, plot_file)
                        print plot_cmd
                        os.system(plot_cmd)

            total += 1

    print "TOTAL:", total

    return total

def main():
    """look for interesting vignettes with variants in them
    """
    # args
    gwas_file = sys.argv[1]
    out_dir = sys.argv[2]
    filter_genes_file = sys.argv[3]
    gene_id_mapping_file = sys.argv[4]
    h5_dir = sys.argv[5]
    summary_file = sys.argv[6]
    tmp_dir = "{}/tmp".format(out_dir)
    os.system("mkdir -p {}".format(tmp_dir))

    # set up h5 files
    summary = pd.read_csv(summary_file, sep="\t")
    summary = summary[~summary["interaction"].str.contains("FAILED", regex=False)]
    dirnames = summary["grammar"].values
    h5_files = ["{}/{}/ggr.synergy.h5".format(h5_dir, dirname) for dirname in dirnames]

    # filter_genes
    genes_mat = pd.read_csv(filter_genes_file, sep="\t", index_col=0)
    filter_genes = genes_mat.index.values.tolist()

    # get hgnc ids
    mappings = pd.read_csv(gene_id_mapping_file, sep="\t", header=0)
    ensembl_to_hgnc = dict(zip(
        mappings["ensembl_gene_id"].values,
        mappings["hgnc_symbol"].values))

    # rsid to gene
    rsid_to_genes = {}
    if "gtex" in gwas_file:
        signif_variant_gene_pairs_files = [
            "/mnt/lab_data/kundaje/users/dskim89/ggr/variants/GTEx/GTEx_Analysis_v7_eQTL/Skin_Not_Sun_Exposed_Suprapubic.v7.signif_variant_gene_pairs.txt.gz",
            "/mnt/lab_data/kundaje/users/dskim89/ggr/variants/GTEx/GTEx_Analysis_v7_eQTL/Skin_Sun_Exposed_Lower_leg.v7.signif_variant_gene_pairs.txt.gz"]

        for filename in signif_variant_gene_pairs_files:
            print filename
            pairs = pd.read_csv(filename, sep="\t")
            pairs["gene_id"] = pairs["gene_id"].str.split(".").str[0]
            print pairs.shape

            if True:
                pairs = pairs[pairs["gene_id"].isin(filter_genes)]
            print pairs.shape

            tmp_rsid_to_genes = dict(zip(pairs["variant_id"], pairs["gene_id"]))
            rsid_to_genes.update(tmp_rsid_to_genes)

    # go through each file
    total = 0
    for h5_file in h5_files:
        print h5_file
        file_total = get_vignettes(
            h5_file,
            gwas_file,
            out_dir,
            tmp_dir=tmp_dir,
            importance_filter=True,
            rsid_to_genes=rsid_to_genes,
            ensembl_to_hgnc=ensembl_to_hgnc)
        total += file_total
    print total

    return

main()


text:
require("requirish")._(module);
var factories  = require("lib/misc/factories");
var coerceNodeId = require("lib/datamodel/nodeid").coerceNodeId;
var ServiceCounter_Schema = {
    id:  coerceNodeId('ns=0;i=873'),
    name: "ServiceCounter",
    fields: [
       {
           name: "totalCount",
           fieldType: "UInt32"
       },
       {
           name: "errorCount",
           fieldType: "UInt32"
       },
        ]
    };
exports.ServiceCounter_Schema = ServiceCounter_Schema;

redpajama_set_name: RedPajamaGithub


text:
DATE_NOW=`date`
echo "IPFS ringpin publish at ${DATE_NOW}"

# Get the currently-published root hash on this node
ROOT_HASH=$(ipfs name resolve)
echo "Using latest published address ${ROOT_HASH}"

# Input data
INPUT_HASH=$1
TARGET_PATH=$2

# Show the operation we're doing
echo "Adding IPFS hash ${INPUT_HASH} as ${TARGET_PATH}"
NEW_ROOT_HASH=$(ipfs object patch $ROOT_HASH add-link -p $TARGET_PATH $INPUT_HASH)
echo "New root hash is ${NEW_ROOT_HASH}"
ipfs name publish $NEW_ROOT_HASH


text:
/* @module TextGradientSVG
 * text-gradient v0.2.0
 */
(function(factory) {
  'use strict';
  if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    window.TextGradientSVG = factory();
  }
}(function factory() {
  'use strict';
  return {
    __wrapperElement: null,
    __textElement: null,
    __maskedClone: null,

    /* Initialize.
     * @override, private, abstract
     */
    _init: function _init() {
      this.__wrapperElement = document.createElement('span');
      this.__textElement = document.createElement('span');

      this._include(this.__wrapperElement.style, {
        position: 'relative',
        display: 'inline-block',
        color: this.options.fallbackColor || this.options.to
      });

      this.__createGradient();
      this.__createMaskedClone();
      this.__wrapperElement.appendChild(this.__textElement);

      this.updateText(this.options.text);
      this.element.appendChild(this.__wrapperElement);
    },

    /* Creates the SVG Mask and Gradient that will be applied to the element.
     * @private
     */
    __createGradient: function __createGradient() {
      var svgMaskString = "" +
        "<mask id='tg-mask-" + this._id +"'  maskContentUnits='objectBoundingBox'>" +
          "<linearGradient id='tg-linear-"+ this._id +"' {coords}>" +
            "<stop stop-color='white' offset='0'/>" +
            "<stop stop-color='white' stop-opacity='0' offset='1'/>" +
          "</linearGradient>" +
          "<rect x='0' y='0' width='1' height='1' fill='url(#tg-linear-"+ this._id +")'/>" +
        "</mask>";

      switch(this.options.direction) {
        case 'top': svgMaskString = svgMaskString.replace(/{coords}/, "x1='0' x2='0' y1='1' y2='0'"); break;
        case 'bottom': svgMaskString = svgMaskString.replace(/{coords}/, "x1='0' x2='0' y1='0' y2='1'"); break;
        case 'left': svgMaskString = svgMaskString.replace(/{coords}/, "x1='1' x2='0' y1='0' y2='0'"); break;
        default: svgMaskString = svgMaskString.replace(/{coords}/, "x1='0' x2='1' y1='0' y2='0'"); break;
      }

      this._svgDefsContainer.insertAdjacentHTML('afterbegin', svgMaskString);
    },

    /* Creates a new element to apply the masking.
     * @private
     */
    __createMaskedClone: function __createMaskedClone() {
      this.__maskedClone = document.createElement('span');

      this._include(this.__maskedClone.style, {
        mask: 'url(#tg-mask-' + this._id +')',
        color: this.options.from,
        position: 'absolute',
        left: 0
      });

      this.__wrapperElement.appendChild(this.__maskedClone);
    },

    /* Implementation to update the text contents of this.element keeping the gradient intact.
     * @override, public, abstract
     */
    updateText: function updateText(text) {
      if (this._destroyed === true) {
        return console.warn('TextGradient: calling on destroyed object');
      }

      this.options.text = text;
      this.__textElement.textContent = text;
      this.__maskedClone.textContent = text;
    },

    /* Implementation to remove the gradient and created elements.
     * @override, public, abstract
     */
    destroy: function destroy() {
      if (this._destroyed === true) {
        return console.warn('TextGradient: calling on destroyed object');
      }

      var svgMaskElement = document.getElementById('tg-mask-' + this._id);
      this._svgDefsContainer.removeChild(svgMaskElement);

      while(this.element.childNodes.length > 0) {
        this.element.removeChild(this.element.childNodes[0]);
      }
      this.element.textContent = this.options.text;

      this.element = null;
      this.options = null;
      this.__wrapperElement = null;
      this.__textElement = null;
      this.__maskedClone = null;
      this._svgDefsContainer = null;
      this._destroyed = true;
    }
  };
}));


text:
<?php

/**
 * Stock resource model
 *
 * @category    Mage
 * @package     Mage_CatalogInventory
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_CatalogInventory_Model_Mysql4_Stock extends Mage_CatalogInventory_Model_Resource_Stock
{
}


text:
#include "src/core/CL/kernels/CLArgMinMaxLayerKernel.h"

#include "arm_compute/core/CL/CLHelpers.h"
#include "arm_compute/core/CL/CLKernelLibrary.h"
#include "arm_compute/core/CL/ICLTensor.h"
#include "arm_compute/core/Helpers.h"
#include "arm_compute/core/TensorInfo.h"
#include "arm_compute/core/Utils.h"
#include "arm_compute/core/Validate.h"
#include "src/core/CL/CLValidate.h"
#include "src/core/helpers/AutoConfiguration.h"
#include "src/core/helpers/WindowHelpers.h"

#include "support/StringSupport.h"

namespace arm_compute
{
namespace
{
Status validate_arguments(const ITensorInfo *input, const ITensorInfo *prev_output, const ITensorInfo *output, unsigned int axis, ReductionOperation op)
{
    ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, output);
    ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(input);
    ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QASYMM8, DataType::QASYMM8_SIGNED, DataType::S32, DataType::F16, DataType::F32);
    ARM_COMPUTE_RETURN_ERROR_ON_MSG(op != ReductionOperation::ARG_IDX_MAX && op != ReductionOperation::ARG_IDX_MIN, "Only ARG_IDX_MAX and ARG_IDX_MIN are supported");
    ARM_COMPUTE_RETURN_ERROR_ON_MSG(axis >= TensorShape::num_max_dimensions, "Reduction axis greater than max number of dimensions");
    ARM_COMPUTE_RETURN_ERROR_ON_MSG(axis > 3, "Unsupported reduction axis");

    if(output->total_size() != 0)
    {
        ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(output, 1, DataType::U32, DataType::S32);
    }
    if(prev_output != nullptr && prev_output->total_size() != 0)
    {
        ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(prev_output, 1, DataType::U32, DataType::S32);
        if(output->total_size() != 0)
        {
            ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(prev_output, output);
        }
    }

    return Status{};
}
} // namespace

CLArgMinMaxLayerKernel::CLArgMinMaxLayerKernel()
    : _input(nullptr), _prev_output(nullptr), _output(nullptr), _reduction_axis(0), _op(ReductionOperation::ARG_IDX_MAX)
{
    _type = CLKernelType::ELEMENTWISE;
}

void CLArgMinMaxLayerKernel::configure(const ICLTensor *input, const ICLTensor *prev_output, ICLTensor *output, unsigned int axis, ReductionOperation op)
{
    configure(CLKernelLibrary::get().get_compile_context(), input, prev_output, output, axis, op);
}

void CLArgMinMaxLayerKernel::configure(const CLCompileContext &compile_context, const ICLTensor *input, const ICLTensor *prev_output, ICLTensor *output, unsigned int axis, ReductionOperation op)
{
    ARM_COMPUTE_ERROR_ON_NULLPTR(input, output);

    TensorShape output_shape{ input->info()->tensor_shape() };
    output_shape.set(axis, 1);
    auto_init_if_empty(*output->info(), input->info()->clone()->set_tensor_shape(output_shape).set_data_type(DataType::S32).reset_padding().set_is_resizable(true));

    ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input->info(), (prev_output != nullptr) ? prev_output->info() : nullptr, output->info(), axis, op));

    auto padding_info = get_padding_info({ input, prev_output, output });

    _input          = input;
    _prev_output    = prev_output;
    _output         = output;
    _reduction_axis = axis;
    _op             = op;

    // Set build options
    const auto vector_size = (axis == 0) ? 16U : adjust_vec_size(16U, input->info()->dimension(0));

    CLBuildOptions build_opts;
    build_opts.add_option_if(_prev_output != nullptr, "-DPREV_OUTPUT");
    build_opts.add_option("-DDATA_TYPE=" + get_cl_type_from_data_type(input->info()->data_type()));
    build_opts.add_option("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(input->info()->dimension(0) % vector_size));
    build_opts.add_option("-DVEC_SIZE=" + support::cpp11::to_string(vector_size));
    build_opts.add_option_if(is_data_type_float(input->info()->data_type()), "-DFLOAT_DATA_TYPE");
    build_opts.add_option_if_else(op == ReductionOperation::ARG_IDX_MAX, "-DARG_MAX", "-DARG_MIN");
    build_opts.add_option("-DDATA_TYPE_OUTPUT=" + get_cl_type_from_data_type(output->info()->data_type()));

    // Create kernel
    cl::NDRange lws_hint = CLKernelLibrary::get().default_ndrange();
    std::string kernel_axis_name;
    switch(axis)
    {
        case 0:
        {
            const ICLTensor *input_for_width = prev_output != nullptr ? _prev_output : _input;
            build_opts.add_option("-DWIDTH=" + support::cpp11::to_string(input_for_width->info()->dimension(0)));

            kernel_axis_name = "x";
            lws_hint         = create_lws_hint_parallel_implementations(input_for_width->info()->dimension(0), vector_size);
        }
        break;
        case 1:
            build_opts.add_option("-DHEIGHT=" + support::cpp11::to_string(input->info()->dimension(1)));
            kernel_axis_name = "y";
            break;
        case 2:
            build_opts.add_option("-DDEPTH=" + support::cpp11::to_string(input->info()->dimension(2)));
            kernel_axis_name = "z";
            break;
        case 3:
            build_opts.add_option("-DDEPTH=" + support::cpp11::to_string(input->info()->dimension(2)));
            build_opts.add_option("-DBATCH=" + support::cpp11::to_string(input->info()->dimension(3)));
            kernel_axis_name = "w";
            break;
        default:
            ARM_COMPUTE_ERROR("Not supported");
    }
    _kernel = create_kernel(compile_context, "arg_min_max_" + kernel_axis_name, build_opts.options());

    // Configure kernel window
    Window win = calculate_max_window((prev_output != nullptr) ? (*prev_output->info()) : (*input->info()), Steps(vector_size));
    ICLKernel::configure_internal(win, lws_hint);

    ARM_COMPUTE_ERROR_ON(has_padding_changed(padding_info));
}

Status CLArgMinMaxLayerKernel::validate(const ITensorInfo *input, const ITensorInfo *prev_output, const ITensorInfo *output, unsigned int axis, ReductionOperation op)
{
    ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, prev_output, output, axis, op));
    return Status{};
}

void CLArgMinMaxLayerKernel::run(const Window &window, cl::CommandQueue &queue)
{
    ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
    ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(IKernel::window(), window);

    switch(_reduction_axis)
    {
        case 0:
        {
            // Set out window
            Window out_window(window);
            out_window.set(Window::DimX, Window::Dimension(0, 0, 0));

            // Get first input and output slices
            Window in_slice  = window.first_slice_window_2D();
            Window out_slice = out_window.first_slice_window_2D();

            // Reshape window
            const unsigned int num_tensors = _prev_output != nullptr ? 3 : 2;

            // Set local sums buffer
            unsigned int local_res_size = lws_hint()[0] * _output->info()->element_size();
            _kernel.setArg(num_arguments_per_2D_tensor() * num_tensors, local_res_size, nullptr);
            do
            {
                unsigned int idx = 0;
                add_2D_tensor_argument(idx, _input, in_slice);
                if(_prev_output != nullptr)
                {
                    add_2D_tensor_argument(idx, _prev_output, in_slice);
                }
                add_2D_tensor_argument(idx, _output, out_slice);
                enqueue(queue, *this, in_slice, lws_hint());
            }
            while(window.slide_window_slice_2D(in_slice) && window.slide_window_slice_2D(out_slice));
        }
        break;
        case 1:
        {
            // Get first input and output slices
            Window window_in{ window };
            window_in.set(Window::DimY, Window::Dimension(0, _input->info()->dimension(1), _input->info()->dimension(1)));
            Window in_slice  = window_in.first_slice_window_2D();
            Window out_slice = window.first_slice_window_2D();

            do
            {
                unsigned int idx = 0;
                add_2D_tensor_argument(idx, _input, in_slice);
                add_2D_tensor_argument(idx, _output, out_slice);
                enqueue(queue, *this, in_slice, lws_hint());
            }
            while(window_in.slide_window_slice_2D(in_slice) && window.slide_window_slice_2D(out_slice));
        }
        break;
        case 2:
        {
            // Get first input and output slices
            Window window_in{ window };
            window_in.set(Window::DimZ, Window::Dimension(0, _input->info()->dimension(2), _input->info()->dimension(2)));
            Window in_slice  = window_in.first_slice_window_3D();
            Window out_slice = window.first_slice_window_3D();

            do
            {
                unsigned int idx = 0;
                add_3D_tensor_argument(idx, _input, in_slice);
                add_3D_tensor_argument(idx, _output, out_slice);
                enqueue(queue, *this, in_slice, lws_hint());
            }
            while(window_in.slide_window_slice_3D(in_slice) && window.slide_window_slice_3D(out_slice));
        }
        break;
        case 3:
        {
            // Get first input and output slices
            Window window_in{ window };
            window_in.set(3, Window::Dimension(0, 1, 1));
            Window in_slice  = window_in.first_slice_window_4D();
            Window out_slice = window.first_slice_window_4D();

            do
            {
                unsigned int idx = 0;
                add_4D_tensor_argument(idx, _input, in_slice);
                add_4D_tensor_argument(idx, _output, out_slice);
                enqueue(queue, *this, in_slice, lws_hint());
            }
            while(window_in.slide_window_slice_4D(in_slice) && window.slide_window_slice_4D(out_slice));
        }
        break;
        default:
            ARM_COMPUTE_ERROR("Not supported");
    }
}
} // namespace arm_compute


text:
static const int kPaintLocationX = 5;

// The height of the line edit.
static const int kLineEditSize = 18;

// The vertical margin of the highlight.
static const int kHighlightVerticalMargin = 5;

// The margin to leave from the top of the line edit
// before drawing the text.
static const int kVerticalMargin = 3;

RgLineEdit::RgLineEdit(QWidget* parent) : QLineEdit(parent)
{
}

void RgLineEdit::focusInEvent(QFocusEvent* event)
{
    emit LineEditFocusInEvent();

    // Pass the event onto the base class.
    QLineEdit::focusInEvent(event);

    // Select the text using single shot timer.
    QTimer::singleShot(0, this, &QLineEdit::selectAll);
}

void RgLineEdit::focusOutEvent(QFocusEvent* event)
{
    emit LineEditFocusOutEvent();

    // Pass the event onto the base class.
    QLineEdit::focusOutEvent(event);
}

void RgLineEdit::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event);

    // Let the base class draw everything, i.e. text, cursor, border, etc.
    QLineEdit::paintEvent(event);

    // Set up the painter.
    QPainter painter;
    painter.begin(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // Set the font size.
    QFont font = this->font();
    font.setPointSize(8);
    painter.setFont(font);

    // Highlight substring if it is requested.
    if (highlight_sub_string_)
    {
        // Go through all highlight locations.
        for (const auto& string_highlight_data : string_highlight_data_)
        {
            QString current = text().mid(0, string_highlight_data.m_startLocation);
            int initial_text_width = QtCommon::QtUtil::GetTextWidth(font, current);

            current = text().mid(string_highlight_data.m_startLocation,
                string_highlight_data.m_endLocation - string_highlight_data.m_startLocation);
            int width = QtCommon::QtUtil::GetTextWidth(font, current);
            QRect rect = this->rect();
            rect.setX(rect.x() + kPaintLocationX + initial_text_width);
            rect.setHeight(rect.height() - kHighlightVerticalMargin);
            rect.setY(rect.y() + kHighlightVerticalMargin);
            rect.setWidth(width);
            painter.fillRect(rect, string_highlight_data.m_highlightColor);
        }
    }

    painter.end();
}

void RgLineEdit::SetHighlightSubStringData(QVector<StringHighlightData> string_highlight_data)
{
    string_highlight_data_ = string_highlight_data;
}

void RgLineEdit::SetHighlightSubString(bool value)
{
    highlight_sub_string_ = value;
}


text:
namespace content {

class SessionMetricsPrerenderingBrowserTest : public ContentBrowserTest {
 public:
  SessionMetricsPrerenderingBrowserTest()
      : prerender_helper_(base::BindRepeating(
            &SessionMetricsPrerenderingBrowserTest::web_contents,
            base::Unretained(this))) {}
  ~SessionMetricsPrerenderingBrowserTest() override = default;

  content::test::PrerenderTestHelper* prerender_helper() {
    return &prerender_helper_;
  }

  void SetUp() override {
    prerender_helper_.SetUp(embedded_test_server());
    ContentBrowserTest::SetUp();
  }

  void SetUpOnMainThread() override {
    ASSERT_TRUE(embedded_test_server()->Start());
    ContentBrowserTest::SetUpOnMainThread();
  }

  WebContents* web_contents() { return shell()->web_contents(); }

 private:
  content::test::PrerenderTestHelper prerender_helper_;
};

// Tests that prerendering doesn't record immersive session.
IN_PROC_BROWSER_TEST_F(SessionMetricsPrerenderingBrowserTest,
                       DoNotRecordImmersiveSessionInPrerendering) {
  ukm::TestAutoSetUkmRecorder test_ukm_recorder;

  const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
  EXPECT_TRUE(NavigateToURL(shell(), initial_url));

  SessionMetricsHelper* metrics_helper =
      SessionMetricsHelper::CreateForWebContents(web_contents());
  auto session_options = device::mojom::XRSessionOptions::New();
  std::unordered_set<device::mojom::XRSessionFeature> enabled_features;
  metrics_helper->StartImmersiveSession(*(session_options), enabled_features);
  auto entries = test_ukm_recorder.GetEntriesByName(
      ukm::builders::XR_WebXR_Session::kEntryName);
  EXPECT_EQ(0u, entries.size());

  // Load a page in the prerender.
  auto prerender_url = embedded_test_server()->GetURL("/title1.html");
  int host_id = prerender_helper()->AddPrerender(prerender_url);
  content::test::PrerenderHostObserver host_observer(*web_contents(), host_id);
  EXPECT_FALSE(host_observer.was_activated());
  entries = test_ukm_recorder.GetEntriesByName(
      ukm::builders::XR_WebXR_Session::kEntryName);
  EXPECT_EQ(0u, entries.size());

  // Activate the page from the prerendering.
  prerender_helper()->NavigatePrimaryPage(prerender_url);
  EXPECT_TRUE(host_observer.was_activated());
  entries = test_ukm_recorder.GetEntriesByName(
      ukm::builders::XR_WebXR_Session::kEntryName);
  EXPECT_EQ(1u, entries.size());
}

class SessionMetricsFencedFrameBrowserTest : public ContentBrowserTest {
 public:
  SessionMetricsFencedFrameBrowserTest() = default;
  ~SessionMetricsFencedFrameBrowserTest() override = default;

  void SetUpOnMainThread() override {
    ASSERT_TRUE(embedded_test_server()->Start());
    ContentBrowserTest::SetUpOnMainThread();
  }

  WebContents* web_contents() { return shell()->web_contents(); }

  content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
    return fenced_frame_helper_;
  }

 private:
  content::test::FencedFrameTestHelper fenced_frame_helper_;
};

// Tests that a fenced frame doesn't record immersive session.
IN_PROC_BROWSER_TEST_F(SessionMetricsFencedFrameBrowserTest,
                       DoNotRecordImmersiveSessionInFencedFrame) {
  ukm::TestAutoSetUkmRecorder test_ukm_recorder;

  const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
  EXPECT_TRUE(NavigateToURL(shell(), initial_url));

  SessionMetricsHelper* metrics_helper =
      SessionMetricsHelper::CreateForWebContents(web_contents());
  auto session_options = device::mojom::XRSessionOptions::New();
  std::unordered_set<device::mojom::XRSessionFeature> enabled_features;
  metrics_helper->StartImmersiveSession(*(session_options), enabled_features);
  auto entries = test_ukm_recorder.GetEntriesByName(
      ukm::builders::XR_WebXR_Session::kEntryName);
  EXPECT_EQ(0u, entries.size());

  // Create a fenced frame and check the immersive session is not recorded.
  GURL fenced_frame_url(
      embedded_test_server()->GetURL("/fenced_frames/title1.html"));
  RenderFrameHost* fenced_frame_host =
      fenced_frame_test_helper().CreateFencedFrame(
          web_contents()->GetMainFrame(), fenced_frame_url);
  ASSERT_TRUE(fenced_frame_host);
  entries = test_ukm_recorder.GetEntriesByName(
      ukm::builders::XR_WebXR_Session::kEntryName);
  EXPECT_EQ(0u, entries.size());
}

}  // namespace content


text:
<!---
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Configuration Group
A Configuration group or Config group is type of resource that supports grouping of configuration resources and host resources for a service.
Host is identified using the registered hostname of the host and the configuration resource is identified by the type and tag.

Example list of all config groups defined for a cluster:

    GET /api/v1/clusters/c1/config_groups
    {
      "href" : "http://your.ambari.server/api/v1/clusters/c1/config_groups",
      "items" : [
        {
          "href" : "http://your.ambari.server/api/v1/clusters/c1/config_groups/2",
          "ConfigGroup" : {
            "cluster_name" : "c1",
            "id" : 2
          }
        }
      ]
    }

### Intuition
Hosts grouped together based on certain similar characteristics will essentially share the same configuration for a Service and its components deployed on those hosts; consequently, different configuration for a different service.

## Management
Get call to view details of a particular config group identified by an :id

    GET /api/v1/clusters/c1/config_groups/:id
    {
      "href" : "http://your.ambari.server/api/v1/clusters/c1/config_groups/:id",
      "ConfigGroup" : {
        "cluster_name" : "c1",
        "description" : "Next Gen Slaves Group",
        "desired_configs" : [
          {
            "tag" : "nextgen1",
            "type" : "core-site",
            "href" : "http://your.ambari.server/api/v1/clusters/c1/configurations?type=core-site&tag=nextgen1"
          }
        ],
        "group_name" : "Test Datanode group",
        "hosts" : [
          {
            "host_name" : "host1",
            "href" : "http://your.ambari.server/api/v1/clusters/c1/hosts/host1"
          }
        ],
        "id" : :id,
        "tag" : "HDFS"
      }
    }

    200 OK

To create a new config group, it is mandatory to provide a config group name, a tag and the cluster name to which it belongs.
The tag as seen in this example is a name of the service. Two config groups with the same tag cannot be associated with the same host.

    POST /api/v1/clusters/c1/config_groups
    [
       {
          "ConfigGroup": {
             "cluster_name": "c1",
             "group_name": "hdfs-nextgenslaves",
             "tag": "HDFS",
             "description": "HDFS configs for rack added on May 19, 2010",
             "hosts": [
                {
                   "host_name": "host1"
                }
             ],
             "desired_configs": [
                {
                   "type": "core-site",
                   "tag": "nextgen1",
                   "properties": {
                      "key": "value"
                   }
                }
             ]
          }
       }
    ]

    201 Created

Notice that the desired_configs specifies the property set for the configuration resource. In this particular case, a new configuration will be created with the type and tag specified and associated with the resulting Config group if the configuration does not exist.
If a configuration with given type and tag exists, the property set would be ignored since a configuration is immutable.

An update on a Config group expects the entire resource definition to be sent with the PUT request.

    PUT /api/v1/clusters/c1/config_groups/2
    [
       {
          "ConfigGroup": {
             "cluster_name": "c1",
             "group_name": "hdfs-nextgenslaves",
             "tag": "HDFS",
             "description": "HDFS configs for rack added on May 19, 2010",
             "hosts": [
                {
                   "host_name": "host1",
                   "host_name": "host2",
                   "host_name": "host3"
                }
             ],
             "desired_configs": [
                {
                   "type": "core-site",
                   "tag": "nextgen1"
                },
                {
                   "type": "hdfs-site",
                   "tag": "nextgen1"
                }
             ]
          }
       }
    ]

    202 Accepted

A Config group identified by the :id can be deleted.

    DELETE /api/v1/clusters/c1/config_groups/:id

    200 OK


text:
/**
 * For testing custom thread pool.
 */
package ru.matevosyan;


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

/**
 * The command channel between the client and service as speced on the
 * wiki.
 *
 * @author Mike Samuel <mikesamuel@gmail.com>
 */
@javax.annotation.ParametersAreNonnullByDefault
package org.prebake.channel;


text:
//
//  AGBoxCollectionViewController.m
//  AGViewModelDemo
//
//  Created by JohnnyB0Y on 2017/8/20.
//  Copyright © 2017年 JohnnyB0Y. All rights reserved.
//

#import "AGBoxCollectionViewController.h"
#import "AGBoxDetailViewController.h"
#import "AGBoxVMGenerator.h"

@interface AGBoxCollectionViewController ()
<AGVMDelegate, UICollectionViewDelegateFlowLayout>

/** box generator */
@property (nonatomic, strong) AGBoxVMGenerator *boxVMGenerator;

@end

@implementation AGBoxCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // UI
    self.collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];

    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"🐒" style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemClick:)];

    // 注册 cell
    [AGBoxACell ag_registerCellBy:self.collectionView];
    [AGBoxBCell ag_registerCellBy:self.collectionView];
    [AGBoxCCell ag_registerCellBy:self.collectionView];

    // 监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeViewModelNoti:) name:kChangeViewModelNoti object:nil];

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

}

- (UIViewController *)initWithViewModel:(AGViewModel *)vm
{
    UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc] init];
    self = [super initWithCollectionViewLayout:fl];
    if ( self ) {
        self.title = @"多类型Cell展示";
    }
    return self;
}

+ (instancetype)newWithContext:(AGViewModel *)vm
{
	return [[self alloc] initWithViewModel:vm];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.boxVMGenerator.boxVMManager.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.boxVMGenerator.boxVMManager[section].count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    AGViewModel *vm = self.boxVMGenerator.boxVMManager[indexPath.section][indexPath.row];

    Class<AGCollectionCellReusable> cellClass = vm[kAGVMViewClass];
    UICollectionViewCell<AGVMResponsive> *cell = [cellClass ag_dequeueCellBy:collectionView for:indexPath];

    [cell setViewModel:vm];
    vm.setBindingView(cell).setDelegate(self).setIndexPath(indexPath);

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.boxVMGenerator.boxVMManager[indexPath.section][indexPath.row] ag_sizeOfBindingView];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(34., 4., 34., 4.);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 4.;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 4.;
}

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 选中
    AGViewModel *vm = self.boxVMGenerator.boxVMManager[indexPath.section][indexPath.row];
    AGBoxDetailViewController *vc = [AGBoxDetailViewController newWithContext:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ---------- Event Methods ----------
- (void) rightBarButtonItemClick:(UIBarButtonItem *)item
{
    static BOOL selected = 0;
    selected = ! selected;

    AGVMManager *boxVMManager = self.boxVMGenerator.boxVMManager;

    [boxVMManager ag_enumerateSectionsItemUsingBlock:^(AGViewModel * _Nonnull vm, NSIndexPath * _Nonnull indexPath, BOOL * _Nonnull stop) {

        // 所有 Class A 选中猴子
        Class cellClass = vm[kAGVMViewClass];
        if ( cellClass == [AGBoxACell class] ) {
            //
            [vm ag_refreshUIByUpdateModelUsingBlock:^(AGViewModel *viewModel) {
                viewModel[kAGBoxACellSegmentedControlSelectedIndex] = @( selected );
            }];

            NSLog(@"indexPath : %ld - %ld", (long)indexPath.section, (long)indexPath.item);
        }

    }];
}

- (void) changeViewModelNoti:(NSNotification *)noti
{
    NSDictionary *dict = noti.userInfo;
    Class selectedCellClass = dict[kAGVMViewClass];
    UIColor *selectedCellColor = dict[kAGVMBoxColor];

    AGVMManager *boxVMManager = self.boxVMGenerator.boxVMManager;

    [boxVMManager ag_enumerateSectionsItemUsingBlock:^(AGViewModel * _Nonnull vm, NSIndexPath * _Nonnull indexPath, BOOL * _Nonnull stop) {

        // 改变对应类的颜色
        if ( vm[kAGVMViewClass] == selectedCellClass ) {
            // 选中类名的 cell
            [vm ag_refreshUIByUpdateModelUsingBlock:^(AGViewModel *viewModel) {
                viewModel[kAGVMBoxColor] = selectedCellColor;
            }];

        }

    }];
}

#pragma mark - ----------- Getter Methods ----------
- (AGBoxVMGenerator *)boxVMGenerator
{
    if (_boxVMGenerator == nil) {
        _boxVMGenerator = [AGBoxVMGenerator new];
    }
    return _boxVMGenerator;
}

@end


text:
def mode(array)
  hash = Hash.new(0)
  num_a = []
  final_a = Array.new

    array.each do |value|
      hash[value] += 1
    end

  num_a = hash.values.sort

  hash.each do |k,v|
    if v == num_a[-1]
      final_a << k
    end
  end

  return final_a
end

# 3. Refactored Solution

# 4. Reflection

=begin
    Which data structure did you and your pair decide to implement and why?

    We decided to implement a hash. With the array given it was easier to turn the array elements into keys and then iterate over that array to see how many times the object key was listed in the array.

    Were you more successful breaking this problem down into implementable pseudocode than the last with a pair?

    Yes. We broke every step down and worked on coding each step until our method produced the results we wanted.

    What issues/successes did you run into when translating your pseudocode to code?

    We ran into issues where we used the wrong methods so our results didnt come out as planned. When we figured that part out everything else was a success. The pseudocode helped alot.

    What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement?

    We used the .each method to iterate through the array and the hash we creaed. We werent able to find a good one while looking to refactor.

=end


text:
#include "UniformSampler.h"

#include <iostream>
using namespace std;

UniformSampler::UniformSampler(ImplicitFunction* _implicit, int _numScans, int _resX, int _resY)  {
	implicit_function = _implicit;

	num_scans = _numScans;
	res_x = _resX;
	res_y = _resY;

	my_pi = acos(-1.0);

	min_range = 20;
	max_range = 300;

	to_register = false;
	registration_error = 0;

	num_stripes = res_x;
	double default_thickness = 10, default_fov = 45;
	double fov_thickness = (default_fov / (double)num_stripes) * default_thickness;
	laser_fov = (fov_thickness/180.0)*acos(-1);

	additive_noise = 0.0;
	laser_smoother = 0.1;

	peak_threshold = 0.1;
	std_threshold = 1.5;

	normal_type = NORMALS_PCA_ORIENTED;
	pca_knn = 12;

	baseline = 50;
	//baseline = 25;
	to_random_sample_rotation = true;

	dump_range_images = false;
}

UniformSampler::~UniformSampler()  {
	clear_range_images();
}

void UniformSampler::clear_range_images() {
	for(vector<OrientedRangeImage*>::iterator it = range_images.begin();
		it!=range_images.end();
		++it)
			delete (*it);
	range_images.clear();
}

void UniformSampler::sample()  {
	if(range_images.size() > 0)
		clear_range_images();

	cout << "------ scanner parameters ------" << endl;
	cout << "   num scans : " << num_scans << endl;
	cout << "   image resolution : " << res_x << ", " << res_y << endl;

	cout << "   sensor range : " << min_range << ", " << max_range << endl;
	cout << "   num stripes : " << num_stripes <<  endl;
	cout << "   laser fov : " << ((laser_fov/my_pi)*180.0) <<  endl;
	cout << "   additive noise : " << additive_noise << " laser smoother : " << laser_smoother << endl;
	cout << "   peak threshold : " << peak_threshold << " std threshold : " << std_threshold << endl;

	cout << "   do register ? " << to_register << " : registration error: " << ((registration_error/my_pi)*180.0) << endl;

	cout << "   PCA knn: " << pca_knn << " normal type: " << normal_type << endl;

	cout << "   baseline : " << baseline << endl;
	cout << "   do random sample rotation ? " << to_random_sample_rotation << endl;

	Vector3 ll_bound, ur_bound;
	implicit_function->bounds(ll_bound, ur_bound);

	Vector3 diag_bound = ur_bound-ll_bound;
	Vector3 center = (ur_bound+ll_bound)*0.5;
	double sampling_radius = min_range + 0.5*diag_bound.length();

	time_t cur_time;
	time(&cur_time);
	srand(cur_time);
	for(int i = 0; i < 20; i++)
		rand();

	vector<Vector3> uniform_sampling;
	ostringstream num_samples;
	num_samples << num_scans;
	string particle_file = "./bin/particle_sampler/particles"+num_samples.str()+".npts";
	OrientedPointCloud sphere_pc;
	NPTSReader npts_reader(particle_file);

	if(!npts_reader.read_pc(&sphere_pc))  {
		cout << "couldn't open file " << particle_file << " ; instead, going to sample ..." << endl;
		ImplicitSphere* sampling_sphere = new ImplicitSphere(1);
		uniform_sampling = sampling_sphere->sample_surface(num_scans, 0, false);
	}
	else  {
		double rx = (double)rand() / (double)RAND_MAX;
		double ry = (double)rand() / (double)RAND_MAX;
		double rz = (double)rand() / (double)RAND_MAX;
		double random_angle = 2.0*acos(-1)*((double)rand() / (double)RAND_MAX);
		Vector3 random_axis(rx, ry, rz);
		random_axis.normalize();
		RotationMatrix sphere_rotation(random_axis, random_angle);

		for(int i = 0; i < sphere_pc.size(); i++)  {
			Vector3 sphere_pt = sphere_pc.getPoint(i);
			if(to_random_sample_rotation)  {
				Vector3 rotated_pt = sphere_rotation.rotate(sphere_pt);
				uniform_sampling.push_back(rotated_pt);
			}
			else
				uniform_sampling.push_back(sphere_pt);
		}
	}
	if(uniform_sampling.size() != num_scans)
		cout << "ERROR: uniform sampling not at prescribed size!" << endl;

	double lipschitz = implicit_function->lipschitz_constant(100);
	int num_stripes_processed = 0;

	for(int s = 0; s < num_scans; s++)  {
		ComputationTimer timer("uniform sampler");
		timer.start();

		double rand_x = (double)rand() / (double)RAND_MAX;
		double rand_y = (double)rand() / (double)RAND_MAX;
		double rand_z = (double)rand() / (double)RAND_MAX;
		Vector3 rand_axis(rand_x, rand_y, rand_z);
		rand_axis.normalize();
		RotationMatrix random_rotation(rand_axis, registration_error);

		Vector3 sphere_sample = uniform_sampling[s];
		Vector3 look_from = center + sphere_sample*sampling_radius;
		Vector3 look_at = center;
		Vector3 view_dir = look_at-look_from;
		view_dir.normalize();

		Vector3 up;
		if(view_dir.x == 0 && view_dir.y == 1 && view_dir.z == 0)
			up = Vector3(0,0,1);
		else  {
			Vector3 fake_up(0,-1,0);
			Vector3 crossed = view_dir.cross(fake_up);
			crossed.normalize();
			up = crossed.cross(view_dir);
			up.normalize();
		}

		cout << "scan " << s << " / " << num_scans << endl;
		RayCaster ray_caster(look_from, view_dir, up, res_x, res_y, 50, my_pi/4.0);
		Vector3 laser_pos = look_from + ray_caster.getUBasis()*baseline;

		RangeScanner range_scanner(implicit_function, ray_caster, laser_pos, lipschitz);
		range_scanner.set_range(min_range, max_range);
		range_scanner.set_num_stripes(num_stripes);
		range_scanner.set_laser_fov(laser_fov);

		range_scanner.set_noise(additive_noise);
		range_scanner.set_laser_smoother(laser_smoother);
		range_scanner.set_peak_threshold(peak_threshold);
		range_scanner.set_std_threshold(std_threshold);

		range_scanner.set_base_stripe(stripe_base, num_stripes_processed);
		SparseRangeScan* sparse_scan = range_scanner.optical_triangulation();
		num_stripes_processed += range_scanner.num_stripes_processed();

		Vector3 center_of_mass(0,0,0);
		for(int i = 0; i < sparse_scan->size(); i++)
			center_of_mass = center_of_mass + sparse_scan->getPt(i);
		center_of_mass.scale((1.0 / (double)sparse_scan->size()));

		OrientedRangeImage* range_image = new OrientedRangeImage(res_x, res_y);
		for(int p = 0; p < sparse_scan->size(); p++)  {
			PixelCoord pix = sparse_scan->getPixel(p);
			Vector3 pt = sparse_scan->getPt(p);
			Vector3 normal = implicit_function->normal(pt);

			// misregistration: take center of mass of scan, and perturb scan around this
			if(to_register)  {
				pt = center_of_mass + random_rotation.rotate(pt-center_of_mass);
				normal = random_rotation.rotate(normal);
			}

			range_image->setRangePoint(pix.x, pix.y, pt, normal);
		}
		char depth_filename[256];
		sprintf(depth_filename, "%s_depth%u.png", stripe_base.c_str(), s);
		range_scanner.depth_image(sparse_scan, depth_filename);
		delete sparse_scan;

		range_images.push_back(range_image);
		timer.end();
		cout << timer.getComputation() << " : " << timer.getElapsedTime() << "s" << endl;
	}

	this->dump_to_movie();
}

void UniformSampler::dump_to_movie()  {
	string exec_movie = "./bin/scan_movie.sh " + stripe_base;
	int sampler_result = system(exec_movie.c_str());
}

void UniformSampler::dump_to_file(string _filename)  {
	FILE* pts_file = fopen(_filename.c_str(), "w");

	// point cloud used only if the normal type deems it
	PointCloud pc;
	vector<Vector3> analytical_normals;

	if(to_register)  {
		vector<string> transform_names;
		double ave_image_size = 0;
		for(unsigned i = 0; i < range_images.size(); i++)  {
			OrientedRangeImage* range_image = range_images[i];
			stringstream int_out;
			int_out << i;
			ave_image_size += range_image->size();
			string range_name = "bin/range_image" + int_out.str() + ".ply";
			transform_names.push_back("./bin/global/rigid/range_image" + int_out.str() + ".xf");
			range_image->dump_to_ply(range_name);
		}
		ave_image_size /= (double)range_images.size();

		int target_samples = 200;
		double sample_perc = (double)target_samples / ave_image_size;
		char* perc_string = new char[30];
		sprintf(perc_string, "%.7f", sample_perc);

		// run registration
		string perc_perc_string = perc_string;
		string exec_registration = "./bin/rigid_align.sh " + perc_perc_string;
		cout << exec_registration << endl;
		system(exec_registration.c_str());

		int num_pts = 0;

		for(unsigned i = 0; i < range_images.size(); i++)  {
			OrientedRangeImage* range_image = range_images[i];

			// get rigid transformation
			DenseMatrix rotation(3);
			Vector3 translation;
			if(!this->getRigidTransformation(transform_names[i], rotation, translation))
				cerr << "bad transformation! " << transform_names[i] << endl;
			rotation.printMatrix();
			cout << translation << endl;

			for(int y = 0; y < range_image->yRes(); y++)  {
				for(int x = 0; x < range_image->xRes(); x++)  {
					if(!range_image->isValidPoint(x,y))
						continue;

					num_pts++;
					Vector3 local_pt = range_image->getRangePoint(x,y);
					Vector3 local_normal = range_image->getRangeNormal(x,y);
					Vector3 range_pt = rotation.mult(local_pt) + translation;
					Vector3 range_normal = rotation.mult(local_normal);

					if(normal_type == NORMALS_ANALYTICAL)  {
						fprintf(pts_file, "%.7f %.7f %.7f %.7f %.7f %.7f\n", range_pt.x, range_pt.y, range_pt.z,
								range_normal.x, range_normal.y, range_normal.z);
					}
					else  {
						pc.addPoint(range_pt);
						analytical_normals.push_back(range_normal);
					}
				}
			}
		}

		// clean up
		system("rm -r bin/global");
		system("rm bin/*.ply");
		cout << "num pts: " << num_pts << endl;
	}

	else  {
		int num_pts = 0;
		for(unsigned i = 0; i < range_images.size(); i++)  {
			OrientedRangeImage* range_image = range_images[i];
			for(int y = 0; y < range_image->yRes(); y++)  {
				for(int x = 0; x < range_image->xRes(); x++)  {
					if(!range_image->isValidPoint(x,y))
						continue;

					num_pts++;
					Vector3 range_pt = range_image->getRangePoint(x,y);
					Vector3 range_normal = range_image->getRangeNormal(x,y);

					if(normal_type == NORMALS_ANALYTICAL)  {
						fprintf(pts_file, "%.7f %.7f %.7f %.7f %.7f %.7f\n", range_pt.x, range_pt.y, range_pt.z,
								range_normal.x, range_normal.y, range_normal.z);
					}
					else  {
						pc.addPoint(range_pt);
						analytical_normals.push_back(range_normal);
					}
				}
			}
		}

		cout << "num pts: " << num_pts << endl;
	}

	if(normal_type != NORMALS_ANALYTICAL)  {
		OrientedPointCloud* oriented_pc = pc.orient_points(pca_knn);
		for(int p = 0; p < oriented_pc->size(); p++)  {
			Vector3 range_pt = oriented_pc->getPoint(p);
			Vector3 range_normal = oriented_pc->getNormal(p);
			if(normal_type == NORMALS_PCA_ORIENTED)  {
				Vector3 analytical_normal = analytical_normals[p];
				double dot = analytical_normal.dotProduct(range_normal);
				if(dot < 0)
					range_normal.scale(-1);
			}
			fprintf(pts_file, "%.7f %.7f %.7f %.7f %.7f %.7f\n", range_pt.x, range_pt.y, range_pt.z,
					range_normal.x, range_normal.y, range_normal.z);
		}
	}

	fclose(pts_file);
}

bool UniformSampler::getRigidTransformation(string _filename, DenseMatrix& rotation, Vector3& translation)  {
	char line_raw[256];
	ifstream file(_filename.c_str());
	if (file.fail())
		return false;

	for (int row = 0; row < 3; row++)  {
		file.getline(line_raw, 256);
		if (file.eof())
			break;

		string line(line_raw);
		vector<string> tokens;
		tokenize_line(&tokens, line, " \t");

		rotation.setEntry(0, row, atof(tokens[0].c_str()));
		rotation.setEntry(1, row, atof(tokens[1].c_str()));
		rotation.setEntry(2, row, atof(tokens[2].c_str()));

		if(row == 0)
			translation.x = atof(tokens[3].c_str());
		else if(row == 1)
			translation.y = atof(tokens[3].c_str());
		else
			translation.z = atof(tokens[3].c_str());
	}

	file.close();

	return true;
}

/**
 * STOLEN FROM JOSIAH MANSON. SHEEEEIT
 */
void UniformSampler::tokenize_line(vector<string>* tokens, const string& input, string sep)  {
	string comm;
	for (unsigned int i = 0; i < input.size(); i++)  {
		const char ch = input[i];
		bool added = false;
		for (unsigned int s = 0; s < sep.size(); s++)  {
			if (ch == sep[s])  {
				tokens->push_back(comm);
				comm = "";
				added = true;
				break;
			}
		}
		if (!added)
			comm += ch;
	}
	if (comm != "")
		tokens->push_back(comm);
}


text:
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// ------------------------------------------------------------------------------

package com.microsoft.onedrivesdk.picker;

import android.app.Activity;
import android.content.*;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;

/**
 * Picker provides hooks into the OneDrive application for users to find files
 * on OneDrive and hand back references to the current application.
 *
 * @see IPicker for detailed usage information
 * @author pnied
 */
public final class Picker implements IPicker {

    /**
     * The intent that triggers the OneDrive picking experience
     */
    private static final String ONEDRIVE_PICKER_ACTION = "onedrive.intent.action.PICKER";

    /**
     * The specific picker handler in the OneDrive application
     */
    private static final String ONEDRIVE_PICKER_HANDLER = "com.microsoft.skydrive.getcontent.RecieveSdkPickerActivity";

    /**
     * The default picker file request code leveraged by onActivtyResult(...)
     * signature
     */
    private static final int PICK_FILE_REQUEST_CODE = 0xF0F0;

    /**
     * The OneDrive application package name
     */
    private static final String ONEDRIVE_PACKAGE_NAME = "com.microsoft.skydrive";

    /**
     * The application ID registered with OneDrive that created this picker
     * {@link https://account.live.com/developers/applications/index}
     */
    private String mAppId;

    /**
     * The request code leveraged by onActivityResult(int, int, Intent)
     * signature
     */
    private int mRequestCode;

    /**
     * Default Constructor
     *
     * @param appId The application ID registered with OneDrive that created
     *            this picker.
     */
    private Picker(final String appId) {
        this.mAppId = appId;
        this.mRequestCode = PICK_FILE_REQUEST_CODE;
    }

    /**
     * Creates an instance of the OneDrive picker
     *
     * @param appId The application ID registered with OneDrive that created
     *            this picker.
     * @return The new picker instance ready to use
     */
    public static IPicker createPicker(final String appId) {
        if (TextUtils.isEmpty(appId)) {
            throw new IllegalArgumentException("appId");
        }
        return new Picker(appId);
    }

    /**
     * Helper for onActivityResult(int, int, Intent). Validates the request and
     * result codes and returns a type-safe {@link IPickerResult}.
     *
     * @param requestCode The request code from the onActivityResult call
     * @param resultCode The result code from the onActivityResult call
     * @param data The data from the onActivityResult call
     * @return If the picking process was successful, returns an instance of the
     *         {@link IPickerResult}; if it was unsuccessful because of a user
     *         cancellation or error, returns null.
     */
    public IPickerResult getPickerResult(final int requestCode, final int resultCode, final Intent data) {
        if (mRequestCode == requestCode && Activity.RESULT_OK == resultCode) {
            return PickerResult.fromBundle(data.getExtras());
        }
        return null;
    }

    /**
     * Starts a new activity that allows users to pick a file from OneDrive,
     * create links for viewing or downloading, and then to be returned to the
     * starting application. Note, to get the picking results, you must
     * implement onActivityResult(int, int, Intent) to get the picking results.
     * If the OneDrive application is not available, starts a marketplace so
     * that users can install the OneDrive application
     *
     * @param activity The activity that will start the picker experience
     * @param linkType The type of link that should be returned to this activity
     *            from the picking flow
     */
    public void startPicking(final Activity activity, final LinkType linkType) {
        final Intent pickerIntent = createOneDriveIntent();
        final Intent androidMarketPlaceIntent = createAndroidMarketPlaceIntent();
        final Intent amazonMarketPlaceIntent = createAmazonMarketPlaceIntent();
        if (isAvailable(activity, pickerIntent)) {
            pickerIntent.putExtra("linkType", linkType.toString());
            activity.startActivityForResult(pickerIntent, mRequestCode);
        } else if (isAvailable(activity, androidMarketPlaceIntent)) {
            activity.startActivity(androidMarketPlaceIntent);
        } else if (isAvailable(activity, amazonMarketPlaceIntent)) {
            activity.startActivity(amazonMarketPlaceIntent);
        } else {
            Toast.makeText(activity, "Unable to start the OneDrive picker or device market place", Toast.LENGTH_LONG)
                    .show();
        }
    }

    /**
     * Allows the request code used by this instance to be configured by the
     * source application
     *
     * @param requestCode The request code to be used by the
     *            startActivityForResult(Intent, int) call.
     */
    public void setRequestCode(final int requestCode) {
        mRequestCode = requestCode;
    }

    /**
     * Gets the request code to be used by the startActivityForResult(Intent,
     * int) method during the startPicking(Activity, LinkType) call.
     *
     * @return The request code
     */
    public int getRequestCode() {
        return mRequestCode;
    }

    /**
     * Determines if the given intent can be resolved to an activity.
     *
     * @param activity The activity that would start the picker experience
     * @param intent The intent to check
     * @return true if the OneDrive application can start and execute the
     *         file picking flow. Return false if the OneDrive
     *         application does not support this call, or if the application is
     *         not installed.
     */
    private boolean isAvailable(final Activity activity, final Intent intent) {
        final PackageManager pm = activity.getPackageManager();
        return pm.queryIntentActivities(intent, 0).size() != 0;
    }

    /**
     * Creates the intent to launch the OneDrive picker
     *
     * @return The intent instance
     */
    private Intent createOneDriveIntent() {
        final Intent intent = new Intent();
        intent.setAction(ONEDRIVE_PICKER_ACTION);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setComponent(new ComponentName(ONEDRIVE_PACKAGE_NAME, ONEDRIVE_PICKER_HANDLER));
        intent.putExtra("appId", mAppId);
        return intent;
    }

    /**
     * Creates the intent to launch the android marketplace for the OneDrive
     * application
     *
     * @return the intent instance
     */
    private Intent createAndroidMarketPlaceIntent() {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(String.format("market://details?id=%s", ONEDRIVE_PACKAGE_NAME)));
        return intent;
    }

    /**
     * Creates the intent to launch the amazon marketplace for the OneDrive
     * application
     *
     * @return the intent instance
     */
    private Intent createAmazonMarketPlaceIntent() {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(String.format("amzn://apps/android?p=%s", ONEDRIVE_PACKAGE_NAME)));
        return intent;
    }
}


text:
package com.markatta.stackdetective.parse;

import com.markatta.stackdetective.model.StackTrace;
import java.util.List;

/**
 * Not ready for prime time yet
 * @author johan
 */
class DefaultTextParser implements StackTraceTextParser {

    @Override
    public StackTrace parse(CharSequence stacktrace) {
        Lexer lexer = new Lexer();
        List<Token> tokens = lexer.tokenize(stacktrace.toString());
        Parser parser = new Parser();
        return parser.parse(tokens);
    }
}


text:
namespace Xilium.CefGlue
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using Xilium.CefGlue.Interop;

    // Role: PROXY
    public sealed unsafe partial class CefBrowser : IDisposable
    {
        internal static CefBrowser FromNative(cef_browser_t* ptr)
        {
            return new CefBrowser(ptr);
        }

        internal static CefBrowser FromNativeOrNull(cef_browser_t* ptr)
        {
            if (ptr == null) return null;
            return new CefBrowser(ptr);
        }

        private cef_browser_t* _self;

        private CefBrowser(cef_browser_t* ptr)
        {
            if (ptr == null) throw new ArgumentNullException("ptr");
            _self = ptr;
        }

        ~CefBrowser()
        {
            if (_self != null)
            {
                Release();
                _self = null;
            }
        }

        public void Dispose()
        {
            if (_self != null)
            {
                Release();
                _self = null;
            }
            GC.SuppressFinalize(this);
        }

        internal void AddRef()
        {
            cef_browser_t.add_ref(_self);
        }

        internal bool Release()
        {
            return cef_browser_t.release(_self) != 0;
        }

        internal bool HasOneRef
        {
            get { return cef_browser_t.has_one_ref(_self) != 0; }
        }

        internal cef_browser_t* ToNative()
        {
            AddRef();
            return _self;
        }
    }
}


text:
<?php

namespace OroCRM\Bundle\MagentoBundle\Tests\Unit\Provider\Iterator;

use OroCRM\Bundle\MagentoBundle\Provider\Iterator\AbstractBridgeIterator;

class BaseIteratorTestCase extends \PHPUnit_Framework_TestCase
{
    /** @var AbstractBridgeIterator */
    protected $iterator;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $transport;

    /** @var array */
    protected $settings;

    protected function setUp()
    {
        $this->transport = $this->getMockBuilder('OroCRM\\Bundle\\MagentoBundle\\Provider\\Transport\\SoapTransport')
            ->disableOriginalConstructor()
            ->getMock();

        $this->settings  = ['start_sync_date' => new \DateTime('NOW'), 'website_id' => 0];
    }

    public function tearDown()
    {
        unset($this->iterator, $this->transport);
    }
}


text:
@interface UIImage (SVG)

@end


text:
<localize key="merchelloReports_abandonedBaskets" />

        Configuration: {{result.configuredDays}}

        {{ result.startDate | date : settings.dateFormat }} - {{ result.endDate | date : settings.dateFormat }}

            <canvas id="polar-area" class="chart chart-polar-area"
                    chart-data="data" chart-labels="labels">
            </canvas>

                {{anonymousBaskets}}
                {{anonymousCheckouts}}
                {{anonymousPercentLabel}}
                {{customerBaskets}}
                {{customerCheckouts}}
                {{customerPercentLabel}}

                {{result.anonymousBasketCount}}
                {{result.anonymousCheckoutCount}}
                {{anonymousCheckoutPercent}}%
                {{result.customerBasketCount}}
                {{result.customerCheckoutCount}}
                {{customerCheckoutPercent}}%


text:
import processTestFnError from './process-test-fn-error';
import { UncaughtErrorInTestCode } from './test-run';

export default class TestCafeErrorList {
    constructor () {
        this.items   = [];
        this.name    = TestCafeErrorList.name;
        this.adapter = null;
    }

    get hasErrors () {
        return !!this.items.length;
    }

    get hasUncaughtErrorsInTestCode () {
        return this.items.some(item => item instanceof UncaughtErrorInTestCode);
    }

    addError (err) {
        if (err instanceof TestCafeErrorList)
            this.items = this.items.concat(err.items);
        else
            this.items.push(processTestFnError(err));
    }
}


text:
using System;
using Xbehave.Test.Infrastructure;
using Xunit;
using Xunit.Abstractions;

namespace Xbehave.Test
{
    public class ClassFixtureFeature : Feature
    {
        [Background]
        public void Background() =>
            "Given no events have occurred"
                .x(() => typeof(ClassFixtureFeature).ClearTestEvents());

        [Scenario]
        public void ClassFixture(Type feature, ITestResultMessage[] results)
        {
            "Given a scenario with a class fixture"
                .x(() => feature = typeof(ScenarioWithAClassFixture));

            "When I run the scenario"
                .x(() => results = this.Run<ITestResultMessage>(feature));

            "Then the class fixture is supplied as a constructor to each test class instance and disposed"
                .x(() =>
                {
                    Assert.All(results, result => Assert.IsAssignableFrom<ITestPassed>(result));
                    Assert.All(typeof(ClassFixtureFeature).GetTestEvents(), @event => Assert.Equal("disposed", @event));
                });
        }

        private class ScenarioWithAClassFixture : IClassFixture<Fixture>
        {
            private readonly Fixture fixture;

            public ScenarioWithAClassFixture(Fixture fixture)
            {
                Assert.NotNull(fixture);
                this.fixture = fixture;
            }

            [Scenario]
            public void Scenario1() =>
                "Given"
                    .x(() => this.fixture.Scenario1Executed = true);

            [Scenario]
            public void Scenario2() =>
                "Given"
                    .x(() => this.fixture.Scenario2Executed = true);
        }

        private sealed class Fixture : IDisposable
        {
            public bool Scenario1Executed { private get; set; }

            public bool Scenario2Executed { private get; set; }

            public void Dispose()
            {
                Assert.True(this.Scenario1Executed);
                Assert.True(this.Scenario2Executed);
                typeof(ClassFixtureFeature).SaveTestEvent("disposed");
            }
        }
    }
}


text:
#include "engine/model.hpp"
#include "engine/shader.hpp"

using namespace std;
using namespace glm;

/*  Functions   */
// Constructor, expects filepath and floats of matrices translate and scale
Model::Model(std::string const& path, std::vector<float>& xyz){
    GLuint i;
    for(i = 0; i < xyz.size(); i+=9){
        glm::mat4 ViewTranslate = translate(glm::mat4(1.0f), vec3(xyz[i], xyz[i+1], xyz[i+2]));
        //  modelmat = rotate(modelmat, xyz[i+9], vec3((int)xyz[i+6], (int)xyz[i+7], (int)xyz[i+8]));
        glm::mat4 ViewRotateX = glm::rotate(ViewTranslate, xyz[i+6], glm::vec3(1.f, 0.0f, 0.0f));
        glm::mat4 ViewRotateY = glm::rotate(ViewRotateX, xyz[i+7], glm::vec3(0.0f, 1.f, 0.0f));
        glm::mat4 View = glm::rotate(ViewRotateY, xyz[i+8], glm::vec3(0.0f, 0.0f, 1.f));
        glm::mat4 scaled = scale(glm::mat4(1.0f), vec3(xyz[i+3], xyz[i+4], xyz[i+5]));
        glm::mat4 modelmat = View * scaled;

        m_modelmatVector.push_back(modelmat);
    }
    this->loadModel(path);
}

// Draws the model, and thus all its meshes
void Model::Draw(Shader const& shader){
    for(unsigned int j = 0; j < m_modelmatVector.size() ; ++j) {
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE,glm::value_ptr(glm::mat4()));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(m_modelmatVector[j]));
        for(GLuint i = 0; i < this->meshes.size(); i++){
            this->meshes[i].Draw(shader);
        }
    }
}

//Create the models with the path, translate and scale matrix
void drawModels(map<int, unique_ptr<Model> > const& models, Shader const& shader){
        //Load a list of ModelMatrix from a text file
        GLuint i;
        for(i = 0; i < models.size(); i++){
            models.at(i)->Draw(shader);
        }
}

glm::mat4 Model::getModelMatrix(int numModelMat){
    return m_modelmatVector[numModelMat];
}

//Creates a map of models pointers from file
map<int, unique_ptr<Model> > modelsFromFile(string const& filepath){
    ifstream myFile; //creation du ifstream qui contiendra les données du fichier
    myFile.open(filepath); //ouverture du fichier où sont contenus toutes les infos des modeles (une ligne, un model)
    std::map<int, std::unique_ptr<Model> > models;
        string path, line; //path est une variable temporaire
        string stx, sty, stz, ssx, ssy, ssz, srx, sry, srz;

         if (!myFile.is_open()){
             std::cerr << "Erreur lors de l'ouverture du fichier: " << strerror(errno) << std::endl;
         }
         int i = 0;
         bool first_model_already_exists = false;
         std::vector<float> xyz;

        while(getline(myFile, line)){ //tant qu'il existe une ligne après celle-ci{
            istringstream lineStream(line); //on prend les données de la ligne suivante

            lineStream >> stx; //The first "word" of the line goes into stx
            if(stx != "#"){
                if(stx == "Model" || stx == "Fin"){
                    if(first_model_already_exists == true){

                        //std::cout << "i = " << i << std::endl;
                        models[i].reset(new Model(path, xyz));
                        xyz.clear(); //xyz has to be clean again for the new model
                        ++i;
                    }
                    if(stx == "Model"){
                        lineStream >> path;
                    } //Beginning of a new model
                }
                else{
                    lineStream >> sty >> stz >> ssx >> ssy >> ssz >> srx >> sry >> srz;
                    //on rentre les données de la ligne dans les différentes variables temporaires
                    //std::cout << "i : " << path << stx << sty << stz << ssx << ssy << ssz << std::endl;
                    std::vector<float> abc;
                    abc.push_back(stof(stx));
                    abc.push_back(stof(sty));
                    abc.push_back(stof(stz));
                    abc.push_back(stof(ssx));
                    abc.push_back(stof(ssy));
                    abc.push_back(stof(ssz));
                    abc.push_back(stof(srx));
                    abc.push_back(stof(sry));
                    abc.push_back(stof(srz));

                    xyz.insert(xyz.end(), abc.begin(), abc.end() );
                }
                first_model_already_exists = true; //permits to create a model with the xyz created when meeting the next path
            }
        }
    myFile.close();
    //std::cout << "file closed" << std::endl;
    return models;
}

/*  Functions   */

// Loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
void Model::loadModel(string path)
{
    // Read file via ASSIMP
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile( path, aiProcess_Triangulate | aiProcess_FlipUVs);
      // Check for errors
    ifstream myFile; //creation du ifstream qui contiendra les données du fichier
    myFile.open(path);
    if(!myFile.is_open()){
        std::cerr << "Erreur: Fichier modèle non trouvé" << std::endl;
    }
    //std::cout << "Ouverture réussie pour " << path << std::endl;

    if(!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
    {
        std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl;
        return;
    }
    // Retrieve the directory path of the filepath
    this->directory = path.substr(0, path.find_last_of('/'));

    // Process ASSIMP's root node recursively
    this->processNode(scene->mRootNode, scene);
}

// Processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any).
void Model::processNode(aiNode* node, const aiScene* scene)
{
    // Process each mesh located at the current node
    for(GLuint i = 0; i < node->mNumMeshes; i++)
    {
        // The node object only contains indices to index the actual objects in the scene.
        // The scene contains all the data, node is just to keep stuff organized (like relations between nodes).
        aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
        this->meshes.push_back(this->processMesh(mesh, scene));
    }
    // After we've processed all of the meshes (if any) we then recursively process each of the children nodes
    for(GLuint i = 0; i < node->mNumChildren; i++)
    {
        this->processNode(node->mChildren[i], scene);
    }

}

Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene)
{
    // Data to fill
    vector<Vertex> vertices;
    vector<GLuint> indices;
    vector<Texture> textures;

    // Walk through each of the mesh's vertices
    for(GLuint i = 0; i < mesh->mNumVertices; i++)
    {
        Vertex vertex;
        glm::vec3 vector; // We declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first.
        // Positions
        vector.x = mesh->mVertices[i].x;
        vector.y = mesh->mVertices[i].y;
        vector.z = mesh->mVertices[i].z;
        vertex.Position = vector;
        // Normals
        vector.x = mesh->mNormals[i].x;
        vector.y = mesh->mNormals[i].y;
        vector.z = mesh->mNormals[i].z;
        vertex.Normal = vector;

        // Texture Coordinates
        if(mesh->mTextureCoords[0]) // Does the mesh contain texture coordinates?
        {
            glm::vec2 vec;
            // A vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't
            // use models where a vertex can have multiple texture coordinates so we always take the first set (0).
            vec.x = mesh->mTextureCoords[0][i].x;
            vec.y = mesh->mTextureCoords[0][i].y;
            vertex.TexCoords = vec;
        }
        else
            vertex.TexCoords = glm::vec2(0.0f, 0.0f);
        vertices.push_back(vertex);
    }
    // Now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices.
    for(GLuint i = 0; i < mesh->mNumFaces; i++)
    {
        aiFace face = mesh->mFaces[i];
        // Retrieve all indices of the face and store them in the indices vector
        for(GLuint j = 0; j < face.mNumIndices; j++)
            indices.push_back(face.mIndices[j]);
    }

    // Process materials
    aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
    // We assume a convention for sampler names in the shaders. Each diffuse texture should be named
    // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
    // Same applies to other texture as the following list summarizes:
    // Diffuse: texture_diffuseN
    // Specular: texture_specularN
    // Normal: texture_normalN

    // 1. Diffuse maps
    vector<Texture> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
    textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
    // 2. Specular maps
    vector<Texture> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
    textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());

    // Return a mesh object created from the extracted mesh data
    return Mesh(vertices, indices, textures);
}

// Checks all material textures of a given type and loads the textures if they're not loaded yet.
// The required info is returned as a Texture struct.
vector<Texture> Model::loadMaterialTextures(aiMaterial* mat, aiTextureType type, string typeName)
{
    vector<Texture> textures;
    for(GLuint i = 0; i < mat->GetTextureCount(type); i++)
    {
        aiString str;
        mat->GetTexture(type, i, &str);
        // Check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
        GLboolean skip = false;
        for(GLuint j = 0; j < textures_loaded.size(); j++)
        {
            if(textures_loaded[j].path == str)
            {
                textures.push_back(textures_loaded[j]);
                skip = true; // A texture with the same filepath has already been loaded, continue to next one. (optimization)
                break;
            }
        }
        if(!skip)
        {   // If texture hasn't been loaded already, load it
            Texture texture;
            texture.id = TextureFromFile(str.C_Str(), this->directory);
            texture.type = typeName;
            texture.path = str;
            textures.push_back(texture);
            this->textures_loaded.push_back(texture);  // Store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures.
        }
    }
    return textures;
}

GLint Model::TextureFromFile(const string path, string directory)
{
    //Generate texture ID and load texture data
    // TODO use filepath class
    string filename = string(path);
    filename = directory + '/' + filename;
    GLuint textureID;

    glGenTextures(1, &textureID);
    unique_ptr<glimac::Image> image = glimac::loadImage(filename.c_str());
    // Assign texture to ID
    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->getWidth(), image->getHeight(), 0, GL_RGBA, GL_FLOAT, image->getPixels());
    glGenerateMipmap(GL_TEXTURE_2D);

    // Parameters
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glBindTexture(GL_TEXTURE_2D, 0);

    return textureID;
}


text:
<?php defined( 'SYSPATH' ) OR die( 'No direct access allowed.' ); ?>

<?php echo $row->name; ?> - <a href="<?php echo url::base( TRUE ); ?>mapping/panel/<?php echo $row->id; ?>" ><?php echo Kohana::lang( 'region.edit_map' ); ?>

						<?php echo Kohana::lang( 'region.name' ); ?> :
						<input name="name" id="name" value="<?php echo $row->name; ?>" class="inputbox input-text" type="text" maxlength="50" />

						<?php echo Kohana::lang( 'region.desc' ); ?> : <?php echo Kohana::lang( 'form.minus' ); ?>
						<textarea name="comment" id="comment" class="inputbox input-textarea" style="height:100px;"><?php echo $row->comment; ?></textarea>

						<?php echo Kohana::lang( 'region.parent_map' ); ?> :
						<select name="id_parent" id="id_parent" class="inputbox" >
								<option value="" ><?php echo Kohana::lang( 'region.prim_map' ); ?></option>
								<?php if( $listing ) : ?>
										<?php foreach( $listing as $val ) : ?>
												<option value="<?php echo $val->id; ?>" <?php
								if( $val->id == $row->id_parent )
										echo 'selected="selected"';
												?> <?php
								if( $val->id == $row->id )
										echo 'disabled="disabled""';
												?> style="padding-left:<?php echo $val->level * 12; ?>px;"><?php echo $val->name; ?></option>
														<?php endforeach ?>
												<?php endif ?>
						</select>

						<?php echo Kohana::lang( 'region.nbr_case' ); ?> X :
						<input name="x" id="x" value="<?php echo $row->x; ?>" class="inputbox input-text" type="text" maxlength="50" />

						<?php echo Kohana::lang( 'region.nbr_case' ); ?> Y :
						<input name="y" id="y" value="<?php echo $row->y; ?>" class="inputbox input-text" type="text" maxlength="50" />

                <?php echo Kohana::lang( 'region.nbr_case' ); ?> Z :
                <input name="z" id="z" value="<?php echo $row->z; ?>" class="inputbox input-text" type="text" maxlength="50" />

                <?php echo Kohana::lang( 'region.degradation' ); ?> :
                <select name="degradation" id="degradation" class="inputbox" >
                    <?php for( $n = 0; $n <= 5; $n++ ) : ?>
                        <option value="<?php echo $n; ?>" <?php echo ( $n == $row->degradation ) ? 'selected="selected"' : ''; ?>><?php echo sprintf( '%02d', $n ); ?></option>
                    <?php endfor ?>
                </select>

                <?php echo Kohana::lang( 'region.frequence' ); ?> :
                <select name="frequence" id="frequence" class="inputbox" >
                    <?php for( $n = 0; $n <=100; $n++ ) : ?>
                        <option value="<?php echo $n; ?>" <?php echo ( $n == $row->frequence ) ? 'selected="selected"' : ''; ?>><?php echo sprintf( '%02d', $n ); ?></option>
                    <?php endfor ?>
                </select>

                <?php echo Kohana::lang( 'region.color' ); ?> :
                <input name="background_color" id="background_color" value="<?php echo str_replace('0x', '#',$row->background_color); ?>" class="inputbox input-text" type="color" maxlength="50" />

                <?php echo Kohana::lang( 'region.ambiance' ); ?> :
                <input name="ambiance" id="ambiance" value="<?php echo str_replace('0x', '#',$row->ambiance); ?>" class="inputbox input-text" type="color" maxlength="50" />

                <?php echo Kohana::lang( 'region.sun' ); ?> :
                <select class="inputbox" name="sun" id="sun">
                    <option value="1" class="vert"><?php echo Kohana::lang( 'form.yes' ); ?></option>
                    <option value="0" class="rouge" <?php if( !$row->sun ) echo 'selected="selected"'; ?>><?php echo Kohana::lang( 'form.no' ); ?></option>
                </select>

                <?php echo Kohana::lang( 'region.skybox' ); ?> :
                <select name="skybox" id="skybox" class="inputbox" >
                    <option value="0"><?php echo Kohana::lang( 'region.noSkybox' ); ?></option>
                    <?php if( $skybox ) : ?>
                        <?php foreach( $skybox as $val ) : ?>
                            <option value="<?php echo $val; ?>" <?php echo ( $val == $row->skybox ) ? 'selected="selected"' : ''; ?>><?php echo $val; ?></option>
                        <?php endforeach ?>
                    <?php endif ?>
                </select>

						<?php echo Kohana::lang( 'region.image_bg' ); ?> :
						<input type="button" id="list_vignette_background" class="button" value="<?php echo Kohana::lang( 'form.selected_list' ); ?>" />
						<input type="hidden" value="<?php echo $row->background; ?>" id="background" name="background"/>

						<?php echo Kohana::lang( 'region.music' ); ?> :
						<select name="music" id="music" class="inputbox" >
								<option value="" ><?php echo Kohana::lang( 'region.no_music' ); ?></option>
								<?php if( $music ) : ?>
										<?php foreach( $music as $val ) : ?>
												<option value="<?php echo $val; ?>" <?php
								if( $val == $row->music )
										echo 'selected="selected"';
												?> ><?php echo str_replace( '.ogg', '', str_replace( '_', ' ', $val ) ); ?></option>
														<?php endforeach ?>
												<?php endif ?>
						</select>

                <?php echo Kohana::lang( 'region.function' ); ?> :
                <textarea name="fonction" id="fonction" class="inputbox input-textarea" style="height:200px;"><?php echo $row->fonction; ?></textarea>


text:
This folder contains resources required for building the library and publishing the website.

Publishing the website
----------------------

The website at http://openlayers.org/ol-cesium/ is built using GitHub's [Automatic Page Generator](https://github.com/openlayers/ol-cesium/generated_pages/new), with the Architect theme. The page should be regenerated any time `README.md` changes. Please follow the instructions in the HTML comment block at the top of the content editor when updating the content of the web site.

To update the distribution artifacts (build, examples, API docs), go to the root of the repository, and invoke

    $ build/publish-website.sh

This will build the distribution artifacts and will publish them to the website.


text:
package com.szagurskii.patternedtextwatcher;

final class Preconditions {
  static void checkPatternInput(String pattern) {
    if (pattern == null) {
      throw new NullPointerException("Pattern can't be null.");
    }
    if (pattern.isEmpty()) {
      throw new IllegalArgumentException("Pattern can't be empty.");
    }
  }

  static void checkInput(String specialChar, boolean saveInput, boolean fillExtraChars) {
    if (specialChar == null) {
      throw new NullPointerException("Special char can't be null.");
    }
    if (specialChar.isEmpty()) {
      throw new IllegalArgumentException("Special char can't be empty.");
    }
    if (specialChar.length() > 1) {
      throw new IllegalArgumentException("Special char must be length = 1.");
    }
    if (saveInput && fillExtraChars) {
      throw new IllegalArgumentException("It is impossible to save input when the characters are " +
          "filled automatically instead of characters.");
    }
  }

  static void checkPatternInInput(String pattern, String specialChar) {
    if (!pattern.contains(specialChar)) {
      throw new IllegalStateException("There should be at least one special character in the " +
          "pattern string.");
    }
  }

  private Preconditions() {
  }
}


text: Rails.application.config.assets.precompile += %w( canteen/store.js canteen/store.css )


text:
<?php

namespace ActiveRecord\Exception;

use \Exception;

/**
 * Description of ActiveRecordException
 *
 * @author maguirre
 */
class ActiveRecordException extends Exception
{

}


text:
/**
 * @license Highstock JS v8.2.0 (2020-08-20)
 * @module highcharts/indicators/bollinger-bands
 * @requires highcharts
 * @requires highcharts/modules/stock
 *
 * Indicator series type for Highstock
 *
 * (c) 2010-2019 Paweł Fus
 *
 * License: www.highcharts.com/license
 */
'use strict';
import '../../Stock/Indicators/BBIndicator.js';


text:
package com.github.kafka_tools.local_communications;

import com.github.kafka_tools.local_communications.util.MemWriter;

/**
 * Author: Evgeny Zhoga
 * Date: 14.10.14
 */
public interface ClientInfo {
    public abstract void write(MemWriter writer);
}


text:
#include <Wt/WApplication>
#include <Wt/WBreak>
#include <Wt/WText>
#include <Wt/WVideo>
#include <Wt/WImage>
#include <Wt/WFlashObject>

using namespace Wt;

Wt::WApplication *createApplication(const Wt::WEnvironment& env)
{
  WApplication* app = new WApplication(env);

  app->messageResourceBundle().use(WApplication::appRoot() + "text");

  std::string ogvVideo =
    "http://www.webtoolkit.eu/videos/sintel_trailer.ogv";
  std::string mp4Video =
    "http://www.webtoolkit.eu/videos/sintel_trailer.mp4";
  std::string poster = "sintel_trailer.jpg";

  new WText(WString::tr("intro"), app->root());

  new WText(WString::tr("html5"), app->root());
  WVideo *v1 = new WVideo(app->root());
  v1->addSource(mp4Video);
  v1->addSource(ogvVideo);
  v1->setPoster(poster);
  v1->setAlternativeContent(new WImage(poster));
  v1->resize(640, 360);

  new WText(WString::tr("flash-fallback"), app->root());
  WFlashObject *flash2 =
    new WFlashObject("http://www.webtoolkit.eu/videos/player_flv_maxi.swf");
  flash2->setFlashVariable("startimage", "sintel_trailer.jpg");
  flash2->setFlashParameter("allowFullScreen", "true");
  flash2->setFlashVariable("flv", mp4Video);
  flash2->setFlashVariable("showvolume", "1");
  flash2->setFlashVariable("showfullscreen", "1");
  flash2->setAlternativeContent(new WImage(poster));
  flash2->resize(640, 360);
  WVideo *v2 = new WVideo(app->root());
  v2->addSource(mp4Video);
  v2->addSource(ogvVideo);
  v2->setAlternativeContent(flash2);
  v2->setPoster(poster);
  v2->resize(640, 360);

  return app;
}

int main(int argc, char **argv)
{
  return Wt::WRun(argc, argv, &createApplication);
}


text:
<?php

class Phoenix_Moneybookers_Model_Wlt extends Phoenix_Moneybookers_Model_Abstract
{
    /**
     * unique internal payment method identifier
     */
    protected $_code			= 'moneybookers_wlt';
    protected $_paymentMethod	= 'WLT';
    protected $_hidelogin		= '0';
}


text:
using System;

namespace Itschwabing.Libraries.ResourceChangeEvent
{
    public class ResourceChangeEventArgs : EventArgs
    {
        public object OldValue { get; private set; }
        public object NewValue { get; private set; }

        public ResourceChangeEventArgs(object oldValue, object newValue)
        {
            OldValue = oldValue;
            NewValue = newValue;
        }
    }
}


text:
package sl.hr_client.net.link;

/**
 * Created by Administrator on 2017/4/24.
 */

public interface LinkView {
    void updateLinksView(String str);

    void updateLoadMoreLinksView(String str);

    void showLoading();

    void showLoadingFailed();

    void hideLoading();

    void showError(String msg);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:es="http://marklogic.com/entity-services" xmlns:sem="http://marklogic.com/semantics" elementFormDefault="qualified">
  <xs:element name="a" type="xs:integer" />
  <xs:element name="b" type="xs:string" />
  <xs:element name="c" type="xs:date" />
  <xs:complexType name="ETOneType" mixed="true">
    <xs:sequence minOccurs="0">
      <xs:element ref="a" />
      <xs:element ref="b" />
      <xs:element minOccurs="0" ref="c" />
    </xs:sequence>
  </xs:complexType>
  <xs:element name="ETOne" type="ETOneType" />
</xs:schema>