text:
function Base.summary(df::AbstractDataFrame) # -> UTF8String
    nrows, ncols = size(df)
    return utf8(@sprintf "%dx%d %s" nrows ncols typeof(df))
end

#' @description
#'
#' Determine the number of UTF8 characters that would be used to
#' render a value.
#'
#' @param x::Any A value whose string width will be computed.
#'
#' @returns w::Int The width of the string.
#'
#' @examples
#'
#' ourstrwidth("abc")
#' ourstrwidth(10000)
let
    local io = IOBuffer(Array(UInt8, 80), true, true)
    global ourstrwidth
    function ourstrwidth(x::Any) # -> Int
        truncate(io, 0)
        ourshowcompact(io, x)
        return position(io)
    end
    ourstrwidth(x::AbstractString) = strwidth(x) + 2 # -> Int
    myconv = VERSION < v"0.4-" ? convert : Base.unsafe_convert
    ourstrwidth(s::Symbol) =
        @compat Int(ccall(:u8_strwidth,
                          Csize_t,
                          (Ptr{UInt8}, ),
                          myconv(Ptr{UInt8}, s)))
end

#' @description
#'
#' Render a value to an IO object in a compact format. Unlike
#' Base.showcompact, we render strings without surrounding quote
#' marks.
#'
#' @param io::IO An IO object to be printed to.
#' @param x::Any A value to be printed.
#'
#' @returns x::Void A `nothing` value.
#'
#' @examples
#'
#' ourshowcompact(STDOUT, "abc")
#' ourshowcompact(STDOUT, 10000)
ourshowcompact(io::IO, x::Any) = showcompact(io, x) # -> Void
ourshowcompact(io::IO, x::AbstractString) = showcompact(io, x) # -> Void
ourshowcompact(io::IO, x::Symbol) = print(io, x) # -> Void

#' @description
#'
#' Calculates, for each column of an AbstractDataFrame, the maximum
#' string width used to render either the name of that column or the
#' longest entry in that column -- among the rows of the AbstractDataFrame
#' will be rendered to IO. The widths for all columns are returned as a
#' vector.
#'
#' NOTE: The last entry of the result vector is the string width of the
#'       implicit row ID column contained in every AbstractDataFrame.
#'
#' @param df::AbstractDataFrame The AbstractDataFrame whose columns will be
#'        printed.
#' @param rowindices1::AbstractVector{Int} A set of indices of the first
#'        chunk of the AbstractDataFrame that would be rendered to IO.
#' @param rowindices2::AbstractVector{Int} A set of indices of the second
#'        chunk of the AbstractDataFrame that would be rendered to IO. Can
#'        be empty if the AbstractDataFrame would be printed without any
#'        ellipses.
#' @param rowlabel::AbstractString The label that will be used when rendered the
#'        numeric ID's of each row. Typically, this will be set to "Row".
#'
#' @returns widths::Vector{Int} The maximum string widths required to render
#'          each column, including that column's name.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "yy", "z"])
#' maxwidths = getmaxwidths(df, 1:1, 3:3, :Row)
function getmaxwidths(df::AbstractDataFrame,
                      rowindices1::AbstractVector{Int},
                      rowindices2::AbstractVector{Int},
                      rowlabel::Symbol) # -> Vector{Int}
    maxwidths = Array(Int, size(df, 2) + 1)

    # TODO: Move this definition somewhere else
    NAstrwidth = 2
    undefstrwidth = ourstrwidth(Base.undef_ref_str)

    j = 1
    for (name, col) in eachcol(df)
        # (1) Consider length of column name
        maxwidth = ourstrwidth(name)

        # (2) Consider length of longest entry in that column
        for indices in (rowindices1, rowindices2)
            for i in indices
                if isna(col, i)
                    maxwidth = max(maxwidth, NAstrwidth)
                else
                    try
                        maxwidth = max(maxwidth, ourstrwidth(col[i]))
                    catch
                        maxwidth = max(maxwidth, undefstrwidth)
                    end
                end
            end
        end
        maxwidths[j] = maxwidth
        j += 1
    end

    rowmaxwidth1 = isempty(rowindices1) ? 0 : ndigits(maximum(rowindices1))
    rowmaxwidth2 = isempty(rowindices2) ? 0 : ndigits(maximum(rowindices2))

    maxwidths[j] = max(max(rowmaxwidth1, rowmaxwidth2), ourstrwidth(rowlabel))

    return maxwidths
end

#' @description
#'
#' Given the maximum widths required to render each column of an
#' AbstractDataFrame, this returns the total number of UTF8 characters
#' that would be required to render an entire row to an IO system.
#'
#' NOTE: This width includes the whitespace and special characters used to
#'       pretty print the AbstractDataFrame.
#'
#' @param maxwidths::Vector{Int} The maximum width needed to render each
#'        column of an AbstractDataFrame.
#'
#' @returns totalwidth::Int The total width required to render a complete row
#'          of the AbstractDataFrame for which `maxwidths` was computed.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "yy", "z"])
#' maxwidths = getmaxwidths(df, 1:1, 3:3, "Row")
#' totalwidth = getprintedwidth(maxwidths))
function getprintedwidth(maxwidths::Vector{Int}) # -> Int
    # Include length of line-initial |
    totalwidth = 1
    for i in 1:length(maxwidths)
        # Include length of field + 2 spaces + trailing |
        totalwidth += maxwidths[i] + 3
    end
    return totalwidth
end

#' @description
#'
#' When rendering an AbstractDataFrame to a REPL window in chunks, each of
#' which will fit within the width of the REPL window, this function will
#' return the indices of the columns that should be included in each chunk.
#'
#' NOTE: The resulting bounds should be interpreted as follows: the
#'       i-th chunk bound is the index MINUS 1 of the first column in the
#'       i-th chunk. The (i + 1)-th chunk bound is the EXACT index of the
#'       last column in the i-th chunk. For example, the bounds [0, 3, 5]
#'       imply that the first chunk contains columns 1-3 and the second chunk
#'       contains columns 4-5.
#'
#' @param maxwidths::Vector{Int} The maximum width needed to render each
#'        column of an AbstractDataFrame.
#' @param splitchunks::Bool Should the output be split into chunks at all or
#'        should only one chunk be constructed for the entire
#'        AbstractDataFrame?
#'
#' @returns chunkbounds::Vector{Int} The bounds of each chunk of columns.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "yy", "z"])
#' maxwidths = getmaxwidths(df, 1:1, 3:3, "Row")
#' chunkbounds = getchunkbounds(maxwidths, true)
function getchunkbounds(maxwidths::Vector{Int},
                        splitchunks::Bool) # -> Vector{Int}
    ncols = length(maxwidths) - 1
    rowmaxwidth = maxwidths[ncols + 1]
    _, availablewidth = Base.tty_size()
    if splitchunks
        chunkbounds = [0]
        # Include 2 spaces + 2 | characters for row/col label
        totalwidth = rowmaxwidth + 4
        for j in 1:ncols
            # Include 2 spaces + | character in per-column character count
            totalwidth += maxwidths[j] + 3
            if totalwidth > availablewidth
                push!(chunkbounds, j - 1)
                totalwidth = rowmaxwidth + 4 + maxwidths[j] + 3
            end
        end
        push!(chunkbounds, ncols)
    else
        chunkbounds = [0, ncols]
    end
    return chunkbounds
end

#' @description
#'
#' Render a subset of rows and columns of an AbstractDataFrame to an
#' IO system. For chunked printing, this function is used to print a
#' single chunk, starting from the first indicated column and ending with
#' the last indicated column. Assumes that the maximum string widths
#' required for printing have been precomputed.
#'
#' @param io::IO The IO system to which `df` will be printed.
#' @param df::AbstractDataFrame An AbstractDataFrame.
#' @param rowindices::AbstractVector{Int} The indices of the subset of rows
#'        that will be rendered to `io`.
#' @param maxwidths::Vector{Int} The pre-computed maximum string width
#'        required to render each column.
#' @param leftcol::Int The index of the first column in a chunk to be
#'        rendered.
#' @param rightcol::Int The index of the last column in a chunk to be
#'        rendered.
#'
#' @returns o::Void A `nothing` value.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "y", "z"])
#' showrowindices(STDOUT, df, 1:2, [1, 1, 5], 1, 2)
function showrowindices(io::IO,
                        df::AbstractDataFrame,
                        rowindices::AbstractVector{Int},
                        maxwidths::Vector{Int},
                        leftcol::Int,
                        rightcol::Int) # -> Void
    rowmaxwidth = maxwidths[end]

    for i in rowindices
        # Print row ID
        @printf io "| %d" i
        padding = rowmaxwidth - ndigits(i)
        for _ in 1:padding
            write(io, ' ')
        end
        print(io, " | ")
        # Print DataFrame entry
        for j in leftcol:rightcol
            strlen = 0
            try
                strlen = ourstrwidth(df[i, j])
                ourshowcompact(io, df[i, j])
            catch
                strlen = ourstrwidth(Base.undef_ref_str)
                ourshowcompact(io, Base.undef_ref_str)
            end
            padding = maxwidths[j] - strlen
            for _ in 1:padding
                write(io, ' ')
            end
            if j == rightcol
                if i == rowindices[end]
                    print(io, " |")
                else
                    print(io, " |\n")
                end
            else
                print(io, " | ")
            end
        end
    end
    return
end

