text:
package uk.co.real_logic.sbe.examples;

import extension.Car;
import uk.co.real_logic.sbe.codec.java.DirectBuffer;

import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ExampleUsingGeneratedStubExtension
{
    private static final String ENCODING_FILENAME = "sbe.encoding.filename";
    private static final byte[] VEHICLE_CODE;
    private static final byte[] MANUFACTURER_CODE;
    private static final byte[] MAKE;
    private static final byte[] MODEL;

    private static final baseline.MessageHeader MESSAGE_HEADER = new baseline.MessageHeader();
    private static final baseline.Car CAR_0 = new baseline.Car();
    private static final extension.Car CAR_1 = new extension.Car();

    static
    {
        try
        {
            VEHICLE_CODE = "abcdef".getBytes(baseline.Car.vehicleCodeCharacterEncoding());
            MANUFACTURER_CODE = "123".getBytes(baseline.Engine.manufacturerCodeCharacterEncoding());
            MAKE = "Honda".getBytes(baseline.Car.makeCharacterEncoding());
            MODEL = "Civic VTi".getBytes(baseline.Car.modelCharacterEncoding());
        }
        catch (final UnsupportedEncodingException ex)
        {
            throw new RuntimeException(ex);
        }
    }

    public static void main(final String[] args)throws Exception
    {
        System.out.println("\n*** Extension Stub Example ***");

        final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);
        final DirectBuffer directBuffer = new DirectBuffer(byteBuffer);
        final short messageTemplateVersion = 0;
        int bufferOffset = 0;
        int encodingLength = 0;

        // Setup for encoding a message

        MESSAGE_HEADER.wrap(directBuffer, bufferOffset, messageTemplateVersion)
                      .blockLength(CAR_0.blockLength())
                      .templateId(CAR_0.templateId())
                      .version(CAR_0.templateVersion());

        bufferOffset += MESSAGE_HEADER.size();
        encodingLength += MESSAGE_HEADER.size();
        encodingLength += encode(CAR_0, directBuffer, bufferOffset);

        // Optionally write the encoded buffer to a file for decoding by the On-The-Fly decoder

        final String encodingFilename = System.getProperty(ENCODING_FILENAME);
        if (encodingFilename != null)
        {
            try (final FileChannel channel = new FileOutputStream(encodingFilename).getChannel())
            {
                byteBuffer.limit(encodingLength);
                channel.write(byteBuffer);
            }
        }

        // Decode the encoded message

        bufferOffset = 0;
        MESSAGE_HEADER.wrap(directBuffer, bufferOffset, messageTemplateVersion);

        // Lookup the applicable flyweight to decode this type of message based on templateId and version.
        final int templateId = MESSAGE_HEADER.templateId();
        if (templateId != extension.Car.TEMPLATE_ID)
        {
            throw new IllegalStateException("Template ids do not match");
        }

        final short actingVersion = MESSAGE_HEADER.version();
        final int actingBlockLength = MESSAGE_HEADER.blockLength();

        bufferOffset += MESSAGE_HEADER.size();
        decode(CAR_1, directBuffer, bufferOffset, actingBlockLength, actingVersion);
    }

    public static int encode(final baseline.Car car,
                             final DirectBuffer directBuffer,
                             final int bufferOffset)
    {
        final int srcOffset = 0;

        car.wrapForEncode(directBuffer, bufferOffset)
           .serialNumber(1234)
           .modelYear(2013)
           .available(baseline.BooleanType.TRUE)
           .code(baseline.Model.A)
           .putVehicleCode(VEHICLE_CODE, srcOffset);

        for (int i = 0, size = baseline.Car.someNumbersLength(); i < size; i++)
        {
            car.someNumbers(i, i);
        }

        car.extras().clear()
                    .cruiseControl(true)
                    .sportsPack(true)
                    .sunRoof(false);

        car.engine().capacity(2000)
                    .numCylinders((short)4)
                    .putManufacturerCode(MANUFACTURER_CODE, srcOffset);

        car.fuelFiguresCount(3).next().speed(30).mpg(35.9f)
                               .next().speed(55).mpg(49.0f)
                               .next().speed(75).mpg(40.0f);

        final baseline.Car.PerformanceFigures perfFigures = car.performanceFiguresCount(2);
        perfFigures.next().octaneRating((short)95)
                          .accelerationCount(3).next().mph(30).seconds(4.0f)
                                               .next().mph(60).seconds(7.5f)
                                               .next().mph(100).seconds(12.2f);
        perfFigures.next().octaneRating((short)99)
                          .accelerationCount(3).next().mph(30).seconds(3.8f)
                                               .next().mph(60).seconds(7.1f)
                                               .next().mph(100).seconds(11.8f);

        car.putMake(MAKE, srcOffset, MAKE.length);
        car.putModel(MODEL, srcOffset, MODEL.length);

        return car.size();
    }

    public static void decode(final extension.Car car,
                              final DirectBuffer directBuffer,
                              final int bufferOffset,
                              final int actingBlockLength,
                              final int actingVersion)
        throws Exception
    {
        final byte[] buffer = new byte[128];
        final StringBuilder sb = new StringBuilder();

        car.wrapForDecode(directBuffer, bufferOffset, actingBlockLength, actingVersion);

        sb.append("\ncar.templateId=").append(car.templateId());
        sb.append("\ncar.templateVersion=").append(car.templateVersion());
        sb.append("\ncar.serialNumber=").append(car.serialNumber());
        sb.append("\ncar.modelYear=").append(car.modelYear());
        sb.append("\ncar.available=").append(car.available());
        sb.append("\ncar.code=").append(car.code());

        sb.append("\ncar.someNumbers=");
        for (int i = 0, size = extension.Car.someNumbersLength(); i < size; i++)
        {
            sb.append(car.someNumbers(i)).append(", ");
        }

        sb.append("\ncar.vehicleCode=");
        for (int i = 0, size = extension.Car.vehicleCodeLength(); i < size; i++)
        {
            sb.append((char)car.vehicleCode(i));
        }

        final extension.OptionalExtras extras = car.extras();
        sb.append("\ncar.extras.cruiseControl=").append(extras.cruiseControl());
        sb.append("\ncar.extras.sportsPack=").append(extras.sportsPack());
        sb.append("\ncar.extras.sunRoof=").append(extras.sunRoof());

        final extension.Engine engine = car.engine();
        sb.append("\ncar.engine.capacity=").append(engine.capacity());
        sb.append("\ncar.engine.numCylinders=").append(engine.numCylinders());
        sb.append("\ncar.engine.maxRpm=").append(engine.maxRpm());
        sb.append("\ncar.engine.manufacturerCode=");
        for (int i = 0, size = extension.Engine.manufacturerCodeLength(); i < size; i++)
        {
            sb.append((char)engine.manufacturerCode(i));
        }

        sb.append("\ncar.engine.fuel=").append(new String(buffer, 0, engine.getFuel(buffer, 0, buffer.length), "ASCII"));

        final String cupHolderCount = car.cupHolderCount() == Car.cupHolderCountNullValue() ? "null" : car.cupHolderCount() + "";
        sb.append("\ncar.cutHolderCount=").append(cupHolderCount);

        for (final extension.Car.FuelFigures fuelFigures : car.fuelFigures())
        {
            sb.append("\ncar.fuelFigures.speed=").append(fuelFigures.speed());
            sb.append("\ncar.fuelFigures.mpg=").append(fuelFigures.mpg());
        }

        for (final extension.Car.PerformanceFigures performanceFigures : car.performanceFigures())
        {
            sb.append("\ncar.performanceFigures.octaneRating=").append(performanceFigures.octaneRating());

            for (final extension.Car.PerformanceFigures.Acceleration acceleration : performanceFigures.acceleration())
            {
                sb.append("\ncar.performanceFigures.acceleration.mph=").append(acceleration.mph());
                sb.append("\ncar.performanceFigures.acceleration.seconds=").append(acceleration.seconds());
            }
        }

        sb.append("\ncar.make.semanticType=").append(extension.Car.makeMetaAttribute(extension.MetaAttribute.SEMANTIC_TYPE));
        sb.append("\ncar.make=").append(new String(buffer, 0, car.getMake(buffer, 0, buffer.length), extension.Car.makeCharacterEncoding()));

        sb.append("\ncar.model=").append(new String(buffer, 0, car.getModel(buffer, 0, buffer.length), extension.Car.modelCharacterEncoding()));

        sb.append("\ncar.size=").append(car.size());

        System.out.println(sb);
    }
}


text:
php-htmldiff-advanced
=======
*An add-on for the php-htmldiff library for comparing two HTML files/snippets and highlighting the differences using simple HTML.*

This HTML Diff implementation leverages https://github.com/caxy/php-htmldiff - a PHP port of the ruby implementation found at https://github.com/myobie/htmldiff.

It extends php-htmldiff in a backward compatible way that
- allows to run multiple diffs using the same instance of the class, which eases the integration as a service of dependency injection containers
- provide an interface, which eases the integration as a service of dependency injection containers
- discovers removals or additions of complete HTML sections

