text:
@class HTMLElement;

@interface CSSSelectorTest : NSObject

@property (nonatomic, copy) NSString *testName;
@property (nonatomic, strong) NSArray *selectors;
@property (nonatomic, strong) HTMLElement *testDOM;

+ (NSArray *)loadCSSSelectorTests;

@end


text:
/**
 *
 * @file ssygst.c
 *
 *  PLASMA computational routines
 *  PLASMA is a software package provided by Univ. of Tennessee,
 *  Univ. of California Berkeley and Univ. of Colorado Denver
 *
 * @version 2.4.2
 * @author Hatem Ltaief
 * @date 2010-11-15
 * @generated s Thu Sep 15 12:09:18 2011
 *
 **/
#include "common.h"

/***************************************************************************//**
 *
 * @ingroup float
 *
 *  PLASMA_ssygst - reduces a complex Hermitian-definite generalized
 *  eigenproblem to standard form.
 *  If PlasmaItype == 1, the problem is A*x = lambda*B*x, and A is
 *  overwritten by inv(U**T)*A*inv(U) or inv(L)*A*inv(L**T)
 *  If PlasmaItype == 2 or 3, the problem is A*B*x = lambda*x or B*A*x
 *  = lambda*x, and A is overwritten by U*A*U**T or L**T*A*L.  B must
 *  have been previously factorized as U**T*U or L*L**T by
 *  PLASMA_SPOTRF.
 *
 *******************************************************************************
 *
 * @param[in] PlasmaItype
 *          Intended usage:
 *          = 1: A*x=(lambda)*B*x
 *          = 2: A*Bx=(lambda)*x
 *          = 3: B*A*x=(lambda)*x
 *
 * @param[in] uplo
 *          Specifies whether the matrix A is upper triangular or
 *          lower triangular:
 *          = PlasmaUpper: Upper triangle of A is stored;
 *          = PlasmaLower: Lower triangle of A is stored.
 *
 * @param[in] N
 *          The order of the matrices A and B. N >= 0.
 *
 * @param[in,out] A
 *          On entry, the symmetric (or Hermitian) matrix A.
 *          If uplo = PlasmaUpper, the leading N-by-N upper triangular
 *          part of A contains the upper triangular part of the matrix
 *          A, and the strictly lower triangular part of A is not
 *          referenced.
 *          If uplo = PlasmaLower, the leading N-by-N lower triangular
 *          part of A contains the lower triangular part of the matrix
 *          A, and the strictly upper triangular part of A is not
 *          referenced.
 *          On exit, if return value == 0, the transformed matrix,
 *          stored in the same format as A.
 *
 * @param[in] LDA
 *          The leading dimension of the array A. LDA >= max(1,N).
 *
 * @param[in,out] B
 *          On entry, the triangular factor from the Cholesky
 *          factorization of B, as returned by PLASMA_SPOTRF.
 *
 * @param[in] LDB
 *          The leading dimension of the array B. LDB >= max(1,N).
 *
 *******************************************************************************
 *
 * @return
 *          \retval PLASMA_SUCCESS successful exit
 *          \retval <0 if -i, the i-th argument had an illegal value
 *
 *******************************************************************************
 *
 * @sa PLASMA_ssygst_Tile
 * @sa PLASMA_ssygst_Tile_Async
 * @sa PLASMA_chegst
 * @sa PLASMA_dsygst
 * @sa PLASMA_ssygst
 *
 ******************************************************************************/
int PLASMA_ssygst(PLASMA_enum itype, PLASMA_enum uplo, int N,
                  float *A, int LDA,
                  float *B, int LDB)
{
    int NB, IB, IBNB, NT;
    int status;
    plasma_context_t *plasma;
    PLASMA_sequence *sequence = NULL;
    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
    PLASMA_desc descA, descB;

    plasma = plasma_context_self();
    if (plasma == NULL) {
        plasma_fatal_error("PLASMA_ssygst", "PLASMA not initialized");
        return PLASMA_ERR_NOT_INITIALIZED;
    }
    /* Check input arguments */
    if (itype != 1 && itype != 2 && itype != 3) {
        plasma_error("PLASMA_ssygst", "Illegal value of itype");
        return -1;
    }
    if (uplo != PlasmaUpper && uplo != PlasmaLower) {
        plasma_error("PLASMA_ssygst", "Illegal value of uplo");
        return -2;
    }
    if (N < 0) {
        plasma_error("PLASMA_ssygst", "illegal value of N");
        return -3;
    }
    if (LDA < max(1, N)) {
        plasma_error("PLASMA_ssygst", "illegal value of LDA");
        return -5;
    }
    if (LDB < max(1, N)) {
        plasma_error("PLASMA_ssygst", "illegal value of LDB");
        return -7;
    }
    /* Quick return */
    if (N == 0)
        return PLASMA_SUCCESS;

    /* Tune NB & IB depending on M, N & NRHS; Set NBNBSIZE */
    status = plasma_tune(PLASMA_FUNC_SSYGST, N, N, 0);
    if (status != PLASMA_SUCCESS) {
        plasma_error("PLASMA_ssygst", "plasma_tune() failed");
        return status;
    }

    /* Set NT */
    NB   = PLASMA_NB;
    IB   = PLASMA_IB;
    IBNB = IB*NB;
    NT   = (N%NB==0) ? (N/NB) : (N/NB+1);

    plasma_sequence_create(plasma, &sequence);

    if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
        plasma_sooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N, plasma_desc_mat_free(&(descA)) );
        plasma_sooplap2tile( descB, B, NB, NB, LDB, N, 0, 0, N, N, plasma_desc_mat_free(&(descB)) );
    } else {
        plasma_siplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N);
        plasma_siplap2tile( descB, B, NB, NB, LDB, N, 0, 0, N, N);
    }

    /* Call the tile interface */
    PLASMA_ssygst_Tile_Async(itype, uplo, &descA, &descB, sequence, &request);

    if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
        plasma_sooptile2lap( descA, A, NB, NB, LDA, N );
        plasma_sooptile2lap( descB, B, NB, NB, LDB, N );
        plasma_dynamic_sync();
        plasma_desc_mat_free(&descA);
        plasma_desc_mat_free(&descB);
    } else {
        plasma_siptile2lap( descA, A, NB, NB, LDA, N );
        plasma_siptile2lap( descB, B, NB, NB, LDB, N );
        plasma_dynamic_sync();
    }

    status = sequence->status;
    plasma_sequence_destroy(plasma, sequence);
    return status;
}

/***************************************************************************//**
 *
 * @ingroup float_Tile
 *
 *  PLASMA_ssygst_Tile - reduces a complex Hermitian-definite
 *  generalized eigenproblem to standard form.
 *  If PlasmaItype == 1, the problem is A*x = lambda*B*x, and A is
 *  overwritten by inv(U**T)*A*inv(U) or inv(L)*A*inv(L**T)
 *  If PlasmaItype == 2 or 3, the problem is A*B*x = lambda*x or B*A*x
 *  = lambda*x, and A is overwritten by U*A*U**T or L**T*A*L.  B must
 *  have been previously factorized as U**T*U or L*L**T by
 *  PLASMA_SPOTRF.
 *  ONLY PlasmaItype == 1 and PlasmaLower supported!
 *  Tile equivalent of PLASMA_ssygst().
 *  Operates on matrices stored by tiles.
 *  All matrices are passed through descriptors.
 *  All dimensions are taken from the descriptors.
 *
 *******************************************************************************
 *
 * @param[in] PlasmaItype
 *          Intended usage:
 *          = 1: A*x=(lambda)*B*x
 *          = 2: A*Bx=(lambda)*x
 *          = 3: B*A*x=(lambda)*x
 *          Currently only PlasmaItype == 1 is supported.
 *
 * @param[in] uplo
 *          Specifies whether the matrix A is upper triangular or
 *          lower triangular:
 *          = PlasmaUpper: Upper triangle of A is stored;
 *          = PlasmaLower: Lower triangle of A is stored.
 *          Currently only PlasmaLower is supported.
 *
 * @param[in,out] A
 *          On entry, the symmetric (or Hermitian) matrix A.
 *          If uplo = PlasmaUpper, the leading N-by-N upper triangular
 *          part of A contains the upper triangular part of the matrix
 *          A, and the strictly lower triangular part of A is not
 *          referenced.
 *          If uplo = PlasmaLower, the leading N-by-N lower triangular
 *          part of A contains the lower triangular part of the matrix
 *          A, and the strictly upper triangular part of A is not
 *          referenced.
 *          On exit, if return value == 0, the transformed matrix,
 *          stored in the same format as A.
 *
 * @param[in,out] B
 *          On entry, the triangular factor from the Cholesky
 *          factorization of B, as returned by PLASMA_SPOTRF.
 *
 *******************************************************************************
 *
 * @return
 *          \retval PLASMA_SUCCESS successful exit
 *          \retval <0 if -i, the i-th argument had an illegal value
 *
 *******************************************************************************
 *
 * @sa PLASMA_ssygst
 * @sa PLASMA_ssygst_Tile_Async
 * @sa PLASMA_chegst_Tile
 * @sa PLASMA_dsygst_Tile
 * @sa PLASMA_ssygst_Tile
 * @sa PLASMA_ssygst_Tile
 *
 ******************************************************************************/
int PLASMA_ssygst_Tile(PLASMA_enum itype, PLASMA_enum uplo,
                       PLASMA_desc *A,
                       PLASMA_desc *B)
{
    plasma_context_t *plasma;
    PLASMA_sequence *sequence = NULL;
    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
    int status;

    plasma = plasma_context_self();
    if (plasma == NULL) {
        plasma_fatal_error("PLASMA_ssygst_Tile", "PLASMA not initialized");
        return PLASMA_ERR_NOT_INITIALIZED;
    }
    plasma_sequence_create(plasma, &sequence);
    PLASMA_ssygst_Tile_Async(itype, uplo, A, B, sequence, &request);
    plasma_dynamic_sync();
    status = sequence->status;
    plasma_sequence_destroy(plasma, sequence);
    return status;
}

/***************************************************************************//**
 *
 * @ingroup float_Tile_Async
 *
 *  PLASMA_ssygst_Tile_Async - reduces a complex Hermitian-definite
 *  generalized eigenproblem to standard form.
 *  If PlasmaItype == 1, the problem is A*x = lambda*B*x, and A is
 *  overwritten by inv(U**T)*A*inv(U) or inv(L)*A*inv(L**T)
 *  If PlasmaItype == 2 or 3, the problem is A*B*x = lambda*x or B*A*x
 *  = lambda*x, and A is overwritten by U*A*U**T or L**T*A*L.  B must
 *  have been previously factorized as U**T*U or L*L**T by
 *  PLASMA_SPOTRF.
 *  ONLY PlasmaItype == 1 and PlasmaLower supported!
 *  Non-blocking equivalent of PLASMA_ssygst_Tile().
 *  May return before the computation is finished.
 *  Allows for pipelining of operations ar runtime.
 *
 *******************************************************************************
 *
 * @param[in] sequence
 *          Identifies the sequence of function calls that this call belongs to
 *          (for completion checks and exception handling purposes).
 *
 * @param[out] request
 *          Identifies this function call (for exception handling purposes).
 *
 *******************************************************************************
 *
 * @sa PLASMA_ssygst
 * @sa PLASMA_ssygst_Tile
 * @sa PLASMA_chegst_Tile_Async
 * @sa PLASMA_dsygst_Tile_Async
 * @sa PLASMA_ssygst_Tile_Async
 * @sa PLASMA_ssygv_Tile_Async
 *
 ******************************************************************************/
int PLASMA_ssygst_Tile_Async(PLASMA_enum itype, PLASMA_enum uplo,
                             PLASMA_desc *A,
                             PLASMA_desc *B,
                             PLASMA_sequence *sequence, PLASMA_request *request)
{
    PLASMA_desc descA = *A;
    PLASMA_desc descB = *B;
    plasma_context_t *plasma;

    plasma = plasma_context_self();
    if (plasma == NULL) {
        plasma_fatal_error("PLASMA_ssygst_Tile", "PLASMA not initialized");
        return PLASMA_ERR_NOT_INITIALIZED;
    }
    if (sequence == NULL) {
        plasma_fatal_error("PLASMA_ssygst_Tile", "NULL sequence");
        return PLASMA_ERR_UNALLOCATED;
    }
    if (request == NULL) {
        plasma_fatal_error("PLASMA_ssygst_Tile", "NULL request");
        return PLASMA_ERR_UNALLOCATED;
    }
    /* Check sequence status */
    if (sequence->status == PLASMA_SUCCESS)
        request->status = PLASMA_SUCCESS;
    else
        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);

    /* Check descriptors for correctness */
    if (plasma_desc_check(&descA) != PLASMA_SUCCESS) {
        plasma_error("PLASMA_ssygst_Tile", "invalid first descriptor");
        return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
    }
    if (plasma_desc_check(&descB) != PLASMA_SUCCESS) {
        plasma_error("PLASMA_ssygst_Tile", "invalid second descriptor");
        return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
    }
    /* Check input arguments */
    if (descA.nb != descA.mb) {
        plasma_error("PLASMA_ssygst_Tile", "only square tiles supported");
        return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
    }

    /*
     * Transform Hermitian-definite generalized eigenproblem
     * to standard form
     */
    plasma_dynamic_call_6(plasma_pssygst,
        PLASMA_enum, itype,
        PLASMA_enum, uplo,
        PLASMA_desc, descA,
        PLASMA_desc, descB,
        PLASMA_sequence*, sequence,
        PLASMA_request*, request);

    return PLASMA_SUCCESS;
}

