text:
package com.signalcollect.util

import scala.util.Random

object RandomString {
  def alpha = "abcdefghijklmnopqrstuvwxyz"
  def numeric = "0123456789"
  def alphaNumeric = alpha + numeric

  def generate(length: Int, characters: String = alpha): String = {
    def randomIndex = Random.nextInt(characters.length)
    def randomChar = characters(randomIndex)
    val sb = new StringBuilder(length)
    for (i <- 0 until length) {
      sb.append(randomChar)
    }
    sb.toString
  }

}


text:
<?php
/**
 * Print the Google webfont loader into the <head> element.
 *
 * @package Graphene
 * @since Graphene 1.7.3
 */
function graphene_webfont_script(){
	global $graphene_settings;

	$families = array( 'Pontano+Sans::latin,latin-ext' );
	foreach ( explode( "\n", $graphene_settings['webfont_families'] ) as $family ){
		if ( $family ) $families[] = trim( $family );
	}
	$families = array_unique( $families );
	$families = join( "', '", $families );
	$families = apply_filters( 'graphene_webfont_families', $families );
	?>
	<script type="text/javascript">
	WebFontConfig = {
		google: { families: ['<?php echo $families; ?>'] }
	};
	(function() {
		var wf = document.createElement('script');
		wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
		wf.type = 'text/javascript';
		wf.async = 'true';
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(wf, s);
	})();
    </script>
    <?php
}
add_action( 'wp_head', 'graphene_webfont_script', 5 );
add_action( 'admin_head-appearance_page_custom-header', 'graphene_webfont_script' );

redpajama_set_name: RedPajamaGithub


text:
/*!
    \file  gd32f1x0_it.c
    \brief interrupt service routines
*/

/*
    Copyright (C) 2016 GigaDevice

    2014-12-26, V1.0.0, firmware for GD32F1x0(x=3,5)
    2016-01-15, V2.0.0, firmware for GD32F1x0(x=3,5,7,9)
    2016-04-30, V3.0.0, firmware update for GD32F1x0(x=3,5,7,9)
*/

#include "gd32f1x0_it.h"

extern __IO uint32_t transfer;

/*!
    \brief      this function handles NMI exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void NMI_Handler(void)
{
}

/*!
    \brief      this function handles HardFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void HardFault_Handler(void)
{
    /* if Hard Fault exception occurs, go to infinite loop */
    while (1);
}

/*!
    \brief      this function handles MemManage exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void MemManage_Handler(void)
{
    /* if Memory Manage exception occurs, go to infinite loop */
    while (1);
}

/*!
    \brief      this function handles BusFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void BusFault_Handler(void)
{
    /* if Bus Fault exception occurs, go to infinite loop */
    while (1);
}

/*!
    \brief      this function handles UsageFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void UsageFault_Handler(void)
{
    /* if Usage Fault exception occurs, go to infinite loop */
    while (1);
}

/*!
    \brief      this function handles SVC exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void SVC_Handler(void)
{
}

/*!
    \brief      this function handles DebugMon exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DebugMon_Handler(void)
{
}

/*!
    \brief      this function handles PendSV exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void PendSV_Handler(void)
{
}

/*!
    \brief      this function handles SysTick exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void SysTick_Handler(void)
{
}

#ifdef GD32F130_150

/*!
    \brief      this function handles DMA_Channel1_2_IRQHandler interrupt
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DMA_Channel1_2_IRQHandler(void)
{
    if(dma_interrupt_flag_get(DMA_CH1,DMA_CHXCTL_FTFIF)){
        transfer++;
        dma_interrupt_flag_clear(DMA_CH1,DMA_INTF_ANYIC);
    }
}

#elif defined GD32F170_190

/*!
    \brief      this function handles DMA_Channel3_4_IRQHandler interrupt
    \param[in]  none
    \param[out] none
    \retval     none
*/
void DMA_Channel3_4_IRQHandler(void)
{
    if(dma_interrupt_flag_get(DMA_CH3,DMA_CHXCTL_FTFIF)){
        transfer++;
        dma_interrupt_flag_clear(DMA_CH3,DMA_INTF_ANYIC);
    }
}

#endif   /* GD32F130_150 */


text:
// @author Karl Voskuil (karl@facebook.com)
// @author Mark Rabkin (mrabkin@facebook.com)
//

#ifndef COMMON_STRINGS_THRIFT_SERIALIZER_INL_H
#define COMMON_STRINGS_THRIFT_SERIALIZER_INL_H

#include <stdexcept>
#include <string>
#include <thrift/lib/cpp/util/ThriftSerializer.h>
#include <thrift/lib/cpp/protocol/TProtocolException.h>

namespace apache { namespace thrift { namespace util {

using apache::thrift::protocol::TMessageType;

template <typename Dummy, typename P>
template <typename T, class String>
void
ThriftSerializer<Dummy, P>::serialize(const T& fields, String* serialized)
{
  static_assert(is_legacy_struct<T>::value, "Only works with legacy structs.");

  // prepare or reset buffer
  //
  // note: Three cases:
  //
  //   1) The buffer has never been prepared.  Call prepare().
  //
  //   2) The buffer was last used for a deserialize() call.  In this
  //      case, the buffer is pointing to a now-invalid constant
  //      string, and the buffer should be reallocated.
  //
  //   3) The buffer was last used for a serialize() call.  In this
  //      case, the buffer is still pointing to a valid buffer, but it
  //      contains the serialization from the last serialize(), and
  //      the buffer just needs to be reset.
  //
  // This would be a little simpler if we allocated separate buffers
  // and protocols for serialization and deserialization, but it
  // seemed to me that this fit the common use cases better.  The case
  // that performs poorly (20% slower) is doing many alternating
  // serializations and deserializations.
  if (!prepared_ || lastDeserialized_) {
    prepare();
  } else {
    buffer_->resetBuffer();
  }
  lastDeserialized_ = false;

  // serialize protocol version if necessary
  if (serializeVersion_) {
    protocol_->writeMessageBegin("", TMessageType (0), 0);
  }

  // serialize fields into buffer
  fields.write(protocol_.get());

  // write the end of message
  if (serializeVersion_) {
    protocol_->writeMessageEnd();
  }

  // assign buffer to string
  uint8_t *byteBuffer;
  uint32_t byteBufferSize;
  buffer_->getBuffer(&byteBuffer, &byteBufferSize);
  serialized->assign((const char*)byteBuffer, byteBufferSize);
}

template <typename Dummy, typename P>
template <typename T>
void
ThriftSerializer<Dummy, P>::serialize(const T& fields,
                                      const uint8_t** serializedBuffer,
                                      size_t* serializedLen) {
  static_assert(is_legacy_struct<T>::value, "Only works with legacy structs.");

  CHECK(serializedBuffer);
  CHECK(serializedLen);

  // prepare or reset buffer
  if (!prepared_ || lastDeserialized_) {
    prepare();
  } else {
    buffer_->resetBuffer();
  }
  lastDeserialized_ = false;

  // if required serialize protocol version
  if (serializeVersion_) {
    protocol_->writeMessageBegin("", TMessageType (0), 0);
  }

  // serialize fields into buffer
  fields.write(protocol_.get());

  // write the end of message
  if (serializeVersion_) {
    protocol_->writeMessageEnd();
  }

  // assign buffer to string
  uint8_t *byteBuffer;
  uint32_t byteBufferSize;
  buffer_->getBuffer(&byteBuffer, &byteBufferSize);
  *serializedBuffer = byteBuffer;
  *serializedLen =  byteBufferSize;
}

// Deserializes a thrift object, but assumes that the object passed in the
// fields argument is "clean". If your thrift class contains optional fields,
// you should use deserialize() instead (see below), otherwise optional fields
// that were previously set by other calls to this function won't get reset,
// and will appear to have been desearialized along with the other fields.
template <typename Dummy, typename P>
template <typename T, class String>
uint32_t
ThriftSerializer<Dummy, P>::deserializeClean(const String& serialized,
                                             T* fields)
{
  static_assert(is_legacy_struct<T>::value, "Only works with legacy structs.");

  // prepare buffer if necessary
  if (!prepared_) {
    prepare();
  }
  lastDeserialized_ = true;

  // reset buffer transport to passed string
  buffer_->resetBuffer((uint8_t*)serialized.data(), serialized.size());

  // read the protocol version if necessary
  if (serializeVersion_) {
    std::string name = "";
    TMessageType mt = (TMessageType) 0;
    int32_t seq_id = 0;
    protocol_->readMessageBegin(name, mt, seq_id);
  }

  // deserialize buffer into fields
  uint32_t len = fields->read(protocol_.get());

  // read the end of message
  if (serializeVersion_) {
    protocol_->readMessageEnd();
  }

  return len;
}

template <typename Dummy, typename P>
template <typename T>
uint32_t
ThriftSerializer<Dummy, P>::deserialize(const uint8_t* serializedBuffer,
                                        size_t length,
                                        T* fields)
{
  static_assert(is_legacy_struct<T>::value, "Only works with legacy structs.");

  // prepare buffer if necessary
  if (!prepared_) {
    prepare();
  }
  lastDeserialized_ = true;

  // reset buffer transport to passed string
  buffer_->resetBuffer((uint8_t*)serializedBuffer, length);

  // need to clean the existing structure, as fields->read() will not overwrite
  // the optional fields that were not set in the serialized object.
  T emptyFields;
  swap(emptyFields, *fields);

  // read the protocol version if necessary
  if (serializeVersion_) {
    std::string name = "";
    TMessageType mt = (TMessageType) 0;
    int32_t seq_id = 0;
    protocol_->readMessageBegin(name, mt, seq_id);
  }

  // deserialize buffer into fields
  uint32_t len = fields->read(protocol_.get());

  uint32_t string_limit = protocol_->getStringSizeLimit();
  if (string_limit > 0 && len > string_limit) {
    throw apache::thrift::protocol::TProtocolException(
        apache::thrift::protocol::TProtocolException::SIZE_LIMIT);
  }

  // read the end of message
  if (serializeVersion_) {
    protocol_->readMessageEnd();
  }

  return len;
}

template <typename Dummy, typename P>
void
ThriftSerializer<Dummy, P>::setSerializeVersion(bool value)
{
  serializeVersion_ = value;
}

template <typename Dummy, typename P>
void
ThriftSerializer<Dummy, P>::setVersion(int8_t version)
{
  version_ = version;
  setVersion_ = true;
}

template <typename Dummy, typename P>
void
ThriftSerializer<Dummy, P>::prepareProtocol(shared_ptr<P> protocol)
{
  if (setVersion_) {
    protocol->setVersion(version_);
  }
}

template <typename Dummy, typename P>
void
ThriftSerializer<Dummy, P>::prepare()
{
  // create memory buffer to use as transport
  //
  // note: TMemoryBuffer won't write to the buffer unless it is the
  // owner of it, which means that we can't pass in our own local
  // buffer.  Either must malloc a buffer which TMemoryBuffer will
  // free, or else just let it malloc its own.  This has the added
  // benefit that TMemoryBuffer will grow the buffer size as
  // necessary.
  //
  // The initial allocation of the memory buffer might seem
  // unnecessary in case of parsing (since the memory buffer will be
  // reset to point to the string passed to parseSerializer()), but
  // it's apparently necessary for some protocols.
  buffer_.reset(new TMemoryBuffer());

  // create a protocol for the memory buffer transport
  protocol_.reset(new Protocol(buffer_));
  prepareProtocol(protocol_);

  prepared_ = true;
}

}}} // namespace apache::thrift::util

