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

package com.google.devtools.build.lib.rules.apple;

import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import static com.google.devtools.build.lib.syntax.Type.STRING_LIST;

import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClass.Builder;

/**
 * Rule definition for {@code xcode_version} rule.
 */
public class XcodeVersionRule implements RuleDefinition {

  static final String VERSION_ATTR_NAME = "version";
  static final String ALIASES_ATTR_NAME = "aliases";
  static final String DEFAULT_IOS_SDK_VERSION_ATTR_NAME = "default_ios_sdk_version";
  static final String DEFAULT_WATCHOS_SDK_VERSION_ATTR_NAME = "default_watchos_sdk_version";
  static final String DEFAULT_TVOS_SDK_VERSION_ATTR_NAME = "default_tvos_sdk_version";
  // TODO(b/37508376): Remove in lieu of default_macos_sdk_version.
  static final String DEPRECATED_DEFAULT_MACOSX_SDK_VERSION_ATTR_NAME =
      "default_macosx_sdk_version";
  static final String DEFAULT_MACOS_SDK_VERSION_ATTR_NAME =
      "default_macos_sdk_version";

  @Override
  public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
    return builder
        .requiresConfigurationFragments(AppleConfiguration.class)
        .exemptFromConstraintChecking(
            "this rule refines configuration variables and does not build actual content")
        /*
        The official version number of a version of Xcode.
         */
        .add(attr(VERSION_ATTR_NAME, STRING)
            .mandatory()
            .nonconfigurable("this rule determines configuration"))
        /*
        Accepted aliases for this version of Xcode.
        If the value of the xcode_version build flag matches any of the given
        alias strings, this xcode version will be used.
         */
        .add(attr(ALIASES_ATTR_NAME, STRING_LIST)
            .nonconfigurable("this rule determines configuration"))
        /*
        The ios sdk version that is used by default when this version of xcode is being used.
        The ios_sdk_version build flag will override the value specified here.
         */
        .add(attr(DEFAULT_IOS_SDK_VERSION_ATTR_NAME, STRING)
            .nonconfigurable("this rule determines configuration"))
        /*
        The watchos sdk version that is used by default when this version of xcode is being used.
        The watchos_sdk_version build flag will override the value specified here.
         */
        .add(attr(DEFAULT_WATCHOS_SDK_VERSION_ATTR_NAME, STRING)
            .nonconfigurable("this rule determines configuration"))
        /*
        The tvos sdk version that is used by default when this version of xcode is being used.
        The tvos_sdk_version build flag will override the value specified here.
         */
        .add(attr(DEFAULT_TVOS_SDK_VERSION_ATTR_NAME, STRING)
            .nonconfigurable("this rule determines configuration"))
        /*
        The macosx sdk version that is used by default when this version of xcode is being used.
        The macos_sdk_version build flag will override the value specified here.
         */
        .add(attr(DEFAULT_MACOS_SDK_VERSION_ATTR_NAME, STRING)
            .nonconfigurable("this rule determines configuration"))
        .add(attr(DEPRECATED_DEFAULT_MACOSX_SDK_VERSION_ATTR_NAME, STRING)
            .nonconfigurable("this rule determines configuration"))
        .build();
  }

  @Override
  public Metadata getMetadata() {
    return RuleDefinition.Metadata.builder()
        .name("xcode_version")
        .ancestors(BaseRuleClasses.BaseRule.class)
        .factoryClass(XcodeVersion.class)
        .build();
  }
}

/*

Represents a single official xcode version with acceptable aliases for that xcode version.
See the xcode_config rule.

*/


text:
@javax.xml.bind.annotation.XmlSchema(namespace = "urn:hl7-org:cql-annotations:r1", xmlns = {
        @XmlNs(prefix="a", namespaceURI = "urn:hl7-org:cql-annotations:r1")},
        elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.hl7.cql_annotations.r1;

import javax.xml.bind.annotation.XmlNs;

redpajama_set_name: RedPajamaGithub


text:
Creating a React App From Scratch With Webpack 4

This is the basic version. Use react-test for tests.

Use this URL when using Nginx as described in `<../docs/docker-basics.rst>`_:

Browse http://localhost:33340/react-test/public/index.html (try http://127.0.0.1:33340/react-test/public/index.html or a host name pointing to the correct IP if localhost doesn't work)

See `details <https://blog.usejournal.com/creating-a-react-app-from-scratch-f3c693b84658>`_.

.. code-block:: bash

  $ cd react-test
  $ docker run -it --rm --mount type=bind,source=$(pwd),target=/home/node -w /home/node --user $(id -u):$(id -g) node:10.11-alpine /bin/ash

  $ npm init -y

  # if getting "Unhandled rejection Error: EACCES: permission denied" during npm install try without --user to work as root in the container
  $ docker run -it --rm --mount type=bind,source=$(pwd),target=/home/node -w /home/node node:10.11-alpine /bin/ash

  # may not need that dot at the end
  $ npm install --save-dev @babel/core@7.1.0 @babel/cli@7.1.0 @babel/preset-env@7.1.0 @babel/preset-react@7.0.0 .
  $ npm install --save-dev webpack@4.20.2 webpack-cli@3.1.2 webpack-dev-server@3.1.9 style-loader@0.23.1 css-loader@1.0.0 babel-loader@8.0.4 .

  # install React
  $ npm install react@16.5.2 react-dom@16.5.2
  # optional
  $ npm install react-hot-loader@4.3.11

I can run this from inside the container using npx to execute the local webpack package.

.. code-block:: bash

  # npx webpack --mode development --watch

You can also run the same from scripts package.json.

.. code-block:: bash

  # npm run start

Finally, the same can  be run from the host.

.. code-block:: bash

  $ docker run -it --rm --mount type=bind,source=$(pwd),target=/home/node -w /home/node node:10.11-alpine npm run start

This example uses multiple instances of `HtmlWebpackPlugin <https://webpack.js.org/plugins/html-webpack-plugin/>`_ with templates from `<public/template.html>`_  and `<public/template-footer.html>`_ to generate the HTML with the links to Javascript and CSS using lodash syntax. The inject option is set to false to avoid inserting the Javascript automatically and hash is true for cache busting. This can be used with Django templates.

Issues
---------------------

CleanWebpackPlugin with watch true sometimes doesn't recreate CSS when using MiniCssExtractPlugin

Troubleshooting
---------------------


text:
package org.apereo.cas.oidc.token;

import org.apereo.cas.oidc.AbstractOidcTests;
import org.apereo.cas.services.DefaultRegisteredServiceProperty;
import org.apereo.cas.services.OidcRegisteredService;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.RegisteredServiceProperty;
import org.apereo.cas.support.oauth.web.response.accesstoken.response.OAuth20JwtAccessTokenEncoder;
import org.apereo.cas.ticket.accesstoken.OAuth20AccessToken;

import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.test.context.TestPropertySource;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link OidcJwtAccessTokenEncoderTests}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@Tag("OIDC")
@TestPropertySource(properties = "cas.authn.oauth.access-token.crypto.encryption-enabled=false")
public class OidcJwtAccessTokenEncoderTests extends AbstractOidcTests {
    private OAuth20JwtAccessTokenEncoder getAccessTokenEncoder(final OAuth20AccessToken accessToken,
                                                               final RegisteredService registeredService) {
        return OAuth20JwtAccessTokenEncoder.builder()
            .accessToken(accessToken)
            .registeredService(registeredService)
            .service(accessToken.getService())
            .accessTokenJwtBuilder(oidcAccessTokenJwtBuilder)
            .casProperties(casProperties)
            .build();
    }

    @Test
    public void verifyEncodingWithoutEncryptionForService() {
        val accessToken = getAccessToken();
        val registeredService = getOidcRegisteredService(accessToken.getClientId());
        registeredService.setJwtAccessToken(true);
        registeredService.setProperties(Map.of(
            RegisteredServiceProperty.RegisteredServiceProperties.ACCESS_TOKEN_AS_JWT_ENCRYPTION_ENABLED.getPropertyName(),
            new DefaultRegisteredServiceProperty("false")
        ));
        this.servicesManager.save(registeredService);

        val token1 = getAccessTokenEncoder(accessToken, registeredService).encode();
        val token2 = getAccessTokenEncoder(accessToken, registeredService).encode();
        assertEquals(token1, token2);
    }

    @Test
    public void verifyExtractionAsParameterForService() {
        val accessToken = getAccessToken();
        val registeredService = getRegisteredServiceForJwtAccessTokenWithKeys(accessToken);
        val encoder = getAccessTokenEncoder(accessToken, registeredService);

        val encodedAccessToken = encoder.encode();
        val decoded = encoder.decode(encodedAccessToken);
        assertNotNull(decoded);
        assertEquals(accessToken.getId(), decoded);
    }

    @Test
    public void verifyEncodingWithNoCiphersForService() {
        val accessToken = getAccessToken(StringUtils.EMPTY, "encoding-service-clientid");
        val registeredService = getRegisteredServiceForJwtAccessTokenWithKeys(accessToken);

        val encoder = getAccessTokenEncoder(accessToken, registeredService);
        val token1 = encoder.encode();
        val token2 = encoder.encode();
        assertEquals(token1, token2);

        val decoded1 = encoder.decode(token1);
        val decoded2 = encoder.decode(token2);
        assertEquals(decoded1, decoded2);
        assertEquals(accessToken.getId(), decoded1);
    }

    private OidcRegisteredService getRegisteredServiceForJwtAccessTokenWithKeys(final OAuth20AccessToken accessToken) {
        val registeredService = getOidcRegisteredService(accessToken.getClientId());
        registeredService.setJwtAccessToken(true);

        val property = new DefaultRegisteredServiceProperty("false");
        registeredService.setProperties(Map.of(
            RegisteredServiceProperty.RegisteredServiceProperties.ACCESS_TOKEN_AS_JWT_ENCRYPTION_ENABLED.getPropertyName(),
            property,
            RegisteredServiceProperty.RegisteredServiceProperties.ACCESS_TOKEN_AS_JWT_SIGNING_ENABLED.getPropertyName(),
            property
        ));
        this.servicesManager.save(registeredService);
        return registeredService;
    }
}


text:
<?php

namespace AndreasWeber\Kanoa\Mail;

use AndreasWeber\Kanoa\Mail\Message\MessageFactory;
use AndreasWeber\Kanoa\Mail\Transport\MailTransport;
use AndreasWeber\Kanoa\Mail\Transport\SmtpTransport;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

class MailServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple An Container instance
     */
    public function register(Container $pimple)
    {
        \Assert\that($pimple['config']['mail']['mode'])
            ->string()
            ->notEmpty()
            ->choice(
                array(
                    'mail',
                    'smtp'
                )
            );

        if ($pimple['config']['mail']['mode'] === 'smtp') {
            $pimple['mail.transport.transport'] = function () use ($pimple) {
                $instance = SmtpTransport::newInstance(
                    $pimple['config']['mail']['host'],
                    $pimple['config']['mail']['port']
                );

                $instance
                    ->setUsername($pimple['config']['mail']['username'])
                    ->setPassword($pimple['config']['mail']['password']);

                if (!is_null($pimple['config']['mail']['encryption'])) {
                    $instance->setEncryption($pimple['config']['mail']['encryption']);
                }

                return $instance;
            };
        } else {
            $pimple['mail.transport.transport'] = function () use ($pimple) {
                return MailTransport::newInstance();
            };
        }

        $pimple['mail.mailer'] = function () use ($pimple) {
            return new Mailer($pimple['mail.transport.transport']);
        };

        $pimple['mail.message.messageFactory'] = function () use ($pimple) {
            return new MessageFactory($pimple['config']['mail']['from']);
        };
    }
}


text:
#ifndef itkNoiseImageFilter_h
#define itkNoiseImageFilter_h

#include "itkBoxImageFilter.h"
#include "itkImage.h"
#include "itkNumericTraits.h"