redpajama_set_name: RedPajamaGithub


text:
// ----------------------------------------------------------------------------
// Copyright © Aleksey Nemiro, 2015-2016. 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.
// ----------------------------------------------------------------------------
using System;
using Nemiro.OAuth.Clients;

namespace Nemiro.OAuth.LoginForms
{

  ///
  /// Represents login form for Tumblr.
  ///
  public class TumblrLogin : Login, ILoginForm
  {

    ///
    /// Initializes a new instance of the login form with a specified parameters.
    ///
    /// <param name="consumerKey">The Consumer Key obtained from the <see href="https://www.tumblr.com/oauth/apps">Tumblr Dashboard</see>.</param>
    /// <param name="consumerSecret">The Consumer Secret obtained from the <see href="https://www.tumblr.com/oauth/apps">Tumblr Dashboard</see>.</param>
    /// <param name="autoLogout">Disables saving and restoring authorization cookies in WebBrowser. Default: false.</param>
    /// <param name="loadUserInfo">Indicates the need to make a request for recive the user profile or not. Default: false.</param>
    public TumblrLogin(string consumerKey, string consumerSecret, bool autoLogout = false, bool loadUserInfo = false) : this(new TumblrClient(consumerKey, consumerSecret), autoLogout, loadUserInfo) { }

    ///
    /// Initializes a new instance of the login form with a specified OAuth client.
    ///
    /// <param name="client">Instance of the OAuth client.</param>
    /// <param name="autoLogout">Disables saving and restoring authorization cookies in WebBrowser. Default: false.</param>
    /// <param name="loadUserInfo">Indicates the need to make a request for recive the user profile or not. Default: false.</param>
    public TumblrLogin(TumblrClient client, bool autoLogout = false, bool loadUserInfo = false) : base(client, autoLogout, loadUserInfo)
    {
      this.Width = 845;
      this.Height = 540;
      this.Icon = Properties.Resources.tumblr;
    }

    ///
    /// Handler of event to receive notification when the document finishes loading.
    ///
    /// <param name="webBrowser">The <see cref="System.Windows.Forms.WebBrowser"/> instance.</param>
    /// <param name="url">The loaded url.</param>
    public void WebDocumentLoaded(System.Windows.Forms.WebBrowser webBrowser, Uri url)
    {
      // cancel button click handler
      if (webBrowser.Document.GetElementsByTagName("button").GetElementsByName("deny").Count > 0)
      {
        webBrowser.Document.GetElementsByTagName("button").GetElementsByName("deny")[0].Click += (sender, e) =>
        {
          this.Close();
        };
      }
    }

    ///
    /// Logout.
    ///
    public override void Logout()
    {
      base.SetUrl
      (
        "https://www.tumblr.com/logout",
        (object sender, WebBrowserCallbackEventArgs e) =>
        {
          // goto auth
          if (this.CanLogin)
          {
            base.SetUrl(this.AuthorizationUrl);
          }
          else
          {
            base.GetAccessToken();
          }
        }
      );
    }

  }

}


text:
using WebKit::WebKeyboardEvent;

namespace webkit {
namespace ppapi {

#if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_WIN)

uint32_t UsbKeyCodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  return 0;
}

#endif

}  // namespace ppapi
}  // namespace webkit


text:
export const WEB_COMPONENTS: any[] = [
  {
    id: 0,
    name: "paper-collapse-item",
    install: {
      packager: "bower",
      url: "paper-collapse-item"
    },
    source: {
      domain: "github",
      url: "Collaborne/paper-collapse-item"
    },
    demo: {
      repl: "custom",
      src: "https://www.webcomponents.org/element/Collaborne/paper-collapse-item/demo/demo/index.html"
    },
    framework: "Web Components",
    version: "2.0.3",
    license: "Apache-2.0",
    details: "https://www.webcomponents.org/element/Collaborne/paper-collapse-item",
    keywords: ["polymer", "paper", "expand", "collapse", "accordion"],
    contributedBy: "souvikbasu"
  }
];


text:
@interface PodsDummy_Pods_CellRegistration_Example : NSObject
@end
@implementation PodsDummy_Pods_CellRegistration_Example
@end


text:
package com.bitpay.sdk.exceptions;

import org.junit.jupiter.api.Test;

public class PayoutNotificationExceptionTest  extends AbstractTestException {

    private static final String MESSAGE = "Failed to send payout notification.";
    private static final String CODE = "BITPAY-PAYOUT-NOTIFICATION";

    @Test
    public void it_should_create_exception_without_status() {
        this.testExceptionWithoutStatus(this.getTestedClass(null), MESSAGE, CODE);
    }

    @Test
    public void it_should_create_exception_with_status() {
        this.testExceptionWithStatus(this.getTestedClass(AbstractTestException.STATUS_CODE), MESSAGE, CODE);
    }

    private PayoutNotificationException getTestedClass(String status) {
        return new PayoutNotificationException(status, AbstractTestException.REASON_MESSAGE);
    }
}


text:
<?php

namespace PlentyConnector\DependencyInjection\CompilerPass;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class DefinitionCompilerPass.
 */
class CleanupDefinitionCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->has('plenty_connector.cleanup_service')) {
            return;
        }

        $definition = $container->findDefinition('plenty_connector.cleanup_service');

        $taggedServices = $container->findTaggedServiceIds('plenty_connector.cleanup_definition');

        foreach ($taggedServices as $id => $tags) {
            $definition->addMethodCall('addDefinition', [new Reference($id)]);
        }
    }
}


text:
class NFCItemCardConsumeProcessModule
    : public NFIItemCardConsumeProcessModule
{

public:
    NFCItemCardConsumeProcessModule( NFIPluginManager* p )
    {
        pPluginManager = p;
    }
    virtual bool Init();
    virtual bool Shut();
    virtual bool Execute();
    virtual bool AfterInit();

	virtual int ConsumeLegal(const NFGUID& self, const std::string& strItemID, const NFIDataList& targetID);

	virtual int ConsumeProcess(const NFGUID& self, const std::string& strItemID, const NFIDataList& targetID);

private:
    NFIKernelModule* m_pKernelModule;
    NFILogModule* m_pLogModule;
    NFIPackModule* m_pPackModule;
	NFIElementModule* m_pElementModule;
	NFIItemModule* m_pItemModule;
	NFIHeroModule* m_pHeroModule;
};

#endif


text:
package Commands;

import Game.*;

/**
 * Attack.java
 *
 * Class for combat.
 *
 * @author Joel Penney, Drew Smith, Marshall Kirk
 */
public class Attack implements Command {

	/**
	 * Attack the enemy if there is one
	 * @param fullCommand Unused. The string representing the entire command
	 */
	public void execute(String fullCommand) {
		if (Game.getGame().getCurrentRoom().getEnemy() != null) {

			if (Game.getGame().getCurrentRoom().getEnemy().takeDamage(Player.getInstance().getDamage())) {
				Player.getInstance().takeDamage(Game.getGame().getCurrentRoom().getEnemy().getDamage());
			} else {
				System.out.println("Enemy has died");
				Game.getGame().getCurrentRoom().kill();
				System.out.println("You have : " + Player.getInstance().getHealth() + " of health remaining");
			}

		} else {
			System.out.println("There are no enemies in room");

		}

	}

}


text:
using media::VideoDecodeAccelerator;

namespace content {
namespace {

// Values optionally filled in from flags; see main() below.
// The syntax of this variable is:
//  filename:width:height:numframes:numfragments:minFPSwithRender:minFPSnoRender
// where only the first field is required.  Value details:
// - |filename| must be an h264 Annex B (NAL) stream or an IVF VP8 stream.
// - |width| and |height| are in pixels.
// - |numframes| is the number of picture frames in the file.
// - |numfragments| NALU (h264) or frame (VP8) count in the stream.
// - |minFPSwithRender| and |minFPSnoRender| are minimum frames/second speeds
//   expected to be achieved with and without rendering to the screen, resp.
//   (the latter tests just decode speed).
// - |profile| is the media::VideoCodecProfile set during Initialization.
// An empty value for a numeric field means "ignore".
#if defined(OS_MACOSX)
const base::FilePath::CharType* test_video_data =
    FILE_PATH_LITERAL("test-25fps_high.h264:1280:720:250:252:50:100:4");
#else
// TODO(fischman): figure out how to support multiple test videos per run (needs
// to refactor where ParseTestVideoData is called).  For now just make it easy
// to replace which file is used by commenting/uncommenting these lines:
const base::FilePath::CharType* test_video_data =
    // FILE_PATH_LITERAL("test-25fps.vp8:320:240:250:250:50:175:11");
    FILE_PATH_LITERAL("test-25fps.h264:320:240:250:258:50:175:1");
#endif

// Parse |data| into its constituent parts and set the various output fields
// accordingly.  CHECK-fails on unexpected or missing required data.
// Unspecified optional fields are set to -1.
void ParseTestVideoData(base::FilePath::StringType data,
                        base::FilePath::StringType* file_name,
                        int* width, int* height,
                        int* num_frames,
                        int* num_fragments,
                        int* min_fps_render,
                        int* min_fps_no_render,
                        int* profile) {
  std::vector<base::FilePath::StringType> elements;
  base::SplitString(data, ':', &elements);
  CHECK_GE(elements.size(), 1U) << data;
  CHECK_LE(elements.size(), 8U) << data;
  *file_name = elements[0];
  *width = *height = *num_frames = *num_fragments = -1;
  *min_fps_render = *min_fps_no_render = -1;
  *profile = -1;
  if (!elements[1].empty())
    CHECK(base::StringToInt(elements[1], width));
  if (!elements[2].empty())
    CHECK(base::StringToInt(elements[2], height));
  if (!elements[3].empty())
    CHECK(base::StringToInt(elements[3], num_frames));
  if (!elements[4].empty())
    CHECK(base::StringToInt(elements[4], num_fragments));
  if (!elements[5].empty())
    CHECK(base::StringToInt(elements[5], min_fps_render));
  if (!elements[6].empty())
    CHECK(base::StringToInt(elements[6], min_fps_no_render));
  if (!elements[7].empty())
    CHECK(base::StringToInt(elements[7], profile));
}

// State of the GLRenderingVDAClient below.  Order matters here as the test
// makes assumptions about it.
enum ClientState {
  CS_CREATED = 0,
  CS_DECODER_SET = 1,
  CS_INITIALIZED = 2,
  CS_FLUSHING = 3,
  CS_FLUSHED = 4,
  CS_DONE = 5,
  CS_RESETTING = 6,
  CS_RESET = 7,
  CS_ERROR = 8,
  CS_DESTROYED = 9,
  CS_MAX,  // Must be last entry.
};

// Helper class allowing one thread to wait on a notification from another.
// If notifications come in faster than they are Wait()'d for, they are
// accumulated (so exactly as many Wait() calls will unblock as Notify() calls
// were made, regardless of order).
class ClientStateNotification {
 public:
  ClientStateNotification();
  ~ClientStateNotification();