#endif


text:
// Template Source: BaseEntityCollectionRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests;

import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.SchemaExtension;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

import com.microsoft.graph.requests.SchemaExtensionCollectionRequestBuilder;
import com.microsoft.graph.requests.SchemaExtensionRequestBuilder;
import com.microsoft.graph.requests.SchemaExtensionCollectionRequest;
import com.microsoft.graph.http.BaseCollectionRequestBuilder;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.PrimitiveRequestBuilder;
// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Schema Extension Collection Request Builder.
 */
public class SchemaExtensionCollectionRequestBuilder extends BaseCollectionRequestBuilder<SchemaExtension, SchemaExtensionRequestBuilder, SchemaExtensionCollectionResponse, SchemaExtensionCollectionPage, SchemaExtensionCollectionRequest> {

    /**
     * The request builder for this collection of SchemaExtension
     *
     * @param requestUrl     the request URL
     * @param client         the service client
     * @param requestOptions the options for this request
     */
    public SchemaExtensionCollectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        super(requestUrl, client, requestOptions, SchemaExtensionRequestBuilder.class, SchemaExtensionCollectionRequest.class);
    }

    /**
     * Gets the raw count request for the collection
     * @return The raw count request for the collection
     */
    @Nonnull
    public PrimitiveRequestBuilder<Long> count() {
        return new PrimitiveRequestBuilder<Long>(getRequestUrlWithAdditionalSegment("$count"), getClient(), null, Long.class);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
    <entity name="AppBundle\Entity\Tagency" repository-class="AppBundle\Repository\TagencyRepository" table="TAgency">

        <!--FP-->
        <!--
            <entity-listeners>
                <entity-listener class="AppBundle\EventListener\TagencyfeeListener"/>
                    <lifecycle-callback type="postPersist" method="updatePaymentMethodIds"/>
            </entity-listeners>
        -->
        <!--FP-->

        <lifecycle-callbacks>
            <lifecycle-callback type="postUpdate" method="doStuffOnPostUpdate"/>
        </lifecycle-callbacks>

        <lifecycle-callbacks>
            <lifecycle-callback type="postLoad" method="doStuffOnPostLoad"/>
        </lifecycle-callbacks>

        <unique-constraints>
            <unique-constraint name="FAgencyName" columns="FAgencyName"/>
        </unique-constraints>
        <id name="fagencyid" type="integer" column="FAgencyID">
            <generator strategy="IDENTITY"/>
        </id>

        <one-to-many field="terminalList" target-entity="Tpos" mapped-by="agency" />

        <!--        <one-to-many field="purchaseList" target-entity="Tpurchase" mapped-by="agency" />-->

        <many-to-one field="subgroup" target-entity="Tsubgroup" inversed-by="agencyList">
            <join-column name="FsubgroupID" referenced-column-name="FSubgroupID" />
        </many-to-one>

        <!--    ALTER TABLE `parcelaja_payments`.`TAgency`
        CHANGE COLUMN `FPostalCode1` `FPostalCode1` VARCHAR(10) CHARACTER SET 'utf8' NULL ,
        CHANGE COLUMN `FPostalCode2` `FPostalCode2` VARCHAR(10) CHARACTER SET 'utf8' NULL ,
        CHANGE COLUMN `FLocation` `FLocation` VARCHAR(100) CHARACTER SET 'utf8' NULL ;-->

        <!--    ALTER TABLE `parcelaja_payments`.`TAgency`
        ADD COLUMN `broker_id` INT NULL AFTER `FState`;-->

        <!--ALTER TABLE `parcelaja_payments`.`TAgency`
        CHANGE COLUMN `FAddress` `FAddress` TEXT CHARACTER SET 'utf8' NOT NULL ,
        ADD COLUMN `tax_address` TEXT NULL AFTER `broker_id`;-->

        <!--update TAgency set tax_address = concat(FAddress,', ', FPostalCode1,'-',FPostalCode2,' ', FLocation)-->

        <!--ALTER TABLE `parcelaja_payments`.`TAgency`
        ADD COLUMN `updated_at` DATETIME NULL AFTER `tax_address`;-->

        <!--
      ALTER TABLE `parcelaja_payments`.`TAgency`
      ADD INDEX `fk_TAgency_1_idx` (`broker_id` ASC);
      ALTER TABLE `parcelaja_payments`.`TAgency`
      ADD CONSTRAINT `fk_TAgency_1`
        FOREIGN KEY (`broker_id`)
        REFERENCES `parcelaja_payments`.`broker` (`id`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION;-->

        <many-to-one field="broker" target-entity="Broker" inversed-by="agencyList">
            <join-column name="broker_id" referenced-column-name="id" />
        </many-to-one>

        <!--    <field name="fsubgroupid" type="integer" column="FSubgroupID" nullable="false">
          <options>
            <option name="unsigned"/>
          </options>
        </field>-->
        <field name="fagencyname" type="string" column="FAgencyName" length="100" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="ffiscalname" type="string" column="FFiscalName" length="100" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="ftaxidnumber" type="string" column="FTaxIdNumber" length="20" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <!--        <field name="faddress" type="string" column="FAddress" length="255" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>-->

        <field name="faddress" type="text" column="FAddress" length="65535" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>

        <field name="fpostalcode1" type="string" column="FPostalCode1" length="10" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fpostalcode2" type="string" column="FPostalCode2" length="10" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="flocation" type="string" column="FLocation" length="100" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="femail1" type="string" column="FEmail1" length="100" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="femail2" type="string" column="FEmail2" length="100" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fcontactperson" type="string" column="FContactPerson" length="100" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="ftelephone" type="string" column="FTelephone" length="20" nullable="false">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fmobilephone" type="string" column="FMobilePhone" length="20" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fwebsite" type="string" column="FWebSite" length="255" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fbank" type="string" column="FBank" length="100" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fiban" type="string" column="FIBAN" length="34" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fbicswift" type="string" column="FBICSWIFT" length="11" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="frnavt" type="string" column="FRNAVT" length="4" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fpaymethodid" type="string" column="FPayMethodID" length="255" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="flogo" type="string" column="FLogo" length="100" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>
        <field name="fstate" type="boolean" column="FState" nullable="false"/>

        <field name="taxAddress" type="text" column="tax_address" length="65535" nullable="true">
            <options>
                <option name="fixed"/>
            </options>
        </field>

        <field name="updatedAt" type="datetime" column="updated_at" nullable="true"/>

        <!--        FP      -->
        <one-to-many field="fpaymethodfees" target-entity="Tpaymethodfee" mapped-by="fagency" >
            <cascade>
                <cascade-persist />
            </cascade>

        </one-to-many>

         <field name="fuseonlyshoptax" type="boolean" column="FUseOnlyShopTax" nullable="false"/>

        <field name="invoiceFrequency" type="integer" column="invoice_frequency" nullable="false">
            <options>
                <option name="unsigned"/>
            </options>
        </field>

        <one-to-one field="agencyDocuments" target-entity="AgencyDocuments" mapped-by="agency" />

    </entity>
</doctrine-mapping>

<!--
ALTER TABLE `parcelaja_payments`.`TAgency`
ADD COLUMN `invoice_frequency` INT(11) NULL AFTER `FUseOnlyShopTax`;
ALTER TABLE `parcelaja_payments`.`TAgency`
CHANGE COLUMN `invoice_frequency` `invoice_frequency` INT(11) NULL DEFAULT 1 ;

-->


text:
class Admin::AdminController < ApplicationController
  layout "layouts/admin"
end


text:
package emplRegApp.web.manageBeans;

import emplRegApp.domain.models.view.EmployeeViewModel;
import emplRegApp.service.EmployeeService;
import org.modelmapper.ModelMapper;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

@Named
@RequestScoped
public class EmployeeListBean implements Serializable {
    private static final long serialVersionUID = 1L;

    private List<EmployeeViewModel> employees;

    private EmployeeService employeeService;
    private ModelMapper modelMapper;

    public EmployeeListBean() {
    }

    @Inject
    public EmployeeListBean(EmployeeService employeeService,
                            ModelMapper modelMapper) {
        this.employeeService = employeeService;
        this.modelMapper = modelMapper;
        this.employees = getAllEmployees();
    }

    public List<EmployeeViewModel> getEmployees() {
        return this.employees;
    }

    public void setEmployees(List<EmployeeViewModel> employees) {
        this.employees = employees;
    }

    public BigDecimal getTotalMoney() {
        return this.employees
                .stream()
                .map(EmployeeViewModel::getSalary)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    public BigDecimal getAverageSalary() {
        return this.employees.size() == 0 ? BigDecimal.ZERO
                : this.getTotalMoney().divide(new BigDecimal(this.employees.size()), RoundingMode.HALF_UP);
    }

    private List<EmployeeViewModel> getAllEmployees() {
        return this.employeeService.findAll()
                .stream()
                .map(serviceModel -> this.modelMapper.map(serviceModel, EmployeeViewModel.class))
                .collect(Collectors.toList());
    }
}


text:
JsHamcrest = {
  /**
   * Library version.
   */
  version: '0.6.3',

  /**
   * Returns whether the given object is a matcher.
   */
  isMatcher: function(obj) {
    return obj instanceof JsHamcrest.SimpleMatcher;
  },

  /**
   * Returns whether the given arrays are equivalent.
   */
  areArraysEqual: function(array, anotherArray) {
    if (array instanceof Array || anotherArray instanceof Array) {
      if (array.length != anotherArray.length) {
        return false;
      }

      for (var i = 0; i < array.length; i++) {
        var a = array[i];
        var b = anotherArray[i];

        if (a instanceof Array || b instanceof Array) {
          return JsHamcrest.areArraysEqual(a, b);
        } else if (a != b) {
          return false;
        }
      }
      return true;
    } else {
      return array == anotherArray;
    }
  },

  /**
   * Builds a matcher object that uses external functions provided by the
   * caller in order to define the current matching logic.
   */
  SimpleMatcher: function(params) {
    params = params || {};

    this.matches = params.matches;
    this.describeTo = params.describeTo;

    // Replace the function to describe the actual value
    if (params.describeValueTo) {
      this.describeValueTo = params.describeValueTo;
    }
  },

  /**
   * Matcher that provides an easy way to wrap several matchers into one.
   */
  CombinableMatcher: function(params) {
    // Call superclass' constructor
    JsHamcrest.SimpleMatcher.apply(this, arguments);

    params = params || {};

    this.and = function(anotherMatcher) {
      var all = JsHamcrest.Matchers.allOf(this, anotherMatcher);
      return new JsHamcrest.CombinableMatcher({
        matches: all.matches,

        describeTo: function(description) {
          description.appendDescriptionOf(all);
        }
      });
    };

    this.or = function(anotherMatcher) {
      var any = JsHamcrest.Matchers.anyOf(this, anotherMatcher);
      return new JsHamcrest.CombinableMatcher({
        matches: any.matches,

        describeTo: function(description) {
          description.appendDescriptionOf(any);
        }
      });
    };
  },

  /**
   * Class that builds assertion error messages.
   */
  Description: function() {
    var value = '';

    this.get = function() {
      return value;
    };

    this.appendDescriptionOf = function(selfDescribingObject) {
      if (selfDescribingObject) {
        selfDescribingObject.describeTo(this);
      }
      return this;
    };

    this.append = function(text) {
      if (text != null) {
        value += text;
      }
      return this;
    };

    this.appendLiteral = function(literal) {
      var undefined;
      if (literal === undefined) {
        this.append('undefined');
      } else if (literal === null) {
        this.append('null');
      } else if (literal instanceof Array) {
        this.appendValueList('[', ', ', ']', literal);
      } else if (typeof literal == 'string') {
        this.append('"' + literal + '"');
      } else if (literal instanceof Function) {
        this.append('Function');
      } else {
        this.append(literal);
      }
      return this;
    };

    this.appendValueList = function(start, separator, end, list) {
      this.append(start);
      for (var i = 0; i < list.length; i++) {
        if (i > 0) {
          this.append(separator);
        }
        this.appendLiteral(list[i]);
      }
      this.append(end);
      return this;
    };

    this.appendList = function(start, separator, end, list) {
      this.append(start);
      for (var i = 0; i < list.length; i++) {
        if (i > 0) {
          this.append(separator);
        }
        this.appendDescriptionOf(list[i]);
      }
      this.append(end);
      return this;
    };
  }
};

/**
 * Describes the actual value to the given description. This method is optional
 * and, if it's not present, the actual value will be described as a JavaScript
 * literal.
 */
JsHamcrest.SimpleMatcher.prototype.describeValueTo = function(actual, description) {
  description.appendLiteral(actual);
};

// CombinableMatcher is a specialization of SimpleMatcher
JsHamcrest.CombinableMatcher.prototype = new JsHamcrest.SimpleMatcher();
JsHamcrest.CombinableMatcher.prototype.constructor = JsHamcrest.CombinableMatcher;

JsHamcrest.Matchers = {};

/**
 * The actual value must be any value considered truth by the JavaScript
 * engine.
 */
JsHamcrest.Matchers.truth = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual;
    },

    describeTo: function(description) {
      description.append('truth');
    }
  });
};