#' @description
#'
#' Render a subset of rows (possibly in chunks) of an AbstractDataFrame to an
#' IO system. Users can control
#'
#' NOTE: The value of `maxwidths[end]` must be the string width of
#' `rowlabel`.
#'
#' @param io::IO The IO system to which `df` will be printed.
#' @param df::AbstractDataFrame An AbstractDataFrame.
#' @param rowindices1::AbstractVector{Int} The indices of the first subset
#'        of rows to be rendered.
#' @param rowindices2::AbstractVector{Int} The indices of the second subset
#'        of rows to be rendered. An ellipsis will be printed before
#'        rendering this second subset of rows.
#' @param maxwidths::Vector{Int} The pre-computed maximum string width
#'        required to render each column.
#' @param splitchunks::Bool Should the printing of the AbstractDataFrame
#'        be done in chunks? Defaults to `false`.
#' @param rowlabel::Symbol What label should be printed when rendering the
#'        numeric ID's of each row? Defaults to `"Row"`.
#' @param displaysummary::Bool Should a brief string summary of the
#'        AbstractDataFrame be rendered to the IO system before printing the
#'        contents of the renderable rows? Defaults to `true`.
#'
#' @returns o::Void A `nothing` value.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "y", "z"])
#' showrows(STDOUT, df, 1:2, 3:3, [1, 1, 5], false, :Row, true)
function showrows(io::IO,
                  df::AbstractDataFrame,
                  rowindices1::AbstractVector{Int},
                  rowindices2::AbstractVector{Int},
                  maxwidths::Vector{Int},
                  splitchunks::Bool = false,
                  rowlabel::Symbol = symbol("Row"),
                  displaysummary::Bool = true) # -> Void
    ncols = size(df, 2)

    if displaysummary
        println(io, summary(df))
    end

    if isempty(rowindices1)
        return
    end

    rowmaxwidth = maxwidths[ncols + 1]
    chunkbounds = getchunkbounds(maxwidths, splitchunks)
    nchunks = length(chunkbounds) - 1

    for chunkindex in 1:nchunks
        leftcol = chunkbounds[chunkindex] + 1
        rightcol = chunkbounds[chunkindex + 1]

        # Print column names
        @printf io "| %s" rowlabel
        padding = rowmaxwidth - ourstrwidth(rowlabel)
        for itr in 1:padding
            write(io, ' ')
        end
        @printf io " | "
        for j in leftcol:rightcol
            s = _names(df)[j]
            ourshowcompact(io, s)
            padding = maxwidths[j] - ourstrwidth(s)
            for itr in 1:padding
                write(io, ' ')
            end
            if j == rightcol
                print(io, " |\n")
            else
                print(io, " | ")
            end
        end

        # Print table bounding line
        write(io, '|')
        for itr in 1:(rowmaxwidth + 2)
            write(io, '-')
        end
        write(io, '|')
        for j in leftcol:rightcol
            for itr in 1:(maxwidths[j] + 2)
                write(io, '-')
            end
            write(io, '|')
        end
        write(io, '\n')

        # Print main table body, potentially in two abbreviated sections
        showrowindices(io,
                       df,
                       rowindices1,
                       maxwidths,
                       leftcol,
                       rightcol)

        if !isempty(rowindices2)
            print(io, "\n⋮\n")
            showrowindices(io,
                           df,
                           rowindices2,
                           maxwidths,
                           leftcol,
                           rightcol)
        end

        # Print newlines to separate chunks
        if chunkindex < nchunks
            print(io, "\n\n")
        end
    end

    return
end

#' @exported
#' @description
#'
#' Render an AbstractDataFrame to an IO system. The specific visual
#' representation chosen depends on the width of the REPL window
#' from which the call to `show` derives. If the DataFrame could not
#' be rendered without splitting the output into chunks, a summary of the
#' columns is rendered instead of rendering the raw data. This dynamic
#' response to screen width can be configured using the argument
#' `splitchunks`.
#'
#' @param io::IO The IO system to which `df` will be printed.
#' @param df::AbstractDataFrame An AbstractDataFrame.
#' @param splitchunks::Bool Should the printing of the AbstractDataFrame
#'        be done in chunks? Defaults to `false`.
#' @param rowlabel::Symbol What label should be printed when rendering the
#'        numeric ID's of each row? Defaults to `"Row"`.
#' @param displaysummary::Bool Should a brief string summary of the
#'        AbstractDataFrame be rendered to the IO system before printing the
#'        contents of the renderable rows? Defaults to `true`.
#'
#' @returns o::Void A `nothing` value.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "y", "z"])
#' show(STDOUT, df, false, :Row, true)
function Base.show(io::IO,
                   df::AbstractDataFrame,
                   splitchunks::Bool = true,
                   rowlabel::Symbol = symbol("Row"),
                   displaysummary::Bool = true) # -> Void
    nrows = size(df, 1)
    tty_rows, tty_cols = Base.tty_size()
    availableheight = tty_rows - 5
    nrowssubset = fld(availableheight, 2)
    bound = min(nrowssubset - 1, nrows)
    if nrows <= availableheight
        rowindices1 = 1:nrows
        rowindices2 = 1:0
    else
        rowindices1 = 1:bound
        rowindices2 = max(bound + 1, nrows - nrowssubset + 1):nrows
    end
    maxwidths = getmaxwidths(df, rowindices1, rowindices2, rowlabel)
    width = getprintedwidth(maxwidths)
    if width > tty_cols && !splitchunks
        showcols(io, df)
    else
        showrows(io,
                 df,
                 rowindices1,
                 rowindices2,
                 maxwidths,
                 splitchunks,
                 rowlabel,
                 displaysummary)
    end
    return
end

#' @exported
#' @description
#'
#' Render an AbstractDataFrame to STDOUT with or without chunking. See
#' other `show` documentation for details. This is mainly used to force
#' showing the AbstractDataFrame in chunks.
#'
#' @param df::AbstractDataFrame An AbstractDataFrame.
#' @param splitchunks::Bool Should the printing of the AbstractDataFrame
#'        be done in chunks? Defaults to `false`.
#'
#' @returns o::Void A `nothing` value.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "y", "z"])
#' show(df, true)
function Base.show(df::AbstractDataFrame,
                   splitchunks::Bool = true) # -> Void
    return show(STDOUT, df, splitchunks)
end

#' @exported
#' @description
#'
#' Render all of the rows of an AbstractDataFrame to an IO system. See
#' `show` documentation for details.
#'
#' @param io::IO The IO system to which `df` will be printed.
#' @param df::AbstractDataFrame An AbstractDataFrame.
#' @param splitchunks::Bool Should the printing of the AbstractDataFrame
#'        be done in chunks? Defaults to `false`.
#' @param rowlabel::Symbol What label should be printed when rendering the
#'        numeric ID's of each row? Defaults to `"Row"`.
#' @param displaysummary::Bool Should a brief string summary of the
#'        AbstractDataFrame be rendered to the IO system before printing the
#'        contents of the renderable rows? Defaults to `true`.
#'
#' @returns o::Void A `nothing` value.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "y", "z"])
#' showall(STDOUT, df, false, :Row, true)
function Base.showall(io::IO,
                      df::AbstractDataFrame,
                      splitchunks::Bool = false,
                      rowlabel::Symbol = symbol("Row"),
                      displaysummary::Bool = true) # -> Void
    rowindices1 = 1:size(df, 1)
    rowindices2 = 1:0
    maxwidths = getmaxwidths(df, rowindices1, rowindices2, rowlabel)
    width = getprintedwidth(maxwidths)
    showrows(io,
             df,
             rowindices1,
             rowindices2,
             maxwidths,
             splitchunks,
             rowlabel,
             displaysummary)
    return
end

#' @exported
#' @description
#'
#' Render all of the rows of an AbstractDataFrame to STDOUT. See
#' `showall` documentation for details.
#'
#' @param df::AbstractDataFrame An AbstractDataFrame.
#' @param splitchunks::Bool Should the printing of the AbstractDataFrame
#'        be done in chunks? Defaults to `false`.
#'
#' @returns o::Void A `nothing` value.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "y", "z"])
#' showall(df, true)
function Base.showall(df::AbstractDataFrame,
                      splitchunks::Bool = false) # -> Void
    showall(STDOUT, df, splitchunks)
    return
end

#' @description
#'
#' Render a summary of the column names, column types and column missingness
#' count.
#'
#' @param io::IO The `io` to be rendered to.
#' @param df::AbstractDataFrame An AbstractDataFrame.
#'
#' @returns o::Void A `nothing` value.
#'
#' @examples
#'
#' df = DataFrame(A = 1:3, B = ["x", "y", "z"])
#' showcols(df, true)
function showcols(io::IO, df::AbstractDataFrame) # -> Void
    println(io, summary(df))
    metadata = DataFrame(Name = _names(df),
                         Eltype = eltypes(df),
                         Missing = colmissing(df))
    showall(io, metadata, true, symbol("Col #"), false)
    return
end

showcols(df::AbstractDataFrame) = showcols(STDOUT, df) # -> Void


text:
package com.socrata.pg.server.config

import com.typesafe.config.Config
import com.socrata.http.server.livenesscheck.LivenessCheckConfig
import com.socrata.pg.config.{StoreConfig}
import com.socrata.curator.{CuratorConfig, DiscoveryConfig}
import com.socrata.thirdparty.metrics.MetricsOptions
import com.socrata.thirdparty.typesafeconfig.ConfigClass

class QueryServerConfig(val config: Config, val root: String) extends ConfigClass(config, root) {
  val log4j = getRawConfig("log4j")
  val store = new StoreConfig(config, path("store"))
  val port = getInt("port")
  val curator = new CuratorConfig(config, path("curator"))
  val discovery = new DiscoveryConfig(config, path("service-advertisement"))
  val livenessCheck = new LivenessCheckConfig(config, path("liveness-check"))
  val metrics = MetricsOptions(config.getConfig(path("metrics")))
  val instance = getString("instance")
  val threadpool = getRawConfig("threadpool")
  val maxConcurrentRequestsPerDataset = getInt("max-concurrent-requests-per-dataset")
  val leadingSearch = getBoolean("leading-search")
  val httpQueryTimeoutDelta = getDuration("http-query-timeout-delta")
}

