text:
package com.bigcommerce.catalog.models;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import org.joda.time.DateTime;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

	@XmlElement(name = "first_name")
	private String firstName;

	@XmlElement(name = "last_name")
	private String lastName;

	@XmlElement(name = "email")
	private String email;

	@XmlElement(name = "id")
	private int id;

	@XmlElement(name = "company")
	private String company;

	@XmlElement(name = "phone")
	private String phone;

	@XmlJavaTypeAdapter(DateTimeAdapter.class)
	@XmlElement(name = "date_created")
	private DateTime dateCreated;

	@XmlJavaTypeAdapter(DateTimeAdapter.class)
	@XmlElement(name = "date_modified")
	private DateTime dateModified;

	@XmlElement(name = "store_credit")
	private BigDecimal storeCredit;

	@XmlElement(name = "registration_ip_address")
	private String registrationIpAddress;

	@XmlElement(name = "customer_group_id")
	private int customerGroupId;

	@XmlElement(name = "notes")
	private String notes;

	@XmlElement(name = "tax_exempt_category")
	private String taxExemptCategory;

	@XmlElement(name = "reset_pass_on_login")
	private String resetPassOnLogin;

	@XmlElement(name = "accepts_marketing")
	private String acceptsMarketing;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getId() {
		return id;
	}

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

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public DateTime getDateCreated() {
		return dateCreated;
	}

	public void setDateCreated(DateTime dateCreated) {
		this.dateCreated = dateCreated;
	}

	public DateTime getDateModified() {
		return dateModified;
	}

	public void setDateModified(DateTime dateModified) {
		this.dateModified = dateModified;
	}

	public BigDecimal getStoreCredit() {
		return storeCredit;
	}

	public void setStoreCredit(BigDecimal storeCredit) {
		this.storeCredit = storeCredit;
	}

	public int getCustomerGroupId() {
		return customerGroupId;
	}

	public void setCustomerGroupId(int customerGroupId) {
		this.customerGroupId = customerGroupId;
	}

	public String getNotes() {
		return notes;
	}

	public void setNotes(String notes) {
		this.notes = notes;
	}

	public String getTaxExemptCategory() {
		return taxExemptCategory;
	}

	public void setTaxExemptCategory(String taxExemptCategory) {
		this.taxExemptCategory = taxExemptCategory;
	}

	public String getResetPassOnLogin() {
		return resetPassOnLogin;
	}

	public void setResetPassOnLogin(String resetPassOnLogin) {
		this.resetPassOnLogin = resetPassOnLogin;
	}

	public String getAcceptsMarketing() {
		return acceptsMarketing;
	}

	public void setAcceptsMarketing(String acceptsMarketing) {
		this.acceptsMarketing = acceptsMarketing;
	}

	public String getRegistrationIpAddress() {
		return registrationIpAddress;
	}

	public void setRegistrationIpAddress(String registrationIpAddress) {
		this.registrationIpAddress = registrationIpAddress;
	}
}


text:
using System;

namespace System.Collections
{
	public interface IStructuralComparable {
		int CompareTo (object other, IComparer comparer);
	}
}

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.offbytwo.jenkins.integration;

import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.model.TopLevelItem;
import org.dom4j.DocumentException;
import org.junit.Test;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

import javax.servlet.ServletException;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.util.Collection;

import static org.junit.Assert.assertNotNull;

public class JenkinsClientViewIntegrationTest extends BaseIntegrationTest {

    public static final String TEST_VIEW = "testView";

    @Test
    public void shouldObtainView() throws URISyntaxException, IOException, JAXBException, DocumentException {
        // given
        jenkinsRule.getInstance().addView(new TestView());

        // when
        com.offbytwo.jenkins.model.View testView = jenkinsServer.getView(TEST_VIEW);

        // then
        assertNotNull(testView);
    }

    private static class TestView extends hudson.model.View implements Serializable {
        public TestView() {
            super(TEST_VIEW);
        }

        @Override
        public Collection<TopLevelItem> getItems() {
            return null;
        }

        @Override
        public boolean contains(TopLevelItem topLevelItem) {
            return false;
        }

        @Override
        protected void submit(StaplerRequest staplerRequest) throws IOException, ServletException, Descriptor.FormException {

        }

        @Override
        public Item doCreateItem(StaplerRequest staplerRequest, StaplerResponse staplerResponse) throws IOException, ServletException {
            return null;
        }
    }
}


text:
package ec2

import "github.com/timob/javabind"

type ServicesEc2ModelDescribeInstanceAttributeResultInterface interface {
	JavaLangObjectInterface

	// public void setInstanceAttribute(com.amazonaws.services.ec2.model.InstanceAttribute)
	SetInstanceAttribute(a ServicesEc2ModelInstanceAttributeInterface)

	// public com.amazonaws.services.ec2.model.InstanceAttribute getInstanceAttribute()
	GetInstanceAttribute() *ServicesEc2ModelInstanceAttribute

	// public com.amazonaws.services.ec2.model.DescribeInstanceAttributeResult withInstanceAttribute(com.amazonaws.services.ec2.model.InstanceAttribute)
	WithInstanceAttribute(a ServicesEc2ModelInstanceAttributeInterface) *ServicesEc2ModelDescribeInstanceAttributeResult

	// public com.amazonaws.services.ec2.model.DescribeInstanceAttributeResult clone()
	Clone() *ServicesEc2ModelDescribeInstanceAttributeResult
}

type ServicesEc2ModelDescribeInstanceAttributeResult struct {
	JavaLangObject
}

// public com.amazonaws.services.ec2.model.DescribeInstanceAttributeResult()
func NewServicesEc2ModelDescribeInstanceAttributeResult() (*ServicesEc2ModelDescribeInstanceAttributeResult) {

	obj, err := javabind.GetEnv().NewObject("com/amazonaws/services/ec2/model/DescribeInstanceAttributeResult")
	if err != nil {
		panic(err)
	}
	x := &ServicesEc2ModelDescribeInstanceAttributeResult{}
	x.Callable = &javabind.Callable{obj}
	return x
}

// public void setInstanceAttribute(com.amazonaws.services.ec2.model.InstanceAttribute)
func (jbobject *ServicesEc2ModelDescribeInstanceAttributeResult) SetInstanceAttribute(a ServicesEc2ModelInstanceAttributeInterface)  {
	conv_a := javabind.NewGoToJavaCallable()
	if err := conv_a.Convert(a); err != nil {
		panic(err)
	}
	_, err := jbobject.CallMethod(javabind.GetEnv(), "setInstanceAttribute", javabind.Void, conv_a.Value().Cast("com/amazonaws/services/ec2/model/InstanceAttribute"))
	if err != nil {
		panic(err)
	}
	conv_a.CleanUp()

}

// public com.amazonaws.services.ec2.model.InstanceAttribute getInstanceAttribute()
func (jbobject *ServicesEc2ModelDescribeInstanceAttributeResult) GetInstanceAttribute() *ServicesEc2ModelInstanceAttribute {
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "getInstanceAttribute", "com/amazonaws/services/ec2/model/InstanceAttribute")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelInstanceAttribute{}
	unique_x.Callable = dst
	return unique_x
}

// public com.amazonaws.services.ec2.model.DescribeInstanceAttributeResult withInstanceAttribute(com.amazonaws.services.ec2.model.InstanceAttribute)
func (jbobject *ServicesEc2ModelDescribeInstanceAttributeResult) WithInstanceAttribute(a ServicesEc2ModelInstanceAttributeInterface) *ServicesEc2ModelDescribeInstanceAttributeResult {
	conv_a := javabind.NewGoToJavaCallable()
	if err := conv_a.Convert(a); err != nil {
		panic(err)
	}
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "withInstanceAttribute", "com/amazonaws/services/ec2/model/DescribeInstanceAttributeResult", conv_a.Value().Cast("com/amazonaws/services/ec2/model/InstanceAttribute"))
	if err != nil {
		panic(err)
	}
	conv_a.CleanUp()
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelDescribeInstanceAttributeResult{}
	unique_x.Callable = dst
	return unique_x
}

// public java.lang.String toString()
func (jbobject *ServicesEc2ModelDescribeInstanceAttributeResult) ToString() string {
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "toString", "java/lang/String")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoString()
	dst := new(string)
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	return *dst
}

// public boolean equals(java.lang.Object)
func (jbobject *ServicesEc2ModelDescribeInstanceAttributeResult) Equals(a interface{}) bool {
	conv_a := javabind.NewGoToJavaCallable()
	if err := conv_a.Convert(a); err != nil {
		panic(err)
	}
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "equals", javabind.Boolean, conv_a.Value().Cast("java/lang/Object"))
	if err != nil {
		panic(err)
	}
	conv_a.CleanUp()
	return jret.(bool)
}

