text:
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.styles = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var React = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _clsx = _interopRequireDefault(require("clsx"));

var _utils = require("@material-ui/utils");

var _InputBase = _interopRequireDefault(require("../InputBase"));

var _NotchedOutline = _interopRequireDefault(require("./NotchedOutline"));

var _withStyles = _interopRequireDefault(require("../styles/withStyles"));

var styles = function styles(theme) {
  var borderColor = theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
  return {
    /* Styles applied to the root element. */
    root: {
      position: 'relative',
      borderRadius: theme.shape.borderRadius,
      '&:hover $notchedOutline': {
        borderColor: theme.palette.text.primary
      },
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        '&:hover $notchedOutline': {
          borderColor: borderColor
        }
      },
      '&$focused $notchedOutline': {
        borderColor: theme.palette.primary.main,
        borderWidth: 2
      },
      '&$error $notchedOutline': {
        borderColor: theme.palette.error.main
      },
      '&$disabled $notchedOutline': {
        borderColor: theme.palette.action.disabled
      }
    },

    /* Styles applied to the root element if the color is secondary. */
    colorSecondary: {
      '&$focused $notchedOutline': {
        borderColor: theme.palette.secondary.main
      }
    },

    /* Styles applied to the root element if the component is focused. */
    focused: {},

    /* Styles applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the root element if `startAdornment` is provided. */
    adornedStart: {
      paddingLeft: 14
    },

    /* Styles applied to the root element if `endAdornment` is provided. */
    adornedEnd: {
      paddingRight: 14
    },

    /* Pseudo-class applied to the root element if `error={true}`. */
    error: {},

    /* Styles applied to the `input` element if `margin="dense"`. */
    marginDense: {},

    /* Styles applied to the root element if `multiline={true}`. */
    multiline: {
      padding: '18.5px 14px',
      '&$marginDense': {
        paddingTop: 10.5,
        paddingBottom: 10.5
      }
    },

    /* Styles applied to the `NotchedOutline` element. */
    notchedOutline: {
      borderColor: borderColor
    },

    /* Styles applied to the `input` element. */
    input: {
      padding: '18.5px 14px',
      '&:-webkit-autofill': {
        WebkitBoxShadow: theme.palette.type === 'light' ? null : '0 0 0 100px #266798 inset',
        WebkitTextFillColor: theme.palette.type === 'light' ? null : '#fff',
        caretColor: theme.palette.type === 'light' ? null : '#fff',
        borderRadius: 'inherit'
      }
    },

    /* Styles applied to the `input` element if `margin="dense"`. */
    inputMarginDense: {
      paddingTop: 10.5,
      paddingBottom: 10.5
    },

    /* Styles applied to the `input` element if `multiline={true}`. */
    inputMultiline: {
      padding: 0
    },

    /* Styles applied to the `input` element if `startAdornment` is provided. */
    inputAdornedStart: {
      paddingLeft: 0
    },

    /* Styles applied to the `input` element if `endAdornment` is provided. */
    inputAdornedEnd: {
      paddingRight: 0
    }
  };
};

exports.styles = styles;
var OutlinedInput = React.forwardRef(function OutlinedInput(props, ref) {
  var classes = props.classes,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
      _props$inputComponent = props.inputComponent,
      inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,
      label = props.label,
      _props$labelWidth = props.labelWidth,
      labelWidth = _props$labelWidth === void 0 ? 0 : _props$labelWidth,
      _props$multiline = props.multiline,
      multiline = _props$multiline === void 0 ? false : _props$multiline,
      notched = props.notched,
      _props$type = props.type,
      type = _props$type === void 0 ? 'text' : _props$type,
      other = (0, _objectWithoutProperties2.default)(props, ["classes", "fullWidth", "inputComponent", "label", "labelWidth", "multiline", "notched", "type"]);
  return /*#__PURE__*/React.createElement(_InputBase.default, (0, _extends2.default)({
    renderSuffix: function renderSuffix(state) {
      return /*#__PURE__*/React.createElement(_NotchedOutline.default, {
        className: classes.notchedOutline,
        label: label,
        labelWidth: labelWidth,
        notched: typeof notched !== 'undefined' ? notched : Boolean(state.startAdornment || state.filled || state.focused)
      });
    },
    classes: (0, _extends2.default)((0, _extends2.default)({}, classes), {}, {
      root: (0, _clsx.default)(classes.root, classes.underline),
      notchedOutline: null
    }),
    fullWidth: fullWidth,
    inputComponent: inputComponent,
    multiline: multiline,
    ref: ref,
    type: type
  }, other));
});
process.env.NODE_ENV !== "production" ? OutlinedInput.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * This prop helps users to fill forms faster, especially on mobile devices.
   * The name can be confusing, as it's more like an autofill.
   * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
   */
  autoComplete: _propTypes.default.string,

  /**
   * If `true`, the `input` element will be focused during the first mount.
   */
  autoFocus: _propTypes.default.bool,

  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: _propTypes.default.object,

  /**
   * The color of the component. It supports those theme colors that make sense for this component.
   */
  color: _propTypes.default.oneOf(['primary', 'secondary']),

  /**
   * The default `input` element value. Use when the component is not controlled.
   */
  defaultValue: _propTypes.default.any,

  /**
   * If `true`, the `input` element will be disabled.
   */
  disabled: _propTypes.default.bool,

  /**
   * End `InputAdornment` for this component.
   */
  endAdornment: _propTypes.default.node,

  /**
   * If `true`, the input will indicate an error. This is normally obtained via context from
   * FormControl.
   */
  error: _propTypes.default.bool,

  /**
   * If `true`, the input will take up the full width of its container.
   */
  fullWidth: _propTypes.default.bool,

  /**
   * The id of the `input` element.
   */
  id: _propTypes.default.string,

  /**
   * The component used for the `input` element.
   * Either a string to use a HTML element or a component.
   */
  inputComponent: _propTypes.default.elementType,

  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   */
  inputProps: _propTypes.default.object,

  /**
   * Pass a ref to the `input` element.
   */
  inputRef: _utils.refType,

  /**
   * The label of the input. It is only used for layout. The actual labelling
   * is handled by `InputLabel`. If specified `labelWidth` is ignored.
   */
  label: _propTypes.default.node,

  /**
   * The width of the label. Is ignored if `label` is provided. Prefer `label`
   * if the input label appears with a strike through.
   */
  labelWidth: _propTypes.default.number,

  /**
   * If `dense`, will adjust vertical spacing. This is normally obtained via context from
   * FormControl.
   */
  margin: _propTypes.default.oneOf(['dense', 'none']),

  /**
   * If `true`, a textarea element will be rendered.
   */
  multiline: _propTypes.default.bool,

  /**
   * Name attribute of the `input` element.
   */
  name: _propTypes.default.string,

  /**
   * If `true`, the outline is notched to accommodate the label.
   */
  notched: _propTypes.default.bool,

  /**
   * Callback fired when the value is changed.
   *
   * @param {object} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: _propTypes.default.func,

  /**
   * The short hint displayed in the input before the user enters a value.
   */
  placeholder: _propTypes.default.string,

  /**
   * It prevents the user from changing the value of the field
   * (not from interacting with the field).
   */
  readOnly: _propTypes.default.bool,

  /**
   * If `true`, the `input` element will be required.
   */
  required: _propTypes.default.bool,

  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),

  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  rowsMax: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),

  /**
   * Start `InputAdornment` for this component.
   */
  startAdornment: _propTypes.default.node,

  /**
   * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
   */
  type: _propTypes.default.string,

  /**
   * The value of the `input` element, required for a controlled component.
   */
  value: _propTypes.default.any
} : void 0;
OutlinedInput.muiName = 'Input';

var _default = (0, _withStyles.default)(styles, {
  name: 'MuiOutlinedInput'
})(OutlinedInput);

exports.default = _default;


text:
package cgeo.geocaching.enumerations;

import cgeo.geocaching.loaders.AbstractSearchLoader.CacheListLoaderType;

import androidx.annotation.NonNull;

public enum CacheListType {
    OFFLINE(true, CacheListLoaderType.OFFLINE),
    POCKET(false, CacheListLoaderType.POCKET),
    HISTORY(true, CacheListLoaderType.HISTORY),
    NEAREST(false, CacheListLoaderType.NEAREST),
    COORDINATE(false, CacheListLoaderType.COORDINATE),
    KEYWORD(false, CacheListLoaderType.KEYWORD),
    ADDRESS(false, CacheListLoaderType.ADDRESS),
    FINDER(false, CacheListLoaderType.FINDER),
    OWNER(false, CacheListLoaderType.OWNER),
    MAP(false, CacheListLoaderType.MAP);

    /**
     * whether or not this list allows switching to another list
     */
    public final boolean canSwitch;

    @NonNull public final CacheListLoaderType loaderType;

    CacheListType(final boolean canSwitch, @NonNull final CacheListLoaderType loaderType) {
        this.canSwitch = canSwitch;
        this.loaderType = loaderType;
    }