  // Used to notify a single waiter of a ClientState.
  void Notify(ClientState state);
  // Used by waiters to wait for the next ClientState Notification.
  ClientState Wait();
 private:
  base::Lock lock_;
  base::ConditionVariable cv_;
  std::queue<ClientState> pending_states_for_notification_;
};

ClientStateNotification::ClientStateNotification() : cv_(&lock_) {}

ClientStateNotification::~ClientStateNotification() {}

void ClientStateNotification::Notify(ClientState state) {
  base::AutoLock auto_lock(lock_);
  pending_states_for_notification_.push(state);
  cv_.Signal();
}

ClientState ClientStateNotification::Wait() {
  base::AutoLock auto_lock(lock_);
  while (pending_states_for_notification_.empty())
    cv_.Wait();
  ClientState ret = pending_states_for_notification_.front();
  pending_states_for_notification_.pop();
  return ret;
}

// Magic constants for differentiating the reasons for NotifyResetDone being
// called.
enum ResetPoint {
  MID_STREAM_RESET = -2,
  END_OF_STREAM_RESET = -1
};

// Client that can accept callbacks from a VideoDecodeAccelerator and is used by
// the TESTs below.
class GLRenderingVDAClient : public VideoDecodeAccelerator::Client {
 public:
  // Doesn't take ownership of |rendering_helper| or |note|, which must outlive
  // |*this|.
  // |num_fragments_per_decode| counts NALUs for h264 and frames for VP8.
  // |num_play_throughs| indicates how many times to play through the video.
  // |reset_after_frame_num| can be a frame number >=0 indicating a mid-stream
  // Reset() should be done after that frame number is delivered, or
  // END_OF_STREAM_RESET to indicate no mid-stream Reset().
  // |delete_decoder_state| indicates when the underlying decoder should be
  // Destroy()'d and deleted and can take values: N<0: delete after -N Decode()
  // calls have been made, N>=0 means interpret as ClientState.
  // Both |reset_after_frame_num| & |delete_decoder_state| apply only to the
  // last play-through (governed by |num_play_throughs|).
  GLRenderingVDAClient(RenderingHelper* rendering_helper,
                        int rendering_window_id,
                        ClientStateNotification* note,
                        const std::string& encoded_data,
                        int num_fragments_per_decode,
                        int num_in_flight_decodes,
                        int num_play_throughs,
                        int reset_after_frame_num,
                        int delete_decoder_state,
                        int frame_width,
                        int frame_height,
                        int profile);
  virtual ~GLRenderingVDAClient();
  void CreateDecoder();

  // VideoDecodeAccelerator::Client implementation.
  // The heart of the Client.
  virtual void ProvidePictureBuffers(uint32 requested_num_of_buffers,
                                     const gfx::Size& dimensions,
                                     uint32 texture_target) OVERRIDE;
  virtual void DismissPictureBuffer(int32 picture_buffer_id) OVERRIDE;
  virtual void PictureReady(const media::Picture& picture) OVERRIDE;
  // Simple state changes.
  virtual void NotifyInitializeDone() OVERRIDE;
  virtual void NotifyEndOfBitstreamBuffer(int32 bitstream_buffer_id) OVERRIDE;
  virtual void NotifyFlushDone() OVERRIDE;
  virtual void NotifyResetDone() OVERRIDE;
  virtual void NotifyError(VideoDecodeAccelerator::Error error) OVERRIDE;

  // Simple getters for inspecting the state of the Client.
  int num_done_bitstream_buffers() { return num_done_bitstream_buffers_; }
  int num_skipped_fragments() { return num_skipped_fragments_; }
  int num_queued_fragments() { return num_queued_fragments_; }
  int num_decoded_frames() { return num_decoded_frames_; }
  double frames_per_second();
  bool decoder_deleted() { return !decoder_.get(); }

 private:
  typedef std::map<int, media::PictureBuffer*> PictureBufferById;

  void SetState(ClientState new_state);

  // Delete the associated OMX decoder helper.
  void DeleteDecoder();

  // Compute & return the first encoded bytes (including a start frame) to send
  // to the decoder, starting at |start_pos| and returning
  // |num_fragments_per_decode| units. Skips to the first decodable position.
  std::string GetBytesForFirstFragments(size_t start_pos, size_t* end_pos);
  // Compute & return the next encoded bytes to send to the decoder (based on
  // |start_pos| & |num_fragments_per_decode_|).
  std::string GetBytesForNextFragments(size_t start_pos, size_t* end_pos);
  // Helpers for GetRangeForNextFragments above.
  void GetBytesForNextNALU(size_t start_pos, size_t* end_pos);  // For h.264.
  std::string GetBytesForNextFrames(
      size_t start_pos, size_t* end_pos);  // For VP8.

  // Request decode of the next batch of fragments in the encoded data.
  void DecodeNextFragments();

  RenderingHelper* rendering_helper_;
  int rendering_window_id_;
  std::string encoded_data_;
  const int num_fragments_per_decode_;
  const int num_in_flight_decodes_;
  int outstanding_decodes_;
  size_t encoded_data_next_pos_to_decode_;
  int next_bitstream_buffer_id_;
  ClientStateNotification* note_;
  scoped_ptr<VideoDecodeAccelerator> decoder_;
  std::set<int> outstanding_texture_ids_;
  int remaining_play_throughs_;
  int reset_after_frame_num_;
  int delete_decoder_state_;
  ClientState state_;
  int num_skipped_fragments_;
  int num_queued_fragments_;
  int num_decoded_frames_;
  int num_done_bitstream_buffers_;
  PictureBufferById picture_buffers_by_id_;
  base::TimeTicks initialize_done_ticks_;
  base::TimeTicks last_frame_delivered_ticks_;
  int profile_;
};

GLRenderingVDAClient::GLRenderingVDAClient(
    RenderingHelper* rendering_helper,
    int rendering_window_id,
    ClientStateNotification* note,
    const std::string& encoded_data,
    int num_fragments_per_decode,
    int num_in_flight_decodes,
    int num_play_throughs,
    int reset_after_frame_num,
    int delete_decoder_state,
    int frame_width,
    int frame_height,
    int profile)
    : rendering_helper_(rendering_helper),
      rendering_window_id_(rendering_window_id),
      encoded_data_(encoded_data),
      num_fragments_per_decode_(num_fragments_per_decode),
      num_in_flight_decodes_(num_in_flight_decodes), outstanding_decodes_(0),
      encoded_data_next_pos_to_decode_(0), next_bitstream_buffer_id_(0),
      note_(note),
      remaining_play_throughs_(num_play_throughs),
      reset_after_frame_num_(reset_after_frame_num),
      delete_decoder_state_(delete_decoder_state),
      state_(CS_CREATED),
      num_skipped_fragments_(0), num_queued_fragments_(0),
      num_decoded_frames_(0), num_done_bitstream_buffers_(0),
      profile_(profile) {
  CHECK_GT(num_fragments_per_decode, 0);
  CHECK_GT(num_in_flight_decodes, 0);
  CHECK_GT(num_play_throughs, 0);
}

GLRenderingVDAClient::~GLRenderingVDAClient() {
  DeleteDecoder();  // Clean up in case of expected error.
  CHECK(decoder_deleted());
  STLDeleteValues(&picture_buffers_by_id_);
  SetState(CS_DESTROYED);
}

#if !defined(OS_MACOSX)
static bool DoNothingReturnTrue() { return true; }
#endif

void GLRenderingVDAClient::CreateDecoder() {
  CHECK(decoder_deleted());
  CHECK(!decoder_.get());
#if defined(OS_WIN)
  decoder_.reset(new DXVAVideoDecodeAccelerator(
      this, base::Bind(&DoNothingReturnTrue)));
#elif defined(OS_MACOSX)
  decoder_.reset(new MacVideoDecodeAccelerator(
      static_cast<CGLContextObj>(rendering_helper_->GetGLContext()), this));
#elif defined(OS_CHROMEOS)
#if defined(ARCH_CPU_ARMEL)
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseExynosVda)) {
    decoder_.reset(
        new ExynosVideoDecodeAccelerator(
            static_cast<EGLDisplay>(rendering_helper_->GetGLDisplay()),
            static_cast<EGLContext>(rendering_helper_->GetGLContext()),
            this, base::Bind(&DoNothingReturnTrue)));
  } else {
    decoder_.reset(
        new OmxVideoDecodeAccelerator(
            static_cast<EGLDisplay>(rendering_helper_->GetGLDisplay()),
            static_cast<EGLContext>(rendering_helper_->GetGLContext()),
            this, base::Bind(&DoNothingReturnTrue)));
  }
#elif defined(ARCH_CPU_X86_FAMILY)
  decoder_.reset(new VaapiVideoDecodeAccelerator(
      static_cast<Display*>(rendering_helper_->GetGLDisplay()),
      static_cast<GLXContext>(rendering_helper_->GetGLContext()),
      this, base::Bind(&DoNothingReturnTrue)));
#endif  // ARCH_CPU_ARMEL
#endif  // OS_WIN
  CHECK(decoder_.get());
  SetState(CS_DECODER_SET);
  if (decoder_deleted())
    return;

  // Configure the decoder.
  media::VideoCodecProfile profile = media::H264PROFILE_BASELINE;
  if (profile_ != -1)
    profile = static_cast<media::VideoCodecProfile>(profile_);
  CHECK(decoder_->Initialize(profile));
}

void GLRenderingVDAClient::ProvidePictureBuffers(
    uint32 requested_num_of_buffers,
    const gfx::Size& dimensions,
    uint32 texture_target) {
  if (decoder_deleted())
    return;
  std::vector<media::PictureBuffer> buffers;

  for (uint32 i = 0; i < requested_num_of_buffers; ++i) {
    uint32 id = picture_buffers_by_id_.size();
    uint32 texture_id;
    base::WaitableEvent done(false, false);
    rendering_helper_->CreateTexture(
        rendering_window_id_, texture_target, &texture_id, &done);
    done.Wait();
    CHECK(outstanding_texture_ids_.insert(texture_id).second);
    media::PictureBuffer* buffer =
        new media::PictureBuffer(id, dimensions, texture_id);
    CHECK(picture_buffers_by_id_.insert(std::make_pair(id, buffer)).second);
    buffers.push_back(*buffer);
  }
  decoder_->AssignPictureBuffers(buffers);
}

void GLRenderingVDAClient::DismissPictureBuffer(int32 picture_buffer_id) {
  PictureBufferById::iterator it =
      picture_buffers_by_id_.find(picture_buffer_id);
  CHECK(it != picture_buffers_by_id_.end());
  CHECK_EQ(outstanding_texture_ids_.erase(it->second->texture_id()), 1U);
  rendering_helper_->DeleteTexture(it->second->texture_id());
  delete it->second;
  picture_buffers_by_id_.erase(it);
}

void GLRenderingVDAClient::PictureReady(const media::Picture& picture) {
  // We shouldn't be getting pictures delivered after Reset has completed.
  CHECK_LT(state_, CS_RESET);

  if (decoder_deleted())
    return;
  last_frame_delivered_ticks_ = base::TimeTicks::Now();

  CHECK_LE(picture.bitstream_buffer_id(), next_bitstream_buffer_id_);
  ++num_decoded_frames_;

  // Mid-stream reset applies only to the last play-through per constructor
  // comment.
  if (remaining_play_throughs_ == 1 &&
      reset_after_frame_num_ == num_decoded_frames_) {
    reset_after_frame_num_ = MID_STREAM_RESET;
    decoder_->Reset();
    // Re-start decoding from the beginning of the stream to avoid needing to
    // know how to find I-frames and so on in this test.
    encoded_data_next_pos_to_decode_ = 0;
  }

  media::PictureBuffer* picture_buffer =
      picture_buffers_by_id_[picture.picture_buffer_id()];
  CHECK(picture_buffer);
  rendering_helper_->RenderTexture(picture_buffer->texture_id());

  decoder_->ReusePictureBuffer(picture.picture_buffer_id());
}

void GLRenderingVDAClient::NotifyInitializeDone() {
  SetState(CS_INITIALIZED);
  initialize_done_ticks_ = base::TimeTicks::Now();
  for (int i = 0; i < num_in_flight_decodes_; ++i)
    DecodeNextFragments();
  DCHECK_EQ(outstanding_decodes_, num_in_flight_decodes_);
}

void GLRenderingVDAClient::NotifyEndOfBitstreamBuffer(
    int32 bitstream_buffer_id) {
  // TODO(fischman): this test currently relies on this notification to make
  // forward progress during a Reset().  But the VDA::Reset() API doesn't
  // guarantee this, so stop relying on it (and remove the notifications from
  // VaapiVideoDecodeAccelerator::FinishReset()).
  ++num_done_bitstream_buffers_;
  --outstanding_decodes_;
  DecodeNextFragments();
}

void GLRenderingVDAClient::NotifyFlushDone() {
  if (decoder_deleted())
    return;
  SetState(CS_FLUSHED);
  --remaining_play_throughs_;
  DCHECK_GE(remaining_play_throughs_, 0);
  if (decoder_deleted())
    return;
  decoder_->Reset();
  SetState(CS_RESETTING);
}

void GLRenderingVDAClient::NotifyResetDone() {
  if (decoder_deleted())
    return;

  if (reset_after_frame_num_ == MID_STREAM_RESET) {
    reset_after_frame_num_ = END_OF_STREAM_RESET;
    DecodeNextFragments();
    return;
  }

  if (remaining_play_throughs_) {
    encoded_data_next_pos_to_decode_ = 0;
    NotifyInitializeDone();
    return;
  }

  SetState(CS_RESET);
  if (!decoder_deleted())
    DeleteDecoder();
}

void GLRenderingVDAClient::NotifyError(VideoDecodeAccelerator::Error error) {
  SetState(CS_ERROR);
}

static bool LookingAtNAL(const std::string& encoded, size_t pos) {
  return encoded[pos] == 0 && encoded[pos + 1] == 0 &&
      encoded[pos + 2] == 0 && encoded[pos + 3] == 1;
}