License
-------
php-htmldiff-advanced is available under [GNU General Public License, version 2] (http://www.gnu.org/licenses/gpl-2.0.html).

redpajama_set_name: RedPajamaGithub


text:
package org.knowm.xchange.independentreserve.service;

import java.util.Collection;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.independentreserve.IndependentReserveExchange;
import org.knowm.xchange.utils.AuthUtils;

public class IndependentReserveTradeServiceIntegration {

  static Exchange exchange;
  static IndependentReserveTradeService tradeService;

  @BeforeClass
  public static void beforeClass() {
    exchange = ExchangeFactory.INSTANCE.createExchange(IndependentReserveExchange.class.getName());
    AuthUtils.setApiAndSecretKey(exchange.getExchangeSpecification());
    exchange = ExchangeFactory.INSTANCE.createExchange(exchange.getExchangeSpecification());
    tradeService = (IndependentReserveTradeService) exchange.getTradeService();
  }

  @Test
  public void testGetOpenOrders() throws Exception {

    Assume.assumeNotNull(exchange.getExchangeSpecification().getApiKey());

    OpenOrders openOrders = tradeService.getOpenOrders();
  }

  @Test
  public void testGetTradeHistory() throws Exception {
    Assume.assumeNotNull(exchange.getExchangeSpecification().getApiKey());

    UserTrades userTrades = tradeService.getTradeHistory(tradeService.createTradeHistoryParams());
    if (userTrades.getUserTrades().size() > 0) {
      UserTrade userTrade = userTrades.getUserTrades().get(0);
      String orderId = userTrade.getOrderId();
      Collection<Order> orders = tradeService.getOrder(orderId);
    }
  }
}


text:
<?php

namespace Dflydev\DotAccessConfiguration;

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    protected function getTestData()
    {
        return array(
            'a' => array(
                'b' => array(
                    'c' => 'ABC',
                ),
            ),
            'abc' => '%a.b.c%',
            'abcd' => '%a.b.c.d%',
            'some' => array(
                'object' => new ConfigurationTestObject('some.object'),
                'other' => array(
                    'object' => new ConfigurationTestObject('some.other.object'),
                ),
            ),
            'object' => new ConfigurationTestObject('object'),
            'an_array' => array('hello'),
        );
    }

    protected function runBasicTests($configuration)
    {
        $this->assertEquals('ABC', $configuration->get('a.b.c'), 'Direct access by dot notation');
        $this->assertEquals('ABC', $configuration->get('abc'), 'Resolved access');
        $this->assertEquals('%a.b.c.d%', $configuration->get('abcd'), 'Unresolved access');
        $this->assertEquals('object', $configuration->get('object')->key);
        $this->assertEquals('some.object', $configuration->get('some.object')->key);
        $this->assertEquals('some.other.object', $configuration->get('some.other.object')->key);
        $this->assertEquals(array('hello'), $configuration->get('an_array'));
        $this->assertEquals('This is ABC', $configuration->resolve('This is %a.b.c%'));
        $this->assertNull($configuration->resolve());
    }

    public function testGet()
    {
        $configuration = new Configuration($this->getTestData());

        $this->runBasicTests($configuration);
    }

    public function testAppend()
    {
        $configuration = new Configuration($this->getTestData());

        $configuration->append('a.b.c', 'abc');
        $configuration->append('an_array', 'world');

        $this->assertEquals(array('ABC', 'abc'), $configuration->get('a.b.c'));
        $this->assertEquals(array('hello', 'world'), $configuration->get('an_array'));
    }

    public function testExportRaw()
    {
        $configuration = new Configuration($this->getTestData());

        // Start with "known" expected value.
        $expected = $this->getTestData();

        $this->assertEquals($expected, $configuration->exportRaw());

        // Simulate change on an object to ensure that objects
        // are being handled correctly.
        $expected['object']->key = 'object (modified)';

        // Make the same change in the object that the
        // configuration is managing.
        $configuration->get('object')->key = 'object (modified)';

        $this->assertEquals($expected, $configuration->exportRaw());
    }

    public function testExport()
    {
        $configuration = new Configuration($this->getTestData());

        // Start with "known" expected value.
        $expected = $this->getTestData();

        // We have one replacement that is expected to happen.
        // It should be represented in the export as the
        // resolved value!
        $expected['abc'] = 'ABC';

        $this->assertEquals($expected, $configuration->export());

        // Simulate change on an object to ensure that objects
        // are being handled correctly.
        $expected['object']->key = 'object (modified)';

        // Make the same change in the object that the
        // configuration is managing.
        $configuration->get('object')->key = 'object (modified)';

        $this->assertEquals($expected, $configuration->export());

        // Test to make sure that set will result in setting
        // a new value and also that export will show this new
        // value. (tests "export is dirty" functionality)
        $configuration->set('abc', 'ABCD');
        $expected['abc'] = 'ABCD';
        $this->assertEquals($expected, $configuration->export());
    }

    public function testExportData()
    {
        $configuration = new Configuration($this->getTestData());

        $data = $configuration->exportData();

        // The exportData call should return data filled with
        // resolved data.
        $this->assertEquals('ABC', $data->get('abc'));
    }

    public function testImportRaw()
    {
        $configuration = new Configuration();

        $configuration->importRaw($this->getTestData());

        $this->runBasicTests($configuration);
    }

    public function testImport()
    {
        $configuration = new Configuration();

        $configuration->import(new Configuration($this->getTestData()));

        $this->runBasicTests($configuration);
    }

    public function testSetPlaceholderResolver()
    {
        $placeholderResolver = $this->getMock('Dflydev\PlaceholderResolver\PlaceholderResolverInterface');

        $placeholderResolver
            ->expects($this->once())
            ->method('resolvePlaceholder')
            ->with($this->equalTo('foo'))
            ->will($this->returnValue('bar'))
        ;

        $configuration = new Configuration;

        $configuration->setPlaceholderResolver($placeholderResolver);

        $this->assertEquals('bar', $configuration->resolve('foo'));
    }
}

class ConfigurationTestObject
{
    public $key;
    public function __construct($key)
    {
        $this->key = $key;
    }
}


text:
class ProjectsController < ApplicationController
	layout "application"

	def index

	end

	def show

	end

end


text:
layout: default
title: Projects
permalink: /projects/
---

## Projects


text:
scripts for processing next generation sequencing data

##Douglas McCloskey

##Credits:

Ali Ebrahim for writing the original [sequtil](http://github.com/SBRG) library from which this is derived

To install, please follow the [instructions](INSTALL.md).

###Project Goals:
1.	Compilation of all open-source next generation sequencing packages in a single docker image for fast and pain-free deployment

2.	Methods to run analyses on large batches of samples utilizing docker containers

3.	Methods for distributing data across storage servers and compute servers utilizing docker containers

###TODO:

add/update .py __main__ to include all function parameters

modify shell scripts to call .py __main__

add docker_run scripts to run breseq using Docker


text:
#ifndef _WX_META_POD_H_
#define _WX_META_POD_H_

#include "wx/defs.h"

//
// TODO: Use TR1 is_pod<> implementation where available. VC9 SP1 has it
//       in tr1 namespace, VC10 has it in std namespace. GCC 4.2 has it in
//       <tr1/type_traits>, while GCC 4.3 and later have it in <type_traits>.
//

// This macro declares something called "value" inside a class declaration.
//
// It has to be used because VC6 doesn't handle initialization of the static
// variables in the class declaration itself while BCC5.82 doesn't understand
// enums (it compiles the template fine but can't use it later)
#if defined(__VISUALC__) && !wxCHECK_VISUALC_VERSION(7)
    #define wxDEFINE_TEMPLATE_BOOL_VALUE(val) enum { value = val }
#else
    #define wxDEFINE_TEMPLATE_BOOL_VALUE(val) static const bool value = val
#endif

// Helper to decide if an object of type T is POD (Plain Old Data)
template<typename T>
struct wxIsPod
{
    wxDEFINE_TEMPLATE_BOOL_VALUE(false);
};

// Macro to add wxIsPod<T> specialization for given type that marks it
// as Plain Old Data:
#define WX_DECLARE_TYPE_POD(type)                           \
    template<> struct wxIsPod<type>                         \
    {                                                       \
        wxDEFINE_TEMPLATE_BOOL_VALUE(true);                 \
    };

WX_DECLARE_TYPE_POD(bool)
WX_DECLARE_TYPE_POD(unsigned char)
WX_DECLARE_TYPE_POD(signed char)
WX_DECLARE_TYPE_POD(unsigned int)
WX_DECLARE_TYPE_POD(signed int)
WX_DECLARE_TYPE_POD(unsigned short int)
WX_DECLARE_TYPE_POD(signed short int)
WX_DECLARE_TYPE_POD(signed long int)
WX_DECLARE_TYPE_POD(unsigned long int)
WX_DECLARE_TYPE_POD(float)
WX_DECLARE_TYPE_POD(double)
WX_DECLARE_TYPE_POD(long double)
#if wxWCHAR_T_IS_REAL_TYPE
WX_DECLARE_TYPE_POD(wchar_t)
#endif
#ifdef wxLongLong_t
WX_DECLARE_TYPE_POD(wxLongLong_t)
WX_DECLARE_TYPE_POD(wxULongLong_t)
#endif

// Visual C++ 6.0 can't compile partial template specializations and as this is
// only an optimization, we can live with pointers not being recognized as
// POD types under VC6
#if !defined(__VISUALC__) || wxCHECK_VISUALC_VERSION(7)

// pointers are Plain Old Data:
template<typename T>
struct wxIsPod<T*>
{
    static const bool value = true;
};

template<typename T>
struct wxIsPod<const T*>
{
    static const bool value = true;
};

#endif // !VC++ < 7

#endif // _WX_META_POD_H_


text:
import inspect
import logging
import math
import struct
from typing import Union
from zlib import crc32

import numpy as np

from .timestamp import *
from ..utils.enum_utils import IntEnum

_logger = logging.getLogger('point_one.fusion_engine.messages.defs')

class SatelliteType(IntEnum):
    UNKNOWN = 0
    GPS = 1
    GLONASS = 2
    LEO = 3
    GALILEO = 4
    BEIDOU = 5
    QZSS = 6
    MIXED = 7
    SBAS = 8
    IRNSS = 9

class SolutionType(IntEnum):
    # Invalid, no position available.
    Invalid = 0
    # Standalone GNSS fix, no correction data used.
    AutonomousGPS = 1
    # Differential GNSS pseudorange solution using a local RTK base station or SSR or SBAS corrections.
    DGPS = 2
    # GNSS RTK solution with fixed integer carrier phase ambiguities (one or more signals fixed).
    RTKFixed = 4
    # GNSS RTK solution with floating point carrier phase ambiguities.
    RTKFloat = 5
    # Integrated position using dead reckoning.
    Integrate = 6
    # Using vision measurements.
    Visual = 9
    # GNSS precise point positioning (PPP) pseudorange/carrier phase solution.
    PPP = 10

class Response(IntEnum):
    ## Command succeeded.
    OK = 0
    ## A version specified in the command or subcommand could not be handled. This could mean that the version was
    ## too new and not supported by the device, or it was older than the version used by the device and there was no
    ## translation for it.
    UNSUPPORTED_CMD_VERSION = 1
    ## The command interacts with a feature that is not present on the target device (e.g., setting the baud rate on
    ## a device without a serial port).
    UNSUPPORTED_FEATURE = 2
    ## One or more values in the command were not in acceptable ranges (e.g., an undefined enum value, or an invalid
    ## baud rate).
    VALUE_ERROR = 3
    ## The command would require adding too many elements to internal storage.
    INSUFFICIENT_SPACE = 4
    ## There was a runtime failure executing the command.
    EXECUTION_FAILURE = 5
    ## The header `payload_size_bytes` is in conflict with the size of the message based on its type or type
    ## specific length fields.
    INCONSISTENT_PAYLOAD_LENGTH = 6
    ## Requested data was corrupted and not available.
    DATA_CORRUPTED = 7
    ## The requested data isn't available.
    NO_DATA_STORED = 8

class MessageType(IntEnum):
    INVALID = 0

    # Navigation solution messages.
    POSE = 10000
    GNSS_INFO = 10001
    GNSS_SATELLITE = 10002
    POSE_AUX = 10003
    CALIBRATION_STATUS = 10004
    RELATIVE_ENU_POSITION = 10005

    # Sensor measurement messages.
    IMU_MEASUREMENT = 11000

    # Vehicle measurement messages.
    WHEEL_SPEED_MEASUREMENT = 11101
    VEHICLE_SPEED_MEASUREMENT = 11102
    WHEEL_TICK_MEASUREMENT = 11103
    VEHICLE_TICK_MEASUREMENT = 11104

    # ROS messages.
    ROS_POSE = 12000
    ROS_GPS_FIX = 12010
    ROS_IMU = 12011

    # Command and control messages.
    COMMAND_RESPONSE = 13000
    MESSAGE_REQUEST = 13001
    RESET_REQUEST = 13002
    VERSION_INFO = 13003
    EVENT_NOTIFICATION = 13004
    SHUTDOWN_REQUEST = 13005
    FAULT_CONTROL = 13006

    SET_CONFIG = 13100
    GET_CONFIG = 13101
    SAVE_CONFIG = 13102
    CONFIG_RESPONSE = 13103

    IMPORT_DATA = 13110
    EXPORT_DATA = 13111
    PLATFORM_STORAGE_DATA = 13113

    SET_MESSAGE_RATE = 13220
    GET_MESSAGE_RATE = 13221
    MESSAGE_RATE_RESPONSE = 13222

    RESERVED = 20000

    @classmethod
    def get_type_string(cls, type):
        try:
            if isinstance(type, str):
                # Convert a string name to a message type (e.g., 'POSE' -> MessageType.POSE).
                type = MessageType[type.upper()]
            else:
                # Convert an int to a MessageType. If `type` is already a MessageType, it'll pass through.
                type = MessageType(type)

            return '%s (%d)' % (type.name, type.value)
        except (KeyError, ValueError):
            try:
                if int(type) >= MessageType.RESERVED:
                    return 'RESERVED (%s)' % str(type)
            except BaseException:
                pass

            return 'UNKNOWN (%s)' % str(type)

class MessageHeader:
    INVALID_SOURCE_ID = 0xFFFFFFFF

    _SYNC0 = 0x2E  # '.'
    _SYNC1 = 0x31  # '1'

    _FORMAT = '<BB2xIBBHIII'
    _SIZE: int = struct.calcsize(_FORMAT)

    _MAX_EXPECTED_SIZE_BYTES = (1 << 24)

    def __init__(self, message_type: MessageType = MessageType.INVALID):
        self.crc: int = 0
        self.protocol_version: int = 2
        self.sequence_number: int = 0
        self.message_version: int = 0
        self.message_type: MessageType = message_type
        self.payload_size_bytes: int = 0
        self.source_identifier: int = MessageHeader.INVALID_SOURCE_ID

    def get_type_string(self):
        return MessageType.get_type_string(self.message_type)

    def calculate_crc(self, payload: bytes):
        """!
        @brief Calculate the CRC for this header and the specified payload.

        @post
        @ref crc and @ref payload_size_bytes will be populated automatically on return.

        @return The computed CRC.
        """
        # Set the payload length and then pack the header so we can compute the CRC on the header fields starting with
        # protocol_version, then add the payload into the CRC.
        self.payload_size_bytes = len(payload)
        header_buffer = self.pack()
        self.crc = crc32(header_buffer[8:])
        self.crc = crc32(payload, self.crc)
        return self.crc

    def validate_crc(self, buffer: bytes, offset: int = 0):
        # Sanity check the message payload length before calculating the CRC.
        if self.payload_size_bytes > MessageHeader._MAX_EXPECTED_SIZE_BYTES:
            raise ValueError('Payload length failed sanity check. [%d bytes > %d bytes]' %
                             (self.payload_size_bytes, MessageHeader._MAX_EXPECTED_SIZE_BYTES))

        message_size_bytes = MessageHeader._SIZE + self.payload_size_bytes
        crc = crc32(buffer[(offset + 8):(offset + message_size_bytes)])
        if crc != self.crc:
            raise ValueError('CRC mismatch. [type=%s, payload_size=%d B, expected=0x%08x, computed=0x%08x]' %
                             (self.get_type_string(), self.payload_size_bytes, self.crc, crc))

    def pack(self, buffer: bytes = None, offset: int = 0, payload: bytes = None, return_buffer: bool = True) ->\
            (bytes, int):
        """!
        @brief Serialize this header, or a complete header + payload, into a byte buffer.

        @post
        If `payload is not None`, @ref payload_size_bytes will be set automatically and @ref crc will be populated with
        the computed CRC.

        @param buffer If specified, serialize into the provided buffer. Otherwise, create a new buffer.
        @param offset The offset into the buffer (in bytes) at which the message header will be written. Ignored if
               `buffer is None`.
        @param payload If specified, include the provided message payload in the serialized result.
        @param return_buffer If `True`, return the `bytes` buffer object. Otherwise, return the size of the serialized
               content (in bytes).

        @return A `bytes` object containing the serialized message, or the size of the serialized content (in bytes).
        """
        # If the payload is specified, set the CRC and payload length, and then append the payload to the returned
        # result.
        if payload is not None:
            self.calculate_crc(payload)

        args = (MessageHeader._SYNC0, MessageHeader._SYNC1, self.crc, self.protocol_version, self.message_version,
                int(self.message_type), self.sequence_number, self.payload_size_bytes, self.source_identifier)
        if buffer is None:
            buffer = struct.pack(MessageHeader._FORMAT, *args)
            if payload is not None:
                buffer += payload
        else:
            struct.pack_into(MessageHeader._FORMAT, buffer, offset, *args)
            if payload is not None:
                offset += MessageHeader._SIZE
                buffer[offset:offset + len(payload)] = payload

        if return_buffer:
            return buffer
        else:
            return self.calcsize()

    def unpack(self, buffer: bytes, offset: int = 0, validate_crc: bool = False,
               warn_on_unrecognized: bool = True) -> int:
        """!
        @brief Deserialize a message header and validate its sync bytes and CRC.

        @note
        If CRC validation is enabled, the complete message payload is assumed to follow the header in `buffer`.

        @param buffer A byte buffer containing a serialized message.
        @param offset The offset into the buffer (in bytes) at which the message header begins.
        @param validate_crc If `True`, validate the deserialized CRC against the data in the buffer.

        @return The size of the serialized header (in bytes).
        """
        (sync0, sync1,
         self.crc, self.protocol_version,
         self.message_version, message_type_int,
         self.sequence_number, self.payload_size_bytes, self.source_identifier) = \
            struct.unpack_from(MessageHeader._FORMAT, buffer, offset)

        if sync0 != MessageHeader._SYNC0 or sync1 != MessageHeader._SYNC1:
            raise ValueError('Received invalid sync bytes. [sync0=0x%02x, sync1=0x%02x]' % (sync0, sync1))

        # Validate the CRC, assuming the message payload follows in the buffer.
        if validate_crc:
            self.validate_crc(buffer, offset)

        try:
            self.message_type = MessageType(message_type_int)
        except ValueError:
            if warn_on_unrecognized:
                _logger.log(logging.WARNING if message_type_int < int(MessageType.RESERVED) else logging.DEBUG,
                            'Unrecognized message type %d.' % message_type_int)
            self.message_type = message_type_int

        return MessageHeader._SIZE

    def get_message_size(self) -> int:
        """!
        @brief Calculate the total message size (header + payload).

        @return The message size (in bytes).
        """
        return MessageHeader._SIZE + self.payload_size_bytes

    @classmethod
    def calcsize(cls) -> int:
        """!
        @brief Calculate the size of the header.

        @return The size of the header (in bytes).
        """
        return MessageHeader._SIZE

    def __str__(self):
        return f"""\
{self.get_type_string()} Message (version {self.message_version}):
  Sequence #: {self.sequence_number}
  Payload: {self.payload_size_bytes} B
  Source: {self.source_identifier}
  CRC: 0x{self.crc:08x}"""

    def __repr__(self):
        return f"[type={self.get_type_string()}, seq={self.sequence_number}, payload={self.payload_size_bytes} B, " \
               f"crc=0x{self.crc:08x}]"

class MessagePayload:
    """!
    @brief Message payload API.
    """

    def __init__(self):
        pass

    @classmethod
    def get_type(cls) -> MessageType:
        return cls.MESSAGE_TYPE

    @classmethod
    def get_type_string(cls):
        return MessageType.get_type_string(cls.get_type())

    @classmethod
    def get_version(cls) -> int:
        return cls.MESSAGE_VERSION

    @classmethod
    def is_subclass(cls, obj) -> bool:
        """!
        @brief Check if an object is a _class_, which is derived from @ref MessagePayload.

        This function calls the built-in `issubclass()` operator to check if a specified object is a class derived from
        @ref MessagePayload. Unlike the operator, which raises a `TypeError` if the object is not a class (e.g., if you
        pass in a `None`, or any other object), this function accepts any type for its argument:
        ```py
        issubclass(None, MessagePayload)        # TypeError
        issubclass(float, MessagePayload)       # False
        issubclass(dict, MessagePayload)        # False
        issubclass(PoseMessage, MessagePayload) # True

        MessagePayload.is_subclass(None)        # False
        MessagePayload.is_subclass(float)       # False
        MessagePayload.is_subclass(dict)        # False
        MessagePayload.is_subclass(PoseMessage) # True
        ```

        Note that this function is specifically meant to check classes, not class _instances_. To test if an object is
        an instance of a class derived from @ref MessagePayload, use the `isinstance()` operator instead:
        ```py
        isinstance(None, MessagePayload)          # False
        isinstance(3.6, MessagePayload)           # False
        isinstance(dict(), MessagePayload)        # False
        isinstance(PoseMessage(), MessagePayload) # True
        ```

        @param obj The object to be tested.

        @return `True` if obj is a class type that is derived from @ref MessagePayload.
        """
        return inspect.isclass(obj) and issubclass(obj, MessagePayload)

    def pack(self, buffer: bytes = None, offset: int = 0, return_buffer: bool = True) -> (bytes, int):
        raise NotImplementedError('pack() not implemented.')

    def unpack(self, buffer: bytes, offset: int = 0) -> int:
        raise NotImplementedError('unpack() not implemented.')

    def get_p1_time(self) -> Timestamp:
        measurement_timestamps = getattr(self, 'timestamps', None)
        if isinstance(measurement_timestamps, MeasurementTimestamps):
            return measurement_timestamps.p1_time
        else:
            return getattr(self, 'p1_time', None)

    def get_system_time_ns(self) -> float:
        measurement_timestamps = getattr(self, 'timestamps', None)
        if isinstance(measurement_timestamps, MeasurementTimestamps):
            if measurement_timestamps.measurement_time_source == SystemTimeSource.TIMESTAMPED_ON_RECEPTION:
                return float(measurement_timestamps.measurement_time)
            else:
                return np.nan
        else:
            return getattr(self, 'system_time_ns', None)

    def get_system_time_sec(self) -> float:
        system_time_ns = self.get_system_time_ns()
        if system_time_ns is None:
            return None
        else:
            return system_time_ns * 1e-9

    def __repr__(self):
        try:
            return '%s message' % MessageType.get_type_string(self.get_type())
        except NotImplementedError:
            return 'Unknown message payload.'

    def __str__(self):
        return repr(self)

    @classmethod
    def pack_values(cls, format: Union[str, struct.Struct], buffer: bytes, offset: int = 0, *args):
        """!
        @brief Serialize data into a byte stream.

        This is a convenience packing function for consistency with @ref unpack_values(). It behaves similarly to a
        direct call to `struct.pack_into()`, however the list of values (`args`) may include NumPy `ndarray` elements,
        which will be flattened automatically.

        @param format A `struct` format string or a `struct.Struct` object describing the data packing.
        @param buffer A byte buffer in which the serialized data will be stored.
        @param offset The start offset (in bytes) within `buffer`.
        @param args The values to be packed.

        @return The size of the serialized data.
        """
        # If the user passed in a numpy array, expand it into its elements:
        #   (1, 2, array([3, 4, 5])) -->
        #   (1, 2, 3, 4, 5)
        if any([isinstance(e, np.ndarray) for e in args]):
            flattened_args = []
            for e in args:
                if isinstance(e, np.ndarray):
                    flattened_args.extend(e.flat)
                else:
                    flattened_args.append(e)
        else:
            flattened_args = args

        if isinstance(format, struct.Struct):
            format.pack_into(buffer, offset, *flattened_args)
            return format.size
        else:
            struct.pack_into(format, buffer, offset, *flattened_args)
            return struct.calcsize(format)

    @classmethod
    def unpack_values(cls, format: Union[str, struct.Struct], buffer: bytes, offset: int = 0, *args):
        """!
        @brief Unpack serialized data.

        This is a helper function, similar to `struct.unpack_from()`, which can be used to unpack class members where
        _all_ members are NumPy `ndarray` elements.

        @warning
        Primitives cannot be passed by reference in Python. If you pass in anything other than a NumPy array in `args`,
        it will _not_ be populated on return.

        For example, the following:
        ```py
        my_array = np.ndarray((3,))
        (my_array[0], my_array[1], my_array[2]) = my_struct.unpack_from(buffer, offset)
        ```

        can be rewritten as:
        ```py
        my_array = np.ndarray((3,))
        self.unpack_values(my_struct, buffer, offset, my_array)
        ```

        This function also has the benefit of being consistent with `struct.pack_into()`, making derived classes'
        `pack()` and `unpack()` functions more symmetrical. For example, the above data can be serialized as follows:
        ```py
        self.pack_values(my_struct, buffer, offset, my_double, my_array)

        # or

        my_struct.pack_into(buffer, offset, my_double, *my_array)
        ```

        @param format A `struct` format string or a `struct.Struct` object describing the data packing.
        @param buffer A byte buffer containing the data to be unpacked.
        @param offset The start offset (in bytes) within `buffer`.
        @param args References to variables to be populated.

        @return The number of bytes consumed.
        """
        if isinstance(format, struct.Struct):
            values = format.unpack_from(buffer, offset)
            size = format.size
        else:
            values = struct.unpack_from(format, buffer, offset)
            size = struct.calcsize(format)

        args = list(args)
        value_idx = 0
        for arg_idx in range(len(args)):
            arg = args[arg_idx]
            if isinstance(arg, np.ndarray):
                for i in range(arg.size):
                    arg.flat[i] = values[value_idx]
                    value_idx += 1
            else:
                args[arg_idx] = values[value_idx]
                value_idx += 1

        return size

def PackedDataToBuffer(packed_data: bytes, buffer: bytes = None, offset: int = 0,
                       return_buffer: bool = True) -> (bytes, int):
    if buffer is None:
        buffer = packed_data
    else:
        buffer[offset:(offset + len(packed_data))] = packed_data

    if return_buffer:
        return buffer
    else:
        return len(packed_data)


text:
<?php

$edge_type = PhortuneAccountHasMerchantEdgeType::EDGECONST;

$table = new PhortuneCart();
foreach (new LiskMigrationIterator($table) as $cart) {
  id(new PhabricatorEdgeEditor())
    ->addEdge($cart->getAccountPHID(), $edge_type, $cart->getMerchantPHID())
    ->save();
}


text:
FM_ID: ''
name: Westwood Village Farmers Market
address_1: 1083 Braxton Avenue
address_2: ''
city: Los Angeles
state: California
zip: '90024'
phone: ''
latitude: '34.057'
longitude: '-118.4494'
website: ''
daycode1: Thu
day1_open: '1200'
day1_close: '1800'
daycode2: ''
day2_open: ''
day2_close: ''
category: Farmers Market
title: 'Westwood Village Farmers Market, Food Oasis Los Angeles'
uri: /farmers-market/westwood-village/
formatted_daycode1: Thursday
formatted_day1_open: 12pm
formatted_day1_close: 6pm

---


text:
cask 'meshcommander' do
  version '0.7.7'
  sha256 'ac104f6bd8c79786fdd371064fd6a2a892ba58851e60447a8ce83ad2bed6725c'

  # bintray.com/gomesjj/APPS/ was verified as official when first introduced to the cask
  url "https://bintray.com/gomesjj/APPS/download_file?file_path=#{version.major}.#{version.minor}#{version.patch}%2FMeshCommander.dmg.zip"
  appcast 'https://dl.bintray.com/gomesjj/APPS/',
          must_contain: "#{version.major_minor}#{version.patch}"
  name 'MeshCommander'
  homepage 'https://www.devtty.uk/apple/Intel_Mesh_Commander_on_Mac_OS_X/'

  app 'MeshCommander.app'
end


text:
package pgs

type mockPP struct {
	match bool
	out   []byte
	err   error
}

func (pp mockPP) Match(a Artifact) bool             { return pp.match }
func (pp mockPP) Process(in []byte) ([]byte, error) { return pp.out, pp.err }


text:
jest.dontMock("../MesosSummaryStore");
jest.dontMock("../../utils/MesosSummaryUtil");
jest.dontMock("../../utils/StringUtil");
jest.dontMock("../../utils/Util");

const MesosSummaryStore = require("../MesosSummaryStore");
const Framework = require("../../../../plugins/services/src/js/structs/Framework");

MesosSummaryStore.init();

describe("Mesos State Store", function() {
  describe("#processSummary", function() {
    beforeEach(function() {
      this.processSummaryError = MesosSummaryStore.processSummaryError;
      MesosSummaryStore.processSummaryError = jest.genMockFunction();
      MesosSummaryStore.processSummary({});
    });

    afterEach(function() {
      MesosSummaryStore.processSummaryError = this.processSummaryError;
    });

    it("calls processSummaryError with no arguments when summary is empty Object", function() {
      expect(MesosSummaryStore.processSummaryError.mock.calls.length).toEqual(
        1
      );
      expect(
        MesosSummaryStore.processSummaryError.mock.calls[0].length
      ).toEqual(0);
    });
  });

  describe("#hasServiceUrl", function() {
    beforeEach(function() {
      this.getServiceFromName = MesosSummaryStore.getServiceFromName;
      MesosSummaryStore.getServiceFromName = function(hasUrl) {
        if (hasUrl === "name_of_service_with_url") {
          return new Framework({
            name: "fake_service",
            webui_url: "http://google.com"
          });
        }

        return new Framework({
          name: "fake_service"
        });
      };
    });

    afterEach(function() {
      MesosSummaryStore.getServiceFromName = this.getServiceFromName;
    });

    it("returns true if service has a web url", function() {
      var hasUrl = MesosSummaryStore.hasServiceUrl("name_of_service_with_url");

      expect(hasUrl).toEqual(true);
    });

    it("returns false if service does not have a web url", function() {
      var hasUrl = MesosSummaryStore.hasServiceUrl(
        "name_of_service_without_url"
      );

      expect(hasUrl).toEqual(false);
    });
  });
});


text:
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.coverage'
]