namespace itk
{
/** \class NoiseImageFilter
 * \brief Calculate the local noise in an image.
 *
 * Computes an image where a given pixel is the standard deviation of
 * the pixels in a neighborhood about the corresponding input pixel.
 * This serves as an estimate of the local noise (or texture) in an
 * image. Currently, this noise estimate assume a piecewise constant
 * image.  This filter should be extended to fitting a (hyper) plane
 * to the neighborhood and calculating the standard deviation of the
 * residuals to this (hyper) plane.
 *
 * \sa Image
 * \sa Neighborhood
 * \sa NeighborhoodOperator
 * \sa NeighborhoodIterator
 *
 * \ingroup IntensityImageFilters
 * \ingroup ITKImageFilterBase
 *
 * \sphinx
 * \sphinxexample{Filtering/ImageFilterBase/ComputerLocalNoise,Compute Local Noise In Image}
 * \endsphinx
 */
template <typename TInputImage, typename TOutputImage>
class ITK_TEMPLATE_EXPORT NoiseImageFilter : public BoxImageFilter<TInputImage, TOutputImage>
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(NoiseImageFilter);

  /** Extract dimension from input and output image. */
  static constexpr unsigned int InputImageDimension = TInputImage::ImageDimension;
  static constexpr unsigned int OutputImageDimension = TOutputImage::ImageDimension;

  /** Convenient type alias for simplifying declarations. */
  using InputImageType = TInputImage;
  using OutputImageType = TOutputImage;

  /** Standard class type aliases. */
  using Self = NoiseImageFilter;
  using Superclass = BoxImageFilter<InputImageType, OutputImageType>;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(NoiseImageFilter, BoxImageFilter);

  /** Image type alias support */
  using InputPixelType = typename InputImageType::PixelType;
  using OutputPixelType = typename OutputImageType::PixelType;
  using InputRealType = typename NumericTraits<InputPixelType>::RealType;

  using InputImageRegionType = typename InputImageType::RegionType;
  using OutputImageRegionType = typename OutputImageType::RegionType;

  using InputSizeType = typename InputImageType::SizeType;

#ifdef ITK_USE_CONCEPT_CHECKING
  // Begin concept checking
  itkConceptMacro(InputHasNumericTraitsCheck, (Concept::HasNumericTraits<InputPixelType>));
  // End concept checking
#endif

protected:
  NoiseImageFilter();
  ~NoiseImageFilter() override = default;

  /** NoiseImageFilter can be implemented as a multithreaded filter.
   * Therefore, this implementation provides a DynamicThreadedGenerateData()
   * routine which is called for each processing thread. The output
   * image data is allocated automatically by the superclass prior to
   * calling DynamicThreadedGenerateData().  DynamicThreadedGenerateData can only
   * write to the portion of the output image specified by the
   * parameter "outputRegionForThread"
   *
   * \sa BoxImageFilter::ThreadedGenerateData(),
   *     BoxImageFilter::GenerateData() */
  void
  DynamicThreadedGenerateData(const OutputImageRegionType & outputRegionForThread) override;
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "itkNoiseImageFilter.hxx"
#endif

#endif


text:
SYNONYM

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

#### Published in
Mat. fl. atl. 15. 1860 (non A. Rich. 1847)

#### Original name
null

### Remarks
null


text:
class UserNotification < ApplicationMailer

  def send_verification_email(user)
    @user = user
    mail(:to => @user.email, :subject => 'Verifikasi Email')
  end

end


text:
@extends('newsages::layout')

@section('content')

{{ trans('newsages::admin.reset_password') }}

                    <form class="form-horizontal" role="form" method="POST" action="{{ url(config('newsages.admin.route_prefix', 'admin').'/password/reset') }}">
                        {!! csrf_field() !!}

                        <input type="hidden" name="token" value="{{ $token }}">

has('email') ? ' has-error' : '' }}">
                            {{ trans('newsages::admin.email_address') }}

                                <input type="email" class="form-control" name="email" value="{{ $email or old('email') }}">

                                @if ($errors->has('email'))

                                        {{ $errors->first('email') }}

                                @endif

has('password') ? ' has-error' : '' }}">
                            {{ trans('newsages::admin.password') }}

                                <input type="password" class="form-control" name="password">

                                @if ($errors->has('password'))

                                        {{ $errors->first('password') }}

                                @endif

has('password_confirmation') ? ' has-error' : '' }}">
                            {{ trans('newsages::admin.confirm_password') }}

                                <input type="password" class="form-control" name="password_confirmation">

                                @if ($errors->has('password_confirmation'))

                                        {{ $errors->first('password_confirmation') }}

                                @endif

                                <button type="submit" class="btn btn-primary">
                                     {{ trans('newsages::admin.reset_password') }}
                                </button>

                    </form>

@endsection


text:
import { INgorBaseComponent } from './base-component';

export interface INgorEntityDetailComponent<Query, Params, EntityCreateDto, EntityUpdateDto, EntityDto>
  extends INgorBaseComponent<Query, Params, EntityCreateDto, EntityUpdateDto, EntityDto> {
  entity: EntityDto;
}


text:
<?php

declare(strict_types=1);

namespace tests\Dudulina\CodeGeneration\QueryHandlersWithMultipleHandlersMapCodeGeneratorData;

class Query
{

}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--~
  ~ JBoss, Home of Professional Open Source
  ~ Copyright Red Hat, Inc., and individual contributors
  ~ by the @authors tag. See the copyright.txt in the distribution for a
  ~ full listing of individual contributors.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10sp">

    <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Title"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/FormLabel"
            android:text="@string/title"/>

    <EditText
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="15sp"/>

    <Button
            android:id="@+id/buttonSave"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/add"/>

    <Button
            android:id="@+id/buttonCancel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/cancel"/>

</LinearLayout>


text:
@interface ORKQuestionResult (Values)

- (NSString*) getAnswerString;

@end


text:
<!DOCTYPE html>

<link rel="stylesheet" href="./css/main.css">

    <meta charset="utf-8">
    <title>Pan rústico de masa madre | Ñam Ñam: Recetas Probadas y Aprobadas</title>

Home

Daikiritos

Pan rústico de masa madre

Pollo Tikka Masala

Pan rústico de masa madre

Pan rústico de masa madre

De la receta de Ibán Yarza

Esta receta es recomendada hacer un día que te vas a quedar en la casa, pues la masa requiere constante intervención, aunque cada intervención es de segundos, se hace muchas veces durante la mañana.

Ingredientes

475 g de harina panificable (de fuerza)

25 g de harina integral de centeno o trigo

290-300 g de agua

200 g de masa madre natural burbujeante

10-12 g de sal.

La noche anterior

Alimenta la masa madre natural que tengas guardada. A la mañana siguiente verás que está llena de burbujas y haya ganado volumen.

El día del pan

Se mezclan todos los ingredientes y se amasan. Se tapa.

Espera ½ hora.

Amasar por 10-15 segundos (1).

Espera ½ hora (1).

Amasar por 10-15 segundos (2).

Espera ½ hora (2).

Amasar por 10-15 segundos (3).

Espera ½ hora (3).

Amasar por 10-15 segundos (4).

Espera 1 y ½ horas.

Plegar sin amasar.

Espera 1 y ½ horas.

Formar la hogaza.

Leudar por 2 a 4 horas.

Prender el Horno al máximo (250ºC) (15 a 20 minutos)

Meter el pan y hornear por 10 minutos al máximo.

Bajar a 200ºC y hornear por 50 minutos más.

Dándole ese tiempo de amasado y reposo hasta que esté amasado del todo.

El amasado de 15 segundos consiste en estirar la masa, plegar la masa en dos, girar 90º y repetir hasta que vaya ganando elasticiad.

Para facilitar el amasado aceitar generosamente la superficie. Repetir este proceso unas 4 veces, al final casi no será necesario aceitar la superficie.

Dejar reposar durante 3 horas, a mitad del proceso (1 hora y media), opcionalmente se le puede dar un pliegue en ambos sentidos para tensar la masa.

Cuando ya tenga volumen, se form la hogaza. Esta vez, enharinando la mesa, se pone la masa y se doblan las orillas hacia el centro, como doblando los brazos de una estrella hacia el centro; esa será la parte abajo del pan.

Poner un paño abierto en una fuente para recibir la hogaza. Enharinar el paño abundantemente para que la masa no se pege incluso después de horas de reposo. Se pone la masa con la parte tensa y lisa hacia abajo.

Se deja leudar la masa durante 3 o 4 horas más. El tiempo dependerá de la masa madre y de la temperatura ambiente. Cuando haya casi doblado su volumen está lista.

Precalentar el horno a 250ªC (al máximo), idealmente poner un cacharro de cerámica con piedra pómez adentro también.

Con el horno caliente echar agua en el cacharro para formar un ambiente húmedo en el horno. Poner la hogaza sobre la lata y hacer cortes de buena profundidad, que expongan la miga, para guiar la expansión del pan. Meter el pan y dejar en alta temperatura por 10 minutos.

Al cabo de los 10 minutos, retirar el cacharro con agua y bajar la temperatura a 200ºC.

Hornear durante 50 minutos más.

Luego de un total de una hora de horneado (10 + 50 minutos), sacar el pan.

La recomendación general es envolver en un paño y dejar sobre una rejilla hasta el día siguiente. Pero yo nunca me aguanto, prefiero pegarle un corte en un lado y comerme un crujiente y aromático trozo de pan con mantequilla y otro con aceite de oliva.

…y otro con palta.

Oink!

Variaciones

Agregar semillas pequeñas, un buen puñado de linaza o de semillas de girasol.

Más agua, es más complicado amazar y la hogaza es más fofa, pero la miga es impresionante.

Harinas débiles: se puede hacer, pero cuesta más, la masa es notoriamente menos elástica, hay que amazar bastante pero se puede hacer un pan igualmente bueno.


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

package com.ksmpartners.ernie.api

import com.ksmpartners.ernie.util.Utility._
import org.testng.annotations._
import scala.concurrent.duration._
import org.testng.Assert
import java.io.{ ByteArrayInputStream, File }
import com.ksmpartners.ernie.model.{ DeleteStatus, ReportType }
import org.slf4j.{ LoggerFactory, Logger }
import scala.Array
import ErnieBuilder._
import ApiTestUtil._
import org.joda.time.DateTime
import com.ksmpartners.ernie.api.InvalidDefinitionException
import com.ksmpartners.ernie.api.MissingArgumentException
import scala.Some
import com.ksmpartners.ernie.api.NotFoundException
import scala.concurrent.ExecutionContext.Implicits.global

object ApiTestUtil {
  def testException[B <: Exception](func: () => Unit, ex: Class[B]) = try {
    func()
    Assert.assertTrue(false)
  } catch {
    case t: Throwable => Assert.assertEquals(t.getClass, ex)
  }
}

//@Test(dependsOnGroups = Array("timeout"))
class APITest { //extends TestNGSuite {

  @BeforeClass
  private var ernie: ErnieControl = null
  private val log: Logger = LoggerFactory.getLogger("com.ksmpartners.ernie.api.APITest")

  @BeforeClass(dependsOnGroups = Array("tTCleanUp"))
  def startup() {
  }

  @AfterClass
  def shutdown() {
    ernie.shutDown
  }

  @BeforeClass
  private var defId = ""

  @BeforeClass
  private var jobId = -1L

  @BeforeClass
  private val jobDir = createTempDirectory.getAbsolutePath

  @Test(dependsOnGroups = Array("timeout"))
  def init() {
    log.info("Beginning APITest")
    ernie = ErnieEngine(
      ernieBuilder
        withFileReportManager (createTempDirectory.getAbsolutePath, createTempDirectory().getAbsolutePath, jobDir)
        withDefaultRetentionDays (5)
        withMaxRetentionDays (10)
        timeoutAfter (5 minutes)
        withWorkers (5)
        build ()).start
  }