void GLRenderingVDAClient::SetState(ClientState new_state) {
  note_->Notify(new_state);
  state_ = new_state;
  if (!remaining_play_throughs_ && new_state == delete_decoder_state_) {
    CHECK(!decoder_deleted());
    DeleteDecoder();
  }
}

void GLRenderingVDAClient::DeleteDecoder() {
  if (decoder_deleted())
    return;
  decoder_.release()->Destroy();
  STLClearObject(&encoded_data_);
  for (std::set<int>::iterator it = outstanding_texture_ids_.begin();
       it != outstanding_texture_ids_.end(); ++it) {
    rendering_helper_->DeleteTexture(*it);
  }
  outstanding_texture_ids_.clear();
  // Cascade through the rest of the states to simplify test code below.
  for (int i = state_ + 1; i < CS_MAX; ++i)
    SetState(static_cast<ClientState>(i));
}

std::string GLRenderingVDAClient::GetBytesForFirstFragments(
    size_t start_pos, size_t* end_pos) {
  if (profile_ < media::H264PROFILE_MAX) {
    *end_pos = start_pos;
    while (*end_pos + 4 < encoded_data_.size()) {
      if ((encoded_data_[*end_pos + 4] & 0x1f) == 0x7) // SPS start frame
        return GetBytesForNextFragments(*end_pos, end_pos);
      GetBytesForNextNALU(*end_pos, end_pos);
      num_skipped_fragments_++;
    }
    *end_pos = start_pos;
    return std::string();
  }
  DCHECK_LE(profile_, media::VP8PROFILE_MAX);
  return GetBytesForNextFragments(start_pos, end_pos);
}

std::string GLRenderingVDAClient::GetBytesForNextFragments(
    size_t start_pos, size_t* end_pos) {
  if (profile_ < media::H264PROFILE_MAX) {
    size_t new_end_pos = start_pos;
    *end_pos = start_pos;
    for (int i = 0; i < num_fragments_per_decode_; ++i) {
      GetBytesForNextNALU(*end_pos, &new_end_pos);
      if (*end_pos == new_end_pos)
        break;
      *end_pos = new_end_pos;
      num_queued_fragments_++;
    }
    return encoded_data_.substr(start_pos, *end_pos - start_pos);
  }
  DCHECK_LE(profile_, media::VP8PROFILE_MAX);
  return GetBytesForNextFrames(start_pos, end_pos);
}

void GLRenderingVDAClient::GetBytesForNextNALU(
    size_t start_pos, size_t* end_pos) {
  *end_pos = start_pos;
  if (*end_pos + 4 > encoded_data_.size())
    return;
  CHECK(LookingAtNAL(encoded_data_, start_pos));
  *end_pos += 4;
  while (*end_pos + 4 <= encoded_data_.size() &&
         !LookingAtNAL(encoded_data_, *end_pos)) {
    ++*end_pos;
  }
  if (*end_pos + 3 >= encoded_data_.size())
    *end_pos = encoded_data_.size();
}

std::string GLRenderingVDAClient::GetBytesForNextFrames(
    size_t start_pos, size_t* end_pos) {
  // Helpful description: http://wiki.multimedia.cx/index.php?title=IVF
  std::string bytes;
  if (start_pos == 0)
    start_pos = 32;  // Skip IVF header.
  *end_pos = start_pos;
  for (int i = 0; i < num_fragments_per_decode_; ++i) {
    uint32 frame_size = *reinterpret_cast<uint32*>(&encoded_data_[*end_pos]);
    *end_pos += 12;  // Skip frame header.
    bytes.append(encoded_data_.substr(*end_pos, frame_size));
    *end_pos += frame_size;
    num_queued_fragments_++;
    if (*end_pos + 12 >= encoded_data_.size())
      return bytes;
  }
  return bytes;
}

void GLRenderingVDAClient::DecodeNextFragments() {
  if (decoder_deleted())
    return;
  if (encoded_data_next_pos_to_decode_ == encoded_data_.size()) {
    if (outstanding_decodes_ == 0) {
      decoder_->Flush();
      SetState(CS_FLUSHING);
    }
    return;
  }
  size_t end_pos;
  std::string next_fragment_bytes;
  if (encoded_data_next_pos_to_decode_ == 0) {
    next_fragment_bytes = GetBytesForFirstFragments(0, &end_pos);
  } else {
    next_fragment_bytes =
        GetBytesForNextFragments(encoded_data_next_pos_to_decode_, &end_pos);
  }
  size_t next_fragment_size = next_fragment_bytes.size();

  // Populate the shared memory buffer w/ the fragments, duplicate its handle,
  // and hand it off to the decoder.
  base::SharedMemory shm;
  CHECK(shm.CreateAndMapAnonymous(next_fragment_size));
  memcpy(shm.memory(), next_fragment_bytes.data(), next_fragment_size);
  base::SharedMemoryHandle dup_handle;
  CHECK(shm.ShareToProcess(base::Process::Current().handle(), &dup_handle));
  media::BitstreamBuffer bitstream_buffer(
      next_bitstream_buffer_id_, dup_handle, next_fragment_size);
  // Mask against 30 bits, to avoid (undefined) wraparound on signed integer.
  next_bitstream_buffer_id_ = (next_bitstream_buffer_id_ + 1) & 0x3FFFFFFF;
  decoder_->Decode(bitstream_buffer);
  ++outstanding_decodes_;
  encoded_data_next_pos_to_decode_ = end_pos;

  if (!remaining_play_throughs_ &&
      -delete_decoder_state_ == next_bitstream_buffer_id_) {
    DeleteDecoder();
  }
}

double GLRenderingVDAClient::frames_per_second() {
  base::TimeDelta delta = last_frame_delivered_ticks_ - initialize_done_ticks_;
  if (delta.InSecondsF() == 0)
    return 0;
  return num_decoded_frames_ / delta.InSecondsF();
}

// Test parameters:
// - Number of fragments per Decode() call.
// - Number of concurrent decoders.
// - Number of concurrent in-flight Decode() calls per decoder.
// - Number of play-throughs.
// - reset_after_frame_num: see GLRenderingVDAClient ctor.
// - delete_decoder_phase: see GLRenderingVDAClient ctor.
class VideoDecodeAcceleratorTest
    : public ::testing::TestWithParam<
  Tuple6<int, int, int, int, ResetPoint, ClientState> > {
};

// Helper so that gtest failures emit a more readable version of the tuple than
// its byte representation.
::std::ostream& operator<<(
    ::std::ostream& os,
    const Tuple6<int, int, int, int, ResetPoint, ClientState>& t) {
  return os << t.a << ", " << t.b << ", " << t.c << ", " << t.d << ", " << t.e
            << ", " << t.f;
}

// Wait for |note| to report a state and if it's not |expected_state| then
// assert |client| has deleted its decoder.
static void AssertWaitForStateOrDeleted(ClientStateNotification* note,
                                        GLRenderingVDAClient* client,
                                        ClientState expected_state) {
  ClientState state = note->Wait();
  if (state == expected_state) return;
  ASSERT_TRUE(client->decoder_deleted())
      << "Decoder not deleted but Wait() returned " << state
      << ", instead of " << expected_state;
}

// We assert a minimal number of concurrent decoders we expect to succeed.
// Different platforms can support more concurrent decoders, so we don't assert
// failure above this.
#if defined(OS_MACOSX)
enum { kMinSupportedNumConcurrentDecoders = 1 };
#else
enum { kMinSupportedNumConcurrentDecoders = 3 };
#endif

// Test the most straightforward case possible: data is decoded from a single
// chunk and rendered to the screen.
TEST_P(VideoDecodeAcceleratorTest, TestSimpleDecode) {
  // Can be useful for debugging VLOGs from OVDA.
  // logging::SetMinLogLevel(-1);

  // Required for Thread to work.  Not used otherwise.
  base::ShadowingAtExitManager at_exit_manager;

  const int num_fragments_per_decode = GetParam().a;
  const size_t num_concurrent_decoders = GetParam().b;
  const size_t num_in_flight_decodes = GetParam().c;
  const int num_play_throughs = GetParam().d;
  const int reset_after_frame_num = GetParam().e;
  const int delete_decoder_state = GetParam().f;

  base::FilePath::StringType test_video_file;
  int frame_width, frame_height;
  int num_frames, num_fragments, min_fps_render, min_fps_no_render, profile;
  ParseTestVideoData(test_video_data, &test_video_file, &frame_width,
                     &frame_height, &num_frames, &num_fragments,
                     &min_fps_render, &min_fps_no_render, &profile);
  min_fps_render /= num_concurrent_decoders;
  min_fps_no_render /= num_concurrent_decoders;

  // If we reset mid-stream and start playback over, account for frames that are
  // decoded twice in our expectations.
  if (num_frames > 0 && reset_after_frame_num >= 0)
    num_frames += reset_after_frame_num;

  // Suppress GL swapping in all but a few tests, to cut down overall test
  // runtime.
  const bool suppress_swap_to_display = num_fragments_per_decode > 1;

  std::vector<ClientStateNotification*> notes(num_concurrent_decoders, NULL);
  std::vector<GLRenderingVDAClient*> clients(num_concurrent_decoders, NULL);

  // Read in the video data.
  std::string data_str;
  CHECK(file_util::ReadFileToString(base::FilePath(test_video_file),
                                    &data_str))
      << "test_video_file: " << base::FilePath(test_video_file).MaybeAsASCII();

  // Initialize the rendering helper.
  base::Thread rendering_thread("GLRenderingVDAClientThread");
  base::Thread::Options options;
  options.message_loop_type = MessageLoop::TYPE_DEFAULT;
#if defined(OS_WIN)
  // For windows the decoding thread initializes the media foundation decoder
  // which uses COM. We need the thread to be a UI thread.
  options.message_loop_type = MessageLoop::TYPE_UI;
#endif  // OS_WIN

  rendering_thread.StartWithOptions(options);
  scoped_ptr<RenderingHelper> rendering_helper(RenderingHelper::Create());

  base::WaitableEvent done(false, false);
  rendering_thread.message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&RenderingHelper::Initialize,
                 base::Unretained(rendering_helper.get()),
                 suppress_swap_to_display, num_concurrent_decoders,
                 frame_width, frame_height, &done));
  done.Wait();

  // First kick off all the decoders.
  for (size_t index = 0; index < num_concurrent_decoders; ++index) {
    ClientStateNotification* note = new ClientStateNotification();
    notes[index] = note;
    GLRenderingVDAClient* client = new GLRenderingVDAClient(
        rendering_helper.get(), index, note, data_str, num_fragments_per_decode,
        num_in_flight_decodes, num_play_throughs, reset_after_frame_num,
        delete_decoder_state, frame_width, frame_height, profile);
    clients[index] = client;

    rendering_thread.message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&GLRenderingVDAClient::CreateDecoder,
                   base::Unretained(client)));

    ASSERT_EQ(note->Wait(), CS_DECODER_SET);
  }
  // Then wait for all the decodes to finish.
  // Only check performance & correctness later if we play through only once.
  bool skip_performance_and_correctness_checks = num_play_throughs > 1;
  for (size_t i = 0; i < num_concurrent_decoders; ++i) {
    ClientStateNotification* note = notes[i];
    ClientState state = note->Wait();
    if (state != CS_INITIALIZED) {
      skip_performance_and_correctness_checks = true;
      // We expect initialization to fail only when more than the supported
      // number of decoders is instantiated.  Assert here that something else
      // didn't trigger failure.
      ASSERT_GT(num_concurrent_decoders,
                static_cast<size_t>(kMinSupportedNumConcurrentDecoders));
      continue;
    }
    ASSERT_EQ(state, CS_INITIALIZED);
    for (int n = 0; n < num_play_throughs; ++n) {
      // For play-throughs other than the first, we expect initialization to
      // succeed unconditionally.
      if (n > 0) {
        ASSERT_NO_FATAL_FAILURE(
            AssertWaitForStateOrDeleted(note, clients[i], CS_INITIALIZED));
      }
      // InitializeDone kicks off decoding inside the client, so we just need to
      // wait for Flush.
      ASSERT_NO_FATAL_FAILURE(
          AssertWaitForStateOrDeleted(note, clients[i], CS_FLUSHING));
      ASSERT_NO_FATAL_FAILURE(
          AssertWaitForStateOrDeleted(note, clients[i], CS_FLUSHED));
      // FlushDone requests Reset().
      ASSERT_NO_FATAL_FAILURE(
          AssertWaitForStateOrDeleted(note, clients[i], CS_RESETTING));
    }
    ASSERT_NO_FATAL_FAILURE(
        AssertWaitForStateOrDeleted(note, clients[i], CS_RESET));
    // ResetDone requests Destroy().
    ASSERT_NO_FATAL_FAILURE(
        AssertWaitForStateOrDeleted(note, clients[i], CS_DESTROYED));
  }
  // Finally assert that decoding went as expected.
  for (size_t i = 0; i < num_concurrent_decoders &&
           !skip_performance_and_correctness_checks; ++i) {
    // We can only make performance/correctness assertions if the decoder was
    // allowed to finish.
    if (delete_decoder_state < CS_FLUSHED)
      continue;
    GLRenderingVDAClient* client = clients[i];
    if (num_frames > 0)
      EXPECT_EQ(client->num_decoded_frames(), num_frames);
    if (reset_after_frame_num < 0) {
      EXPECT_EQ(num_fragments, client->num_skipped_fragments() +
                client->num_queued_fragments());
      EXPECT_EQ(client->num_done_bitstream_buffers(),
                ceil(static_cast<double>(client->num_queued_fragments()) /
                     num_fragments_per_decode));
    }
    LOG(INFO) << "Decoder " << i << " fps: " << client->frames_per_second();
    int min_fps = suppress_swap_to_display ? min_fps_no_render : min_fps_render;
    if (min_fps > 0)
      EXPECT_GT(client->frames_per_second(), min_fps);
  }

  rendering_thread.message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&STLDeleteElements<std::vector<GLRenderingVDAClient*> >,
                 &clients));
  rendering_thread.message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&STLDeleteElements<std::vector<ClientStateNotification*> >,
                 &notes));
  rendering_thread.message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&RenderingHelper::UnInitialize,
                 base::Unretained(rendering_helper.get()),
                 &done));
  done.Wait();
  rendering_thread.Stop();
};

