text:
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/lib/core/bits.h"

namespace tensorflow {

namespace {

using shape_inference::DimensionHandle;
using shape_inference::InferenceContext;
using shape_inference::ShapeHandle;

Status DecodeWavShapeFn(InferenceContext* c) {
  ShapeHandle unused;
  TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &unused));

  DimensionHandle channels_dim;
  int32 desired_channels;
  TF_RETURN_IF_ERROR(c->GetAttr("desired_channels", &desired_channels));
  if (desired_channels == -1) {
    channels_dim = c->UnknownDim();
  } else {
    if (desired_channels < 0) {
      return errors::InvalidArgument("channels must be non-negative, got ",
                                     desired_channels);
    }
    channels_dim = c->MakeDim(desired_channels);
  }
  DimensionHandle samples_dim;
  int32 desired_samples;
  TF_RETURN_IF_ERROR(c->GetAttr("desired_samples", &desired_samples));
  if (desired_samples == -1) {
    samples_dim = c->UnknownDim();
  } else {
    if (desired_samples < 0) {
      return errors::InvalidArgument("samples must be non-negative, got ",
                                     desired_samples);
    }
    samples_dim = c->MakeDim(desired_samples);
  }
  c->set_output(0, c->MakeShape({samples_dim, channels_dim}));
  c->set_output(1, c->Scalar());
  return Status::OK();
}

Status EncodeWavShapeFn(InferenceContext* c) {
  ShapeHandle unused;
  TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &unused));
  TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &unused));
  c->set_output(0, c->Scalar());
  return Status::OK();
}

Status SpectrogramShapeFn(InferenceContext* c) {
  ShapeHandle input;
  TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &input));
  int32 window_size;
  TF_RETURN_IF_ERROR(c->GetAttr("window_size", &window_size));
  int32 stride;
  TF_RETURN_IF_ERROR(c->GetAttr("stride", &stride));

  DimensionHandle input_channels = c->Dim(input, 0);
  DimensionHandle input_length = c->Dim(input, 1);

  DimensionHandle output_length;
  if (!c->ValueKnown(input_length)) {
    output_length = c->UnknownDim();
  } else {
    const int64 input_length_value = c->Value(input_length);
    const int64 length_minus_window = (input_length_value - window_size);
    int64 output_length_value;
    if (length_minus_window < 0) {
      output_length_value = 0;
    } else {
      output_length_value = 1 + (length_minus_window / stride);
    }
    output_length = c->MakeDim(output_length_value);
  }

  DimensionHandle output_channels =
      c->MakeDim(1 + NextPowerOfTwo(window_size) / 2);
  c->set_output(0,
                c->MakeShape({input_channels, output_length, output_channels}));
  return Status::OK();
}

Status MfccShapeFn(InferenceContext* c) {
  ShapeHandle spectrogram;
  TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 3, &spectrogram));
  ShapeHandle unused;
  TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &unused));

  int32 dct_coefficient_count;
  TF_RETURN_IF_ERROR(
      c->GetAttr("dct_coefficient_count", &dct_coefficient_count));

  DimensionHandle spectrogram_channels = c->Dim(spectrogram, 0);
  DimensionHandle spectrogram_length = c->Dim(spectrogram, 1);

  DimensionHandle output_channels = c->MakeDim(dct_coefficient_count);

  c->set_output(0, c->MakeShape({spectrogram_channels, spectrogram_length,
                                 output_channels}));
  return Status::OK();
}

}  // namespace

REGISTER_OP("DecodeWav")
    .Input("contents: string")
    .Attr("desired_channels: int = -1")
    .Attr("desired_samples: int = -1")
    .Output("audio: float")
    .Output("sample_rate: int32")
    .SetShapeFn(DecodeWavShapeFn)
    .Doc(R"doc(
Decode a 16-bit PCM WAV file to a float tensor.

The -32768 to 32767 signed 16-bit values will be scaled to -1.0 to 1.0 in float.

When desired_channels is set, if the input contains fewer channels than this
then the last channel will be duplicated to give the requested number, else if
the input has more channels than requested then the additional channels will be
ignored.

If desired_samples is set, then the audio will be cropped or padded with zeroes
to the requested length.

The first output contains a Tensor with the content of the audio samples. The
lowest dimension will be the number of channels, and the second will be the
number of samples. For example, a ten-sample-long stereo WAV file should give an
output shape of [10, 2].

contents: The WAV-encoded audio, usually from a file.
desired_channels: Number of sample channels wanted.
desired_samples: Length of audio requested.
audio: 2-D with shape `[length, channels]`.
sample_rate: Scalar holding the sample rate found in the WAV header.
)doc");

REGISTER_OP("EncodeWav")
    .Input("audio: float")
    .Input("sample_rate: int32")
    .Output("contents: string")
    .SetShapeFn(EncodeWavShapeFn)
    .Doc(R"doc(
Encode audio data using the WAV file format.

This operation will generate a string suitable to be saved out to create a .wav
audio file. It will be encoded in the 16-bit PCM format. It takes in float
values in the range -1.0f to 1.0f, and any outside that value will be clamped to
that range.

`audio` is a 2-D float Tensor of shape `[length, channels]`.
`sample_rate` is a scalar Tensor holding the rate to use (e.g. 44100).

audio: 2-D with shape `[length, channels]`.
sample_rate: Scalar containing the sample frequency.
contents: 0-D. WAV-encoded file contents.
)doc");

REGISTER_OP("AudioSpectrogram")
    .Input("input: float")
    .Attr("window_size: int")
    .Attr("stride: int")
    .Attr("magnitude_squared: bool = false")
    .Output("spectrogram: float")
    .SetShapeFn(SpectrogramShapeFn)
    .Doc(R"doc(
Produces a visualization of audio data over time.

Spectrograms are a standard way of representing audio information as a series of
slices of frequency information, one slice for each window of time. By joining
these together into a sequence, they form a distinctive fingerprint of the sound
over time.

This op expects to receive audio data as an input, stored as floats in the range
-1 to 1, together with a window width in samples, and a stride specifying how
far to move the window between slices. From this it generates a three
dimensional output. The lowest dimension has an amplitude value for each
frequency during that time slice. The next dimension is time, with successive
frequency slices. The final dimension is for the channels in the input, so a
stereo audio input would have two here for example.

This means the layout when converted and saved as an image is rotated 90 degrees
clockwise from a typical spectrogram. Time is descending down the Y axis, and
the frequency decreases from left to right.

Each value in the result represents the square root of the sum of the real and
imaginary parts of an FFT on the current window of samples. In this way, the
lowest dimension represents the power of each frequency in the current window,
and adjacent windows are concatenated in the next dimension.

To get a more intuitive and visual look at what this operation does, you can run
tensorflow/examples/wav_to_spectrogram to read in an audio file and save out the
resulting spectrogram as a PNG image.

input: Float representation of audio data.
window_size: How wide the input window is in samples. For the highest efficiency
  this should be a power of two, but other values are accepted.
stride: How widely apart the center of adjacent sample windows should be.
magnitude_squared: Whether to return the squared magnitude or just the
  magnitude. Using squared magnitude can avoid extra calculations.
spectrogram: 3D representation of the audio frequencies as an image.
)doc");

REGISTER_OP("Mfcc")
    .Input("spectrogram: float")
    .Input("sample_rate: int32")
    .Attr("upper_frequency_limit: float = 4000")
    .Attr("lower_frequency_limit: float = 20")
    .Attr("filterbank_channel_count: int = 40")
    .Attr("dct_coefficient_count: int = 13")
    .Output("output: float")
    .SetShapeFn(MfccShapeFn)
    .Doc(R"doc(
Transforms a spectrogram into a form that's useful for speech recognition.

Mel Frequency Cepstral Coefficients are a way of representing audio data that's
been effective as an input feature for machine learning. They are created by
taking the spectrum of a spectrogram (a 'cepstrum'), and discarding some of the
higher frequencies that are less significant to the human ear. They have a long
history in the speech recognition world, and https://en.wikipedia.org/wiki/Mel-frequency_cepstrum
is a good resource to learn more.

spectrogram: Typically produced by the Spectrogram op, with magnitude_squared
  set to true.
sample_rate: How many samples per second the source audio used.
upper_frequency_limit: The highest frequency to use when calculating the
  ceptstrum.
lower_frequency_limit: The lowest frequency to use when calculating the
  ceptstrum.
filterbank_channel_count: Resolution of the Mel bank used internally.
dct_coefficient_count: How many output channels to produce per time slice.
)doc");

}  // namespace tensorflow


text:
"""
Copyright 2013 Steven Diamond

This file is part of CVXPY.

CVXPY is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

CVXPY is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with CVXPY.  If not, see <http://www.gnu.org/licenses/>.
"""

from cvxpy.interface import cvxopt_interface as co_intf
from cvxpy.interface import numpy_interface as np_intf
import cvxopt
import scipy.sparse as sp
import numbers
import numpy as np
import warnings
from cvxpy.utilities.sign import Sign

# A mapping of class to interface.
INTERFACES = {cvxopt.matrix: co_intf.DenseMatrixInterface(),
              cvxopt.spmatrix: co_intf.SparseMatrixInterface(),
              np.ndarray: np_intf.NDArrayInterface(),
              np.matrix: np_intf.MatrixInterface(),
              sp.csc_matrix: np_intf.SparseMatrixInterface(),
}
# Default Numpy interface.
DEFAULT_NP_INTERFACE = INTERFACES[np.ndarray]
# Default dense and sparse matrix interfaces.
DEFAULT_INTERFACE = INTERFACES[np.matrix]
DEFAULT_SPARSE_INTERFACE = INTERFACES[sp.csc_matrix]
# CVXOPT interfaces.
CVXOPT_DENSE_INTF = INTERFACES[cvxopt.matrix]
CVXOPT_SPARSE_INTF = INTERFACES[cvxopt.spmatrix]

# Returns the interface for interacting with the target matrix class.
def get_matrix_interface(target_class):
    return INTERFACES[target_class]

def is_sparse(constant):
    """Is the constant a sparse matrix?
    """
    return sp.issparse(constant) or isinstance(constant, cvxopt.spmatrix)