redpajama_set_name: RedPajamaGithub


text:
using Newtonsoft.Json.Schema;

namespace Google.Apis.Discovery.Schema
{
    /// <summary>
    /// Represents one child of the schema node in the discovery document.
    /// This represents one top level DataTransferOjbect which will form
    /// part of the request or response to the service.
    /// </summary>
    public interface ISchema
    {
        /// <summary>
        /// The name of this schema
        /// </summary>
        string Name { get; }

        /// <summary>
        /// The ID of this schema
        /// </summary>
        string Id { get; }

        /// <summary>
        /// The inner details of this schema
        /// </summary>
        JsonSchema SchemaDetails { get; }
    }
}


text:
from typing import Optional

import dask.array as da
import numpy as np
import sklearn.metrics
from dask import is_dask_collection
from dask.utils import derived_from

from .._typing import ArrayLike

def _check_sample_weight(sample_weight: Optional[ArrayLike]):
    if sample_weight is not None:
        raise ValueError("'sample_weight' is not supported.")

def _check_reg_targets(
    y_true: ArrayLike, y_pred: ArrayLike, multioutput: Optional[str]
):
    if multioutput is not None and (
        is_dask_collection(multioutput) or multioutput != "uniform_average"
    ):
        raise NotImplementedError("'multioutput' must be 'uniform_average'")

    if y_true.ndim == 1:
        y_true = y_true.reshape((-1, 1))
    if y_pred.ndim == 1:
        y_pred = y_pred.reshape((-1, 1))

    # TODO: y_type, multioutput
    return None, y_true, y_pred, multioutput

@derived_from(sklearn.metrics)
def mean_squared_error(
    y_true: ArrayLike,
    y_pred: ArrayLike,
    sample_weight: Optional[ArrayLike] = None,
    multioutput: Optional[str] = "uniform_average",
    squared: bool = True,
    compute: bool = True,
) -> ArrayLike:
    _check_sample_weight(sample_weight)
    output_errors = ((y_pred - y_true) ** 2).mean(axis=0)

    if isinstance(multioutput, str) or multioutput is None:
        if multioutput == "raw_values":
            if compute:
                return output_errors.compute()
            else:
                return output_errors
    else:
        raise ValueError("Weighted 'multioutput' not supported.")
    result = output_errors.mean()
    if not squared:
        result = da.sqrt(result)
    if compute:
        result = result.compute()
    return result

@derived_from(sklearn.metrics)
def mean_absolute_error(
    y_true: ArrayLike,
    y_pred: ArrayLike,
    sample_weight: Optional[ArrayLike] = None,
    multioutput: Optional[str] = "uniform_average",
    compute: bool = True,
) -> ArrayLike:
    _check_sample_weight(sample_weight)
    output_errors = abs(y_pred - y_true).mean(axis=0)

    if isinstance(multioutput, str) or multioutput is None:
        if multioutput == "raw_values":
            if compute:
                return output_errors.compute()
            else:
                return output_errors
    else:
        raise ValueError("Weighted 'multioutput' not supported.")
    result = output_errors.mean()
    if compute:
        result = result.compute()
    return result

def mean_absolute_percentage_error(
    y_true: ArrayLike,
    y_pred: ArrayLike,
    sample_weight: Optional[ArrayLike] = None,
    multioutput: Optional[str] = "uniform_average",
    compute: bool = True,
) -> ArrayLike:
    """Mean absolute percentage error regression loss.

    Note here that we do not represent the output as a percentage in range
    [0, 100]. Instead, we represent it in range [0, 1/eps]. Read more in
    https://scikit-learn.org/stable/modules/model_evaluation.html#mean-absolute-percentage-error

    Parameters
    ----------
    y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput : {'raw_values', 'uniform_average'} or array-like
        Defines aggregating of multiple output values.
        Array-like value defines weights used to average errors.
        If input is list then the shape must be (n_outputs,).
        'raw_values' :
            Returns a full set of errors in case of multioutput input.
        'uniform_average' :
            Errors of all outputs are averaged with uniform weight.
    compute : bool
        Whether to compute this result (default ``True``)

    Returns
    -------
    loss : float or array-like of floats in the range [0, 1/eps]
        If multioutput is 'raw_values', then mean absolute percentage error
        is returned for each output separately.
        If multioutput is 'uniform_average' or ``None``, then the
        equally-weighted average of all output errors is returned.
        MAPE output is non-negative floating point. The best value is 0.0.
        But note the fact that bad predictions can lead to arbitarily large
        MAPE values, especially if some y_true values are very close to zero.
        Note that we return a large value instead of `inf` when y_true is zero.
    """
    _check_sample_weight(sample_weight)
    epsilon = np.finfo(np.float64).eps
    mape = abs(y_pred - y_true) / da.maximum(y_true, epsilon)
    output_errors = mape.mean(axis=0)

    if isinstance(multioutput, str) or multioutput is None:
        if multioutput == "raw_values":
            if compute:
                return output_errors.compute()
            else:
                return output_errors
    else:
        raise ValueError("Weighted 'multioutput' not supported.")
    result = output_errors.mean()
    if compute:
        result = result.compute()
    return result

@derived_from(sklearn.metrics)
def r2_score(
    y_true: ArrayLike,
    y_pred: ArrayLike,
    sample_weight: Optional[ArrayLike] = None,
    multioutput: Optional[str] = "uniform_average",
    compute: bool = True,
) -> ArrayLike:
    _check_sample_weight(sample_weight)
    _, y_true, y_pred, _ = _check_reg_targets(y_true, y_pred, multioutput)
    weight = 1.0

    numerator = (weight * (y_true - y_pred) ** 2).sum(axis=0, dtype="f8")
    denominator = (weight * (y_true - y_true.mean(axis=0)) ** 2).sum(axis=0, dtype="f8")

    nonzero_denominator = denominator != 0
    nonzero_numerator = numerator != 0
    valid_score = nonzero_denominator & nonzero_numerator
    output_chunks = getattr(y_true, "chunks", [None, None])[1]
    output_scores = da.ones([y_true.shape[1]], chunks=output_chunks)
    with np.errstate(all="ignore"):
        output_scores[valid_score] = 1 - (
            numerator[valid_score] / denominator[valid_score]
        )
        output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0

    result = output_scores.mean(axis=0)
    if compute:
        result = result.compute()
    return result

@derived_from(sklearn.metrics)
def mean_squared_log_error(
    y_true: ArrayLike,
    y_pred: ArrayLike,
    sample_weight: Optional[ArrayLike] = None,
    multioutput: Optional[str] = "uniform_average",
    compute: bool = True,
) -> ArrayLike:

    result = mean_squared_error(
        np.log1p(y_true),
        np.log1p(y_pred),
        sample_weight=sample_weight,
        multioutput=multioutput,
        compute=compute,
    )
    return result


text:
package de.cosmocode.palava.cache;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.google.inject.BindingAnnotation;

/**
 * A binding annotation for the backing {@link CacheService} of a
 * {@link BackedComputingCacheService}.
 *
 * @since 2.4
 * @author Willi Schoenborn
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({
    ElementType.PARAMETER,
    ElementType.METHOD
})
@BindingAnnotation
@interface Backing {

}


text:
/** @file CHUNKS.h
 * @brief Provides functionality to create and use Chunks.
 */

 #ifndef CHUNKS_H_
 #define CHUNKS_H_

#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

/** Create and use Chunks.
 * A Chunk is an array of bytes (uint8_t). The first field contains the amount of bytes this array is long.
 * When processing an array by its reference, it is known how many bytes this array takes.
 *
 * Any type can be stored as a chunk (as long it is not bigger than 255 bytes).
 */
class ChunkClass {
public:
	/** Create a Chunk from a reference.
	 *@tparam The type of data that should be put into this chunk
	 *@param  data A reference to the data that should be stored in this chunk
	 *@param  length An optional Argument. Needs to be set if the Reference points to an array.
	 */
	template<class T> static uint8_t* create(T* data, uint8_t length = 1) {
		return createFromPointer<T>((data), (length * sizeof(T)));
	}
	/** Create a Chunk from a value.
	 *@tparam The type of the Value that should be put into this chunk
	 *@param  data The Value that should be stored in this chunk
	 *@param  length An optional Argument. Needs to be set if the Value is an array.
	 */
	template<class T> static uint8_t* create(T value, uint8_t length = 1) {
		return createFromPointer<T>(&value, sizeof(T));
	}

	/**
	 * @param chunk The chunk which length should be returned.
	 * @return The amount of elements of an array stored in this chunk.
	 */
	template<class T> static uint8_t length(uint8_t* chunk) {
		return chunk[0] / sizeof(T);
	}

	/**
	 * @param chunk The chunk which size should be returned.
	 * @return The amount of bytes stored in this chunk.
	 * @note The chunk takes up one byte more in memory.
	 */
	static uint8_t size(uint8_t* chunk) {
		return chunk[0];
	}

	/**
	 * @param chunk The chunk to use.
	 * @tparam The type of the data that is stored in the given chunk.
	 * @return A pointer to the data stored in this chunk
	 */
	template<class T> static T* getPointer(uint8_t* chunk) {
		return (T*) (chunk + 1);
	}