/**
 * Delegate-only matcher frequently used to improve readability.
 */
JsHamcrest.Matchers.is = function(matcherOrValue) {
  // Uses 'equalTo' matcher if the given object is not a matcher
  if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return matcherOrValue.matches(actual);
    },

    describeTo: function(description) {
      description.append('is ').appendDescriptionOf(matcherOrValue);
    }
  });
};

/**
 * The actual value must not match the given matcher or value.
 */
JsHamcrest.Matchers.not = function(matcherOrValue) {
  // Uses 'equalTo' matcher if the given object is not a matcher
  if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return !matcherOrValue.matches(actual);
    },

    describeTo: function(description) {
      description.append('not ').appendDescriptionOf(matcherOrValue);
    }
  });
};

/**
 * The actual value must be equal to the given value.
 */
JsHamcrest.Matchers.equalTo = function(expected) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      if (expected instanceof Array || actual instanceof Array) {
        return JsHamcrest.areArraysEqual(expected, actual);
      }
      return actual == expected;
    },

    describeTo: function(description) {
      description.append('equal to ').appendLiteral(expected);
    }
  });
};

/**
 * Useless always-match matcher.
 */
JsHamcrest.Matchers.anything = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return true;
    },

    describeTo: function(description) {
      description.append('anything');
    }
  });
};

/**
 * The actual value must be null (or undefined).
 */
JsHamcrest.Matchers.nil = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual == null;
    },

    describeTo: function(description) {
      description.appendLiteral(null);
    }
  });
};

/**
 * The actual value must be the same as the given value.
 */
JsHamcrest.Matchers.sameAs = function(expected) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual === expected;
    },

    describeTo: function(description) {
      description.append('same as ').appendLiteral(expected);
    }
  });
};

/**
 * The actual value is a function and, when invoked, it should thrown an
 * exception with the given name.
 */
JsHamcrest.Matchers.raises = function(exceptionName) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actualFunction) {
      try {
        actualFunction();
      } catch (e) {
        if (e.name == exceptionName) {
          return true;
        } else {
          throw e;
        }
      }
      return false;
    },

    describeTo: function(description) {
      description.append('raises ').append(exceptionName);
    }
  });
};

/**
 * The actual value is a function and, when invoked, it should raise any
 * exception.
 */
JsHamcrest.Matchers.raisesAnything = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actualFunction) {
      try {
        actualFunction();
      } catch (e) {
        return true;
      }
      return false;
    },

    describeTo: function(description) {
      description.append('raises anything');
    }
  });
};

/**
 * Combinable matcher where the actual value must match both of the given
 * matchers.
 */
JsHamcrest.Matchers.both = function(matcherOrValue) {
  // Uses 'equalTo' matcher if the given object is not a matcher
  if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  return new JsHamcrest.CombinableMatcher({
    matches: matcherOrValue.matches,
    describeTo: function(description) {
      description.append('both ').appendDescriptionOf(matcherOrValue);
    }
  });
};

/**
 * Combinable matcher where the actual value must match at least one of the
 * given matchers.
 */
JsHamcrest.Matchers.either = function(matcherOrValue) {
  // Uses 'equalTo' matcher if the given object is not a matcher
  if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  return new JsHamcrest.CombinableMatcher({
    matches: matcherOrValue.matches,
    describeTo: function(description) {
      description.append('either ').appendDescriptionOf(matcherOrValue);
    }
  });
};

/**
 * All the given values or matchers should match the actual value to be
 * sucessful. This matcher behaves pretty much like the && operator.
 */
JsHamcrest.Matchers.allOf = function() {
  var args = arguments;
  if (args[0] instanceof Array) {
    args = args[0];
  }
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      for (var i = 0; i < args.length; i++) {
        var matcher = args[i];
        if (!JsHamcrest.isMatcher(matcher)) {
          matcher = JsHamcrest.Matchers.equalTo(matcher);
        }
        if (!matcher.matches(actual)) {
          return false;
        }
      }
      return true;
    },

    describeTo: function(description) {
      description.appendList('(', ' and ', ')', args);
    }
  });
};

/**
 * At least one of the given matchers should match the actual value. This
 * matcher behaves pretty much like the || (or) operator.
 */
JsHamcrest.Matchers.anyOf = function() {
  var args = arguments;
  if (args[0] instanceof Array) {
    args = args[0];
  }
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      for (var i = 0; i < args.length; i++) {
        var matcher = args[i];
        if (!JsHamcrest.isMatcher(matcher)) {
          matcher = JsHamcrest.Matchers.equalTo(matcher);
        }
        if (matcher.matches(actual)) {
          return true;
        }
      }
      return false;
    },

    describeTo: function(description) {
      description.appendList('(', ' or ', ')', args);
    }
  });
};

/**
 * The actual number must be greater than the expected number.
 */
JsHamcrest.Matchers.greaterThan = function(expected) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual > expected;
    },

    describeTo: function(description) {
      description.append('greater than ').appendLiteral(expected);
    }
  });
};

/**
 * The actual number must be greater than or equal to the expected number
 */
JsHamcrest.Matchers.greaterThanOrEqualTo = function(expected) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual >= expected;
    },

    describeTo: function(description) {
      description.append('greater than or equal to ').appendLiteral(expected);
    }
  });
};

/**
 * The actual number must be less than the expected number.
 */
JsHamcrest.Matchers.lessThan = function(expected) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual < expected;
    },

    describeTo: function(description) {
      description.append('less than ').appendLiteral(expected);
    }
  });
};

/**
 * The actual number must be less than or equal to the expected number.
 */
JsHamcrest.Matchers.lessThanOrEqualTo = function(expected) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual <= expected;
    },

    describeTo: function(description) {
      description.append('less than or equal to ').append(expected);
    }
  });
};

/**
 * The actual value must not be a number.
 */
JsHamcrest.Matchers.notANumber = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return isNaN(actual);
    },

    describeTo: function(description) {
      description.append('not a number');
    }
  });
};

/**
 * The actual value must be divisible by the given number.
 */
JsHamcrest.Matchers.divisibleBy = function(divisor) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual % divisor === 0;
    },

    describeTo: function(description) {
      description.append('divisible by ').appendLiteral(divisor);
    }
  });
};

/**
 * The actual value must be even.
 */
JsHamcrest.Matchers.even = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual % 2 === 0;
    },

    describeTo: function(description) {
      description.append('even');
    }
  });
};

/**
 * The actual number must be odd.
 */
JsHamcrest.Matchers.odd = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual % 2 !== 0;
    },

    describeTo: function(description) {
      description.append('odd');
    }
  });
};

/**
 * The actual number must be between the given range (inclusive).
 */
JsHamcrest.Matchers.between = function(start) {
  return {
    and: function(end) {
      var greater = end;
      var lesser = start;

      if (start > end) {
        greater = start;
        lesser = end;
      }

      return new JsHamcrest.SimpleMatcher({
        matches: function(actual) {
          return actual >= lesser && actual <= greater;
        },

        describeTo: function(description) {
          description.append('between ').appendLiteral(lesser)
              .append(' and ').appendLiteral(greater);
        }
      });
    }
  };
};

/**
 * The actual number must be close enough to *expected*, that is, the actual
 *  number is equal to a value within some range of acceptable error.
 */
JsHamcrest.Matchers.closeTo = function(expected, delta) {
  if (!delta) {
    delta = 0;
  }

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return (Math.abs(actual - expected) - delta) <= 0;
    },

    describeTo: function(description) {
      description.append('number within ')
          .appendLiteral(delta).append(' of ').appendLiteral(expected);
    }
  });
};

/**
 * The actual number must be zero.
 */
JsHamcrest.Matchers.zero = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual === 0;
    },

    describeTo: function(description) {
      description.append('zero');
    }
  });
};

/**
 * The actual string must be equal to the given string, ignoring case.
 */
JsHamcrest.Matchers.equalIgnoringCase = function(str) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual.toUpperCase() == str.toUpperCase();
    },

    describeTo: function(description) {
      description.append('equal ignoring case "').append(str).append('"');
    }
  });
};

/**
 * The actual string must have a substring equals to the given string.
 */