// Test that replay after EOS works fine.
INSTANTIATE_TEST_CASE_P(
    ReplayAfterEOS, VideoDecodeAcceleratorTest,
    ::testing::Values(
        MakeTuple(1, 1, 1, 4, END_OF_STREAM_RESET, CS_RESET)));

// Test that Reset() mid-stream works fine and doesn't affect decoding even when
// Decode() calls are made during the reset.
INSTANTIATE_TEST_CASE_P(
    MidStreamReset, VideoDecodeAcceleratorTest,
    ::testing::Values(
        MakeTuple(1, 1, 1, 1, static_cast<ResetPoint>(100), CS_RESET)));

// Test that Destroy() mid-stream works fine (primarily this is testing that no
// crashes occur).
INSTANTIATE_TEST_CASE_P(
    TearDownTiming, VideoDecodeAcceleratorTest,
    ::testing::Values(
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET, CS_DECODER_SET),
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET, CS_INITIALIZED),
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET, CS_FLUSHING),
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET, CS_FLUSHED),
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET, CS_RESETTING),
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET, CS_RESET),
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET,
                  static_cast<ClientState>(-1)),
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET,
                  static_cast<ClientState>(-10)),
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET,
                  static_cast<ClientState>(-100))));

// Test that decoding various variation works: multiple concurrent decoders and
// multiple fragments per Decode() call.
INSTANTIATE_TEST_CASE_P(
    DecodeVariations, VideoDecodeAcceleratorTest,
    ::testing::Values(
        MakeTuple(1, 1, 1, 1, END_OF_STREAM_RESET, CS_RESET),
        MakeTuple(1, 1, 10, 1, END_OF_STREAM_RESET, CS_RESET),
        // Tests queuing.
        MakeTuple(1, 1, 15, 1, END_OF_STREAM_RESET, CS_RESET),
        // +0 hack below to promote enum to int.
        MakeTuple(1, kMinSupportedNumConcurrentDecoders + 0, 1, 1,
                  END_OF_STREAM_RESET, CS_RESET),
        MakeTuple(2, 1, 1, 1, END_OF_STREAM_RESET, CS_RESET),
        MakeTuple(3, 1, 1, 1, END_OF_STREAM_RESET, CS_RESET),
        MakeTuple(5, 1, 1, 1, END_OF_STREAM_RESET, CS_RESET),
        MakeTuple(8, 1, 1, 1, END_OF_STREAM_RESET, CS_RESET),
        // TODO(fischman): decoding more than 15 NALUs at once breaks decode -
        // visual artifacts are introduced as well as spurious frames are
        // delivered (more pictures are returned than NALUs are fed to the
        // decoder).  Increase the "15" below when
        // http://code.google.com/p/chrome-os-partner/issues/detail?id=4378 is
        // fixed.
        MakeTuple(15, 1, 1, 1, END_OF_STREAM_RESET, CS_RESET)));

// Find out how many concurrent decoders can go before we exhaust system
// resources.
INSTANTIATE_TEST_CASE_P(
    ResourceExhaustion, VideoDecodeAcceleratorTest,
    ::testing::Values(
        // +0 hack below to promote enum to int.
        MakeTuple(1, kMinSupportedNumConcurrentDecoders + 0, 1, 1,
                  END_OF_STREAM_RESET, CS_RESET),
        MakeTuple(1, kMinSupportedNumConcurrentDecoders + 1, 1, 1,
                  END_OF_STREAM_RESET, CS_RESET)));

// TODO(fischman, vrk): add more tests!  In particular:
// - Test life-cycle: Seek/Stop/Pause/Play for a single decoder.
// - Test alternate configurations
// - Test failure conditions.
// - Test frame size changes mid-stream

}  // namespace
}  // namespace content

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);  // Removes gtest-specific args.
  CommandLine::Init(argc, argv);

  // Needed to enable DVLOG through --vmodule.
  CHECK(logging::InitLogging(
      NULL,
      logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
      logging::DONT_LOCK_LOG_FILE,
      logging::APPEND_TO_OLD_LOG_FILE,
      logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS));

  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  DCHECK(cmd_line);

  CommandLine::SwitchMap switches = cmd_line->GetSwitches();
  for (CommandLine::SwitchMap::const_iterator it = switches.begin();
       it != switches.end(); ++it) {
    if (it->first == "test_video_data") {
      content::test_video_data = it->second.c_str();
      continue;
    }
    if (it->first == "v" || it->first == "vmodule")
      continue;
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
    if (it->first == switches::kUseExynosVda)
      continue;
#endif
    LOG(FATAL) << "Unexpected switch: " << it->first << ":" << it->second;
  }

  base::ShadowingAtExitManager at_exit_manager;
  content::RenderingHelper::InitializePlatform();

#if defined(OS_WIN)
  base::WaitableEvent event(true, false);
  content::DXVAVideoDecodeAccelerator::PreSandboxInitialization(
      base::Bind(&base::WaitableEvent::Signal,
                 base::Unretained(&event)));
  event.Wait();
#elif defined(OS_CHROMEOS)
#if defined(ARCH_CPU_ARMEL)
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseExynosVda))
    content::ExynosVideoDecodeAccelerator::PreSandboxInitialization();
  else
    content::OmxVideoDecodeAccelerator::PreSandboxInitialization();
#elif defined(ARCH_CPU_X86_FAMILY)
  content::VaapiVideoDecodeAccelerator::PreSandboxInitialization();
#endif  // ARCH_CPU_ARMEL
#endif  // OS_CHROMEOS

  return RUN_ALL_TESTS();
}


text:
<?php
/**
 * Date: 2016/3/22
 */

namespace DesignPatterns\Structural\Decorator;

class RenderInXml extends Decorator
{
    /**
     * render data as xml
     *
     * @return string
     */
    public function renderData()
    {
        $output = $this->wrapped->renderData();

        // 想象在这里把 array 转换成 xml ...

        $doc = new \DOMDocument();

        foreach ($output as $key => $val) {
            $doc->appendChild($doc->createElement($key, $val));
        }

        return $doc->saveXML();
    }
}


text:
namespace Anycmd.Engine.Rdb.Messages
{
    using Engine.Messages;
    using InOuts;

    public class UpdateDatabaseCommand : UpdateEntityCommand<IDatabaseUpdateInput>, IAnycmdCommand
    {
        public UpdateDatabaseCommand(IAcSession acSession, IDatabaseUpdateInput input)
            : base(acSession, input)
        {

        }
    }
}


text:
public class CodaCollegata implements Coda {

	private Record inizio = null;
	private Record fine = null;

	private class Record {
 		public Object elem;
 		public Record next;

		public Record(Object e) {
			elem = e;
			next = null;
		}
	}

	public boolean isEmpty() {
		return inizio == null;
	}

	public void enqueue(Object e) {
		if (isEmpty())
			inizio = fine = new Record(e);
		else {
			fine.next = new Record(e);
			fine = fine.next;
		}
	}

	public Object first() throws EccezioneStrutturaVuota {}

	public void dequeue(){}

}


text:
require 'minitest/autorun'
require 'geometry'

class ArithmeticsTest < Minitest::Test
  include Geometry

  def test_summation
    assert_equal Vector.new(4, 6), Vector.new(1, 2) + Vector.new(3, 4)
  end

  def test_subtraction
    assert_equal Vector.new(-2, -4), Vector.new(1, 0) - Vector.new(3, 4)
  end

  def test_vector_multiplied_by_scalar
    assert_equal Vector.new(-2, -4), Vector.new(1, 2) * -2
  end

  def test_scalar_multiplied_by_vector
    assert_equal Vector.new(-2, -4), -2 * Vector.new(1, 2)
  end
end


text:
{NODE.title|htmlspecialchars}

{NODE.title|htmlspecialchars}

{ITEM.title|htmlspecialchars}

						{CONTAINER.1}


text:
/****** Object:  Stored Procedure dbo.b4nCreateCategoryMenu2    Script Date: 23/06/2005 13:31:05 ******/

CREATE        proc dbo.b4nCreateCategoryMenu2
@parentCategoryID varchar(40)
AS
Begin

Declare @table table(
	sortid		int IDENTITY (1, 1),
	priority	int,
	ident	int,
	menuid	varchar(40),
	parentmenuid	varchar	(40),
	menuTitle	varchar	(200),
	menuLink	varchar	(2000),
	menuTarget	varchar	(1000),
	isParent	smallint,
	menuLevel	smallint,
	usesimages	smallint,
	onPromotion	smallint,
	categoryImage	varchar	(100),
	parentCatMenuid varchar(40),
	catcount	int
)

Declare @catcount int

Set @catcount = (Select count(menuid) From b4ncategorymenu with(nolock) Where parentmenuid = '0')

Declare catCursor Insensitive Cursor
For Select priority,menuid,parentmenuid,isParent From b4ncategorymenu with(nolock)
Where parentmenuid = '0' Order By priority

Open catCursor

	Declare @priority int, @menuid varchar(40), @parentmenuid varchar(40), @isParent smallint

	Fetch Next From catCursor into @priority, @menuid, @parentmenuid,@isParent

	While (@@fetch_status = 0)
	Begin

		Insert Into @table(priority,ident,menuid,parentmenuid,menuTitle,menuLink,menuTarget,isParent,menuLevel,usesimages,onPromotion,categoryImage,parentCatMenuid,catcount)
		Select cm.priority,cm.ident,cm.menuid,cm.parentmenuid,ac.attributevalue,cm.menuLink,cm.menuTarget,cm.isParent,cm.menuLevel,cm.usesimages,cm.onPromotion,cm.categoryImage,0,1
			From b4ncategorymenu cm with(nolock), b4nattributeCategory ac with(nolock)
		Where cm.menuid = @menuid and cm.menuid = ac.categoryid and ac.attributeid = 73

		Insert Into @table(priority,ident,menuid,parentmenuid,menuTitle,menuLink,menuTarget,isParent,menuLevel,usesimages,onPromotion,categoryImage,parentCatMenuid,catcount)
		Select cm.priority,cm.ident,cm.menuid,cm.parentmenuid,ac.attributevalue,cm.menuLink,cm.menuTarget,cm.isParent,cm.menuLevel,cm.usesimages,cm.onPromotion,cm.categoryImage,0,1
			From b4ncategorymenu cm with(nolock), b4nattributeCategory ac with(nolock)
		Where cm.parentmenuid = @menuid and cm.menuid = ac.categoryid and ac.attributeid = 73
		Order by priority,menuTitle

	Fetch Next From catCursor Into @priority, @menuid, @parentmenuid, @isParent

	End

Close catCursor
Deallocate catCursor

Select * From @table Order By sortid
End

GRANT EXECUTE ON b4nCreateCategoryMenu2 TO b4nuser
GO
GRANT EXECUTE ON b4nCreateCategoryMenu2 TO helpdesk
GO
GRANT EXECUTE ON b4nCreateCategoryMenu2 TO ofsuser
GO
GRANT EXECUTE ON b4nCreateCategoryMenu2 TO reportuser
GO
GRANT EXECUTE ON b4nCreateCategoryMenu2 TO b4nexcel
GO
GRANT EXECUTE ON b4nCreateCategoryMenu2 TO b4nloader
GO


text:
package org.usfirst.frc.team1306.robot.commands.intake;

import org.usfirst.frc.team1306.robot.commands.CommandBase;