	/**
	 * @param chunk The chunk to use.
	 * @tparam The type of the value that is stored in the given chunk.
	 * @return The Value that is stored in the given chunk.
	 */
	template<class T> static T getValue(uint8_t* chunk) {
		return *(getPointer<T>(chunk));
	}

#ifdef CHUNKS_PRINT
	/** Prints the given chunk.
	 * @param chunk The chunk to print.
	 * @note #CHUNKS_PRINT needs to be defined in order to use this function.
	 */
	static void printChunk(uint8_t* chunk) {
		DBG("(");DBG(int(chunk[0]));DBG(")\t");
		DBG("[ ");
		for (int i = 1; i <= chunk[0]; i++) {
			DBG(int(chunk[i]));DBG(" ");
		}
		DBG("]");
	}
#endif

private:
	/** Creates a chunk from the given pointer.
	 *
	 */
	template<class T> static uint8_t* createFromPointer(T* data,
			uint8_t length) {
		uint8_t* in = (uint8_t*) data;
		uint8_t* chunk = new uint8_t[length + 1];
		chunk[0] = length;
		for (uint8_t i = 0; i < length; i++) {
			chunk[i + 1] = in[i];
		}
		return chunk;
	}

};

extern ChunkClass CHUNKS;

#endif /* CHUNKS_H_ */


text:
extern "C"
{
	#include <lua-5.1/src/lua.h>
	#include <lua-5.1/src/lualib.h>
	#include <lua-5.1/src/lauxlib.h>
}
#include <luabind/luabind.hpp>

#include <levels/Level1.h>
#include <lua-exports/ExportBox2d.h>
#include <lua-exports/B2WorldProxy.h>
#include <utilities/Bitwise.h>
#include <SFML/System.hpp>
#include <components/IgnoreCollisionComponent.h>
#include <components/PhysicsComponent.h>
#include <iostream>
#include <tmx/MapLoader.h>
#include <tmx/tmx2box2d.h>
#include <lua-exports/ExportSFML.h>

class LuaScriptLevel::LuaScriptLevelImpl {

public:
	lua_State* m_luaState;
	B2WorldProxy box2dWorldProxy;
	std::vector<b2Fixture*> m_fixturesInterestedInCollisions;
	bool shouldCallScript = false;

	LuaScriptLevelImpl(b2World& b2dworld, std::string levelScriptName) : box2dWorldProxy(b2dworld) {
		m_luaState = luaL_newstate();
		luabind::open(m_luaState);
		luaL_openlibs(m_luaState);

		if(!levelScriptName.empty()){
			shouldCallScript = true;

			std::string scriptPath = "lua-scripts/levels/" + levelScriptName;
			if (luaL_dofile(m_luaState, scriptPath.c_str())) {
				printf("%s\n", lua_tostring(m_luaState, -1));
			}

			ExportBox2d exportBox2d;
			exportBox2d.exportToLua(m_luaState);

			ExportSFML exportSFML;
			exportSFML.exportToLua(m_luaState);
		}

	}

	~LuaScriptLevelImpl() {

		lua_close(m_luaState);
		std::cout << "deleted lua state" << std::endl;
	}

	void loadLevel(std::unordered_map<std::string, tmx::MapObject>& levelObjects) {

		if(!shouldCallScript)
			return;

		std::cout << "loadlelve in c++" << std::endl;

		try {
			luabind::call_function<void>(m_luaState, "init", &box2dWorldProxy);
		} catch (luabind::error& e) {
			std::string error = lua_tostring(e.state(), -1);
			std::cout << error << std::endl;
		}

		for(auto iterator = levelObjects.begin(); iterator != levelObjects.end(); iterator++) {
			std::string name = iterator->first;
			tmx::MapObject mapObject = iterator->second;
			try {
				luabind::call_function<void>(m_luaState, "loadMapObject", name,  mapObject);
			} catch (luabind::error& e) {
				std::string error = lua_tostring(e.state(), -1);
				std::cout << error << std::endl;
			}
		}

		try {
			luabind::object levels =  luabind::call_function<luabind::object>(m_luaState, "getFixturesInterestedInCollisions");
			for(int i = 1; ; i++){
				if(levels[i]){
					b2Fixture* collisionFixture =  luabind::object_cast<b2Fixture*>(levels[i]);
				    m_fixturesInterestedInCollisions.push_back(collisionFixture);

				}else{
					break;
				}
			}
		} catch (luabind::error& e) {
		    std::string error = lua_tostring(e.state(), -1);
		    std::cout << error << std::endl;
		}
	}

	void updateLevel() {
		if(!shouldCallScript)
			return;

		try {
			luabind::call_function<void>(m_luaState, "update");
		} catch (luabind::error& e) {
			std::string error = lua_tostring(e.state(), -1);
			std::cout << error << std::endl;
		}
	}

	void endLevel() {
		lua_close(m_luaState);
	}

	bool shouldIgnore(b2Contact* contact){
//		anax::World::EntityArray entities = m_anaxWorld.getEntities();
//		for(auto entity : entities){
//			if(entity.isValid() && entity.hasComponent<PhysicsComponent>() && entity.hasComponent<IgnoreCollisionComponent>()){
//				auto& physicsComp = entity.getComponent<PhysicsComponent>();
//				b2Fixture* fixtureToCompare = physicsComp.physicsBody->GetFixtureList();
//				while(fixtureToCompare){
//					if(fixtureToCompare == contact->GetFixtureA() || fixtureToCompare == contact->GetFixtureB()){
//						return true;
//					}
//					fixtureToCompare = fixtureToCompare->GetNext();
//				}
//			}
//		}
		return false;
	}

	void filterContacts(b2Contact* contact,  const char* luaScriptFunctionName){
		if(!shouldCallScript)
			return;

			for (auto fixture : m_fixturesInterestedInCollisions) {
				if (fixture == contact->GetFixtureA() || fixture == contact->GetFixtureB()) {
					try {
						luabind::call_function<void>(m_luaState,
								luaScriptFunctionName, contact);
					} catch (luabind::error& e) {
						std::string error = lua_tostring(e.state(), -1);
						std::cout << error << std::endl;
					}
				}
			}
	}

	void beginContact(b2Contact* contact) {
		//filterContacts(contact, "beginCollision");
	}

	void endContact(b2Contact* contact) {
	//	filterContacts(contact, "endCollision");
	}

};

LuaScriptLevel::LuaScriptLevel(b2World& b2dworld, std::string luaScriptLevel) :
		m_impl(new LuaScriptLevelImpl(b2dworld, luaScriptLevel)) {
}

LuaScriptLevel::~LuaScriptLevel() {
}

void LuaScriptLevel::loadLevel(std::unordered_map<std::string, tmx::MapObject>& levelObjects) {
	m_impl->loadLevel(levelObjects);
}

void LuaScriptLevel::updateLevel() {
	m_impl->updateLevel();
}

void LuaScriptLevel::endLevel() {
	m_impl->endLevel();
}

void LuaScriptLevel::BeginContact(b2Contact* contact) {
	m_impl->beginContact(contact);
}

void LuaScriptLevel::EndContact(b2Contact* contact) {
	m_impl->endContact(contact);
}


text:
require 'spec_helper'
require 'puppet'
require 'puppet/type/keystone_user_role'

describe Puppet::Type.type(:keystone_user_role) do

  before :each do
    @user_roles = Puppet::Type.type(:keystone_user_role).new(
    :name => 'foo@bar',
    :roles => ['a', 'b']
    )

    @roles = @user_roles.parameter('roles')
  end

  it 'should not be in sync for' do
    expect(@roles.insync?(['a', 'b', 'c'])).to be false
    expect(@roles.insync?('a')).to be false
    expect(@roles.insync?(['a'])).to be false
    expect(@roles.insync?(nil)).to be false
  end

  it 'should be in sync for' do
    expect(@roles.insync?(['a', 'b'])).to be true
    expect(@roles.insync?(['b', 'a'])).to be true
  end

end


text:
import os
import sys

BASE_APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(os.path.join(BASE_APP_DIR, 'src/'))
sys.path.append(os.path.join(BASE_APP_DIR, 'venv/lib/python3.4/site-packages'))

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


text:
<bill session="111" type="h" number="370" updated="2009-03-07T10:31:00-05:00">
	<status><introduced date="1231477200" datetime="2009-01-09"/></status>

	<introduced date="1231477200" datetime="2009-01-09"/>
	<titles>
		<title type="short" as="introduced">Foreign Service Overseas Pay Equity Act of 2009</title>
		<title type="official" as="introduced">To amend the Foreign Service Act of 1980 to extend comparability pay adjustments to members of the Foreign Service assigned to posts abroad, and to amend the provision relating to the death gratuity payable to surviving dependents of Foreign Service employees who die as a result of injuries sustained in the performance of duty abroad.</title>
	</titles>
	<sponsor id="400380"/>
	<cosponsors>
		<cosponsor id="400263" joined="2009-02-24"/>
		<cosponsor id="412268" joined="2009-02-24"/>
		<cosponsor id="400283" joined="2009-02-23"/>
		<cosponsor id="400363" joined="2009-03-03"/>
		<cosponsor id="400312" joined="2009-01-09"/>
	</cosponsors>
	<actions>
		<action date="1231477200" datetime="2009-01-09"><text>Referred to the Committee on Foreign Affairs, and in addition to the Committee on Oversight and Government Reform, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text></action>
		<action date="1231477200" datetime="2009-01-09"><text>Referred to House Foreign Affairs</text></action>
		<action date="1231477200" datetime="2009-01-09"><text>Referred to House Oversight and Government Reform</text></action>
	</actions>
	<committees>
		<committee name="House Foreign Affairs" subcommittee="" activity="Referral, In Committee" />
		<committee name="House Oversight and Government Reform" subcommittee="" activity="Referral, In Committee" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>
		<term name="International affairs"/>
		<term name="Diplomacy, foreign officials, Americans abroad"/>
		<term name="Government employee pay, benefits, personnel management"/>
	</subjects>
	<amendments>

	</amendments>

	1/9/2009--Introduced.