templates_path = ['_templates']

source_suffix = '.rst'

master_doc = 'index'

project = u'python-troveclient'
copyright = u'2012, OpenStack Foundation'

exclude_trees = []

pygments_style = 'sphinx'

html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename = 'python-troveclientdoc'
latex_documents = [
    ('index', 'python-troveclient.tex', u'python-troveclient Documentation',
     u'OpenStack', 'manual'),
]


text:
package api.web.gw2.mapping.v2.continents;

import api.web.gw2.mapping.core.ContinentDimensions;
import api.web.gw2.mapping.core.ContinentDims;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.core.QuantityValue;
import api.web.gw2.mapping.core.SetValue;
import api.web.gw2.mapping.v2.APIv2;
import java.util.Set;

/**
 * Defines a continent.
 * @author FabriceB
 */
@APIv2(endpoint = "v2/continents") // NOI18N.
public interface Continent {

    /**
     * Gets the id of this continent.
     * @return An {@code int} ≥ 0.
     */
    @IdValue
    int getId();

    /**
     * Gets the i18n name of this continent.
     * @return A {@code String} instance, never {@code null}.
     */
    @LocalizedResource
    String getName();

    /**
     * Gets the dimensions of the area defined by this continent.
     * @return A {@code ContinentDimension} instance, never {@code null}.
     */
    @ContinentDims
    ContinentDimensions getContinentDims();

    /**
     * Gets the minimum zoom level support for this continent.
     * @return An {@code int}
     */
    @QuantityValue
    int getMinZoom();

    /**
     * Gets the maximum zoom level support for this continent.
     * @return An {@code int}
     */
    @QuantityValue
    int getMaxZoom();

    /**
     * Gets a set of tile ids included in this continent.
     * @return A {@code Set<Integer>} instance, never {@code null}.
     */
    @SetValue
    Set<Integer> getFloors();
}


text:
<?php

namespace KrzysztofMazur\ObjectMapper\Mapping;

use KrzysztofMazur\ObjectMapper\Exception\MappingException;
use KrzysztofMazur\ObjectMapper\Mapping\Field\FieldFactory;
use KrzysztofMazur\ObjectMapper\Mapping\Field\FieldsMatchmakerInterface;

/**
 * @author Krzysztof Mazur <krz@ychu.pl>
 */
class MappingRepository implements MappingRepositoryInterface
{
    /**
     * @var array
     */
    private $mappings;