    public int getLoaderId() {
        return loaderType.getLoaderId();
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * This module has utilities for URL resolution and parsing.
 */
var url = {};

/**
 * Take a URL string, and return an object.
 * @param urlStr
 * @param parseQueryString
 * @param slashesDenoteHost
 * @returns {URL}
 */
url.parse = function(urlStr, parseQueryString, slashesDenoteHost) {}

/**
 * Take a base URL, and a href URL, and resolve them as a browser would for
 * an anchor tag.
 * @param from
 * @param to
 */
url.resolve = function(from, to) {}

/**
 * Take a parsed URL object, and return a formatted URL string.
 * @param urlObj
 */
url.format = function(urlObj) {}

/* see http://nodejs.org/docs/v0.6.12/api/url.html#url_url */
function URL() {}
URL.prototype = {
    "href": "",
    "protocol": "",
    "host": "",
    "auth": "",
    "hostname": "",
    "port": "",
    "pathname": "",
    "search": "",
    "path": "",
    "query": "",
    "hash": "",
};

exports = url;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Falaise: falaise/bipo3/geometry/calo_tapered_scin_box_model.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Falaise
    2.1.0

SuperNEMO Software Toolkit

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

falaise

bipo3

geometry

Classes |
Namespaces

calo_tapered_scin_box_model.h File Reference

#include <iostream>

#include <string>

#include <boost/scoped_ptr.hpp>

#include <geomtools/i_model.h>

#include <geomtools/box.h>

#include <geomtools/sphere.h>

#include <geomtools/subtraction_3d.h>

#include <geomtools/intersection_3d.h>

#include <geomtools/polycone.h>

#include <geomtools/i_wires_drawer.h>

Go to the source code of this file.

Classes

class  	snemo::geometry::calo_tapered_scin_box_model

 	The geometry model for SuperNEMO calorimeter tapered scintillator block.  More...

struct  	snemo::geometry::calo_tapered_scin_box_model::wires_drawer

 	Special Gnuplot wires 3D rendering.  More...

Namespaces

  	snemo

  	snemo::geometry

<address class="footer">
Generated by

 1.8.11
</address>


text:
<?php

namespace PHPStamp\Document;

use PHPStamp\Exception\InvalidArgumentException;
use PHPStamp\Processor\Tag;

abstract class Document implements DocumentInterface
{
    const XPATH_PARAGRAPH  = 0;
    const XPATH_RUN  = 1;
    const XPATH_RUN_PROPERTY  = 2;
    const XPATH_TEXT  = 3;

    /**
     * Original document filename.
     *
     * @var string
     */
    private $documentName;

    /**
     * Path to original document.
     *
     * @var string
     */
    private $documentPath;

    /**
     * Creates a new Document.
     *
     * @param string $documentPath
     * @throws InvalidArgumentException
     */
    public function __construct($documentPath)
    {
        if (file_exists($documentPath) === false) {
            throw new InvalidArgumentException('File not found.');
        }

        $this->documentPath = $documentPath;
        $this->documentName = pathinfo($this->documentPath, PATHINFO_BASENAME);
    }

    /**
     * Extract main content file.
     *
     * @param string $to Path to extract content file.
     * @param bool $overwrite Overwrite content file.
     * @return string Full path to extracted document file.
     * @throws InvalidArgumentException
     */
    public function extract($to, $overwrite)
    {
        $filePath = $to . $this->getDocumentName() . '/' . $this->getContentPath();

        if (!file_exists($filePath) || $overwrite === true) {
            $zip = new \ZipArchive();

            $code = $zip->open($this->getDocumentPath());
            if ($code !== true) {
                throw new InvalidArgumentException(
                    'Can`t open archive "' . $this->documentPath . '", code "' . $code . '" returned.'
                );
            }

            if ($zip->extractTo($to . $this->documentName, $this->getContentPath()) === false) {
                throw new InvalidArgumentException('Destination not reachable.');
            }
        }

        return $filePath;
    }

    /**
     * Get MD5 hash to detect original document update.
     */
    public function getDocumentHash()
    {
        return md5_file($this->documentPath);
    }

    /**
     * @inherit
     */
    public function getDocumentName()
    {
        return $this->documentName;
    }

    /**
     * @inherit
     */
    public function getDocumentPath()
    {
        return $this->documentPath;
    }

    /**
     * @inherit
     * @param \DOMDocument $template
     */
    public abstract function cleanup(\DOMDocument $template);

    /**
     * @inherit
     */
    public abstract function getContentPath();

    /**
     * @inherit
     */
    public abstract function getNodePath();

    /**
     * @inherit
     * @param int $type XPATH_* constant.
     * @param bool $global Append global xpath //.
     */
    public abstract function getNodeName($type, $global = false);

    /**
     * @inherit
     * @param string $id Id as entered in placeholder.
     * @param Tag $tag Container tag.
     */
    public abstract function getExpression($id, Tag $tag);
}


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.

#include <cmath>
#include <numeric>
#include <vector>

#include "arrow/compute/api_aggregate.h"
#include "arrow/compute/kernels/common.h"
#include "arrow/compute/kernels/util_internal.h"
#include "arrow/stl_allocator.h"

namespace arrow {
namespace compute {
namespace internal {

namespace {

using QuantileState = internal::OptionsWrapper<QuantileOptions>;

// output is at some input data point, not interpolated
bool IsDataPoint(const QuantileOptions& options) {
  // some interpolation methods return exact data point
  return options.interpolation == QuantileOptions::LOWER ||
         options.interpolation == QuantileOptions::HIGHER ||
         options.interpolation == QuantileOptions::NEAREST;
}

// quantile to exact datapoint index (IsDataPoint == true)
uint64_t QuantileToDataPoint(size_t length, double q,
                             enum QuantileOptions::Interpolation interpolation) {
  const double index = (length - 1) * q;
  uint64_t datapoint_index = static_cast<uint64_t>(index);
  const double fraction = index - datapoint_index;

  if (interpolation == QuantileOptions::LINEAR ||
      interpolation == QuantileOptions::MIDPOINT) {
    DCHECK_EQ(fraction, 0);
  }

  // convert NEAREST interpolation method to LOWER or HIGHER
  if (interpolation == QuantileOptions::NEAREST) {
    if (fraction < 0.5) {
      interpolation = QuantileOptions::LOWER;
    } else if (fraction > 0.5) {
      interpolation = QuantileOptions::HIGHER;
    } else {
      // round 0.5 to nearest even number, similar to numpy.around
      interpolation =
          (datapoint_index & 1) ? QuantileOptions::HIGHER : QuantileOptions::LOWER;
    }
  }

  if (interpolation == QuantileOptions::HIGHER && fraction != 0) {
    ++datapoint_index;
  }

  return datapoint_index;
}

template <typename T>
double DataPointToDouble(T value, const DataType&) {
  return static_cast<double>(value);
}
double DataPointToDouble(const Decimal128& value, const DataType& ty) {
  return value.ToDouble(checked_cast<const DecimalType&>(ty).scale());
}
double DataPointToDouble(const Decimal256& value, const DataType& ty) {
  return value.ToDouble(checked_cast<const DecimalType&>(ty).scale());
}

// copy and nth_element approach, large memory footprint
template <typename InType>
struct SortQuantiler {
  using CType = typename TypeTraits<InType>::CType;
  using Allocator = arrow::stl::allocator<CType>;

  Status Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
    const QuantileOptions& options = QuantileState::Get(ctx);
    const Datum& datum = batch[0];

    // copy all chunks to a buffer, ignore nulls and nans
    std::vector<CType, Allocator> in_buffer(Allocator(ctx->memory_pool()));
    int64_t in_length = 0;
    if ((!options.skip_nulls && datum.null_count() > 0) ||
        (datum.length() - datum.null_count() < options.min_count)) {
      in_length = 0;
    } else {
      in_length = datum.length() - datum.null_count();
    }

    if (in_length > 0) {
      in_buffer.resize(in_length);
      CopyNonNullValues(datum, in_buffer.data());

      // drop nan
      if (is_floating_type<InType>::value) {
        const auto& it = std::remove_if(in_buffer.begin(), in_buffer.end(),
                                        [](CType v) { return v != v; });
        in_buffer.resize(it - in_buffer.begin());
      }
    }

    // prepare out array
    // out type depends on options
    const bool is_datapoint = IsDataPoint(options);
    const std::shared_ptr<DataType> out_type = is_datapoint ? datum.type() : float64();
    int64_t out_length = options.q.size();
    if (in_buffer.empty()) {
      return MakeArrayOfNull(out_type, out_length, ctx->memory_pool()).Value(out);
    }
    auto out_data = ArrayData::Make(out_type, out_length, 0);
    out_data->buffers.resize(2, nullptr);

    // calculate quantiles
    if (out_length > 0) {
      ARROW_ASSIGN_OR_RAISE(out_data->buffers[1],
                            ctx->Allocate(out_length * GetBitWidth(*out_type) / 8));

      // find quantiles in descending order
      std::vector<int64_t> q_indices(out_length);
      std::iota(q_indices.begin(), q_indices.end(), 0);
      std::sort(q_indices.begin(), q_indices.end(),
                [&options](int64_t left_index, int64_t right_index) {
                  return options.q[right_index] < options.q[left_index];
                });

      // input array is partitioned around data point at `last_index` (pivot)
      // for next quatile which is smaller, we only consider inputs left of the pivot
      uint64_t last_index = in_buffer.size();
      if (is_datapoint) {
        CType* out_buffer = out_data->template GetMutableValues<CType>(1);
        for (int64_t i = 0; i < out_length; ++i) {
          const int64_t q_index = q_indices[i];
          out_buffer[q_index] = GetQuantileAtDataPoint(
              in_buffer, &last_index, options.q[q_index], options.interpolation);
        }
      } else {
        double* out_buffer = out_data->template GetMutableValues<double>(1);
        for (int64_t i = 0; i < out_length; ++i) {
          const int64_t q_index = q_indices[i];
          out_buffer[q_index] =
              GetQuantileByInterp(in_buffer, &last_index, options.q[q_index],
                                  options.interpolation, *datum.type());
        }
      }
    }

    *out = Datum(std::move(out_data));
    return Status::OK();
  }

  // return quantile located exactly at some input data point
  CType GetQuantileAtDataPoint(std::vector<CType, Allocator>& in, uint64_t* last_index,
                               double q,
                               enum QuantileOptions::Interpolation interpolation) {
    const uint64_t datapoint_index = QuantileToDataPoint(in.size(), q, interpolation);

    if (datapoint_index != *last_index) {
      DCHECK_LT(datapoint_index, *last_index);
      std::nth_element(in.begin(), in.begin() + datapoint_index,
                       in.begin() + *last_index);
      *last_index = datapoint_index;
    }

    return in[datapoint_index];
  }

  // return quantile interpolated from adjacent input data points
  double GetQuantileByInterp(std::vector<CType, Allocator>& in, uint64_t* last_index,
                             double q, enum QuantileOptions::Interpolation interpolation,
                             const DataType& in_type) {
    const double index = (in.size() - 1) * q;
    const uint64_t lower_index = static_cast<uint64_t>(index);
    const double fraction = index - lower_index;

    if (lower_index != *last_index) {
      DCHECK_LT(lower_index, *last_index);
      std::nth_element(in.begin(), in.begin() + lower_index, in.begin() + *last_index);
    }

    const double lower_value = DataPointToDouble(in[lower_index], in_type);
    if (fraction == 0) {
      *last_index = lower_index;
      return lower_value;
    }

    const uint64_t higher_index = lower_index + 1;
    DCHECK_LT(higher_index, in.size());
    if (lower_index != *last_index && higher_index != *last_index) {
      DCHECK_LT(higher_index, *last_index);
      // higher value must be the minimal value after lower_index
      auto min = std::min_element(in.begin() + higher_index, in.begin() + *last_index);
      std::iter_swap(in.begin() + higher_index, min);
    }
    *last_index = lower_index;

    const double higher_value = DataPointToDouble(in[higher_index], in_type);

    if (interpolation == QuantileOptions::LINEAR) {
      // more stable than naive linear interpolation
      return fraction * higher_value + (1 - fraction) * lower_value;
    } else if (interpolation == QuantileOptions::MIDPOINT) {
      return lower_value / 2 + higher_value / 2;
    } else {
      DCHECK(false);
      return NAN;
    }
  }
};

// histogram approach with constant memory, only for integers within limited value range
template <typename InType>
struct CountQuantiler {
  using CType = typename InType::c_type;

  CType min;
  std::vector<uint64_t> counts;  // counts[i]: # of values equals i + min

  // indices to adjacent non-empty bins covering current quantile
  struct AdjacentBins {
    int left_index;
    int right_index;
    uint64_t total_count;  // accumulated counts till left_index (inclusive)
  };

  CountQuantiler(CType min, CType max) {
    uint32_t value_range = static_cast<uint32_t>(max - min) + 1;
    DCHECK_LT(value_range, 1 << 30);
    this->min = min;
    this->counts.resize(value_range, 0);
  }

  Status Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
    const QuantileOptions& options = QuantileState::Get(ctx);

    // count values in all chunks, ignore nulls
    const Datum& datum = batch[0];
    int64_t in_length = 0;
    if ((options.skip_nulls || (!options.skip_nulls && datum.null_count() == 0)) &&
        (datum.length() - datum.null_count() >= options.min_count)) {
      in_length = CountValues<CType>(this->counts.data(), datum, this->min);
    }

    // prepare out array
    // out type depends on options
    const bool is_datapoint = IsDataPoint(options);
    const std::shared_ptr<DataType> out_type =
        is_datapoint ? TypeTraits<InType>::type_singleton() : float64();
    int64_t out_length = options.q.size();
    if (in_length == 0) {
      return MakeArrayOfNull(out_type, out_length, ctx->memory_pool()).Value(out);
    }
    auto out_data = ArrayData::Make(out_type, out_length, 0);
    out_data->buffers.resize(2, nullptr);

    // calculate quantiles
    if (out_length > 0) {
      ARROW_ASSIGN_OR_RAISE(out_data->buffers[1],
                            ctx->Allocate(out_length * GetBitWidth(*out_type) / 8));

      // find quantiles in ascending order
      std::vector<int64_t> q_indices(out_length);
      std::iota(q_indices.begin(), q_indices.end(), 0);
      std::sort(q_indices.begin(), q_indices.end(),
                [&options](int64_t left_index, int64_t right_index) {
                  return options.q[left_index] < options.q[right_index];
                });

      AdjacentBins bins{0, 0, this->counts[0]};
      if (is_datapoint) {
        CType* out_buffer = out_data->template GetMutableValues<CType>(1);
        for (int64_t i = 0; i < out_length; ++i) {
          const int64_t q_index = q_indices[i];
          out_buffer[q_index] = GetQuantileAtDataPoint(
              in_length, &bins, options.q[q_index], options.interpolation);
        }
      } else {
        double* out_buffer = out_data->template GetMutableValues<double>(1);
        for (int64_t i = 0; i < out_length; ++i) {
          const int64_t q_index = q_indices[i];
          out_buffer[q_index] = GetQuantileByInterp(in_length, &bins, options.q[q_index],
                                                    options.interpolation);
        }
      }
    }

    *out = Datum(std::move(out_data));
    return Status::OK();
  }

  // return quantile located exactly at some input data point
  CType GetQuantileAtDataPoint(int64_t in_length, AdjacentBins* bins, double q,
                               enum QuantileOptions::Interpolation interpolation) {
    const uint64_t datapoint_index = QuantileToDataPoint(in_length, q, interpolation);
    while (datapoint_index >= bins->total_count &&
           static_cast<size_t>(bins->left_index) < this->counts.size() - 1) {
      ++bins->left_index;
      bins->total_count += this->counts[bins->left_index];
    }
    DCHECK_LT(datapoint_index, bins->total_count);
    return static_cast<CType>(bins->left_index + this->min);
  }

  // return quantile interpolated from adjacent input data points
  double GetQuantileByInterp(int64_t in_length, AdjacentBins* bins, double q,
                             enum QuantileOptions::Interpolation interpolation) {
    const double index = (in_length - 1) * q;
    const uint64_t index_floor = static_cast<uint64_t>(index);
    const double fraction = index - index_floor;

    while (index_floor >= bins->total_count &&
           static_cast<size_t>(bins->left_index) < this->counts.size() - 1) {
      ++bins->left_index;
      bins->total_count += this->counts[bins->left_index];
    }
    DCHECK_LT(index_floor, bins->total_count);
    const double lower_value = static_cast<double>(bins->left_index + this->min);

    // quantile lies in this bin, no interpolation needed
    if (index <= bins->total_count - 1) {
      return lower_value;
    }

    // quantile lies across two bins, locate next bin if not already done
    DCHECK_EQ(index_floor, bins->total_count - 1);
    if (bins->right_index <= bins->left_index) {
      bins->right_index = bins->left_index + 1;
      while (static_cast<size_t>(bins->right_index) < this->counts.size() - 1 &&
             this->counts[bins->right_index] == 0) {
        ++bins->right_index;
      }
    }
    DCHECK_LT(static_cast<size_t>(bins->right_index), this->counts.size());
    DCHECK_GT(this->counts[bins->right_index], 0);
    const double higher_value = static_cast<double>(bins->right_index + this->min);

    if (interpolation == QuantileOptions::LINEAR) {
      return fraction * higher_value + (1 - fraction) * lower_value;
    } else if (interpolation == QuantileOptions::MIDPOINT) {
      return lower_value / 2 + higher_value / 2;
    } else {
      DCHECK(false);
      return NAN;
    }
  }
};

// histogram or 'copy & nth_element' approach per value range and size, only for integers
template <typename InType>
struct CountOrSortQuantiler {
  using CType = typename InType::c_type;

  Status Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
    // cross point to benefit from histogram approach
    // parameters estimated from ad-hoc benchmarks manually
    static constexpr int kMinArraySize = 65536;
    static constexpr int kMaxValueRange = 65536;

    const Datum& datum = batch[0];
    if (datum.length() - datum.null_count() >= kMinArraySize) {
      CType min, max;
      std::tie(min, max) = GetMinMax<CType>(datum);

      if (static_cast<uint64_t>(max) - static_cast<uint64_t>(min) <= kMaxValueRange) {
        return CountQuantiler<InType>(min, max).Exec(ctx, batch, out);
      }
    }

    return SortQuantiler<InType>().Exec(ctx, batch, out);
  }
};

template <typename InType, typename Enable = void>
struct ExactQuantiler;

template <>
struct ExactQuantiler<UInt8Type> {
  CountQuantiler<UInt8Type> impl;
  ExactQuantiler() : impl(0, 255) {}
};

template <>
struct ExactQuantiler<Int8Type> {
  CountQuantiler<Int8Type> impl;
  ExactQuantiler() : impl(-128, 127) {}
};

template <typename InType>
struct ExactQuantiler<InType, enable_if_t<(is_integer_type<InType>::value &&
                                           (sizeof(typename InType::c_type) > 1))>> {
  CountOrSortQuantiler<InType> impl;
};

template <typename InType>
struct ExactQuantiler<InType, enable_if_t<is_floating_type<InType>::value>> {
  SortQuantiler<InType> impl;
};

template <typename InType>
struct ExactQuantiler<InType, enable_if_t<is_decimal_type<InType>::value>> {
  SortQuantiler<InType> impl;
};

template <typename T>
Status ScalarQuantile(KernelContext* ctx, const QuantileOptions& options,
                      const Scalar& scalar, Datum* out) {
  using CType = typename TypeTraits<T>::CType;
  ArrayData* output = out->mutable_array();
  output->length = options.q.size();
  auto out_type = IsDataPoint(options) ? scalar.type : float64();
  ARROW_ASSIGN_OR_RAISE(
      output->buffers[1],
      ctx->Allocate(output->length * bit_util::BytesForBits(GetBitWidth(*out_type))));

  if (!scalar.is_valid || options.min_count > 1) {
    output->null_count = output->length;
    ARROW_ASSIGN_OR_RAISE(output->buffers[0], ctx->AllocateBitmap(output->length));
    bit_util::SetBitsTo(output->buffers[0]->mutable_data(), /*offset=*/0, output->length,
                        false);
    if (IsDataPoint(options)) {
      CType* out_buffer = output->template GetMutableValues<CType>(1);
      std::fill(out_buffer, out_buffer + output->length, CType(0));
    } else {
      double* out_buffer = output->template GetMutableValues<double>(1);
      std::fill(out_buffer, out_buffer + output->length, 0.0);
    }
    return Status::OK();
  }
  output->null_count = 0;
  if (IsDataPoint(options)) {
    CType* out_buffer = output->template GetMutableValues<CType>(1);
    for (int64_t i = 0; i < output->length; i++) {
      out_buffer[i] = UnboxScalar<T>::Unbox(scalar);
    }
  } else {
    double* out_buffer = output->template GetMutableValues<double>(1);
    for (int64_t i = 0; i < output->length; i++) {
      out_buffer[i] = DataPointToDouble(UnboxScalar<T>::Unbox(scalar), *scalar.type);
    }
  }
  return Status::OK();
}

template <typename _, typename InType>
struct QuantileExecutor {
  static Status Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
    if (ctx->state() == nullptr) {
      return Status::Invalid("Quantile requires QuantileOptions");
    }

    const QuantileOptions& options = QuantileState::Get(ctx);
    if (options.q.empty()) {
      return Status::Invalid("Requires quantile argument");
    }
    for (double q : options.q) {
      if (q < 0 || q > 1) {
        return Status::Invalid("Quantile must be between 0 and 1");
      }
    }

    if (batch[0].is_scalar()) {
      return ScalarQuantile<InType>(ctx, options, *batch[0].scalar(), out);
    }

    return ExactQuantiler<InType>().impl.Exec(ctx, batch, out);
  }
};

Result<ValueDescr> ResolveOutput(KernelContext* ctx,
                                 const std::vector<ValueDescr>& args) {
  const QuantileOptions& options = QuantileState::Get(ctx);
  if (IsDataPoint(options)) {
    return ValueDescr::Array(args[0].type);
  } else {
    return ValueDescr::Array(float64());
  }
}

void AddQuantileKernels(VectorFunction* func) {
  VectorKernel base;
  base.init = QuantileState::Init;
  base.can_execute_chunkwise = false;
  base.output_chunked = false;

  for (const auto& ty : NumericTypes()) {
    base.signature = KernelSignature::Make({InputType(ty)}, OutputType(ResolveOutput));
    // output type is determined at runtime, set template argument to nulltype
    base.exec = GenerateNumeric<QuantileExecutor, NullType>(*ty);
    DCHECK_OK(func->AddKernel(base));
  }
  {
    base.signature =
        KernelSignature::Make({InputType(Type::DECIMAL128)}, OutputType(ResolveOutput));
    base.exec = QuantileExecutor<NullType, Decimal128Type>::Exec;
    DCHECK_OK(func->AddKernel(base));
  }
  {
    base.signature =
        KernelSignature::Make({InputType(Type::DECIMAL256)}, OutputType(ResolveOutput));
    base.exec = QuantileExecutor<NullType, Decimal256Type>::Exec;
    DCHECK_OK(func->AddKernel(base));
  }
}

const FunctionDoc quantile_doc{
    "Compute an array of quantiles of a numeric array or chunked array",
    ("By default, 0.5 quantile (median) is returned.\n"
     "If quantile lies between two data points, an interpolated value is\n"
     "returned based on selected interpolation method.\n"
     "Nulls and NaNs are ignored.\n"
     "An array of nulls is returned if there is no valid data point."),
    {"array"},
    "QuantileOptions"};

}  // namespace

void RegisterScalarAggregateQuantile(FunctionRegistry* registry) {
  static QuantileOptions default_options;
  auto func = std::make_shared<VectorFunction>("quantile", Arity::Unary(), &quantile_doc,
                                               &default_options);
  AddQuantileKernels(func.get());
  DCHECK_OK(registry->AddFunction(std::move(func)));
}

}  // namespace internal
}  // namespace compute
}  // namespace arrow