  /* @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def trouble() {
    val design = scala.xml.XML.loadFile(Thread.currentThread.getContextClassLoader.getResource("in/new_report.rptdesign").getPath)
    log.info(design + "  asdf")
    val d = ernie.createDefinition(Some(new java.io.ByteArrayInputStream(design.toString.getBytes)), "test", "adam")
    log.info(d + " derp")
    val j = ernie.createJob(d.getDefId, com.ksmpartners.ernie.model.ReportType.PDF, None, Map.empty[String, String], "adam")
    log.info("job " + j)
    val endTime = DateTime.now.plus(ernie.timeoutDuration.toMillis)
    var inProgress = true
    while ((DateTime.now.isBefore(endTime)) && inProgress) {
      if (ernie.getJobStatus(j._1) == com.ksmpartners.ernie.model.JobStatus.COMPLETE) inProgress = false
    }
    log.info("done... " + jobDir)

  }  */

  //@TestSpecs(Array(new TestSpec(key = "ERNIE-184")))
  @Test(groups = Array("setup"), dependsOnMethods = Array("init"))
  def createDefinition() {
    testException(() => ernie.createDefinition(Some(null), "test", "test"), classOf[InvalidDefinitionException])
    //  testException(() => ernie.createDefinition(None, null, null), classOf[IllegalArgumentException])

    // Assert.assertEquals(ernie.createDefinition(Some(Right(null)), "test", "test").error.get.getClass, classOf[InvalidDefinitionException])
    // Assert.assertEquals(ernie.createDefinition(None, null, null).error.get.getClass, classOf[IllegalArgumentException])
    val xml = scala.xml.XML.loadFile(new File(Thread.currentThread.getContextClassLoader.getResource("in/test_def.rptdesign").getPath))
    try_(new ByteArrayInputStream(xml.toString.getBytes)) { bAIS =>
      {
        val resp = ernie.createDefinition(Some(bAIS), "test", "test")
        defId = resp.getDefId
      }
    }
    Assert.assertNotSame(defId, "")
  }

  //@TestSpecs(Array(new TestSpec(key = "ERNIE-185"), new TestSpec(key = "ERNIE-186")))
  @Test(dependsOnMethods = Array("createDefinition"), groups = Array("setup"))
  def updateDefinition() {
    testException(() => ernie.updateDefinition(null, None, None), classOf[MissingArgumentException])
    testException(() => ernie.updateDefinition(defId, None, None), classOf[MissingArgumentException])
    val resp = ernie.updateDefinition(defId, Some(ernie.getDefinitionEntity(defId)), None)
    Assert.assertEquals(resp.getDefId, defId)
    try_(new ByteArrayInputStream(<break/>.toString.getBytes)) { bAIS =>
      testException(() => ernie.updateDefinition(defId, None, Some(bAIS)), classOf[InvalidDefinitionException])
    }
    val xml = scala.xml.XML.loadFile(new File(Thread.currentThread.getContextClassLoader.getResource("in/test_def_params.rptdesign").getPath))
    try_(new ByteArrayInputStream(xml.toString.getBytes)) { bAIS =>
      Assert.assertTrue(ernie.updateDefinition(defId, None, Some(bAIS)).getParams.size > 0)
    }
  }