Foreign Service Overseas Pay Equity Act of 2009 - Amends the Foreign Service Act of 1980 to: (1) extend comparability pay adjustments to Foreign Service members assigned abroad; and (2) amend the death gratuity computation payable to surviving dependents of Foreign Service employees who die from injuries sustained in the performance of duty abroad.

</bill>


text:
// Apache-2:
// https://github.com/MatejTymes/JavaFixes/blob/37e74b9d0a29f7a47485c6d1bb1307f01fb93634/LICENSE
package io.sentry.transport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import org.jetbrains.annotations.NotNull;

/**
 * Class originally copied from ReusableCountLatch.java.
 *
 *
A synchronization aid that allows one or more threads to wait until a set of operations being
 * performed in other threads completes.
 *
 *
A {@code ReusableCountLatch} is initialized with a given count. The {@link
 * #waitTillZero} methods block until the current count reaches zero due to invocations of the
 * {@link #decrement} method, after which all waiting threads are released. If zero has been reached
 * any subsequent invocations of {@link #waitTillZero} return immediately. The coun cen be increased
 * calling the {@link #increment()} method and any subsequent thread calling the {@link
 * #waitTillZero} method will be block again until another zero is reached.
 *
 *
{@code ReusableCountLatch} provides more versatility than {@link
 * java.util.concurrent.CountDownLatch CountDownLatch} as the count doesn't have to be known upfront
 * and you can reuse this class as many times as you want to. It is also better than a {@link
 * java.util.concurrent.Phaser Phaser} whose count is limited to 65_535. {@code ReusableCountLatch}
 * instead can count up to 2_147_483_647 (2^31-1).
 *
 *
Great use case for {@code ReusableCountLatch} is when you wait for tasks on other threads to
 * finish, but these tasks could trigger more tasks and it is not know upfront how many will be
 * triggered in total.
 *
 * @author mtymes
 * @since 07/10/16 00:10 AM
 */
public final class ReusableCountLatch {

  private final @NotNull Sync sync;

  /**
   * Constructs a {@code ReusableCountLatch} initialized with the given count.
   *
   * @param initialCount the number of times {@link #decrement} must be invoked before threads can
   *     pass through {@link #waitTillZero}. For each additional call of the {@link #increment}
   *     method one more {@link #decrement} must be called.
   * @throws IllegalArgumentException if {@code initialCount} is negative
   */
  public ReusableCountLatch(final int initialCount) {
    if (initialCount < 0) {
      throw new IllegalArgumentException(
          "negative initial count '" + initialCount + "' is not allowed");
    }
    this.sync = new Sync(initialCount);
  }

  /** Constructs a {@code ReusableCountLatch} with initial count set to 0. */
  public ReusableCountLatch() {
    this(0);
  }

  /**
   * Returns the current count.
   *
   * @return the current count
   */
  public int getCount() {
    return sync.getCount();
  }

  /**
   * Decrements the count of the latch, releasing all waiting threads if the count reaches zero.
   *
   *
If the current count is greater than zero then it is decremented. If the new count is zero
   * then all waiting threads are re-enabled for thread scheduling purposes.
   *
   *
If the current count equals zero then nothing happens.
   */
  public void decrement() {
    sync.decrement();
  }

  /**
   * Increments the count of the latch, which will make it possible to block all threads waiting
   * till count reaches zero.
   */
  public void increment() {
    sync.increment();
  }

  /**
   * Causes the current thread to wait until the latch has counted down to zero, unless the thread
   * is {@linkplain Thread#interrupt interrupted}.
   *
   *
If the current count is zero then this method returns immediately.
   *
   *
If the current count is greater than zero then the current thread becomes disabled for
   * thread scheduling purposes and lies dormant until one of two things happen:
   *
   *

   *
The count reaches zero due to invocations of the {@link #decrement} method; or
   *
Some other thread {@linkplain Thread#interrupt interrupts} the current thread.
   *

   *
   *
If the current thread:
   *
   *

   *
has its interrupted status set on entry to this method; or
   *
is {@linkplain Thread#interrupt interrupted} while waiting,
   *

   *
   * then {@link InterruptedException} is thrown and the current thread's interrupted status is
   * cleared.
   *
   * @throws InterruptedException if the current thread is interrupted while waiting
   */
  public void waitTillZero() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
  }

  /**
   * Causes the current thread to wait until the latch has counted down to zero, unless the thread
   * is {@linkplain Thread#interrupt interrupted}, or the specified waiting time elapses.
   *
   *
If the current count is zero then this method returns immediately with the value {@code
   * true}.
   *
   *
If the current count is greater than zero then the current thread becomes disabled for
   * thread scheduling purposes and lies dormant until one of three things happen:
   *
   *

   *
The count reaches zero due to invocations of the {@link #decrement()} method; or
   *
Some other thread {@linkplain Thread#interrupt interrupts} the current thread; or
   *
The specified waiting time elapses.
   *

   *
   *
If the count reaches zero then the method returns with the value {@code true}.
   *
   *
If the current thread:
   *
   *

   *
has its interrupted status set on entry to this method; or
   *
is {@linkplain Thread#interrupt interrupted} while waiting,
   *

   *
   * then {@link InterruptedException} is thrown and the current thread's interrupted status is
   * cleared.
   *
   *
If the specified waiting time elapses then the value {@code false} is returned. If the time
   * is less than or equal to zero, the method will not wait at all.
   *
   * @param timeout the maximum time to wait
   * @param unit the time unit of the {@code timeout} argument
   * @return {@code true} if the count reached zero and {@code false} if the waiting time elapsed
   *     before the count reached zero
   * @throws InterruptedException if the current thread is interrupted while waiting
   */
  public boolean waitTillZero(final long timeout, final @NotNull TimeUnit unit)
      throws InterruptedException {
    return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
  }

  /** Synchronization control For ReusableCountLatch. Uses AQS state to represent count. */
  private static final class Sync extends AbstractQueuedSynchronizer {
    private static final long serialVersionUID = 5970133580157457018L;

    Sync(final int count) {
      setState(count);
    }

    private int getCount() {
      return getState();
    }

    private void increment() {
      for (; ; ) {
        int oldCount = getState();
        int newCount = oldCount + 1;
        if (compareAndSetState(oldCount, newCount)) {
          return;
        }
      }
    }

    private void decrement() {
      releaseShared(1);
    }

    @Override
    public int tryAcquireShared(final int acquires) {
      return (getState() == 0) ? 1 : -1;
    }

    @Override
    public boolean tryReleaseShared(final int releases) {
      // Decrement count; signal when transition to zero
      for (; ; ) {
        int oldCount = getState();
        if (oldCount == 0) {
          return false;
        }
        int newCount = oldCount - 1;
        if (compareAndSetState(oldCount, newCount)) {
          return newCount == 0;
        }
      }
    }
  }
}


text:
Custer is full of holes.

A super simple web server. Someday it will mostly support HTTP 1.1.

## Usage

    lein deps

    bin/custer.sh

Visit `http://localhost:8080` for an echo.


text:
package uk.co.manifesto.wcs.mvc.controller;

import COM.FutureTense.Interfaces.ICS;

public interface Controller {

    Model handleRequest(ICS ics);

}


text:
<?php

namespace App\Http\Controllers;

use App\Domain\Repositories\CarsRepository;

/**
 * Class PageController
 *
 * @package App\Http\Controllers
 */
class PageController extends Controller
{
    /**
     * Create new instance PageController
     */

    /**
     * Show page login
     *
     * @return \Illuminate\View\View
     */
    public function __construct(CarsRepository $cars)
    {
        $this->middleware('guest', ['only' => [ 'getLogin', 'signup']]);
        $this->cars = $cars;
    }

    public function landingpage()
    {
        return view('landingpage');

//        $getlist = $this->jurusan->getList();
//         dump($getlist);
//        return view('landingpage')->with([
//            'getlist' => $getlist
//        ]);

    }

    /**
     * @return string
     */
    public function token()
    {
        return csrf_token();
    }

    public function signup()
    {
        return view('signup');

    }
    public function cars()
    {

        $getlist = $this->cars->getList();
//         dump($getlist);
        return view('cars-list')->with([
            'getlistsedan' => $getlist
        ]);

    }

    public function getLogin()
    {
        return view('login');
    }

    public function pendaftaran()
    {
        return view('welcome');

    }
    public function backoffice()
    {
        return view('welcome');

    }

    public function confirm($confirmation_code)
    {
        $users = \DB::table('users')
            ->where('confirmation_code', $confirmation_code)
            ->count();

        if ($users == 0) {
            session()->flash('auth_message', 'maaf user konfirmasi email tidak berlaku lagi');
            return redirect()->route('login');

        } else {
            $user = \DB::table('users')
                ->where('confirmation_code', $confirmation_code)
                ->first();
            $userupdate = User::find($user->id);

            $userupdate->is_aktif = 1;
            $userupdate->confirmation_code = 0;
            $userupdate->save();
            session()->flash('auth_messagee', 'User berhasil dikonfirmasi ');
            return redirect()->route('login');

        }
    }

}


text:
package org.eclipse.jetty.client;

public class SelectConnectionTest extends AbstractConnectionTest
{
    protected HttpClient newHttpClient()
    {
        HttpClient httpClient = new HttpClient();
        httpClient.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
        httpClient.setConnectBlocking(true);
        return httpClient;
    }
}


text:
package org.deuce.benchmark.stmbench7.operations;

import org.deuce.benchmark.stmbench7.OperationId;
import org.deuce.benchmark.stmbench7.Setup;
import org.deuce.benchmark.stmbench7.annotations.Transactional;
import org.deuce.benchmark.stmbench7.annotations.Update;
import org.deuce.benchmark.stmbench7.core.Document;
import org.deuce.benchmark.stmbench7.core.OperationFailedException;
import org.deuce.benchmark.stmbench7.core.RuntimeError;