JsHamcrest.Matchers.containsString = function(str) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual.indexOf(str) >= 0;
    },

    describeTo: function(description) {
      description.append('contains string "').append(str).append('"');
    }
  });
};

/**
 * The actual string must start with the given string.
 */
JsHamcrest.Matchers.startsWith = function(str) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual.indexOf(str) === 0;
    },

    describeTo: function(description) {
      description.append('starts with ').appendLiteral(str);
    }
  });
};

/**
 * The actual string must end with the given string.
 */
JsHamcrest.Matchers.endsWith = function(str) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual.lastIndexOf(str) + str.length == actual.length;
    },

    describeTo: function(description) {
      description.append('ends with ').appendLiteral(str);
    }
  });
};

/**
 * The actual string must match the given regular expression.
 */
JsHamcrest.Matchers.matches = function(regex) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return regex.test(actual);
    },

    describeTo: function(description) {
      description.append('matches ').appendLiteral(regex);
    }
  });
};

/**
 * The actual string must look like an e-mail address.
 */
JsHamcrest.Matchers.emailAddress = function() {
  var regex = /^([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+$/i;

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return regex.test(actual);
    },

    describeTo: function(description) {
      description.append('email address');
    }
  });
};

/**
 * The actual value has a member with the given name.
 */
JsHamcrest.Matchers.hasMember = function(memberName, matcherOrValue) {
  var undefined;
  if (matcherOrValue === undefined) {
    matcherOrValue = JsHamcrest.Matchers.anything();
  } else if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      if (actual && memberName in actual) {
        return matcherOrValue.matches(actual[memberName]);
      }
      return false;
    },

    describeTo: function(description) {
      description.append('has member ').appendLiteral(memberName)
        .append(' (').appendDescriptionOf(matcherOrValue).append(')');
    }
  });
};

/**
 * The actual value has a function with the given name.
 */
JsHamcrest.Matchers.hasFunction = function(functionName) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      if (actual) {
        return functionName in actual &&
            actual[functionName] instanceof Function;
      }
      return false;
    },

    describeTo: function(description) {
      description.append('has function ').appendLiteral(functionName);
    }
  });
};

/**
 * The actual value must be an instance of the given class.
 */
JsHamcrest.Matchers.instanceOf = function(clazz) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return !!(actual instanceof clazz);
    },

    describeTo: function(description) {
      var className = clazz.name ? clazz.name : 'a class';
      description.append('instance of ').append(className);
    }
  });
};

/**
 * The actual value must be an instance of the given type.
 */
JsHamcrest.Matchers.typeOf = function(typeName) {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return (typeof actual == typeName);
    },

    describeTo: function(description) {
      description.append('typeof ').append('"').append(typeName).append('"');
    }
  });
};

/**
 * The actual value must be an object.
 */
JsHamcrest.Matchers.object = function() {
  return new JsHamcrest.Matchers.instanceOf(Object);
};

/**
 * The actual value must be a string.
 */
JsHamcrest.Matchers.string = function() {
  return new JsHamcrest.Matchers.typeOf('string');
};

/**
 * The actual value must be a number.
 */
JsHamcrest.Matchers.number = function() {
  return new JsHamcrest.Matchers.typeOf('number');
};

/**
 * The actual value must be a boolean.
 */
JsHamcrest.Matchers.bool = function() {
  return new JsHamcrest.Matchers.typeOf('boolean');
};

/**
 * The actual value must be a function.
 */
JsHamcrest.Matchers.func = function() {
  return new JsHamcrest.Matchers.instanceOf(Function);
};

/**
 * The actual value should be an array and it must contain at least one value
 * that matches the given value or matcher.
 */
JsHamcrest.Matchers.hasItem = function(matcherOrValue) {
  // Uses 'equalTo' matcher if the given object is not a matcher
  if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      // Should be an array
      if (!(actual instanceof Array)) {
        return false;
      }

      for (var i = 0; i < actual.length; i++) {
        if (matcherOrValue.matches(actual[i])) {
          return true;
        }
      }
      return false;
    },

    describeTo: function(description) {
      description.append('array contains item ')
          .appendDescriptionOf(matcherOrValue);
      }
  });
};

/**
 * The actual value should be an array and the given values or matchers must
 * match at least one item.
 */
JsHamcrest.Matchers.hasItems = function() {
  var items = [];
  for (var i = 0; i < arguments.length; i++) {
    items.push(JsHamcrest.Matchers.hasItem(arguments[i]));
  }
  return JsHamcrest.Matchers.allOf(items);
};

/**
 * The actual value should be an array and the given value or matcher must
 * match all items.
 */
JsHamcrest.Matchers.everyItem = function(matcherOrValue) {
  // Uses 'equalTo' matcher if the given object is not a matcher
  if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      // Should be an array
      if (!(actual instanceof Array)) {
        return false;
      }

      for (var i = 0; i < actual.length; i++) {
        if (!matcherOrValue.matches(actual[i])) {
          return false;
        }
      }
      return true;
    },

    describeTo: function(description) {
      description.append('every item ')
          .appendDescriptionOf(matcherOrValue);
    }
  });
};

/**
 * The given array must contain the actual value.
 */
JsHamcrest.Matchers.isIn = function() {
  var equalTo = JsHamcrest.Matchers.equalTo;

  var args = arguments;
  if (args[0] instanceof Array) {
    args = args[0];
  }

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      for (var i = 0; i < args.length; i++) {
        if (equalTo(args[i]).matches(actual)) {
          return true;
        }
      }
      return false;
    },

    describeTo: function(description) {
      description.append('one of ').appendLiteral(args);
    }
  });
};

/**
 * Alias to 'isIn' matcher.
 */
JsHamcrest.Matchers.oneOf = JsHamcrest.Matchers.isIn;

/**
 * The actual value should be an array and it must be empty to be sucessful.
 */
JsHamcrest.Matchers.empty = function() {
  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return actual.length === 0;
    },

    describeTo: function(description) {
      description.append('empty');
    }
  });
};

/**
 * The length of the actual value value must match the given value or matcher.
 */
JsHamcrest.Matchers.hasSize = function(matcherOrValue) {
  // Uses 'equalTo' matcher if the given object is not a matcher
  if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  return new JsHamcrest.SimpleMatcher({
    matches: function(actual) {
      return matcherOrValue.matches(actual.length);
    },

    describeTo: function(description) {
      description.append('has size ').appendDescriptionOf(matcherOrValue);
    },

    describeValueTo: function(actual, description) {
      description.append(actual.length);
    }
  });
};

JsHamcrest.Operators = {};

/**
 * Returns those items of the array for which matcher matches.
 */
JsHamcrest.Operators.filter = function(array, matcherOrValue) {
  if (!(array instanceof Array) || matcherOrValue == null) {
    return array;
  }
  if (!(matcherOrValue instanceof JsHamcrest.SimpleMatcher)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  var result = [];
  for (var i = 0; i < array.length; i++) {
    if (matcherOrValue.matches(array[i])) {
      result.push(array[i]);
    }
  }
  return result;
};

/**
 * Generic assert function.
 */
JsHamcrest.Operators.assert = function(actualValue, matcherOrValue, options) {
  options = options ? options : {};
  var description = new JsHamcrest.Description();

  if (matcherOrValue == null) {
    matcherOrValue = JsHamcrest.Matchers.truth();
  } else if (!JsHamcrest.isMatcher(matcherOrValue)) {
    matcherOrValue = JsHamcrest.Matchers.equalTo(matcherOrValue);
  }

  if (options.message) {
    description.append(options.message).append('. ');
  }

  description.append('Expected ');
  matcherOrValue.describeTo(description);

  if (!matcherOrValue.matches(actualValue)) {
    description.passed = false;
    description.append(' but was ');
    matcherOrValue.describeValueTo(actualValue, description);
    if (options.fail) {
      options.fail(description.get());
    }
  } else {
    description.append(': Success');
    description.passed = true;
    if (options.pass) {
      options.pass(description.get());
    }
  }
  return description;
};

/**
 * Delegate function, useful when used along with raises() and raisesAnything().
 */
JsHamcrest.Operators.callTo = function() {
  var func = [].shift.call(arguments);
  var args = arguments;
  return function() {
    return func.apply(this, args);
  };
}

/**
 * Integration utilities.
 */

JsHamcrest.Integration = (function() {

  var self = this;

  return {

    /**
     * Copies all members of an object to another.
     */
    copyMembers: function(source, target) {
      if (arguments.length == 1) {
        target = source;
        JsHamcrest.Integration.copyMembers(JsHamcrest.Matchers, target);
        JsHamcrest.Integration.copyMembers(JsHamcrest.Operators, target);
      } else if (source) {
        for (var method in source) {
          if (!(method in target)) {
            target[method] = source[method];
          }
        }
      }
    },

    /**
     * Adds the members of the given object to JsHamcrest.Matchers
     * namespace.
     */
    installMatchers: function(matchersNamespace) {
      var target = JsHamcrest.Matchers;
      JsHamcrest.Integration.copyMembers(matchersNamespace, target);
    },

    /**
     * Adds the members of the given object to JsHamcrest.Operators
     * namespace.
     */
    installOperators: function(operatorsNamespace) {
      var target = JsHamcrest.Operators;
      JsHamcrest.Integration.copyMembers(operatorsNamespace, target);
    },

    /**
     * Uses the web browser's alert() function to display the assertion
     * results. Great for quick prototyping.
     */
    WebBrowser: function() {
      JsHamcrest.Integration.copyMembers(self);

      self.assertThat = function (actual, matcher, message) {
        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: function(message) {
            alert('[FAIL] ' + message);
          },
          pass: function(message) {
            alert('[SUCCESS] ' + message);
          }
        });
      };
    },

    /**
     * Uses the Rhino's print() function to display the assertion results.
     * Great for prototyping.
     */
    Rhino: function() {
      JsHamcrest.Integration.copyMembers(self);

      self.assertThat = function (actual, matcher, message) {
        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: function(message) {
            print('[FAIL] ' + message + '\n');
          },
          pass: function(message) {
            print('[SUCCESS] ' + message + '\n');
          }
        });
      };
    },

    /**
     * JsTestDriver integration.
     */
    JsTestDriver: function(params) {
      params = params ? params : {};
      var target = params.scope || self;

      JsHamcrest.Integration.copyMembers(target);

      // Function called when an assertion fails.
      function fail(message) {
        var exc = new Error(message);
        exc.name = 'AssertError';

        try {
          // Removes all jshamcrest-related entries from error stack
          var re = new RegExp('jshamcrest.*\.js\:', 'i');
          var stack = exc.stack.split('\n');
          var newStack = '';
          for (var i = 0; i < stack.length; i++) {
            if (!re.test(stack[i])) {
              newStack += stack[i] + '\n';
            }
          }
          exc.stack = newStack;
        } catch (e) {
          // It's okay, do nothing
        }
        throw exc;
      }

      // Assertion method exposed to JsTestDriver.
      target.assertThat = function (actual, matcher, message) {
        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: fail
        });
      };
    },

    /**
     * JsUnitTest integration.
     */
    JsUnitTest: function(params) {
      params = params ? params : {};
      var target = params.scope || JsUnitTest.Unit.Testcase.prototype;

      JsHamcrest.Integration.copyMembers(target);

      // Assertion method exposed to JsUnitTest.
      target.assertThat = function (actual, matcher, message) {
        var self = this;

        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: function(message) {
            self.fail(message);
          },
          pass: function() {
            self.pass();
          }
        });
      };
    },

    /**
     * YUITest (Yahoo UI) integration.
     */
    YUITest: function(params) {
      params = params ? params : {};
      var target = params.scope || self;

      JsHamcrest.Integration.copyMembers(target);

      target.Assert = YAHOO.util.Assert;

      // Assertion method exposed to YUITest.
      YAHOO.util.Assert.that = function(actual, matcher, message) {
        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: function(message) {
            YAHOO.util.Assert.fail(message);
          }
        });
      };
    },

    /**
     * QUnit (JQuery) integration.
     */
    QUnit: function(params) {
      params = params ? params : {};
      var target = params.scope || self;

      JsHamcrest.Integration.copyMembers(target);

      // Assertion method exposed to QUnit.
      target.assertThat = function(actual, matcher, message) {
        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: function(message) {
            QUnit.ok(false, message);
          },
          pass: function(message) {
            QUnit.ok(true, message);
          }
        });
      };
    },

    /**
     * jsUnity integration.
     */
    jsUnity: function(params) {
      params = params ? params : {};
      var target = params.scope || jsUnity.env.defaultScope;
      var assertions = params.attachAssertions || false;

      JsHamcrest.Integration.copyMembers(target);

      if (assertions) {
        jsUnity.attachAssertions(target);
      }

      // Assertion method exposed to jsUnity.
      target.assertThat = function(actual, matcher, message) {
        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: function(message) {
            throw message;
          }
        });
      };
    },

    /**
     * Screw.Unit integration.
     */
    screwunit: function(params) {
      params = params ? params : {};
      var target = params.scope || Screw.Matchers;

      JsHamcrest.Integration.copyMembers(target);

      // Assertion method exposed to Screw.Unit.
      target.assertThat = function(actual, matcher, message) {
        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: function(message) {
            throw message;
          }
        });
      };
    },

    /**
     * Jasmine integration.
     */
    jasmine: function(params) {
      params = params ? params : {};
      var target = params.scope || self;

      JsHamcrest.Integration.copyMembers(target);

      // Assertion method exposed to Jasmine.
      target.assertThat = function(actual, matcher, message) {
        return JsHamcrest.Operators.assert(actual, matcher, {
          message: message,
          fail: function(message) {
            jasmine.getEnv().currentSpec.addMatcherResult(
              new jasmine.ExpectationResult({passed:false, message:message})
            );
          },
          pass: function(message) {
            jasmine.getEnv().currentSpec.addMatcherResult(
              new jasmine.ExpectationResult({passed:true, message:message})
            );
          }
        });
      };
    }
  };
})();