    /**
     * @param array                     $config
     * @param FieldFactory              $fieldFactory
     * @param FieldsMatchmakerInterface $fieldsMatchmaker
     */
    public function __construct(array $config, FieldFactory $fieldFactory, FieldsMatchmakerInterface $fieldsMatchmaker)
    {
        $this->mappings = [];
        foreach ($config as $mappingConfiguration) {
            self::checkMappingConfiguration($mappingConfiguration);
            $mapId = isset($mappingConfiguration['mapId']) ? $mappingConfiguration['mapId'] : null;
            if (!isset($this->mappings[$mapId])) {
                $this->mappings[$mapId] = [];
            }
            $auto = isset($mappingConfiguration['auto']) ? $mappingConfiguration['auto'] : false;
            $fields = isset($mappingConfiguration['fields']) ? $mappingConfiguration['fields'] : [];
            $this->mappings[$mapId][] = MappingBuilder::create()
                ->setFields($fields)
                ->setSourceClass($mappingConfiguration['from'])
                ->setTargetClass($mappingConfiguration['to'])
                ->setFieldFactory($fieldFactory)
                ->setFieldsAutoMatch($auto)
                ->setFieldsMatchmaker($fieldsMatchmaker)
                ->build();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getMapping($sourceClass, $targetClass, $mapId = null)
    {
        if (!isset($this->mappings[$mapId])) {
            throw MappingException::createNotSupportedMapping($sourceClass, $targetClass);
        }
        foreach ($this->mappings[$mapId] as $mapping) {
            /** @var Mapping $mapping */
            if ($mapping->supports($sourceClass, $targetClass)) {
                return $mapping;
            }
        }

        throw MappingException::createNotSupportedMapping($sourceClass, $targetClass);
    }

    /**
     * @param array $configuration
     */
    private static function checkMappingConfiguration(array $configuration)
    {
        self::assertOneOfArrayKeysExist(
            ['fields', 'auto'],
            $configuration,
            "\"fields\" or \"auto\" property is required"
        );
        self::assertArrayKeyExists('from', $configuration, "Missing \"from\" key in mapping configuration");
        self::assertArrayKeyExists('to', $configuration, "Missing \"to\" key in mapping configuration");
    }

    /**
     * @param string $key
     * @param array  $array
     * @param string $message
     */
    private static function assertArrayKeyExists($key, $array, $message)
    {
        if (!isset($array[$key])) {
            throw new \InvalidArgumentException($message);
        }
    }

    /**
     * @param string[] $keys
     * @param array    $array
     * @param string   $message
     */
    private static function assertOneOfArrayKeysExist($keys, $array, $message)
    {
        foreach ($keys as $key) {
            if (isset($array[$key])) {
                return;
            }
        }

        throw new \InvalidArgumentException($message);
    }
}


text:
package com.questionanswer.service;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.questionanswer.data.QuestionRepository;
import com.questionanswer.model.AnswerAndVoteCount;
import com.questionanswer.model.Question;

@Service
public class QuestionDetailsServiceImpl implements QuestionDetailService {

	private QuestionRepository questionRepo;

	@Autowired
	public QuestionDetailsServiceImpl(QuestionRepository questionRepo) {
		this.questionRepo = questionRepo;
	}

	@Override
	@Transactional
	public Map<String, Object> getQuestionDetails(long id) {
		Map<String, Object> resultMap = new HashMap<>();

		Question resultQuestion = this.questionRepo.findOne(id);
		resultQuestion.getAnswers().size();
		resultMap.put("question", resultQuestion);
		resultMap.put("user", resultQuestion.getUser());
		resultMap.put("answers", resultQuestion.getAnswers()
			.stream()
			.map(AnswerAndVoteCount::new)
			.collect(Collectors.toList()));

		return resultMap;
	}

}


text:
<?php

declare(strict_types=1);

namespace AveEntityManager\Parser;

use AveEntityManager\Config\Config;

/**
 * Interface Parser
 *
 * @package AveEntityManager\Parser
 * @author Averor <averor.dev@gmail.com>
 * @created 19.06.17
 */
interface Parser
{
    /**
     * @param Config $config
     * @return array
     * @throws ParserException
     */
    public static function parse(Config $config) : array;
}


text:
package zzb.rest
package directives

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.control.NonFatal
import akka.actor._

trait ExecutionDirectives {
  import BasicDirectives._

  /**
   * Transforms exceptions thrown during evaluation of its inner route using the given
   * [[zzb.rest.ExceptionHandler]].
   */
  def handleExceptions(handler: ExceptionHandler): Directive0 =
    mapInnerRoute { inner ⇒
      ctx ⇒
        def handleError = handler andThen (_(ctx.withContentNegotiationDisabled))
        try inner {
          ctx withRouteResponseHandling {
            case Status.Failure(error) if handler isDefinedAt error ⇒ handleError(error)
          }
        }
        catch handleError
    }

  /**
   * Transforms rejections produced by its inner route using the given
   * [[zzb.rest.RejectionHandler]].
   */
  def handleRejections(handler: RejectionHandler): Directive0 =
    mapRequestContext { ctx ⇒
      ctx withRejectionHandling { rejections ⇒
        val filteredRejections = RejectionHandler.applyTransformations(rejections)
        if (handler isDefinedAt filteredRejections)
          handler(filteredRejections) {
            ctx.withContentNegotiationDisabled withRejectionHandling { r ⇒
              sys.error(s"The RejectionHandler for $rejections must not itself produce rejections (received $r)!")
            }
          }
        else ctx.reject(filteredRejections: _*)
      }
    }

  /**
   * A directive that evaluates its inner Route for every request anew. Note that this directive has no additional
   * effect when used inside (or some level underneath) a directive extracting one or more values, since everything
   * inside a directive extracting values is _always_ reevaluated for every request.
   *
   * Also Note that this directive differs from most other directives in that it cannot be combined with other routes
   * via the usual `&` and `|` operators.
   */
  def dynamic = ExecutionDirectives._dynamic

  /**
   * A directive that evaluates its inner Route for every request anew, if the given enabled flag is true.
   * Note that this directive has no additional effect when used inside (or some level underneath) a directive
   * extracting one or more values, since everything inside a directive extracting values is _always_ reevaluated for
   * every request.
   *
   * Also Note that this directive differs from most other directives in that it cannot be combined with other routes
   * via the usual `&` and `|` operators.
   */
  case class dynamicIf(enabled: Boolean) {
    def apply(inner: ⇒ Route): Route =
      if (enabled) Route(ctx ⇒ inner(ctx)) else inner
  }

  /**
   * Executes its inner Route in a `Future`.
   */
  def detach(dm: DetachMagnet): Directive0 = {
    import dm._
    mapInnerRoute { inner ⇒
      ctx ⇒
        Future(inner(ctx)).onFailure { case e ⇒ ctx.failWith(e) }
    }
  }
}

object ExecutionDirectives extends ExecutionDirectives {
  private val _dynamic = dynamicIf(enabled = true)
}

class DetachMagnet()(implicit val ec: ExecutionContext)

object DetachMagnet {
  implicit def fromUnit(u: Unit)(implicit dm2: DetachMagnet2) = new DetachMagnet()(dm2.ec)
  implicit def fromExecutionContext(ec: ExecutionContext) = new DetachMagnet()(ec)
}

class DetachMagnet2(val ec: ExecutionContext)

object DetachMagnet2 extends DetachMagnet2LowerPriorityImplicits {
  implicit def fromImplicitExecutionContext(implicit ec: ExecutionContext) = new DetachMagnet2(ec)
}

private[directives] abstract class DetachMagnet2LowerPriorityImplicits {
  implicit def fromImplicitRefFactory(implicit factory: ActorRefFactory) = new DetachMagnet2(factory.dispatcher)
}


text:
package eu.ydp.empiria.player.client.controller.multiview;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.google.web.bindery.event.shared.HandlerRegistration;
import eu.ydp.empiria.player.client.controller.Page;
import eu.ydp.empiria.player.client.controller.extensions.internal.InternalExtension;
import eu.ydp.empiria.player.client.controller.extensions.types.FlowRequestSocketUserExtension;
import eu.ydp.empiria.player.client.controller.flow.request.FlowRequestInvoker;
import eu.ydp.empiria.player.client.controller.multiview.swipe.SwipeType;
import eu.ydp.empiria.player.client.controller.multiview.touch.MultiPageTouchHandler;
import eu.ydp.empiria.player.client.gin.factory.TouchRecognitionFactory;
import eu.ydp.empiria.player.client.module.button.NavigationButtonDirection;
import eu.ydp.empiria.player.client.util.events.internal.bus.EventsBus;
import eu.ydp.empiria.player.client.util.events.internal.emulate.TouchEvent;
import eu.ydp.empiria.player.client.util.events.internal.emulate.TouchTypes;
import eu.ydp.empiria.player.client.util.events.internal.emulate.handlers.HasTouchHandlers;
import eu.ydp.empiria.player.client.util.events.internal.player.PlayerEvent;
import eu.ydp.empiria.player.client.util.events.internal.player.PlayerEventTypes;
import eu.ydp.gwtutil.client.NumberUtils;
import eu.ydp.gwtutil.client.collections.KeyValue;
import eu.ydp.gwtutil.client.proxy.RootPanelDelegate;
import eu.ydp.gwtutil.client.proxy.WindowDelegate;
import eu.ydp.gwtutil.client.util.UserAgentChecker;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Singleton
public class MultiPageController extends InternalExtension implements FlowRequestSocketUserExtension, IMultiPageController {

    @Inject
    private EventsBus eventsBus;
    @Inject
    private PanelCache panelsCache;
    @Inject
    private Page page;
    @Inject
    private MultiPageView view;
    @Inject
    private TouchRecognitionFactory touchRecognitionFactory;
    @Inject
    private MultiPageTouchHandler multiPageTouchHandler;
    @Inject
    private VisiblePagesManager visiblePagesManager;
    @Inject
    @Named("multiPageControllerMainPanel")
    private FlowPanel mainPanel;
    @Inject
    private Provider<SwipeType> swipeType;
    @Inject
    private MultiPageControllerStyleManager multiPageControllerStyleManager;
    @Inject
    private WindowDelegate windowDelegate;
    @Inject
    private RootPanelDelegate rootPanelDelegate;
    @Inject
    private PageSwitchAnimation pageSwitchAnimation;
    @Inject
    private PanelAttacher panelAttacher;
    @Inject
    private PanelDetacher panelDetacher;
    @Inject
    private Provider<ResizeTimer> resizeTimer;

    private int currentVisiblePage = -1;
    private final static int WIDTH = 100;
    private final static int DEFAULT_ANIMATION_TIME = 500;
    private final static int QUICK_ANIMATION_TIME = 150;
    public final static int TOUCH_END_TIMER_TIME = 800;
    private float currentPosition;

    private FlowRequestInvoker flowRequestInvoker;
    private int swipeLength = 220;

    private final Set<Integer> loadedPages = new HashSet<>();
    private int pageProgressBar = -1;

    private final Set<HandlerRegistration> touchHandlers = new HashSet<>();
    private boolean focusDropped;

    private static final Function<KeyValue<FlowPanel, FlowPanel>, FlowPanel> keyPanelExtractor = new Function<KeyValue<FlowPanel, FlowPanel>, FlowPanel>() {
        @Override
        public FlowPanel apply(KeyValue<FlowPanel, FlowPanel> keyValue) {
            return keyValue.getKey();
        }
    };

    private void clearPagesStyles() {
        Collection<KeyValue<FlowPanel, FlowPanel>> cacheValues = panelsCache.getCache().values();
        Collection<FlowPanel> keyPanels = Collections2.transform(cacheValues, keyPanelExtractor);
        multiPageControllerStyleManager.clearPagesStyles(keyPanels);
    }

    protected int getHeightForPage(int pageNumber) {
        FlowPanel flowPanel = (FlowPanel) getViewForPage(pageNumber).getParent();
        return flowPanel == null ? 0 : flowPanel.getOffsetHeight();
    }

    protected void setHeight(int height) {
        if (isSwipeDisabled()) {
            view.setHeight("auto");
        } else {
            view.setHeight(height + "px");
        }
    }

    @Override
    public void setVisiblePage(int pageNumber) {
        showProgressBarForPage(pageNumber);
        ResizeTimer resizeTimer = this.resizeTimer.get();
        resizeTimer.cancelAndReset();
        resizeTimer.schedule(350);
        if (currentVisiblePage != pageNumber && pageNumber >= 0) {
            this.currentVisiblePage = pageNumber;
            pageSwitchAnimation.animatePageSwitch(this, getPositionLeft(), -pageNumber * WIDTH, null, DEFAULT_ANIMATION_TIME, false);
        } else {
            eventsBus.fireEvent(new PlayerEvent(PlayerEventTypes.PAGE_VIEW_LOADED));
        }
        hideProgressBarForPage(pageNumber);
    }

    public FlowPanel getViewForPage(Integer pageNumber) {
        boolean pageWasCreated = panelsCache.isPresent(pageNumber);
        KeyValue<FlowPanel, FlowPanel> panel = panelsCache.getOrCreateAndPut(pageNumber);

        if (!pageWasCreated) {
            mainPanel.add(panel.getKey());
            applyStylesToPanelOnIndex(pageNumber);
            showProgressBarForPage(pageNumber);
        }
        loadedPages.add(pageNumber);
        return panel.getValue();
    }

    private void applyStylesToPanelOnIndex(Integer pageNumber) {
        KeyValue<FlowPanel, FlowPanel> panelsPair = panelsCache.getOrCreateAndPut(pageNumber);
        FlowPanel panel = panelsPair.getKey();

        boolean isChangeToNextPage = isChangeToNextPage(pageNumber);
        multiPageControllerStyleManager.setPageStyles(panel, isChangeToNextPage);
    }

    private boolean isChangeToNextPage(Integer pageNumber) {
        return pageNumber > currentVisiblePage;
    }

    @Override
    public void detachAttachPanels() {
        Set<Integer> pagesToDetach = visiblePagesManager.getPagesToDetach(currentVisiblePage);
        panelDetacher.detach(pagesToDetach);

        List<Integer> pagesToAttache = visiblePagesManager.getPagesToAttache(currentVisiblePage);
        panelAttacher.attach(this, pagesToAttache);
    }

    @Override
    public void animatePageSwitch() {
        pageSwitchAnimation.animatePageSwitch(this, getPositionLeft(), getCurrentPosition(), null, QUICK_ANIMATION_TIME, true);
    }

    private float getPositionLeft() {
        Style style = getStyle();
        return NumberUtils.tryParseFloat(style.getLeft().replaceAll("[a-z%]+$", ""));
    }

    /**
     * Na androidzie podczas swipe gapy zle sie rysowaly nachodzac na siebie.
     * Pozbycie sie z nich focusa na czas swipe rozwiazalo problem
     */
    private void dropFocus() {
        focusDropped = true;
        NodeList<Element> elementsByTagName = rootPanelDelegate.getBodyElement().getElementsByTagName("input");
        for (int x = 0; x < elementsByTagName.getLength(); ++x) {
            elementsByTagName.getItem(x).blur();
        }
    }

    @Override
    public void move(boolean swipeRight, float length) {
        if (!focusDropped && UserAgentChecker.isStackAndroidBrowser()) {
            dropFocus();
        }
        if (swipeRight) {
            showProgressBarForPage(currentVisiblePage + 1);
        } else {
            showProgressBarForPage(currentVisiblePage - 1);
        }
        Style style = getStyle();
        float position = getPositionLeft();
        if (swipeRight) {
            style.setLeft(position - length, Unit.PCT);
        } else {
            style.setLeft(position + length, Unit.PCT);
        }
    }

    public Style getStyle() {
        return mainPanel.getElement().getStyle();
    }

    private void showProgressBarForPage(int pageIndex) {
        if (!loadedPages.contains(pageIndex) && isValidPageIndex(pageIndex)) {
            Panel panel = getViewForPage(pageIndex);
            panel.add(new ProgressPanel());
            pageProgressBar = pageIndex;
        }
    }

    private boolean isValidPageIndex(int pageIndex) {
        return pageProgressBar != pageIndex && page.isNotLastPage(pageIndex) && pageIndex >= 0;
    }

    public void hideCurrentPageProgressBar(){
        hideProgressBarForPage(currentVisiblePage);
    }

    private void hideProgressBarForPage(int pageIndex) {
        if (page.isNotLastPage(pageIndex)) {
            FlowPanel panel = getViewForPage(pageIndex);
            for (int x = 0; x < panel.getWidgetCount(); ++x) {
                if (panel.getWidget(x) instanceof ProgressPanel) {
                    panel.getWidget(x).removeFromParent();
                    break;
                }
            }
        }
    }

    @Override
    public void reset() {
        multiPageTouchHandler.resetModelAndTimer();
        resetFocusAndStyles();
        multiPageTouchHandler.setTouchReservation(true);
    }

    @Override
    public void resetFocusAndStyles() {
        focusDropped = false;
        clearPagesStyles();
    }

    @Override
    public boolean isZoomed() {
        int clientWidth = windowDelegate.getClientWidth();
        int innerWidth = windowDelegate.getInnerWidth();
        return innerWidth < clientWidth;
    }

    @Override
    public void switchPage() {
        if (multiPageTouchHandler.getTouchReservation()) {
            pageSwitchAnimation.animatePageSwitch(this, getPositionLeft(), currentPosition, null, QUICK_ANIMATION_TIME, true);
            return;
        }

        NavigationButtonDirection direction = multiPageTouchHandler.getDirection();
        float percent = (float) swipeLength / rootPanelDelegate.getOffsetWidth() * 100;
        if (direction != null) {
            if (direction == NavigationButtonDirection.PREVIOUS && page.getCurrentPageNumber() > 0) {
                pageSwitchAnimation.animatePageSwitch(this, getPositionLeft(), getPositionLeft() + (WIDTH - percent), direction, DEFAULT_ANIMATION_TIME, true);
                eventsBus.fireEvent(new PlayerEvent(PlayerEventTypes.PAGE_CHANGE_STARTED));
            } else if (direction == NavigationButtonDirection.NEXT && page.isNotLastPage(page.getCurrentPageNumber())) {
                pageSwitchAnimation.animatePageSwitch(this, getPositionLeft(), getPositionLeft() - (WIDTH - percent), direction, DEFAULT_ANIMATION_TIME, true);
                eventsBus.fireEvent(new PlayerEvent(PlayerEventTypes.PAGE_CHANGE_STARTED));
            } else {
                pageSwitchAnimation.animatePageSwitch(this, getPositionLeft(), currentPosition, null, QUICK_ANIMATION_TIME, true);
            }
        }
    }

    @Override
    public void setFlowRequestsInvoker(FlowRequestInvoker fri) {
        flowRequestInvoker = fri;
    }

    @Override
    public void init() {
        multiPageTouchHandler.setMultiPageController(this);
        view.setController(this);
        configureSwipe();

        LoadPageViewHandler loadPageViewHandler = new LoadPageViewHandler(this);
        TouchReservationHandler touchReservationHandler = new TouchReservationHandler(this);
        PageViewLoadedHandler pageViewLoadedHandler = new PageViewLoadedHandler(this);
        eventsBus.addHandler(PlayerEvent.getType(PlayerEventTypes.LOAD_PAGE_VIEW), loadPageViewHandler);
        eventsBus.addHandler(PlayerEvent.getType(PlayerEventTypes.TOUCH_EVENT_RESERVATION), touchReservationHandler);
        eventsBus.addHandler(PlayerEvent.getType(PlayerEventTypes.PAGE_VIEW_LOADED), pageViewLoadedHandler);

        view.add(mainPanel);
    }

    public boolean isSwipeDisabled() {
        return swipeType.get() == SwipeType.DISABLED;
    }

    private void configureSwipe() {
        if (isSwipeDisabled()) {
            for (HandlerRegistration registration : touchHandlers) {
                registration.removeHandler();
            }
            touchHandlers.clear();
            setVisiblePageCount(1);
        } else {
            RootPanel rootPanel = rootPanelDelegate.getRootPanel();
            HasTouchHandlers touchHandler = touchRecognitionFactory.getTouchRecognition(rootPanel, false);
            touchHandlers.add(touchHandler.addTouchHandler(multiPageTouchHandler, TouchEvent.getType(TouchTypes.TOUCH_START)));
            touchHandlers.add(touchHandler.addTouchHandler(multiPageTouchHandler, TouchEvent.getType(TouchTypes.TOUCH_MOVE)));
            touchHandlers.add(touchHandler.addTouchHandler(multiPageTouchHandler, TouchEvent.getType(TouchTypes.TOUCH_END)));
            setVisiblePageCount(3);
        }
        panelsCache.setSwipeType(swipeType.get());
    }

    private void setVisiblePageCount(int count) {
        visiblePagesManager.setVisiblePageCount(count);
    }

    public int getCurrentVisiblePage() {
        return currentVisiblePage;
    }

    public FlowPanel getMainPanel() {
        return mainPanel;
    }

    public int getWidth() {
        return WIDTH;
    }

    public MultiPageView getView() {
        return view;
    }

    @Override
    public boolean isAnimationRunning() {
        return pageSwitchAnimation.isAnimationRunning();
    }

    private float getCurrentPosition() {
        return currentPosition;
    }

    public void setSwipeLength(int swipeLength) {
        this.swipeLength = swipeLength;
    }

    public void setCurrentPosition(float currentPosition) {
        this.currentPosition = currentPosition;
    }

    public void invokeNavigationRequest(NavigationButtonDirection direction) {
        flowRequestInvoker.invokeRequest(direction.getRequest());
    }

    public void setCurrentPageHeight() {
        int height = getHeightForPage(currentVisiblePage);
        setHeight(height);
    }

    public int getCurrentPageHeight() {
        return getHeightForPage(currentVisiblePage);
    }

    public boolean isCurrentPage(int pageNumber) {
        return pageNumber == currentVisiblePage;
    }
}


text:
class ChangeArchiveToPublished < ActiveRecord::Migration
  def change
    rename_column :campaigns, :archive_flag, :published_flag
  end
end


text:
var browser = require('browser');
var T = require('./load.test');

browser.browse("shinout.net", function(err, out) {
  T.equal(out.statusCode, 200);
  T.equal(out.cookies.length, 0);
  T.equal(typeof out.responseHeaders.date, "string");
  T.equal(typeof out.responseHeaders["content-length"], "string");
  T.equal(typeof out.result, "string");
});


text:
require_relative 'helpers/helper'

require 'event'

module Fidgit
  describe Event do
    before :each do
      class Test
        include Event
      end
    end

    after :each do
      Fidgit.send :remove_const, :Test
    end

    subject { Test }

    describe "events" do
      it "should initially be empty" do
        subject.events.should be_empty
      end
    end

    describe "event" do
      it "should add the event to the list of events handled" do
        subject.event :frog
        subject.events.should include :frog
      end

      it "should inherit parent's events and be able to add more" do
        Test.event :frog
        class Test2 < Test; end
        Test2.event :fish
        Test2.events.should include :frog
        Test2.events.should include :fish
      end
    end

    context "When included into a class that is instanced" do
      subject { Test.event :frog; Test.new }

      describe "#subscribe" do
        it "should add a handler as a block" do
          subject.subscribe(:frog) { puts "hello" }
        end

        it "should fail if the event name isn't handled by this object" do
          ->{ subject.subscribe(:unhandled_event) {} }.should raise_error ArgumentError
        end

        it "should add a handler as a method" do
          subject.stub! :handler
          subject.subscribe(:frog, subject.method(:handler))
        end

        it "should fail if neither a method or a block is passed" do
          ->{ subject.subscribe(:frog) }.should raise_error ArgumentError
        end

        it "should fail if both a method and a block is passed" do
          subject.stub! :handler
          ->{ subject.subscribe(:frog, subject.method(:handler)) { } }.should raise_error ArgumentError
        end

        it "should return a Subscription" do
          handler = proc {}
          result = subject.subscribe(:frog, &handler)
          result.should be_a Fidgit::Event::Subscription
          result.handler.should be handler
          result.publisher.should be subject
          result.event.should equal :frog
        end

        it "should return a Subscription that can use Subscription#unsubscribe" do
          handler_ran = false
          subscription = subject.subscribe(:frog) { handler_ran = true }
          subscription.unsubscribe
          subject.publish :frog
          handler_ran.should be_false
        end
      end

      describe "#unsubscribe" do
        it "should accept a Subscription" do
          handler_ran = false
          subscription = subject.subscribe(:frog) { handler_ran = true }
          subject.unsubscribe subscription
          subject.publish :frog
          handler_ran.should be_false
        end

        it "should accept a handler" do
          handler_ran = false
          handler = proc { handler_ran = true }
          subject.subscribe(:frog, &handler)
          subject.unsubscribe handler
          subject.publish :frog
          handler_ran.should be_false
        end

        it "should accept an event and handler" do
          handler_ran = false
          handler = proc { handler_ran = true }
          subject.subscribe(:frog, &handler)
          subject.unsubscribe :frog, handler
          subject.publish :frog
          handler_ran.should be_false
        end

        it "should require 1..2 arguments" do
          ->{ subject.unsubscribe }.should raise_error ArgumentError
          ->{ subject.unsubscribe 1, 2, 3 }.should raise_error ArgumentError
        end

        it "should fail with bad types" do
          ->{ subject.unsubscribe 1 }.should raise_error TypeError
          ->{ subject.unsubscribe 1, ->{} }.should raise_error TypeError
          ->{ subject.unsubscribe :event, 2 }.should raise_error TypeError
        end

        it "should fail if passed a Subscription to another object" do
          subscription = Fidgit::Event::Subscription.new(Object.new.extend(Fidgit::Event), :event, proc {})
          ->{ subject.unsubscribe subscription }.should raise_error ArgumentError
        end
      end

      describe "#publish" do
        it "should return nil if there are no handlers" do
          subject.publish(:frog).should be_nil
        end

        it "should return nil if there are no handlers that handle the event" do
          subject.should_receive(:frog).with(subject)
          subject.should_receive(:handler).with(subject)
          subject.subscribe(:frog, subject.method(:handler))
          subject.publish(:frog).should be_nil
        end

        it "should return :handled if a manual handler handled the event and not call other handlers" do
          subject.should_not_receive(:handler1)
          subject.should_receive(:handler2).with(subject).and_return(:handled)
          subject.subscribe(:frog, subject.method(:handler1))
          subject.subscribe(:frog, subject.method(:handler2))
          subject.publish(:frog).should == :handled
        end

        it "should return :handled if an automatic handler handled the event and not call other handlers" do
          subject.should_receive(:frog).with(subject).and_return(:handled)
          subject.should_not_receive(:handler2)
          subject.subscribe(:frog, subject.method(:handler2))
          subject.publish(:frog).should == :handled
        end

        it "should pass the object as the first parameter" do
          subject.should_receive(:handler).with(subject)
          subject.subscribe(:frog, subject.method(:handler))
          subject.publish :frog
        end

        it "should call all the handlers, once each" do
          subject.should_receive(:handler1).with(subject)
          subject.should_receive(:handler2).with(subject)
          subject.subscribe(:frog, subject.method(:handler1))
          subject.subscribe(:frog, subject.method(:handler2))
          subject.publish(:frog).should be_nil
        end

        it "should pass parameters passed to it" do
          subject.should_receive(:handler).with(subject, 1, 2)
          subject.subscribe(:frog, subject.method(:handler))
          subject.publish(:frog, 1, 2).should be_nil
        end

        it "should do nothing if the subject is disabled" do
          subject.should_receive(:enabled?).and_return(false)
          subject.should_not_receive(:handler)
          subject.subscribe(:frog, subject.method(:handler))
          subject.publish(:frog, 1, 2).should be_nil
        end

        it "should act normally if the subject is enabled" do
          subject.should_receive(:enabled?).and_return(true)
          subject.should_receive(:handler)
          subject.subscribe(:frog, subject.method(:handler))
          subject.publish(:frog, 1, 2).should be_nil
        end

        it "should only call the handlers requested" do
          Test.event :fish

          subject.should_receive(:handler1).with(subject)
          subject.should_not_receive(:handler2)
          subject.subscribe(:frog, subject.method(:handler1))
          subject.subscribe(:fish, subject.method(:handler2))
          subject.publish(:frog).should be_nil
        end

        it "should automatically call a method on the publisher if it exists" do
          subject.should_receive(:frog).with(subject)
          subject.publish(:frog).should be_nil
        end

        it "should fail if the event name isn't handled by this object" do
          ->{ subject.publish(:unhandled_event) }.should raise_error ArgumentError
        end
      end
    end
  end
end


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#include <stdint.h>
#include <stdbool.h>
#include <board.h>
#include <sysclk.h>
#include <string.h>
#include <unit_test/suite.h>
#include <stdio_serial.h>
#include <twi.h>
#include <conf_test.h>
#include <conf_board.h>
#include <conf_example.h>
#include "FreeRTOS.h"
#include "task.h"
#include "freertos_twi_master.h"
#include "at24cxx.h"

/*-----------------------------------------------------------*/

/* Clock speed to use. */
#define TWI_CLOCK_HZ                    400000

/* The size of the EEPROM in bytes. */
#define TOTAL_EEPROM_SIZE               65536

/* The size of each page in the EEPROM. */
#define PAGE_SIZE                       128

/* The maximum time the EEPROM takes to commit its RAM buffer. */
#define INTERNAL_WRITE_DELAY            (7 / portTICK_RATE_MS)

/*-----------------------------------------------------------*/

/**
 * \mainpage
 *
 * \section intro Introduction
 * This is the unit test application for the FreeRTOS TWI Interface Layer.
 * It consists of test cases for the following functionality:
 * - Data read/write on TWI bus using FreeRTOS Interface Layer
 *
 * \section files Main Files
 * - \ref twi_unit_tests.c
 * - \ref FreeRTOSConfig.h
 * - \ref conf_board.h
 * - \ref conf_clock.h
 * - \ref conf_example.h
 * - \ref conf_twi_master.h
 * - \ref conf_test.h
 * - \ref conf_usart_serial.h
 *
 * \section device_info Device Info
 * All SAM devices can be used.
 * This example has been tested with the following setup:
 * - sam3x8h_sam3x_ek
 * - sam4c16c_sam4c_ek
 *
 * Note: this unit test takes about 20 seconds to finish.
 *
 * \section compinfo Compilation info
 * This software was written for the GNU GCC and IAR for ARM. Other compilers
 * may or may not work.
 *
 * \section contactinfo Contact Information
 * For further information, visit Atmel.\n
 * Support and FAQ: http://www.atmel.com/design-support/
 */

/* ! \name Unit test configuration */
/* @{ */

/**
 * \def twi_test
 * \brief Init, read and write on AT25 using FreeRTOS TWI Interface Layer.
 */
/* @} */

static void run_twi_test(const struct test_case *test);
static void create_twi_task(Twi *twi_base, uint16_t stack_depth_words,
		unsigned portBASE_TYPE task_priority);
static void twi_eeprom_task(void *pvParameters);
static void write_page_to_eeprom(uint16_t page);
static void read_page_from_eeprom(uint16_t page);

/* A buffer large enough to hold a complete page of data. */
static uint8_t data_buffer[PAGE_SIZE];
/* Used to latch errors found during the execution of the example. */
static uint32_t error_detected = pdFALSE;
/* TWI instance */
static freertos_twi_if freertos_twi;

/*
 * Sets up the hardware ready to run this example.
 */
static void prvSetupHardware(void);

/*
 * FreeRTOS hook (or callback) functions that are defined in this file.
 */
void vApplicationMallocFailedHook(void);
void vApplicationIdleHook(void);
void vApplicationStackOverflowHook(xTaskHandle pxTask,
		signed char *pcTaskName);
void vApplicationTickHook(void);

/**
 * \brief Run TWI unit tests
 */
int main(void)
{
	/* Prepare the hardware to run this demo. */
	prvSetupHardware();

	/* Create the test task. */
	create_twi_task(BOARD_BASE_TWI_EEPROM, 1024, tskIDLE_PRIORITY);

	/* Start the RTOS scheduler. */
	vTaskStartScheduler();

	/* If all is well, the scheduler will now be running, and the following line
	will never be reached.  If the following line does execute, then there was
	insufficient FreeRTOS heap memory available for the idle and/or timer tasks
	to be created.  See the memory management section on the FreeRTOS web site
	for more details. */
	for (;;) {
	}
}

static void create_twi_task(Twi *twi_base, uint16_t stack_depth_words,
		unsigned portBASE_TYPE task_priority)
{
	const freertos_peripheral_options_t blocking_driver_options = {
	NULL,											/* This peripheral does not need a receive buffer, so this parameter is just set to NULL. */
	0,												/* There is no Rx buffer, so the rx buffer size is not used. */
	configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY,	/* The priority used by the TWI interrupts. */
	TWI_I2C_MASTER,									/* Communicating with the EEPROM requires the TWI to be configured as an I2C master. */
	(USE_TX_ACCESS_MUTEX | USE_RX_ACCESS_MUTEX | WAIT_TX_COMPLETE | WAIT_RX_COMPLETE)	/* The blocking driver is to be used, so WAIT_TX_COMPLETE and WAIT_RX_COMPLETE are set. */
};

	/* Initialize the FreeRTOS driver for blocking operation.  The
	peripheral clock is configured in this function call. */
	freertos_twi = freertos_twi_master_init(twi_base,
			&blocking_driver_options);

	/* Check the port was initialized successfully. */
	configASSERT(freertos_twi);

	/* Configure the TWI bus parameters.  Do this after calling
	freertos_twi_master_init(). */
	twi_set_speed(twi_base, TWI_CLOCK_HZ, sysclk_get_cpu_hz());

	/* Create the task as described above. */
	xTaskCreate(twi_eeprom_task, (const signed char *const) "Tx",
			stack_depth_words, (void *) freertos_twi, task_priority,
			NULL);
}

/*-----------------------------------------------------------*/

static void twi_eeprom_task(void *pvParameters)
{
	UNUSED(pvParameters);
	/* Define all the test cases */
	DEFINE_TEST_CASE(twi_test, NULL, run_twi_test, NULL,
			"FreeRTOS TWI init-read-write on EEPROM");

	/* Put test case addresses in an array */
	DEFINE_TEST_ARRAY(twi_tests) = {
		&twi_test,
	};

	/* Define the test suite */
	DEFINE_TEST_SUITE(twi_suite, twi_tests,
			"SAM FreeRTOS TWI Interface Layer test suite");

	/* Run all tests in the test suite */
	test_suite_run(&twi_suite);

	/* Delete task */
	vTaskDelete(NULL);
}

/*-----------------------------------------------------------*/

static void run_twi_test(const struct test_case *test)
{
	portBASE_TYPE page;
	const portBASE_TYPE max_page = TOTAL_EEPROM_SIZE / PAGE_SIZE;
	size_t byte_in_page;
	uint8_t byte_value;

	/* Fill the EEPROM with 0xaa, one page at a time. */
	memset(data_buffer, 0xaa, PAGE_SIZE);
	for (page = 0; page < max_page; page++) {
		write_page_to_eeprom(page);
	}

	/* Check that the data is read back from the EEPROM as 0xaa.  First make
	sure that the buffer contains a value other than 0xaa to be sure that it
	does not coincidentally already hold the expected data. */
	for (page = 0; page < max_page; page++) {
		memset((void *) data_buffer, 0xff, PAGE_SIZE);
		read_page_from_eeprom(page);

		/* Check each byte in the page is as expected. */
		for (byte_in_page = 0; byte_in_page < PAGE_SIZE;
				byte_in_page++) {
			if (data_buffer[byte_in_page] != 0xaa) {
				error_detected = pdTRUE;
			}
		}
	}

	/* Check Test1. */
	test_assert_true(test, error_detected == pdFALSE,
			"Test1: read/write test failed!");

	/* Fill the EEPROM with 0x55, one page at a time. */
	memset(data_buffer, 0x55, PAGE_SIZE);
	for (page = 0; page < max_page; page++) {
		write_page_to_eeprom(page);
	}

	/* Check that the data is read back from the EEPROM as 0x55.  First make
	sure that the buffer contains a value other than 0x55 to be sure that it
	does not coincidentally already hold the expected data. */
	for (page = 0; page < max_page; page++) {
		memset((void *) data_buffer, 0xff, PAGE_SIZE);
		read_page_from_eeprom(page);

		/* Check each byte in the page is as expected. */
		for (byte_in_page = 0; byte_in_page < PAGE_SIZE;
				byte_in_page++) {
			if (data_buffer[byte_in_page] != 0x55) {
				error_detected = pdTRUE;
			}
		}
	}

	/* Check Test2. */
	test_assert_true(test, error_detected == pdFALSE,
			"Test2: read/write test failed!");

	/* Fill the EEPROM using different values in each position (the value
	 * will wrap). */
	byte_value = 0;
	for (page = 0; page < max_page; page++) {
		for (byte_in_page = 0; byte_in_page < PAGE_SIZE;
				byte_in_page++) {
			data_buffer[byte_in_page] = byte_value;
			byte_value++;
		}

		write_page_to_eeprom(page);
	}

	/* Check each byte read back matches that expected once more. */
	byte_value = 0;
	for (page = 0; page < max_page; page++) {
		memset((void *) data_buffer, 0x00, PAGE_SIZE);
		read_page_from_eeprom(page);

		/* Check each byte in the page is as expected. */
		for (byte_in_page = 0; byte_in_page < PAGE_SIZE;
				byte_in_page++) {
			if (data_buffer[byte_in_page] != byte_value) {
				error_detected = pdTRUE;
			}

			byte_value++;
		}
	}

	/* Check Test3. */
	test_assert_true(test, error_detected == pdFALSE,
			"Test3: read/write test failed!");
}

/*-----------------------------------------------------------*/

static void write_page_to_eeprom(uint16_t page)
{
	twi_packet_t write_parameters;
	uint16_t calculated_address;
	const portTickType max_block_time_ticks = 200UL / portTICK_RATE_MS;

	write_parameters.chip = BOARD_AT24C_ADDRESS;
	write_parameters.buffer = data_buffer;
	write_parameters.length = PAGE_SIZE;

	/* The internal EEPROM address being written to is calculated from the page
	number. */
	calculated_address = page * PAGE_SIZE;
	write_parameters.addr[0] = (uint8_t) ((calculated_address >> 8) & 0xff);
	write_parameters.addr[1] = (uint8_t) (calculated_address & 0xff);
	write_parameters.addr_length = 2;

	/* The blocking API is being used.  Other tasks will execute while the
	write operation is in progress. */
	if (freertos_twi_write_packet(freertos_twi, &write_parameters,
			max_block_time_ticks) != STATUS_OK) {
		error_detected = pdTRUE;
	}

	/* Wait for the EEPROM to complete programming its internal memory.
	Note this is a very crude way of doing this, the EEPROM status
	register could be polled to determine when it was finished. */
	vTaskDelay(INTERNAL_WRITE_DELAY);
}

/*-----------------------------------------------------------*/

static void read_page_from_eeprom(uint16_t page)
{
	twi_packet_t read_parameters;
	uint16_t calculated_address;
	const portTickType max_block_time_ticks = 200UL / portTICK_RATE_MS;

	read_parameters.chip = BOARD_AT24C_ADDRESS;
	read_parameters.buffer = data_buffer;
	read_parameters.length = PAGE_SIZE;

	/* The internal EEPROM address being read from is calculated from the page
	number. */
	calculated_address = page * PAGE_SIZE;
	read_parameters.addr[0] = (uint8_t) ((calculated_address >> 8) & 0xff);
	read_parameters.addr[1] = (uint8_t) (calculated_address & 0xff);
	read_parameters.addr_length = 2;

	/* The blocking API is being used.  Other tasks will execute while the
	 * read operation is in progress. */
	if (freertos_twi_read_packet(freertos_twi, &read_parameters,
			max_block_time_ticks) != STATUS_OK) {
		error_detected = pdTRUE;
	}
}

/*-----------------------------------------------------------*/

static void prvSetupHardware(void)
{
	const usart_serial_options_t usart_serial_options = {
		.baudrate   = CONF_TEST_BAUDRATE,
		.paritytype = CONF_TEST_PARITY
	};

	/* ASF function to setup clocking. */
	sysclk_init();

	/* Ensure all priority bits are assigned as preemption priority bits. */
	NVIC_SetPriorityGrouping(0);

	/* Atmel library function to setup for the evaluation kit being used. */
	board_init();
	/* Reset TWI EEPROM state to release TWI */
	at24cxx_reset();

	/* Enable unit test output peripheral. */
	sysclk_enable_peripheral_clock(CONSOLE_UART_ID);
	stdio_serial_init(CONF_TEST_USART, &usart_serial_options);
}

/*-----------------------------------------------------------*/

void vApplicationMallocFailedHook(void)
{
	/* vApplicationMallocFailedHook() will only be called if
	configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h.  It is a hook
	function that will get called if a call to pvPortMalloc() fails.
	pvPortMalloc() is called internally by the kernel whenever a task, queue,
	timer or semaphore is created.  It is also called by various parts of the
	demo application.  If heap_1.c or heap_2.c are used, then the size of the
	heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
	FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
	to query the size of free heap space that remains (although it does not
	provide information on how the remaining heap might be fragmented). */
	taskDISABLE_INTERRUPTS();
	for (;;) {
	}
}

/*-----------------------------------------------------------*/

void vApplicationIdleHook(void)
{
	/* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set
	to 1 in FreeRTOSConfig.h.  It will be called on each iteration of the idle
	task.  It is essential that code added to this hook function never attempts
	to block in any way (for example, call xQueueReceive() with a block time
	specified, or call vTaskDelay()).  If the application makes use of the
	vTaskDelete() API function (as this demo application does) then it is also
	important that vApplicationIdleHook() is permitted to return to its calling
	function, because it is the responsibility of the idle task to clean up
	memory allocated by the kernel to any task that has since been deleted. */
}
/*-----------------------------------------------------------*/

void vApplicationStackOverflowHook(xTaskHandle pxTask,
		signed char *pcTaskName)
{
	(void) pcTaskName;
	(void) pxTask;

	/* Run time stack overflow checking is performed if
	configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
	function is called if a stack overflow is detected. */
	taskDISABLE_INTERRUPTS();
	for (;;) {
	}
}

/*-----------------------------------------------------------*/

void vApplicationTickHook(void)
{
	/* This function will be called by each tick interrupt if
	configUSE_TICK_HOOK is set to 1 in FreeRTOSConfig.h.  User code can be
	added here, but the tick hook is called from an interrupt context, so
	code must not attempt to block, and only the interrupt safe FreeRTOS API
	functions can be used (those that end in FromISR()). */
}


text:
class VendorObject < KFSDataObject

  include AddressLinesMixin
  include PhoneNumberLinesMixin
  include ContactLinesMixin
  include ContractLinesMixin
  include SearchAliasLinesMixin

  DOC_INFO = { label: 'Vendor', type_code: 'PVEN', transactional?: false, action_wait_time: 30 }

  attr_accessor :vendor_number, :vendor_name, :vendor_last_name, :vendor_first_name,
                :vendor_type, :foreign, :tax_number,
                :tax_number_type_fein, :tax_number_type_ssn, :tax_number_type_none,
                :ownership, :w9_received

  def defaults
    super.merge({
      vendor_type:         'PO - PURCHASE ORDER',
      vendor_name:         'Keith, inc',
      foreign:             'No',
      tax_number:          random_tax_number,
      tax_number_type_ssn: :set, # If this default is changed, you must update #sync_tax_number_type
      ownership:           'INDIVIDUAL/SOLE PROPRIETOR',
      w9_received:         'Yes'
    }).merge(default_addresses)
      .merge(default_contacts)
      .merge(default_contracts)
      .merge(default_phone_numbers)
      .merge(default_search_aliases)
      .merge(get_aft_parameter_values_as_hash(ParameterConstants::DEFAULTS_FOR_VENDOR))
  end

  def build
    visit(MainPage).vendor
    on(VendorLookupPage).create_new
    on VendorPage do |page|
      page.expand_all
      page.description.focus
      page.alert.ok if page.alert.exists? # Because, y'know, sometimes it doesn't actually come up...

      sync_tax_number_type

      fill_out page, :description,
                     :vendor_name, :vendor_last_name, :vendor_first_name,
                     :vendor_type, :foreign, :tax_number,
                     :tax_number_type_fein, :tax_number_type_ssn, :tax_number_type_none,
                     :ownership, :w9_received
    end
  end

  def absorb!(target=:new)
    super
    on(VendorPage).expand_all
    case target
      when :new; update_options(pull_new_vendor_data)
      when :old; update_options(pull_old_vendor_data)
    end

    update_line_objects_from_page!(target)
  end

  # @return [Hash] The return values of attributes for the old Vendor
  def pull_old_vendor_data
    pulled_vendor = Hash.new
    on VendorPage do |vp|
      pulled_vendor = {
        vendor_number: vp.old_vendor_number,
        vendor_name:   vp.old_vendor_name.empty? ? "#{vp.old_vendor_last_name}, #{vp.old_vendor_first_name}" : vp.old_vendor_name,
        vendor_last_name:  vp.old_vendor_last_name,
        vendor_first_name: vp.old_vendor_first_name,
        vendor_type: vp.old_vendor_type,
        foreign:     vp.old_foreign,
        tax_number:  vp.old_tax_number,
        tax_number_type_fein: vp.old_tax_number_type_fein,
        tax_number_type_ssn:  vp.old_tax_number_type_ssn,
        tax_number_type_none: vp.old_tax_number_type_none,
        ownership:   vp.old_ownership,
        w9_received: vp.old_w9_received
      }
    end
    pulled_vendor.merge(pull_vendor_extended_data(:old))
  end

  # @return [Hash] The return values of attributes for the new Vendor
  def pull_new_vendor_data
    pulled_vendor = Hash.new
    on VendorPage do |vp|
      pulled_vendor = {
          vendor_number: vp.new_vendor_number,
          vendor_name: vp.new_vendor_name.value.strip,
          vendor_last_name:  vp.new_vendor_last_name.value.strip,
          vendor_first_name: vp.new_vendor_first_name.value.strip,
          vendor_type: vp.new_vendor_type.value.strip,
          foreign:     vp.new_foreign.selected_options.first.text.strip,
          tax_number:  vp.new_tax_number.value.strip,
          tax_number_type_fein: vp.new_tax_number_type_fein.value.strip,
          tax_number_type_ssn:  vp.new_tax_number_type_ssn.value.strip,
          tax_number_type_none: vp.new_tax_number_type_none.value.strip,
          ownership:   vp.new_ownership.selected_options.first.text.strip,
          w9_received: vp.new_w9_received.selected_options.first.text.strip
      }
    end
    pulled_vendor.merge(pull_vendor_extended_data(:new))
  end

  # @return [Hash] The return values of extended attributes for the old Vendor
  # @param [Symbol] target The set of Vendor data to pull in
  def pull_vendor_extended_data(target=:new)
    Hash.new
  end

  private

  # We want the tax number types to either be :set or nil but only one can
  # be :set at a time since this is a radio. This should update the other two
  # when one is set.
  def sync_tax_number_type
    if @tax_number_type_fein == :set
      @tax_number_type_ssn = nil
      @tax_number_type_none = nil
    elsif @tax_number_type_ssn == :set
      @tax_number_type_fein = nil
      @tax_number_type_none = nil
    elsif @tax_number_type_none == :set
      @tax_number_type_ssn = nil
      @tax_number_type_fein = nil
    end
  end

end


text:
namespace OneSky.CSharp.Json
{
    public interface IOrderTaskBase
    {
        int Id { get; }

        ILocale FromLanguage { get; }

        ILocale ToLanguage { get; }
    }
}