/**
 * Short traversal ST7 (see the specification).
 * Simple update, short.
 */
public class ShortTraversal7 extends ShortTraversal2 {

	public ShortTraversal7(Setup oo7setup) {
		super(oo7setup);
	}

    @Override
	@Transactional @Update
	public int performOperation() throws OperationFailedException {
    	return super.performOperation();
	}

    @Override
	protected int traverse(Document documentation) {
		if(documentation.textBeginsWith("I am")) return documentation.replaceText("I am", "This is");
		if(documentation.textBeginsWith("This is")) return documentation.replaceText("This is", "I am");

		throw new RuntimeError("ST7: unexpected beginning of Document.text!");
	}

    @Override
    public OperationId getOperationId() {
    	return OperationId.ST7;
    }
}


text:
require 'spec_helper'

require 'capybara/util/save_and_open_page'
require 'launchy'
describe Capybara do
  describe ".save_page & .save_and_open_page" do
    before do
      @temp_file = mock("FILE")
      @temp_file.stub!(:write)
      @temp_file.stub!(:close)

      @html = <<-HTML


text:
scotchApp.controller('changePasswordController', ['$scope', '$location', '$rootScope', '$http', '$cookies', 'dataFactory',
    function ($scope, $location, $rootScope, $http, $cookies, dataFactory, $localStorage) {
        console.log("changePasswordController");

        if($rootScope.currentUserSignedIn == false || $rootScope.currentUserSignedIn== null){
            console.log("test");
            $location.path('/login');
        }

        dataFactory.verifyToken().then(function (response)
        {
            console.log(response);

        }, function(error){

            console.log(error);
            window.alert("Login is exipred");
            delete window.localStorage['currentUsername'];
            delete window.localStorage['currentUserID'];
            delete window.localStorage['currentToken'];
            delete window.localStorage['currentPermission'];
            delete window.localStorage['key'];
            delete window.localStorage['word'];
            delete window.localStorage['files'];
            delete window.localStorage['usersCount'];
            delete window.localStorage['currfiles'];
            delete window.localStorage['currchoices'];
            delete window.localStorage['searchType'];
            delete window.localStorage['searchKeyword'];
            $http.defaults.headers.common.Authorization = '';
            $rootScope.currentUserSignedIn = false;
            $rootScope.permission = '';
            $location.path('/login');

        });

		$scope.userName = "";
        $scope.password = "";
        console.log($scope.username + "|" + $scope.password);

        $scope.usernameLabel = window.localStorage['currentUsername']

        $scope.changePassword = function () {
            console.log("updateuser");

            dataFactory.verifyToken().then(function (response)
            {
                console.log(response);

            }, function(error){

                console.log(error);
                window.alert("Login is exipred");
                delete window.localStorage['currentUsername'];
                delete window.localStorage['currentUserID'];
                delete window.localStorage['currentToken'];
                delete window.localStorage['currentPermission'];
                delete window.localStorage['key'];
                delete window.localStorage['word'];
                delete window.localStorage['files'];
                delete window.localStorage['usersCount'];
                delete window.localStorage['currfiles'];
                delete window.localStorage['currchoices'];
                delete window.localStorage['searchType'];
                delete window.localStorage['searchKeyword'];
                $http.defaults.headers.common.Authorization = '';
                $rootScope.currentUserSignedIn = false;
                $rootScope.permission = '';
                $location.path('/login');

            });

            dataFactory.changePassword(window.localStorage['currentUserID'], $scope.password).then(function (respone) {

                if(respone.data.status == 200)

                    delete window.localStorage['currentUsername'];
                    delete window.localStorage['currentUserID'];
                    delete window.localStorage['currentToken'];
                    delete window.localStorage['currentPermission'];
                    delete window.localStorage['key'];
                    delete window.localStorage['word'];
                    delete window.localStorage['files'];
                    delete window.localStorage['usersCount'];
                    delete window.localStorage['currfiles'];
                    delete window.localStorage['currchoices'];
                    delete window.localStorage['searchType'];
                    delete window.localStorage['searchKeyword'];
                    console.log($rootScope);
                    $http.defaults.headers.common.Authorization = '';
                    $rootScope.currentUserSignedIn = false;
                    $rootScope.permission = '';
                    $location.path('/login');

            });

        }

        return $scope.usernameLabel;

    }]);


text:
""" Collection helper for the process """
import os
import pwd
import grp
from instana.log import logger
from instana.util import DictionaryOfStan
from instana.util.runtime import get_proc_cmdline
from instana.util.secrets import contains_secret
from .base import BaseHelper

class ProcessHelper(BaseHelper):
    """ Helper class to collect metrics for this process """

    def collect_metrics(self, **kwargs):
        plugin_data = dict()
        try:
            plugin_data["name"] = "com.instana.plugin.process"
            plugin_data["entityId"] = str(os.getpid())
            plugin_data["data"] = DictionaryOfStan()
            plugin_data["data"]["pid"] = int(os.getpid())

            if kwargs.get("with_snapshot"):
                self._collect_process_snapshot(plugin_data)
        except Exception:
            logger.debug("ProcessHelper.collect_metrics: ", exc_info=True)
        return plugin_data

    def _collect_process_snapshot(self, plugin_data):
        try:
            env = dict()
            for key in os.environ:
                if contains_secret(key,
                                   self.collector.agent.options.secrets_matcher,
                                   self.collector.agent.options.secrets_list):
                    env[key] = "<ignored>"
                else:
                    env[key] = os.environ[key]
            plugin_data["data"]["env"] = env
            if os.path.isfile("/proc/self/exe"):
                plugin_data["data"]["exec"] = os.readlink("/proc/self/exe")
            else:
                logger.debug("Can't access /proc/self/exe...")

            cmdline = get_proc_cmdline()
            if len(cmdline) > 1:
                # drop the exe
                cmdline.pop(0)
            plugin_data["data"]["args"] = cmdline
            try:
                euid = os.geteuid()
                egid = os.getegid()
                plugin_data["data"]["user"] = pwd.getpwuid(euid)
                plugin_data["data"]["group"] = grp.getgrgid(egid).gr_name
            except Exception:
                logger.debug("euid/egid detection: ", exc_info=True)

            plugin_data["data"]["start"] = self.collector.fetching_start_time

        except Exception:
            logger.debug("ProcessHelper._collect_process_snapshot: ", exc_info=True)


text:
#include <aws/lightsail/model/GetDomainsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Lightsail::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

GetDomainsResult::GetDomainsResult()
{
}

GetDomainsResult::GetDomainsResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