text:
'use strict';

var path = require('path'),
    webpack = require('webpack'),
    node_modules = path.resolve(__dirname, 'node_modules'),
    pathToAngular = path.resolve(node_modules, 'angular/angular.min.js');

module.exports = {
   context: __dirname,
   entry: [
         './client/app/app.js'
      ],
   resolve: {
     alias: {
        'angular': pathToAngular
     }
   },
   output: {
      path: __dirname + '/client/build',
      publicPath: 'http://localhost:3000/assets/[hash]',
      filename: 'bundle.js'
   },
   module: {
      preLoaders: [
         {
            test: /\.js$/, // include .js files
            exclude: /node_modules/, // exclude any and all files in the node_modules folder
            loader: 'jshint-loader'
         }
      ],
      loaders: [
         {test: /\.html$/, loader: 'html', exclude: /node_modules/},
         {test: /\.css$/,  loader: 'style!css', exclude: /node_modules/},
         {test: /\.styl$/, loader: 'style!css!stylus', exclude: /node_modules/},
         {test: /\.(jpe?g|png|gif|svg)$/i, loader:'url'}
      ],
      norParse: [pathToAngular]
   }
};


text:
int main()
{
	double a, x, ans1, ans2, ans3;   //variables needed
	cout<<"Welcome to the EQUATIONS PROGRAM.\n";                   //prompt/intro to the program
	cout<<"This program will evaluate the function: \n";
	cout<<"f(x)=ax^3+7 \n";
	cout<<"when you input the values for 'a' and 'x'. \n";
	cout<<"========================================== \n";
	cout<<endl;
	cout<<"Enter a value for 'a'. \n";   	//asks user for 'a'. next line accepts 'a' and stores it.
	cin>>a;
	cout<<"Enter a value for 'x.' \n";   	//asks user for 'x'. next line accepts 'x' and stores it.
	cin>>x;
	cout.precision(5);
	ans1=pow(x,3);               			//does the math of the equation f(x)=ax^3+7
	ans2=ans1*a;
	ans3=ans2+7;
	cout<<endl;
	cout<<"The value of the function is f(" <<x <<")=" <<ans3<<"\n";        //displays the final equation.
	cout<<endl;
	cout<<"Thank You for using the EQUATIONS PROGRAM.";
	return 0;
}


text:
<?xml version="1.0"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://incubator.apache.org/ivy/schemas/ivy.xsd">

    <info organisation="apache" module="commons-pool" revision="1.2.2">
        <license name="Apache" url="http://www.apache.org/licenses/LICENSE-2.0.txt"/>
        <description homepage="http://commons.apache.org/pool">Apache Commons Object Pooling
            API</description>
    </info>
</ivy-module>


text:
from rester.struct import DictWrapper
import json
import os
import yaml
from rester.manifest import Variables

class TestSuite(object):
    def __init__(self, filename):
        self.filename = filename
        self.test_cases = []
        self.variables = Variables()
        self.load()

    def load(self):
        with open(self.filename) as fh:
            data = load(self.filename, fh)
            self._load(data)

    def _load(self, data):
        self.variables.update(data.get('globals', {}).get('variables', {}).items())
        for case in data['test_cases']:
            filename = os.path.join(os.path.dirname(self.filename), case)
            self.test_cases.append(TestCase(self, filename))

class TestCase(object):
    def __init__(self, suite, filename):
        self.filename = filename
        self.data = None
        self.variables = Variables()
        if suite:
            self.variables.update(suite.variables)
        self.load()

    def __getattr__(self, key):
        return getattr(self.data, key)

    @property
    def steps(self):
        return self.data.testSteps

    @property
    def request_opts(self):
        return self.variables.get('request_opts', {})

    def load(self):
        with open(self.filename) as fh:
            data = load(self.filename, fh)
            self._load(data)

    def _load(self, data):
        self.data = DictWrapper(data)
        self.variables.update(data.get('globals', {}).get('variables', {}).items())

def load(filename, fh):
    if filename.endswith(".yaml"):
        return yaml.load(fh.read())
    return json.load(fh)


text:
import { isNotEmptyString } from '../../utils'

export default function SubscribeToStream ({
  eventsStream
}) {
  return (call) => {
    let onClientTermination = () => call.end()
    call.on('end', () => onClientTermination())

    call.once('data', (request) => {
      let { stream } = request

      // Validate request
      if (!isNotEmptyString(stream)) return call.emit('error', new TypeError('stream should be a non empty string'))

      let subscription = eventsStream
        .filter((event) => event.stream === stream)
        .subscribe(
          event => call.write(event),
          err => call.emit('error', err)
        )

      onClientTermination = () => {
        subscription.unsubscribe()
        call.end()
      }
    })
  }
}


text:
<?php

if (!defined('SMF'))
	die('Hacking attempt...');

/*	This function has only one job: providing a display for forum statistics.
	As such, it has only one function:

	void DisplayStats()
		- gets all the statistics in order and puts them in.
		- uses the Stats template and language file. (and main sub template.)
		- requires the view_stats permission.
		- accessed from ?action=stats.

	void getDailyStats(string $condition)
		- called by DisplayStats().
		- loads the statistics on a daily basis in $context.

	void SMStats()
		- called by simplemachines.org.
		- only returns anything if stats was enabled during installation.
		- can also be accessed by the admin, to show what stats sm.org collects.
		- does not return any data directly to sm.org, instead starts a new request for security.

*/