# Get the dimensions of the constant.
def size(constant):
    if isinstance(constant, numbers.Number) or np.isscalar(constant):
        return (1, 1)
    elif isinstance(constant, list):
        if len(constant) == 0:
            return (0,0)
        elif isinstance(constant[0], numbers.Number): # Vector
            return (len(constant),1)
        else: # Matrix
            return (len(constant[0]), len(constant))
    elif constant.__class__ in INTERFACES:
        return INTERFACES[constant.__class__].size(constant)
    # Direct all sparse matrices to CSC interface.
    elif is_sparse(constant):
        return INTERFACES[sp.csc_matrix].size(constant)
    else:
        raise TypeError("%s is not a valid type for a Constant value." % type(constant))

# Is the constant a column vector?
def is_vector(constant):
    return size(constant)[1] == 1

# Is the constant a scalar?
def is_scalar(constant):
    return size(constant) == (1, 1)

def from_2D_to_1D(constant):
    """Convert 2D Numpy matrices or arrays to 1D.
    """
    if isinstance(constant, np.ndarray):
        return np.asarray(constant)[:, 0]
    else:
        return constant

def from_1D_to_2D(constant):
    """Convert 1D Numpy arrays to matrices.
    """
    if isinstance(constant, np.ndarray) and constant.ndim == 1:
        return np.mat(constant).T
    else:
        return constant

# Get the value of the passed constant, interpreted as a scalar.
def scalar_value(constant):
    assert is_scalar(constant)
    if isinstance(constant, numbers.Number) or np.isscalar(constant):
        return constant
    elif isinstance(constant, list):
        return constant[0]
    elif constant.__class__ in INTERFACES:
        return INTERFACES[constant.__class__].scalar_value(constant)
    # Direct all sparse matrices to CSC interface.
    elif is_sparse(constant):
        return INTERFACES[sp.csc_matrix].scalar_value(constant.tocsc())
    else:
        raise TypeError("%s is not a valid type for a Constant value." % type(constant))

# Return the collective sign of the matrix entries.
def sign(constant):
    if isinstance(constant, numbers.Number):
        return Sign.val_to_sign(constant)
    elif isinstance(constant, cvxopt.spmatrix):
        max_val = max(constant.V)
        min_val = min(constant.V)
    elif sp.issparse(constant):
        max_val = constant.max()
        min_val = constant.min()
    else: # Convert to Numpy array.
        mat = INTERFACES[np.ndarray].const_to_matrix(constant)
        max_val = mat.max()
        min_val = mat.min()
    max_sign = Sign.val_to_sign(max_val)
    min_sign = Sign.val_to_sign(min_val)
    return max_sign + min_sign

# Get the value at the given index.
def index(constant, key):
    if is_scalar(constant):
        return constant
    elif constant.__class__ in INTERFACES:
        return INTERFACES[constant.__class__].index(constant, key)
    # Use CSC interface for all sparse matrices.
    elif is_sparse(constant):
        interface = INTERFACES[sp.csc_matrix]
        constant = interface.const_to_matrix(constant)
        return interface.index(constant, key)

redpajama_set_name: RedPajamaGithub


text:
package com.kotkovets.fines.modules.launcher.router;

/**
 * Created by igork on 6/19/16.
 */
public interface LauncherRouterInput {
    void presentList();
}


text:
# ifndef GRAPHICS_ORIGIN_SIMPLE_TERRAIN_MAP_H_
# define GRAPHICS_ORIGIN_SIMPLE_TERRAIN_MAP_H_
# include "../../../graphics-origin/geometry/vec.h"
# include "../../../graphics-origin/application/renderable.h"
# include "../../../graphics-origin/application/shader_program.h"
# include <stdexcept>
# include <vector>
# include <noise/noise.h>
namespace graphics_origin
{
  namespace application
  {
    /**@brief A class to render in 3D a simple terrain map
     *
     * This class uses a noise module to generate an height map
     * for a simple terrain and render it in 3D. The map is a square, centered
     * at the origin, with a size equals to two time a radius R.
     */
    class simple_terrain_map : public renderable
    {
    public:
      simple_terrain_map();

      ~simple_terrain_map()
      {
        remove_gpu_data();
      }

      /** @brief Set the desired horizontal resolution.
       *
       * Request for a particular horizontal resolution, i.e. what is the
       * minimum size of a tile to represent all the features you want.
       * @param resolution_in_m The resolution requested, in meter(s).
       */
      void
      set_resolution( gl_real resolution_in_m = 1.0 );

      /** @brief Specify the height to generate an height map.
       *
       * Send a noise module such that an height map can be built to render
       * the whole scene.
       * @param land_generator A noise module that gives the height of a 2D point
       * @param texture_size Size of the height map texture to use internally.
       */
      void
      set_heightmap(
        noise::module::Module& land_generator,
        unsigned int texture_size = 2048 );

      /**@brief Specify the radius of the map.
       *
       * Set the radius of the map.
       * @param map_radius_in_m The new map radius in meters.
       */
      void
      set_radius(
        gl_real map_radius_in_m );

      /**@brief Specify the maximum elevation of the map.
       *
       * Set the maximum elevation of the map. This will be sent to the GPU
       * to compute a color depending on the height of a point.
       * @param maximum_elevation_in_m The new maximum elevation in meters.
       */
      void
      set_maximum_elevation(
        gl_real maximum_elevation_in_m );

    private:
      void
      update_gpu_data( ) override;

      void
      do_render( ) override;

      void
      remove_gpu_data() override;

      std::vector< gl_vec4 > m_normal_height_texture;
      gl_real m_map_radius;
      gl_real m_resolution;
      gl_real m_maximum_elevation;
      unsigned int m_texture_size;
      unsigned int m_number_of_patches;

      enum
      {
        positions_texcoords_vbo_id, indices_vbo_id, number_of_vbos
      };
      unsigned int m_vao;
      unsigned int m_vbos[number_of_vbos];
      unsigned int m_texture_id;
    };
  }
}
#endif /* ISLAND_H_ */


text:
package org.rundeck.client.tool.format;

import java.util.regex.Pattern;
import static org.rundeck.client.tool.format.NiceFormatter.NL;

public class PrefixFormatter implements OutputFormatter {
    final String prefix;
    final OutputFormatter base;
    private boolean truncateFinalNewline = true;

    public PrefixFormatter(final String prefix) {
        this.prefix = prefix;
        this.base = new ToStringFormatter();
    }

    public PrefixFormatter(final String prefix, final OutputFormatter base) {
        this.prefix = prefix;
        this.base = base;
    }

    @Override
    public String format(final Object o) {
        return addPrefix(prefix, null != base ? base.format(o) : o.toString());
    }

    private String addPrefix(final String prefix, final String text) {
        StringBuilder sb = new StringBuilder();
        indent(text, sb, true, prefix);
        return sb.toString();
    }

    private void indent(final String text, final StringBuilder sb, final boolean firstLine, final String prefix) {
        if (text.contains(NL)) {
            String[] split = text.split(Pattern.quote(NL), -1);
            int length = split.length;
            if (text.endsWith(NL)) {
                length--;
            }
            for (int i = 0; i < length; i++) {
                if (i > 0) {
                    sb.append(NL);
                }
                sb.append(prefix).append(split[i]);
            }
            if (text.endsWith(NL) && !isTruncateFinalNewline()) {
                sb.append(NL);
            }
        } else {
            sb.append(prefix).append(text);
        }
    }

    @Override
    public OutputFormatter withBase(final OutputFormatter base) {
        return new PrefixFormatter(prefix, base);
    }

    public boolean isTruncateFinalNewline() {
        return truncateFinalNewline;
    }

    public void setTruncateFinalNewline(boolean truncateFinalNewline) {
        this.truncateFinalNewline = truncateFinalNewline;
    }
}


text:
package org.apache.beam.sdk.extensions.ml;

import com.google.auto.value.AutoValue;
import com.google.cloud.language.v1.AnnotateTextRequest;
import com.google.cloud.language.v1.AnnotateTextResponse;
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.LanguageServiceClient;
import java.io.IOException;
import javax.annotation.Nullable;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;

/**
 * A {@link PTransform} using the Cloud AI Natural language processing capability. Takes an input
 * {@link PCollection} of {@link Document}s and converts them to {@link AnnotateTextResponse}s.
 *
 * <p>It is possible to provide a language hint to the API. A {@link
 * com.google.cloud.language.v1.AnnotateTextRequest.Features} object is required to configure
 * analysis types to be done on the data.
 */
@Experimental
@AutoValue
public abstract class AnnotateText
    extends PTransform<PCollection<Document>, PCollection<AnnotateTextResponse>> {

  @Nullable
  public abstract String languageHint();

  public abstract AnnotateTextRequest.Features features();

  @AutoValue.Builder
  public abstract static class Builder {
    public abstract Builder setLanguageHint(String hint);

    public abstract Builder setFeatures(AnnotateTextRequest.Features features);

    public abstract AnnotateText build();
  }

  public static Builder newBuilder() {
    return new AutoValue_AnnotateText.Builder();
  }

  @Override
  public PCollection<AnnotateTextResponse> expand(PCollection<Document> input) {
    return input.apply(ParDo.of(new CallLanguageApi(languageHint(), features())));
  }

  private static class CallLanguageApi extends DoFn<Document, AnnotateTextResponse> {
    private final String languageHint;
    private final AnnotateTextRequest.Features features;

    private CallLanguageApi(String languageHint, AnnotateTextRequest.Features features) {
      this.languageHint = languageHint;
      this.features = features;
    }

    @ProcessElement
    public void processElement(ProcessContext context) throws IOException {
      try (LanguageServiceClient client = LanguageServiceClient.create()) {
        Document element = context.element();
        if (languageHint != null) {
          element = element.toBuilder().setLanguage(languageHint).build();
        }
        AnnotateTextResponse output = client.annotateText(element, features);
        context.output(output);
      }
    }
  }
}


text:
<?php

declare(strict_types=1);

namespace PSR7SessionsTest\Storageless\Http;

use DateTime;
use DateTimeImmutable;
use Dflydev\FigCookies\FigResponseCookies;
use Dflydev\FigCookies\Modifier\SameSite;
use Dflydev\FigCookies\SetCookie;
use Laminas\Diactoros\Response;
use Laminas\Diactoros\ServerRequest;
use Lcobucci\Clock\FrozenClock;
use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
use PSR7Sessions\Storageless\Session\DefaultSessionData;
use PSR7Sessions\Storageless\Session\SessionInterface;
use PSR7SessionsTest\Storageless\Asset\MutableBadCookie;
use ReflectionProperty;
use function assert;
use function file_get_contents;
use function random_int;
use function time;
use function uniqid;