  @Test(dependsOnMethods = Array("updateDefinition"), groups = Array("setup"))
  def createJob() {
    var (id, status) = ernie.createJob("test", ReportType.PDF, None, null, "test")
    Assert.assertEquals(status, com.ksmpartners.ernie.model.JobStatus.FAILED_NO_SUCH_DEFINITION)
    jobId = ernie.createJob(defId, ReportType.PDF, None, null, "test")._1
    Assert.assertTrue(jobId > 0)
    getStatusFuture
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getDefinitionsCatalog() {
    Assert.assertTrue(ernie.getDefinitionsCatalog.size > 0)
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getDefList() {
    Assert.assertTrue(ernie.getDefinitionList.size > 0)
  }

  /*  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getDefinition() {
    Assert.assertEquals(ernie.getDefinition(null).error.get.getClass, classOf[MissingArgumentException])
    Assert.assertTrue(ernie.getDefinition(defId).defEnt.isDefined)
  }    */

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getDefinitionEntity() {
    testException(() => ernie.getDefinitionEntity(null), classOf[MissingArgumentException])
    testException(() => ernie.getDefinitionEntity("test"), classOf[NotFoundException])
    Assert.assertEquals(ernie.getDefinitionEntity(defId).getDefId, defId)
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getDefinitionDesign() {
    testException(() => ernie.getDefinitionDesign(null)(b => b), classOf[MissingArgumentException])
    ernie.getDefinitionDesign(defId)(b => Assert.assertTrue(scala.xml.XML.load(b).toString.length > 10))
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getDefinitionDesignOpt() {
    testException(() => ernie.getDefinitionDesignOpt(null)(b => b), classOf[MissingArgumentException])
    ernie.getDefinitionDesignOpt(defId)(b => {
      Assert.assertTrue(b.isDefined);
      Assert.assertTrue(scala.xml.XML.load(b.get).toString.length > 10)
    })
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getStatus(): com.ksmpartners.ernie.model.JobStatus = {
    testException(() => ernie.getJobStatus(-1L), classOf[MissingArgumentException])
    ernie.getJobStatus(jobId)
  }

  var callbackSuccess = false

  def getStatusFuture() = {
    val f = ernie.getJobStatusFuture(jobId, Some(com.ksmpartners.ernie.model.JobStatus.COMPLETE))
    f.onSuccess {
      case j => callbackSuccess = (j.status == com.ksmpartners.ernie.model.JobStatus.COMPLETE)
    }
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getJobEntity() {
    testException(() => ernie.getJobEntity(-1L), classOf[MissingArgumentException])
    Assert.assertTrue(ernie.getJobEntity(jobId).isDefined)
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getJobCatalog() {
    Assert.assertTrue(ernie.getJobCatalog(None).size > 0)
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def getJobList() {
    Assert.assertTrue(ernie.getJobList.size > 0)
  }

  @Test(dependsOnGroups = Array("setup"), groups = Array("main"))
  def completeJob() {
    val endTime = DateTime.now.plus(ernie.timeoutDuration.toMillis)
    var inProgress = true
    while ((DateTime.now.isBefore(endTime)) && inProgress) {
      if (getStatus == com.ksmpartners.ernie.model.JobStatus.COMPLETE) inProgress = false
    }
    Assert.assertFalse(inProgress)
  }

  @Test(dependsOnGroups = Array("main"), groups = Array("completed"))
  def callbackSuccessful() {
    Assert.assertTrue(callbackSuccess)
  }

  @Test(dependsOnGroups = Array("main"), groups = Array("completed"))
  def getRptEnt() {
    testException(() => ernie.getReportEntity(-1L), classOf[MissingArgumentException])
    var resp = ernie.getReportEntity(jobId)
    Assert.assertTrue(resp.isDefined)
    resp = ernie.getReportEntity(jobToRptId(jobId))
    Assert.assertTrue(resp.isDefined)
    Assert.assertTrue(resp.get.getStartDate.isBeforeNow)
  }

  @Test(dependsOnGroups = Array("main"), groups = Array("completed"))
  def getOutputStream() {
    testException(() => ernie.getReportOutput(-1L), classOf[MissingArgumentException])
    val resp = ernie.getReportOutput(jobId)
    Assert.assertTrue(resp.isDefined)
  }

  /*@Test(dependsOnGroups = Array("main"), groups = Array("completed"))
  def getOutputFile() {
    Assert.assertEquals(ernie.getReportOutputFile(-1L).error.get.getClass, classOf[MissingArgumentException])
    val resp = ernie.getReportOutputFile(jobId)
    Assert.assertTrue(resp.file.isDefined)
    Assert.assertTrue(resp.file.get.isFile)
    Assert.assertEquals(resp.file.get.getParent, ernie.outputDir)
  }

  @Test(dependsOnGroups = Array("main"), groups = Array("completed"))
  def getOutput() {
    Assert.assertEquals(ernie.getReportOutput(-1L).error.get.getClass, classOf[MissingArgumentException])
    val resp = ernie.getReportOutput(jobId)
    Assert.assertTrue(resp.stream.isDefined)
    Assert.assertTrue(resp.file.isDefined)
    Assert.assertTrue(resp.file.get.isFile)
    Assert.assertEquals(resp.file.get.getParent, ernie.outputDir)
  }      */

  @Test(dependsOnGroups = Array("completed"), groups = Array("aTCleanUp"))
  def deleteOutput() {
    val resp = ernie.deleteReportOutput(jobId)
    Assert.assertEquals(resp, DeleteStatus.SUCCESS)
  }

  @Test(dependsOnGroups = Array("completed"), groups = Array("aTCleanUp"))
  def deleteDef() {
    val resp = ernie.deleteDefinition(defId)
    Assert.assertEquals(resp, DeleteStatus.SUCCESS)
  }

  @Test(dependsOnGroups = Array("completed"), groups = Array("aTCleanUp"))
  def purge() {
    val resp = ernie.purgeExpiredReports()
    Assert.assertEquals(resp._1, DeleteStatus.SUCCESS)
  }

}


text:
package org.gluu.oxtrust.model.push;

import java.io.Serializable;

import org.gluu.persist.model.base.Entry;
import org.gluu.persist.annotation.AttributeName;
import org.gluu.persist.annotation.DataEntry;
import org.gluu.persist.annotation.JsonObject;
import org.gluu.persist.annotation.ObjectClass;

/**
 * Push device
 *
 * @author Yuriy Movchan Date: 01/10/2014
 */
@DataEntry(sortBy = { "userId" }, sortByName = "oxAuthUserId")
@ObjectClass(value = "oxPushDevice")
public class PushDevice extends Entry implements Serializable {

	private static final long serialVersionUID = 1332826784937052508L;

	@AttributeName(ignoreDuringUpdate = true, name = "oxId")
	private String id;

	@AttributeName(name = "oxType")
	private String type;

	@AttributeName(name = "oxPushApplication")
	private String application;

	@AttributeName(name = "oxAuthUserId")
	private String userId;

	@AttributeName(name = "oxPushDeviceConf")
	@JsonObject
	private PushDeviceConfiguration deviceConfiguration;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getApplication() {
		return application;
	}

	public void setApplication(String application) {
		this.application = application;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public PushDeviceConfiguration getDeviceConfiguration() {
		return deviceConfiguration;
	}

	public void setDeviceConfiguration(PushDeviceConfiguration deviceConfiguration) {
		this.deviceConfiguration = deviceConfiguration;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("PushDevice [id=").append(id).append(", type=").append(type).append(", application=").append(application)
				.append(", userId=").append(userId).append(", deviceConfiguration=").append(deviceConfiguration).append("]");
		return builder.toString();
	}

}


text:
# ファサード

- [イントロダクション](#introduction)
- [いつファサードを使うか](#when-to-use-facades)
    - [ファサード 対 依存注入](#facades-vs-dependency-injection)
    - [ファサード 対 ヘルパ関数](#facades-vs-helper-functions)
- [ファサードの仕組み](#how-facades-work)
- [リアルタイムファサード](#real-time-facades)
- [ファサードクラス一覧](#facade-class-reference)

## イントロダクション

ファサード(facade、「入り口」)はアプリケーションの[サービスコンテナ](/docs/{{version}}/container)に登録したクラスへ、「静的」なインターフェイスを提供します。Laravelのほとんどの機能に対して、ファサードが用意されています。Laravelの「ファサード」は、サービスコンテナ下で動作しているクラスに対し、"static proxy"として動作しています。これにより伝統的な静的メソッドよりもテストの行いやすさと柔軟性を保ちながらも、簡潔で記述的であるという利点があります。

Laravelのファサードはすべて、`Illuminate\Support\Facades`名前空間下で定義されています。ですから、簡単にファサードへアクセスできます。

    use Illuminate\Support\Facades\Cache;

    Route::get('/cache', function () {
        return Cache::get('key');
    });

フレームワークの様々な機能をデモンストレートするために、Laravelのドキュメント全般でたくさんの例がファサードを使用しています。

## いつファサードを使うか

ファサードにはたくさんの利点があります。自分で取り込んだり、設定したりする必要があり、長くて覚えにくいクラス名を使わずに、Laravelの機能を簡素で覚えやすい文法で使ってもらえます。その上に、PHPの動的メソッドのユニークな使用方法のおかげで、簡単にテストができます。

しかしながら、ファサードの使用にはいくつか気をつけるべき点も存在します。ファサードの一番の危険性は、クラスの責任範囲の暴走です。ファサードはとても簡単に使用でき、依存注入も必要ないため、簡単にクラスが成長し続ける結果、一つのクラスで多くのファサードが使われます。依存注入を使用すれば、クラスが大きくなりすぎることに伴う、大きなコンストラクタの視覚的なフィードバックにより、この危険性は抑制されます。ですから、ファサードを使用するときは、クラスの責任範囲を小さくとどめるため、クラスサイズに特に注意をはらいましょう。

> {tip} Laravelに関連した、サードパーティパッケージを構築する場合は、ファサードの代わりに[Laravelの契約](/docs/{{version}}/contracts)を使うほうが好ましいでしょう。Laravel自身の外でパッケージを構築するわけですから、Laravelのテストヘルパへアクセスする必要はありません。

### ファサード 対 依存注入

依存注入の最大の利便性は、注入するクラスの実装を入れ替えられるという機能です。モックやスタブを注入し、そうした代替オブジェクトの様々なメソッドのアサートが行えるため、テスト中に便利です。

本当の静的クラスメソッドをモックしたり、スタブにすることは、通常は不可能です。しかしファサードは、サービスコンテナが依存解決したオブジェクトの代替メソッドを呼び出すために、動的メソッドが使えますので、注入したクラスインスタンスをテストするのと同様に、ファサードを実際にテスト可能です。

    use Illuminate\Support\Facades\Cache;

    Route::get('/cache', function () {
        return Cache::get('key');
    });

`Cache::get`メソッドが、予想した引数で呼び出されることを確認するために、以下のようなテストを書けます。

    use Illuminate\Support\Facades\Cache;

    /**
     * 基本的なテスト機能の例
     *
     * @return void
     */
    public function testBasicExample()
    {
        Cache::shouldReceive('get')
             ->with('key')
             ->andReturn('value');

        $this->visit('/cache')
             ->see('value');
    }

### ファサード 対 ヘルパ関数

ファサードに加え、Laravelは様々な「ヘルパ」関数を用意しており、ビューの生成、イベントの発行、ジョブの起動、HTTPレスポンスの送信など、一般的なタスクを実行できます。こうしたヘルパ関数の多くは、対応するファサードと同じ機能を実行します。たとえば、以下のファサードとヘルパの呼び出しは、同じ働きをします。

    return View::make('profile');

    return view('profile');

ここではファサードとヘルパ関数との間に、全く違いはありません。ヘルパ関数を使う場合も、対応するファサードと全く同様にテストできます。たとえば、以下のルートが存在するとしましょう。

    Route::get('/cache', function () {
        return cache('key');
    });

内部で`cache`ヘルパは、`Cache`ファサードの裏で動作しているクラスの`get`メソッドを呼び出します。ですから、ヘルパ関数を使用していても、期待する引数でメソッドが呼びだされていることを確認する、以下のテストを書けます。

    use Illuminate\Support\Facades\Cache;

    /**
     * 基本的なテスト機能の例
     *
     * @return void
     */
    public function testBasicExample()
    {
        Cache::shouldReceive('get')
             ->with('key')
             ->andReturn('value');

        $this->visit('/cache')
             ->see('value');
    }

## ファサードの仕組み

Laravelアプリケーション中で、ファサードとは、コンテナを通じてオブジェクトにアクセス方法を提供するクラスのことです。`Facade`クラス中の仕組みでこれを行なっています。Laravelのファサードと皆さんが作成するカスタムファサードは、`Illuminate\Support\Facades\Facade`クラスを拡張します。

`Facade`基本クラスは、ファサードへの関数呼び出しをコンテナにより依存解決されたオブジェクトへ送るため、`__callStatic()`マジックメソッドを使用します。下の例では、Laravelのキャッシュシステムを呼び出しています。これを読むと一見、`Cache`クラスのstaticな`get`メソッドが呼び出されているのだと考えてしまうことでしょう。

    <?php

    namespace App\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Cache;

    class UserController extends Controller
    {
        /**
         * 指定したユーザーのプロフィール表示
         *
         * @param  int  $id
         * @return Response
         */
        public function showProfile($id)
        {
            $user = Cache::get('user:'.$id);

            return view('profile', ['user' => $user]);
        }
    }

ファイルの先頭で、`Cache`ファサードを取り込んでいることに注目です。このファサードサービスは、`Illuminate\Contracts\Cache\Factory`インターフェイスの裏にある実装へアクセスするプロキシとして動作します。ファサードを使ったメソッド呼び出しは、裏のLaravelのキャッシュサービスの実装へ渡されます。

そのため、`Illuminate\Support\Facades\Cache`クラスを見てもらえば、staticの`get`メソッドは存在していないことが分かります。

    class Cache extends Facade
    {
        /**
         * コンポーネントの登録名を取得
         *
         * @return string
         */
        protected static function getFacadeAccessor() { return 'cache'; }
    }

かわりに`Cache`ファサードは、`Facade`ベースクラスを拡張し、`getFacadeAccessor()`メソッドを定義しています。このメソッドの仕事は、サービスコンテナの結合名を返すことです。ユーザーが`Cache`ファサードのどのstaticメソッドを利用しようと、Laravelは[サービスコンテナ](/docs/{{version}}/container)から`cache`に結び付けられたインスタンスを依存解決し、要求されたメソッドを(この場合は`get`)そのオブジェクトに対し実行します。

## リアルタイムファサード

リアルタムファサードを使用すれば、アプリケーション中のどんなクラスでも、ファサードとして取り扱えます。活用法を示すために、新しいテストの手法を撮ってみましょう。例として、`Podcast`モデルが`publish`メソッドを持っているとしましょう。しかしポッドキャストを公開(publish)するには、`Publisher`インスタンスを注入する必要があるとします。

    <?php

    namespace App;

    use App\Contracts\Publisher;
    use Illuminate\Database\Eloquent\Model;

    class Podcast extends Model
    {
        /**
         * ポッドキャストの公開
         *
         * @param  Publisher  $publisher
         * @return void
         */
        public function publish(Publisher $publisher)
        {
            $this->update(['publishing' => now()]);

            $publisher->publish($this);
        }
    }

メソッドへPublisherの実装を注入することにより、注入するpublisherをモックできるため、メソッドを簡単にメソッドを他と切り離してテストできます。しかし、`publish`メソッドを呼び出すごとに、publisherインスタンスを常に渡す必要があります。リアルタイムファサードを使用すれば、同じてスタビリティを保ちながらも、明確に`Publisher`インスタンスを渡す必要がなくなります。リアルタイムファサードを作成するには、インポートするクラスのプレフィックスとして、`Facade`名前空間を付けます。

    <?php

    namespace App;

    use Facades\App\Contracts\Publisher;
    use Illuminate\Database\Eloquent\Model;

    class Podcast extends Model
    {
        /**
         * ポッドキャストの公開
         *
         * @return void
         */
        public function publish()
        {
            $this->update(['publishing' => now()]);

            Publisher::publish($this);
        }
    }

リアルタイムファサードを使用しているため、インターフェイスやクラス名の`Facade`プレフィックス後の部分を使い、サービスコンテナがpublisherの実装を依存注入解決します。テストのときは、このメソッドの呼び出しをモックするために、ファサードに組み込まれているLaravelのテストヘルパが使用できます。

    <?php

    namespace Tests\Feature;

    use App\Podcast;
    use Tests\TestCase;
    use Facades\App\Contracts\Publisher;
    use Illuminate\Foundation\Testing\RefreshDatabase;

    class PodcastTest extends TestCase
    {
        use RefreshDatabase;

        /**
         * A test example.
         *
         * @return void
         */
        public function test_podcast_can_be_published()
        {
            $podcast = factory(Podcast::class)->create();

            Publisher::shouldReceive('publish')->once()->with($podcast);

            $podcast->publish();
        }
    }

## ファサードクラス一覧

以下は全ファサードと実際のクラスの一覧です。これは特定のファサードを元にし、APIドキュメントを素早く探したい場合に便利な道具になります。対応する[サービスコンテナ結合キー](/docs/{{version}}/container)も記載しています。

ファサード  |  クラス  |  サービスコンテナ結合
------------- | ------------- | -------------
App  |  [Illuminate\Foundation\Application](https://laravel.com/api/{{version}}/Illuminate/Foundation/Application.html)  |  `app`
Artisan  |  [Illuminate\Contracts\Console\Kernel](https://laravel.com/api/{{version}}/Illuminate/Contracts/Console/Kernel.html)  |  `artisan`
Auth  |  [Illuminate\Auth\AuthManager](https://laravel.com/api/{{version}}/Illuminate/Auth/AuthManager.html)  |  `auth`
Auth (Instance)  |  [Illuminate\Contracts\Auth\Guard](https://laravel.com/api/{{version}}/Illuminate/Contracts/Auth/Guard.html)  |  `auth.driver`
Blade  |  [Illuminate\View\Compilers\BladeCompiler](https://laravel.com/api/{{version}}/Illuminate/View/Compilers/BladeCompiler.html)  |  `blade.compiler`
Broadcast  |  [Illuminate\Contracts\Broadcasting\Factory](https://laravel.com/api/{{version}}/Illuminate/Contracts/Broadcasting/Factory.html)  |
Broadcast (Instance)  |  [Illuminate\Contracts\Broadcasting\Broadcaster](https://laravel.com/api/{{version}}/Illuminate/Contracts/Broadcasting/Broadcaster.html)  |
Bus  |  [Illuminate\Contracts\Bus\Dispatcher](https://laravel.com/api/{{version}}/Illuminate/Contracts/Bus/Dispatcher.html)  |
Cache  |  [Illuminate\Cache\CacheManager](https://laravel.com/api/{{version}}/Illuminate/Cache/CacheManager.html)  |  `cache`
Cache (Instance)  |  [Illuminate\Cache\Repository](https://laravel.com/api/{{version}}/Illuminate/Cache/Repository.html)  |  `cache.store`
Config  |  [Illuminate\Config\Repository](https://laravel.com/api/{{version}}/Illuminate/Config/Repository.html)  |  `config`
Cookie  |  [Illuminate\Cookie\CookieJar](https://laravel.com/api/{{version}}/Illuminate/Cookie/CookieJar.html)  |  `cookie`
Crypt  |  [Illuminate\Encryption\Encrypter](https://laravel.com/api/{{version}}/Illuminate/Encryption/Encrypter.html)  |  `encrypter`
DB  |  [Illuminate\Database\DatabaseManager](https://laravel.com/api/{{version}}/Illuminate/Database/DatabaseManager.html)  |  `db`
DB (Instance)  |  [Illuminate\Database\Connection](https://laravel.com/api/{{version}}/Illuminate/Database/Connection.html)  |  `db.connection`
Event  |  [Illuminate\Events\Dispatcher](https://laravel.com/api/{{version}}/Illuminate/Events/Dispatcher.html)  |  `events`
File  |  [Illuminate\Filesystem\Filesystem](https://laravel.com/api/{{version}}/Illuminate/Filesystem/Filesystem.html)  |  `files`
Gate  |  [Illuminate\Contracts\Auth\Access\Gate](https://laravel.com/api/{{version}}/Illuminate/Contracts/Auth/Access/Gate.html)  |
Hash  |  [Illuminate\Contracts\Hashing\Hasher](https://laravel.com/api/{{version}}/Illuminate/Contracts/Hashing/Hasher.html)  |  `hash`
Lang  |  [Illuminate\Translation\Translator](https://laravel.com/api/{{version}}/Illuminate/Translation/Translator.html)  |  `translator`
Log  |  [Illuminate\Log\Writer](https://laravel.com/api/{{version}}/Illuminate/Log/Writer.html)  |  `log`
Mail  |  [Illuminate\Mail\Mailer](https://laravel.com/api/{{version}}/Illuminate/Mail/Mailer.html)  |  `mailer`
Notification  |  [Illuminate\Notifications\ChannelManager](https://laravel.com/api/{{version}}/Illuminate/Notifications/ChannelManager.html)  |
Password  |  [Illuminate\Auth\Passwords\PasswordBrokerManager](https://laravel.com/api/{{version}}/Illuminate/Auth/Passwords/PasswordBrokerManager.html)  |  `auth.password`
Password (Instance)  |  [Illuminate\Auth\Passwords\PasswordBroker](https://laravel.com/api/{{version}}/Illuminate/Auth/Passwords/PasswordBroker.html)  |  `auth.password.broker`
Queue  |  [Illuminate\Queue\QueueManager](https://laravel.com/api/{{version}}/Illuminate/Queue/QueueManager.html)  |  `queue`
Queue (Instance)  |  [Illuminate\Contracts\Queue\Queue](https://laravel.com/api/{{version}}/Illuminate/Contracts/Queue/Queue.html)  |  `queue.connection`
Queue (Base Class)  |  [Illuminate\Queue\Queue](https://laravel.com/api/{{version}}/Illuminate/Queue/Queue.html)  |
Redirect  |  [Illuminate\Routing\Redirector](https://laravel.com/api/{{version}}/Illuminate/Routing/Redirector.html)  |  `redirect`
Redis  |  [Illuminate\Redis\RedisManager](https://laravel.com/api/{{version}}/Illuminate/Redis/RedisManager.html)  |  `redis`
Redis (Instance)  |  [Illuminate\Redis\Connections\Connection](https://laravel.com/api/{{version}}/Illuminate/Redis/Connections/Connection.html)  |  `redis.connection`
Request  |  [Illuminate\Http\Request](https://laravel.com/api/{{version}}/Illuminate/Http/Request.html)  |  `request`
Response  |  [Illuminate\Contracts\Routing\ResponseFactory](https://laravel.com/api/{{version}}/Illuminate/Contracts/Routing/ResponseFactory.html)  |
Response (Instance)  |  [Illuminate\Http\Response](https://laravel.com/api/{{version}}/Illuminate/Http/Response.html)  |
Route  |  [Illuminate\Routing\Router](https://laravel.com/api/{{version}}/Illuminate/Routing/Router.html)  |  `router`
Schema  |  [Illuminate\Database\Schema\Builder](https://laravel.com/api/{{version}}/Illuminate/Database/Schema/Builder.html)  |
Session  |  [Illuminate\Session\SessionManager](https://laravel.com/api/{{version}}/Illuminate/Session/SessionManager.html)  |  `session`
Session (Instance)  |  [Illuminate\Session\Store](https://laravel.com/api/{{version}}/Illuminate/Session/Store.html)  |  `session.store`
Storage  |  [Illuminate\Filesystem\FilesystemManager](https://laravel.com/api/{{version}}/Illuminate/Filesystem/FilesystemManager.html)  |  `filesystem`
Storage (Instance)  |  [Illuminate\Contracts\Filesystem\Filesystem](https://laravel.com/api/{{version}}/Illuminate/Contracts/Filesystem/Filesystem.html)  |  `filesystem.disk`
URL  |  [Illuminate\Routing\UrlGenerator](https://laravel.com/api/{{version}}/Illuminate/Routing/UrlGenerator.html)  |  `url`
Validator  |  [Illuminate\Validation\Factory](https://laravel.com/api/{{version}}/Illuminate/Validation/Factory.html)  |  `validator`
Validator (Instance)  |  [Illuminate\Validation\Validator](https://laravel.com/api/{{version}}/Illuminate/Validation/Validator.html)  |
View  |  [Illuminate\View\Factory](https://laravel.com/api/{{version}}/Illuminate/View/Factory.html)  |  `view`
View (Instance)  |  [Illuminate\View\View](https://laravel.com/api/{{version}}/Illuminate/View/View.html)  |


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<software-distribution project="MinGW" home="http://mingw.org" issue="2012073100">

  <!-- File: msys-findutils.xml -->

  <package-collection subsystem="msys">
    <download-host uri="http://prdownloads.sourceforge.net/mingw/%F?download" />

    <package name="msys-findutils">
      <affiliate group="MSYS Base System" />
      <description lang="en" title="GNU find utilities" >
        <paragraph>The GNU Find Utilities are the basic directory searching
          utilities of the GNU operating system. These programs are
          typically used in conjunction with other programs to provide
          modular and powerful directory search and file locating
          capabilities to other commands.
        </paragraph>
        <paragraph>The msys-findutils package provides 'find' -- search
          for files in a directory hierarchy, and 'xargs' -- build and
          execute command lines from standard input. The associated
          msys-locate package provides 'locate' -- list files in databases
          that match a pattern, and 'updatedb' -- update a file name
          database.
        </paragraph>
      </description>

      <source tarname="findutils-%-msys-%-src.tar.%" />
      <licence tarname="findutils-%-msys-%-lic.tar.%" />

      <component class="bin">
        <requires eq="msys-core-*-msys-*-bin.tar" />
        <release tarname="findutils-4.4.2-2-msys-1.0.13-bin.tar.lzma" >
          <requires eq="msys-libintl-*-msys-*-dll-8.tar" />
        </release>
      </component>

      <component class="lang">
        <release tarname="findutils-4.4.2-2-msys-1.0.13-lang.tar.lzma" />
      </component>

      <component class="doc">
        <release tarname="findutils-4.4.2-2-msys-1.0.13-doc.tar.lzma" />
      </component>

      <component class="lic">
        <release tarname="findutils-4.4.2-2-msys-1.0.13-lic.tar.lzma" />
      </component>
    </package>

    <package name="msys-locate">
      <affiliate group="MSYS Base System" />
      <description lang="en" title="A database-driven fast 'find'" >
        <paragraph>The GNU Find Utilities are the basic directory searching
          utilities of the GNU operating system. These programs are
          typically used in conjunction with other programs to provide
          modular and powerful directory search and file locating
          capabilities to other commands.
        </paragraph>
        <paragraph>The msys-locate package provides 'locate' -- list files
          in databases that match a pattern, and 'updatedb' -- update a
          file name database. The associated msys-findutils package
          provides 'find' -- search for files in a directory hierarchy, and
          'xargs' -- build and execute command lines from standard input.
        </paragraph>
        <paragraph>The msys-locate package is an optional adjunct to the
          standard MSYS Base System installation; it is NOT automatically
          installed as a component of msys-base, and must be selected
          independently, if desired.
        </paragraph>
      </description>

      <source tarname="findutils-%-msys-%-src.tar.%" />
      <licence tarname="findutils-%-msys-%-lic.tar.%" />

      <component class="bin">
        <requires eq="msys-core-*-msys-*-bin.tar" />
        <release tarname="locate-4.4.2-2-msys-1.0.13-bin.tar.lzma" >
          <requires eq="msys-libintl-*-msys-*-dll-8.tar" />
        </release>
        <requires eq="msys-bash-*-msys-*-bin.tar" />
        <requires eq="msys-coreutils-*-msys-*-bin.tar" />
        <requires eq="msys-findutils-%-msys-%-bin.tar" />
      </component>
    </package>

  </package-collection>
</software-distribution>
<!-- vim: set nocompatible expandtab fileformat=unix textwidth=80 tabstop=2 shiftwidth=2: -->


text:
{% extends "base.html" %}

{% block body %}

Registration is completed!

You are almost done! Please follow the link that was sent to your email address to activate your account.

{% endblock %}


text:
using System;

public class Robot
{
    private static readonly Random Random = new Random();

    public string Name { get; private set; }

    public Robot()
    {
        Reset();
    }

    private static string GenerateName()
    {
        return GetRandomCharacter() + GetRandomCharacter() + Random.Next(1000).ToString("000");
    }

    private static string GetRandomCharacter()
    {
        return ((char)('A' + Random.Next(26))).ToString();
    }

    public void Reset()
    {
        Name = GenerateName();
    }
}


text:
v0.0.4
------

**Date: 2015-04-16**

- Added COM Support Check
- Added User Password Recovery Field
- Added Authentication Clients
- Added Google Recaptcha

v0.0.3
------

**Date: 2015-02-08**

- Added Mailer
- Linked Mailer to Database
- Fixed Typos and Bugs
- Added useTransport to the mailer component
- Added Check to see whether the application has been successfully installed
- Updated View
- Fixed User table
- Fixed Mailer View

v0.0.2
------

**Date: 2015-02-08**

- Added Auto Migrate Feature [still buggy]
- Fixed Bugs
- Fixed Views

v0.0.1
------

**Date: 2015-02-08**

- Initial Release


text:
from parker.library import ParkerLibrary

from mock import Mock

class TestLib(object):

    def test_register_object(self):
        pl = ParkerLibrary()
        mcarrier = Mock()
        mcarrier.return_value = 'instance?'
        mcarrier.name = 'test_name'
        pl.register(mcarrier)
        assert pl.carriers['test_name'] == 'instance?'

    def test_getitem(self):
        pl = ParkerLibrary()
        mcarrier = Mock()
        mcarrier.return_value = 'instance?'
        mcarrier.name = 'test_name'
        pl.register(mcarrier)
        assert pl['test_name'] == 'instance?'


text:
package com.knowweather.app.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.knowweather.app.db.KnowWeatherDB;
import com.knowweather.app.model.City;
import com.knowweather.app.model.Country;
import com.knowweather.app.model.Province;

public class Utility {

	public synchronized static boolean handleProvincesResponse(KnowWeatherDB knowWeatherDB, String response) {
		if (!TextUtils.isEmpty(response)) {
			String[] allProvinces = response.split(",");
			if (allProvinces != null && allProvinces.length > 0) {
				for (String p : allProvinces) {
					String[] array = p.split("\\|");
					Province province = new Province();
					province.setProvinceCode(array[0]);
					province.setProvinceName(array[1]);
					knowWeatherDB.saveProvince(province);
				}
				return true;
			}
		}
		return false;
	}

	public synchronized static boolean handleCitiesResponse(KnowWeatherDB knowWeatherDB, String response, int provinceId) {
		if (!TextUtils.isEmpty(response)) {
			String[] allCities = response.split(",");
			if (allCities != null && allCities.length > 0) {
				for (String p : allCities) {
					String[] array = p.split("\\|");
					City city = new City();
					city.setCityCode(array[0]);
					city.setCityName(array[1]);
					city.setProvinceId(provinceId);
					knowWeatherDB.saveCity(city);
				}
				return true;
			}
		}
		return false;
	}

	public synchronized static boolean handleCountriesResponse(KnowWeatherDB knowWeatherDB, String response, int cityId) {
		if (!TextUtils.isEmpty(response)) {
			String[] allCountries = response.split(",");
			if (allCountries != null && allCountries.length > 0) {
				for (String p : allCountries) {
					String[] array = p.split("\\|");
					Country country = new Country();
					country.setCountryCode(array[0]);
					country.setCountryName(array[1]);
					country.setCityId(cityId);
					knowWeatherDB.saveCountry(country);
				}
				return true;
			}
		}
		return false;
	}

	public static void handleWeatherResponse(Context context, String response) {
		try {
			JSONObject jsonObject = new JSONObject(response);
			JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");
			String cityName = weatherInfo.getString("city");
			String weatherCode = weatherInfo.getString("cityid");
			String temp1 = weatherInfo.getString("temp1");
			String temp2 = weatherInfo.getString("temp2");
			String weatherDesp = weatherInfo.getString("weather");
			String publishTime = weatherInfo.getString("ptime");
			saveWeatherInfo(context, cityName, weatherCode, temp1, temp2, weatherDesp, publishTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void saveWeatherInfo(Context context, String cityName,
			String weatherCode, String temp1, String temp2, String weatherDesp,
			String publishTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyÄêMÔÂdÈÕ",Locale.CHINA);
		SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
		editor.putBoolean("city_selected", true);
		editor.putString("city_name", cityName);
		editor.putString("weather_code", weatherCode);
		editor.putString("temp1", temp1);
		editor.putString("temp2", temp2);
		editor.putString("weather_desp", weatherDesp);
		editor.putString("publish_time", publishTime);
		editor.putString("current_date", sdf.format(new Date()));
		editor.commit();

	}

}


text:
<?php

class AdminStatesController extends AdminStatesControllerCore
{

}


text:
package org.apache.flink.runtime.state;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.state.InternalCheckpointListener;
import org.apache.flink.api.common.state.State;
import org.apache.flink.api.common.state.StateDescriptor;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.core.fs.CloseableRegistry;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
import org.apache.flink.runtime.checkpoint.SnapshotType;
import org.apache.flink.runtime.query.TaskKvStateRegistry;
import org.apache.flink.runtime.state.heap.InternalKeyContext;
import org.apache.flink.runtime.state.internal.InternalKvState;
import org.apache.flink.runtime.state.metrics.LatencyTrackingStateConfig;
import org.apache.flink.runtime.state.metrics.LatencyTrackingStateFactory;
import org.apache.flink.runtime.state.ttl.TtlStateFactory;
import org.apache.flink.runtime.state.ttl.TtlTimeProvider;
import org.apache.flink.util.IOUtils;
import org.apache.flink.util.Preconditions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.Stream;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * Base implementation of KeyedStateBackend. The state can be checkpointed to streams using {@link
 * #snapshot(long, long, CheckpointStreamFactory, CheckpointOptions)}.
 *
 * @param <K> Type of the key by which state is keyed.
 */
public abstract class AbstractKeyedStateBackend<K>
        implements CheckpointableKeyedStateBackend<K>,
                InternalCheckpointListener,
                TestableKeyedStateBackend<K>,
                InternalKeyContext<K> {

    /** The key serializer. */
    protected final TypeSerializer<K> keySerializer;

    /** Listeners to changes of ({@link #keyContext}). */
    private final ArrayList<KeySelectionListener<K>> keySelectionListeners;

    /** So that we can give out state when the user uses the same key. */
    private final HashMap<String, InternalKvState<K, ?, ?>> keyValueStatesByName;

    /** For caching the last accessed partitioned state. */
    private String lastName;

    @SuppressWarnings("rawtypes")
    private InternalKvState lastState;

    /** The number of key-groups aka max parallelism. */
    protected final int numberOfKeyGroups;

    /** Range of key-groups for which this backend is responsible. */
    protected final KeyGroupRange keyGroupRange;

    /** KvStateRegistry helper for this task. */
    protected final TaskKvStateRegistry kvStateRegistry;

    /**
     * Registry for all opened streams, so they can be closed if the task using this backend is
     * closed.
     */
    protected CloseableRegistry cancelStreamRegistry;

    protected final ClassLoader userCodeClassLoader;

    private final ExecutionConfig executionConfig;

    protected final TtlTimeProvider ttlTimeProvider;

    protected final LatencyTrackingStateConfig latencyTrackingStateConfig;

    /** Decorates the input and output streams to write key-groups compressed. */
    protected final StreamCompressionDecorator keyGroupCompressionDecorator;

    /** The key context for this backend. */
    protected final InternalKeyContext<K> keyContext;

    public AbstractKeyedStateBackend(
            TaskKvStateRegistry kvStateRegistry,
            TypeSerializer<K> keySerializer,
            ClassLoader userCodeClassLoader,
            ExecutionConfig executionConfig,
            TtlTimeProvider ttlTimeProvider,
            LatencyTrackingStateConfig latencyTrackingStateConfig,
            CloseableRegistry cancelStreamRegistry,
            InternalKeyContext<K> keyContext) {
        this(
                kvStateRegistry,
                keySerializer,
                userCodeClassLoader,
                executionConfig,
                ttlTimeProvider,
                latencyTrackingStateConfig,
                cancelStreamRegistry,
                determineStreamCompression(executionConfig),
                keyContext);
    }

    public AbstractKeyedStateBackend(
            TaskKvStateRegistry kvStateRegistry,
            TypeSerializer<K> keySerializer,
            ClassLoader userCodeClassLoader,
            ExecutionConfig executionConfig,
            TtlTimeProvider ttlTimeProvider,
            LatencyTrackingStateConfig latencyTrackingStateConfig,
            CloseableRegistry cancelStreamRegistry,
            StreamCompressionDecorator keyGroupCompressionDecorator,
            InternalKeyContext<K> keyContext) {
        this.keyContext = Preconditions.checkNotNull(keyContext);
        this.numberOfKeyGroups = keyContext.getNumberOfKeyGroups();
        this.keyGroupRange = Preconditions.checkNotNull(keyContext.getKeyGroupRange());
        Preconditions.checkArgument(
                numberOfKeyGroups >= 1, "NumberOfKeyGroups must be a positive number");
        Preconditions.checkArgument(
                numberOfKeyGroups >= keyGroupRange.getNumberOfKeyGroups(),
                "The total number of key groups must be at least the number in the key group range assigned to this backend. "
                        + "The total number of key groups: %s, the number in key groups in range: %s",
                numberOfKeyGroups,
                keyGroupRange.getNumberOfKeyGroups());

        this.kvStateRegistry = kvStateRegistry;
        this.keySerializer = keySerializer;
        this.userCodeClassLoader = Preconditions.checkNotNull(userCodeClassLoader);
        this.cancelStreamRegistry = cancelStreamRegistry;
        this.keyValueStatesByName = new HashMap<>();
        this.executionConfig = executionConfig;
        this.keyGroupCompressionDecorator = keyGroupCompressionDecorator;
        this.ttlTimeProvider = Preconditions.checkNotNull(ttlTimeProvider);
        this.latencyTrackingStateConfig = Preconditions.checkNotNull(latencyTrackingStateConfig);
        this.keySelectionListeners = new ArrayList<>(1);
    }

    private static StreamCompressionDecorator determineStreamCompression(
            ExecutionConfig executionConfig) {
        if (executionConfig != null && executionConfig.isUseSnapshotCompression()) {
            return SnappyStreamCompressionDecorator.INSTANCE;
        } else {
            return UncompressedStreamCompressionDecorator.INSTANCE;
        }
    }

    @Override
    public void notifyCheckpointSubsumed(long checkpointId) throws Exception {}

    /**
     * Closes the state backend, releasing all internal resources, but does not delete any
     * persistent checkpoint data.
     */
    @Override
    public void dispose() {

        IOUtils.closeQuietly(cancelStreamRegistry);

        if (kvStateRegistry != null) {
            kvStateRegistry.unregisterAll();
        }

        lastName = null;
        lastState = null;
        keyValueStatesByName.clear();
    }

    /** @see KeyedStateBackend */
    @Override
    public void setCurrentKey(K newKey) {
        notifyKeySelected(newKey);
        this.keyContext.setCurrentKey(newKey);
        this.keyContext.setCurrentKeyGroupIndex(
                KeyGroupRangeAssignment.assignToKeyGroup(newKey, numberOfKeyGroups));
    }

    private void notifyKeySelected(K newKey) {
        // we prefer a for-loop over other iteration schemes for performance reasons here.
        for (int i = 0; i < keySelectionListeners.size(); ++i) {
            keySelectionListeners.get(i).keySelected(newKey);
        }
    }

    @Override
    public void registerKeySelectionListener(KeySelectionListener<K> listener) {
        keySelectionListeners.add(listener);
    }

    @Override
    public boolean deregisterKeySelectionListener(KeySelectionListener<K> listener) {
        return keySelectionListeners.remove(listener);
    }

    /** @see KeyedStateBackend */
    @Override
    public TypeSerializer<K> getKeySerializer() {
        return keySerializer;
    }

    /** @see KeyedStateBackend */
    @Override
    public K getCurrentKey() {
        return this.keyContext.getCurrentKey();
    }

    /** @see KeyedStateBackend */
    public int getCurrentKeyGroupIndex() {
        return this.keyContext.getCurrentKeyGroupIndex();
    }

    /** @see KeyedStateBackend */
    public int getNumberOfKeyGroups() {
        return numberOfKeyGroups;
    }

    /** @see KeyedStateBackend */
    @Override
    public KeyGroupRange getKeyGroupRange() {
        return keyGroupRange;
    }

    /** @see KeyedStateBackend */
    @Override
    public <N, S extends State, T> void applyToAllKeys(
            final N namespace,
            final TypeSerializer<N> namespaceSerializer,
            final StateDescriptor<S, T> stateDescriptor,
            final KeyedStateFunction<K, S> function)
            throws Exception {

        applyToAllKeys(
                namespace,
                namespaceSerializer,
                stateDescriptor,
                function,
                this::getPartitionedState);
    }

    public <N, S extends State, T> void applyToAllKeys(
            final N namespace,
            final TypeSerializer<N> namespaceSerializer,
            final StateDescriptor<S, T> stateDescriptor,
            final KeyedStateFunction<K, S> function,
            final PartitionStateFactory partitionStateFactory)
            throws Exception {

        try (Stream<K> keyStream = getKeys(stateDescriptor.getName(), namespace)) {

            final S state =
                    partitionStateFactory.get(namespace, namespaceSerializer, stateDescriptor);

            keyStream.forEach(
                    (K key) -> {
                        setCurrentKey(key);
                        try {
                            function.process(key, state);
                        } catch (Throwable e) {
                            // we wrap the checked exception in an unchecked
                            // one and catch it (and re-throw it) later.
                            throw new RuntimeException(e);
                        }
                    });
        }
    }

    /** @see KeyedStateBackend */
    @Override
    @SuppressWarnings("unchecked")
    public <N, S extends State, V> S getOrCreateKeyedState(
            final TypeSerializer<N> namespaceSerializer, StateDescriptor<S, V> stateDescriptor)
            throws Exception {
        checkNotNull(namespaceSerializer, "Namespace serializer");
        checkNotNull(
                keySerializer,
                "State key serializer has not been configured in the config. "
                        + "This operation cannot use partitioned state.");

        InternalKvState<K, ?, ?> kvState = keyValueStatesByName.get(stateDescriptor.getName());
        if (kvState == null) {
            if (!stateDescriptor.isSerializerInitialized()) {
                stateDescriptor.initializeSerializerUnlessSet(executionConfig);
            }
            kvState =
                    LatencyTrackingStateFactory.createStateAndWrapWithLatencyTrackingIfEnabled(
                            TtlStateFactory.createStateAndWrapWithTtlIfEnabled(
                                    namespaceSerializer, stateDescriptor, this, ttlTimeProvider),
                            stateDescriptor,
                            latencyTrackingStateConfig);
            keyValueStatesByName.put(stateDescriptor.getName(), kvState);
            publishQueryableStateIfEnabled(stateDescriptor, kvState);
        }
        return (S) kvState;
    }

    public void publishQueryableStateIfEnabled(
            StateDescriptor<?, ?> stateDescriptor, InternalKvState<?, ?, ?> kvState) {
        if (stateDescriptor.isQueryable()) {
            if (kvStateRegistry == null) {
                throw new IllegalStateException("State backend has not been initialized for job.");
            }
            String name = stateDescriptor.getQueryableStateName();
            kvStateRegistry.registerKvState(keyGroupRange, name, kvState, userCodeClassLoader);
        }
    }

    /**
     * TODO: NOTE: This method does a lot of work caching / retrieving states just to update the
     * namespace. This method should be removed for the sake of namespaces being lazily fetched from
     * the keyed state backend, or being set on the state directly.
     *
     * @see KeyedStateBackend
     */
    @SuppressWarnings("unchecked")
    @Override
    public <N, S extends State> S getPartitionedState(
            final N namespace,
            final TypeSerializer<N> namespaceSerializer,
            final StateDescriptor<S, ?> stateDescriptor)
            throws Exception {

        checkNotNull(namespace, "Namespace");

        if (lastName != null && lastName.equals(stateDescriptor.getName())) {
            lastState.setCurrentNamespace(namespace);
            return (S) lastState;
        }

        InternalKvState<K, ?, ?> previous = keyValueStatesByName.get(stateDescriptor.getName());
        if (previous != null) {
            lastState = previous;
            lastState.setCurrentNamespace(namespace);
            lastName = stateDescriptor.getName();
            return (S) previous;
        }

        final S state = getOrCreateKeyedState(namespaceSerializer, stateDescriptor);
        final InternalKvState<K, N, ?> kvState = (InternalKvState<K, N, ?>) state;

        lastName = stateDescriptor.getName();
        lastState = kvState;
        kvState.setCurrentNamespace(namespace);

        return state;
    }

    @Override
    public void close() throws IOException {
        cancelStreamRegistry.close();
    }

    public LatencyTrackingStateConfig getLatencyTrackingStateConfig() {
        return latencyTrackingStateConfig;
    }

    @VisibleForTesting
    public StreamCompressionDecorator getKeyGroupCompressionDecorator() {
        return keyGroupCompressionDecorator;
    }

    @VisibleForTesting
    public int numKeyValueStatesByName() {
        return keyValueStatesByName.size();
    }

    // TODO remove this once heap-based timers are working with RocksDB incremental snapshots!
    public boolean requiresLegacySynchronousTimerSnapshots(SnapshotType checkpointType) {
        return false;
    }

    public InternalKeyContext<K> getKeyContext() {
        return keyContext;
    }

    public interface PartitionStateFactory {
        <N, S extends State> S get(
                final N namespace,
                final TypeSerializer<N> namespaceSerializer,
                final StateDescriptor<S, ?> stateDescriptor)
                throws Exception;
    }

    @Override
    public void setCurrentKeyGroupIndex(int currentKeyGroupIndex) {
        keyContext.setCurrentKeyGroupIndex(currentKeyGroupIndex);
    }
}


text:
//***************************  C Source Code  *****************************
//*************************************************************************
// vim: set ts=2 sw=2 tw=78 et :
//
//  DESIGNER NAME:  Ryan S. Tucker <rst7983@rit.edu>
//
//       LAB NAME:  Lab 7: Game System
//
//      FILE NAME:  codebreaker.c
//
//-------------------------------------------------------------------------
//
//  DESCRIPTION
//
//    This is an implementation of the CodeBreaker game.
//
//*************************************************************************
//*************************************************************************

#include <string.h>
#include "nios_std_types.h"         // for standard embedded types
#include "system.h"                 // for Qsys defines

#include "lfsr_if.h"
#include "pio_if.h"
#include "timer_if.h"
#include "uart_if.h"
#include "utilities.h"

#include "codebreaker.h"

//-------------------------------------------------------------------------
// NAME:        check_guess
//
// DESCRIPTION: Checks each character in the guess to determine if it is
//              in the actual secret code, and if so, whether it is in the
//              right position.
// ARGUMENTS:
//    secret  uint8*  pointer to the secret code (null-terminated string)
//    guess   uint8*  pointer to the user's guess (null-terminated string)
//    hint    uint8*  pointer to a place to put the guess (again, string)
// RETURNS:
//    uint32  TRUE or FALSE depending on whether they're a winner
//-------------------------------------------------------------------------
uint32 check_guess(uint8* secret, uint8* guess, uint8* hint)
{
  uint32  result  = FALSE;    /* end result */
  uint32  got_p   = FALSE;
  uint32  got_c   = FALSE;

  // Indices for loops
  uint32  secret_idx;
  uint32  guess_idx;
  uint32  hint_idx = 0;

  for (guess_idx = 0; guess_idx < CB_COLOR_LENGTH; guess_idx++)
  {
    if (NULL == guess[guess_idx])
    {
      // we're out of characters on the input
      result = FALSE;
      hint[hint_idx] = NULL;
      break;
    } /* if null */
    for (secret_idx = 0; secret_idx < CB_COLOR_LENGTH; secret_idx++)
    {
      if (NULL == secret[secret_idx])
      {
        // this is a big problem...
        uart_SendString((uint8*)"secret too short?  aborting check_guess\n");
        return FALSE;
      } /* if on fire */
      if (guess[guess_idx] == secret[secret_idx])
      {
        // we have a match!
        if (guess_idx == secret_idx)
        {
          // in the correct position!
          hint[hint_idx++] = 'P';
          got_p = TRUE;
        } /* if position */
        else
        {
          // not in the correct position!
          hint[hint_idx++] = 'C';
          got_c = TRUE;
        } /* else */
      } /* if match */
    } /* for secret_idx */
  } /* for guess_idx */

  if (got_p && !got_c && (CB_COLOR_LENGTH == hint_idx))
  {
    // We have a winner!
    result = TRUE;
  } /* if winner */

  // null-terminate the hint string
  hint[hint_idx] = NULL;

  return result;
} /* check_guess */

//-------------------------------------------------------------------------
// NAME:        game_loop
//
// DESCRIPTION: Main function of the game itself.  Ensures that the game
//              starts in a fresh state on every round.
// ARGUMENTS:   None
// RETURNS:     void
//-------------------------------------------------------------------------
void game_loop()
{
  uint32  secret_code;
  uint8   secret_code_str[CB_COLOR_LENGTH+1];
  uint8   input_str[UART_RECVBUFFER];
  uint8   hint_str[CB_COLOR_LENGTH+1];

  uint32  loser = FALSE;
  uint32  winner = FALSE;

  // Clear strings
  memset(secret_code_str, 0, sizeof(secret_code_str));
  memset(input_str, 0, sizeof(input_str));
  memset(hint_str, 0, sizeof(hint_str));

  // Set the UART mode to MAIN
  uart_SetMode(UART_MAINMODE);

  // Announce that a new game is starting
  uart_SendString((uint8*)CB_NEWGAME);

  // Wait for key1 press
  pio_key_pressed(1); // clear it
  uart_SendString((uint8*)CB_PRESSKEY1);
  while (!pio_key_pressed(1));

  // Clear LEDs
  pio_leds_update(FALSE, FALSE);

  // Generate secret code
  secret_code = generate_secret_code();
  #ifdef CHEAT_MODE
    // If we're under development, simply output the secret number...
    uart_SendString((uint8*)"Today's secret number is: ");
    to_colorstr(secret_code, (uint8*)secret_code_str);
    uart_SendString((uint8*)secret_code_str);
    uart_SendString((uint8*)"!\n");
  #endif /* CHEAT_MODE */

  // Start game by notifying user, switching to game input mode, and
  // starting the countdown timer.
  uart_SendString((uint8*)CB_GAMESTART);
  uart_SetMode(UART_GAMEMODE);
  timer_countdown_start(CB_COUNTDOWN_TIME);

  // Main gameplay loop
  while (!winner && !loser)
  {
    // Clear the input
    memset(input_str, 0, sizeof(input_str));

    // Display the prompt
    uart_SendString((uint8*)CB_PROMPT);

    // Wait for something to happen...
    while(1)
    {
      // check for incoming stuff from the UART
      uart_RecvString(input_str);

      // strip down to

      // check for key 2
      if (pio_key_pressed(2))
      {
        uart_SendString((uint8*)CB_YOUGUESSED);
        uart_SendString(input_str);
        uart_SendString((uint8*)"\n");
        break;
      } /* if key 2 pressed */

      // check time remaining
      if (timer_expired())
      {
        // sorry!
        loser = TRUE;
        break;
      } /* if timer_expired */
    } /* while idle */

    if(!loser)
    {
      winner = check_guess((uint8*)secret_code_str, (uint8*)input_str,
                           (uint8*)hint_str);
      if(!winner)
      {
        // Demoralize the opponent
        switch (lfsr_rand() % 4)
        {
          case 0:
            uart_SendString((uint8*)CB_NOTRIGHT1);
            break;
          case 1:
            uart_SendString((uint8*)CB_NOTRIGHT2);
            break;
          case 2:
            uart_SendString((uint8*)CB_NOTRIGHT3);
            break;
          case 3:
            uart_SendString((uint8*)CB_NOTRIGHT4);
            break;
          default:
            // This shouldn't happen with mod 4......
            uart_SendString((uint8*)"Bank error in your favor, collect $200.\n");
            break;
        } /* switch */

        // Display a hint
        uart_SendString((uint8*)CB_YOURHINT);
        uart_SendString((uint8*)hint_str);
        uart_SendString((uint8*)"\n");

      } /* if !winner */
    } /* if !loser */
  } /* while neither winner nor loser */

  // Display either win or lose
  pio_leds_update(loser, winner);
  if(loser)
  {
    timer_countdown_stop();
    uart_SendString((uint8*)CB_TIME_EXPIRED);
  } /* if loser */
  else if (winner)
  {
    timer_countdown_stop();
    uart_SendString((uint8*)CB_WINNER);
  } /* if winner */
  else
  {
    // ??  We shouldn't be here.
    uart_SendString((uint8*)"Error: you have neither won nor lost.");
  } /* else */
} /* game_loop */

//-------------------------------------------------------------------------
// NAME:        main
//
// DESCRIPTION: Main function of codebreaker program.  Handles system setup
//              tasks, briefing of user, and repeated calls to game_loop.
// ARGUMENTS:   None
// RETURNS:     int
//-------------------------------------------------------------------------
int main()
{
  // System initialization tasks
  //
  // Linear Feedback Shift Register PRNG
  // (Seed with the Qsys build timestamp)
  lfsr_rand_init((uint16)SYSID_QSYS_0_TIMESTAMP);
  // Peripheral I/O initialization
  pio_init();
  // Timer initialization
  timer_init();
  // UART initialization
  uart_init();

  // Set up a known initial state
  //
  // Shut off the seven-segment displays and LEDs
  pio_ssd_update(0, FALSE);
  pio_leds_update(FALSE, FALSE);
  // Stop the timer, which shouldn't be running anyway
  timer_countdown_stop();
  // Send the greeting to the user
  uart_SendString((uint8*)CB_WELCOME);
  uart_SendString((uint8*)CB_INSTRUCTIONS);

  // Play the game.  Check for LFSR validity while doing so, to ensure that
  // we have a random initial state...
  while(lfsr_rand_valid())
  {
    game_loop();
  } /* while 1 */

  return 0;
} /* main */


text:
"""
读取数据示例
"""
from kquant_data.api import get_price

pricing = get_price('600000.SH', instrument_type='stock')
print(pricing)
pricing = get_price(['600000.SH', '000001.SZ'], instrument_type='stock')
print(pricing)
pricing = get_price(['000001.SZ'], instrument_type='stock', start_date='2010-01-01')
print(pricing)
pricing = get_price(['000001.SZ'], instrument_type='stock', start_date='2010-01-01', bar_size=300, fields=['Close'])
print(pricing)
pricing = get_price(['000001.SZ'], instrument_type='stock', start_date='2010-01-01', bar_size=86400)
print(pricing)

# 拿到的价格是原始价格,需要自己复权

# 向前复权
pricing['Close_forward_factor'] = pricing['Close'] * pricing['forward_factor']
print(pricing.tail())
# 向后复权
pricing['Close_backward_factor'] = pricing['Close'] * pricing['backward_factor']
print(pricing)

pricing = get_price(['IF.'], start_date='2010-01-01', bar_size=86400)
print(pricing)


text:
ohai "ruby" do
  action :nothing
end

node[:ruby_installer][:package_removals].each do |r_pkg|
  package r_pkg do
    action :remove
  end
end

case node[:ruby_installer][:method]
when 'package'
  include_recipe 'ruby_installer::package'
when 'ree'
  include_recipe 'ruby_installer::ree'
when 'source'
  include_recipe 'ruby_installer::source'
else
  Chef::Log.error "[ruby_installer]: Unknown installation method requested (#{node[:ruby_installer][:method]})"
  raise "Unknown ruby installation method requested"
end


text:
#ifndef GENERIC_EVENT_MANAGER_HPP_
#define GENERIC_EVENT_MANAGER_HPP_

#include "event_set.h"
#include "event_manager.hpp"
#include <algorithm>

#include <list>
#include <vector>
#include <set>
#include <deque>

#include "event_functor.h"

#include "ltsf_queue.3.hpp"

using std::list;
using std::vector;
using std::multiset;
using std::upper_bound;

template < class E, class ES >
class EventManager : public event_manager< E > {
public:
    typedef typename event_manager< E >::event_t event_t;
    typedef ES event_set_t;
    typedef typename event_set_t::iterator iterator;

    EventManager();
    bool insertEvent( const event_t * );
    void reset_pending();

    const event_t * getEvent( const system_id & );
    const event_t * peekEvent(const system_id & ) const;

    size_t pendingEventCount(const system_id & ) const;
    size_t processedEventCount(const system_id & ) const;
    size_t canceledEventCount(const system_id & ) const;

    virtual ~EventManager();
};

template < class E >
class EventManager < E, std::list< const E * > > : virtual public event_manager< E > {
public:
    typedef typename event_manager< E >::event_t event_t;
    typedef std::list< const event_t * > event_set_t;
    typedef typename event_set_t::iterator iterator;

    EventManager() :
        m_events( ),
        m_head( m_events.begin() ),
        m_nPending(0),
        m_nProcessed(0),
        m_nCanceled(0) {
    }

    bool insertEvent( const event_t * evt ) {
        iterator pos = upper_bound( m_head, m_events.end(), evt, ltsf_event_order());

        bool res = false;
        if( pos == m_head ) {
            m_head = m_events.insert( pos, evt );
            res = true;
        } else {
            m_events.insert( pos, evt );
        }
        ++m_nPending;
        return res;
    }

    void reset_pending() {
        while( !m_events.empty() ) {
            const event * t = m_events.back();
            m_events.pop_back();
            if( t ) delete t;
            --m_nPending;
            ++m_nCanceled;
        }

        assert( m_nPending == 0 );
    }

    void reset_processed() {
        while( m_events.begin() != m_head ) {
            const event * t = *m_events.begin();
            m_events.pop_front();
            if( t ) delete t;
        }
    }

    const event_t * getEvent( const system_id & ) {
        if( m_head == m_events.end() ) return NULL;

        const event * t = *m_head++;
        --m_nPending;
        ++m_nProcessed;
        return t;
    }

    const event_t * peekEvent(const system_id & ) const {
        return ((m_head == m_events.end() ) ? NULL : *m_head);
    }

    size_t pendingEventCount(const system_id & ) const {
        return m_nPending;
    }

    size_t processedEventCount(const system_id & ) const {
        return m_nProcessed;
    }

    size_t canceledEventCount( const system_id & ) const {
        return m_nCanceled;
    }

    virtual ~EventManager() {
        while( !m_events.empty() ) {
            const event * t = m_events.back();
            m_events.pop_back();
            if( t ) delete t;
        }
    }
protected:
    event_set_t   m_events;

    iterator    m_head;
    size_t      m_nPending, m_nProcessed, m_nCanceled;
};

template < class E >
class EventManager< E, std::vector< const E * > > : virtual public event_manager < E > {
public:
    typedef typename event_manager< E >::event_t event_t;
    typedef std::vector< const event_t * > event_set_t;
    typedef typename event_set_t::iterator iterator;

    EventManager() :
        m_events(),
        m_head(0),
        m_nProcessed(0),
        m_nCanceled(0) {
    }

    bool insertEvent( const event_t * e ) {
        if( e == NULL ) return false;

        iterator s = m_events.begin() + m_head;
        iterator pos = upper_bound( s, m_events.end(), e, ltsf_event_order());

        m_events.insert( pos, e );
        return (*(m_events.begin() + m_head) == e);
    }

    void reset_pending() {
        while( m_events.begin() + m_head != m_events.end() ) {
            const event * t = m_events.back();
            m_events.pop_back();
            if( t ) delete t;
            ++m_nCanceled;
        }
    }

    void reset_processed() {
        while( m_head != 0 ) {
            const event * t = m_events[ --m_head ];
            m_events.erase( m_events.begin() + m_head );

            if( t ) delete t;
            ++m_nProcessed;
        }
    }

    const event_t * getEvent( const system_id & ) {
        return ((m_head >= m_events.size() ) ? NULL : m_events[m_head++]);
    }

    const event_t * peekEvent( const system_id & ) const {
        return ((m_head >= m_events.size() ) ? NULL : m_events[m_head]);
    }

    size_t pendingEventCount( const system_id & ) const {
        return m_events.size() - m_head;
    }

    size_t processedEventCount( const system_id & ) const {
        return m_head + m_nProcessed;
    }

    size_t canceledEventCount( const system_id & ) const {
        return m_nCanceled;
    }

    virtual ~EventManager() {
        while( !m_events.empty() ) {
            const event * t = m_events.back();
            m_events.pop_back();
            if( t ) delete t;
        }
    }

protected:
    event_set_t     m_events;
    size_t      m_head;
    size_t      m_nProcessed, m_nCanceled;
};

template < class E >
class EventManager<E, std::multiset< const E *, ltsf_event_order > > : virtual public event_manager< E > {
public:
    typedef typename event_manager< E >::event_t event_t;
    typedef std::multiset< const E *, ltsf_event_order > event_set_t;
    typedef typename event_set_t::iterator iterator;

    EventManager() :
        m_events(),
        m_processed(),
        m_nProcessed(0),
        m_nCanceled(0) {
    }

    bool insertEvent( const event_t * e ) {
        iterator it = m_events.insert( e );
        return (m_events.begin() == it );
    }

    void reset_pending() {
        while(!m_events.empty() ) {
            const event * t = *(m_events.begin());
            m_events.erase( m_events.begin());
            if(t) delete t;
            ++m_nCanceled;
        }
    }

    void reset_processed() {
        while( !m_processed.empty() ) {
            const event * t = m_processed.back();
            m_processed.pop_back();
            if( t ) delete t;
            ++m_nProcessed;
        }
    }

    const event_t * getEvent( const system_id & ) {
        if( m_events.empty() ) return NULL;
        const event_t * t = *(m_events.begin());
        m_events.erase( m_events.begin() );
        m_processed.push_back(t);
        //std::cout << "Got Event - " << *t << std::endl;
        return t;
    }

    const event_t * peekEvent( const system_id & ) const {
        if( m_events.empty() ) return NULL;
        return *(m_events.begin());
    }

    size_t pendingEventCount( const system_id & ) const {
        return m_events.size();
    }

    size_t processedEventCount( const system_id & ) const {
        return m_nProcessed + m_processed.size();
    }

    size_t  canceledEventCount( const system_id & ) const {
        return m_nCanceled;
    }

    virtual ~EventManager() {
        reset_pending();
        reset_processed();
    }
protected:
    event_set_t m_events;

    std::deque< const event_t * > m_processed;
    size_t  m_nProcessed, m_nCanceled;
};

template < class E >
class EventManager<E, ltsf_queue< typename E::vtime_t, E > > : virtual public event_manager< E > {
public:
    typedef typename event_manager< E >::event_t event_t;
    typedef typename event_manager< E >::vtime_t vtime_t;
    typedef ltsf_queue< vtime_t , /*const*/ E > event_set_t;

    EventManager() :
        m_events(),
//        m_processed(),
        m_nProcessed(0),
        m_nCanceled(0) {
    }

    bool insertEvent( event_t * e ) {
        vtime_t t = e->getReceived();
        return insertEventAt( e, t );
    }

    bool insertEventAt( event_t * e, const vtime_t & t ) {
        return m_events.enqueue( e, t );
    }

    void reset_pending() {
        while(m_events.size() != 0 ) {
            event_t * e = m_events.dequeue();
            if( e ) {
                delete e;
                //e->release();
                ++m_nCanceled;
            }
        }
    }

    void reset_processed() {
//        while( !m_processed.empty() ) {
//            event_t * t = m_processed.back();
//            m_processed.pop_back();
//            if( t ) {
//            //    delete t;
//               t->release();
//            }
//            ++m_nProcessed;
//        }
    }

    event_t * getEvent( const system_id & ) {
        event_t * t = m_events.dequeue();
        if( t != NULL ) {
            //    m_processed.push_back(t);
            ++m_nProcessed;
        }
        return t;
    }

    event_t * peekEvent( const system_id & ) const {
        return m_events.peek();
    }

    size_t pendingEventCount( const system_id & ) const {
        return m_events.size();
    }

    size_t processedEventCount( const system_id & ) const {
        return m_nProcessed /* + m_processed.size()*/;
    }

    size_t  canceledEventCount( const system_id & ) const {
        return m_nCanceled;
    }

    virtual ~EventManager() {
        reset_pending();
        //reset_processed();
    }
protected:
    event_set_t m_events;

    //std::vector< event_t * > m_processed;
    size_t  m_nProcessed, m_nCanceled;
};

#endif  // GENERIC_EVENT_MANAGER_HPP_


text:
using System;
using System.Collections.Generic;

namespace Igloo.Tools
{
    public class TemplateCollection : Dictionary<string, Template>
    {
        private Dictionary<string, Func<string, Template, bool>> _onAddCallbacks = new Dictionary<string, Func<string, Template, bool>>();
        private Dictionary<string, Func<string, bool>> _onIndexerGetCallbacks = new Dictionary<string, Func<string, bool>>();
        private Dictionary<string, Func<string, Template, bool>> _onIndexerSetCallbacks = new Dictionary<string, Func<string, Template, bool>>();

        public void Add(string key, Template template, Func<string, Template, bool> onAdding)
        {
            if (!_onAddCallbacks.ContainsKey(key))
            {
                _onAddCallbacks.Add(key, onAdding);
            }
            else
            {
                _onAddCallbacks[key] = onAdding;
            }

            if (onAdding(key, template))
            {
                base.Add(key, template);
            }
        }

        public new void Add(string key, Template template)
        {
            Func<string, Template, bool> onAdding;

            if (_onAddCallbacks.TryGetValue(key, out onAdding))
            {
                if (onAdding(key, template))
                {
                    base.Add(key, template);
                }
            }
            else
            {
                base.Add(key, template);
            }
        }

        public Template this[string key, Func<string, bool> onIndexerGet, Func<string, Template, bool> onIndexerSet]
        {
            get
            {
                if (!_onIndexerGetCallbacks.ContainsKey(key))
                {
                    _onIndexerGetCallbacks.Add(key, onIndexerGet);
                }
                else
                {
                    _onIndexerGetCallbacks[key] = onIndexerGet;
                }

                if (onIndexerGet(key))
                {
                    return base[key];
                }

                return null;
            }
            set
            {
                if (!_onIndexerSetCallbacks.ContainsKey(key))
                {
                    _onIndexerSetCallbacks.Add(key, onIndexerSet);
                }
                else
                {
                    _onIndexerSetCallbacks[key] = onIndexerSet;
                }

                if (onIndexerSet(key, value))
                {
                    base[key] = value;
                }
            }
        }

        public new Template this[string key]
        {
            get
            {
                Func<string, bool> onIndexerGet;
                if (_onIndexerGetCallbacks.TryGetValue(key, out onIndexerGet))
                {
                    if (onIndexerGet(key))
                    {
                        return base[key];
                    }
                    return null;
                }
                else
                {
                    return base[key];
                }
            }
            set
            {
                Func<string, Template, bool> onIndexerSet;
                if (_onIndexerSetCallbacks.TryGetValue(key, out onIndexerSet))
                {
                    if (onIndexerSet(key, value))
                    {
                        base[key] = value;
                    }
                }
                else
                {
                    base[key] = value;
                }
            }
        }
    }
}


text:
package org.springframework.beans.factory.support;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.DependencyDescriptor;

/**
 * {@link AutowireCandidateResolver} implementation to use when no annotation
 * support is available. This implementation checks the bean definition only.
 *
 * @author Mark Fisher
 * @author Juergen Hoeller
 * @since 2.5
 * @see BeanDefinition#isAutowireCandidate()
 */
public class SimpleAutowireCandidateResolver implements AutowireCandidateResolver {

	/**
	 * Determine if the provided bean definition is an autowire candidate.
	 *
To be considered a candidate the bean's autowire-candidate
	 * attribute must not have been set to 'false'.
	 */
	@Override
	public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
		return bdHolder.getBeanDefinition().isAutowireCandidate();
	}

	@Override
	public Object getSuggestedValue(DependencyDescriptor descriptor) {
		return null;
	}

	@Override
	public Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, String beanName) {
		return null;
	}

}