// Display some useful/interesting board statistics.
function DisplayStats()
{
	global $txt, $scripturl, $modSettings, $user_info, $context, $smcFunc;

	isAllowedTo('view_stats');

	if (!empty($_REQUEST['expand']))
	{
		$context['robot_no_index'] = true;

		$month = (int) substr($_REQUEST['expand'], 4);
		$year = (int) substr($_REQUEST['expand'], 0, 4);
		if ($year > 1900 && $year < 2200 && $month >= 1 && $month <= 12)
			$_SESSION['expanded_stats'][$year][] = $month;
	}
	elseif (!empty($_REQUEST['collapse']))
	{
		$context['robot_no_index'] = true;

		$month = (int) substr($_REQUEST['collapse'], 4);
		$year = (int) substr($_REQUEST['collapse'], 0, 4);
		if (!empty($_SESSION['expanded_stats'][$year]))
			$_SESSION['expanded_stats'][$year] = array_diff($_SESSION['expanded_stats'][$year], array($month));
	}

	// Handle the XMLHttpRequest.
	if (isset($_REQUEST['xml']))
	{
		// Collapsing stats only needs adjustments of the session variables.
		if (!empty($_REQUEST['collapse']))
			obExit(false);

		$context['sub_template'] = 'stats';
		getDailyStats('YEAR(date) = {int:year} AND MONTH(date) = {int:month}', array('year' => $year, 'month' => $month));
		$context['yearly'][$year]['months'][$month]['date'] = array(
			'month' => sprintf('%02d', $month),
			'year' => $year,
		);
		return;
	}

	loadLanguage('Stats');
	loadTemplate('Stats');

	// Build the link tree......
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=stats',
		'name' => $txt['stats_center']
	);
	$context['page_title'] = $context['forum_name'] . ' - ' . $txt['stats_center'];

	$context['show_member_list'] = allowedTo('view_mlist');

	// Get averages...
	$result = $smcFunc['db_query']('', '
		SELECT
			SUM(posts) AS posts, SUM(topics) AS topics, SUM(registers) AS registers,
			SUM(most_on) AS most_on, MIN(date) AS date, SUM(hits) AS hits
		FROM {db_prefix}log_activity',
		array(
		)
	);
	$row = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

	// This would be the amount of time the forum has been up... in days...
	$total_days_up = ceil((time() - strtotime($row['date'])) / (60 * 60 * 24));

	$context['average_posts'] = comma_format(round($row['posts'] / $total_days_up, 2));
	$context['average_topics'] = comma_format(round($row['topics'] / $total_days_up, 2));
	$context['average_members'] = comma_format(round($row['registers'] / $total_days_up, 2));
	$context['average_online'] = comma_format(round($row['most_on'] / $total_days_up, 2));
	$context['average_hits'] = comma_format(round($row['hits'] / $total_days_up, 2));

	$context['num_hits'] = comma_format($row['hits'], 0);

	// How many users are online now.
	$result = $smcFunc['db_query']('', '
		SELECT COUNT(*)
		FROM {db_prefix}log_online',
		array(
		)
	);
	list ($context['users_online']) = $smcFunc['db_fetch_row']($result);
	$smcFunc['db_free_result']($result);

	// Statistics such as number of boards, categories, etc.
	$result = $smcFunc['db_query']('', '
		SELECT COUNT(*)
		FROM {db_prefix}boards AS b
		WHERE b.redirect = {string:blank_redirect}',
		array(
			'blank_redirect' => '',
		)
	);
	list ($context['num_boards']) = $smcFunc['db_fetch_row']($result);
	$smcFunc['db_free_result']($result);

	$result = $smcFunc['db_query']('', '
		SELECT COUNT(*)
		FROM {db_prefix}categories AS c',
		array(
		)
	);
	list ($context['num_categories']) = $smcFunc['db_fetch_row']($result);
	$smcFunc['db_free_result']($result);

	// Format the numbers nicely.
	$context['users_online'] = comma_format($context['users_online']);
	$context['num_boards'] = comma_format($context['num_boards']);
	$context['num_categories'] = comma_format($context['num_categories']);

	$context['num_members'] = comma_format($modSettings['totalMembers']);
	$context['num_posts'] = comma_format($modSettings['totalMessages']);
	$context['num_topics'] = comma_format($modSettings['totalTopics']);
	$context['most_members_online'] = array(
		'number' => comma_format($modSettings['mostOnline']),
		'date' => timeformat($modSettings['mostDate'])
	);
	$context['latest_member'] = &$context['common_stats']['latest_member'];

	// Male vs. female ratio - let's calculate this only every four minutes.
	if (($context['gender'] = cache_get_data('stats_gender', 240)) == null)
	{
		$result = $smcFunc['db_query']('', '
			SELECT COUNT(*) AS total_members, gender
			FROM {db_prefix}members
			GROUP BY gender',
			array(
			)
		);
		$context['gender'] = array();
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			// Assuming we're telling... male or female?
			if (!empty($row['gender']))
				$context['gender'][$row['gender'] == 2 ? 'females' : 'males'] = $row['total_members'];
		}
		$smcFunc['db_free_result']($result);

		// Set these two zero if the didn't get set at all.
		if (empty($context['gender']['males']))
			$context['gender']['males'] = 0;
		if (empty($context['gender']['females']))
			$context['gender']['females'] = 0;

		// Try and come up with some "sensible" default states in case of a non-mixed board.
		if ($context['gender']['males'] == $context['gender']['females'])
			$context['gender']['ratio'] = '1:1';
		elseif ($context['gender']['males'] == 0)
			$context['gender']['ratio'] = '0:1';
		elseif ($context['gender']['females'] == 0)
			$context['gender']['ratio'] = '1:0';
		elseif ($context['gender']['males'] > $context['gender']['females'])
			$context['gender']['ratio'] = round($context['gender']['males'] / $context['gender']['females'], 1) . ':1';
		elseif ($context['gender']['females'] > $context['gender']['males'])
			$context['gender']['ratio'] = '1:' . round($context['gender']['females'] / $context['gender']['males'], 1);

		cache_put_data('stats_gender', $context['gender'], 240);
	}

	$date = strftime('%Y-%m-%d', forum_time(false));

	// Members online so far today.
	$result = $smcFunc['db_query']('', '
		SELECT most_on
		FROM {db_prefix}log_activity
		WHERE date = {date:today_date}
		LIMIT 1',
		array(
			'today_date' => $date,
		)
	);
	list ($context['online_today']) = $smcFunc['db_fetch_row']($result);
	$smcFunc['db_free_result']($result);

	$context['online_today'] = comma_format((int) $context['online_today']);

	// Poster top 10.
	$members_result = $smcFunc['db_query']('', '
		SELECT id_member, real_name, posts
		FROM {db_prefix}members
		WHERE posts > {int:no_posts}
		ORDER BY posts DESC
		LIMIT 10',
		array(
			'no_posts' => 0,
		)
	);
	$context['top_posters'] = array();
	$max_num_posts = 1;
	while ($row_members = $smcFunc['db_fetch_assoc']($members_result))
	{
		$context['top_posters'][] = array(
			'name' => $row_members['real_name'],
			'id' => $row_members['id_member'],
			'num_posts' => $row_members['posts'],
			'href' => $scripturl . '?action=profile;u=' . $row_members['id_member'],
			'link' => '' . $row_members['real_name'] . ''
		);

		if ($max_num_posts < $row_members['posts'])
			$max_num_posts = $row_members['posts'];
	}
	$smcFunc['db_free_result']($members_result);

	foreach ($context['top_posters'] as $i => $poster)
	{
		$context['top_posters'][$i]['post_percent'] = round(($poster['num_posts'] * 100) / $max_num_posts);
		$context['top_posters'][$i]['num_posts'] = comma_format($context['top_posters'][$i]['num_posts']);
	}

	// Board top 10.
	$boards_result = $smcFunc['db_query']('', '
		SELECT id_board, name, num_posts
		FROM {db_prefix}boards AS b
		WHERE {query_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
			AND b.id_board != {int:recycle_board}' : '') . '
			AND b.redirect = {string:blank_redirect}
		ORDER BY num_posts DESC
		LIMIT 10',
		array(
			'recycle_board' => $modSettings['recycle_board'],
			'blank_redirect' => '',
		)
	);
	$context['top_boards'] = array();
	$max_num_posts = 1;
	while ($row_board = $smcFunc['db_fetch_assoc']($boards_result))
	{
		$context['top_boards'][] = array(
			'id' => $row_board['id_board'],
			'name' => $row_board['name'],
			'num_posts' => $row_board['num_posts'],
			'href' => $scripturl . '?board=' . $row_board['id_board'] . '.0',
			'link' => '' . $row_board['name'] . ''
		);

		if ($max_num_posts < $row_board['num_posts'])
			$max_num_posts = $row_board['num_posts'];
	}
	$smcFunc['db_free_result']($boards_result);

	foreach ($context['top_boards'] as $i => $board)
	{
		$context['top_boards'][$i]['post_percent'] = round(($board['num_posts'] * 100) / $max_num_posts);
		$context['top_boards'][$i]['num_posts'] = comma_format($context['top_boards'][$i]['num_posts']);
	}

	// Are you on a larger forum?  If so, let's try to limit the number of topics we search through.
	if ($modSettings['totalMessages'] > 100000)
	{
		$request = $smcFunc['db_query']('', '
			SELECT id_topic
			FROM {db_prefix}topics
			WHERE num_replies != {int:no_replies}' . ($modSettings['postmod_active'] ? '
				AND approved = {int:is_approved}' : '') . '
			ORDER BY num_replies DESC
			LIMIT 100',
			array(
				'no_replies' => 0,
				'is_approved' => 1,
			)
		);
		$topic_ids = array();
		while ($row = $smcFunc['db_fetch_assoc']($request))
			$topic_ids[] = $row['id_topic'];
		$smcFunc['db_free_result']($request);
	}
	else
		$topic_ids = array();

	// Topic replies top 10.
	$topic_reply_result = $smcFunc['db_query']('', '
		SELECT m.subject, t.num_replies, t.id_board, t.id_topic, b.name
		FROM {db_prefix}topics AS t
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
			AND b.id_board != {int:recycle_board}' : '') . ')
		WHERE {query_see_board}' . (!empty($topic_ids) ? '
			AND t.id_topic IN ({array_int:topic_list})' : ($modSettings['postmod_active'] ? '
			AND t.approved = {int:is_approved}' : '')) . '
		ORDER BY t.num_replies DESC
		LIMIT 10',
		array(
			'topic_list' => $topic_ids,
			'recycle_board' => $modSettings['recycle_board'],
			'is_approved' => 1,
		)
	);
	$context['top_topics_replies'] = array();
	$max_num_replies = 1;
	while ($row_topic_reply = $smcFunc['db_fetch_assoc']($topic_reply_result))
	{
		censorText($row_topic_reply['subject']);

		$context['top_topics_replies'][] = array(
			'id' => $row_topic_reply['id_topic'],
			'board' => array(
				'id' => $row_topic_reply['id_board'],
				'name' => $row_topic_reply['name'],
				'href' => $scripturl . '?board=' . $row_topic_reply['id_board'] . '.0',
				'link' => '' . $row_topic_reply['name'] . ''
			),
			'subject' => $row_topic_reply['subject'],
			'num_replies' => $row_topic_reply['num_replies'],
			'href' => $scripturl . '?topic=' . $row_topic_reply['id_topic'] . '.0',
			'link' => '' . $row_topic_reply['subject'] . ''
		);

		if ($max_num_replies < $row_topic_reply['num_replies'])
			$max_num_replies = $row_topic_reply['num_replies'];
	}
	$smcFunc['db_free_result']($topic_reply_result);

	foreach ($context['top_topics_replies'] as $i => $topic)
	{
		$context['top_topics_replies'][$i]['post_percent'] = round(($topic['num_replies'] * 100) / $max_num_replies);
		$context['top_topics_replies'][$i]['num_replies'] = comma_format($context['top_topics_replies'][$i]['num_replies']);
	}

	// Large forums may need a bit more prodding...
	if ($modSettings['totalMessages'] > 100000)
	{
		$request = $smcFunc['db_query']('', '
			SELECT id_topic
			FROM {db_prefix}topics
			WHERE num_views != {int:no_views}
			ORDER BY num_views DESC
			LIMIT 100',
			array(
				'no_views' => 0,
			)
		);
		$topic_ids = array();
		while ($row = $smcFunc['db_fetch_assoc']($request))
			$topic_ids[] = $row['id_topic'];
		$smcFunc['db_free_result']($request);
	}
	else
		$topic_ids = array();

	// Topic views top 10.
	$topic_view_result = $smcFunc['db_query']('', '
		SELECT m.subject, t.num_views, t.id_board, t.id_topic, b.name
		FROM {db_prefix}topics AS t
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
			AND b.id_board != {int:recycle_board}' : '') . ')
		WHERE {query_see_board}' . (!empty($topic_ids) ? '
			AND t.id_topic IN ({array_int:topic_list})' : ($modSettings['postmod_active'] ? '
			AND t.approved = {int:is_approved}' : '')) . '
		ORDER BY t.num_views DESC
		LIMIT 10',
		array(
			'topic_list' => $topic_ids,
			'recycle_board' => $modSettings['recycle_board'],
			'is_approved' => 1,
		)
	);
	$context['top_topics_views'] = array();
	$max_num_views = 1;
	while ($row_topic_views = $smcFunc['db_fetch_assoc']($topic_view_result))
	{
		censorText($row_topic_views['subject']);

		$context['top_topics_views'][] = array(
			'id' => $row_topic_views['id_topic'],
			'board' => array(
				'id' => $row_topic_views['id_board'],
				'name' => $row_topic_views['name'],
				'href' => $scripturl . '?board=' . $row_topic_views['id_board'] . '.0',
				'link' => '' . $row_topic_views['name'] . ''
			),
			'subject' => $row_topic_views['subject'],
			'num_views' => $row_topic_views['num_views'],
			'href' => $scripturl . '?topic=' . $row_topic_views['id_topic'] . '.0',
			'link' => '' . $row_topic_views['subject'] . ''
		);

		if ($max_num_views < $row_topic_views['num_views'])
			$max_num_views = $row_topic_views['num_views'];
	}
	$smcFunc['db_free_result']($topic_view_result);

	foreach ($context['top_topics_views'] as $i => $topic)
	{
		$context['top_topics_views'][$i]['post_percent'] = round(($topic['num_views'] * 100) / $max_num_views);
		$context['top_topics_views'][$i]['num_views'] = comma_format($context['top_topics_views'][$i]['num_views']);
	}

	// Try to cache this when possible, because it's a little unavoidably slow.
	if (($members = cache_get_data('stats_top_starters', 360)) == null)
	{
		$request = $smcFunc['db_query']('', '
			SELECT id_member_started, COUNT(*) AS hits
			FROM {db_prefix}topics' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
			WHERE id_board != {int:recycle_board}' : '') . '
			GROUP BY id_member_started
			ORDER BY hits DESC
			LIMIT 20',
			array(
				'recycle_board' => $modSettings['recycle_board'],
			)
		);
		$members = array();
		while ($row = $smcFunc['db_fetch_assoc']($request))
			$members[$row['id_member_started']] = $row['hits'];
		$smcFunc['db_free_result']($request);

		cache_put_data('stats_top_starters', $members, 360);
	}

	if (empty($members))
		$members = array(0 => 0);

	// Topic poster top 10.
	$members_result = $smcFunc['db_query']('top_topic_starters', '
		SELECT id_member, real_name
		FROM {db_prefix}members
		WHERE id_member IN ({array_int:member_list})
		ORDER BY FIND_IN_SET(id_member, {string:top_topic_posters})
		LIMIT 10',
		array(
			'member_list' => array_keys($members),
			'top_topic_posters' => implode(',', array_keys($members)),
		)
	);
	$context['top_starters'] = array();
	$max_num_topics = 1;
	while ($row_members = $smcFunc['db_fetch_assoc']($members_result))
	{
		$context['top_starters'][] = array(
			'name' => $row_members['real_name'],
			'id' => $row_members['id_member'],
			'num_topics' => $members[$row_members['id_member']],
			'href' => $scripturl . '?action=profile;u=' . $row_members['id_member'],
			'link' => '' . $row_members['real_name'] . ''
		);

		if ($max_num_topics < $members[$row_members['id_member']])
			$max_num_topics = $members[$row_members['id_member']];
	}
	$smcFunc['db_free_result']($members_result);

	foreach ($context['top_starters'] as $i => $topic)
	{
		$context['top_starters'][$i]['post_percent'] = round(($topic['num_topics'] * 100) / $max_num_topics);
		$context['top_starters'][$i]['num_topics'] = comma_format($context['top_starters'][$i]['num_topics']);
	}

	// Time online top 10.
	$temp = cache_get_data('stats_total_time_members', 600);
	$members_result = $smcFunc['db_query']('', '
		SELECT id_member, real_name, total_time_logged_in
		FROM {db_prefix}members' . (!empty($temp) ? '
		WHERE id_member IN ({array_int:member_list_cached})' : '') . '
		ORDER BY total_time_logged_in DESC
		LIMIT 20',
		array(
			'member_list_cached' => $temp,
		)
	);
	$context['top_time_online'] = array();
	$temp2 = array();
	$max_time_online = 1;
	while ($row_members = $smcFunc['db_fetch_assoc']($members_result))
	{
		$temp2[] = (int) $row_members['id_member'];
		if (count($context['top_time_online']) >= 10)
			continue;

		// Figure out the days, hours and minutes.
		$timeDays = floor($row_members['total_time_logged_in'] / 86400);
		$timeHours = floor(($row_members['total_time_logged_in'] % 86400) / 3600);

		// Figure out which things to show... (days, hours, minutes, etc.)
		$timelogged = '';
		if ($timeDays > 0)
			$timelogged .= $timeDays . $txt['totalTimeLogged5'];
		if ($timeHours > 0)
			$timelogged .= $timeHours . $txt['totalTimeLogged6'];
		$timelogged .= floor(($row_members['total_time_logged_in'] % 3600) / 60) . $txt['totalTimeLogged7'];

		$context['top_time_online'][] = array(
			'id' => $row_members['id_member'],
			'name' => $row_members['real_name'],
			'time_online' => $timelogged,
			'seconds_online' => $row_members['total_time_logged_in'],
			'href' => $scripturl . '?action=profile;u=' . $row_members['id_member'],
			'link' => '' . $row_members['real_name'] . ''
		);

		if ($max_time_online < $row_members['total_time_logged_in'])
			$max_time_online = $row_members['total_time_logged_in'];
	}
	$smcFunc['db_free_result']($members_result);

	foreach ($context['top_time_online'] as $i => $member)
		$context['top_time_online'][$i]['time_percent'] = round(($member['seconds_online'] * 100) / $max_time_online);

	// Cache the ones we found for a bit, just so we don't have to look again.
	if ($temp !== $temp2)
		cache_put_data('stats_total_time_members', $temp2, 480);

	// Activity by month.
	$months_result = $smcFunc['db_query']('', '
		SELECT
			YEAR(date) AS stats_year, MONTH(date) AS stats_month, SUM(hits) AS hits, SUM(registers) AS registers, SUM(topics) AS topics, SUM(posts) AS posts, MAX(most_on) AS most_on, COUNT(*) AS num_days
		FROM {db_prefix}log_activity
		GROUP BY stats_year, stats_month',
		array()
	);

	$context['yearly'] = array();
	while ($row_months = $smcFunc['db_fetch_assoc']($months_result))
	{
		$ID_MONTH = $row_months['stats_year'] . sprintf('%02d', $row_months['stats_month']);
		$expanded = !empty($_SESSION['expanded_stats'][$row_months['stats_year']]) && in_array($row_months['stats_month'], $_SESSION['expanded_stats'][$row_months['stats_year']]);

		if (!isset($context['yearly'][$row_months['stats_year']]))
			$context['yearly'][$row_months['stats_year']] = array(
				'year' => $row_months['stats_year'],
				'new_topics' => 0,
				'new_posts' => 0,
				'new_members' => 0,
				'most_members_online' => 0,
				'hits' => 0,
				'num_months' => 0,
				'months' => array(),
				'expanded' => false,
				'current_year' => $row_months['stats_year'] == date('Y'),
			);

		$context['yearly'][$row_months['stats_year']]['months'][(int) $row_months['stats_month']] = array(
			'id' => $ID_MONTH,
			'date' => array(
				'month' => sprintf('%02d', $row_months['stats_month']),
				'year' => $row_months['stats_year']
			),
			'href' => $scripturl . '?action=stats;' . ($expanded ? 'collapse' : 'expand') . '=' . $ID_MONTH . '#m' . $ID_MONTH,
			'link' => '' . $txt['months'][(int) $row_months['stats_month']] . ' ' . $row_months['stats_year'] . '',
			'month' => $txt['months'][(int) $row_months['stats_month']],
			'year' => $row_months['stats_year'],
			'new_topics' => comma_format($row_months['topics']),
			'new_posts' => comma_format($row_months['posts']),
			'new_members' => comma_format($row_months['registers']),
			'most_members_online' => comma_format($row_months['most_on']),
			'hits' => comma_format($row_months['hits']),
			'num_days' => $row_months['num_days'],
			'days' => array(),
			'expanded' => $expanded
		);

		$context['yearly'][$row_months['stats_year']]['new_topics'] += $row_months['topics'];
		$context['yearly'][$row_months['stats_year']]['new_posts'] += $row_months['posts'];
		$context['yearly'][$row_months['stats_year']]['new_members'] += $row_months['registers'];
		$context['yearly'][$row_months['stats_year']]['hits'] += $row_months['hits'];
		$context['yearly'][$row_months['stats_year']]['num_months']++;
		$context['yearly'][$row_months['stats_year']]['expanded'] |= $expanded;
		$context['yearly'][$row_months['stats_year']]['most_members_online'] = max($context['yearly'][$row_months['stats_year']]['most_members_online'], $row_months['most_on']);
	}

	krsort($context['yearly']);

	$context['collapsed_years'] = array();
	foreach ($context['yearly'] as $year => $data)
	{
		// This gets rid of the filesort on the query ;).
		krsort($context['yearly'][$year]['months']);

		$context['yearly'][$year]['new_topics'] = comma_format($data['new_topics']);
		$context['yearly'][$year]['new_posts'] = comma_format($data['new_posts']);
		$context['yearly'][$year]['new_members'] = comma_format($data['new_members']);
		$context['yearly'][$year]['most_members_online'] = comma_format($data['most_members_online']);
		$context['yearly'][$year]['hits'] = comma_format($data['hits']);

		// Keep a list of collapsed years.
		if (!$data['expanded'] && !$data['current_year'])
			$context['collapsed_years'][] = $year;
	}

	if (empty($_SESSION['expanded_stats']))
		return;

	$condition_text = array();
	$condition_params = array();
	foreach ($_SESSION['expanded_stats'] as $year => $months)
		if (!empty($months))
		{
			$condition_text[] = 'YEAR(date) = {int:year_' . $year . '} AND MONTH(date) IN ({array_int:months_' . $year . '})';
			$condition_params['year_' . $year] = $year;
			$condition_params['months_' . $year] = $months;
		}

	// No daily stats to even look at?
	if (empty($condition_text))
		return;

	getDailyStats(implode(' OR ', $condition_text), $condition_params);
}