// public int hashCode()
func (jbobject *ServicesEc2ModelDescribeInstanceAttributeResult) HashCode() int {
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "hashCode", javabind.Int)
	if err != nil {
		panic(err)
	}
	return jret.(int)
}

// public com.amazonaws.services.ec2.model.DescribeInstanceAttributeResult clone()
func (jbobject *ServicesEc2ModelDescribeInstanceAttributeResult) Clone() *ServicesEc2ModelDescribeInstanceAttributeResult {
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "clone", "com/amazonaws/services/ec2/model/DescribeInstanceAttributeResult")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelDescribeInstanceAttributeResult{}
	unique_x.Callable = dst
	return unique_x
}

// public java.lang.Object clone() throws java.lang.CloneNotSupportedException
func (jbobject *ServicesEc2ModelDescribeInstanceAttributeResult) Clone2() (*JavaLangObject, error) {
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "clone", "java/lang/Object")
	if err != nil {
		var zero *JavaLangObject
		return zero, err
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &JavaLangObject{}
	unique_x.Callable = dst
	return unique_x, nil
}


text:
@interface SOChartHeader : UIView

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *subtitleLabel;
@property (nonatomic, strong) UIColor *separatorColor;

@end


text:
module PageObjects
  class Base
    attr_reader :context, :form
    delegate :fill_in_form, to: :form

    def initialize(context)
      @context = context
    end

    def find(selector, options = {})
      context.find(selector, options)
    rescue
      MissingElement.new(:element, selector, options)
    end

    def find_link(label)
      context.find_link(label)
    rescue
      MissingElement.new(:link, label)
    end

    def respond_to_missing?(name, _)
      context.respond_to?(name)
    end

    def method_missing(name, *args, &block)
      context.public_send(name, *args, &block)
    end

    def debug
      save_and_open_page
    end

    def get_edit_page(model)
      "PageObjects::Edit#{model.class}".constantize.new(context, model)
    end
  end
end


text:
layout: article
title: Euro 2017 Trip
permalink: /EuroTrip2017/
---
Budapest, Krakow, Prague and Dresden
---------------------------------------------------------

I will be traveling for 10 days in Euorpe with my daughter on an EFTours Education adventure.