/**
 * A Command to move the intake arm to a given position. It uses the Talon's
 * internal PID loop.
 *
 * @author Finn Voichick
 */
public class IntakeArmMove extends CommandBase {

	/** The position to move the arm to. */
	private final IntakePosition position;

	/**
	 * Constructs an IntakeArmMove Command that requires the IntakeArm.
	 */
	public IntakeArmMove(IntakePosition position) {
		this.position = position;
		requires(intakeArm);
	}

	/**
	 * Called just before this Command runs the first time. This is where the
	 * arm's new position is set.
	 */
	@Override
	protected void initialize() {
		intakeArm.setPosition(position);
	}

	/**
	 * Called repeatedly when this Command is scheduled to run. Nothing needs to
	 * be run repeatedly because the PID calculations are done internally on the
	 * Talon SRX.
	 */
	@Override
	protected void execute() {
	}

	/**
	 * Returns true when this Command no longer needs to run execute(). This
	 * command doesn't have a finish condition because it runs until
	 * interrupted.
	 *
	 * @return false
	 */
	@Override
	protected boolean isFinished() {
		return false;
	}

	/**
	 * Called once after isFinished returns true. This command never does end.
	 */
	@Override
	protected void end() {
	}

	/**
	 * Called when another command which requires one or more of the same
	 * subsystems is scheduled to run. Nothing needs to happen when this command
	 * is interrupted.
	 */
	@Override
	protected void interrupted() {
	}
}


text:
#include "TestAutomaticTestProjects/APublicFile.h"

int APublicFile::doSomething()
{
    someNumber = 666;
	return 4711;
}


text:
package org.apache.wss4j.policy.model;

import org.apache.neethi.Assertion;
import org.apache.neethi.Policy;
import org.apache.wss4j.policy.SPConstants;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.*;

public class RelToken extends AbstractToken {

    public enum RelTokenType {
        WssRelV10Token10,
        WssRelV20Token10,
        WssRelV10Token11,
        WssRelV20Token11;

        private static final Map<String, RelTokenType> LOOKUP = new HashMap<>();

        static {
            for (RelTokenType u : EnumSet.allOf(RelTokenType.class)) {
                LOOKUP.put(u.name(), u);
            }
        }

        public static RelTokenType lookUp(String name) {
            return LOOKUP.get(name);
        }
    }

    private boolean requireKeyIdentifierReference;
    private RelTokenType relTokenType;

    public RelToken(SPConstants.SPVersion version, SPConstants.IncludeTokenType includeTokenType,
                    Element issuer, String issuerName, Element claims, Policy nestedPolicy) {
        super(version, includeTokenType, issuer, issuerName, claims, nestedPolicy);

        parseNestedPolicy(nestedPolicy, this);
    }

    @Override
    public QName getName() {
        return getVersion().getSPConstants().getRelToken();
    }

    @Override
    public boolean equals(Object object) {
        if (object == this) {
            return true;
        }
        if (!(object instanceof RelToken)) {
            return false;
        }

        RelToken that = (RelToken)object;
        if (requireKeyIdentifierReference != that.requireKeyIdentifierReference) {
            return false;
        }
        if (relTokenType != that.relTokenType) {
            return false;
        }

        return super.equals(object);
    }

    @Override
    public int hashCode() {
        int result = 17;
        if (relTokenType != null) {
            result = 31 * result + relTokenType.hashCode();
        }
        result = 31 * result + Boolean.hashCode(requireKeyIdentifierReference);

        return 31 * result + super.hashCode();
    }

    @Override
    protected AbstractSecurityAssertion cloneAssertion(Policy nestedPolicy) {
        return new RelToken(getVersion(), getIncludeTokenType(), getIssuer(), getIssuerName(),
                            getClaims(), nestedPolicy);
    }

    protected void parseNestedPolicy(Policy nestedPolicy, RelToken relToken) {
        Iterator<List<Assertion>> alternatives = nestedPolicy.getAlternatives();
        //we just process the first alternative
        //this means that if we have a compact policy only the first alternative is visible
        //in contrary to a normalized policy where just one alternative exists
        if (alternatives.hasNext()) {
            List<Assertion> assertions = alternatives.next();
            for (Assertion assertion : assertions) {
                String assertionName = assertion.getName().getLocalPart();
                String assertionNamespace = assertion.getName().getNamespaceURI();
                DerivedKeys derivedKeys = DerivedKeys.lookUp(assertionName);
                if (derivedKeys != null) {
                    if (relToken.getDerivedKeys() != null) {
                        throw new IllegalArgumentException(SPConstants.ERR_INVALID_POLICY);
                    }
                    relToken.setDerivedKeys(derivedKeys);
                    continue;
                }
                QName requireKeyIdentifierRef =
                    getVersion().getSPConstants().getRequireKeyIdentifierReference();
                if (requireKeyIdentifierRef.getLocalPart().equals(assertionName)
                    && requireKeyIdentifierRef.getNamespaceURI().equals(assertionNamespace)) {
                    if (relToken.isRequireKeyIdentifierReference()) {
                        throw new IllegalArgumentException(SPConstants.ERR_INVALID_POLICY);
                    }
                    relToken.setRequireKeyIdentifierReference(true);
                    continue;
                }
                RelTokenType samlTokenType = RelTokenType.lookUp(assertionName);
                if (samlTokenType != null) {
                    if (relToken.getRelTokenType() != null) {
                        throw new IllegalArgumentException(SPConstants.ERR_INVALID_POLICY);
                    }
                    relToken.setRelTokenType(samlTokenType);
                    continue;
                }
            }
        }
    }

    public boolean isRequireKeyIdentifierReference() {
        return requireKeyIdentifierReference;
    }

    public void setRequireKeyIdentifierReference(boolean requireKeyIdentifierReference) {
        this.requireKeyIdentifierReference = requireKeyIdentifierReference;
    }

    public RelTokenType getRelTokenType() {
        return relTokenType;
    }

    protected void setRelTokenType(RelTokenType relTokenType) {
        this.relTokenType = relTokenType;
    }
}


text:
<?php

namespace Octava\Bundle\BranchingBundle\DependencyInjection\Compiler;