function getDailyStats($condition_string, $condition_parameters = array())
{
	global $context, $smcFunc;

	// Activity by day.
	$days_result = $smcFunc['db_query']('', '
		SELECT YEAR(date) AS stats_year, MONTH(date) AS stats_month, DAYOFMONTH(date) AS stats_day, topics, posts, registers, most_on, hits
		FROM {db_prefix}log_activity
		WHERE ' . $condition_string . '
		ORDER BY stats_day ASC',
		$condition_parameters
	);
	while ($row_days = $smcFunc['db_fetch_assoc']($days_result))
		$context['yearly'][$row_days['stats_year']]['months'][(int) $row_days['stats_month']]['days'][] = array(
			'day' => sprintf('%02d', $row_days['stats_day']),
			'month' => sprintf('%02d', $row_days['stats_month']),
			'year' => $row_days['stats_year'],
			'new_topics' => comma_format($row_days['topics']),
			'new_posts' => comma_format($row_days['posts']),
			'new_members' => comma_format($row_days['registers']),
			'most_members_online' => comma_format($row_days['most_on']),
			'hits' => comma_format($row_days['hits'])
		);
	$smcFunc['db_free_result']($days_result);
}

// This is the function which returns stats to simplemachines.org IF enabled!
// See http://www.simplemachines.org/about/stats.php for more info.
function SMStats()
{
	global $modSettings, $user_info, $forum_version, $sourcedir;

	// First, is it disabled?
	if (empty($modSettings['allow_sm_stats']))
		die();

	// Are we saying who we are, and are we right? (OR an admin)
	if (!$user_info['is_admin'] && (!isset($_GET['sid']) || $_GET['sid'] != $modSettings['allow_sm_stats']))
		die();

	// Verify the referer...
	if (!$user_info['is_admin'] && (!isset($_SERVER['HTTP_REFERER']) || md5($_SERVER['HTTP_REFERER']) != '746cb59a1a0d5cf4bd240e5a67c73085'))
		die();

	// Get some server versions.
	require_once($sourcedir . '/Subs-Admin.php');
	$checkFor = array(
		'php',
		'db_server',
	);
	$serverVersions = getServerVersions($checkFor);

	// Get the actual stats.
	$stats_to_send = array(
		'UID' => $modSettings['allow_sm_stats'],
		'time_added' => time(),
		'members' => $modSettings['totalMembers'],
		'messages' => $modSettings['totalMessages'],
		'topics' => $modSettings['totalTopics'],
		'boards' => 0,
		'php_version' => $serverVersions['php']['version'],
		'database_type' => strtolower($serverVersions['db_server']['title']),
		'database_version' => $serverVersions['db_server']['version'],
		'smf_version' => $forum_version,
		'smfd_version' => $modSettings['smfVersion'],
	);

	// Encode all the data, for security.
	foreach ($stats_to_send as $k => $v)
		$stats_to_send[$k] = urlencode($k) . '=' . urlencode($v);

	// Turn this into the query string!
	$stats_to_send = implode('&', $stats_to_send);

	// If we're an admin, just plonk them out.
	if ($user_info['is_admin'])
		echo $stats_to_send;
	else
	{
		// Connect to the collection script.
		$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
		if ($fp)
		{
			$length = strlen($stats_to_send);

			$out = 'POST /smf/stats/collect_stats.php HTTP/1.1' . "\r\n";
			$out .= 'Host: www.simplemachines.org' . "\r\n";
			$out .= 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
			$out .= 'Content-Length: ' . $length . "\r\n\r\n";
			$out .= $stats_to_send . "\r\n";
			$out .= 'Connection: Close' . "\r\n\r\n";
			fwrite($fp, $out);
			fclose($fp);
		}
	}

	// Die.
	die('OK');
}