final class SessionMiddlewareTest extends TestCase
{
    /**
     * @see https://tools.ietf.org/html/rfc6265#section-4.1.2.5 for Secure flag
     * @see https://tools.ietf.org/html/rfc6265#section-4.1.2.6 for HttpOnly flag
     * @see https://github.com/psr7-sessions/storageless/pull/46 for / path
     * @see https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site for SameSite flag
     * @see https://tools.ietf.org/html/draft-ietf-httpbis-cookie-prefixes for __Secure- prefix
     *
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider defaultMiddlewaresProvider
     * @group #46
     */
    public function testDefaultMiddlewareConfiguresASecureCookie(callable $middlewareFactory) : void
    {
        $middleware = $middlewareFactory();
        $response   = $middleware->process(new ServerRequest(), $this->writingMiddleware());

        $cookie = $this->getCookie($response);

        self::assertTrue($cookie->getSecure());
        self::assertTrue($cookie->getHttpOnly());
        self::assertSame('/', $cookie->getPath());
        self::assertEquals(SameSite::lax(), $cookie->getSameSite());
        self::assertStringStartsWith('__Secure-', $cookie->getName());
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testSkipsInjectingSessionCookieOnEmptyContainer(callable $middlewareFactory) : void
    {
        $middleware = $middlewareFactory();
        $response   = $this->ensureSameResponse($middleware, new ServerRequest(), $this->emptyValidationMiddleware());

        self::assertNull($this->getCookie($response)->getValue());
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testExtractsSessionContainerFromEmptyRequest(callable $middlewareFactory) : void
    {
        $middleware = $middlewareFactory();
        $this->ensureSameResponse($middleware, new ServerRequest(), $this->emptyValidationMiddleware());
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testInjectsSessionInResponseCookies(callable $middlewareFactory) : void
    {
        $middleware      = $middlewareFactory();
        $initialResponse = new Response();
        $response        = $middleware->process(new ServerRequest(), $this->writingMiddleware());

        self::assertNotSame($initialResponse, $response);
        self::assertEmpty($this->getCookie($response, 'non-existing')->getValue());

        $token = $this->getCookie($response)->getValue();

        self::assertIsString($token);
        self::assertEquals((object) ['foo' => 'bar'], (new Parser())->parse($token)->getClaim('session-data'));
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testSessionContainerCanBeReusedOverMultipleRequests(callable $middlewareFactory) : void
    {
        $middleware   = $middlewareFactory();
        $sessionValue = uniqid('', true);

        $checkingMiddleware = $this->fakeDelegate(
            static function (ServerRequestInterface $request) use ($sessionValue) {
                $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
                assert($session instanceof SessionInterface);

                self::assertSame($sessionValue, $session->get('foo'));
                self::assertFalse($session->hasChanged());

                $session->set('foo', $sessionValue . 'changed');

                self::assertTrue(
                    $session->hasChanged(),
                    'ensuring that the cookie is sent again: '
                    . 'non-modified session containers are not to be re-serialized into a token'
                );

                return new Response();
            }
        );

        $firstResponse = $middleware->process(new ServerRequest(), $this->writingMiddleware($sessionValue));

        $response = $middleware->process(
            $this->requestWithResponseCookies($firstResponse),
            $checkingMiddleware
        );

        self::assertNotSame($response, $firstResponse);
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testSessionContainerCanBeCreatedEvenIfTokenDataIsMalformed(callable $middlewareFactory) : void
    {
        $middleware   = $middlewareFactory();
        $sessionValue = uniqid('not valid session data', true);

        $checkingMiddleware = $this->fakeDelegate(
            static function (ServerRequestInterface $request) use ($sessionValue) {
                $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
                assert($session instanceof SessionInterface);

                self::assertSame($sessionValue, $session->get('scalar'));
                self::assertFalse($session->hasChanged());

                return new Response();
            }
        );

        $this->createTokenWithCustomClaim(
            $middleware,
            new DateTime('-1 day'),
            new DateTime('+1 day'),
            'not valid session data'
        );

        $middleware->process(
            (new ServerRequest())
                ->withCookieParams([
                    SessionMiddleware::DEFAULT_COOKIE => $this->createTokenWithCustomClaim(
                        $middleware,
                        new DateTime('-1 day'),
                        new DateTime('+1 day'),
                        $sessionValue
                    ),
                ]),
            $checkingMiddleware
        );
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testWillIgnoreRequestsWithExpiredTokens(callable $middlewareFactory) : void
    {
        $middleware   = $middlewareFactory();
        $expiredToken = (new ServerRequest())
            ->withCookieParams([
                SessionMiddleware::DEFAULT_COOKIE => $this->createToken(
                    $middleware,
                    new DateTime('-1 day'),
                    new DateTime('-2 day')
                ),
            ]);

        $this->ensureSameResponse($middleware, $expiredToken, $this->emptyValidationMiddleware());
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testWillIgnoreRequestsWithTokensFromFuture(callable $middlewareFactory) : void
    {
        $middleware    = $middlewareFactory();
        $tokenInFuture = (new ServerRequest())
            ->withCookieParams([
                SessionMiddleware::DEFAULT_COOKIE => $this->createToken(
                    $middleware,
                    new DateTime('+1 day'),
                    new DateTime('-2 day')
                ),
            ]);

        $this->ensureSameResponse($middleware, $tokenInFuture, $this->emptyValidationMiddleware());
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testWillIgnoreUnSignedTokens(callable $middlewareFactory) : void
    {
        $middleware    = $middlewareFactory();
        $unsignedToken = (new ServerRequest())
            ->withCookieParams([
                SessionMiddleware::DEFAULT_COOKIE => (string) (new Builder())
                    ->setIssuedAt((new DateTime('-1 day'))->getTimestamp())
                    ->setExpiration((new DateTime('+1 day'))->getTimestamp())
                    ->set(SessionMiddleware::SESSION_CLAIM, DefaultSessionData::fromTokenData(['foo' => 'bar']))
                    ->getToken(),
            ]);

        $this->ensureSameResponse($middleware, $unsignedToken, $this->emptyValidationMiddleware());
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testWillNotRefreshSignedTokensWithoutIssuedAt(callable $middlewareFactory) : void
    {
        $middleware    = $middlewareFactory();
        $unsignedToken = (new ServerRequest())
            ->withCookieParams([
                SessionMiddleware::DEFAULT_COOKIE => (string) (new Builder())
                    ->setExpiration((new DateTime('+1 day'))->getTimestamp())
                    ->set(SessionMiddleware::SESSION_CLAIM, DefaultSessionData::fromTokenData(['foo' => 'bar']))
                    ->sign($this->getSigner($middleware), $this->getSignatureKey($middleware))
                    ->getToken(),
            ]);

        $this->ensureSameResponse($middleware, $unsignedToken);
    }

    public function testWillRefreshTokenWithIssuedAtExactlyAtTokenRefreshTimeThreshold() : void
    {
        // forcing ourselves to think of time as a mutable value:
        $time = time() + random_int(-100, +100);

        $clock = new FrozenClock(new DateTimeImmutable('@' . $time));

        $middleware = new SessionMiddleware(
            new Sha256(),
            'foo',
            'foo',
            SetCookie::create(SessionMiddleware::DEFAULT_COOKIE),
            new Parser(),
            1000,
            $clock,
            100
        );

        $requestWithTokenIssuedInThePast = (new ServerRequest())
            ->withCookieParams([
                SessionMiddleware::DEFAULT_COOKIE => (string) (new Builder())
                    ->setExpiration($time + 10000)
                    ->setIssuedAt($time - 100)
                    ->set(SessionMiddleware::SESSION_CLAIM, DefaultSessionData::fromTokenData(['foo' => 'bar']))
                    ->sign($this->getSigner($middleware), $this->getSignatureKey($middleware))
                    ->getToken(),
            ]);

        $tokenString = $this
            ->getCookie($middleware->process($requestWithTokenIssuedInThePast, $this->fakeDelegate(static function () {
                return new Response();
            })))
            ->getValue();

        self::assertIsString($tokenString);

        $token = (new Parser())->parse($tokenString);

        self::assertEquals($time, $token->getClaim(SessionMiddleware::ISSUED_AT_CLAIM), 'Token was refreshed');
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testWillSkipInjectingSessionCookiesWhenSessionIsNotChanged(callable $middlewareFactory) : void
    {
        $middleware = $middlewareFactory();
        $this->ensureSameResponse(
            $middleware,
            $this->requestWithResponseCookies(
                $middleware->process(new ServerRequest(), $this->writingMiddleware())
            ),
            $this->fakeDelegate(
                static function (ServerRequestInterface $request) {
                    $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
                    assert($session instanceof SessionInterface);

                    // note: we set the same data just to make sure that we are indeed interacting with the session
                    $session->set('foo', 'bar');

                    self::assertFalse($session->hasChanged());

                    return new Response();
                }
            )
        );
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testWillSendExpirationCookieWhenSessionContentsAreCleared(callable $middlewareFactory) : void
    {
        $middleware = $middlewareFactory();
        $this->ensureClearsSessionCookie(
            $middleware,
            $this->requestWithResponseCookies(
                $middleware->process(new ServerRequest(), $this->writingMiddleware())
            ),
            $this->fakeDelegate(
                static function (ServerRequestInterface $request) {
                    $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
                    assert($session instanceof SessionInterface);

                    $session->clear();

                    return new Response();
                }
            )
        );
    }

    /**
     * @param callable(): SessionMiddleware $middlewareFactory
     *
     * @dataProvider validMiddlewaresProvider
     */
    public function testWillIgnoreMalformedTokens(callable $middlewareFactory) : void
    {
        $middleware = $middlewareFactory();
        $this->ensureSameResponse(
            $middleware,
            (new ServerRequest())->withCookieParams([SessionMiddleware::DEFAULT_COOKIE => 'malformed content']),
            $this->emptyValidationMiddleware()
        );
    }

    public function testRejectsTokensWithInvalidSignature() : void
    {
        $middleware = new SessionMiddleware(
            new Sha256(),
            'foo',
            'bar', // wrong symmetric key (on purpose)
            SetCookie::create(SessionMiddleware::DEFAULT_COOKIE),
            new Parser(),
            100,
            new SystemClock()
        );

        $this->ensureSameResponse(
            $middleware,
            $this->requestWithResponseCookies(
                $middleware->process(new ServerRequest(), $this->writingMiddleware())
            ),
            $this->emptyValidationMiddleware()
        );
    }

    public function testAllowsModifyingCookieDetails() : void
    {
        $defaultCookie = SetCookie::create('a-different-cookie-name')
            ->withDomain('foo.bar')
            ->withPath('/yadda')
            ->withHttpOnly(false)
            ->withMaxAge(123123)
            ->withValue('a-random-value');

        $dateTime   = new DateTimeImmutable();
        $middleware = new SessionMiddleware(
            new Sha256(),
            'foo',
            'foo',
            $defaultCookie,
            new Parser(),
            123456,
            new FrozenClock($dateTime),
            123
        );

        $response = $middleware->process(new ServerRequest(), $this->writingMiddleware());

        self::assertNull($this->getCookie($response)->getValue());

        $tokenCookie = $this->getCookie($response, 'a-different-cookie-name');

        self::assertNotEmpty($tokenCookie->getValue());
        self::assertNotSame($defaultCookie->getValue(), $tokenCookie->getValue());
        self::assertSame($defaultCookie->getDomain(), $tokenCookie->getDomain());
        self::assertSame($defaultCookie->getPath(), $tokenCookie->getPath());
        self::assertSame($defaultCookie->getHttpOnly(), $tokenCookie->getHttpOnly());
        self::assertSame($defaultCookie->getMaxAge(), $tokenCookie->getMaxAge());
        self::assertEquals($dateTime->getTimestamp() + 123456, $tokenCookie->getExpires());
    }

    public function testSessionTokenParsingIsDelayedWhenSessionIsNotBeingUsed() : void
    {
        $signer = $this->createMock(Signer::class);

        $signer->expects(self::never())->method('verify');
        $signer->method('getAlgorithmId')->willReturn('HS256');

        $currentTimeProvider = new SystemClock();
        $setCookie           = SetCookie::create(SessionMiddleware::DEFAULT_COOKIE);
        $middleware          = new SessionMiddleware($signer, 'foo', 'foo', $setCookie, new Parser(), 100, $currentTimeProvider);
        $request             = (new ServerRequest())
            ->withCookieParams([
                SessionMiddleware::DEFAULT_COOKIE => (string) (new Builder())
                    ->set(SessionMiddleware::SESSION_CLAIM, DefaultSessionData::fromTokenData(['foo' => 'bar']))
                    ->setIssuedAt(time())
                    ->sign(new Sha256(), 'foo')
                    ->getToken(),
            ]);

        $middleware->process(
            $request,
            $this->fakeDelegate(static function (ServerRequestInterface $request) {
                self::assertInstanceOf(
                    SessionInterface::class,
                    $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE)
                );

                return new Response();
            })
        );
    }

    public function testShouldRegenerateTokenWhenRequestHasATokenThatIsAboutToExpire() : void
    {
        $dateTime   = new DateTimeImmutable();
        $middleware = new SessionMiddleware(
            new Sha256(),
            'foo',
            'foo',
            SetCookie::create(SessionMiddleware::DEFAULT_COOKIE),
            new Parser(),
            1000,
            new FrozenClock($dateTime),
            300
        );

        $expiringToken = (new ServerRequest())
            ->withCookieParams([
                SessionMiddleware::DEFAULT_COOKIE => (string) (new Builder())
                    ->setIssuedAt((new DateTime('-800 second'))->getTimestamp())
                    ->setExpiration((new DateTime('+200 second'))->getTimestamp())
                    ->set(SessionMiddleware::SESSION_CLAIM, DefaultSessionData::fromTokenData(['foo' => 'bar']))
                    ->sign($this->getSigner($middleware), $this->getSignatureKey($middleware))
                    ->getToken(),
            ]);

        $initialResponse = new Response();

        $response = $middleware->process($expiringToken, $this->fakeDelegate(static function () use ($initialResponse) {
            return $initialResponse;
        }));

        self::assertNotSame($initialResponse, $response);

        $tokenCookie = $this->getCookie($response);

        self::assertNotEmpty($tokenCookie->getValue());
        self::assertEquals($dateTime->getTimestamp() + 1000, $tokenCookie->getExpires());
    }

    public function testShouldNotRegenerateTokenWhenRequestHasATokenThatIsFarFromExpiration() : void
    {
        $middleware = new SessionMiddleware(
            new Sha256(),
            'foo',
            'foo',
            SetCookie::create(SessionMiddleware::DEFAULT_COOKIE),
            new Parser(),
            1000,
            new SystemClock(),
            300
        );

        $validToken = (new ServerRequest())
            ->withCookieParams([
                SessionMiddleware::DEFAULT_COOKIE => (string) (new Builder())
                    ->setIssuedAt((new DateTime('-100 second'))->getTimestamp())
                    ->setExpiration((new DateTime('+900 second'))->getTimestamp())
                    ->set(SessionMiddleware::SESSION_CLAIM, DefaultSessionData::fromTokenData(['foo' => 'bar']))
                    ->sign($this->getSigner($middleware), $this->getSignatureKey($middleware))
                    ->getToken(),
            ]);

        $this->ensureSameResponse($middleware, $validToken);
    }

    /**
     * @return array<array<callable(): SessionMiddleware>>
     */
    public function validMiddlewaresProvider() : array
    {
        return $this->defaultMiddlewaresProvider() + [
            [static function () : SessionMiddleware {
                return new SessionMiddleware(
                    new Sha256(),
                    'foo',
                    'foo',
                    SetCookie::create(SessionMiddleware::DEFAULT_COOKIE),
                    new Parser(),
                    100,
                    new SystemClock()
                );
            },
            ],
        ];
    }

    /**
     * @return array<array<callable(): SessionMiddleware>>
     */
    public function defaultMiddlewaresProvider() : array
    {
        return [
            [static function () : SessionMiddleware {
                return SessionMiddleware::fromSymmetricKeyDefaults('not relevant', 100);
            },
            ],
            [static function () : SessionMiddleware {
                return SessionMiddleware::fromAsymmetricKeyDefaults(
                    self::privateKey(),
                    self::publicKey(),
                    200
                );
            },
            ],
        ];
    }

    public function testMutableCookieWillNotBeUsed() : void
    {
        $cookie = MutableBadCookie::create(SessionMiddleware::DEFAULT_COOKIE);

        assert($cookie instanceof MutableBadCookie);

        $middleware = new SessionMiddleware(
            new Sha256(),
            'foo',
            'foo',
            $cookie,
            new Parser(),
            1000,
            new SystemClock()
        );

        $cookie->mutated = true;

        self::assertStringStartsWith(
            '__Secure-slsession=',
            $middleware
                ->process(new ServerRequest(), $this->writingMiddleware())
                ->getHeaderLine('Set-Cookie')
        );
    }

    private function ensureSameResponse(
        SessionMiddleware $middleware,
        ServerRequestInterface $request,
        ?RequestHandlerInterface $next = null
    ) : ResponseInterface {
        $initialResponse = new Response();

        $handleRequest = $this->createMock(RequestHandlerInterface::class);

        if ($next === null) {
            $handleRequest
                ->expects(self::once())
                ->method('handle')
                ->willReturn($initialResponse);
        } else {
            // capturing `$initialResponse` from the `$next` handler
            $handleRequest
                ->expects(self::once())
                ->method('handle')
                ->willReturnCallback(static function (ServerRequestInterface $serverRequest) use ($next, & $initialResponse) {
                    $response = $next->handle($serverRequest);

                    $initialResponse = $response;

                    return $response;
                });
        }

        $response = $middleware->process($request, $handleRequest);

        self::assertSame($initialResponse, $response);

        return $response;
    }

    private function ensureClearsSessionCookie(
        SessionMiddleware $middleware,
        ServerRequestInterface $request,
        RequestHandlerInterface $next
    ) : ResponseInterface {
        $response = $middleware->process($request, $next);

        $cookie = $this->getCookie($response);

        self::assertLessThan((new DateTime('-29 day'))->getTimestamp(), $cookie->getExpires());
        self::assertEmpty($cookie->getValue());

        return $response;
    }

    private function createToken(SessionMiddleware $middleware, DateTime $issuedAt, DateTime $expiration) : string
    {
        return (string) (new Builder())
            ->setIssuedAt($issuedAt->getTimestamp())
            ->setExpiration($expiration->getTimestamp())
            ->set(SessionMiddleware::SESSION_CLAIM, DefaultSessionData::fromTokenData(['foo' => 'bar']))
            ->sign($this->getSigner($middleware), $this->getSignatureKey($middleware))
            ->getToken();
    }

    /** @param mixed $claim */
    private function createTokenWithCustomClaim(
        SessionMiddleware $middleware,
        DateTime $issuedAt,
        DateTime $expiration,
        $claim
    ) : string {
        return (string) (new Builder())
            ->setIssuedAt($issuedAt->getTimestamp())
            ->setExpiration($expiration->getTimestamp())
            ->set(SessionMiddleware::SESSION_CLAIM, $claim)
            ->sign($this->getSigner($middleware), $this->getSignatureKey($middleware))
            ->getToken();
    }

    private function emptyValidationMiddleware() : RequestHandlerInterface
    {
        return $this->fakeDelegate(
            static function (ServerRequestInterface $request) {
                $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);

                self::assertInstanceOf(SessionInterface::class, $session);
                self::assertTrue($session->isEmpty());

                return new Response();
            }
        );
    }

    private function writingMiddleware(string $value = 'bar') : RequestHandlerInterface
    {
        return $this->fakeDelegate(
            static function (ServerRequestInterface $request) use ($value) {
                $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
                assert($session instanceof SessionInterface);
                $session->set('foo', $value);

                return new Response();
            }
        );
    }

    private function fakeDelegate(callable $callback) : RequestHandlerInterface
    {
        $middleware = $this->createMock(RequestHandlerInterface::class);

        $middleware
            ->expects(self::once())
           ->method('handle')
           ->willReturnCallback($callback)
           ->with(self::isInstanceOf(RequestInterface::class));

        return $middleware;
    }

    /**
     * @return ServerRequest
     */
    private function requestWithResponseCookies(ResponseInterface $response) : ServerRequestInterface
    {
        return (new ServerRequest())->withCookieParams([
            SessionMiddleware::DEFAULT_COOKIE => $this->getCookie($response)->getValue(),
        ]);
    }

    private function getCookie(ResponseInterface $response, string $name = SessionMiddleware::DEFAULT_COOKIE) : SetCookie
    {
        return FigResponseCookies::get($response, $name);
    }

    private function getSigner(SessionMiddleware $middleware) : Signer
    {
        $property = new ReflectionProperty(SessionMiddleware::class, 'signer');

        $property->setAccessible(true);

        return $property->getValue($middleware);
    }

    private function getSignatureKey(SessionMiddleware $middleware) : string
    {
        $property = new ReflectionProperty(SessionMiddleware::class, 'signatureKey');

        $property->setAccessible(true);

        return $property->getValue($middleware);
    }

    private static function privateKey() : string
    {
        $key = file_get_contents(__DIR__ . '/../../keys/private_key.pem');

        self::assertIsString($key);

        return $key;
    }

    private static function publicKey() : string
    {
        $key = file_get_contents(__DIR__ . '/../../keys/public_key.pem');

        self::assertIsString($key);

        return $key;
    }
}


text:
<?php

namespace IrishDan\NotificationBundle\Repository;

use IrishDan\NotificationBundle\DatabaseNotifiableInterface;

interface DatabaseNotificationRepositoryInterface
{
    public function getNotificationsCount(DatabaseNotifiableInterface $user, $status = '');

    public function getUnreadNotifications(DatabaseNotifiableInterface $user);
}


text:
#ifndef WebGeolocationPermissionRequest_h
#define WebGeolocationPermissionRequest_h

#include "../platform/WebCommon.h"
#include "../platform/WebPrivatePtr.h"

namespace WebCore {
class Geolocation;
}

namespace WebKit {
class WebSecurityOrigin;

// WebGeolocationPermissionRequest encapsulates a WebCore Geolocation object and represents
// a request from WebCore for permission to be determined for that Geolocation object.
// The underlying Geolocation object is guaranteed to be valid until the invocation of
// either  WebGeolocationPermissionRequest::setIsAllowed (request complete) or
// WebGeolocationClient::cancelPermissionRequest (request cancelled).
class WebGeolocationPermissionRequest {
public:
    WEBKIT_EXPORT WebSecurityOrigin securityOrigin() const;
    WEBKIT_EXPORT void setIsAllowed(bool);

#if WEBKIT_IMPLEMENTATION
    WebGeolocationPermissionRequest(WebCore::Geolocation* geolocation)
        : m_private(geolocation)
    {
    }

    WebCore::Geolocation* geolocation() const { return m_private; }
#endif

private:
    WebCore::Geolocation* m_private;
};
}

#endif // WebGeolocationPermissionRequest_h


text:
module('Ajax and Promise');

test('Basic test for Promise, 1 done method is run.', 2, function() {
    stop();
    html.Promise(function(res, rej) {
        setTimeout(function() {
            res('Ok, got the data.');
            start();
        },5);
    })
    .done(function(data){
        ok(1, 'Should run done method, not fail.');
        ok(data === 'Ok, got the data.', 'Correct message.');
    })
    .fail(function(data) {
        ok(1, 'Shouldn\' reach here.');
    });
});

test('Basic test for Promise, 2 done methods are run.', 2, function() {
    stop();
    var message = 'Ok, got the data.';
    html.Promise(function(res, rej) {
        setTimeout(function() {
            res(message);
            start();
        },5);
    })
    .done(function(data){
        equal(data, message, 'Ok, got the data at first done method.');
    })
    .done(function(data){
        equal(data, message, 'Ok, got the data at second done method.');
    })
    .fail(function(data) {
        ok(1, 'Shouldn\' reach here.');
    });
});

test('Test for Promise, fail method is run.', 1, function() {
    var message = 'Oop, fail.';
    stop();
    var promise = html.Promise(function(res, rej) {
        setTimeout(function() {
            rej(message);
            start();
        }, 5);
    })
    .done(function(data){
        equal(data, message, 'Ok, got the data at first done method.');
    })
    .fail(function(data) {
        equal(data, message, 'Fail method run.');
    });
});

test('Test for Promise, 2 fail methods run.', 2, function() {
    var message = 'Oop, fail.';
    stop();
    var promise = html.Promise(function(res, rej) {
        setTimeout(function() {
            rej(message);
            start();
        }, 5);
    })
    .done(function(data){
        equal(data, message, 'Should not run here.');
    })
    .fail(function(data) {
        equal(data, message, 'Fail method run first time.');
    })
    .fail(function(data) {
        equal(data, message, 'Fail method run second time.');
    });
});

test('Test for Promise, mock done data.', 1, function() {
    var message = 'Done, did it.';
    stop();
    var promise = html.Promise(function(res, rej) {
        setTimeout(function() {
            res('The true data from server.');
        }, 5);
    })
    .mockDone(message)
    .done(function(data){
        equal(data, message, 'Great, data from mocking object.');
        start();
    })
    .fail(function(data) {
        equal(data, message, 'Fail method should not run.');
    });
});

test('Test for Promise, mock done data, 2 done callback.', 2, function() {
    var message = 'Done, did it.';
    stop();
    var promise = html.Promise(function(res, rej) {
        setTimeout(function() {
            res('The true data from server.');
        }, 5);
    })
    .mockDone(message)
    .done(function(data){
        equal(data, message, 'Great, data from mocking object.');
        start();
    })
    .done(function(data){
        equal(data, message, 'Great, data from mocking object, second run.');
    })
    .fail(function(data) {
        equal(data, message, 'Fail method should not run.');
    });
});

test('Test get json - get testData.json and testData2.json', 4, function() {
    stop();
    var mockData = {"firstName":"Nhan","lastName":"Nguyen"},
        mockData2 = {"framework":"html","version":"0.1"};

    html.ajax('testData.json')
	.parser(JSON.parse)
    .done(function(data) {
        equal(JSON.stringify(mockData), JSON.stringify(data), 'Get the expected data from testData.json.');
        ok(data, 'Ok, data from ajax in html.ajax is not null.');
        start();
    });
    stop();
    html.ajax('testData2.json')
	.parser(JSON.parse)
    .done(function(data) {
        equal(JSON.stringify(mockData2), JSON.stringify(data), 'Get the expected data from testData2.json.');
        ok(data, 'Ok, data from ajax html.ajax is not null.');
        start();
    });
});

test('Basic setup for getting JSON, test done method and mockDone', 1, function() {
    stop();
    var mockDoneData = 'Ok, got the mock data.';
        html.getJSON('/someurlhere')
        .mockDone(mockDoneData)
        .done(function(data) {
            ok(JSON.stringify(mockDoneData) === JSON.stringify(data), 'Got the mock data.');
            start();
        });
});

test('Basic setup for getting JSON, test fail method and mockFail', 1, function() {
    stop();
    var mockFailReason = 'Can not get the data from server.';
        html.getJSON('testData.json')
        .mockFail(mockFailReason)
        .fail(function(data) {
            ok(JSON.stringify(mockFailReason) === JSON.stringify(data), 'Error occurs when getting data from server.');
            start();
        });
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>Mesa Source Tree</title>
  <link rel="stylesheet" type="text/css" href="mesa.css">

Mesa source code tree overview

This is a brief summary of Mesa's directory tree and what's contained in
each directory.

docs - Documentation

include - Public OpenGL header files

src

egl - EGL library sources

docs - EGL documentation

drivers - EGL drivers

glsl - the GLSL compiler

main - main EGL library implementation.  This is where all
        the EGL API functions are implemented, like eglCreateContext().

mesa - Main Mesa sources

glapi - OpenGL API dispatch layer.  This is where all the
        GL entrypoints like glClear, glBegin, etc. are generated, as well as
        the GL dispatch table.  All GL function calls jump through the
        dispatch table to functions found in main/.

main - The core Mesa code (mainly state management)

drivers - Mesa drivers (not used with Gallium)

common - code which may be shared by all drivers

dri - Direct Rendering Infrastructure drivers

common - code shared by all DRI drivers

i915 - driver for Intel i915/i945

i965 - driver for Intel i965

radeon - driver for ATI R100

r200 - driver for ATI R200

XXX more

x11 - Xlib-based software driver

osmesa - off-screen software driver

glslcompiler - a stand-alone GLSL compiler driver

XXX more

es - OpenGL ES overlay, parallelly buildable with the core Mesa

math - vertex array translation and transformation code
        (not used with Gallium)

ppc - Assembly code/optimizations for PPC systems
        (not used with Gallium)

shader - Vertex/fragment shader and GLSL compiler code

sparc - Assembly code/optimizations for SPARC systems
        (not used with Gallium)

state_tracker - State tracker / driver for Gallium.  This
        is basically a Mesa device driver that speaks to Gallium.  This
        directory may be moved to src/mesa/drivers/gallium at some point.

swrast - Software rasterization module.  For drawing points,
        lines, triangles, bitmaps, images, etc. in software.
        (not used with Gallium)

swrast_setup - Software primitive setup.  Does things like
        polygon culling, glPolygonMode, polygon offset, etc.
        (not used with Gallium)

tnl - Software vertex Transformation 'n Lighting.
        (not used with Gallium)

tnl_dd - TNL code for device drivers.
        (not used with Gallium)

vbo - Vertex Buffer Object code.  All drawing with
        glBegin/glEnd, glDrawArrays, display lists, etc. goes through this
        module.  The results is a well-defined set of vertex arrays which
        are passed to the device driver (or tnl module) for rendering.

vf - vertex format conversion (currently unused)

x86 - Assembly code/optimizations for 32-bit x86 systems
        (not used with Gallium)

x86-64 - Assembly code/optimizations for 64-bit x86 systems
        (not used with Gallium)

gallium - Gallium3D source code

include - Gallium3D header files which define the Gallium3D
        interfaces

drivers - Gallium3D device drivers

i915 - Driver for Intel i915/i945.

llvmpipe - Software driver using LLVM for runtime code generation.

nv* - Drivers for NVIDIA GPUs.

radeonsi - Driver for AMD Southern Island.

r300 - Driver for ATI R300 - R500.

r600 - Driver for ATI/AMD R600 - Northern Island.

softpipe - Software reference driver.

svga - Driver for VMware's SVGA virtual GPU.

trace - Driver for tracing Gallium calls.

XXX more

auxiliary - Gallium support code

draw - Software vertex processing and primitive assembly
          module.  This includes vertex program execution, clipping, culling
          and optional stages for drawing wide lines, stippled lines,
          polygon stippling, two-sided lighting, etc.
          Intended for use by drivers for hardware that does not have
          vertex shaders.
          Geometry shaders will also be implemented in this module.

cso_cache - Constant State Objects Cache.  Used to filter out
          redundant state changes between state trackers and drivers.

gallivm - LLVM module for Gallium.  For LLVM-based
           compilation, optimization and code generation for TGSI shaders.
           Incomplete.

pipebuffer - utility module for managing buffers

rbug - Gallium remote debug utility

rtasm - run-time assembly/machine code generation.
          Currently there's run-time code generation for x86/SSE, PowerPC
          and Cell SPU.

tgsi - TG Shader Infrastructure.  Code for encoding,
          manipulating and interpretting GPU programs.

translate - module for translating vertex data from one format
          to another.

util - assorted utilities for arithmetic, hashing, surface
          creation, memory management, 2D blitting, simple rendering, etc.

state_trackers -

dri - Meta state tracker for DRI drivers

egl - Meta state tracker for EGL drivers

es - OpenGL ES 1.x and 2.x state trackers

glx - Meta state tracker for GLX

vdpau - VDPAU state tracker

vega - OpenVG 1.x state tracker

wgl -

xorg - Meta state tracker for Xorg video drivers

winsys -

drm -

gdi -

xlib -

glx - The GLX library code for building libGL.  This is used for
         direct rendering drivers.  It will dynamically load one of the
         xxx_dri.so drivers.

progs - OpenGL test and demonstration programs

lib - where the GL libraries are placed


text:
import os

readme = os.path.join(os.path.dirname(__file__), 'README.rst')
LONG_DESCRIPTION = open(readme, 'r').read()

params = dict(
    name='apysigner',
    version='3.0.1',
    url='https://github.com/madisona/apysigner',
    license='BSD',
    author='Aaron Madison',
    author_email='aaron.l.madison@gmail.com',
    description='Basic API request signing',
    long_description=LONG_DESCRIPTION,
    py_modules=['apysigner'],
    install_requires=['six'],

    zip_safe=False,
    classifiers = [
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3.5",
        "Topic :: Software Development",
        "Topic :: Software Development :: Libraries :: Application Frameworks",
        "Topic :: Software Development :: Libraries :: Python Modules",
        ],
)

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup
else:
    params['tests_require'] = ['unittest2', 'mock']
    params['test_suite'] = 'unittest2.collector'

setup(**params)


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.example.android.displayingbitmaps;

/**
 *
 * @author JosephWang
 */
public class BuildConfig
{
    public static boolean DEBUG = true;
}


text:
sheaf::poset_bounds_descriptor::
poset_bounds_descriptor()
{
  // Preconditions:

  // Body:

  _mode  = NOT_A_MODE;
  _lb_id = invalid_pod_index();
  _ub_id = invalid_pod_index();

  // Postconditions:

  ensure(invariant());
  ensure(mode() == NOT_A_MODE);
  ensure(!is_valid(lb_id()));
  ensure(!is_valid(ub_id()));

  // Exit

  return;
}

sheaf::poset_bounds_descriptor::
poset_bounds_descriptor(const poset_bounds_descriptor& xother)
{
  // Preconditions:

  // Body:

  *this = xother;

  // Postconditions:

  ensure(invariant());
  ensure(*this == xother);
}

sheaf::poset_bounds_descriptor&
sheaf::poset_bounds_descriptor::
operator=(const poset_bounds_descriptor& xother)
{

  // Preconditions:

  // Body:

  _mode  = xother._mode;
  _lb_id = xother._lb_id;
  _ub_id = xother._ub_id;

  // Postconditions:

  ensure(invariant());
  ensure(*this == xother);

  // Exit:

  return *this;
}

bool
sheaf::poset_bounds_descriptor::
operator==(const poset_bounds_descriptor& xother) const
{
  bool result;

  // Preconditions:

  // Body:

  result =
    (_mode  == xother._mode) &&
    (_lb_id == xother._lb_id) &&
    (_ub_id == xother._ub_id);

  // Postconditions:

  ensure(invariant());

  // Exit:

  return result;
}

sheaf::poset_bounds_descriptor*
sheaf::poset_bounds_descriptor::
clone() const
{
  poset_bounds_descriptor* result;

  // Preconditions:

  // Body:

  result = new poset_bounds_descriptor(*this);

  // Postconditions:

  ensure(result != 0);
  ensure(is_same_type(result));

  // Exit:

  return result;
}

sheaf::poset_bounds_descriptor::
~poset_bounds_descriptor()
{

  // Preconditions:

  // Body:

  // Postconditions:

  // Exit:

  return;
}

bool
sheaf::poset_bounds_descriptor::
invariant() const
{
  bool result = true;

  // Preconditions:

  // Body:

  // Must satisfy base class invariant

  result = result && any::invariant();

  if(invariant_check())
  {
    // Prevent recursive calls to invariant

    disable_invariant_check();

    /// @issue are there any clauses in this invariant?
    /// @todo finish poset_bounds_descriptor::invariant.

    // Finished, turn invariant checking back on.

    enable_invariant_check();
  }

  // Postconditions:

  // Exit

  return result;
}

bool
sheaf::poset_bounds_descriptor::
is_ancestor_of(const any* other) const
{

  // Preconditions:

  require(other != 0);

  // Body:

  // True if other conforms to this

  bool result = dynamic_cast<const poset_bounds_descriptor*>(other) != 0;

  // Postconditions:

  return result;

}

// POSET_BOUNDS_DESCRIPTOR FACET

int
sheaf::poset_bounds_descriptor::
mode_to_int(specification_mode xmode)
{
  int result;

  // Preconditions:

  // Body:

  /// @issue The C++ standard says this map is unnecessary.
  /// But we've implemented anyway, just in case not all
  /// compilers follow the standard.

  switch(xmode)
  {
  case MEMBER_MEMBER:
    result = 0;
    break;
  case MEMBER_SUBPOSET:
    result = 1;
    break;
  case SUBPOSET_MEMBER:
    result = 2;
    break;
  case SUBPOSET_SUBPOSET:
    result = 3;
    break;
  default:
    post_fatal_error_message("unrecognized specification mode");
    break;
  }

  // Postconditions:

  // Exit

  return result;
}

sheaf::poset_bounds_descriptor::specification_mode
sheaf::poset_bounds_descriptor::
int_to_mode(int xmode)
{
  specification_mode result;

  // Preconditions:

  require((0 <= xmode) && (xmode <= 3));

  // Body:

  switch(xmode)
  {
  case 0:
    result = MEMBER_MEMBER;
    break;
  case 1:
    result = MEMBER_SUBPOSET;
    break;
  case 2:
    result = SUBPOSET_MEMBER;
    break;
  case 3:
    result = SUBPOSET_SUBPOSET;
    break;
  }

  // Postconditions:

  // Exit

  return result;
}

sheaf::poset_bounds_descriptor::
poset_bounds_descriptor(specification_mode xmode,
                        pod_index_type xlb_id,
                        pod_index_type xub_id)
    : _mode(xmode),
      _lb_id(xlb_id),
      _ub_id(xub_id)
{
  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());
  ensure(mode()  == xmode);
  ensure(lb_id() == xlb_id);
  ensure(ub_id() == xub_id);

  // Exit

  return;
}

sheaf::poset_bounds_descriptor::
poset_bounds_descriptor(specification_mode xmode,
                        const scoped_index& xlb_id,
                        const scoped_index& xub_id)
    : _mode(xmode),
      _lb_id(xlb_id.hub_pod()),
      _ub_id(xub_id.hub_pod())
{
  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());
  ensure(mode()  == xmode);
  ensure(lb_id() == xlb_id.hub_pod());
  ensure(ub_id() == xub_id.hub_pod());

  // Exit

  return;
}

sheaf::poset_bounds_descriptor::specification_mode
sheaf::poset_bounds_descriptor::
mode() const
{
  specification_mode result;

  // Preconditions:

  // Body:

  result = _mode;

  // Postconditions:

  // Can't call invariant because it's not const
  // ensure(invariant());

  // Exit

  return result;
}

bool
sheaf::poset_bounds_descriptor::
lb_is_member() const
{
  bool result;

  // Preconditions:

  // Body:

  result = ((mode() == MEMBER_MEMBER) || (mode() == MEMBER_SUBPOSET));

  // Postconditions:

  // Can't call invariant because it's not const
  //  ensure(invariant());
  ensure(result == ((mode() == MEMBER_MEMBER) || (mode() == MEMBER_SUBPOSET)));

  // Exit

  return result;
}

bool
sheaf::poset_bounds_descriptor::
ub_is_member() const
{
  bool result;

  // Preconditions:

  // Body:

  result = ((mode() == MEMBER_MEMBER) || (mode() == SUBPOSET_MEMBER));

  // Postconditions:

  // Can't call invariant because it's not const
  //  ensure(invariant());
  ensure(result == ((mode() == MEMBER_MEMBER) || (mode() == SUBPOSET_MEMBER)));

  // Exit

  return result;
}

sheaf::pod_index_type
sheaf::poset_bounds_descriptor::
lb_id() const
{
  return _lb_id;
}

void
sheaf::poset_bounds_descriptor::
put_lb_id(pod_index_type xlb_id)
{
  // Preconditions:

  // Body:

  _lb_id = xlb_id;

  // Postconditions:

  ensure(lb_id() == xlb_id);

  // Exit:

  return;
}

void
sheaf::poset_bounds_descriptor::
put_lb_id(const scoped_index& xlb_id)
{
  // Preconditions:

  // Body:

  _lb_id = xlb_id.hub_pod();

  // Postconditions:

  ensure(lb_id() == xlb_id.hub_pod());

  // Exit:

  return;
}

sheaf::pod_index_type
sheaf::poset_bounds_descriptor::
ub_id() const
{
  return _ub_id;
}

void
sheaf::poset_bounds_descriptor::
put_ub_id(pod_index_type xub_id)
{
  // Preconditions:

  // Body:

  _ub_id = xub_id;

  // Postconditions:

  ensure(ub_id() == xub_id);

  // Exit:

  return;
}

void
sheaf::poset_bounds_descriptor::
put_ub_id(const scoped_index& xub_id)
{
  // Preconditions:

  // Body:

  _ub_id = xub_id.hub_pod();

  // Postconditions:

  ensure(ub_id() == xub_id.hub_pod());

  // Exit:

  return;
}

bool
sheaf::poset_bounds_descriptor::
lb_is_valid_for(const poset_state_handle& xposet) const
{
  bool result = true;

  // Preconditions:

  require(xposet.state_is_read_accessible());

  // Body:

  if(lb_is_member())
  {
    result = xposet.contains_member(lb_id());
  }
  else
  {
    result =
      lb_id() == TOC_INDEX || xposet.includes_subposet(lb_id());
  }

  // Postconditions:

  // Can't call invariant because it's not const
  //  ensure(invariant());
  ensure(lb_is_member() ? xposet.contains_member(lb_id()) : true);

  ensure(!lb_is_member() ?
         (lb_id() == TOC_INDEX) || xposet.includes_subposet(lb_id()) :
         true);

  // Exit

  return result;
}

bool
sheaf::poset_bounds_descriptor::
ub_is_valid_for(const poset_state_handle& xposet) const
{
  bool result = true;

  // Preconditions:

  require(xposet.state_is_read_accessible());

  // Body:

  result = (ub_is_member() ?
            xposet.contains_member(ub_id()) :
            xposet.includes_subposet(ub_id()));

  // Postconditions:

  // Can't call invariant because it's not const
  //  ensure(invariant());
  ensure(result == (ub_is_member() ?
                    xposet.contains_member(ub_id()) :
                    xposet.includes_subposet(ub_id())));

  // Exit

  return result;
}

bool
sheaf::poset_bounds_descriptor::
is_valid_for(const poset_state_handle& xposet) const
{
  bool result = true;

  // Preconditions:

  require(xposet.state_is_read_accessible());

  // Body:

  result = (lb_is_valid_for(xposet) && ub_is_valid_for(xposet));

  // Postconditions:

  // Can't call invariant because it's not const
  //  ensure(invariant());
  ensure(result == (lb_is_valid_for(xposet) && ub_is_valid_for(xposet)));

  // Exit

  return result;
}

bool
sheaf::poset_bounds_descriptor::
lb_member_is_bottom() const
{
  bool result;

  // Preconditions:

  // Body:

  result = (lb_is_member() && (lb_id() == BOTTOM_INDEX));

  // Postconditions:

  // Can't call invariant because it's not const
  //  ensure(invariant());

  ensure(result == (lb_is_member() && (lb_id() == BOTTOM_INDEX)));

  // Exit

  return result;
}

bool
sheaf::poset_bounds_descriptor::
ub_member_is_not_top() const
{
  bool result = true;

  // Preconditions:

  // Body:

  result = (ub_is_member() && (ub_id() != TOP_INDEX));

  // Postconditions:

  // Can't call invariant because it's not const
  //  ensure(invariant());

  ensure(result == (ub_is_member() && (ub_id() != TOP_INDEX)));

  // Exit

  return result;
}

const sheaf::poset_bounds_descriptor&
sheaf::poset_bounds_descriptor::
BOTTOM_TOP = *(new poset_bounds_descriptor(MEMBER_MEMBER, BOTTOM_INDEX, TOP_INDEX));

const sheaf::poset_bounds_descriptor&
sheaf::poset_bounds_descriptor::
BOTTOM_BOTTOM = *(new poset_bounds_descriptor(MEMBER_MEMBER, BOTTOM_INDEX, BOTTOM_INDEX));


text:
'use strict';

//Setting up route
angular.module('party-masters').config(['$stateProvider',
	function($stateProvider) {
		// Party masters state routing
		$stateProvider.
		state('listPartyMasters', {
			url: '/party-masters',
			templateUrl: 'modules/party-masters/views/list-party-masters.client.view.html'
		}).
		state('createPartyMaster', {
			url: '/party-masters/create',
			templateUrl: 'modules/party-masters/views/create-party-master.client.view.html'
		}).
		state('viewPartyMaster', {
			url: '/party-masters/:partyMasterId',
			templateUrl: 'modules/party-masters/views/view-party-master.client.view.html'
		}).
		state('editPartyMaster', {
			url: '/party-masters/:partyMasterId/edit',
			templateUrl: 'modules/party-masters/views/edit-party-master.client.view.html'
		});
	}
]);


text:
package com.intel.analytics.bigdl.orca.utils

import java.util.concurrent.{ExecutorService, Executors, ThreadFactory}

import jep.{JepConfig, JepException, NamingConventionClassEnquirer, SharedInterpreter}
import org.apache.logging.log4j.LogManager

import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration.Duration

object PythonInterpreter {
  protected val logger = LogManager.getLogger(this.getClass)

  private var threadPool: ExecutorService = null

  private val context = new ExecutionContext {
    threadPool = Executors.newFixedThreadPool(1, new ThreadFactory {
      override def newThread(r: Runnable): Thread = {
        val t = Executors.defaultThreadFactory().newThread(r)
        t.setName("jep-thread " + t.getId)
        t.setDaemon(true)
        t
      }
    })

    def execute(runnable: Runnable) {
      threadPool.submit(runnable)
    }

    def reportFailure(t: Throwable): Unit = {
      throw t
    }
  }
  def getSharedInterpreter(): SharedInterpreter = {
    sharedInterpreter
  }

  def check(): Unit = {
    if (sharedInterpreter == null) {
      init()

    }
  }

  def init(): Unit = synchronized {
    if (sharedInterpreter == null) {
      sharedInterpreter = createInterpreter()
    }
  }

  private var sharedInterpreter: SharedInterpreter = null
  private def createInterpreter(): SharedInterpreter = {
    if (System.getenv("PYTHONHOME") == null) {
      throw new RuntimeException("PYTHONHOME is unset, please set PYTHONHOME first.")
    }
    // Load TFNet before create interpreter, or the TFNet will throw an OMP error #13
    // TFNetNative.isLoaded
    val createInterp = () => {
      val config: JepConfig = new JepConfig()
        config.setClassEnquirer(new NamingConventionClassEnquirer())
        SharedInterpreter.setConfig(config)
        val sharedInterpreter = new SharedInterpreter()
        sharedInterpreter
      }
    logger.debug("Creating jep interpreter...")
    threadExecute(createInterp)
  }

  private def threadExecute[T](task: () => T,
                               timeout: Duration = Duration("100s")): T = {
    try {
      val re = Array(task).map(t => Future {
        t()
      }(context)).map(future => {
        Await.result(future, timeout)
      })
      re(0)
    } catch {
      case t: Throwable =>
        // Don't use logger here, or spark local will stuck when catch an exception.
        // println("Warn: " + ExceptionUtils.getStackTrace(t))
        throw new JepException(t)
    }
  }

  def exec(s: String): Unit = {
    logger.debug(s"jep exec ${s}")
    check()
    val func = () => {
      sharedInterpreter.exec(s)
    }
    threadExecute(func)
  }

  def set(s: String, o: AnyRef): Unit = {
    logger.debug(s"jep set ${s}")
    check()
    val func = () => {
      sharedInterpreter.set(s, o)
    }
    threadExecute(func)
  }

  def getValue[T](name: String): T = {
    logger.debug(s"jep getValue ${name}")
    check()
    val func = () => {
      val re = sharedInterpreter.getValue(name)
      re
    }
    threadExecute(func).asInstanceOf[T]
  }
}


text:
package com.salesforce.dva.argus.service.metric.transform;

import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.system.SystemException;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class PropagateTransformTest {

    private static final String TEST_SCOPE = "test-scope";
    private static final String TEST_METRIC = "test-metric";

    @Test(expected = IllegalArgumentException.class)
    public void testPercentileTransformWithoutConstants() {
        Transform propagateTransform = new PropagateTransform();
        Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);
        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric);

        List<String> constants = new ArrayList<String>();

        propagateTransform.transform(metrics, constants);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testPercentileTransformWithoutMetrics() {
        Transform propagateTransform = new PropagateTransform();
        List<Metric> metrics = null;
        List<String> constants = new ArrayList<String>();

        constants.add("9s");
        propagateTransform.transform(metrics, constants);
    }

    @Test(expected = SystemException.class)
    public void testWithIllegalTimeunit() {
        Transform propagateTransform = new PropagateTransform();
        Map<Long, String> datapoints = new HashMap<Long, String>();

        datapoints.put(1000L, "1");
        datapoints.put(2000L, "2");
        datapoints.put(3000L, "3");

        Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);

        metric.setDatapoints(datapoints);

        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric);

        List<String> constants = new ArrayList<String>(1);

        constants.add("5w");
        propagateTransform.transform(metrics, constants);
    }

    @Test
    public void testWithWindowLessThanPropagateRange() {
        Transform propagateTransform = new PropagateTransform();
        Map<Long, String> datapoints = new HashMap<Long, String>();

        datapoints.put(1000L, "1");
        datapoints.put(4000L, "4");
        datapoints.put(5000L, "5");
        datapoints.put(6000L, "6");

        Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);

        metric.setDatapoints(datapoints);

        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric);

        List<String> constants = new ArrayList<String>();

        constants.add("1s");

        Map<Long, String> expected = new HashMap<Long, String>();

        expected.put(1000L, "1");
        expected.put(2000L, "1");
        expected.put(3000L, "1");
        expected.put(4000L, "4");
        expected.put(5000L, "5");
        expected.put(6000L, "6");

        List<Metric> result = propagateTransform.transform(metrics, constants);

        assertEquals(result.get(0).getDatapoints().size(), 6);
        assertEquals(expected, result.get(0).getDatapoints());
    }

    @Test
    public void testWithWindowEqualsToPropagateRange() {
        Transform propagateTransform = new PropagateTransform();
        Map<Long, String> datapoints = new HashMap<Long, String>();

        datapoints.put(1000L, "1");
        datapoints.put(4000L, "4");
        datapoints.put(5000L, "5");
        datapoints.put(6000L, "6");

        Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);

        metric.setDatapoints(datapoints);

        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric);

        List<String> constants = new ArrayList<String>();

        constants.add("3s");

        Map<Long, String> expected = new HashMap<Long, String>();

        expected.put(1000L, "1");
        expected.put(4000L, "4");
        expected.put(5000L, "5");
        expected.put(6000L, "6");

        List<Metric> result = propagateTransform.transform(metrics, constants);

        assertEquals(result.get(0).getDatapoints().size(), 4);
        assertEquals(expected, result.get(0).getDatapoints());
    }

    @Test
    public void testWithWindowGreaterThanPropagateRange() {
        Transform propagateTransform = new PropagateTransform();
        Map<Long, String> datapoints = new HashMap<Long, String>();

        datapoints.put(1000L, "1");
        datapoints.put(4000L, "4");
        datapoints.put(5000L, "5");
        datapoints.put(6000L, "6");

        Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);

        metric.setDatapoints(datapoints);

        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric);

        List<String> constants = new ArrayList<String>();

        constants.add("4s");

        Map<Long, String> expected = new HashMap<Long, String>();

        expected.put(1000L, "1");
        expected.put(4000L, "4");
        expected.put(5000L, "5");
        expected.put(6000L, "6");

        List<Metric> result = propagateTransform.transform(metrics, constants);

        assertEquals(result.get(0).getDatapoints().size(), 4);
        assertEquals(expected, result.get(0).getDatapoints());
    }