text:
package de.saxsys.mvvmfx.testingutils;

import java.lang.ref.WeakReference;

/**
 * This is a small testing helper to verify that a given object is available for Garbage Collection.
 *
 * The typical usage is:
 *
 *

 * Object testObject = new Object();
 *
 * GCVerifier verifier = GCVerifier.create(testObject);
 *
 *
 * testObject = null;  // now there is no reference to the object anymore so it should be available for GC
 *
 *
 * verifier.verify();  // this will throw an AssertionError if there is still a reference to the object somewhere
 *

 *
 */
public class GCVerifier {
	private final WeakReference reference;

	private final String objectName;

	GCVerifier(WeakReference reference, String objectName) {
		this.reference = reference;
		this.objectName = objectName;
	}

	/**
	 * Create a Verifier instance for the given Object. No hard reference to this object is stored internally.
	 *
	 * @param instance
	 *            the instance that is verified.
	 *
	 * @return an instance of the {@link GCVerifier} that can be used to verify the garbage collection of the given
	 *         instance.
	 */
	@SuppressWarnings("unchecked")
	public static GCVerifier create(Object instance) {
		return new GCVerifier(new WeakReference(instance), instance.toString());
	}

	public void verify(String message) {
		forceGC();

		if (!isAvailableForGC()) {
			throw new AssertionError(message);
		}
	}