Day One
-------
* Arrive jet-lagged in Berlin (Country #1)
* Walk around Berlin to stay awake!

Day Two
-------
* Arrive in Berlin
* Walking tour of the city - see Unter den Linden, Richstag

Day Three
---------
* Checkpoint Charley, Brandenburg Gate, Alexander Platz
* Visit the Berlin Wall
* Half-day excursion to Potsdam

Day Four
--------
* Travel to Dresden
* Walking tour of Dresden - Semper Opera House, Zwinger Palace, Statue of Martin Luther
* Travel to Prague (Country #2)
* Visit the Jewish Quarter in Prague

Day Five
--------
* Walking tour of Prague - St. Vitus Cathedral, Golden Lane, Charles Bridge
* Visit the astrological clock

Day Six
-------
* Travel to Auschwitz
* Visit Auschwitz and Birkenau
* Travel to Krakow (Country #3)

Day Seven
---------
* Guided tour of Krakow - Wawel Hill, Glowny Square, St. Mary's Church

Day Eight
---------
* Drive to Budapest via Tatra Mountains
* Lunch in Slovakia (Country #4)
* Walking tour of Budapest - Fisherman's Bastion, Parliament (Country #5)

Day Nine
---------
* Guided tour of Budapest - Matthias Church
* Visit Budapest Baths

Day Ten
--------
* Collapse on plane ride home!


text:
package hr.element.beepo
package Model

import hr.ngs.patterns._

case class RequestStatus(
    queuedAt: org.joda.time.DateTime = org.joda.time.DateTime.now
  , sentAt: Option[org.joda.time.DateTime] = None
  , status: String = ""
  , serverResponse: Option[String] = None
  )


text:
package gov.nih.nci.evs.api.service;

import java.io.IOException;
import java.util.List;

import org.springframework.data.elasticsearch.core.ElasticsearchOperations;

import gov.nih.nci.evs.api.model.Metric;

/**
 * The service for performing index related operations on Elasticsearch.
 *
 * @author Arun
 */
public interface ElasticOperationsService {

  /** The type in ES for metrics *. */
  public static final String METRIC_TYPE = "metric";

  /** The type in ES for concepts *. */
  public static final String CONCEPT_TYPE = "concept";

  /** The type in ES for cached objects *. */
  public static final String OBJECT_TYPE = "evs_object";

  /** The index in ES for index metadata *. */
  public static final String METADATA_INDEX = "evs_metadata";

  /** The type in ES for index metadata **/
  public static final String METADATA_TYPE = "evs_metadata";

  /**
   * create index using the given index name.
   *
   * @param indexName the index name
   * @param force whether index is to be deleted, if already present
   * @return if the index was created
   * @throws IOException the io exception
   */
  boolean createIndex(String indexName, boolean force) throws IOException;

  /**
   * load objects.
   *
   * @param objects the list of objects
   * @param index the index name
   * @param type the type name
   * @param clazz the clazz
   * @throws IOException the io exception
   */
  @SuppressWarnings("rawtypes")
  void bulkIndex(List objects, String index, String type, Class clazz) throws IOException;

  /**
   * Bulk index and wait.
   *
   * @param objects the objects
   * @param index the index
   * @param type the type
   * @param clazz the clazz
   * @throws IOException Signals that an I/O exception has occurred.
   */
  @SuppressWarnings("rawtypes")
  void bulkIndexAndWait(List objects, String index, String type, Class clazz) throws IOException;

  /**
   * load object.
   *
   * @param object the object
   * @param index the index name
   * @param type the type name
   * @param clazz the clazz
   * @throws IOException the io exception
   */
  void index(Object object, String index, String type, @SuppressWarnings("rawtypes")
  Class clazz) throws IOException;

  /**
   * load metrics.
   *
   * @param metric the metric to load
   * @param index the index name
   * @throws IOException the io exception
   */
  void loadMetric(Metric metric, String index) throws IOException;

  /**
   * get the instance of {@code ElasticsearchOperations}.
   *
   * @return the instance of {@code ElasticsearchOperations}
   */
  ElasticsearchOperations getElasticsearchOperations();

  /**
   * delete the index.
   *
   * @param index the index name
   * @return {@literal true} if the index was deleted
   */
  boolean deleteIndex(String index);

}


text:
using namespace mfem;

#include "unit_tests.hpp"

// You typically want to start by testing things one object at a time.
TEST_CASE("IntegrationRules of Different Types", "[IntegrationRules]")
{
   // This code is automatically re-executed for all of the sections.
   IntegrationRules gauss_intrules(0, Quadrature1D::GaussLegendre);
   IntegrationRules lobatto_intrules(0, Quadrature1D::GaussLobatto);
   IntegrationRules oes_intrules(0, Quadrature1D::OpenUniform);
   IntegrationRules ces_intrules(0, Quadrature1D::ClosedUniform);

   // The tests will be reported in these sections.
   // Each REQUIRE counts as an assertion.
   // true = pass, false = fail
   SECTION("Expected Number of points for GaussLegendre exactness")
   {
      // polynomial degree we want to exactly integrate
      int exact = 4;
      // exact for 2*np - 1
      int pts_needed = 3;

      const IntegrationRule *ir;
      ir = &gauss_intrules.Get(Geometry::SEGMENT, exact);
      REQUIRE(ir->Size() == pts_needed);
   }
   SECTION("Expected Number of points for GaussLobatto exactness")
   {
      // polynomial degree we want to exactly integrate
      int exact = 4;
      // exact for 2*np - 3
      int pts_needed = 4;

      const IntegrationRule *ir;
      ir = &lobatto_intrules.Get(Geometry::SEGMENT, exact);
      REQUIRE(ir->Size() == pts_needed);
   }
}


text:
#include <fcntl.h>

#include "util.hpp"
#include "symmetric-encryptor.hpp"

SymmetricEncryptor::SymmetricEncryptor(std::string keyfile){
	if(keyfile.empty()){
		this->random_pool.GenerateBlock(this->key, CryptoPP::AES::MAX_KEYLENGTH);
		this->random_pool.GenerateBlock(this->iv, CryptoPP::AES::BLOCKSIZE);
		this->random_pool.GenerateBlock(this->hmac_key, CryptoPP::AES::MAX_KEYLENGTH);

		this->hmac = CryptoPP::HMAC<CryptoPP::SHA256>(hmac_key, CryptoPP::AES::MAX_KEYLENGTH);

		/*
		std::string keystr;
		CryptoPP::HexEncoder hex(new CryptoPP::StringSink(keystr));
		hex.Put(this->key, CryptoPP::AES::MAX_KEYLENGTH);
		hex.Put(this->iv, CryptoPP::AES::BLOCKSIZE);
		hex.MessageEnd();
		*/
		PRINT("SymmetricEncryptor generated a key.")
		return;
	}

	const size_t hex_key_length = (CryptoPP::AES::MAX_KEYLENGTH + CryptoPP::AES::BLOCKSIZE) * 2; // 96
	byte hex_key[hex_key_length + 1];
	int fd;
	if((fd = open(keyfile.c_str(), O_RDONLY)) < 0){
		throw std::runtime_error("SymmetricEncryptor open keyfile");
	}
	if(read(fd, hex_key, hex_key_length) < static_cast<ssize_t>(hex_key_length)){
		throw std::runtime_error("SymmetricEncryptor read keyfile");
	}
	if(close(fd) < 0){
		throw std::runtime_error("SymmetricEncryptor close keyfile");
	}
	hex_key[hex_key_length] = 0;

	PRINT("PROVIDED KEY: " << hex_key)

	CryptoPP::ArraySource key_source(hex_key, CryptoPP::AES::MAX_KEYLENGTH * 2, true,
		new CryptoPP::HexDecoder(
		new CryptoPP::ArraySink(this->key, CryptoPP::AES::MAX_KEYLENGTH)));

	CryptoPP::ArraySource iv_source(hex_key + CryptoPP::AES::MAX_KEYLENGTH * 2, CryptoPP::AES::BLOCKSIZE * 2, true,
		new CryptoPP::HexDecoder(
		new CryptoPP::ArraySink(this->iv, CryptoPP::AES::BLOCKSIZE)));

	/*

	// TEST CODE

	std::string keystr;
	CryptoPP::HexEncoder hex(new CryptoPP::StringSink(keystr));
	hex.Put(this->key, CryptoPP::AES::MAX_KEYLENGTH);
	hex.Put(this->iv, CryptoPP::AES::BLOCKSIZE);
	hex.MessageEnd();

	PRINT("PROVIDED KEY: " << this->key << this->iv)
	PRINT("PROVIDED KEY: " << keystr)

	if(std::strncmp(reinterpret_cast<char*>(hex_key), keystr.c_str(), 96) != 0){
		throw std::runtime_error("Bad hex decoding.");
	}

	*/

	this->hmac = CryptoPP::HMAC<CryptoPP::SHA256>(this->key, CryptoPP::AES::MAX_KEYLENGTH);

	// Another random number tool.
	// srand(static_cast<unsigned int>(time(0)));
}

std::string SymmetricEncryptor::encrypt(std::string data){
	CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption encryptor(this->key, CryptoPP::AES::MAX_KEYLENGTH, this->iv);

	//byte salt[CryptoPP::AES::BLOCKSIZE];
	//this->random_pool.GenerateBlock(salt, CryptoPP::AES::BLOCKSIZE);
	//std::string salts(reinterpret_cast<const char*>(salt), CryptoPP::AES::BLOCKSIZE);

	std::string encrypted_data;
	//CryptoPP::StringSource pipeline1(salts + data, true,
	CryptoPP::StringSource pipeline1(data, true,
		new CryptoPP::StreamTransformationFilter(encryptor,
		new CryptoPP::StringSink(encrypted_data)));

	std::string hash;
	CryptoPP::StringSource pipeline2(encrypted_data, true,
		new CryptoPP::HashFilter(this->hmac,
		new CryptoPP::StringSink(hash)));

	// HMAC SHA256 produces 32 bytes.
	if(hash.length() != 32){
		PRINT("SHA256 in BASE64 length not 32 bytes?" << hash.length())
	}

	std::string base64_encrypted_data;
	CryptoPP::StringSource pipeline3(hash + encrypted_data, true,
		new CryptoPP::Base64Encoder(
		new CryptoPP::StringSink(base64_encrypted_data)));
	return base64_encrypted_data;
}

std::string SymmetricEncryptor::decrypt(std::string data){
	CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption decryptor(this->key, CryptoPP::AES::MAX_KEYLENGTH, this->iv);

	std::string encrypted_data;
	CryptoPP::StringSource pipeline1(data, true,
		new CryptoPP::Base64Decoder(
		new CryptoPP::StringSink(encrypted_data)));

	if(encrypted_data.length() % 32 != 0 || encrypted_data.length() == 0){
		//throw std::runtime_error("Bad encrpyted data size (" + std::to_string(encrypted_data.length()) + ").");
	}

	CryptoPP::StringSource pipeline2(encrypted_data, true,
		new CryptoPP::HashVerificationFilter(this->hmac, nullptr,
		CryptoPP::HashVerificationFilter::THROW_EXCEPTION |
		CryptoPP::HashVerificationFilter::HASH_AT_BEGIN));

	std::string decrypted_data;
	CryptoPP::StringSource pipeline3(encrypted_data.substr(32), true,
		new CryptoPP::StreamTransformationFilter(decryptor,
		new CryptoPP::StringSink(decrypted_data)));

	//decrypted_data.erase(0, CryptoPP::AES::BLOCKSIZE);
	return decrypted_data;
}

std::string SymmetricEncryptor::encrypt(std::string data, int transaction){
	DEBUG("STRANS:" << static_cast<unsigned char>(transaction % 255))
	DEBUG("STRANS:" << static_cast<char>(transaction % 255))
	DEBUG("STRANS:" << static_cast<int>(transaction % 255))
	DEBUG("STEXT:" << std::string(static_cast<char>(transaction % 255) + data))

	return this->encrypt(static_cast<char>(transaction % 255) + data);
	//return this->encrypt(data);
}

std::string SymmetricEncryptor::decrypt(std::string data, int transaction){
	std::string new_data = this->decrypt(data);

	DEBUG("RTRANS:" << static_cast<unsigned char>(new_data[0]))
	DEBUG("RTRANS:" << static_cast<char>(new_data[0]))
	DEBUG("RTRANS:" << static_cast<int>(new_data[0]))
	DEBUG("RTEXT:" << new_data)

	//TODO This transaction business was causing incorrect HMAC errors.

	if(static_cast<unsigned char>(new_data[0]) != static_cast<unsigned char>(transaction % 255)){
		PRINT("got " << static_cast<int>(new_data[0]) << " expected " << transaction)
		throw CryptoPP::Exception(CryptoPP::BERDecodeErr::INVALID_DATA_FORMAT, "Bad transaction number.");
	}
	new_data.erase(0, 1);
	return new_data;
}

bool SymmetricEncryptor::send(int fd, const char* data, size_t /* data_length */, int* transaction){
	ssize_t len;
	std::string send_data = this->encrypt(data, *transaction);

	char block_size[4] = {0, 0, 0, 0};
	*(reinterpret_cast<uint32_t*>(block_size)) = static_cast<uint32_t>(send_data.length());

	// Should be consistently 89 bytes.
	std::string send_data_size = this->encrypt(std::string(block_size, 4), *transaction);
	DEBUG("SIZE DATA LENGTH: " << send_data_size.length())

	*transaction += 1;

	DEBUG("SDATA|" << send_data_size << '|' << send_data_size.length())
	if((len = write(fd, send_data_size.c_str(), 89)) < 0){
		ERROR("encryptor write")
		return true;
	}else if(len != 89){
		ERROR("encryptor didn't write all")
		return true;
	}

	DEBUG("SDATA|" << send_data << '|' << send_data.length())
	if((len = write(fd, send_data.c_str(), send_data.length())) < 0){
		ERROR("encryptor write block")
		return true;
	}else if(len != static_cast<ssize_t>(send_data.length())){
		ERROR("encryptor didn't write all block")
		return true;
	}
	return false;
}

ssize_t SymmetricEncryptor::recv(int fd, char* data, size_t data_length,
std::function<ssize_t(int, const char*, ssize_t)> callback, int* transaction){
	ssize_t len;
	std::string recv_data;
	std::string recv_size_data;

	if((len = read(fd, data, 89)) < 0){
		if(errno != EWOULDBLOCK){
			perror("encryptor read");
			ERROR("encryptor read " << fd)
			return -1;
		}
		return 0;
	}else if(len == 0){
		ERROR("encryptor read zero")
		return -2;
	}else if(len != 89){
		ERROR("couldn't read block size?" << len)
		return -3;
	}
	data[len] = 0;
	try{
		recv_size_data = this->decrypt(std::string(data, static_cast<size_t>(len)), *transaction);
	}catch(const std::exception& e){
		ERROR(e.what() << "\nImplied hacker, closing!")
		return -4;
	}
	if(recv_size_data.length() != 4){
		PRINT("Did not receive 4 bytes or decrypted length...")
		return -5;
	}

	const unsigned long block_size = *(reinterpret_cast<const uint32_t*>(recv_size_data.c_str()));
	//block_size = Util::read_size_t(data);
	DEBUG("RDATA|" << data << '|' << block_size)
	if(block_size >= data_length){
		PRINT("Received too large of a packet!")
		return -1;
	}

	while(true){
		if((len = read(fd, data, block_size)) < 0){
			if(errno != EWOULDBLOCK){
				perror("encryptor read block");
				ERROR("encryptor read block " << fd << '|' << block_size)
				return -1;
			}
			continue;
		}else if(len == 0){
			PRINT("Server kicked you.")
			return -2;
		}else if(len != static_cast<ssize_t>(block_size)){
			ERROR("couldn't read block size block?" << len << '|' << block_size)
			return -3;
		}

		data[len] = 0;
		DEBUG("RDATA|" << data << '|')
		try{
			recv_data = this->decrypt(std::string(data, static_cast<size_t>(len)), *transaction);
			*transaction += 1;
		}catch(const std::exception& e){
			ERROR(e.what() << "\nImplied hacker, closing!")
			return -4;
		}
		return callback(fd, recv_data.c_str(), static_cast<ssize_t>(recv_data.length()));
	}
}


text:
package org.ensembl.healthcheck.testcase.compara;

import java.sql.Connection;

import java.util.HashSet;
import java.util.Set;

import org.ensembl.healthcheck.DatabaseRegistry;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.compara.AbstractComparaTestCase;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.CollectionUtils;

/**
 * An EnsEMBL Healthcheck test case that checks that the sizes of the
 * Compara tables are similar to the previous release
 */

public class CheckTableSizes extends AbstractComparaTestCase {

	public CheckTableSizes() {
		setDescription("Checks the size of the Compara tables");
		setTeamResponsible(Team.COMPARA);
	}

	/**
	 * Define what tables are to be checked.
	 */
	private Set<String> getTablesToCheck(final DatabaseRegistryEntry dbre) {

		// get the full list of tables
		Set<String> tables = CollectionUtils.createLinkedHashSet(DBUtils.getTableNames(dbre.getConnection()));

		// remove views since we don't care if they're empty
		Set<String> views = CollectionUtils.createLinkedHashSet(DBUtils.getViews(dbre.getConnection()).toArray(new String[]{}));
		tables.removeAll(views);

		// Tables we don't want to check
		tables.remove( "meta" );

		return tables;
	}

	/**
	 * Kick-off a comparison between the current database and all the
	 * previous ones
	 */
	public boolean run(final DatabaseRegistryEntry dbre) {

		DatabaseRegistryEntry lastReleaseDbre = getLastComparaReleaseDbre(dbre);

		if (lastReleaseDbre == null) {
			ReportManager.problem( this, dbre.getConnection(),
					"Cannot find the compara database in the secondary server. This check expects to find a previous version of the compara database for checking that all the *named* species_sets are still present in the current database.");
			return false;
		}

		boolean result = true;
		result &= compareTableSizes(dbre, lastReleaseDbre);
		return result;

	} // run

	/**
	 * Reports the tables that are now missing or empty, the new
	 * tables, and the tables with a signficantly different size.
	 * NB: Thresholds are -5% and +10%
	 */
	public boolean compareTableSizes(final DatabaseRegistryEntry primaryComparaDbre, final DatabaseRegistryEntry secondaryComparaDbre) {

		Set<String> tables1 = getTablesToCheck(primaryComparaDbre);
		Set<String> tables2 = getTablesToCheck(secondaryComparaDbre);

		Connection con1 = primaryComparaDbre.getConnection();
		Connection con2 = secondaryComparaDbre.getConnection();

		boolean result = true;

		for (String table : tables2) {
			int count2 = DBUtils.countRowsInTable(con2, table);
			if (tables1.contains(table)) {
				int count1 = DBUtils.countRowsInTable(con1, table);
				if (count1 == 0 && count2 > 0) {
					result = false;
					ReportManager.problem( this, con1, String.format("Table %s is now empty but had %,d rows in %s.", table, count2, DBUtils.getShortDatabaseName(con2)));
				} else if (count1 > 0 && count2 == 0) {
					result = false;
					ReportManager.problem( this, con1, String.format("Table %s has %,d rows but was empty in %s.", table, count1, DBUtils.getShortDatabaseName(con2)));
				} else if (count1 == count2 && count1 > 0) {
					result = false;
					ReportManager.problem( this, con1, String.format("Table %s has exactly the same number of rows (%,d) as in %s. Is it expected ?", table, count2, DBUtils.getShortDatabaseName(con2)));
				} else if (count1 < (int) (.95 * count2) || count2 > (int) (1.10 * count2)) {
					result = false;
					ReportManager.problem( this, con1, String.format("Table %s had %,d rows in %s, but now has %,d rows (%+,d = %+.2f %%)", table, count2, DBUtils.getShortDatabaseName(con2), count1, count1-count2, (100.*(count1-count2))/count2));
				}
			} else {
				result = false;
				ReportManager.problem( this, con1, String.format("Table %s was in %s (and had %,d rows) but is now missing.", table, DBUtils.getShortDatabaseName(con2), count2));
			}
		}

		for (String table : tables1) {
			if (! tables2.contains(table)) {
				result = false;
				int count1 = DBUtils.countRowsInTable(con1, table);
				if (count1 == 0) {
					ReportManager.problem( this, con1, String.format("Table %s is new (comparing to %s) but empty.", table, DBUtils.getShortDatabaseName(con2)));
				} else {
					ReportManager.problem( this, con1, String.format("Table %s is new (comparing to %s) and has %,d rows.", table, DBUtils.getShortDatabaseName(con2), count1));
				}
			}
		}

		return result;
	}

} // CheckEmptyTables


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/remoting/demuxer_stream_adapter.h"

#include <memory>
#include <vector>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/task_environment.h"
#include "components/cast_streaming/public/remoting_proto_utils.h"
#include "media/base/decoder_buffer.h"
#include "media/base/demuxer_stream.h"
#include "media/remoting/fake_media_resource.h"
#include "media/remoting/fake_remoter.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using openscreen::cast::RpcMessenger;
using testing::_;
using testing::Invoke;
using testing::Return;

namespace media {
namespace remoting {

class MockDemuxerStreamAdapter {
 public:
  MockDemuxerStreamAdapter(
      scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
      scoped_refptr<base::SingleThreadTaskRunner> media_task_runner,
      const std::string& name,
      DemuxerStream* demuxer_stream,
      mojo::PendingRemote<mojom::RemotingDataStreamSender> stream_sender_remote,
      mojo::ScopedDataPipeProducerHandle producer_handle) {
    rpc_messenger_ = std::make_unique<RpcMessenger>(
        [cb =
             base::BindRepeating(&MockDemuxerStreamAdapter::OnSendMessageToSink,
                                 weak_factory_.GetWeakPtr())](
            std::vector<uint8_t> message) { cb.Run(std::move(message)); });
    demuxer_stream_adapter_ = std::make_unique<DemuxerStreamAdapter>(
        std::move(main_task_runner), std::move(media_task_runner), name,
        demuxer_stream, rpc_messenger_->GetWeakPtr(),
        rpc_messenger_->GetUniqueHandle(), std::move(stream_sender_remote),
        std::move(producer_handle),
        base::BindOnce(&MockDemuxerStreamAdapter::OnError,
                       weak_factory_.GetWeakPtr()));

    // Faking initialization with random callback handle to start mojo watcher.
    demuxer_stream_adapter_->Initialize(3);
  }

  MockDemuxerStreamAdapter(const MockDemuxerStreamAdapter&) = delete;
  MockDemuxerStreamAdapter& operator=(const MockDemuxerStreamAdapter&) = delete;

  ~MockDemuxerStreamAdapter() {
    // Make sure unit tests that did not expect errors did not cause any errors.
    EXPECT_TRUE(errors_.empty());
  }

  int rpc_handle() const { return demuxer_stream_adapter_->rpc_handle(); }

  base::WeakPtr<MockDemuxerStreamAdapter> GetWeakPtr() {
    return weak_factory_.GetWeakPtr();
  }

  void DoDuplicateInitialize() { demuxer_stream_adapter_->Initialize(999); }

  void TakeErrors(std::vector<StopTrigger>* errors) {
    errors->swap(errors_);
    errors_.clear();
  }

  // Fake to signal that it's in reading state.
  void FakeReadUntil(int read_until_count, int callback_handle) {
    std::unique_ptr<openscreen::cast::RpcMessage> rpc(
        new openscreen::cast::RpcMessage());
    rpc->set_handle(rpc_handle());
    rpc->set_proc(openscreen::cast::RpcMessage::RPC_DS_READUNTIL);
    auto* read_message = rpc->mutable_demuxerstream_readuntil_rpc();
    read_message->set_callback_handle(
        callback_handle);  // Given an unique callback handle.
    read_message->set_count(read_until_count);  // Request 1 frame

    demuxer_stream_adapter_->OnReceivedRpc(std::move(rpc));
  }
  void OnNewBuffer(scoped_refptr<DecoderBuffer> frame) {
    demuxer_stream_adapter_->OnNewBuffer(DemuxerStream::kOk, frame);
  }

  void SignalFlush(bool flush) { demuxer_stream_adapter_->SignalFlush(flush); }

  openscreen::cast::RpcMessage* last_received_rpc() const {
    return last_received_rpc_.get();
  }

 private:
  void OnSendMessageToSink(std::vector<uint8_t> message) {
    last_received_rpc_ = std::make_unique<openscreen::cast::RpcMessage>();
    CHECK(last_received_rpc_->ParseFromArray(message.data(), message.size()));
  }

  void OnError(StopTrigger stop_trigger) { errors_.push_back(stop_trigger); }

  std::unique_ptr<RpcMessenger> rpc_messenger_;
  std::unique_ptr<DemuxerStreamAdapter> demuxer_stream_adapter_;
  std::unique_ptr<openscreen::cast::RpcMessage> last_received_rpc_;

  std::vector<StopTrigger> errors_;

  base::WeakPtrFactory<MockDemuxerStreamAdapter> weak_factory_{this};
};

class DemuxerStreamAdapterTest : public ::testing::Test {
 public:
  DemuxerStreamAdapterTest() = default;

  DemuxerStreamAdapterTest(const DemuxerStreamAdapterTest&) = delete;
  DemuxerStreamAdapterTest& operator=(const DemuxerStreamAdapterTest&) = delete;

  ~DemuxerStreamAdapterTest() override = default;

  void SetUpDataPipe() {
    constexpr size_t kDataPipeCapacity = 256;
    demuxer_stream_ = std::make_unique<FakeDemuxerStream>(true);  // audio.
    const MojoCreateDataPipeOptions data_pipe_options{
        sizeof(MojoCreateDataPipeOptions), MOJO_CREATE_DATA_PIPE_FLAG_NONE, 1,
        kDataPipeCapacity};
    mojo::PendingRemote<mojom::RemotingDataStreamSender> stream_sender;
    mojo::ScopedDataPipeProducerHandle producer_end;
    mojo::ScopedDataPipeConsumerHandle consumer_end;
    CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(&data_pipe_options,
                                                  producer_end, consumer_end));

    data_stream_sender_ = std::make_unique<FakeRemotingDataStreamSender>(
        stream_sender.InitWithNewPipeAndPassReceiver(),
        std::move(consumer_end));
    demuxer_stream_adapter_ = std::make_unique<MockDemuxerStreamAdapter>(
        task_environment_.GetMainThreadTaskRunner(),
        task_environment_.GetMainThreadTaskRunner(), "test",
        demuxer_stream_.get(), std::move(stream_sender),
        std::move(producer_end));
    // DemuxerStreamAdapter constructor posts task to main thread to
    // register MessageReceiverCallback. Therefore it should call
    // RunPendingTasks() to make sure task is executed.
    RunPendingTasks();
  }

  void TearDown() override { base::RunLoop().RunUntilIdle(); }

  void RunPendingTasks() { base::RunLoop().RunUntilIdle(); }

 protected:
  void SetUp() override { SetUpDataPipe(); }

  // TODO(miu): Add separate media thread, to test threading also.
  base::test::SingleThreadTaskEnvironment task_environment_;
  std::unique_ptr<FakeDemuxerStream> demuxer_stream_;
  std::unique_ptr<FakeRemotingDataStreamSender> data_stream_sender_;
  std::unique_ptr<MockDemuxerStreamAdapter> demuxer_stream_adapter_;
};

TEST_F(DemuxerStreamAdapterTest, SingleReadUntil) {
  // Read will be called once since it doesn't return frame buffer in the dummy
  // implementation.
  EXPECT_CALL(*demuxer_stream_, Read(_)).Times(1);

  demuxer_stream_adapter_->FakeReadUntil(3, 999);
  RunPendingTasks();
}

TEST_F(DemuxerStreamAdapterTest, MultiReadUntil) {
  // Read will be called once since it doesn't return frame buffer in the dummy
  // implementation, and 2nd one will not proceed when there is ongoing read.
  EXPECT_CALL(*demuxer_stream_, Read(_)).Times(1);

  demuxer_stream_adapter_->FakeReadUntil(1, 100);
  RunPendingTasks();

  demuxer_stream_adapter_->FakeReadUntil(2, 101);
  RunPendingTasks();
}

TEST_F(DemuxerStreamAdapterTest, WriteOneFrameSmallerThanCapacity) {
  EXPECT_CALL(*demuxer_stream_, Read(_)).Times(1);
  // Sends a frame with size 50 bytes, pts = 1 and key frame.
  demuxer_stream_->CreateFakeFrame(50, true, 1 /* pts */);
  demuxer_stream_adapter_->FakeReadUntil(1, 999);
  RunPendingTasks();

  // Checks if it's sent to consumer side and data is correct
  ASSERT_EQ(data_stream_sender_->send_frame_count(), 1U);
  ASSERT_TRUE(data_stream_sender_->ValidateFrameBuffer(0, 50, true, 1));
  openscreen::cast::RpcMessage* last_rpc =
      demuxer_stream_adapter_->last_received_rpc();
  ASSERT_TRUE(last_rpc);
  ASSERT_EQ(last_rpc->proc(),
            openscreen::cast::RpcMessage::RPC_DS_READUNTIL_CALLBACK);
  ASSERT_EQ(last_rpc->handle(), 999);
  data_stream_sender_->ResetHistory();
}

TEST_F(DemuxerStreamAdapterTest, WriteOneFrameLargerThanCapacity) {
  EXPECT_CALL(*demuxer_stream_, Read(_)).Times(1);
  // Sends a frame with size 800 bytes, pts = 1 and key frame.
  demuxer_stream_->CreateFakeFrame(800, true, 1 /* pts */);
  demuxer_stream_adapter_->FakeReadUntil(1, 999);
  RunPendingTasks();

  // Checks if it's sent to consumer side and data is correct
  ASSERT_EQ(data_stream_sender_->send_frame_count(), 1U);
  ASSERT_TRUE(data_stream_sender_->ValidateFrameBuffer(0, 800, true, 1));
  openscreen::cast::RpcMessage* last_rpc =
      demuxer_stream_adapter_->last_received_rpc();
  ASSERT_TRUE(last_rpc);
  ASSERT_EQ(last_rpc->proc(),
            openscreen::cast::RpcMessage::RPC_DS_READUNTIL_CALLBACK);
  ASSERT_EQ(last_rpc->handle(), 999);
  data_stream_sender_->ResetHistory();
}

TEST_F(DemuxerStreamAdapterTest, SendFrameAndSignalFlushMix) {
  EXPECT_CALL(*demuxer_stream_, Read(_)).Times(4);
  // Sends a frame with size 50 bytes, pts = 1 and key frame.
  demuxer_stream_->CreateFakeFrame(50, true, 1 /* pts */);
  // Issues ReadUntil request with frame count up to 1 (fetch #0).
  demuxer_stream_adapter_->FakeReadUntil(1, 100);
  RunPendingTasks();
  ASSERT_EQ(data_stream_sender_->send_frame_count(), 1U);
  ASSERT_TRUE(data_stream_sender_->ValidateFrameBuffer(0, 50, true, 1));
  openscreen::cast::RpcMessage* last_rpc =
      demuxer_stream_adapter_->last_received_rpc();
  ASSERT_TRUE(last_rpc);
  ASSERT_EQ(last_rpc->proc(),
            openscreen::cast::RpcMessage::RPC_DS_READUNTIL_CALLBACK);
  ASSERT_EQ(last_rpc->handle(), 100);
  data_stream_sender_->ResetHistory();

  // Sends two frames with size 100 + 150 bytes
  demuxer_stream_->CreateFakeFrame(100, false, 2 /* pts */);
  demuxer_stream_->CreateFakeFrame(150, false, 3 /* pts */);
  // Issues ReadUntil request with frame count up to 3 (fetch #1 and #2).
  demuxer_stream_adapter_->FakeReadUntil(3, 101);
  RunPendingTasks();
  ASSERT_EQ(data_stream_sender_->send_frame_count(), 2U);
  ASSERT_TRUE(data_stream_sender_->ValidateFrameBuffer(0, 100, false, 2));
  ASSERT_TRUE(data_stream_sender_->ValidateFrameBuffer(1, 150, false, 3));
  last_rpc = demuxer_stream_adapter_->last_received_rpc();
  ASSERT_TRUE(last_rpc);
  ASSERT_EQ(last_rpc->proc(),
            openscreen::cast::RpcMessage::RPC_DS_READUNTIL_CALLBACK);
  ASSERT_EQ(last_rpc->handle(), 101);
  data_stream_sender_->ResetHistory();

  // Signal flush
  ASSERT_EQ(data_stream_sender_->cancel_in_flight_count(), 0U);
  demuxer_stream_adapter_->SignalFlush(true);
  RunPendingTasks();
  ASSERT_EQ(data_stream_sender_->cancel_in_flight_count(), 1U);

  // ReadUntil request after flush signaling should be ignored.
  demuxer_stream_->CreateFakeFrame(100, false, 4 /* pts */);
  demuxer_stream_->CreateFakeFrame(100, false, 5 /* pts */);
  // Issues ReadUntil request with frame count up to 5 (fetch #3 and #4).
  demuxer_stream_adapter_->FakeReadUntil(5, 102);
  RunPendingTasks();
  ASSERT_EQ(data_stream_sender_->send_frame_count(), 0U);

  // Signal flush done
  demuxer_stream_adapter_->SignalFlush(false);
  RunPendingTasks();
  ASSERT_EQ(data_stream_sender_->cancel_in_flight_count(), 1U);
  data_stream_sender_->ResetHistory();

  // Re-issues ReadUntil request with frame count up to 4 (fetch #3).
  demuxer_stream_adapter_->FakeReadUntil(4, 103);
  RunPendingTasks();
  ASSERT_EQ(data_stream_sender_->send_frame_count(), 1U);
  ASSERT_TRUE(data_stream_sender_->ValidateFrameBuffer(0, 100, false, 4));
  last_rpc = demuxer_stream_adapter_->last_received_rpc();
  ASSERT_TRUE(last_rpc);
  ASSERT_EQ(last_rpc->proc(),
            openscreen::cast::RpcMessage::RPC_DS_READUNTIL_CALLBACK);
  ASSERT_EQ(last_rpc->handle(), 103);
  data_stream_sender_->ResetHistory();
}

TEST_F(DemuxerStreamAdapterTest, DuplicateInitializeCausesFatalError) {
  std::vector<StopTrigger> errors;
  demuxer_stream_adapter_->TakeErrors(&errors);
  ASSERT_TRUE(errors.empty());

  demuxer_stream_adapter_->DoDuplicateInitialize();
  demuxer_stream_adapter_->TakeErrors(&errors);
  ASSERT_EQ(1u, errors.size());
  EXPECT_EQ(PEERS_OUT_OF_SYNC, errors[0]);
}

TEST_F(DemuxerStreamAdapterTest, ClosingPipeCausesFatalError) {
  std::vector<StopTrigger> errors;
  demuxer_stream_adapter_->TakeErrors(&errors);
  ASSERT_TRUE(errors.empty());

  // Closes one end of mojo message and data pipes.
  data_stream_sender_.reset();
  RunPendingTasks();  // Allow notification from mojo to propagate.

  demuxer_stream_adapter_->TakeErrors(&errors);
  ASSERT_EQ(1u, errors.size());
  EXPECT_EQ(MOJO_PIPE_ERROR, errors[0]);
}

}  // namesapce remoting
}  // namespace media


text:
#import "FBLPromise.h"

NS_ASSUME_NONNULL_BEGIN

/**
 Waits for promise resolution. The current thread blocks until the promise is resolved.

 @param promise Promise to wait for.
 @param error Error the promise was rejected with, or `nil` if the promise was fulfilled.
 @return Value the promise was fulfilled with. If the promise was rejected, the return value
         is always `nil`, but the error out arg is not.
 */
FOUNDATION_EXTERN id __nullable FBLPromiseAwait(FBLPromise *promise,
                                                NSError **error) NS_REFINED_FOR_SWIFT;

NS_ASSUME_NONNULL_END


text:
var through = require('through2');
module.exports = function (file) {
    return through(function (chunk, enc, callback) {
        callback(new Error('rawr'));
    });
};


text:
"""Show the difference between two dicom files.
"""
# Copyright (c) 2008-2012 Darcy Mason
# This file is part of pydicom, relased under an MIT license.
#    See the file license.txt included with this distribution, also
#    available at http://pydicom.googlecode.com

from __future__ import print_function

usage = """
Usage:
python DicomDiff.py file1 file2

Results printed in python difflib form - indicated by start of each line:
' ' blank means lines the same
'-' means in file1 but "removed" in file2
'+' means not in file1, but "added" in file2
('?' lines from difflib removed - no use here)
"""

import sys
import dicom
import difflib

# only used as a script
if len(sys.argv) != 3:
    print(usage)
    sys.exit()

datasets = dicom.read_file(sys.argv[1]), \
           dicom.read_file(sys.argv[2])

# diflib compare functions require a list of lines, each terminated with newline character
# massage the string representation of each dicom dataset into this form:
rep = []
for dataset in datasets:
    lines = str(dataset).split("\n")
    lines = [line + "\n" for line in lines]  # add the newline to end
    rep.append(lines)

diff = difflib.Differ()
for line in diff.compare(rep[0], rep[1]):
    if line[0] != "?":
        print(line)


text:
![Revit API](https://img.shields.io/badge/Revit%20API-2021-blue.svg)
![Platform](https://img.shields.io/badge/platform-Windows-lightgray.svg)
![.NET](https://img.shields.io/badge/.NET-4.8-blue.svg)
[![License](http://img.shields.io/:license-mit-blue.svg)](http://opensource.org/licenses/MIT)

Revit MEP Sample Application for Revit MEP HVAC and electrical

Demonstrate use of the Revit API for MEP specific tasks.

Keywords: Revit API C# .NET add-in.

## HVAC

Use of the generic Revit API for HVAC specific tasks, using only standard Revit element properties and parameters:

- Determine air terminals for each space.
- Assign flow to the air terminals depending on the space's calculated supply air flow.
- Change size of diffuser based on flow.
- Populate the value of the 'CFM per SF' variable on all spaces.
- Determine unhosted elements.
- Reset demo.

## Electrical

Use of the MEP specific API to traverse an electrical system and display its hierarchy in a tree view.

## Documentation

- [The ADN MEP Sample AdnRme for Revit MEP 2013](http://thebuildingcoder.typepad.com/blog/2012/05/the-adn-mep-sample-adnrme-for-revit-mep-2013.html)
- [The ADN Sample AdnRme for Revit MEP 2014](http://thebuildingcoder.typepad.com/blog/2013/06/the-adn-sample-adnrme-for-revit-mep-2014.html)
- [AdnRme Migrated to Revit MEP 2015 on GitHub](http://thebuildingcoder.typepad.com/blog/2014/06/adnrme-migrated-to-revit-mep-2015-on-github.html)

## Author

Jeremy Tammik,
[The Building Coder](http://thebuildingcoder.typepad.com),
[ADN](http://www.autodesk.com/adn)
[Open](http://www.autodesk.com/adnopen),
[Autodesk Inc.](http://www.autodesk.com)

## License

This sample is licensed under the terms of the [MIT License](http://opensource.org/licenses/MIT).
Please see the [LICENSE](LICENSE) file for full details.


text:
require 'album_photos'

class AlbumCreator
  attr_reader :title, :slug, :logger

  def initialize(title)
    @title = title
    @slug = AlbumSlug.new(title)
    @logger = Rails.logger
  end

  def insert_all_photos
    added_images_count = 0
    logger.info("attempting to import #{valid_keys.count} images")
    valid_keys.each do |filename|
      added_images_count += 1 if insert_photo(filename)
    end
    logger.info("imported #{added_images_count} images")
  end

  def insert_photo(filename)
    Photo.create!(path: slug.to_s, filename: filename, album: album)
  rescue ActiveRecord::RecordNotUnique
  end

  def album
    @album ||= Album.where(title: title).first_or_create!
  end

  def photos
    @photos ||= Rails.application.config.offline_dev ?
      LocalAlbumPhotos.new(slug) : AlbumPhotos.new(slug)
  end

  def valid_keys
    @valid_keys ||= photos.original.select { |f| f =~ /\.jpg|png\Z/i }
  end
end


text:
typedef NS_ENUM(NSUInteger, XMPPOrgSubcribeState) {
    XMPPOrgSubcribeStateNotHandle = 0,
    XMPPOrgSubcribeStateAccept,
    XMPPOrgSubcribeStateRefuse
};

@interface XMPPOrgSubcribeCoreDataStorageObject : NSManagedObject

@property (nonatomic, retain) NSString * formOrgId;
@property (nonatomic, retain) NSString * fromOrgName;
@property (nonatomic, retain) NSString * toOrgId;
@property (nonatomic, retain) NSDate * time;
@property (nonatomic, retain) NSString * message;
@property (nonatomic, retain) NSNumber * state;
@property (nonatomic, retain) NSString * streamBareJidStr;

+ (id)objectInManagedObjectContext:(NSManagedObjectContext *)moc
                     withFormOrgId:(NSString *)formOrgId
                           toOrgId:(NSString *)toOrgId
                  streamBareJidStr:(NSString *)streamBareJidStr;

+ (id)insertInManagedObjectContext:(NSManagedObjectContext *)moc
                           withDic:(NSDictionary *)dic
                  streamBareJidStr:(NSString *)streamBareJidStr;

+ (BOOL)updateInManagedObjectContext:(NSManagedObjectContext *)moc
                             withDic:(NSDictionary *)dic
                    streamBareJidStr:(NSString *)streamBareJidStr;

+ (BOOL)deleteInManagedObjectContext:(NSManagedObjectContext *)moc
                       withFormOrgId:(NSString *)formOrgId
                             toOrgId:(NSString *)toOrgId
                    streamBareJidStr:(NSString *)streamBareJidStr;

+ (BOOL)deleteInManagedObjectContext:(NSManagedObjectContext *)moc
                             withDic:(NSDictionary *)dic
                    streamBareJidStr:(NSString *)streamBareJidStr;

- (void)updateWithDic:(NSDictionary *)dic;

@end


text:
class Review < ActiveRecord::Base
  belongs_to :group_location
  belongs_to :user

  def get_location_reviews(location)

  end

end


text:
using System.Diagnostics;

namespace TSGenHD.TypeScript
{
    [DebuggerDisplay("Value {Name} = {Value}")]
    public class EnumValue
    {
        public readonly string Name;
        public long Value { get; set; }

        public EnumValue(string name, long value)
        {
            Name = name;
            Value = value;
        }
    }
}


text:
require "test_helper"

# Single controller test.
class NameEditorShowAllTabsTest < ActionController::TestCase
  tests NamesController
  setup do
    @name = names(:a_species)
  end

  test "should show all tabs if editor requests details tab" do
    @request.headers["Accept"] = "application/javascript"
    get(:show,
        { id: @name.id, tab: "tab_edit" },
        username: "fred",
        user_full_name: "Fred Jones",
        groups: ["edit"])
    assert_response :success
    assert_select "a#name-details-tab", true, "Should show 'Detail' tab."
    assert_select "a#name-edit-tab", true, "Should show 'Edit' tab."
    assert_select "a#name-instances-tab", true, "Should show 'New instance' tab."
    assert_select "a#name-copy-tab", true, "Should show 'Copy' tab."
    assert_select "a#name-delete-tab", true, "Should show 'Delete' tab."
    assert_select "a#name-more-tab", true, "Should show 'More' tab."
  end
end


text:
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "CommonCommonPch.h"
#include "Common/Tick.h"

namespace Js {
    uint64      Tick::s_luFreq;
    uint64      Tick::s_luBegin;

#if DBG
    uint64      Tick::s_DEBUG_luStart   = 0;
    uint64      Tick::s_DEBUG_luSkip    = 0;
#endif

    ///----------------------------------------------------------------------------
    ///----------------------------------------------------------------------------
    ///
    /// struct Tick
    ///
    ///----------------------------------------------------------------------------
    ///----------------------------------------------------------------------------

    ///----------------------------------------------------------------------------
    ///
    /// Tick::Tick
    ///
    /// Tick() initializes a new Tick instance to an "empty" time.  This instance
    /// must be assigned to another Tick instance or Now() to have value.
    ///
    ///----------------------------------------------------------------------------

    Tick::Tick()
    {
        m_luTick = 0;
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::Tick
    ///
    /// Tick() initializes a new Tick instance to a specific time, in native
    /// time units.
    ///
    ///----------------------------------------------------------------------------

    Tick::Tick(
        uint64 luTick)                      // Tick, in internal units
    {
        m_luTick = luTick;
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::FromMicroseconds
    ///
    /// FromMicroseconds() returns a Tick instance from a given time in
    /// microseconds.
    ///
    ///----------------------------------------------------------------------------

    Tick
    Tick::FromMicroseconds(
        uint64 luTime)                          // Time, in microseconds
    {
        //
        // Ensure we can convert losslessly.
        //

#if DBG
        const uint64 luMaxTick = _UI64_MAX / s_luFreq;
        AssertMsg(luTime <= luMaxTick, "Ensure time can be converted losslessly");
#endif // DBG

        //
        // Create the Tick
        //

        uint64 luTick = luTime * s_luFreq / ((uint64) 1000000);
        return Tick(luTick);
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::FromQPC
    ///
    /// FromQPC() returns a Tick instance from a given QPC time.
    ///
    ///----------------------------------------------------------------------------

    Tick
    Tick::FromQPC(
        uint64 luTime)                      // Time, in QPC units
    {
        return Tick(luTime - s_luBegin);
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::ToQPC
    ///
    /// ToQPC() returns the QPC time for this time instance
    ///
    ///----------------------------------------------------------------------------

    uint64
    Tick::ToQPC()
    {
        return (m_luTick + s_luBegin);
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator +
    ///
    /// operator +()
    ///
    ///----------------------------------------------------------------------------

    Tick
    Tick::operator +(
        TickDelta tdChange                  // RHS TickDelta
        ) const
    {
        return Tick(m_luTick + tdChange.m_lnDelta);
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator -
    ///
    /// operator -()
    ///
    ///----------------------------------------------------------------------------

    Tick
    Tick::operator -(
        TickDelta tdChange                  // RHS TickDelta
        ) const
    {
        return Tick(m_luTick - tdChange.m_lnDelta);
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator -
    ///
    /// operator -()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    Tick::operator -(
        Tick timeOther                      // RHS Tick
        ) const
    {
        return TickDelta(m_luTick - timeOther.m_luTick);
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator ==
    ///
    /// operator ==()
    ///
    ///----------------------------------------------------------------------------

    bool
    Tick::operator ==(
        Tick timeOther                      // RHS Tick
        ) const
    {
        return m_luTick == timeOther.m_luTick;
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator !=
    ///
    /// operator !=()
    ///
    ///----------------------------------------------------------------------------

    bool
    Tick::operator !=(
        Tick timeOther                      // RHS Tick
        ) const
    {
        return m_luTick != timeOther.m_luTick;
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator <
    ///
    /// operator <()
    ///
    ///----------------------------------------------------------------------------

    bool
    Tick::operator <(
        Tick timeOther                      // RHS Tick
        ) const
    {
        return m_luTick < timeOther.m_luTick;
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator <=
    ///
    /// operator <=()
    ///
    ///----------------------------------------------------------------------------

    bool
    Tick::operator <=(
        Tick timeOther                      // RHS Tick
        ) const
    {
        return m_luTick <= timeOther.m_luTick;
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator >
    ///
    /// operator >()
    ///
    ///----------------------------------------------------------------------------

    bool
    Tick::operator >(
        Tick timeOther                      // RHS Tick
        ) const
    {
        return m_luTick > timeOther.m_luTick;
    }

    ///----------------------------------------------------------------------------
    ///
    /// Tick::operator >=
    ///
    /// operator >=()
    ///
    ///----------------------------------------------------------------------------

    bool
    Tick::operator >=(
        Tick timeOther                      // RHS Tick
        ) const
    {
        return m_luTick >= timeOther.m_luTick;
    }

    ///----------------------------------------------------------------------------
    ///----------------------------------------------------------------------------
    ///
    /// struct TickDelta
    ///
    ///----------------------------------------------------------------------------
    ///----------------------------------------------------------------------------

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::TickDelta
    ///
    /// TickDelta() initializes a new TickDelta instance to "zero" delta.
    ///
    ///----------------------------------------------------------------------------

    TickDelta::TickDelta()
    {
        m_lnDelta = 0;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::TickDelta
    ///
    /// TickDelta() initializes a new TickDelta instance to a specific time delta,
    /// in native time units.
    ///
    ///----------------------------------------------------------------------------

    TickDelta::TickDelta(
        int64 lnDelta)
    {
        m_lnDelta = lnDelta;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::ToMicroseconds
    ///
    /// ToMicroseconds() returns the time delta, in microseconds. The time is
    /// rounded to the nearest available whole units.
    ///
    ///----------------------------------------------------------------------------

    int64
    TickDelta::ToMicroseconds() const
    {
        if (*this == Infinite())
        {
            return _I64_MAX;
        }

        //
        // Ensure we can convert losslessly.
        //
#if DBG
        const int64 lnMinTimeDelta = _I64_MIN / ((int64) 1000000);
        const int64 lnMaxTimeDelta = _I64_MAX / ((int64) 1000000);
        AssertMsg((m_lnDelta <= lnMaxTimeDelta) && (m_lnDelta >= lnMinTimeDelta),
                "Ensure delta can be converted to microseconds losslessly");
#endif

        //
        // Compute the microseconds.
        //

        const int64 lnFreq = (int64) Tick::s_luFreq;
        int64 lnTickDelta = (m_lnDelta * ((int64) 1000000)) / lnFreq;
        return lnTickDelta;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::FromMicroseconds
    ///
    /// FromMicroseconds() returns a TickDelta instance from a given delta in
    /// microseconds.
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::FromMicroseconds(
        int64 lnTimeDelta)                  // Time delta, in 1/1000^2 sec
    {
        AssertMsg(lnTimeDelta != _I64_MAX, "Use Infinite() to create an infinite TickDelta");

        //
        // Ensure that we can convert losslessly.
        //

        int64 lnFreq = (int64) Tick::s_luFreq;

#if DBG
        const int64 lnMinTimeDelta = _I64_MIN / lnFreq;
        const int64 lnMaxTimeDelta = _I64_MAX / lnFreq;
        AssertMsg((lnTimeDelta <= lnMaxTimeDelta) && (lnTimeDelta >= lnMinTimeDelta),
                "Ensure delta can be converted to native format losslessly");
#endif // DBG

        //
        // Create the TickDelta
        //

        int64 lnTickDelta = (lnTimeDelta * lnFreq) / ((int64) 1000000);
        TickDelta td(lnTickDelta);

        AssertMsg(td != Infinite(), "Can not create infinite TickDelta");
        return td;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::FromMicroseconds
    ///
    /// FromMicroseconds() returns a TickDelta instance from a given delta in
    /// microseconds.
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::FromMicroseconds(
        int nTimeDelta)                     // Tick delta, in 1/1000^2 sec
    {
        AssertMsg(nTimeDelta != _I32_MAX, "Use Infinite() to create an infinite TickDelta");

        return FromMicroseconds((int64) nTimeDelta);
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::FromMilliseconds
    ///
    /// FromMilliseconds() returns a TickDelta instance from a given delta in
    /// milliseconds.
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::FromMilliseconds(
        int nTimeDelta)                     // Tick delta, in 1/1000^1 sec
    {
        AssertMsg(nTimeDelta != _I32_MAX, "Use Infinite() to create an infinite TickDelta");

        return FromMicroseconds(((int64) nTimeDelta) * ((int64) 1000));
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::Infinite
    ///
    /// Infinite() returns a time-delta infinitely far away.
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::Infinite()
    {
        return TickDelta(_I64_MAX);
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::IsForward
    ///
    /// IsForward() returns whether adding this TickDelta to a given Tick will
    /// not move the time backwards.
    ///
    ///----------------------------------------------------------------------------

    bool
    TickDelta::IsForward() const
    {
        return m_lnDelta >= 0;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::IsBackward
    ///
    /// IsBackward() returns whether adding this TickDelta to a given Tick will
    /// not move the time forwards.
    ///
    ///----------------------------------------------------------------------------

    bool
    TickDelta::IsBackward() const
    {
        return m_lnDelta <= 0;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::Abs
    ///
    /// Abs() returns the absolute value of the TickDelta.
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::Abs(TickDelta tdOther)
    {
        return TickDelta(tdOther.m_lnDelta < 0 ? -tdOther.m_lnDelta : tdOther.m_lnDelta);
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator %
    ///
    /// operator %()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator %(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        return TickDelta(m_lnDelta % tdOther.m_lnDelta);
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator \
    ///
    /// operator \() - Divides one TickDelta by another, in TickDelta units
    ///
    ///----------------------------------------------------------------------------

    int64
    TickDelta::operator /(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        return m_lnDelta / tdOther.m_lnDelta;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator +
    ///
    /// operator +()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator +(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
                "Can not combine infinite TickDeltas");

        return TickDelta(m_lnDelta + tdOther.m_lnDelta);
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator -
    ///
    /// operator -()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator -(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
                "Can not combine infinite TickDeltas");

        return TickDelta(m_lnDelta - tdOther.m_lnDelta);
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator *
    ///
    /// operator *()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator *(
        int nScale                          // RHS scale
        ) const
    {
        AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");

        return TickDelta(m_lnDelta * nScale);
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator *
    ///
    /// operator *()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator *(
        float flScale                       // RHS scale
        ) const
    {
        AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");

        return TickDelta((int64) (((double) m_lnDelta) * ((double) flScale)));
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator /
    ///
    /// operator /()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator /(
        int nScale                          // RHS scale
        ) const
    {
        AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
        AssertMsg(nScale != 0, "Can not scale by 0");

        return TickDelta(m_lnDelta / nScale);
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator /
    ///
    /// operator /()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator /(
        float flScale                       // RHS scale
        ) const
    {
        AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas");
        AssertMsg(flScale != 0, "Can not scale by 0");

        return TickDelta((int64) (((double) m_lnDelta) / ((double) flScale)));
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator +=
    ///
    /// operator +=()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator +=(
        TickDelta tdOther)                  // RHS TickDelta
    {
        AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
                "Can not combine infinite TickDeltas");

        m_lnDelta = m_lnDelta + tdOther.m_lnDelta;

        return *this;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator -=
    ///
    /// operator -=()
    ///
    ///----------------------------------------------------------------------------

    TickDelta
    TickDelta::operator -=(
        TickDelta tdOther)                  // RHS TickDelta
    {
        AssertMsg((*this != Infinite()) && (tdOther != Infinite()),
                "Can not combine infinite TickDeltas");

        m_lnDelta = m_lnDelta - tdOther.m_lnDelta;

        return *this;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator ==
    ///
    /// operator ==()
    ///
    ///----------------------------------------------------------------------------

    bool
    TickDelta::operator ==(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        return m_lnDelta == tdOther.m_lnDelta;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator !=
    ///
    /// operator !=()
    ///
    ///----------------------------------------------------------------------------

    bool
    TickDelta::operator !=(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        return m_lnDelta != tdOther.m_lnDelta;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator <
    ///
    /// operator <()
    ///
    ///----------------------------------------------------------------------------

    bool
    TickDelta::operator <(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        return m_lnDelta < tdOther.m_lnDelta;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator <=
    ///
    /// operator <=()
    ///
    ///----------------------------------------------------------------------------

    bool
    TickDelta::operator <=(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        return m_lnDelta <= tdOther.m_lnDelta;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator >
    ///
    /// operator >()
    ///
    ///----------------------------------------------------------------------------

    bool
    TickDelta::operator >(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        return m_lnDelta > tdOther.m_lnDelta;
    }

    ///----------------------------------------------------------------------------
    ///
    /// TickDelta::operator >=
    ///
    /// operator >=()
    ///
    ///----------------------------------------------------------------------------

    bool
    TickDelta::operator >=(
        TickDelta tdOther                   // RHS TickDelta
        ) const
    {
        return m_lnDelta >= tdOther.m_lnDelta;
    }
    void Tick::InitType()
    {
        /* CheckWin32( */ QueryPerformanceFrequency((LARGE_INTEGER *) &s_luFreq);
        /* CheckWin32( */ QueryPerformanceCounter((LARGE_INTEGER *) &s_luBegin);

#if DBG
        s_luBegin += s_DEBUG_luStart;
#endif

        //
        // Ensure that we have a sufficient amount of time so that we can handle useful time operations.
        //

        uint64 nSec = _UI64_MAX / s_luFreq;
        if (nSec < 5 * 60)
        {
#if FIXTHIS
            PromptInvalid("QueryPerformanceFrequency() will not provide at least 5 minutes");
            return Results::GenericFailure;
#endif
        }
    }

    Tick Tick::Now()
    {
        // Determine our current time
        uint64 luCurrent = s_luBegin;
        /* Verify( */ QueryPerformanceCounter((LARGE_INTEGER *) &luCurrent);

#if DBG
        luCurrent += s_DEBUG_luStart + s_DEBUG_luSkip;
#endif

        // Create a Tick instance, using our delta since we started tracking time.
        uint64 luDelta = luCurrent - s_luBegin;
        return Tick(luDelta);
    }

    uint64 Tick::ToMicroseconds() const
    {
        //
        // Convert time in microseconds (1 / 1000^2).  Because of the finite precision and wrap-around,
        // this math depends on where the Tick is.
        //

        const uint64 luOneSecUs = (uint64) 1000000;
        const uint64 luSafeTick = _UI64_MAX / luOneSecUs;
        if (m_luTick < luSafeTick)
        {
            //
            // Small enough to convert directly into microseconds.
            //

            uint64 luTick = (m_luTick * luOneSecUs) / s_luFreq;
            return luTick;
        }
        else
        {
            //
            // Number is too large, so we need to do this is stages.
            // 1. Compute the number of seconds
            // 2. Convert the remainder
            // 3. Add the two parts together
            //

            uint64 luSec    = m_luTick / s_luFreq;
            uint64 luRemain = m_luTick - luSec * s_luFreq;
            uint64 luTick   = (luRemain * luOneSecUs) / s_luFreq;
            luTick         += luSec * luOneSecUs;

            return luTick;
        }
    }

    int TickDelta::ToMilliseconds() const
    {
        if (*this == Infinite())
        {
            return _I32_MAX;
        }

        int64 nTickUs = ToMicroseconds();

        int64 lnRound = 500;
        if (nTickUs < 0)
        {
            lnRound = -500;
        }

        int64 lnDelta = (nTickUs + lnRound) / ((int64) 1000);
        AssertMsg((lnDelta <= INT_MAX) && (lnDelta >= INT_MIN), "Ensure no overflow");

        return (int) lnDelta;
    }

}