?>


text:
<?php

namespace Honors\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Form\Annotation\AnnotationBuilder;
use Zend\View\Model\ViewModel;
use Honors\Model\AppForm;
use Honors\Entity\Honors;
use Doctrine\ORM\Tools\Pagination; // goes at top of file

class HonorsController extends AbstractActionController {

    /**
     * Entity manager instance
     *
     * @var Doctrine\ORM\EntityManager
     */
    protected $em;

    protected $form;

    public function setEntityManager(EntityManager $em)
    {
    	$this->em = $em;
    }

    public function getEntityManager()
    {

    	if (null === $this->em) {
    		$this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
    	}

    	return $this->em;
    }

    public function listAction()
    {
    	$em = $this->getEntityManager();
    	$request = $this->getRequest();
    	$data = $em->getRepository('Honors\Entity\Honors')->findAll();
    	$srchStr = '';
    	if ($request->isPost()) {
    		if(strlen($request->getPost()->searchStr) >= 1){
    			$srchStr = $request->getPost()->searchStr;
    			$query = $em->createQuery("SELECT u FROM Honors\Entity\Honors u WHERE upper(u.firstname) LIKE :firstname OR upper(u.lastname) LIKE :lastname ");
    			$query->setParameters(array(
    					'firstname' => strtoupper($srchStr)."%",
    					'lastname' => strtoupper($srchStr)."%",
    			));
    			$data = $query->getResult();
    		}
    		else{
    			$data = $em->getRepository('Honors\Entity\Honors')->findAll();
    		}
    	}
    	return new ViewModel(array(
    			'data' => $data,
    			'srchStr' => $srchStr,
    	));
    }

    public function listsortAction()
    {
    	$em = $this->getEntityManager();
    	$request = $this->getRequest();
		$c = count($paginator);
    	$data = $em->getRepository('Honors\Entity\Honors')->findAll();
        return new ViewModel(array(
            'data' => $paginator,
  		));
    }

    public function indexAction() {
        $form = $this->getForm();
        return array(
            'title' => 'Honors College',
            'form' => $form,
            'messages' => $this->flashmessenger()->getMessages()
        );
    }

    public function getForm() {
        if (!$this->form) {
            $honors_application = new AppForm();
            $builder = new AnnotationBuilder();
            $this->form = $builder->createForm($honors_application);
        }
        return $this->form;
    }

}


text:
<?php

namespace Oro\Bundle\EmailBundle\Entity;

use BeSimple\SoapBundle\ServiceDefinition\Annotation as Soap;

use Doctrine\ORM\Mapping as ORM;

use JMS\Serializer\Annotation as JMS;

use Oro\Bundle\EntityConfigBundle\Metadata\Annotation\Config;
use Oro\Bundle\EntityConfigBundle\Metadata\Annotation\ConfigField;
use Oro\Bundle\OrganizationBundle\Entity\OrganizationInterface;
use Oro\Bundle\UserBundle\Entity\User;

/**
 * EmailUser
 *
 * @ORM\Table(
 *      name="oro_email_user"
 * )
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="Oro\Bundle\EmailBundle\Entity\Repository\EmailUserRepository")
 *
 * @Config(
 *      defaultValues={
 *          "security"={
 *              "type"="ACL",
 *              "permissions"="VIEW;CREATE;EDIT",
 *              "group_name"=""
 *          },
 *          "ownership"={
 *              "owner_type"="USER",
 *              "owner_field_name"="owner",
 *              "owner_column_name"="user_owner_id",
 *              "organization_field_name"="organization",
 *              "organization_column_name"="organization_id"
 *          }
 *      }
 * )
 */
class EmailUser
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Soap\ComplexType("int")
     * @JMS\Type("integer")
     */
    protected $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime")
     * @JMS\Type("dateTime")
     * @ConfigField(
     *      defaultValues={
     *          "entity"={
     *              "label"="oro.ui.created_at"
     *          }
     *      }
     * )
     */
    protected $createdAt;

    /**
     * @var OrganizationInterface
     *
     * @ORM\ManyToOne(targetEntity="Oro\Bundle\OrganizationBundle\Entity\Organization")
     * @ORM\JoinColumn(name="organization_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $organization;

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="Oro\Bundle\UserBundle\Entity\User")
     * @ORM\JoinColumn(name="user_owner_id", referencedColumnName="id", onDelete="SET NULL")
     * @JMS\Exclude
     */
    protected $owner;

    /**
     * @var Mailbox
     *
     * @ORM\ManyToOne(targetEntity="Oro\Bundle\EmailBundle\Entity\Mailbox", inversedBy="emailUsers")
     * @ORM\JoinColumn(name="mailbox_owner_id", referencedColumnName="id", onDelete="SET NULL")
     * @JMS\Exclude
     */
    protected $mailboxOwner;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="received", type="datetime")
     * @Soap\ComplexType("dateTime")
     * @JMS\Type("dateTime")
     */
    protected $receivedAt;

    /**
     * @var bool
     *
     * @ORM\Column(name="is_seen", type="boolean", options={"default"=true})
     * @Soap\ComplexType("boolean")
     * @JMS\Type("boolean")
     */
    protected $seen = false;

    /**
     * @var EmailFolder $folder
     *
     * @ORM\ManyToOne(targetEntity="EmailFolder", inversedBy="emailUsers", cascade={"persist"})
     * @ORM\JoinColumn(name="folder_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
     * @JMS\Exclude
     */
    protected $folder;

    /**
     * @var Email $email
     *
     * @ORM\ManyToOne(targetEntity="Email", inversedBy="emailUsers", cascade={"persist"})
     * @ORM\JoinColumn(name="email_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
     * @JMS\Exclude
     */
    protected $email;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get entity created date/time
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Get organization
     *
     * @return OrganizationInterface
     */
    public function getOrganization()
    {
        return $this->organization;
    }

    /**
     * Set organization
     *
     * @param OrganizationInterface $organization
     * @return $this
     */
    public function setOrganization(OrganizationInterface $organization)
    {
        $this->organization = $organization;

        return $this;
    }

    /**
     * Get owning user
     *
     * @return User
     */
    public function getOwner()
    {
        return $this->owner;
    }

    /**
     * Set owning user
     *
     * @param User $owningUser
     *
     * @return $this
     */
    public function setOwner($owningUser)
    {
        $this->owner = $owningUser;

        return $this;
    }

    /**
     * Get date/time when email received
     *
     * @return \DateTime
     */
    public function getReceivedAt()
    {
        return $this->receivedAt;
    }

    /**
     * Set date/time when email received
     *
     * @param \DateTime $receivedAt
     *
     * @return $this
     */
    public function setReceivedAt($receivedAt)
    {
        $this->receivedAt = $receivedAt;

        return $this;
    }

    /**
     * Get if email is seen
     *
     * @return bool
     */
    public function isSeen()
    {
        return $this->seen;
    }

    /**
     * Set email is read flag
     *
     * @param boolean $seen
     *
     * @return $this
     */
    public function setSeen($seen)
    {
        $this->seen = (bool)$seen;

        return $this;
    }

    /**
     * Get email folder
     *
     * @return EmailFolder
     */
    public function getFolder()
    {
        return $this->folder;
    }

    /**
     * @param EmailFolder $folder
     *
     * @return $this
     */
    public function setFolder($folder)
    {
        $this->folder = $folder;

        return $this;
    }

    /**
     * Get email
     *
     * @return Email
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set email
     *
     * @param Email $email
     *
     * @return $this
     */
    public function setEmail(Email $email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Pre persist event listener
     *
     * @ORM\PrePersist
     */
    public function beforeSave()
    {
        $this->createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
    }

    /**
     * @return Mailbox|null
     */
    public function getMailboxOwner()
    {
        return $this->mailboxOwner;
    }

    /**
     * @param Mailbox|null $mailboxOwner
     *
     * @return $this
     */
    public function setMailboxOwner(Mailbox $mailboxOwner = null)
    {
        $this->mailboxOwner = $mailboxOwner;

        return $this;
    }
}