	/**
	 * @return true if the object is available
	 */
	public boolean isAvailableForGC() {
		forceGC();

		return reference.get() == null;
	}

	public void verify() {
		verify("Expected the given object [" + objectName + "] to be available for Garbage Collection but it isn't");
	}

	/**
	 * This method can be used to "force" the garbage collection.
	 *
	 * This can be useful because with "System.gc()" you can't tell if the GC was actually done.
	 *
	 *
	 * This method will only return when the GC was done. Be careful: This method will block until the
	 * GC was done so when for some reason the java runtime doesn't run the GC your application won't continue.
	 */
	@SuppressWarnings("unchecked")
	public static void forceGC() {
		Object o = new Object();

		WeakReference ref = new WeakReference(o);

		o = null;

		while (ref.get() != null) {
			System.gc();
		}
	}
}


text:
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;

namespace Google.Cloud.Compute.V1.Tests
{
    /// <summary>Generated unit tests.</summary>
    public sealed class GeneratedBackendServicesClientTest
    {
        [xunit::FactAttribute]
        public void GetRequestObject()
        {
            moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
            GetBackendServiceRequest request = new GetBackendServiceRequest
            {
                Project = "projectaa6ff846",
                BackendService = "backend_serviceed490d45",
            };
            BackendService expectedResponse = new BackendService
            {
                Id = 11672635353343658936UL,
                Iap = new BackendServiceIAP(),
                ConsistentHash = new ConsistentHashLoadBalancerSettings(),
                Kind = "kindf7aa39d9",
                Name = "name1c9368b0",
                Port = -78310000,
                CustomRequestHeaders =
                {
                    "custom_request_headers3532c035",
                },
                CreationTimestamp = "creation_timestamp235e59a1",
                EdgeSecurityPolicy = "edge_security_policy85c5b8f4",
                PortName = "port_namebaaa4cd4",
                MaxStreamDuration = new Duration(),
                TimeoutSec = -1529270667,
                Protocol = "protocola08b7881",
                FailoverPolicy = new BackendServiceFailoverPolicy(),
                LocalityLbPolicy = "locality_lb_policyc8722098",
                ServiceBindings =
                {
                    "service_bindingse637c4a7",
                },
                Region = "regionedb20d96",
                LocalityLbPolicies =
                {
                    new BackendServiceLocalityLoadBalancingPolicyConfig(),
                },
                ConnectionTrackingPolicy = new BackendServiceConnectionTrackingPolicy(),
                SecurityPolicy = "security_policy76596315",
                CdnPolicy = new BackendServiceCdnPolicy(),
                Network = "networkd22ce091",
                Fingerprint = "fingerprint009e6052",
                EnableCDN = false,
                LogConfig = new BackendServiceLogConfig(),
                OutlierDetection = new OutlierDetection(),
                LoadBalancingScheme = "load_balancing_scheme21346104",
                AffinityCookieTtlSec = -328985636,
                CustomResponseHeaders =
                {
                    "custom_response_headersda5d431e",
                },
                CircuitBreakers = new CircuitBreakers(),
                Description = "description2cf9da67",
                HealthChecks =
                {
                    "health_checksedb1f3f8",
                },
                Subsetting = new Subsetting(),
                SelfLink = "self_link7e87f12d",
                ConnectionDraining = new ConnectionDraining(),
                SessionAffinity = "session_affinitye702dadf",
                SecuritySettings = new SecuritySettings(),
                Backends = { new Backend(), },
            };
            mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
            BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null, null);
            BackendService response = client.Get(request);
            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public async stt::Task GetRequestObjectAsync()
        {
            moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
            GetBackendServiceRequest request = new GetBackendServiceRequest
            {
                Project = "projectaa6ff846",
                BackendService = "backend_serviceed490d45",
            };
            BackendService expectedResponse = new BackendService
            {
                Id = 11672635353343658936UL,
                Iap = new BackendServiceIAP(),
                ConsistentHash = new ConsistentHashLoadBalancerSettings(),
                Kind = "kindf7aa39d9",
                Name = "name1c9368b0",
                Port = -78310000,
                CustomRequestHeaders =
                {
                    "custom_request_headers3532c035",
                },
                CreationTimestamp = "creation_timestamp235e59a1",
                EdgeSecurityPolicy = "edge_security_policy85c5b8f4",
                PortName = "port_namebaaa4cd4",
                MaxStreamDuration = new Duration(),
                TimeoutSec = -1529270667,
                Protocol = "protocola08b7881",
                FailoverPolicy = new BackendServiceFailoverPolicy(),
                LocalityLbPolicy = "locality_lb_policyc8722098",
                ServiceBindings =
                {
                    "service_bindingse637c4a7",
                },
                Region = "regionedb20d96",
                LocalityLbPolicies =
                {
                    new BackendServiceLocalityLoadBalancingPolicyConfig(),
                },
                ConnectionTrackingPolicy = new BackendServiceConnectionTrackingPolicy(),
                SecurityPolicy = "security_policy76596315",
                CdnPolicy = new BackendServiceCdnPolicy(),
                Network = "networkd22ce091",
                Fingerprint = "fingerprint009e6052",
                EnableCDN = false,
                LogConfig = new BackendServiceLogConfig(),
                OutlierDetection = new OutlierDetection(),
                LoadBalancingScheme = "load_balancing_scheme21346104",
                AffinityCookieTtlSec = -328985636,
                CustomResponseHeaders =
                {
                    "custom_response_headersda5d431e",
                },
                CircuitBreakers = new CircuitBreakers(),
                Description = "description2cf9da67",
                HealthChecks =
                {
                    "health_checksedb1f3f8",
                },
                Subsetting = new Subsetting(),
                SelfLink = "self_link7e87f12d",
                ConnectionDraining = new ConnectionDraining(),
                SessionAffinity = "session_affinitye702dadf",
                SecuritySettings = new SecuritySettings(),
                Backends = { new Backend(), },
            };
            mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendService>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null, null);
            BackendService responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
            xunit::Assert.Same(expectedResponse, responseCallSettings);
            BackendService responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public void Get()
        {
            moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
            GetBackendServiceRequest request = new GetBackendServiceRequest
            {
                Project = "projectaa6ff846",
                BackendService = "backend_serviceed490d45",
            };
            BackendService expectedResponse = new BackendService
            {
                Id = 11672635353343658936UL,
                Iap = new BackendServiceIAP(),
                ConsistentHash = new ConsistentHashLoadBalancerSettings(),
                Kind = "kindf7aa39d9",
                Name = "name1c9368b0",
                Port = -78310000,
                CustomRequestHeaders =
                {
                    "custom_request_headers3532c035",
                },
                CreationTimestamp = "creation_timestamp235e59a1",
                EdgeSecurityPolicy = "edge_security_policy85c5b8f4",
                PortName = "port_namebaaa4cd4",
                MaxStreamDuration = new Duration(),
                TimeoutSec = -1529270667,
                Protocol = "protocola08b7881",
                FailoverPolicy = new BackendServiceFailoverPolicy(),
                LocalityLbPolicy = "locality_lb_policyc8722098",
                ServiceBindings =
                {
                    "service_bindingse637c4a7",
                },
                Region = "regionedb20d96",
                LocalityLbPolicies =
                {
                    new BackendServiceLocalityLoadBalancingPolicyConfig(),
                },
                ConnectionTrackingPolicy = new BackendServiceConnectionTrackingPolicy(),
                SecurityPolicy = "security_policy76596315",
                CdnPolicy = new BackendServiceCdnPolicy(),
                Network = "networkd22ce091",
                Fingerprint = "fingerprint009e6052",
                EnableCDN = false,
                LogConfig = new BackendServiceLogConfig(),
                OutlierDetection = new OutlierDetection(),
                LoadBalancingScheme = "load_balancing_scheme21346104",
                AffinityCookieTtlSec = -328985636,
                CustomResponseHeaders =
                {
                    "custom_response_headersda5d431e",
                },
                CircuitBreakers = new CircuitBreakers(),
                Description = "description2cf9da67",
                HealthChecks =
                {
                    "health_checksedb1f3f8",
                },
                Subsetting = new Subsetting(),
                SelfLink = "self_link7e87f12d",
                ConnectionDraining = new ConnectionDraining(),
                SessionAffinity = "session_affinitye702dadf",
                SecuritySettings = new SecuritySettings(),
                Backends = { new Backend(), },
            };
            mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
            BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null, null);
            BackendService response = client.Get(request.Project, request.BackendService);
            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public async stt::Task GetAsync()
        {
            moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
            GetBackendServiceRequest request = new GetBackendServiceRequest
            {
                Project = "projectaa6ff846",
                BackendService = "backend_serviceed490d45",
            };
            BackendService expectedResponse = new BackendService
            {
                Id = 11672635353343658936UL,
                Iap = new BackendServiceIAP(),
                ConsistentHash = new ConsistentHashLoadBalancerSettings(),
                Kind = "kindf7aa39d9",
                Name = "name1c9368b0",
                Port = -78310000,
                CustomRequestHeaders =
                {
                    "custom_request_headers3532c035",
                },
                CreationTimestamp = "creation_timestamp235e59a1",
                EdgeSecurityPolicy = "edge_security_policy85c5b8f4",
                PortName = "port_namebaaa4cd4",
                MaxStreamDuration = new Duration(),
                TimeoutSec = -1529270667,
                Protocol = "protocola08b7881",
                FailoverPolicy = new BackendServiceFailoverPolicy(),
                LocalityLbPolicy = "locality_lb_policyc8722098",
                ServiceBindings =
                {
                    "service_bindingse637c4a7",
                },
                Region = "regionedb20d96",
                LocalityLbPolicies =
                {
                    new BackendServiceLocalityLoadBalancingPolicyConfig(),
                },
                ConnectionTrackingPolicy = new BackendServiceConnectionTrackingPolicy(),
                SecurityPolicy = "security_policy76596315",
                CdnPolicy = new BackendServiceCdnPolicy(),
                Network = "networkd22ce091",
                Fingerprint = "fingerprint009e6052",
                EnableCDN = false,
                LogConfig = new BackendServiceLogConfig(),
                OutlierDetection = new OutlierDetection(),
                LoadBalancingScheme = "load_balancing_scheme21346104",
                AffinityCookieTtlSec = -328985636,
                CustomResponseHeaders =
                {
                    "custom_response_headersda5d431e",
                },
                CircuitBreakers = new CircuitBreakers(),
                Description = "description2cf9da67",
                HealthChecks =
                {
                    "health_checksedb1f3f8",
                },
                Subsetting = new Subsetting(),
                SelfLink = "self_link7e87f12d",
                ConnectionDraining = new ConnectionDraining(),
                SessionAffinity = "session_affinitye702dadf",
                SecuritySettings = new SecuritySettings(),
                Backends = { new Backend(), },
            };
            mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendService>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null, null);
            BackendService responseCallSettings = await client.GetAsync(request.Project, request.BackendService, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
            xunit::Assert.Same(expectedResponse, responseCallSettings);
            BackendService responseCancellationToken = await client.GetAsync(request.Project, request.BackendService, st::CancellationToken.None);
            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public void GetHealthRequestObject()
        {
            moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
            GetHealthBackendServiceRequest request = new GetHealthBackendServiceRequest
            {
                ResourceGroupReferenceResource = new ResourceGroupReference(),
                Project = "projectaa6ff846",
                BackendService = "backend_serviceed490d45",
            };
            BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth
            {
                Kind = "kindf7aa39d9",
                Annotations =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                HealthStatus = { new HealthStatus(), },
            };
            mockGrpcClient.Setup(x => x.GetHealth(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
            BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null, null);
            BackendServiceGroupHealth response = client.GetHealth(request);
            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public async stt::Task GetHealthRequestObjectAsync()
        {
            moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
            GetHealthBackendServiceRequest request = new GetHealthBackendServiceRequest
            {
                ResourceGroupReferenceResource = new ResourceGroupReference(),
                Project = "projectaa6ff846",
                BackendService = "backend_serviceed490d45",
            };
            BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth
            {
                Kind = "kindf7aa39d9",
                Annotations =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                HealthStatus = { new HealthStatus(), },
            };
            mockGrpcClient.Setup(x => x.GetHealthAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendServiceGroupHealth>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null, null);
            BackendServiceGroupHealth responseCallSettings = await client.GetHealthAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
            xunit::Assert.Same(expectedResponse, responseCallSettings);
            BackendServiceGroupHealth responseCancellationToken = await client.GetHealthAsync(request, st::CancellationToken.None);
            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public void GetHealth()
        {
            moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
            GetHealthBackendServiceRequest request = new GetHealthBackendServiceRequest
            {
                ResourceGroupReferenceResource = new ResourceGroupReference(),
                Project = "projectaa6ff846",
                BackendService = "backend_serviceed490d45",
            };
            BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth
            {
                Kind = "kindf7aa39d9",
                Annotations =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                HealthStatus = { new HealthStatus(), },
            };
            mockGrpcClient.Setup(x => x.GetHealth(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
            BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null, null);
            BackendServiceGroupHealth response = client.GetHealth(request.Project, request.BackendService, request.ResourceGroupReferenceResource);
            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public async stt::Task GetHealthAsync()
        {
            moq::Mock<BackendServices.BackendServicesClient> mockGrpcClient = new moq::Mock<BackendServices.BackendServicesClient>(moq::MockBehavior.Strict);
            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
            GetHealthBackendServiceRequest request = new GetHealthBackendServiceRequest
            {
                ResourceGroupReferenceResource = new ResourceGroupReference(),
                Project = "projectaa6ff846",
                BackendService = "backend_serviceed490d45",
            };
            BackendServiceGroupHealth expectedResponse = new BackendServiceGroupHealth
            {
                Kind = "kindf7aa39d9",
                Annotations =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                HealthStatus = { new HealthStatus(), },
            };
            mockGrpcClient.Setup(x => x.GetHealthAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BackendServiceGroupHealth>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            BackendServicesClient client = new BackendServicesClientImpl(mockGrpcClient.Object, null, null);
            BackendServiceGroupHealth responseCallSettings = await client.GetHealthAsync(request.Project, request.BackendService, request.ResourceGroupReferenceResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
            xunit::Assert.Same(expectedResponse, responseCallSettings);
            BackendServiceGroupHealth responseCancellationToken = await client.GetHealthAsync(request.Project, request.BackendService, request.ResourceGroupReferenceResource, st::CancellationToken.None);
            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
    }
}


text:
package chaincode

import (
	"bytes"
	"fmt"
	"io"
	"strconv"
	"sync"
	"time"

	"github.com/golang/protobuf/proto"
	logging "github.com/op/go-logging"
	"github.com/spf13/viper"
	"golang.org/x/net/context"

	"strings"

	"github.com/hyperledger/fabric/core/container"
	"github.com/hyperledger/fabric/core/container/ccintf"
	"github.com/hyperledger/fabric/core/crypto"
	"github.com/hyperledger/fabric/core/ledger"
	"github.com/hyperledger/fabric/flogging"
	pb "github.com/hyperledger/fabric/protos/peer"
)

// ChainName is the name of the chain to which this chaincode support belongs to.
type ChainName string

const (
	// DefaultChain is the name of the default chain.
	DefaultChain ChainName = "default"
	// DevModeUserRunsChaincode property allows user to run chaincode in development environment
	DevModeUserRunsChaincode       string = "dev"
	chaincodeStartupTimeoutDefault int    = 5000
	chaincodeInstallPathDefault    string = "/opt/gopath/bin/"
	peerAddressDefault             string = "0.0.0.0:7051"

	//TXSimulatorKey is used to attach ledger simulation context
	TXSimulatorKey string = "txsimulatorkey"
)

// chains is a map between different blockchains and their ChaincodeSupport.
//this needs to be a first class, top-level object... for now, lets just have a placeholder
var chains map[ChainName]*ChaincodeSupport

func init() {
	chains = make(map[ChainName]*ChaincodeSupport)
}

//use this for ledger access and make sure TXSimulator is being used
func getTxSimulator(context context.Context) ledger.TxSimulator {
	if txsim, ok := context.Value(TXSimulatorKey).(ledger.TxSimulator); ok {
		return txsim
	}
	panic("!!!---Not Using ledgernext---!!!")
}

//
//chaincode runtime environment encapsulates handler and container environment
//This is where the VM that's running the chaincode would hook in
type chaincodeRTEnv struct {
	handler *Handler
}

// runningChaincodes contains maps of chaincodeIDs to their chaincodeRTEs
type runningChaincodes struct {
	sync.RWMutex
	// chaincode environment for each chaincode
	chaincodeMap map[string]*chaincodeRTEnv
}

// GetChain returns the chaincode support for a given chain
func GetChain(name ChainName) *ChaincodeSupport {
	return chains[name]
}

//call this under lock
func (chaincodeSupport *ChaincodeSupport) preLaunchSetup(chaincode string) chan bool {
	//register placeholder Handler. This will be transferred in registerHandler
	//NOTE: from this point, existence of handler for this chaincode means the chaincode
	//is in the process of getting started (or has been started)
	notfy := make(chan bool, 1)
	chaincodeSupport.runningChaincodes.chaincodeMap[chaincode] = &chaincodeRTEnv{handler: &Handler{readyNotify: notfy}}
	return notfy
}

//call this under lock
func (chaincodeSupport *ChaincodeSupport) chaincodeHasBeenLaunched(chaincode string) (*chaincodeRTEnv, bool) {
	chrte, hasbeenlaunched := chaincodeSupport.runningChaincodes.chaincodeMap[chaincode]
	return chrte, hasbeenlaunched
}

// NewChaincodeSupport creates a new ChaincodeSupport instance
func NewChaincodeSupport(chainname ChainName, getPeerEndpoint func() (*pb.PeerEndpoint, error), userrunsCC bool, ccstartuptimeout time.Duration, secHelper crypto.Peer) *ChaincodeSupport {
	pnid := viper.GetString("peer.networkId")
	pid := viper.GetString("peer.id")

	s := &ChaincodeSupport{name: chainname, runningChaincodes: &runningChaincodes{chaincodeMap: make(map[string]*chaincodeRTEnv)}, secHelper: secHelper, peerNetworkID: pnid, peerID: pid}

	//initialize global chain
	chains[chainname] = s

	peerEndpoint, err := getPeerEndpoint()
	if err != nil {
		chaincodeLogger.Errorf("Error getting PeerEndpoint, using peer.address: %s", err)
		s.peerAddress = viper.GetString("peer.address")
	} else {
		s.peerAddress = peerEndpoint.Address
	}
	chaincodeLogger.Infof("Chaincode support using peerAddress: %s\n", s.peerAddress)
	//peerAddress = viper.GetString("peer.address")
	if s.peerAddress == "" {
		s.peerAddress = peerAddressDefault
	}

	s.userRunsCC = userrunsCC

	s.ccStartupTimeout = ccstartuptimeout

	//TODO I'm not sure if this needs to be on a per chain basis... too lowel and just needs to be a global default ?
	s.chaincodeInstallPath = viper.GetString("chaincode.installpath")
	if s.chaincodeInstallPath == "" {
		s.chaincodeInstallPath = chaincodeInstallPathDefault
	}

	s.peerTLS = viper.GetBool("peer.tls.enabled")
	if s.peerTLS {
		s.peerTLSCertFile = viper.GetString("peer.tls.cert.file")
		s.peerTLSKeyFile = viper.GetString("peer.tls.key.file")
		s.peerTLSSvrHostOrd = viper.GetString("peer.tls.serverhostoverride")
	}

	kadef := 0
	if ka := viper.GetString("chaincode.keepalive"); ka == "" {
		s.keepalive = time.Duration(kadef) * time.Second
	} else {
		t, terr := strconv.Atoi(ka)
		if terr != nil {
			chaincodeLogger.Errorf("Invalid keepalive value %s (%s) defaulting to %d", ka, terr, kadef)
			t = kadef
		} else if t <= 0 {
			chaincodeLogger.Debugf("Turn off keepalive(value %s)", ka)
			t = kadef
		}
		s.keepalive = time.Duration(t) * time.Second
	}

	viper.SetEnvPrefix("CORE")
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)

	chaincodeLogLevelString := viper.GetString("logging.chaincode")
	chaincodeLogLevel, err := logging.LogLevel(chaincodeLogLevelString)

	if err == nil {
		s.chaincodeLogLevel = chaincodeLogLevel.String()
	} else {
		chaincodeLogger.Infof("chaincode logging level %s is invalid. defaulting to %s\n", chaincodeLogLevelString, flogging.DefaultLoggingLevel().String())
		s.chaincodeLogLevel = flogging.DefaultLoggingLevel().String()
	}

	return s
}

// // ChaincodeStream standard stream for ChaincodeMessage type.
// type ChaincodeStream interface {
// 	Send(*pb.ChaincodeMessage) error
// 	Recv() (*pb.ChaincodeMessage, error)
// }

// ChaincodeSupport responsible for providing interfacing with chaincodes from the Peer.
type ChaincodeSupport struct {
	name                 ChainName
	runningChaincodes    *runningChaincodes
	peerAddress          string
	ccStartupTimeout     time.Duration
	chaincodeInstallPath string
	userRunsCC           bool
	secHelper            crypto.Peer
	peerNetworkID        string
	peerID               string
	peerTLS              bool
	peerTLSCertFile      string
	peerTLSKeyFile       string
	peerTLSSvrHostOrd    string
	keepalive            time.Duration
	chaincodeLogLevel    string
}

// DuplicateChaincodeHandlerError returned if attempt to register same chaincodeID while a stream already exists.
type DuplicateChaincodeHandlerError struct {
	ChaincodeID *pb.ChaincodeID
}

func (d *DuplicateChaincodeHandlerError) Error() string {
	return fmt.Sprintf("Duplicate chaincodeID error: %s", d.ChaincodeID)
}

func newDuplicateChaincodeHandlerError(chaincodeHandler *Handler) error {
	return &DuplicateChaincodeHandlerError{ChaincodeID: chaincodeHandler.ChaincodeID}
}

func (chaincodeSupport *ChaincodeSupport) registerHandler(chaincodehandler *Handler) error {
	key := chaincodehandler.ChaincodeID.Name

	chaincodeSupport.runningChaincodes.Lock()
	defer chaincodeSupport.runningChaincodes.Unlock()

	chrte2, ok := chaincodeSupport.chaincodeHasBeenLaunched(key)
	if ok && chrte2.handler.registered == true {
		chaincodeLogger.Debugf("duplicate registered handler(key:%s) return error", key)
		// Duplicate, return error
		return newDuplicateChaincodeHandlerError(chaincodehandler)
	}
	//a placeholder, unregistered handler will be setup by query or transaction processing that comes
	//through via consensus. In this case we swap the handler and give it the notify channel
	if chrte2 != nil {
		chaincodehandler.readyNotify = chrte2.handler.readyNotify
		chrte2.handler = chaincodehandler
	} else {
		chaincodeSupport.runningChaincodes.chaincodeMap[key] = &chaincodeRTEnv{handler: chaincodehandler}
	}

	chaincodehandler.registered = true

	//now we are ready to receive messages and send back responses
	chaincodehandler.txCtxs = make(map[string]*transactionContext)
	chaincodehandler.txidMap = make(map[string]bool)
	chaincodehandler.isTransaction = make(map[string]bool)

	chaincodeLogger.Debugf("registered handler complete for chaincode %s", key)

	return nil
}

func (chaincodeSupport *ChaincodeSupport) deregisterHandler(chaincodehandler *Handler) error {

	// clean up rangeQueryIteratorMap
	for _, context := range chaincodehandler.txCtxs {
		for _, v := range context.rangeQueryIteratorMap {
			v.Close()
		}
	}

	key := chaincodehandler.ChaincodeID.Name
	chaincodeLogger.Debugf("Deregister handler: %s", key)
	chaincodeSupport.runningChaincodes.Lock()
	defer chaincodeSupport.runningChaincodes.Unlock()
	if _, ok := chaincodeSupport.chaincodeHasBeenLaunched(key); !ok {
		// Handler NOT found
		return fmt.Errorf("Error deregistering handler, could not find handler with key: %s", key)
	}
	delete(chaincodeSupport.runningChaincodes.chaincodeMap, key)
	chaincodeLogger.Debugf("Deregistered handler with key: %s", key)
	return nil
}

// Based on state of chaincode send either init or ready to move to ready state
func (chaincodeSupport *ChaincodeSupport) sendInitOrReady(context context.Context, txid string, chaincode string, initArgs [][]byte, timeout time.Duration, tx *pb.Transaction, depTx *pb.Transaction) error {
	chaincodeSupport.runningChaincodes.Lock()
	//if its in the map, there must be a connected stream...nothing to do
	var chrte *chaincodeRTEnv
	var ok bool
	if chrte, ok = chaincodeSupport.chaincodeHasBeenLaunched(chaincode); !ok {
		chaincodeSupport.runningChaincodes.Unlock()
		chaincodeLogger.Debugf("handler not found for chaincode %s", chaincode)
		return fmt.Errorf("handler not found for chaincode %s", chaincode)
	}
	chaincodeSupport.runningChaincodes.Unlock()

	var notfy chan *pb.ChaincodeMessage
	var err error
	if notfy, err = chrte.handler.initOrReady(context, txid, initArgs, tx, depTx); err != nil {
		return fmt.Errorf("Error sending %s: %s", pb.ChaincodeMessage_INIT, err)
	}
	if notfy != nil {
		select {
		case ccMsg := <-notfy:
			if ccMsg.Type == pb.ChaincodeMessage_ERROR {
				err = fmt.Errorf("Error initializing container %s: %s", chaincode, string(ccMsg.Payload))
			}
		case <-time.After(timeout):
			err = fmt.Errorf("Timeout expired while executing send init message")
		}
	}

	//if initOrReady succeeded, our responsibility to delete the context
	chrte.handler.deleteTxContext(txid)

	return err
}

//get args and env given chaincodeID
func (chaincodeSupport *ChaincodeSupport) getArgsAndEnv(cID *pb.ChaincodeID, cLang pb.ChaincodeSpec_Type) (args []string, envs []string, err error) {
	envs = []string{"CORE_CHAINCODE_ID_NAME=" + cID.Name}
	//if TLS is enabled, pass TLS material to chaincode
	if chaincodeSupport.peerTLS {
		envs = append(envs, "CORE_PEER_TLS_ENABLED=true")
		envs = append(envs, "CORE_PEER_TLS_CERT_FILE="+chaincodeSupport.peerTLSCertFile)
		if chaincodeSupport.peerTLSSvrHostOrd != "" {
			envs = append(envs, "CORE_PEER_TLS_SERVERHOSTOVERRIDE="+chaincodeSupport.peerTLSSvrHostOrd)
		}
	} else {
		envs = append(envs, "CORE_PEER_TLS_ENABLED=false")
	}

	if chaincodeSupport.chaincodeLogLevel != "" {
		envs = append(envs, "CORE_LOGGING_CHAINCODE="+chaincodeSupport.chaincodeLogLevel)
	}

	switch cLang {
	case pb.ChaincodeSpec_GOLANG, pb.ChaincodeSpec_CAR:
		//chaincode executable will be same as the name of the chaincode
		args = []string{chaincodeSupport.chaincodeInstallPath + cID.Name, fmt.Sprintf("-peer.address=%s", chaincodeSupport.peerAddress)}
		chaincodeLogger.Debugf("Executable is %s", args[0])
	case pb.ChaincodeSpec_JAVA:
		//TODO add security args
		args = strings.Split(
			fmt.Sprintf("/root/Chaincode/bin/runChaincode -a %s -i %s",
				chaincodeSupport.peerAddress, cID.Name),
			" ")
		if chaincodeSupport.peerTLS {
			args = append(args, " -s")
		}
		chaincodeLogger.Debugf("Executable is %s", args[0])
	default:
		return nil, nil, fmt.Errorf("Unknown chaincodeType: %s", cLang)
	}
	return args, envs, nil
}

// launchAndWaitForRegister will launch container if not already running. Use the targz to create the image if not found
func (chaincodeSupport *ChaincodeSupport) launchAndWaitForRegister(ctxt context.Context, cds *pb.ChaincodeDeploymentSpec, cID *pb.ChaincodeID, txid string, cLang pb.ChaincodeSpec_Type, targz io.Reader) (bool, error) {
	chaincode := cID.Name
	if chaincode == "" {
		return false, fmt.Errorf("chaincode name not set")
	}

	chaincodeSupport.runningChaincodes.Lock()
	var ok bool
	//if its in the map, there must be a connected stream...nothing to do
	if _, ok = chaincodeSupport.chaincodeHasBeenLaunched(chaincode); ok {
		chaincodeLogger.Debugf("chaincode is running and ready: %s", chaincode)
		chaincodeSupport.runningChaincodes.Unlock()
		return true, nil
	}
	alreadyRunning := false

	notfy := chaincodeSupport.preLaunchSetup(chaincode)
	chaincodeSupport.runningChaincodes.Unlock()

	//launch the chaincode

	args, env, err := chaincodeSupport.getArgsAndEnv(cID, cLang)
	if err != nil {
		return alreadyRunning, err
	}

	chaincodeLogger.Debugf("start container: %s(networkid:%s,peerid:%s)", chaincode, chaincodeSupport.peerNetworkID, chaincodeSupport.peerID)

	vmtype, _ := chaincodeSupport.getVMType(cds)

	sir := container.StartImageReq{CCID: ccintf.CCID{ChaincodeSpec: cds.ChaincodeSpec, NetworkID: chaincodeSupport.peerNetworkID, PeerID: chaincodeSupport.peerID}, Reader: targz, Args: args, Env: env}

	ipcCtxt := context.WithValue(ctxt, ccintf.GetCCHandlerKey(), chaincodeSupport)

	resp, err := container.VMCProcess(ipcCtxt, vmtype, sir)
	if err != nil || (resp != nil && resp.(container.VMCResp).Err != nil) {
		if err == nil {
			err = resp.(container.VMCResp).Err
		}
		err = fmt.Errorf("Error starting container: %s", err)
		chaincodeSupport.runningChaincodes.Lock()
		delete(chaincodeSupport.runningChaincodes.chaincodeMap, chaincode)
		chaincodeSupport.runningChaincodes.Unlock()
		return alreadyRunning, err
	}

	//wait for REGISTER state
	select {
	case ok := <-notfy:
		if !ok {
			err = fmt.Errorf("registration failed for %s(networkid:%s,peerid:%s,tx:%s)", chaincode, chaincodeSupport.peerNetworkID, chaincodeSupport.peerID, txid)
		}
	case <-time.After(chaincodeSupport.ccStartupTimeout):
		err = fmt.Errorf("Timeout expired while starting chaincode %s(networkid:%s,peerid:%s,tx:%s)", chaincode, chaincodeSupport.peerNetworkID, chaincodeSupport.peerID, txid)
	}
	if err != nil {
		chaincodeLogger.Debugf("stopping due to error while launching %s", err)
		errIgnore := chaincodeSupport.Stop(ctxt, cds)
		if errIgnore != nil {
			chaincodeLogger.Debugf("error on stop %s(%s)", errIgnore, err)
		}
	}
	return alreadyRunning, err
}

//Stop stops a chaincode if running
func (chaincodeSupport *ChaincodeSupport) Stop(context context.Context, cds *pb.ChaincodeDeploymentSpec) error {
	chaincode := cds.ChaincodeSpec.ChaincodeID.Name
	if chaincode == "" {
		return fmt.Errorf("chaincode name not set")
	}

	//stop the chaincode
	sir := container.StopImageReq{CCID: ccintf.CCID{ChaincodeSpec: cds.ChaincodeSpec, NetworkID: chaincodeSupport.peerNetworkID, PeerID: chaincodeSupport.peerID}, Timeout: 0}

	vmtype, _ := chaincodeSupport.getVMType(cds)

	_, err := container.VMCProcess(context, vmtype, sir)
	if err != nil {
		err = fmt.Errorf("Error stopping container: %s", err)
		//but proceed to cleanup
	}

	chaincodeSupport.runningChaincodes.Lock()
	if _, ok := chaincodeSupport.chaincodeHasBeenLaunched(chaincode); !ok {
		//nothing to do
		chaincodeSupport.runningChaincodes.Unlock()
		return nil
	}

	delete(chaincodeSupport.runningChaincodes.chaincodeMap, chaincode)

	chaincodeSupport.runningChaincodes.Unlock()

	return err
}

// Launch will launch the chaincode if not running (if running return nil) and will wait for handler of the chaincode to get into FSM ready state.
func (chaincodeSupport *ChaincodeSupport) Launch(context context.Context, t *pb.Transaction) (*pb.ChaincodeID, *pb.ChaincodeInput, error) {
	//build the chaincode
	var cID *pb.ChaincodeID
	var cMsg *pb.ChaincodeInput
	var cLang pb.ChaincodeSpec_Type
	var initargs [][]byte

	cds := &pb.ChaincodeDeploymentSpec{}
	if t.Type == pb.Transaction_CHAINCODE_DEPLOY {
		err := proto.Unmarshal(t.Payload, cds)
		if err != nil {
			return nil, nil, err
		}
		cID = cds.ChaincodeSpec.ChaincodeID
		cMsg = cds.ChaincodeSpec.CtorMsg
		cLang = cds.ChaincodeSpec.Type
		initargs = cMsg.Args
	} else if t.Type == pb.Transaction_CHAINCODE_INVOKE || t.Type == pb.Transaction_CHAINCODE_QUERY {
		ci := &pb.ChaincodeInvocationSpec{}
		err := proto.Unmarshal(t.Payload, ci)
		if err != nil {
			return nil, nil, err
		}
		cID = ci.ChaincodeSpec.ChaincodeID
		cMsg = ci.ChaincodeSpec.CtorMsg
	} else {
		chaincodeSupport.runningChaincodes.Unlock()
		return nil, nil, fmt.Errorf("invalid transaction type: %d", t.Type)
	}
	chaincode := cID.Name
	chaincodeSupport.runningChaincodes.Lock()
	var chrte *chaincodeRTEnv
	var ok bool
	var err error
	//if its in the map, there must be a connected stream...nothing to do
	if chrte, ok = chaincodeSupport.chaincodeHasBeenLaunched(chaincode); ok {
		if !chrte.handler.registered {
			chaincodeSupport.runningChaincodes.Unlock()
			chaincodeLogger.Debugf("premature execution - chaincode (%s) is being launched", chaincode)
			err = fmt.Errorf("premature execution - chaincode (%s) is being launched", chaincode)
			return cID, cMsg, err
		}
		if chrte.handler.isRunning() {
			chaincodeLogger.Debugf("chaincode is running(no need to launch) : %s", chaincode)
			chaincodeSupport.runningChaincodes.Unlock()
			return cID, cMsg, nil
		}
		chaincodeLogger.Debugf("Container not in READY state(%s)...send init/ready", chrte.handler.FSM.Current())
	}
	chaincodeSupport.runningChaincodes.Unlock()

	var depTx *pb.Transaction

	//extract depTx so we can initialize hander.deployTXSecContext
	//we need it only after container is launched and only if this is not a deploy tx
	//NOTE: ideally this section should be moved before just before sendInitOrReady where
	//      where we need depTx.  However, as we don't check for ExecuteTransactions failure
	//      in consensus/helper, the following race is not resolved:
	//         1) deploy creates image
	//         2) query launches chaincode
	//         3) deploy returns "premature execution" error
	//         4) error ignored and deploy committed
	//         5) query successfully retrives committed tx and calls sendInitOrReady
	// See issue #710

	if t.Type != pb.Transaction_CHAINCODE_DEPLOY {
		if chaincodeSupport.userRunsCC {
			chaincodeLogger.Error("You are attempting to perform an action other than Deploy on Chaincode that is not ready and you are in developer mode. Did you forget to Deploy your chaincode?")
		}

		//PDMP - panic if not using simulator path
		_ = getTxSimulator(context)

		var depPayload []byte

		//hopefully we are restarting from existing image and the deployed transaction exists
		depPayload, err = GetCDSFromLCCC(context, string(DefaultChain), chaincode)
		if err != nil {
			return cID, cMsg, fmt.Errorf("Could not get deployment transaction from LCCC for %s - %s", chaincode, err)
		}
		if depPayload == nil {
			return cID, cMsg, fmt.Errorf("failed to get deployment payload %s - %s", chaincode, err)
		}

		//Get lang from original deployment
		err = proto.Unmarshal(depPayload, cds)
		if err != nil {
			return cID, cMsg, fmt.Errorf("failed to unmarshal deployment transactions for %s - %s", chaincode, err)
		}
		cLang = cds.ChaincodeSpec.Type
	}

	//from here on : if we launch the container and get an error, we need to stop the container

	//launch container if it is a System container or not in dev mode
	if (!chaincodeSupport.userRunsCC || cds.ExecEnv == pb.ChaincodeDeploymentSpec_SYSTEM) && (chrte == nil || chrte.handler == nil) {
		var targz io.Reader = bytes.NewBuffer(cds.CodePackage)
		_, err = chaincodeSupport.launchAndWaitForRegister(context, cds, cID, t.Txid, cLang, targz)
		if err != nil {
			chaincodeLogger.Errorf("launchAndWaitForRegister failed %s", err)
			return cID, cMsg, err
		}
	}

	if err == nil {
		//send init (if (args)) and wait for ready state
		err = chaincodeSupport.sendInitOrReady(context, t.Txid, chaincode, initargs, chaincodeSupport.ccStartupTimeout, t, depTx)
		if err != nil {
			chaincodeLogger.Errorf("sending init failed(%s)", err)
			err = fmt.Errorf("Failed to init chaincode(%s)", err)
			errIgnore := chaincodeSupport.Stop(context, cds)
			if errIgnore != nil {
				chaincodeLogger.Errorf("stop failed %s(%s)", errIgnore, err)
			}
		}
		chaincodeLogger.Debug("sending init completed")
	}

	chaincodeLogger.Debug("LaunchChaincode complete")

	return cID, cMsg, err
}

// getSecHelper returns the security help set from NewChaincodeSupport
func (chaincodeSupport *ChaincodeSupport) getSecHelper() crypto.Peer {
	return chaincodeSupport.secHelper
}

//getVMType - just returns a string for now. Another possibility is to use a factory method to
//return a VM executor
func (chaincodeSupport *ChaincodeSupport) getVMType(cds *pb.ChaincodeDeploymentSpec) (string, error) {
	if cds.ExecEnv == pb.ChaincodeDeploymentSpec_SYSTEM {
		return container.SYSTEM, nil
	}
	return container.DOCKER, nil
}

// Deploy deploys the chaincode if not in development mode where user is running the chaincode.
func (chaincodeSupport *ChaincodeSupport) Deploy(context context.Context, t *pb.Transaction) (*pb.ChaincodeDeploymentSpec, error) {
	//build the chaincode
	cds := &pb.ChaincodeDeploymentSpec{}
	err := proto.Unmarshal(t.Payload, cds)
	if err != nil {
		return nil, err
	}
	cID := cds.ChaincodeSpec.ChaincodeID
	cLang := cds.ChaincodeSpec.Type
	chaincode := cID.Name
	if err != nil {
		return cds, err
	}

	if chaincodeSupport.userRunsCC {
		chaincodeLogger.Debug("user runs chaincode, not deploying chaincode")
		return nil, nil
	}

	chaincodeSupport.runningChaincodes.Lock()
	//if its in the map, there must be a connected stream...and we are trying to build the code ?!
	if _, ok := chaincodeSupport.chaincodeHasBeenLaunched(chaincode); ok {
		chaincodeLogger.Debugf("deploy ?!! there's a chaincode with that name running: %s", chaincode)
		chaincodeSupport.runningChaincodes.Unlock()
		return cds, fmt.Errorf("deploy attempted but a chaincode with same name running %s", chaincode)
	}
	chaincodeSupport.runningChaincodes.Unlock()

	args, envs, err := chaincodeSupport.getArgsAndEnv(cID, cLang)
	if err != nil {
		return cds, fmt.Errorf("error getting args for chaincode %s", err)
	}

	var targz io.Reader = bytes.NewBuffer(cds.CodePackage)
	cir := &container.CreateImageReq{CCID: ccintf.CCID{ChaincodeSpec: cds.ChaincodeSpec, NetworkID: chaincodeSupport.peerNetworkID, PeerID: chaincodeSupport.peerID}, Args: args, Reader: targz, Env: envs}

	vmtype, _ := chaincodeSupport.getVMType(cds)

	chaincodeLogger.Debugf("deploying chaincode %s(networkid:%s,peerid:%s)", chaincode, chaincodeSupport.peerNetworkID, chaincodeSupport.peerID)

	//create image and create container
	resp, err2 := container.VMCProcess(context, vmtype, cir)
	if err2 != nil || (resp != nil && resp.(container.VMCResp).Err != nil) {
		err = fmt.Errorf("Error creating image: %s", err2)
	}

	return cds, err
}

// HandleChaincodeStream implements ccintf.HandleChaincodeStream for all vms to call with appropriate stream
func (chaincodeSupport *ChaincodeSupport) HandleChaincodeStream(ctxt context.Context, stream ccintf.ChaincodeStream) error {
	return HandleChaincodeStream(chaincodeSupport, ctxt, stream)
}

// Register the bidi stream entry point called by chaincode to register with the Peer.
func (chaincodeSupport *ChaincodeSupport) Register(stream pb.ChaincodeSupport_RegisterServer) error {
	return chaincodeSupport.HandleChaincodeStream(stream.Context(), stream)
}

// createTransactionMessage creates a transaction message.
func createTransactionMessage(txid string, cMsg *pb.ChaincodeInput) (*pb.ChaincodeMessage, error) {
	payload, err := proto.Marshal(cMsg)
	if err != nil {
		fmt.Printf(err.Error())
		return nil, err
	}
	return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_TRANSACTION, Payload: payload, Txid: txid}, nil
}

// createQueryMessage creates a query message.
func createQueryMessage(txid string, cMsg *pb.ChaincodeInput) (*pb.ChaincodeMessage, error) {
	payload, err := proto.Marshal(cMsg)
	if err != nil {
		return nil, err
	}
	return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY, Payload: payload, Txid: txid}, nil
}

// Execute executes a transaction and waits for it to complete until a timeout value.
func (chaincodeSupport *ChaincodeSupport) Execute(ctxt context.Context, chaincode string, msg *pb.ChaincodeMessage, timeout time.Duration, tx *pb.Transaction) (*pb.ChaincodeMessage, error) {
	chaincodeSupport.runningChaincodes.Lock()
	//we expect the chaincode to be running... sanity check
	chrte, ok := chaincodeSupport.chaincodeHasBeenLaunched(chaincode)
	if !ok {
		chaincodeSupport.runningChaincodes.Unlock()
		chaincodeLogger.Debugf("cannot execute-chaincode is not running: %s", chaincode)
		return nil, fmt.Errorf("Cannot execute transaction or query for %s", chaincode)
	}
	chaincodeSupport.runningChaincodes.Unlock()

	var notfy chan *pb.ChaincodeMessage
	var err error
	if notfy, err = chrte.handler.sendExecuteMessage(ctxt, msg, tx); err != nil {
		return nil, fmt.Errorf("Error sending %s: %s", msg.Type.String(), err)
	}
	var ccresp *pb.ChaincodeMessage
	select {
	case ccresp = <-notfy:
		//response is sent to user or calling chaincode. ChaincodeMessage_ERROR and ChaincodeMessage_QUERY_ERROR
		//are typically treated as error
	case <-time.After(timeout):
		err = fmt.Errorf("Timeout expired while executing transaction")
	}

	//our responsibility to delete transaction context if sendExecuteMessage succeeded
	chrte.handler.deleteTxContext(msg.Txid)

	return ccresp, err
}


text:
layout: post
title: Limes Romanum na Moravě!
---

Nic lepšího mě nenapadlo..

![_config.yml]({{ site.baseurl }}/images/config.png)


text:
package domain;

public class User {
   private String username;
   private String password;

   public User(String s, String n){
	   this.username = s;
	   this.password = n;
   }

   public String getUserName(){
	   return this.username;
   }

   public String getPwd(){
	   return this.password;
   }

   public void setUserName(String s){
	   this.username = s;
   }

   public void setPwd(String n){
	   this.password = n;
   }

   public String toString(){
	   return "Username: " + getUserName() + "; Password: " + getPwd() + ". ";
   }

   public boolean equal(User u){
	   return (this.username.equals(u.getUserName()) && this.password.equals(u.getPwd()));
   }

}


text:
class ElimincaodeGaus
{
    LinAlg::Matrix<double> X0;
    void PivotParcial(LingAlg::Matrix<double> &MatrizUni, int cols);
    double ads(double valor);

public:

    //Metodos para montar os sistema Linear de Gauss:
    ElimincaodeGaus();
    LinAlg::Matrix<double> Gauss(LinAlg::Matrix<double> MatrizUni);

    //Fatoração LU:
    Void LuFatorization(LinAlg::Matrix<double> Matriz, LinAlg::Matrix<double> &L, LinAlg::Matrix<double> &U);

    //Função Valores Iniciais do sistema:
    void setX0(LinAlg::Matrix<double> InicialStep)
    {
        this-> X0 = InicialStep;
    }

    //Criterio dos Metodos
    void CritLinhas(LinAlg::Matrix<double> MatrizUni);
    void CritSassenfeld(LinAlg::Matrix<double> MatrizUni);

};
#include "elimincaodegaus.hpp"
#endif // ELIMINCAODEGAUS_H


text:
package es.upv.i3m.grycap.im.pojo;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

import java.util.List;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class InfrastructureUris {

  private final List<InfrastructureUri> uris;

  public InfrastructureUris(
      @JsonProperty("uri-list") List<InfrastructureUri> uris) {
    this.uris = uris;
  }

  public List<InfrastructureUri> getUris() {
    return uris;
  }

  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this);
  }

  @Override
  public int hashCode() {
    return new HashCodeBuilder().append(uris).toHashCode();
  }

  @Override
  public boolean equals(Object other) {
    if (other == this) {
      return true;
    }
    if (other instanceof InfrastructureUris) {
      InfrastructureUris infUris = (InfrastructureUris) other;
      return new EqualsBuilder().append(uris, infUris.uris).isEquals();
    }
    return false;
  }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Optimize PDF Cloud API Example</title>

    <form name="form1" enctype="multipart/form-data" method="post" action="make-pdf-searchable.php">

            Input File (*.pdf)
            <input type="hidden" name="MAX_FILE_SIZE" value="8000000"/>
            <input type="file" name="file"/>

        <input type="submit" name="submit" value="Proceed" />
    </form>


text:
title:  I Pa' Ngiimnate
date:  10/08/2022
---

`Mikim in lam-etna lunggulh uhhi. Koiah i mu diam? Mi' nuihmaina peuhpan a ngah zong om thei hi. Adangkhat adingin sumlehpai, innkuanpih peuh tawh mu thei uh hi. Nang e leh koipan na lunggulh hiam?`

Jeremiah in, amite'n galmat hun sungteng lamet bei dikdek ahihna uh a laibu ah ciamteh hi. "Zion khuapi i ngaihsut khak ciangin, Baylon luite geiah tusuk in i kapkap hi" (Late 137:1). Amaute lungsimuh kitamkham phialmah le-uh, lamet a beinailohna thute Jeremiah in pulak hi.

`Jeremiah 29:1-10 sungah lametna'ng bang thu om hiam?`

Hihtengah lametna'ng a thupi thuthum hong kipia hi.

Amasa in, tua thupiangte in ama' thuthu in piang a, theihkholloh thupiang peuh hi lo ahih manin, Pasian in Amite beidonglo ding cihi. Pasian tektek mahin "Keimah in Jerusalem pan Babylon ah salmat in kong paipih hi" (Jer. 29:4) cihi. Siatna in amaute kimkot ah om mahleh Judah in Pasian' khutkuak nusia ngeilo hi.

Anihna ah, Amite haksat hun sung nangawnin Amah'n nasem thei veve ahih manin lungkia sak nuamlo hi. "Salin kong koihna khuapi phattuam nading bawl unla, tua khuapi adingin Topa' tungah thungetsak un. Tua khuapi in phattuamna ngah leh no zong phattuamna a ngahmah nahi uhhi." (Jer. 29:7).

Athumna ah, Pasian in a saltan hun beina omsak ding ahih manin, amaute a lungkiatloh nadingin "Topa'n hibangin cihi: 'Babylon ah kum sawmsagih sung na omkhit uh ciangin, note kong kan kik ding a, Kong thuciamsa hong tangtungsak in, hihmun ah kong lakik ding hi." (Jer. 29:10) cihi.

Pasian in amaute' hunbeisa teng a kemcingpa ahihlam a genkhit ciangin, tuhun zong leh mailam hun zong a kemcingpa ahihna zong gen a, Amite zong itna tawh hoihtak in kemcing ahihna zong gen hi (Jer. 29:11-14).

`Jeremiah 29:11-14 sim lecin, nang hong cihkhit ciangin namin sam in nang tungah kamciam hongpia dingin ngaihsun in. Tu laitak in bangzah haksatna thuakmah lecin, hih kamciamte koibangin na zangthei ding hiam?`


text:
package ch.uzh.ifi.attempto.acerules;

import java.util.Arrays;

import javax.servlet.http.Cookie;

import nextapp.echo2.app.ApplicationInstance;
import nextapp.echo2.webcontainer.ContainerContext;
import nextapp.echo2.webcontainer.command.BrowserSetCookieCommand;

public class SavedPrograms {

	private String[] names = new String[10];
	private String[] programs = new String[10];
	private int programCount = 0;

	public SavedPrograms() {
		ContainerContext cc = (ContainerContext) ApplicationInstance.getActive().getContextProperty(ContainerContext.CONTEXT_PROPERTY_NAME);
		Cookie[] cookies = cc.getCookies();
		for (Cookie c : cookies) {
			if (c.getName().startsWith("SavedProgram")) {
				String value = c.getValue().replace('&', '\n');
				if (value.length() == 0) continue;
				int nameIndex = value.indexOf("\n");
				if (nameIndex == -1) continue;
				if (programCount > 9) break;
				String name = value.substring(0, nameIndex);
				if (existsProgram(name)) continue;
				names[programCount] = name;
				programs[programCount] = value.substring(nameIndex + 1);
				programCount++;
			}
		}
		storeAllCookies();
	}

	public void addProgram(String name, String program) {
		if (isFull()) return;
		if (program.length() > 3950) return;
		if (getFreeSpace() < program.length()) return;
		String nameC = name.replace('&', ' ').replace('\n', ' ');
		if (existsProgram(nameC)) return;
		programs[programCount] = program;
		names[programCount] = nameC;
		storeCookie(programCount);
		programCount++;
	}

	public boolean isEmpty() {
		return programCount < 1;
	}

	public boolean isFull() {
		return programCount > 9;
	}

	public int getFreeSpace() {
		int fs = 7000;
		for (String p : programs) {
			if (p == null) continue;
			fs -= p.length();
		}
		return fs;
	}

	public boolean existsProgram(String name) {
		if (name == null) return false;
		String nameC = name.replace('&', ' ').replace('\n', ' ');
		for (String n : names) {
			if (nameC.equals(n)) return true;
		}
		return false;
	}

	public String getProgram(String name) {
		if (name == null) return "";
		for (int i=0 ; i<10 ; i++) {
			if (name.equals(names[i])) return programs[i];
		}
		return "";
	}

	public String[] getProgramNames() {
		String[] r = new String[programCount];
		for (int i=0 ; i<programCount ; i++) {
			r[i] = names[i];
		}
		Arrays.sort(r);
		return r;
	}

	public void deleteProgram(String name) {
		if (name == null) return;
		for (int i=0 ; i<programCount ; i++) {
			if (name.equals(names[i])) {
				for (int j=i+1 ; j<programCount ; j++) {
					names[j-1] = names[j];
					programs[j-1] = programs[j];
				}
				programCount--;
				names[programCount] = null;
				programs[programCount] = null;
				storeAllCookies();
				return;
			}
		}
	}

	private void storeCookie(int i) {
		String program = programs[i];
		String value = "";
		if (program != null && program.length() > 0) {
			value = names[i] + "&" + program.replace('\n', '&');
		}
		Cookie cookie = new Cookie("SavedProgram" + i, value);
		cookie.setMaxAge(1000000000);
		ApplicationInstance.getActive().enqueueCommand(new BrowserSetCookieCommand(cookie));
	}

	private void storeAllCookies() {
		for (int i=0 ; i<10 ; i++) {
			storeCookie(i);
		}
	}

}


text:
[![Coverage Status](https://coveralls.io/repos/jonkemp/gulp-qunit/badge.svg?branch=master&service=github)](https://coveralls.io/github/jonkemp/gulp-qunit?branch=master)

[![NPM](https://nodei.co/npm/gulp-qunit.png?downloads=true)](https://nodei.co/npm/gulp-qunit/)

> Run QUnit unit tests in a headless PhantomJS instance.

Run QUnit unit tests in a PhantomJS-powered headless test runner, providing basic console output for QUnit tests. Uses the [phantomjs](https://github.com/Medium/phantomjs) node module and the [PhantomJS Runner QUnit Plugin](https://github.com/jonkemp/qunit-phantomjs-runner).

Inspired by the grunt plugin [grunt-contrib-qunit](https://github.com/gruntjs/grunt-contrib-qunit).

![](screenshot.png)

## Install

Install with [npm](https://npmjs.org/package/gulp-qunit)

```bash
$ npm install --save-dev gulp-qunit
```

## Usage

```js
var gulp = require('gulp'),
    qunit = require('gulp-qunit');

gulp.task('test', function() {
    return gulp.src('./qunit/test-runner.html')
        .pipe(qunit());
});
```

With options:

```js
var gulp = require('gulp'),
    qunit = require('gulp-qunit');

gulp.task('test', function() {
    return gulp.src('./qunit/test-runner.html')
        .pipe(qunit({'phantomjs-options': ['--ssl-protocol=any']}));
});
```

With page options:

```js
var gulp = require('gulp'),
    qunit = require('gulp-qunit');

gulp.task('test', function() {
    return gulp.src('./qunit/test-runner.html')
        .pipe(qunit({'page': {
            viewportSize: { width: 1280, height: 800 }
        }}));
});
```

You no longer need this plugin to run QUnit tests in your gulp tasks. Now you can do this with [node-qunit-phantomjs](https://github.com/jonkemp/node-qunit-phantomjs), a stand alone module. It can also be used via command line, and it has an option for more verbose test reporting.
```js
var gulp = require('gulp'),
    qunit = require('node-qunit-phantomjs');

gulp.task('test', function() {
    qunit('./qunit/test-runner.html');
});
```

With phantomjs2:

```js
var gulp = require('gulp'),
    qunit = require('gulp-qunit');

gulp.task('test', function() {
    return gulp.src('./qunit/test-runner.html')
        .pipe(qunit({'binPath': require('phantomjs2').path}));
});
```

## API

### qunit(options)

#### options.timeout

Type: `Number`
Default: `5`

Pass a number or string value to override the default timeout of 5 seconds.

#### options.phantomjs-options

Type: `Array`
Default: `None`

These options are passed on to PhantomJS. See the [PhantomJS documentation](http://phantomjs.org/api/command-line.html) for more information.

#### options.page

Type: `Object`
Default: `None`

These options are passed on to PhantomJS. See the [PhantomJS documentation](http://phantomjs.org/page-automation.html) for more information.

#### options.binPath

Type: `String`
Default: require("phantomjs").path

The option is used to execute phantomjs binary path

## License

MIT © [Jonathan Kemp](http://jonkemp.com)