    @Test
    public void testWithMultipePropagateRange() {
        Transform propagateTransform = new PropagateTransform();
        Map<Long, String> datapoints = new HashMap<Long, String>();

        datapoints.put(1000L, "1");
        datapoints.put(3000L, "3");
        datapoints.put(6000L, "6");

        Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);

        metric.setDatapoints(datapoints);

        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric);

        List<String> constants = new ArrayList<String>();

        constants.add("1s");

        Map<Long, String> expected = new HashMap<Long, String>();

        expected.put(1000L, "1");
        expected.put(2000L, "1");
        expected.put(3000L, "3");
        expected.put(4000L, "3");
        expected.put(5000L, "3");
        expected.put(6000L, "6");

        List<Metric> result = propagateTransform.transform(metrics, constants);

        assertEquals(result.get(0).getDatapoints().size(), 6);
        assertEquals(expected, result.get(0).getDatapoints());
    }

    @Test
    public void testMetricListWithMultipePropagateRange() {
        Transform propagateTransform = new PropagateTransform();
        Map<Long, String> datapoints_1 = new HashMap<Long, String>();

        datapoints_1.put(1000L, "1");
        datapoints_1.put(3000L, "3");
        datapoints_1.put(6000L, "6");

        Metric metric_1 = new Metric(TEST_SCOPE, TEST_METRIC);

        metric_1.setDatapoints(datapoints_1);

        Map<Long, String> datapoints_2 = new HashMap<Long, String>();

        datapoints_2.put(1000L, "21");
        datapoints_2.put(3000L, "23");
        datapoints_2.put(6000L, "26");

        Metric metric_2 = new Metric(TEST_SCOPE, TEST_METRIC);

        metric_2.setDatapoints(datapoints_2);

        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric_1);
        metrics.add(metric_2);

        List<String> constants = new ArrayList<String>();

        constants.add("1s");

        Map<Long, String> expected_1 = new HashMap<Long, String>();

        expected_1.put(1000L, "1");
        expected_1.put(2000L, "1");
        expected_1.put(3000L, "3");
        expected_1.put(4000L, "3");
        expected_1.put(5000L, "3");
        expected_1.put(6000L, "6");

        Map<Long, String> expected_2 = new HashMap<Long, String>();

        expected_2.put(1000L, "21");
        expected_2.put(2000L, "21");
        expected_2.put(3000L, "23");
        expected_2.put(4000L, "23");
        expected_2.put(5000L, "23");
        expected_2.put(6000L, "26");

        List<Metric> result = propagateTransform.transform(metrics, constants);

        assertEquals(result.size(), 2);
        assertEquals(result.get(1).getDatapoints().size(), 6);
        assertEquals(expected_1, result.get(0).getDatapoints());
        assertEquals(expected_2, result.get(1).getDatapoints());
    }

    @Test
    public void testWithOnlyOneDP() {
        Transform propagateTransform = new PropagateTransform();
        Map<Long, String> datapoints = new HashMap<Long, String>();

        datapoints.put(1000L, "1");

        Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);

        metric.setDatapoints(datapoints);

        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric);

        List<String> constants = new ArrayList<String>();

        constants.add("100s");

        Map<Long, String> expected = new HashMap<Long, String>();

        expected.put(1000L, "1");

        List<Metric> result = propagateTransform.transform(metrics, constants);

        assertEquals(result.get(0).getDatapoints().size(), 1);
        assertEquals(expected, result.get(0).getDatapoints());
    }

    @Test
    public void testNoMetricWithMissingPointAndOtherTimeUnit() {
        Transform propagateTransform = new PropagateTransform();
        Map<Long, String> datapoints = new HashMap<Long, String>();

        datapoints.put(1000L, "1");
        datapoints.put(2000L, "2");
        datapoints.put(3000L, "3");

        Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);

        metric.setDatapoints(datapoints);

        List<Metric> metrics = new ArrayList<Metric>();

        metrics.add(metric);

        List<String> constants = new ArrayList<String>();

        constants.add("5m");

        Map<Long, String> expected = new HashMap<Long, String>();

        expected.put(1000L, "1");
        expected.put(2000L, "2");
        expected.put(3000L, "3");

        List<Metric> result = propagateTransform.transform(metrics, constants);

        assertEquals(result.get(0).getDatapoints().size(), 3);
        assertEquals(expected, result.get(0).getDatapoints());
    }
}
/* Copyright (c) 2016, Salesforce.com, Inc.  All rights reserved. */