GetDomainsResult& GetDomainsResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  const JsonValue& jsonValue = result.GetPayload();
  if(jsonValue.ValueExists("domains"))
  {
    Array<JsonValue> domainsJsonList = jsonValue.GetArray("domains");
    for(unsigned domainsIndex = 0; domainsIndex < domainsJsonList.GetLength(); ++domainsIndex)
    {
      m_domains.push_back(domainsJsonList[domainsIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("nextPageToken"))
  {
    m_nextPageToken = jsonValue.GetString("nextPageToken");

  }

  return *this;
}


text:
using namespace metaSMT::solver;
using namespace metaSMT;
struct Solver_Fixture
{
  typedef DirectSolver_Context< Group <BitBlast < SAT_Clause <
    ClauseWriter< dimacs_solver< executable::Glucoser > >
  > > > > ContextType;
  ContextType ctx ;
};

#include "test_solver.cpp"
#include "test_QF_BV.cpp"
// #include "test_Array.cpp"
#include "test_group.cpp"
#include "test_unsat.cpp"
#include "test_lazy.cpp"


text:
namespace llvm {
  class LLVMContext;
  class DiagnosticInfo;
  class GlobalValue;
  class Mangler;
  class MemoryBuffer;
  class TargetLibraryInfo;
  class TargetMachine;
  class raw_ostream;
  class raw_pwrite_stream;

//===----------------------------------------------------------------------===//
/// C++ class which implements the opaque lto_code_gen_t type.
///
struct LTOCodeGenerator {
  static const char *getVersionString();

  LTOCodeGenerator();
  LTOCodeGenerator(std::unique_ptr<LLVMContext> Context);
  ~LTOCodeGenerator();

  // Merge given module, return true on success.
  bool addModule(struct LTOModule *);

  // Set the destination module.
  void setModule(struct LTOModule *);

  void setTargetOptions(TargetOptions options);
  void setDebugInfo(lto_debug_model);
  void setCodePICModel(lto_codegen_model);

  void setCpu(const char *mCpu) { MCpu = mCpu; }
  void setAttr(const char *mAttr) { MAttr = mAttr; }
  void setOptLevel(unsigned optLevel) { OptLevel = optLevel; }

  void setShouldInternalize(bool Value) { ShouldInternalize = Value; }
  void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; }

  void addMustPreserveSymbol(StringRef sym) { MustPreserveSymbols[sym] = 1; }

  // To pass options to the driver and optimization passes. These options are
  // not necessarily for debugging purpose (The function name is misleading).
  // This function should be called before LTOCodeGenerator::compilexxx(),
  // and LTOCodeGenerator::writeMergedModules().
  void setCodeGenDebugOptions(const char *opts);

  // Parse the options set in setCodeGenDebugOptions. Like
  // setCodeGenDebugOptions, this must be called before
  // LTOCodeGenerator::compilexxx() and LTOCodeGenerator::writeMergedModules()
  void parseCodeGenDebugOptions();

  // Write the merged module to the file specified by the given path.
  // Return true on success.
  bool writeMergedModules(const char *path, std::string &errMsg);

  // Compile the merged module into a *single* object file; the path to object
  // file is returned to the caller via argument "name". Return true on
  // success.
  //
  // NOTE that it is up to the linker to remove the intermediate object file.
  //  Do not try to remove the object file in LTOCodeGenerator's destructor
  //  as we don't who (LTOCodeGenerator or the obj file) will last longer.
  bool compile_to_file(const char **name,
                       bool disableInline,
                       bool disableGVNLoadPRE,
                       bool disableVectorization,
                       std::string &errMsg);

  // As with compile_to_file(), this function compiles the merged module into
  // single object file. Instead of returning the object-file-path to the caller
  // (linker), it brings the object to a buffer, and return the buffer to the
  // caller. This function should delete intermediate object file once its content
  // is brought to memory. Return NULL if the compilation was not successful.
  std::unique_ptr<MemoryBuffer> compile(bool disableInline,
                                        bool disableGVNLoadPRE,
                                        bool disableVectorization,
                                        std::string &errMsg);

  // Optimizes the merged module. Returns true on success.
  bool optimize(bool disableInline,
                bool disableGVNLoadPRE,
                bool disableVectorization,
                std::string &errMsg);

  // Compiles the merged optimized module into a single object file. It brings
  // the object to a buffer, and returns the buffer to the caller. Return NULL
  // if the compilation was not successful.
  std::unique_ptr<MemoryBuffer> compileOptimized(std::string &errMsg);

  void setDiagnosticHandler(lto_diagnostic_handler_t, void *);

  LLVMContext &getContext() { return Context; }

private:
  void initializeLTOPasses();

  bool compileOptimized(raw_pwrite_stream &out, std::string &errMsg);
  bool compileOptimizedToFile(const char **name, std::string &errMsg);
  void applyScopeRestrictions();
  void applyRestriction(GlobalValue &GV, ArrayRef<StringRef> Libcalls,
                        std::vector<const char *> &MustPreserveList,
                        SmallPtrSetImpl<GlobalValue *> &AsmUsed,
                        Mangler &Mangler);
  bool determineTarget(std::string &errMsg);

  static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context);

  void DiagnosticHandler2(const DiagnosticInfo &DI);

  typedef StringMap<uint8_t> StringSet;

  void destroyMergedModule();
  std::unique_ptr<LLVMContext> OwnedContext;
  LLVMContext &Context;
  Linker IRLinker;
  TargetMachine *TargetMach = nullptr;
  bool EmitDwarfDebugInfo = false;
  bool ScopeRestrictionsDone = false;
  lto_codegen_model CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
  StringSet MustPreserveSymbols;
  StringSet AsmUndefinedRefs;
  std::vector<char *> CodegenOptions;
  std::string MCpu;
  std::string MAttr;
  std::string NativeObjectPath;
  TargetOptions Options;
  unsigned OptLevel = 2;
  lto_diagnostic_handler_t DiagHandler = nullptr;
  void *DiagContext = nullptr;
  LTOModule *OwnedModule = nullptr;
  bool ShouldInternalize = true;
  bool ShouldEmbedUselists = false;
};
}
#endif


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>visitas-de-extensao-ao-observatorio-pico-dos-dias</id>
    <dbId>3292</dbId>
    <nome>Visitas de extensão ao Observatório Pico dos Dias</nome>
    <sigla></sigla>
    <descricao>Atendimento de visitas do público em geral no Observatório do Pico dos Dias com intuito de extensão.</descricao>
    <contato></contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="3879">
            <tipo>Qualquer pessoa pode utilizar este serviço.</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <entre min="31" max="60" unidade="dias-corridos"/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="7392">
            <titulo>Agendar visita</titulo>
            <descricao></descricao>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="7825" tipo="presencial">
                        <descricao>Observatório Pico dos Dias - Estrada do Observatório, s/n - Bom Sucesso, Brasópolis - MG, 37530-000</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="7826" tipo="e-mail">
                        <descricao>mabans@lna.br</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="7827" tipo="telefone">
                        <descricao>(35) 3629-8100</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/1988" dbId="37525">
        <nomeOrgao>Ministério da Ciência, Tecnologia, Inovações e Comunicações (MCTIC)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="1" idServicoSegmento="7325">Cidadãos</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Educação</item>
        <item>Pesquisa e Desenvolvimento</item>
        <item>Pesquisa, Ciência, Inovação e Tecnologia</item>
        <item>Lazer</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="13589">pico dos dias</item>
        <item id="13590">extensão</item>
        <item id="13591">visita</item>
    </palavras-chave>
</servico>


text:
module Ebay # :nodoc:
  module Types # :nodoc:
    # == Attributes
    #  numeric_node :user_catalog_id, 'UserCatalogID', :optional => true
    #  numeric_node :schedule_id, 'ScheduleID', :optional => true
    #  text_node :lot_number, 'LotNumber', :optional => true
    #  money_node :high_estimate, 'HighEstimate', :optional => true
    #  money_node :low_estimate, 'LowEstimate', :optional => true
    class LiveAuctionDetails
      include XML::Mapping
      include Initializer
      root_element_name 'LiveAuctionDetails'
      numeric_node :user_catalog_id, 'UserCatalogID', :optional => true
      numeric_node :schedule_id, 'ScheduleID', :optional => true
      text_node :lot_number, 'LotNumber', :optional => true
      money_node :high_estimate, 'HighEstimate', :optional => true
      money_node :low_estimate, 'LowEstimate', :optional => true
    end
  end
end


text:
import functools
import uuid

from django.conf import settings
from django.test import SimpleTestCase
from elasticsearch.exceptions import ConnectionError

from corehq.elastic import get_es_new
from corehq.util.elastic import ensure_index_deleted
from corehq.util.test_utils import trap_extra_setup
from pillowtop.es_utils import INDEX_REINDEX_SETTINGS, INDEX_STANDARD_SETTINGS, update_settings, \
    set_index_reindex_settings, set_index_normal_settings, mapping_exists, initialize_index, \
    initialize_index_and_mapping, assume_alias
from pillowtop.exceptions import PillowtopIndexingError
from pillowtop.processors.elastic import send_to_elasticsearch
from .utils import get_doc_count, get_index_mapping, TEST_INDEX_INFO

class ElasticPillowTest(SimpleTestCase):

    def setUp(self):
        self.index = TEST_INDEX_INFO.index
        self.es = get_es_new()
        with trap_extra_setup(ConnectionError):
            ensure_index_deleted(self.index)

    def tearDown(self):
        ensure_index_deleted(self.index)

    def test_create_index(self):
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        # make sure it was created
        self.assertTrue(self.es.indices.exists(self.index))
        # check the subset of settings we expected to set
        settings_back = self.es.indices.get_settings(self.index)[self.index]['settings']
        if settings.ELASTICSEARCH_VERSION < 1.0:
            self.assertEqual('whitespace', settings_back['index.analysis.analyzer.default.tokenizer'])
            self.assertEqual('lowercase', settings_back['index.analysis.analyzer.default.filter.0'])
        else:
            self.assertEqual(
                TEST_INDEX_INFO.meta['settings']['analysis'],
                settings_back['index']['analysis'],
            )
        self.es.indices.delete(self.index)
        self.assertFalse(self.es.indices.exists(self.index))

    def test_mapping_initialization(self):
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        self.assertTrue(mapping_exists(self.es, TEST_INDEX_INFO))
        mapping = get_index_mapping(self.es, self.index, TEST_INDEX_INFO.type)
        # we can't compare the whole dicts because ES adds a bunch of stuff to them
        self.assertEqual(
            TEST_INDEX_INFO.mapping['properties']['doc_type']['index'],
            mapping['properties']['doc_type']['index']
        )

    def test_refresh_index(self):
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        doc_id = uuid.uuid4().hex
        doc = {'_id': doc_id, 'doc_type': 'CommCareCase', 'type': 'mother'}
        self.assertEqual(0, get_doc_count(self.es, self.index))
        self.es.create(self.index, 'case', doc, id=doc_id)
        self.assertEqual(0, get_doc_count(self.es, self.index, refresh_first=False))
        self.es.indices.refresh(self.index)
        self.assertEqual(1, get_doc_count(self.es, self.index, refresh_first=False))

    def test_index_operations(self):
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        self.assertTrue(self.es.indices.exists(self.index))

        # delete and check
        self.es.indices.delete(self.index)
        self.assertFalse(self.es.indices.exists(self.index))

        # create and check
        initialize_index(self.es, TEST_INDEX_INFO)
        self.assertTrue(self.es.indices.exists(self.index))

    def test_assume_alias(self):
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        doc_id = uuid.uuid4().hex
        doc = {'_id': doc_id, 'doc_type': 'CommCareCase', 'type': 'mother'}
        send_to_elasticsearch(self.index, TEST_INDEX_INFO.type, doc_id, get_es_new, 'test', doc)
        self.assertEqual(1, get_doc_count(self.es, self.index))
        assume_alias(self.es, self.index, TEST_INDEX_INFO.alias)
        es_doc = self.es.get_source(TEST_INDEX_INFO.alias, TEST_INDEX_INFO.type, doc_id)
        for prop in doc:
            self.assertEqual(doc[prop], es_doc[prop])

    def test_assume_alias_deletes_old_aliases(self):
        # create a different index and set the alias for it
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        new_index = 'test_index-with-duplicate-alias'
        if not self.es.indices.exists(new_index):
            self.es.indices.create(index=new_index)
        self.es.indices.put_alias(new_index, TEST_INDEX_INFO.alias)
        self.addCleanup(functools.partial(ensure_index_deleted, new_index))

        # make sure it's there in the other index
        aliases = self.es.indices.get_aliases()
        self.assertEqual([TEST_INDEX_INFO.alias], aliases[new_index]['aliases'].keys())

        # assume alias and make sure it's removed (and added to the right index)
        assume_alias(self.es, self.index, TEST_INDEX_INFO.alias)
        aliases = self.es.indices.get_aliases()
        self.assertEqual(0, len(aliases[new_index]['aliases']))
        self.assertEqual([TEST_INDEX_INFO.alias], aliases[self.index]['aliases'].keys())

    def test_update_settings(self):
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        update_settings(self.es, self.index, INDEX_REINDEX_SETTINGS)
        index_settings_back = self.es.indices.get_settings(self.index)[self.index]['settings']
        self._compare_es_dicts(INDEX_REINDEX_SETTINGS, index_settings_back, 'index')
        update_settings(self.es, self.index, INDEX_STANDARD_SETTINGS)
        index_settings_back = self.es.indices.get_settings(self.index)[self.index]['settings']
        self._compare_es_dicts(INDEX_STANDARD_SETTINGS, index_settings_back, 'index')

    def test_set_index_reindex(self):
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        set_index_reindex_settings(self.es, self.index)
        index_settings_back = self.es.indices.get_settings(self.index)[self.index]['settings']
        self._compare_es_dicts(INDEX_REINDEX_SETTINGS, index_settings_back, 'index')

    def test_set_index_normal(self):
        initialize_index_and_mapping(self.es, TEST_INDEX_INFO)
        set_index_normal_settings(self.es, self.index)
        index_settings_back = self.es.indices.get_settings(self.index)[self.index]['settings']
        self._compare_es_dicts(INDEX_STANDARD_SETTINGS, index_settings_back, 'index')

    def _compare_es_dicts(self, expected, returned, prefix):
        if settings.ELASTICSEARCH_VERSION < 1.0:
            for key, value in expected[prefix].items():
                self.assertEqual(str(value), returned['{}.{}'.format(prefix, key)])
        else:
            sub_returned = returned[prefix]
            for key, value in expected[prefix].items():
                split_key = key.split('.')
                returned_value = sub_returned[split_key[0]]
                for sub_key in split_key[1:]:
                    returned_value = returned_value[sub_key]
                self.assertEqual(str(value), returned_value)