use Octava\Bundle\BranchingBundle\ConnectionFactory;
use Octava\Bundle\BranchingBundle\Manager\DatabaseManager;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class UpdateDoctrineConnectionFactoryPass implements CompilerPassInterface
{

    /**
     * You can modify the container here before it is dumped to PHP code.
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container)
    {
        $container
            ->getDefinition('doctrine.dbal.connection_factory')
            ->setClass(ConnectionFactory::class)
            ->addMethodCall('setDatabaseManager', [new Reference(DatabaseManager::class)]);
    }
}


text:
var should = require('chai').should()
  , angular = require('angular')
  , sinon  = require('sinon')
  , $ = require('jquery')
  , mocks = require('../../mocks');

require('angular-mocks');

describe('LeafletCacheController tests', function() {

  var scope
    , ctrl
    , element
    , $rootScope;

  var sandbox;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    sandbox.restore();
  });

  beforeEach(angular.mock.module('mapcache'));

  beforeEach(inject(function(_$rootScope_, $controller){
    $rootScope = _$rootScope_;
    scope = $rootScope.$new();
    scope.cache = JSON.parse(JSON.stringify(mocks.cacheMocks.xyzCache));
    scope.options = {
      baseLayerUrl: 'http://example.com'
    };
    element = $('

');

    ctrl = $controller('LeafletCacheController', {$scope: scope, $element: element});
    scope.$apply();
  }));

  it('should create the LeafletCacheController', function() {
    should.exist(ctrl);
  });

});


text:
gaps.factory('GraphStatistics', [function () {
        var Service = {};

        // Graph statistics per edge
        var _graphStatistics = {
            numberOfNodes: 1,
            numberOfEdges: 1,
            minimumEdgeCost: 1,
            maximumEdgeCost: 1,
            totalEdgeCost: 0,
            averageEdgeCost: 0.0,
            averageEdgesPerNode: 0.0
        };

        Service.getStatistics = function () {
            return _graphStatistics;
        };

        Service.setStatistics = function (graphStatistics) {
            _graphStatistics = graphStatistics;
        };

        Service.reset = function() {
            _graphStatistics.numberOfNodes = 1;
            _graphStatistics.numberOfEdges = 1;
            _graphStatistics.minimumEdgeCost = 1;
            _graphStatistics.maximumEdgeCost = 1;
            _graphStatistics.totalEdgeCost = 0;
            _graphStatistics.averageEdgeCost = 0.0;
            _graphStatistics.averageEdgesPerNode = 0.0;
        };

        Service.getEdgeClass = function (edgeCost) {
            var averageCostLowThreshold = _graphStatistics.averageEdgeCost - (_graphStatistics.averageEdgeCost / 4);
            var averageCostHighThreshold = _graphStatistics.averageEdgeCost + (_graphStatistics.averageEdgeCost / 4);
            if (edgeCost < averageCostLowThreshold) {
                return 'label-success';
            } else if (edgeCost >= averageCostLowThreshold && edgeCost <= averageCostHighThreshold) {
                return 'label-warning';
            } else {
                return 'label-danger';
            }
        };

        return Service;

    }]);


text:
// https://github.com/jasonlam604/grunt-contrib-rename
/*global module*/
module.exports = {
	normalize: {
		files: [
			{
				src: ['<%= paths.bower %>normalize/normalize.css'],
				dest: '<%= paths.bower %>normalize/_normalize.scss'
			}
		]
	}
};


text:
/**
 * @author  Tümay Çeber <tumayceber@gmail.com>
 * @link    https://github.com/brendtumi/bkmexpress
 * @license http://opensource.org/licenses/MIT
 * @date 26.04.2017
 */

export class MerchantLoginRequest {

    private id: string;
    private signature: string;

    public constructor(id: string, signature: string) {
        this.id = id;
        this.signature = signature;
    }

    get Id(): string {
        return this.id;
    }

    set Id(id: string) {
        this.id = id;
    }

    get Signature(): string {
        return this.signature;
    }

    set Signature(signature: string) {
        this.signature = signature;
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DotNetty.Codecs.Mqtt.Packets
{
    using DotNetty.Buffers;

    public sealed class ConnectPacket : Packet
    {
        public override PacketType PacketType
        {
            get { return PacketType.CONNECT; }
        }

        public string ProtocolName { get; set; }

        public int ProtocolLevel { get; set; }

        public bool CleanSession { get; set; }

        public bool HasWill { get; set; }

        public QualityOfService WillQualityOfService { get; set; }

        public bool WillRetain { get; set; }

        public bool HasPassword { get; set; }

        public bool HasUsername { get; set; }

        public int KeepAliveInSeconds { get; set; }

        public string Username { get; set; }

        public string Password { get; set; }

        public string ClientId { get; set; }

        public string WillTopicName { get; set; }

        public IByteBuffer WillMessage { get; set; }
    }
}


text:
#ifndef GEO_H
#define GEO_H

/* Defines */
#define GEO_MATRIX_STACK 16
#define GEO_MAX_POINTS 256

/* Includes */
#include "vector.h"
#include "draw.h"

/* Geo */
namespace Geo
{
	/*
		Initializes geometry rendering library
	*/
	extern void init();
	/*
		Closes geometry rendering library
	*/
	extern void exit();
	/*
		Sets the current transform to identity
	*/
	extern void identity();
	/*
		Raises the current transform stack by 1
	*/
	extern void push();
	/*
		Returns to the previous transform
	*/
	extern void pop();
	/*
		Applies a translation
	*/
	extern void translate(float x,float y,float z);
	/*
		Applies a scale
	*/
	extern void scale(float sx,float sy,float sz);
	/*
		Converts from a point in world space to screen space
		Only works on finally transformed vectors
	*/
	extern void screen(Vector *v,int *px,int *py);
	/*
		Transforms vector according to current transform
	*/
	extern void transform(Vector *v);
	/*
		Sets current texture
	*/
	extern void texture(Texture *t);
	/*
		Sets current mode
	*/
	extern void mode(int m);
	/*
		Draws an array of triangles
		Will not render anything with more than GEO_MAX_POINTS points in it
		pc - count of points
		ps - the points
		txs - the texture coordinates
		cs - the colors
		tc - count of triangles
		ts - the triangles
	*/
	extern void draw(int pc,float *ps,int *txs,int *cs,int tc,int *ts);
}

#endif


text:
package opennlp.tools.parser;

import java.io.IOException;

import opennlp.tools.util.FilterObjectStream;
import opennlp.tools.util.ObjectStream;

public class ParseSampleStream extends FilterObjectStream<String, Parse> {

  public ParseSampleStream(ObjectStream<String> in) {
    super(in);
  }

  public Parse read() throws IOException {

    String parse = samples.read();

    if (parse != null) {
      if (!parse.trim().isEmpty()) {
        return Parse.parseParse(parse);
      }
      else {
        return read();
      }
    }
    else {
      return null;
    }
  }
}


text:
namespace base {

// Dispatcher is used during a nested invocation of Run to dispatch events when
// |RunLoop(dispatcher).Run()| is used.  If |RunLoop().Run()| is invoked,
// MessageLoop does not dispatch events (or invoke TranslateMessage), rather
// every message is passed to Dispatcher's Dispatch method for dispatch. It is
// up to the Dispatcher whether or not to dispatch the event.
//
// The nested loop is exited by either posting a quit, or setting the
// POST_DISPATCH_QUIT_LOOP flag on the return value from Dispatch.
class BASE_EXPORT MessagePumpDispatcher {
 public:
  enum PostDispatchAction {
    POST_DISPATCH_NONE = 0x0,
    POST_DISPATCH_QUIT_LOOP = 0x1,
    POST_DISPATCH_PERFORM_DEFAULT = 0x2,
  };

  virtual ~MessagePumpDispatcher() {}

  // Dispatches the event. The return value can have more than one
  // PostDispatchAction flags OR'ed together. If POST_DISPATCH_PERFORM_DEFAULT
  // is set in the returned value, then the message-pump performs the default
  // action. If POST_DISPATCH_QUIT_LOOP is set, in the return value, then the
  // nested loop exits immediately.
  virtual uint32_t Dispatch(const NativeEvent& event) = 0;
};

}  // namespace base

#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_DISPATCHER_H_


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>edu.marcelo</groupId>
    <artifactId>modules-level2</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>
  <groupId>edu.marcelo</groupId>
  <artifactId>module-l2-java</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>module-l2-java</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
#include <Arduino.h>
#include <Wire.h>
#include "MC3610.h"

#define MC3610_CFG_I2C_ADDR    			(0x6C)
#define MC3610_CFG_MODE_DEFAULT    		MC3610_MODE_STANDBY
#define MC3610_CFG_SAMPLE_RATE_CWAKE_DEFAULT    MC3610_CWAKE_SR_DEFAULT_50Hz
#define MC3610_CFG_SAMPLE_RATE_SNIFF_DEFAULT    MC3610_SNIFF_SR_0p4Hz
#define MC3610_CFG_RANGE_DEFAULT         	MC3610_RANGE_8G
#define MC3610_CFG_RESOLUTION_DEFAULT    	MC3610_RESOLUTION_14BIT
#define MC3610_CFG_ORIENTATION_MAP_DEFAULT    	ORIENTATION_TOP_RIGHT_UP

uint8_t CfgRange, CfgResolution;

 // Read register bit
bool MC3610::readRegisterBit(uint8_t reg, uint8_t pos)
{
    uint8_t value;
    value = readRegister8(reg);
    return ((value >> pos) & 1);
}

// Write register bit
void MC3610::writeRegisterBit(uint8_t reg, uint8_t pos, bool state)
{
    uint8_t value;
    value = readRegister8(reg);

    if (state)
        value |= (1 << pos);
    else
        value &= ~(1 << pos);

    writeRegister8(reg, value);
}

// Read 8-bit from register
uint8_t MC3610::readRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(MC3610_CFG_I2C_ADDR);
    Wire.write(reg);
    Wire.endTransmission(false); //endTransmission but keep the connection active
    Wire.requestFrom(MC3610_CFG_I2C_ADDR, 1); //Once done, bus is released by default
    value = Wire.read();
    return value;
}

// Write 8-bit to register
void MC3610::writeRegister8(uint8_t reg, uint8_t value)
{
    Wire.beginTransmission(MC3610_CFG_I2C_ADDR);
    Wire.write(reg);
    Wire.write(value);
    Wire.endTransmission();
}

// Read 16-bit from register
int16_t MC3610::readRegister16(uint8_t reg)
{
    int16_t value;
    Wire.beginTransmission(MC3610_CFG_I2C_ADDR);
    Wire.write(reg);
    Wire.endTransmission();
    Wire.requestFrom(MC3610_CFG_I2C_ADDR, 2);
    while(!Wire.available()) {};
    uint8_t vha = Wire.read();
    uint8_t vla = Wire.read();

    value = vha << 8 | vla;
    return value;
}

// Write 8-bit from register
void MC3610::writeRegister16(uint8_t reg, int16_t value)
{
    Wire.beginTransmission(MC3610_CFG_I2C_ADDR);
    Wire.write(reg);
    Wire.write((uint8_t)(value >> 8));
    Wire.write((uint8_t)value);
    Wire.endTransmission();
}

// Repeated Read Byte(s) from register
void MC3610::readRegisters(uint8_t reg, byte *buffer, uint8_t len)
{
    Wire.beginTransmission(MC3610_CFG_I2C_ADDR);
    Wire.write(reg);
    Wire.endTransmission(false); //endTransmission but keep the connection active
    Wire.requestFrom(MC3610_CFG_I2C_ADDR, len); //Ask for bytes, once done, bus is released by default

    while(Wire.available() < len); //Hang out until we get the # of bytes we expect
    for(int x = 0 ; x < len ; x++)
	buffer[x] = Wire.read();
}

//Set the operation mode
void MC3610::SetMode(mc3610_mode_t mode)
{
    uint8_t value;
    value = readRegister8(MC3610_REG_MODE_C);
    value &= 0b11110000;
    value |= mode;
    writeRegister8(MC3610_REG_MODE_C, value);
}

//Set the range control
void MC3610::SetRangeCtrl(mc3610_range_t range)
{
    uint8_t value;
    CfgRange = range;
    SetMode(MC3610_MODE_STANDBY);
    value = readRegister8(MC3610_REG_RANGE_C);
    value &= 0b00000111;
    value |= (range << 4)&0x70 ;
    writeRegister8(MC3610_REG_RANGE_C, value);
}

//Set the resolution control
void MC3610::SetResolutionCtrl(mc3610_resolution_t resolution)
{
     uint8_t value;
     CfgResolution = resolution;
     SetMode(MC3610_MODE_STANDBY);
     value = readRegister8(MC3610_REG_RANGE_C);
     value &= 0b01110000;
     value |= resolution;
     writeRegister8(MC3610_REG_RANGE_C, value);
}

//Set the sampling rate
void MC3610::SetCWakeSampleRate(mc3610_cwake_sr_t sample_rate)
{
     uint8_t value;
     SetMode(MC3610_MODE_STANDBY);
     value = readRegister8(MC3610_REG_WAKE_C);
     value &= 0b00000000;
     value |= sample_rate;
     writeRegister8(MC3610_REG_WAKE_C, value);
}

//Get the output sampling rate
mc3610_cwake_sr_t MC3610::GetCWakeSampleRate(void)
{
/* Read the data format register to preserve bits */
     uint8_t value;
     value = readRegister8(MC3610_REG_WAKE_C);
     value &= 0b00001111;
     return (mc3610_cwake_sr_t) (value);
}

//Get the range control
mc3610_range_t MC3610::GetRangeCtrl(void)
{
  	/* Read the data format register to preserve bits */
     uint8_t value;
     value = readRegister8(MC3610_REG_RANGE_C);
     value &= 0x70;
     return (mc3610_range_t) (value >> 4);
}

//Get the range control
mc3610_resolution_t MC3610::GetResolutionCtrl(void)
{
  	/* Read the data format register to preserve bits */
     uint8_t value;
     value = readRegister8(MC3610_REG_RANGE_C);
     value &= 0x07;
     return (mc3610_resolution_t) (value);
}

//Initialize the MC3610 sensor and set as the default configuration
bool MC3610::start(void)
{
     Wire.begin(); // Initialize I2C
     SetMode(MC3610_MODE_STANDBY);
     /* Check I2C connection */
     uint8_t id = readRegister8(MC3610_REG_PROD);
     if (id != 0x70)
     {
     /* No MC3610 detected ... return false */
     	Serial.println(id, HEX);
     	return false;
      }
      SetRangeCtrl(MC3610_RANGE_8G); //Range: 8g
      SetResolutionCtrl(MC3610_RESOLUTION_14BIT); //Resolution: 14bit
      SetCWakeSampleRate(MC3610_CWAKE_SR_DEFAULT_50Hz); //Sampling Rate: 50Hz
      SetMode(MC3610_MODE_CWAKE); //Mode: Active
      return true;
}

void MC3610::stop()
{
      SetMode(MC3610_MODE_SLEEP); //Mode: Sleep
}

//Read the raw counts and SI units mearsurement data
mc3610_acc_t MC3610::readRawAccel(void)
{
      float faRange[5] = { 19.614f, 39.228f, 78.456f, 156.912f, 117.684f}; //{2g, 4g, 8g, 16g, 12g}
      float faResolution[6] = { 32.0f, 64.0f, 128.0f, 512.0f, 2048.0f, 8192.0f}; //{6bit, 7bit, 8bit, 10bit, 12bit, 14bit}

      byte rawData[6];
      readRegisters(MC3610_REG_XOUT_LSB, rawData, 6);  // Read the six raw data registers into data array
      x = (short)((((unsigned short)rawData[1]) << 8) | rawData[0]);
      y = (short)((((unsigned short)rawData[3]) << 8) | rawData[2]);
      z = (short)((((unsigned short)rawData[5]) << 8) | rawData[4]);

      AccRaw.XAxis = (short) (x);
      AccRaw.YAxis = (short) (y);
      AccRaw.ZAxis = (short) (z);
      AccRaw.XAxis_g = (float) (x) / faResolution[CfgResolution]*faRange[CfgRange];
      AccRaw.YAxis_g = (float) (y) / faResolution[CfgResolution]*faRange[CfgRange];
      AccRaw.ZAxis_g = (float) (z) / faResolution[CfgResolution]*faRange[CfgRange];

      return AccRaw;
}


text:
using Specs.Acceptance._CurrentSprint.MasterFiles._BaseSpecifications;

namespace Specs.Acceptance._CurrentSprint.MasterFiles.DisposalReasons
{
    public class DisposalReasonStory : MasterFilesStory
    {
        protected override string EntityName => "Disposal Reason";
    }
}


text:
#ifndef QTADMOBINTERSTITIAL_H
#define QTADMOBINTERSTITIAL_H

#include "QtAdMobInterstitialAndroid.h"
#include "QtAdMobInterstitialDummy.h"
#include "QtAdMobInterstitialIos.h"

inline IQtAdMobInterstitial* CreateQtAdMobInterstitial()
{
#if (__ANDROID_API__ >= 9)
    return new QtAdMobInterstitialAndroid();
#elif (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
    return new QtAdMobInterstitialIos();
#else
    return new QtAdMobInterstitialDummy();
#endif
}

class QmlAdMobInterstitial : public QObject
{
    Q_PROPERTY(QString unitId READ unitId WRITE setUnitId NOTIFY unitIdChanged)
    Q_PROPERTY(bool visible READ visible WRITE setVisible NOTIFY visibleChanged)
    Q_PROPERTY(bool isLoaded READ isLoaded NOTIFY loaded)

    Q_OBJECT
public:
    QmlAdMobInterstitial();
    ~QmlAdMobInterstitial();

    /*
     * Call it before loading qml
     */
    static void DeclareQML();

    /*
     * Setup unit id and start caching interstitial for that id
     */
    void setUnitId(const QString& unitId);

    /*
     * Retrive interstitial id
     */
    const QString& unitId() const;

    /*
     * If interstitial has already loaded it will be presented, another
     * case it will be showed after loading finished
     */
    void setVisible(bool isVisible);

    /*
     * Is interstitial visible
     */
    bool visible();

    /*
     * Check if interstitial loaded
     */
    bool isLoaded();

    /*
     * Add test device identifier. Device identifier you can find in output log, on Android
     * it will looks like 'Ads : Use AdRequest.Builder.addTestDevice("device id") to get test ads on this device.'
     * iOS: // TODO:
     */
    Q_INVOKABLE void addTestDevice(const QString& hashedDeviceId);

signals:
    void unitIdChanged();
    void visibleChanged();
    void loaded();
    void loading();
    void willPresent();
    void closed();
    void clicked();

private:
    IQtAdMobInterstitial* QML() const;

private:
    IQtAdMobInterstitial* m_Instance;
};

#endif // QTADMOBINTERSTITIAL_H


text:
describe 'Constraints - attribute lookup' do

  it 'should return NSLayoutAttributeLeft' do
    MotionKit::Constraint.attribute_lookup(:left).should == NSLayoutAttributeLeft
    MotionKit::Constraint.attribute_lookup(NSLayoutAttributeLeft).should == NSLayoutAttributeLeft
  end

  it 'should return NSLayoutAttributeWidth' do
    MotionKit::Constraint.attribute_lookup(:width).should == NSLayoutAttributeWidth
    MotionKit::Constraint.attribute_lookup(NSLayoutAttributeWidth).should == NSLayoutAttributeWidth
  end

  it 'should raise InvalidAttributeError' do
    -> do
      MotionKit::Constraint.attribute_lookup(:foo)
    end.should.raise(MotionKit::InvalidAttributeError)
  end

  it 'should reverse NSLayoutAttributeLeft' do
    MotionKit::Constraint.attribute_reverse(NSLayoutAttributeLeft).should == :left
  end

  it 'should reverse NSLayoutAttributeWidth' do
    MotionKit::Constraint.attribute_reverse(NSLayoutAttributeWidth).should == :width
  end

end


text: Go?


text:
abstract_class IVBAllocTracker
{
public:
	// This should be called wherever VertexBuffers are allocated
	virtual void CountVB(   void * buffer, bool isDynamic, int bufferSize, int vertexSize, VertexFormat_t fmt ) = 0;
	// This should be called wherever VertexBuffers are freed
	virtual void UnCountVB( void * buffer ) = 0;
	// Track mesh allocations (set this before an allocation, clear it after)
	virtual void TrackMeshAllocations( const char * allocatorName ) = 0;
};

#endif IVBALLOCTRACKER_H


text:
package io.shardingsphere.api.algorithm.fixture;

import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

import java.util.Collection;

public final class TestPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<String> shardingValue) {
        return shardingValue.getValue();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:duration="2000"
        android:fromXScale="3.0"
        android:fromYScale="3.0"
        android:toXScale="1.0"
        android:toYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"/>
    <rotate
        android:duration="2000"
        android:fromDegrees="0"
        android:toDegrees="720"
        android:pivotX="50%"
        android:pivotY="50%"/>
</set>


text:
require "#{$lib}/netlinx/section"

module NetLinx
  class Document
    attr_accessor :programName
    attr_accessor :header
    attr_reader :sections

    def initialize(programName = nil, header = nil)
      @programName = programName
      @header = header

      @sections = {
        :devices => NetLinx::Section.new(:device),
        :constants => NetLinx::Section.new(:constant),
        :includes => NetLinx::Section.new(),
        :types => NetLinx::Section.new(:type),
        :variables => NetLinx::Section.new(:variable),
        :functions => NetLinx::Section.new(),
        :start => NetLinx::Section.new(:start),
        :events => NetLinx::Section.new(:event),
        :program => NetLinx::Section.new(:program)
      }
    end

    def [](section)
      @sections[section]
    end

    def to_s
      out = ''

      out += @header.to_s + "\n" if @header

      out += "PROGRAM_NAME='#{@programName}'\n" if @programName

      @sections.each do |name, section|
        out += "(***********************************************************)\n"
        out += "(*  #{name.to_s.upcase.center 55}*)\n"
        out += "(***********************************************************)\n"

        # Add an extra space to sections that don't start with a DEFINE_ symbol.
        out += "\n" if [:includes, :functions].include? name

        out += section.to_s
      end

      out += <<EOS
(***********************************************************)
(*                     END OF PROGRAM                      *)
(*          DO NOT PUT ANY CODE BELOW THIS COMMENT         *)
(***********************************************************)
EOS

      # Replace tabs with 3 spaces.
      out.gsub(/\t/, '   ')
    end

  end
end


text:
{-# OPTIONS_GHC -Wwarn #-}
{-# LANGUAGE BangPatterns #-}
  -----------------------------------------------------------------------------
-- |
-- Module      :  Haddock.Interface.LexParseRn
-- Copyright   :  (c) Isaac Dupree 2009,
--                    Mateusz Kowalczyk 2013
-- License     :  BSD-like
--
-- Maintainer  :  haddock@projects.haskell.org
-- Stability   :  experimental
-- Portability :  portable
-----------------------------------------------------------------------------
module Haddock.Interface.LexParseRn
  ( processDocString
  , processDocStringParas
  , processDocStrings
  , processModuleHeader
  ) where

import Data.IntSet (toList)
import Data.List
import Documentation.Haddock.Doc (metaDocConcat)
import DynFlags (languageExtensions)
import qualified GHC.LanguageExtensions as LangExt
import FastString
import GHC
import Haddock.Interface.ParseModuleHeader
import Haddock.Parser
import Haddock.Types
import Name
import Outputable ( showPpr )
import RdrName
import RnEnv (dataTcOccs)

processDocStrings :: DynFlags -> GlobalRdrEnv -> [HsDocString]
                  -> ErrMsgM (Maybe (MDoc Name))
processDocStrings dflags gre strs = do
  mdoc <- metaDocConcat <$> traverse (processDocStringParas dflags gre) strs
  case mdoc of
    -- We check that we don't have any version info to render instead
    -- of just checking if there is no comment: there may not be a
    -- comment but we still want to pass through any meta data.
    MetaDoc { _meta = Meta { _version = Nothing }, _doc = DocEmpty } -> pure Nothing
    x -> pure (Just x)

processDocStringParas :: DynFlags -> GlobalRdrEnv -> HsDocString -> ErrMsgM (MDoc Name)
processDocStringParas dflags gre (HsDocString fs) =
  overDocF (rename dflags gre) $ parseParas dflags (unpackFS fs)

processDocString :: DynFlags -> GlobalRdrEnv -> HsDocString -> ErrMsgM (Doc Name)
processDocString dflags gre (HsDocString fs) =
  rename dflags gre $ parseString dflags (unpackFS fs)

processModuleHeader :: DynFlags -> GlobalRdrEnv -> SafeHaskellMode -> Maybe LHsDocString
                    -> ErrMsgM (HaddockModInfo Name, Maybe (MDoc Name))
processModuleHeader dflags gre safety mayStr = do
  (hmi, doc) <-
    case mayStr of
      Nothing -> return failure
      Just (L _ (HsDocString fs)) -> do
        let str = unpackFS fs
            (hmi, doc) = parseModuleHeader dflags str
        !descr <- case hmi_description hmi of
                    Just hmi_descr -> Just <$> rename dflags gre hmi_descr
                    Nothing        -> pure Nothing
        let hmi' = hmi { hmi_description = descr }
        doc'  <- overDocF (rename dflags gre) doc
        return (hmi', Just doc')

  let flags :: [LangExt.Extension]
      -- We remove the flags implied by the language setting and we display the language instead
      flags = map toEnum (toList $ extensionFlags dflags) \\ languageExtensions (language dflags)
  return (hmi { hmi_safety = Just $ showPpr dflags safety
              , hmi_language = language dflags
              , hmi_extensions = flags
              } , doc)
  where
    failure = (emptyHaddockModInfo, Nothing)

-- | Takes a 'GlobalRdrEnv' which (hopefully) contains all the
-- definitions and a parsed comment and we attempt to make sense of
-- where the identifiers in the comment point to. We're in effect
-- trying to convert 'RdrName's to 'Name's, with some guesswork and
-- fallbacks in case we can't locate the identifiers.
--
-- See the comments in the source for implementation commentary.
rename :: DynFlags -> GlobalRdrEnv -> Doc RdrName -> ErrMsgM (Doc Name)
rename dflags gre = rn
  where
    rn d = case d of
      DocAppend a b -> DocAppend <$> rn a <*> rn b
      DocParagraph doc -> DocParagraph <$> rn doc
      DocIdentifier x -> do
        -- Generate the choices for the possible kind of thing this
        -- is.
        let choices = dataTcOccs x
        -- Try to look up all the names in the GlobalRdrEnv that match
        -- the names.
        let names = concatMap (\c -> map gre_name (lookupGRE_RdrName c gre)) choices

        case names of
          -- We found no names in the env so we start guessing.
          [] ->
            case choices of
              [] -> pure (DocMonospaced (DocString (showPpr dflags x)))
              -- There was nothing in the environment so we need to
              -- pick some default from what's available to us. We
              -- diverge here from the old way where we would default
              -- to type constructors as we're much more likely to
              -- actually want anchors to regular definitions than
              -- type constructor names (such as in #253). So now we
              -- only get type constructor links if they are actually
              -- in scope.
              a:_ -> pure (outOfScope dflags a)

          -- There is only one name in the environment that matches so
          -- use it.
          [a] -> pure (DocIdentifier a)
          -- But when there are multiple names available, default to
          -- type constructors: somewhat awfully GHC returns the
          -- values in the list positionally.
          a:b:_ | isTyConName a -> pure (DocIdentifier a)
                | otherwise -> pure (DocIdentifier b)

      DocWarning doc -> DocWarning <$> rn doc
      DocEmphasis doc -> DocEmphasis <$> rn doc
      DocBold doc -> DocBold <$> rn doc
      DocMonospaced doc -> DocMonospaced <$> rn doc
      DocUnorderedList docs -> DocUnorderedList <$> traverse rn docs
      DocOrderedList docs -> DocOrderedList <$> traverse rn docs
      DocDefList list -> DocDefList <$> traverse (\(a, b) -> (,) <$> rn a <*> rn b) list
      DocCodeBlock doc -> DocCodeBlock <$> rn doc
      DocIdentifierUnchecked x -> pure (DocIdentifierUnchecked x)
      DocModule str -> pure (DocModule str)
      DocHyperlink l -> pure (DocHyperlink l)
      DocPic str -> pure (DocPic str)
      DocMathInline str -> pure (DocMathInline str)
      DocMathDisplay str -> pure (DocMathDisplay str)
      DocAName str -> pure (DocAName str)
      DocProperty p -> pure (DocProperty p)
      DocExamples e -> pure (DocExamples e)
      DocEmpty -> pure (DocEmpty)
      DocString str -> pure (DocString str)
      DocHeader (Header l t) -> DocHeader . Header l <$> rn t
      DocTable t -> DocTable <$> traverse rn t

-- | Wrap an identifier that's out of scope (i.e. wasn't found in
-- 'GlobalReaderEnv' during 'rename') in an appropriate doc. Currently
-- we simply monospace the identifier in most cases except when the
-- identifier is qualified: if the identifier is qualified then we can
-- still try to guess and generate anchors accross modules but the
-- users shouldn't rely on this doing the right thing. See tickets
-- #253 and #375 on the confusion this causes depending on which
-- default we pick in 'rename'.
outOfScope :: DynFlags -> RdrName -> Doc a
outOfScope dflags x =
  case x of
    Unqual occ -> monospaced occ
    Qual mdl occ -> DocIdentifierUnchecked (mdl, occ)
    Orig _ occ -> monospaced occ
    Exact name -> monospaced name  -- Shouldn't happen since x is out of scope
  where
    monospaced a = DocMonospaced (DocString (showPpr dflags a))


text:
package com.myconnector.web;

import java.util.Date;

/**
 *
 * @author Nilesh Kapadia (nileshka@gmail.com)
 */
public class TimesheetFilterCommand {

    private Date dateFilter;

    private Date weekFilter;

    private Integer monthFilter;

    public Date getDateFilter() {
        return dateFilter;
    }

    public void setDateFilter(Date dateFilter) {
        this.dateFilter = dateFilter;
    }

    public Integer getMonthFilter() {
        return monthFilter;
    }

    public void setMonthFilter(Integer monthFilter) {
        this.monthFilter = monthFilter;
    }

    public Date getWeekFilter() {
        return weekFilter;
    }

    public void setWeekFilter(Date weekFilter) {
        this.weekFilter = weekFilter;
    }
}


text:
from django.contrib.gis.db import models
import datetime

class Area(models.Model):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    poly = models.PolygonField()
    objects = models.GeoManager()


text:
<?php

namespace Smodeal\UserBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Smodeal\UserBundle\Entity\User;

/**
 * Description of User
 *
 * @author fardus
 */
class Users implements FixtureInterface {

  public function load(ObjectManager $manager) {
    // Les noms d'utilisateurs à créer
    $name_users = array(
        (object) array(
            'username' => 'fardus',
            'name' => 'Hamada Sidi',
            'surname' => 'Fahari',
            'email' => 'h.fahari@gmail.com',
            'roles' => array('ROLE_SUPER_ADMIN')),
        (object) array(
            'username' => 'daouad',
            'name' => 'Bacar',
            'surname' => 'Daoud',
            'email' => 'daouad@hotmail.fr',
            'roles' => array('ROLE_SUPER_ADMIN'))
    );

    $users = array();

    foreach ($name_users as $i => $name_user) {
      // On crée l'utilisateur
      $users[$i] = new User;

      // Le nom d'utilisateur et le mot de passe sont identiques
      $users[$i]->setUsername($name_user->username);
      $users[$i]->setPlainPassword($name_user->username);
      $users[$i]->setEmail($name_user->email);

      $users[$i]->setName($name_user->name);
      $users[$i]->setSurname($name_user->surname);

      // Le sel et les rôles sont vides pour l'instant
      $users[$i]->setSalt('');

      if(is_array($name_user->roles) and !empty($name_user->roles)) {
        foreach ($name_user->roles as $role) {
          $users[$i]->addRole($role);
        }
      }
      $users[$i]->setEnabled(true);

      // On le persiste
      $manager->persist($users[$i]);
    }

    // On déclenche l'enregistrement
    $manager->flush();
  }

}