text:
using System.Security;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;

namespace System.Windows.Forms
{
    public partial class DataGridView
    {
        private class DataGridViewToolTip
        {
            DataGridView dataGridView = null;
            ToolTip toolTip = null;
            private bool toolTipActivated = false;

            public DataGridViewToolTip(DataGridView dataGridView)
            {
                this.dataGridView = dataGridView;
            }

            public bool Activated
            {
                get
                {
                    return this.toolTipActivated;
                }
            }

            public ToolTip ToolTip
            {
                get
                {
                    return this.toolTip;
                }
            }

            public void Activate(bool activate)
            {
                if (this.dataGridView.DesignMode)
                {
                    return;
                }

                // Create the tool tip handle on demand.
                if (activate && this.toolTip == null)
                {
                    this.toolTip = new ToolTip();
                    this.toolTip.ShowAlways = true;
                    this.toolTip.InitialDelay = 0;
                    this.toolTip.UseFading = false;
                    this.toolTip.UseAnimation = false;
                    this.toolTip.AutoPopDelay = 0;
                }

                if (this.dataGridView.IsRestricted)
                {
                    IntSecurity.AllWindows.Assert();
                }
                try
                {
                    if (activate)
                    {
                        this.toolTip.Active = true;
                        this.toolTip.Show(this.dataGridView.ToolTipPrivate, this.dataGridView);
                    }
                    else if (this.toolTip != null)
                    {
                        this.toolTip.Hide(this.dataGridView);
                        this.toolTip.Active = false;
                    }
                }
                finally
                {
                    if (this.dataGridView.IsRestricted)
                    {
                        CodeAccessPermission.RevertAssert();
                    }
                }

                this.toolTipActivated = activate;
            }