class TestSendToElasticsearch(SimpleTestCase):

    def setUp(self):
        self.es = get_es_new()
        self.index = TEST_INDEX_INFO.index

        with trap_extra_setup(ConnectionError):
            ensure_index_deleted(self.index)
            initialize_index_and_mapping(self.es, TEST_INDEX_INFO)

    def tearDown(self):
        ensure_index_deleted(self.index)

    def test_create_doc(self):
        doc = {'_id': uuid.uuid4().hex, 'doc_type': 'MyCoolDoc', 'property': 'foo'}
        self._send_to_es_and_check(doc)

    def _send_to_es_and_check(self, doc, update=False, delete=False, esgetter=None):
        send_to_elasticsearch(
            index=self.index,
            doc_type=TEST_INDEX_INFO.type,
            doc_id=doc['_id'],
            es_getter=esgetter or get_es_new,
            name='test',
            data=doc,
            update=update,
            delete=delete,
            except_on_failure=True,
            retries=1
        )

        if not delete:
            self.assertEqual(1, get_doc_count(self.es, self.index))
            es_doc = self.es.get_source(self.index, TEST_INDEX_INFO.type, doc['_id'])
            for prop in doc:
                self.assertEqual(doc[prop], es_doc[prop])
        else:
            self.assertEqual(0, get_doc_count(self.es, self.index))

    def test_update_doc(self):
        doc = {'_id': uuid.uuid4().hex, 'doc_type': 'MyCoolDoc', 'property': 'bar'}
        self._send_to_es_and_check(doc)

        doc['property'] = 'bazz'
        self._send_to_es_and_check(doc, update=True)

    def test_delete_doc(self):
        doc = {'_id': uuid.uuid4().hex, 'doc_type': 'MyCoolDoc', 'property': 'bar'}
        self._send_to_es_and_check(doc)

        self._send_to_es_and_check(doc, delete=True)

    def test_connection_failure(self):
        def _bad_es_getter():
            from elasticsearch import Elasticsearch
            return Elasticsearch(
                [{
                    'host': 'localhost',
                    'port': '9000',  # bad port
                }],
                timeout=0.1,
            )

        doc = {'_id': uuid.uuid4().hex, 'doc_type': 'MyCoolDoc', 'property': 'bar'}

        with self.assertRaises(PillowtopIndexingError):
            self._send_to_es_and_check(doc, esgetter=_bad_es_getter)

    def test_not_found(self):
        doc = {'_id': uuid.uuid4().hex, 'doc_type': 'MyCoolDoc', 'property': 'bar'}

        self._send_to_es_and_check(doc, delete=True)

    def test_conflict(self):
        doc = {'_id': uuid.uuid4().hex, 'doc_type': 'MyCoolDoc', 'property': 'foo'}
        self._send_to_es_and_check(doc)

        # attempt to create the same doc twice shouldn't fail
        self._send_to_es_and_check(doc)


text:
canary
[![Dependency Status](https://www.versioneye.com/user/projects/566e4ec54e049b003b000975/badge.svg?style=flat)](https://www.versioneye.com/user/projects/566e4ec54e049b003b000975)

A project for tracking canaries!

```
find . -name "ivy.xml" -exec grep "<dependency" {} \; | tr -s \[:space:] | sort | uniq
```


text:
package org.apereo.portal.security;

import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apereo.portal.EntityIdentifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service("identitySwapperManager")
public class IdentitySwapperManagerImpl implements IdentitySwapperManager {

    private static final String SWAP_TARGET_UID = IdentitySwapperManagerImpl.class.getName() + ".SWAP_TARGET_UID";
    private static final String SWAP_TARGET_PROFILE = IdentitySwapperManagerImpl.class.getName() + ".SWAP_TARGET_PROFILE";
    private static final String SWAP_ORIGINAL_UID = IdentitySwapperManagerImpl.class.getName() + ".SWAP_ORIGINAL_UID";
    private static final String SWAP_ORIGINAL_AUTH = IdentitySwapperManagerImpl.class.getName() + ".SWAP_ORIGINAL_AUTH";

    private IAuthorizationService authorizationService;

    @Autowired
    public void setAuthorizationService(IAuthorizationService authorizationService) {
        this.authorizationService = authorizationService;
    }

    @Override
    public boolean canImpersonateUser(IPerson currentUser, String targetUsername) {
        final EntityIdentifier ei = currentUser.getEntityIdentifier();
        final IAuthorizationPrincipal ap = authorizationService.newPrincipal(ei.getKey(), ei.getType());

        return canImpersonateUser(ap, targetUsername);
    }

    @Override
    public boolean canImpersonateUser(String currentUserName, String targetUsername) {
        final IAuthorizationPrincipal ap = authorizationService.newPrincipal(currentUserName, IPerson.class);
        return canImpersonateUser(ap, targetUsername);
    }

    protected boolean canImpersonateUser(final IAuthorizationPrincipal ap, String targetUsername) {
        return ap.hasPermission(IPermission.PORTAL_USERS, IPermission.IMPERSONATE_USER_ACTIVITY, targetUsername);
    }

    @Override
    public void impersonateUser(PortletRequest portletRequest, IPerson currentUser, String targetUsername) {
        this.impersonateUser(portletRequest, currentUser.getName(), targetUsername);
    }

    @Override
    public void impersonateUser(PortletRequest portletRequest, String currentUserName, String targetUsername) {
    	impersonateUser(portletRequest, currentUserName, targetUsername,"default");
    }

    @Override
    public void impersonateUser(PortletRequest portletRequest, String currentUserName, String targetUsername, String profile) {
        if (!canImpersonateUser(currentUserName, targetUsername)) {
            throw new RuntimeAuthorizationException(currentUserName, IPermission.IMPERSONATE_USER_ACTIVITY, targetUsername);
        }

        final PortletSession portletSession = portletRequest.getPortletSession();
        portletSession.setAttribute(SWAP_TARGET_UID, targetUsername, PortletSession.APPLICATION_SCOPE);
        portletSession.setAttribute(SWAP_TARGET_PROFILE, profile, PortletSession.APPLICATION_SCOPE);
    }

    @Override
    public void setOriginalUser(HttpSession session, String currentUserName, String targetUsername) {
        this.setOriginalUser(session, currentUserName, targetUsername, null);
    }

    @Override
    public void setOriginalUser(
            HttpSession session, String currentUserName, String targetUsername, Authentication originalAuth) {
        if (!canImpersonateUser(currentUserName, targetUsername)) {
            throw new RuntimeAuthorizationException(currentUserName, IPermission.IMPERSONATE_USER_ACTIVITY, targetUsername);
        }
        session.setAttribute(SWAP_ORIGINAL_UID, currentUserName);
        session.setAttribute(SWAP_ORIGINAL_AUTH, originalAuth);
    }

    @Override
    public String getOriginalUsername(HttpSession session) {
        return (String) session.getAttribute(SWAP_ORIGINAL_UID);
    }

    @Override
    public Authentication getOriginalAuthentication(HttpSession session) {
        return (Authentication) session.getAttribute(SWAP_ORIGINAL_AUTH);
    }

    @Override
    public String getTargetUsername(HttpSession session) {
        return (String) session.getAttribute(SWAP_TARGET_UID);
    }

    @Override
    public String getTargetProfile(HttpSession session) {
    	return (String) session.getAttribute(SWAP_TARGET_PROFILE);
    }

    @Override
    public boolean isImpersonating(HttpServletRequest request) {
        final HttpSession session = request.getSession(false);
        if (session == null) {
            return false;
        }
        return this.getOriginalUsername(session) != null;
    }
}