            public void Dispose()
            {
                if (this.toolTip != null)
                {
                    this.toolTip.Dispose();
                    this.toolTip = null;
                }
            }
        }
    }
}


text:
package com.shejiaomao.weibo.service.task;

import com.shejiaomao.maobo.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.cattong.commons.LibException;
import com.cattong.commons.Logger;
import com.cattong.entity.Comment;
import com.cattong.weibo.Weibo;
import com.shejiaomao.common.ResourceBook;
import com.shejiaomao.weibo.common.GlobalVars;
import com.shejiaomao.weibo.service.adapter.CacheAdapter;

public class DestroyCommentTask extends AsyncTask<Void, Void, Comment> {
	private static final String LOG = "DestroyCommentTask";

	private Context context = null;
	private CacheAdapter<Comment> adapter;
	private Weibo microBlog = null;
	private Comment comment = null;

	private ProgressDialog dialog;
	private String resultMsg;
	public DestroyCommentTask(CacheAdapter<Comment> adapter, Comment comment) {
		this.context = adapter.getContext();
		this.adapter = adapter;
		this.comment = comment;
        this.microBlog  = GlobalVars.getMicroBlog(adapter.getAccount());
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

	    dialog = ProgressDialog.show(context, null, context.getString(R.string.msg_comment_destorying));
	    dialog.setCancelable(true);
	    dialog.setOnCancelListener(onCancelListener);
	}

	@Override
	protected Comment doInBackground(Void... params) {
		Comment result = null;
		if (microBlog == null || comment == null) {
			return result;
		}

        try {
			result = microBlog.destroyComment(comment.getCommentId());
		} catch (LibException e) {
			if (Logger.isDebug()) Log.e(LOG, "Task", e);
			resultMsg = ResourceBook.getResultCodeValue(e.getErrorCode(), context);
		}

		return result;
	}

	@Override
	protected void onPostExecute(Comment result) {
	    super.onPreExecute();
	    if (dialog != null &&
	        dialog.getContext() != null
	    ) {
	    	try {
	    	    dialog.dismiss();
	    	} catch (Exception e) {}
	    }

	    if (result != null) {
	    	adapter.remove(comment);
        	Toast.makeText(context, R.string.msg_comment_destroy_success, Toast.LENGTH_LONG).show();
	    } else {
	    	Toast.makeText(context, resultMsg, Toast.LENGTH_LONG).show();
	    }

	}

	private OnCancelListener onCancelListener = new OnCancelListener() {
		public void onCancel(DialogInterface dialog) {
			DestroyCommentTask.this.cancel(true);
		}
	};
}