text:
import {inject} from 'aurelia-framework';
import _ from 'lodash';
import PouchDB from 'pouchdb';

const VALID_TYPES = [
  'strike'
];

/**
 * Service for persisting data cards using PouchDB.
 */
@inject(PouchDB)
export class DataCardService {
  static validateType(type) {
    return _.includes(VALID_TYPES, type);
  }

  constructor(pouchDb) {
    this.db = new pouchDb('data-card-store');
  }

  /**
   * Gets all data cards off of the store.
   *
   * @returns {Promise} - A promise that resolves with an {Array} of all data cards.
   */
  all() {
    return new Promise((resolve, reject) => {
      this.db.allDocs({
          include_docs: true
        })
        .then(result => resolve(result))
        .catch(error => reject(error));
    });
  }

  /**
   * Retrieves all data cards of a specific type.
   *
   * @param {string} type - The specific type of data card to retrieve.
   * @returns {Promise} - A promise that resolves with a list containing all data cards of the requested type.
   */
  allType(type) {
    return new Promise((resolve, reject) => {
      if (!DataCardService.validateType(type)) {
        reject('Invalid type.');
      }

      this.db.allDocs({
          include_docs: true,
          startKey: `${type}_`,
          endKey: `${type}_\uffff`
        })
        .then(result => resolve(result))
        .catch(error => reject(error));
    })
  }

  /**
   * Creates a new data card on the store.
   *
   * @param {string} title - The title of the data card.
   * @param {string} type - The type of the data card.
   * @param {Object} fields - The fields that the data card has, and their values.
   * @returns {Promise} - A promise that resolves when the new document is created successfully.
   */
  create(title, type, fields) {
    return new Promise((resolve, reject) => {
      if (!DataCardService.validateType(type)) {
        reject('Invalid type.');
      }

      let id = _.uniqueId(`${type}_`);

      this.db.put({
          _id: id,
          title: title,
          type: type,
          fields: fields
        })
        .then(response => resolve(response))
        .catch(error => reject(error));
    });
  }

  /**
   * Searches the store for a specific data card and returns it.
   *
   * @param id - The ID of the data card document.
   * @returns {Promise} - A promise that resolves with the desired document.
   */
  find(id) {
    return new Promise((resolve, reject) => {
      this.db.get(id)
        .then(result => resolve(result))
        .catch(error => reject(error));
    });
  }

  /**
   * Removes a data card from the store permanently.
   *
   * @param dataCard - The data card object to remove.
   * @returns {Promise} - A promise that resolves once the task is complete.
   */
  remove(dataCard) {
    return new Promise((resolve, reject) => {
      this.db.remove(dataCard)
        .then(result => resolve(result))
        .catch(error => reject(error));
    });
  }

  /**
   * Updates a data card on the store.
   *
   * @param dataCard - The data card object with updates to store.
   * @returns {Promise} - A promise that resolves once the task is complete and returns the updated ID & Revision.
   */
  update(dataCard) {
    return new Promise((resolve, reject) => {
      if (!DataCardService.validateType(dataCard.type)) {
        reject('Invalid type.');
      }

      this.db.put(dataCard)
        .then(response => resolve(response))
        .catch(error => reject(error));
    });
  }
}


text:
namespace LearningKit.Models.Checkout
{
    /// <summary>
    /// Model for a fictitious payment response.
    /// </summary>
    public class ResponseModel
    {
        public int InvoiceNo { get; set; }
        public string Message { get; set; }
        public bool Completed { get; set; }
        public string TransactionID { get; set; }
        public string ResponseCode { get; set; }
        public decimal Amount { get; set; }
        public bool Approved { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Spree::Promotion.class_eval do
  has_one :gift_card, class_name: 'Spree::GiftCard'
end


text:
(function() {
  'use strict';

  describe('SSL Certificates Step', function() {
    var certs = [{
      id: '1',
      name: 'foo',
      expiration: '2015-03-26T21:10:45.417835'
    }];

    beforeEach(module('horizon.framework.util.i18n'));
    beforeEach(module('horizon.dashboard.project.lbaasv2'));

    describe('CertificatesController', function() {
      var ctrl, scope;

      beforeEach(inject(function($controller) {
        scope = {
          model: {
            spec: {
              certificates: []
            },
            certificates: certs
          }
        };
        ctrl = $controller('CertificatesController', { $scope: scope });
      }));

      it('should define transfer table properties', function() {
        expect(ctrl.tableData).toBeDefined();
        expect(ctrl.tableLimits).toBeDefined();
        expect(ctrl.tableHelp).toBeDefined();
      });

      it('should have available certificates', function() {
        expect(ctrl.tableData.available).toBeDefined();
        expect(ctrl.tableData.available.length).toBe(1);
        expect(ctrl.tableData.available[0].id).toBe('1');
      });

      it('should not have allocated members', function() {
        expect(ctrl.tableData.allocated).toEqual([]);
      });

      it('should allow adding multiple certificates', function() {
        expect(ctrl.tableLimits.maxAllocation).toBe(-1);
      });

    });

  });
})();


text:
source ./test-functions.sh
install_service
echo 'PID_FOLDER=/does/not/exist' > /test-service/spring-boot-app.conf
start_service
await_app
curl -s http://127.0.0.1:8080/


text:
title: Round About
redirect_to:
  - http://ironsummitmedia.github.io/startbootstrap-round-about/
---


text:
package com.amazonaws.services.ec2.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * SubnetAssociation StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SubnetAssociationStaxUnmarshaller implements Unmarshaller<SubnetAssociation, StaxUnmarshallerContext> {

    public SubnetAssociation unmarshall(StaxUnmarshallerContext context) throws Exception {
        SubnetAssociation subnetAssociation = new SubnetAssociation();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return subnetAssociation;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("subnetId", targetDepth)) {
                    subnetAssociation.setSubnetId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("state", targetDepth)) {
                    subnetAssociation.setState(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return subnetAssociation;
                }
            }
        }
    }

    private static SubnetAssociationStaxUnmarshaller instance;

    public static SubnetAssociationStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new SubnetAssociationStaxUnmarshaller();
        return instance;
    }
}


text:
<meta charset="UTF-8">
<title>UsageFrequencyPattern.searchExpr - biomedicus-core</title>
<link rel="stylesheet" href="../../../style.css">

biomedicus-core / edu.umn.biomedicus.sh / UsageFrequencyPattern / searchExpr

searchExpr

val searchExpr: SearchExpr


text:
"""
CSCI-603: Lab 3(week 3)
Section 03
Author: Pavan Prabahakar Bhat (pxb8715@rit.edu)
        Vinayak Marali (vkm7895@rit.edu)

This is a program is to draw a tree using recursion.
"""

#IMPORTS CALLED HERE
import turtle
import random

#validation for recursion depth
#flag = True
#while(flag):
recursionDepth = input("Please enter a value for the depth of recursion ")
if(recursionDepth.isnumeric()):
    # A COPY OF THE RECURSION DEPTH
    recursionDepth = int(recursionDepth)
    layers = recursionDepth
#   flag = False
else:
    print("Please enter a valid integer number above zero!")
    # will exit from here as all the validations have failed
    exit()

BRANCH_ANGLE = random.randint(20, 40)# causes right angle between two branches

#validation for overallSize value

# flag1 = True
# while(flag1):
overallSize = input("Please enter the value of the overall expected height of the tree ")
if(overallSize.isnumeric() and int(overallSize) > 0):
    overallSize = int(overallSize)
# flag1 = False
else:
    print("Please enter a valid positive integer!")
    exit()

# as the overallSize has to be approximately equal to the exact height
size = overallSize/2 # used as the size of trunk for the tree
# a copy of the size of trunk
trunkLength = size

#validation for bushiness value

bushiness = input("Please enter a floating point number between 0 and 1 to determine the bushiness of the tree: ")
dotCount = 0 #Count of the number of decimal point
numCount = 0 #Count of the numbers in the input string
notNum = 0 #Count of the  non numeric characters in the input string
numPos = 0 #Index of last number in the input string
decimalPos = 0 #Index of decimal point in the input string
for inputCharacter in bushiness:
    if bushiness[:2] == "0." or bushiness[:2] == "1.":
        if inputCharacter >= "0" and inputCharacter <= "9":
            numCount = numCount +1
            numPos = bushiness.index(inputCharacter)
        elif inputCharacter == ".":
            dotCount = dotCount + 1
            decimalPos = bushiness.index(inputCharacter)
    else:
        notNum = notNum + 1

if notNum > 0:
    print("Enter a valid float number between 0 to 1 eg: 0.5")
    exit()
elif dotCount == 1 and numPos >= decimalPos :
    if numCount == len(bushiness) -1:
        bushiness = float(bushiness)
elif dotCount == 0 and numPos >= decimalPos:
    if numCount == len(bushiness):
        bushiness = float(bushiness)
else:
    print("Enter a valid float number between 0 to 1 eg: 0.5")
    exit()

if(bushiness):
    # randomly generates the number of sub-branches depending on the bushiness value
    noOfSegments = random.randint(1, int(10*bushiness))
else:
    noOfSegments = 0

#validation for leafiness value

leafiness = input("Please enter a floating point number between 0 and 1 to determine the leafiness of the tree: ")
dotCount = 0 #Count of the number of decimal point
numCount = 0 #Count of the numbers in the input string
notNum = 0 #Count of the  non numeric characters in the input string
numPos = 0 #Index of last number in the input string
decimalPos = 0 #Index of decimal point in the input string
for inputCharacter in leafiness:
    if leafiness[:2] == "0." or leafiness[:2]=="1.":
        if inputCharacter >="0" and inputCharacter <="9":
            numCount = numCount +1
            numPos = leafiness.index(inputCharacter)
        elif inputCharacter==".":
            dotCount = dotCount + 1
            decimalPos = leafiness.index(inputCharacter)
    else:
        notNum = notNum + 1

if notNum > 0:
    print("Enter a valid float number between 0 to 1 eg: 0.5")
    exit()
elif dotCount == 1 and numPos>=decimalPos :
    if numCount == len(leafiness) -1:
        leafiness = float(leafiness)
elif dotCount == 0 and numPos>=decimalPos:
    if numCount == len(leafiness):
        leafiness = float(leafiness)
else:
    print("Enter a valid float number between 0 to 1 eg: 0.5")
    exit()

if(leafiness):
     # randomly generates the number of leaves depending on the leafiness value
    noOfLeafs = random.randint(1, int(50*leafiness))
else:
    noOfLeafs = 0

def drawTree( aTurtle, recursionDepth, size ):
    """ Recursively draw a tree.

        :param aTurtle: the turtle to be used to do the drawing

        :param size: positive integer
                    length of tree trunk

        :pre: turtle is at base of tree,
              turtle is facing along trunk of tree,
              turtle is pen-down.

        :post: turtle is at base of tree,
               turtle is facing along trunk of tree,
               turtle is pen-down.
    """
    aTurtle.pendown()
    if recursionDepth == 0:
        # base case: draws the leaves on the tree
        leafLength = trunkLength / 10
        for _ in range(noOfLeafs):
            aTurtle.color("Green")
            aTurtle.fd(leafLength)
            aTurtle.backward(leafLength)
            aTurtle.rt(3)
            aTurtle.color("Black")
        aTurtle.lt(3*noOfLeafs) # required to shift an angle at a relative initial position on the final twig
    elif(recursionDepth < layers):
        # recursive case: draws the trunk and the sub-branches
        aTurtle.forward( size )
        aTurtle.left( BRANCH_ANGLE )
        for _ in range(noOfSegments):
            segmentPosition = random.randint(0,round(size/2)) # chooses a random position to place the sub-branch
            aTurtle.fd(segmentPosition)
            direction = random.randint(0,1) # randomizes the direction in which the sub-branch is drawn
            if(direction == 0):
                aTurtle.lt(BRANCH_ANGLE)
            else:
                aTurtle.rt(BRANCH_ANGLE)
            aTurtle.fd(size/4) # allocates the size to the sub-branch drawn which is varying
            aTurtle.backward( size/4 )
            # required to come back to a relative position from where the branch began
            if(direction == 0):
                aTurtle.rt(BRANCH_ANGLE)
            else:
                aTurtle.lt(BRANCH_ANGLE)
            aTurtle.backward(segmentPosition)
        # required for recursing on the right side
        drawTree( aTurtle, recursionDepth - 1, size / 2 )
        aTurtle.right( 2*BRANCH_ANGLE )
        for _ in range(noOfSegments):
            segmentPosition = random.randint(0,round(size/2))
            aTurtle.fd(segmentPosition)
            direction = random.randint(0,1)
            if(direction == 0):
                aTurtle.lt(BRANCH_ANGLE)
            else:
                aTurtle.rt(BRANCH_ANGLE)
            aTurtle.fd(size/4)
            aTurtle.backward( size/4 )
            if(direction == 0):
                aTurtle.rt(BRANCH_ANGLE)
            else:
                aTurtle.lt(BRANCH_ANGLE)
            aTurtle.backward(segmentPosition)
        drawTree( aTurtle, recursionDepth - 1, size / 2 )
        aTurtle.left( BRANCH_ANGLE )
        aTurtle.backward( size )
    elif(recursionDepth == layers):
     # recursive case: Draws the trunk and the sub-branches
        aTurtle.forward( size )
     # generates a random number of branches between 1 and 4
        randomBranch = random.randint(1,4)
     #required to generate random branch angles
        randomFactor = random.randint(1,2)
        aTurtle.rt(2 * BRANCH_ANGLE)
        while randomBranch > 0:
            aTurtle.left( BRANCH_ANGLE )
            drawTree( aTurtle, recursionDepth - 1, size / 2 )
            aTurtle.right(randomFactor * BRANCH_ANGLE )
            drawTree( aTurtle, recursionDepth - 1, size / 2 )
            aTurtle.left( BRANCH_ANGLE )
            randomBranch = randomBranch -1
        aTurtle.setheading(90)
        aTurtle.backward( trunkLength )

MARGIN = 2 # Space at edges of canvas
PEN_SIZE = 2 # Thickness of turtle's pen

def initWorld( size ):
    """ Initialize the drawing area.

        :param size: integer
                     length of tree trunk to draw
                     (not currently used)
        :pre: size > 0
        :post: coordinate system goes from
               (-2*size, -2*size) at lower-left
                 to (2*size, 2*size) at upper-right.
    """

    turtle.setup( 600, 600 )

    # The lines below are removed because they keep one from
    # seeing the difference that the size parameter makes
    # in the perceived size of the tree.
    #
    turtle.setworldcoordinates( -2*size - MARGIN, -2*size - MARGIN, \
                                2*size + MARGIN, 2*size + MARGIN)

def initTurtle( aTurtle ):
    """ Set up the turtle by establishing the drawTree
        function's pre-conditions.

        :post: aTurtle is at origin ( center ),
               aTurtle is facing North,
               aTurtle's pen is down, size PEN_SIZE, aTurtle's speed is set to 0
    """

    aTurtle.home()  # turtle is at origin, facing east, pen-down
    aTurtle.left( 90 )  # turtle is facing North
    aTurtle.down()  # turtle's pen is put down
    aTurtle.pensize( PEN_SIZE )
    aTurtle.speed(0)

def main():
    """ Print a message, initialize the world,
        draw an instance of the recursive tree, and wait for ENTER
        t: turtle
        recursionDepth: depth of recursion
        size: positive integer
                    length of tree trunk
    """
    print("Drawing recursive tree with", (recursionDepth, size))
    initWorld( size )
    t = turtle.Turtle()
    initTurtle( t )
    drawTree( t, recursionDepth, size )
    input("Hit enter to exit...")

# calls the main function
if __name__ == '__main__':
    main()


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.jenkins-ci.plugins</groupId>
        <artifactId>build-monitor</artifactId>
        <version>1.9-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>build-monitor-acceptance</artifactId>
    <packaging>jar</packaging>

    <name>Build Monitor Acceptance Tests</name>

    <properties>
        <encoding>UTF-8</encoding>
        <serenity.version>1.1.29-rc.1</serenity.version>
        <aether.version>1.0.0.v20140518</aether.version>

        <webdriver.driver>firefox</webdriver.driver>
        <browserstack.url></browserstack.url>
    </properties>

    <profiles>
        <profile>
            <id>remote-browser</id>

            <activation>
                <property><name>env.BROWSERSTACK_USERNAME</name></property>
                <activeByDefault>false</activeByDefault>
            </activation>
            <properties>
                <browserstack.url>http://${env.BROWSERSTACK_USERNAME}:${env.BROWSERSTACK_AUTOMATION_KEY}@hub.browserstack.com/wd/hub</browserstack.url>
            </properties>

            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-enforcer-plugin</artifactId>
                        <version>1.4.1</version>
                        <executions>
                            <execution>
                                <id>ensure-browserstack-credentials-present</id>
                                <goals><goal>enforce</goal></goals>
                                <configuration>
                                    <rules>
                                        <requireEnvironmentVariable>
                                            <variableName>BROWSERSTACK_USERNAME</variableName>
                                            <message>${line.separator}BROWSERSTACK_USERNAME needs to be set to your BrowserStack username${line.separator}</message>
                                        </requireEnvironmentVariable>
                                        <requireEnvironmentVariable>
                                            <variableName>BROWSERSTACK_AUTOMATION_KEY</variableName>
                                            <message>${line.separator}BROWSERSTACK_AUTOMATION_KEY needs to be set${line.separator}</message>
                                        </requireEnvironmentVariable>
                                    </rules>
                                    <fail>true</fail>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.jenkins-ci.main</groupId>
            <artifactId>cli</artifactId>
            <version>${jenkins.version}</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-api</artifactId>
            <version>${aether.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-spi</artifactId>
            <version>${aether.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-util</artifactId>
            <version>${aether.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-impl</artifactId>
            <version>${aether.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-connector-basic</artifactId>
            <version>${aether.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-transport-file</artifactId>
            <version>${aether.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-transport-http</artifactId>
            <version>${aether.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-aether-provider</artifactId>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.4</version>
        </dependency>

        <!-- serenity -->
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-core</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-screenplay</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>browse-the-web</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-junit</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- / serenity -->

        <dependency>
            <groupId>org.jdeferred</groupId>
            <artifactId>jdeferred-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/features/*Test.java</include>
                        <include>**/features/*Should*.java</include>
                    </includes>
                    <argLine>-Xmx512m</argLine>
                    <systemPropertyVariables>
                        <webdriver.driver>${webdriver.driver}</webdriver.driver>
                        <browserstack.url>${browserstack.url}</browserstack.url>
                        <project.root>${project.parent.basedir}/</project.root>
                    </systemPropertyVariables>
                    <environmentVariables>
                        <!-- todo: remove when the acceptance-test-harness is gone -->
                        <BROWSER>htmlunit</BROWSER>
                        <JENKINS_VERSION>1.609.3</JENKINS_VERSION>
                        <PLUGINS_DIR>${project.parent.basedir}/build-monitor-plugin/target</PLUGINS_DIR>
                        <NEVER_REPLACE_EXISTING_PLUGINS>false</NEVER_REPLACE_EXISTING_PLUGINS>
                    </environmentVariables>
                    <forkCount>1C</forkCount>
                    <reuseForks>false</reuseForks>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>
                <artifactId>serenity-maven-plugin</artifactId>
                <version>${serenity.version}</version>
                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
package io.oasp.gastronomy.restaurant.salesmanagement.logic.api.to;

import io.oasp.gastronomy.restaurant.general.common.api.to.SearchCriteriaTo;
import io.oasp.gastronomy.restaurant.salesmanagement.common.api.datatype.OrderState;

/**
 * This is the {@link io.oasp.gastronomy.restaurant.general.common.api.to.SearchCriteriaTo search criteria} {@link net.sf.mmm.util.transferobject.api.TransferObject TO}
 * used to find an {@link io.oasp.gastronomy.restaurant.salesmanagement.common.api.Order}.
 *
 * @author hohwille
 */
public class OrderSearchCriteriaTo extends SearchCriteriaTo {

  /** UID for serialization. */
  private static final long serialVersionUID = 1L;

  private OrderState state;

  private Long tableId;

  /**
   * The constructor.
   */
  public OrderSearchCriteriaTo() {

    super();
  }

  /**
   * @return state
   */
  public OrderState getState() {

    return this.state;
  }

  /**
   * @param state the state to set
   */
  public void setState(OrderState state) {

    this.state = state;
  }

  /**
   * @return tableId
   */
  public Long getTableId() {

    return this.tableId;
  }

  /**
   * @param tableId the tableId to set
   */
  public void setTableId(Long tableId) {

    this.tableId = tableId;
  }

}


text:
<?php

namespace Commercetools\Core\IntegrationTests\ProductSelection;

use Commercetools\Core\Helper\Uuid;
use Commercetools\Core\IntegrationTests\ResourceFixture;
use Commercetools\Core\Client\ApiClient;
use Commercetools\Core\Model\Common\LocalizedString;
use Commercetools\Core\Model\ProductSelection\ProductSelection;
use Commercetools\Core\Model\ProductSelection\ProductSelectionDraft;
use Commercetools\Core\Request\ProductSelections\ProductSelectionCreateRequest;
use Commercetools\Core\Request\ProductSelections\ProductSelectionDeleteRequest;

class ProductSelectionFixture extends ResourceFixture
{
    const CREATE_REQUEST_TYPE = ProductSelectionCreateRequest::class;
    const DELETE_REQUEST_TYPE = ProductSelectionDeleteRequest::class;
    const RAND_MAX = 10000;

    final public static function uniqueProductSelectionString()
    {
        return 'test-' . Uuid::uuidv4();
    }

    final public static function defaultProductSelectionDraftFunction()
    {
        $uniqueProductSelectionString = self::uniqueProductSelectionString();
        $draft = ProductSelectionDraft::of()->setKey($uniqueProductSelectionString)->setName(
            LocalizedString::ofLangAndText('en', 'test-' . $uniqueProductSelectionString . '-name')
        );

        return $draft;
    }

    final public static function defaultProductSelectionDraftBuilderFunction(ProductSelectionDraft $draft)
    {
        return $draft;
    }

    final public static function defaultProductSelectionCreateFunction(ApiClient $client, ProductSelectionDraft $draft)
    {
        return parent::defaultCreateFunction($client, self::CREATE_REQUEST_TYPE, $draft);
    }

    final public static function defaultProductSelectionDeleteFunction(ApiClient $client, ProductSelection $resource)
    {
        return parent::defaultDeleteFunction($client, self::DELETE_REQUEST_TYPE, $resource);
    }

    final public static function withUpdateableDraftProductSelection(
        ApiClient $client,
        callable $draftBuilderFunction,
        callable $assertFunction,
        callable $createFunction = null,
        callable $deleteFunction = null,
        callable $draftFunction = null
    ) {
        if ($draftFunction == null) {
            $draftFunction = [__CLASS__, 'defaultProductSelectionDraftFunction'];
        }
        if ($createFunction == null) {
            $createFunction = [__CLASS__, 'defaultProductSelectionCreateFunction'];
        }
        if ($deleteFunction == null) {
            $deleteFunction = [__CLASS__, 'defaultProductSelectionDeleteFunction'];
        }

        parent::withUpdateableDraftResource(
            $client,
            $draftBuilderFunction,
            $assertFunction,
            $createFunction,
            $deleteFunction,
            $draftFunction
        );
    }

    final public static function withDraftProductSelection(
        ApiClient $client,
        callable $draftBuilderFunction,
        callable $assertFunction,
        callable $createFunction = null,
        callable $deleteFunction = null,
        callable $draftFunction = null
    ) {
        if ($draftFunction == null) {
            $draftFunction = [__CLASS__, 'defaultProductSelectionDraftFunction'];
        }
        if ($createFunction == null) {
            $createFunction = [__CLASS__, 'defaultProductSelectionCreateFunction'];
        }
        if ($deleteFunction == null) {
            $deleteFunction = [__CLASS__, 'defaultProductSelectionDeleteFunction'];
        }

        parent::withDraftResource(
            $client,
            $draftBuilderFunction,
            $assertFunction,
            $createFunction,
            $deleteFunction,
            $draftFunction
        );
    }

    final public static function withProductSelection(
        ApiClient $client,
        callable $assertFunction,
        callable $createFunction = null,
        callable $deleteFunction = null,
        callable $draftFunction = null
    ) {
        self::withDraftProductSelection(
            $client,
            [__CLASS__, 'defaultProductSelectionDraftBuilderFunction'],
            $assertFunction,
            $createFunction,
            $deleteFunction,
            $draftFunction
        );
    }

    final public static function withUpdateableProductSelection(
        ApiClient $client,
        callable $assertFunction,
        callable $createFunction = null,
        callable $deleteFunction = null,
        callable $draftFunction = null
    ) {
        self::withUpdateableDraftProductSelection(
            $client,
            [__CLASS__, 'defaultProductSelectionDraftBuilderFunction'],
            $assertFunction,
            $createFunction,
            $deleteFunction,
            $draftFunction
        );
    }
}


text:
title: Thanks for Being One of the First
description: "Taking a moment to dedicate Pinfinity to you and thank you for being one of the first."
social_type: article
social_title: Thanks for Being One of the First to Join Pinfinity
social_description: "We'd like to take a moment to dedicate Pinfinity to you and thank you for being one of the first to join us on our mission to change textbooks."
page_intro: "Multi-touch books, medicine, and education. It's what we do."
page_id: blog-post
author_name: "Kris Walker"
author_url: "https://plus.google.com/100601805957701195662?rel=author"
media_image: "/assets/figures/free-textbooks-w520h292.jpg"
_template: post
---

		Original by Open Source Way.

__To the students:__ Pinfinity is dedicated to you. Digital publishing has
dramatically changed the way information should be presented in a learning
environment, and there is no other field where the change to digital content is
more important than in medicine.  Our hats are off to you, and the path you
have chosen. We hope our books will eventually allow you to break free of the
textbook publishing machine and chart your own path through your career.

__To professionals:__ We hope you find Pinfinity books to be insightful enough,
that between your long hours caring for your patients, you'll look forward to a
few moments with a multi-touch book to further your knowledge. Thank you for
all you do. We take great pride in our responsibility to help you do it even
better.

__For the patients:__ Nothing would make us more proud than to hear your stories of
downloading one of our books in order to better understand your own healthcare.
Medicine can be intimidating and full of anxiety, but knowledge empowers, and
overcomes. We're there for you.

Most of all, Pinfinity is here to buck the status quo in medical education.
Access to information should be free, __especially__ when it comes to our
healthcare. We will strive to produce the most engaging medical learning
material in the digital age, and we will do it while asking nothing in return
from our readers. Medicine is simply too important for you to be forced to
continue lining the pockets of big, stale, publishing houses.

Maybe we're crazy, but then, maybe that's a good thing.

We're thrilled you've joined us on our journey.


text:
@interface UIImagePickerController (ZY)

@end


text:
module FullTextSearch
  module SimilarSearcher
    module Model
      def self.included(base)
        base.include(InstanceMethods)
        base.class_eval do
          after_commit Callbacks
          after_destroy Callbacks
        end
        if base.respond_to?(:connection_db_config)
          adapter = base.connection_db_config.adapter
        else
          adapter = base.connection_config[:adapter]
        end
        case adapter
        when "postgresql"
          base.include(FullTextSearch::SimilarSearcher::Pgroonga)
        when "mysql2"
          base.include(FullTextSearch::SimilarSearcher::Mroonga)
        end
      end

      module InstanceMethods
        def filter_condition(user = User.current, project_ids = [])
          conditions = []
          target_ids = Project.allowed_to(user, :view_issues).pluck(:id)
          target_ids &= project_ids if project_ids.present?
          if target_ids.present?
            # TODO: support private issue
            conditions << build_condition("&&",
                                          "is_private == false",
                                          "in_values(project_id, #{target_ids.join(',')})")
          end
          if conditions.empty?
            "1==1"
          else
            build_condition("||", conditions)
          end
        end
      end

      # Add callbacks to Issue
      class Callbacks
        class << self
          def after_commit(record)
            FullTextSearch::UpdateIssueContentJob
              .perform_later(record.class.name,
                             record.id,
                             "commit")
          end

          def after_destroy(record)
            # TODO: Refine
            case record
            when Issue
              FullTextSearch::UpdateIssueContentJob
                .perform_later(record.class.name,
                               record.id,
                               "destroy")
            when Journal
              FullTextSearch::UpdateIssueContentJob
                .perform_later(record.class.name,
                               record.id,
                               "destroy",
                               issue_id: record.journalized_id)
            end
          end
        end
      end
    end
  end
end


text:
<?php

namespace LightSaml\Tests\Action\Profile\Outbound\Message;

use LightSaml\Action\Profile\Outbound\Message\ForwardRelayStateAction;
use LightSaml\Context\Profile\ProfileContext;
use LightSaml\Model\Protocol\AuthnRequest;
use LightSaml\Model\Protocol\Response;
use LightSaml\Profile\Profiles;
use LightSaml\Tests\TestHelper;

class ForwardRelayStateActionTest extends \PHPUnit_Framework_TestCase
{
    public function test_constructs_with_logger()
    {
        new ForwardRelayStateAction(TestHelper::getLoggerMock($this));
    }

    public function test_does_nothing_if_no_inbound_message()
    {
        $action = new ForwardRelayStateAction(TestHelper::getLoggerMock($this));

        $context = new ProfileContext(Profiles::SSO_IDP_RECEIVE_AUTHN_REQUEST, ProfileContext::ROLE_IDP);

        $action->execute($context);
    }

    public function test_sets_relat_state_from_inbound_to_outbound_message()
    {
        $action = new ForwardRelayStateAction(TestHelper::getLoggerMock($this));

        $context = new ProfileContext(Profiles::SSO_IDP_RECEIVE_AUTHN_REQUEST, ProfileContext::ROLE_IDP);
        $context->getInboundContext()->setMessage($inboundMessage = new AuthnRequest());
        $context->getOutboundContext()->setMessage($outboundMessage = new Response());

        $inboundMessage->setRelayState($relayState = '123');

        $action->execute($context);

        $this->assertEquals($relayState, $context->getOutboundMessage()->getRelayState());
    }
}


text:
using System.Configuration;

namespace SNS_Bot
{
    [System.Diagnostics.DebuggerNonUserCodeAttribute]
    [System.Runtime.CompilerServices.CompilerGeneratedAttribute]
    public static class AppSettings
    {
        public static class ClientSettingsProvider
        {
            public static string ServiceUri
            {
                get { return ConfigurationManager.AppSettings["ClientSettingsProvider.ServiceUri"]; }
            }
        }

        public static class Moe
        {
            public static class Friends_nico
            {
                public static class AppRegistration
                {
                    public static string AccessToken
                    {
                        get { return ConfigurationManager.AppSettings["Moe.friends_nico.AppRegistration.AccessToken"]; }
                    }

                    public static string ClientId
                    {
                        get { return ConfigurationManager.AppSettings["Moe.friends_nico.AppRegistration.ClientId"]; }
                    }

                    public static string ClientSecret
                    {
                        get { return ConfigurationManager.AppSettings["Moe.friends_nico.AppRegistration.ClientSecret"]; }
                    }

                    public static string Id
                    {
                        get { return ConfigurationManager.AppSettings["Moe.friends_nico.AppRegistration.Id"]; }
                    }

                    public static string Instance
                    {
                        get { return ConfigurationManager.AppSettings["Moe.friends_nico.AppRegistration.Instance"]; }
                    }
                }
            }

            public static class Mstdn_jp
            {
                public static class AppRegistration
                {
                    public static string AccessToken
                    {
                        get { return ConfigurationManager.AppSettings["Moe.mstdn_jp.AppRegistration.AccessToken"]; }
                    }

                    public static string ClientId
                    {
                        get { return ConfigurationManager.AppSettings["Moe.mstdn_jp.AppRegistration.ClientId"]; }
                    }

                    public static string ClientSecret
                    {
                        get { return ConfigurationManager.AppSettings["Moe.mstdn_jp.AppRegistration.ClientSecret"]; }
                    }

                    public static string Id
                    {
                        get { return ConfigurationManager.AppSettings["Moe.mstdn_jp.AppRegistration.Id"]; }
                    }

                    public static string Instance
                    {
                        get { return ConfigurationManager.AppSettings["Moe.mstdn_jp.AppRegistration.Instance"]; }
                    }
                }
            }

            public static class Pawoo_net
            {
                public static class AppRegistration
                {
                    public static string AccessToken
                    {
                        get { return ConfigurationManager.AppSettings["Moe.pawoo_net.AppRegistration.AccessToken"]; }
                    }

                    public static string ClientId
                    {
                        get { return ConfigurationManager.AppSettings["Moe.pawoo_net.AppRegistration.ClientId"]; }
                    }

                    public static string ClientSecret
                    {
                        get { return ConfigurationManager.AppSettings["Moe.pawoo_net.AppRegistration.ClientSecret"]; }
                    }

                    public static string Id
                    {
                        get { return ConfigurationManager.AppSettings["Moe.pawoo_net.AppRegistration.Id"]; }
                    }

                    public static string Instance
                    {
                        get { return ConfigurationManager.AppSettings["Moe.pawoo_net.AppRegistration.Instance"]; }
                    }
                }
            }

            public static class Twitter
            {
                public static string AccessToken
                {
                    get { return ConfigurationManager.AppSettings["Moe.twitter.AccessToken"]; }
                }

                public static string AccessTokenSecret
                {
                    get { return ConfigurationManager.AppSettings["Moe.twitter.AccessTokenSecret"]; }
                }

                public static string ConsumerKey
                {
                    get { return ConfigurationManager.AppSettings["Moe.twitter.ConsumerKey"]; }
                }

                public static string ConsumerSecret
                {
                    get { return ConfigurationManager.AppSettings["Moe.twitter.ConsumerSecret"]; }
                }
            }
        }

        public static class Satomi
        {
            public static class Twitter
            {
                public static string AccessToken
                {
                    get { return ConfigurationManager.AppSettings["Satomi.twitter.AccessToken"]; }
                }

                public static string AccessTokenSecret
                {
                    get { return ConfigurationManager.AppSettings["Satomi.twitter.AccessTokenSecret"]; }
                }

                public static string ConsumerKey
                {
                    get { return ConfigurationManager.AppSettings["Satomi.twitter.ConsumerKey"]; }
                }

                public static string ConsumerSecret
                {
                    get { return ConfigurationManager.AppSettings["Satomi.twitter.ConsumerSecret"]; }
                }
            }
        }
    }
}


text:
define(['services/datacontext','services/logger'], function(datacontext,logger) {

    //message manager is responsible for creating notification messages in the DB.
    //the TaskRunner app will be responsible for converting notification messages to EmailMessages

    //NotificationMessage class
    // int Id { get; set; } AUTO
    // int ReferralId { get; set; }
    // string PupilNameAndForm { get; set; }
    // string Recipient { get; set; }
    // MessageType MessageType { get; set; }
    // string _messageTypeName;
    // string MessageTypeName
    //{
    //    get
    //    {
    //        return _messageTypeName = MessageType.ToString();

    //    }
    //    set { _messageTypeName =  MessageType.ToString(); }
    //}

    var ctor = function() {

    };
    ctor.prototype.create = function(messageType, options) {
        var message = {
            referralId:options.referral.id(),
            messageType: messageType,
            messageTypeName:messageType,
            recipient: options.staffCode,
            referral: options.referral,
            pupilNameAndForm:options.referral.pupilFullName()
        };
        //todo: create the createMessage function

        return datacontext.createMessage(message);
        //return logger.log("message created", null, null, true);
    };
    ctor.prototype.createMessages = function(messages) {
        messages.forEach(function(message) {
           return self.create(type, message);
        });
    }
    return new ctor;
});


text:
#import "SLTCells.h"

@interface SLTCells()

@property(nonatomic, strong, readonly) NSMutableArray* rawData;

@end


text:
/**
@file
@author DINH Viet Huy Hubert <dinh@ifrec.osaka-u.ac.jp>
@version 1.0
@section DESCRIPTION

Calculate correlation values of vectors against each others in a list of vectors
**/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include "correlation.h"

extern float* getCorrelation(const float* vectors,const size_t cols,const size_t rows) {

	size_t totalSize=(rows)*(rows-1)/2; /* number of value in the flat vector storage of the triangle matrix*/
	fprintf(stderr,"%zu (%zu)\n",totalSize,totalSize*sizeof(float));
	float *output=malloc(sizeof(float)*totalSize);
	assert(output!=NULL);
	if(output==NULL) {
		fprintf(stderr,"not enough memory\n");
		abort();
		//return(NULL);
	}
	return(output);
}


text:
def pytest_addoption(parser):
    group = parser.getgroup("pypy options")
    group.addoption(
        "--view",
        action="store_true",
        default=False,
        dest="view",
        help="show only the compiled loops",
    )
    group.addoption(
        "--viewloops",
        action="store_true",
        default=False,
        dest="viewloops",
        help="show only the compiled loops",
    )

def pytest_configure(config):
    from pypy import conftest
    conftest.option = config.option


text:
<?php namespace AnalogueTest\App;

use Analogue\ORM\Mappable;

class Meta implements Mappable {

    protected $content = [];

    public function setEntityAttributes(array $attributes)
    {
        $this->setEntityAttribute('metadatas', $attributes['metadatas']);
    }

    public function getEntityAttributes()
    {
        return ['metadatas' => $this->getEntityAttribute('metadatas')];
    }

    public function setEntityAttribute($key, $value)
    {
        if($key == 'metadatas')
        {
            $this->content = unserialize($value);
        }
    }

    public function getEntityAttribute($key)
    {
        if($key == 'metadatas')
        {
            return serialize($this->content);
        }
    }

    public function all()
    {
        return $this->content;
    }

    public function set($key, $value)
    {
        $this->content[$key] = $value;
    }

    public function get($key)
    {
        return $this->content[$key];
    }

}


text:
#include "webrtc/modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h"

#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/modules/rtp_rtcp/source/byte_io.h"
#include "webrtc/modules/rtp_rtcp/source/rtcp_utility.h"

namespace webrtc {
namespace rtcp {

// Header size:
// * 12 bytes Common Packet Format for RTCP Feedback Messages
// * 8 bytes FeedbackPacket header
static const uint32_t kHeaderSizeBytes = 12 + 8;
static const uint32_t kChunkSizeBytes = 2;
static const uint32_t kOneBitVectorCapacity = 14;
static const uint32_t kTwoBitVectorCapacity = 7;
static const uint32_t kRunLengthCapacity = 0x1FFF;
// TODO(sprang): Add support for dynamic max size for easier fragmentation,
// eg. set it to what's left in the buffer or IP_PACKET_SIZE.
// Size constraint imposed by RTCP common header: 16bit size field interpreted
// as number of four byte words minus the first header word.
static const uint32_t kMaxSizeBytes = (1 << 16) * 4;
static const uint32_t kMinSizeBytes = kHeaderSizeBytes + kChunkSizeBytes;
static const uint32_t kBaseScaleFactor =
    TransportFeedback::kDeltaScaleFactor * (1 << 8);

class PacketStatusChunk {
 public:
  virtual ~PacketStatusChunk() {}
  virtual uint16_t NumSymbols() const = 0;
  virtual void AppendSymbolsTo(
      std::vector<TransportFeedback::StatusSymbol>* vec) const = 0;
  virtual void WriteTo(uint8_t* buffer) const = 0;
};

uint8_t EncodeSymbol(TransportFeedback::StatusSymbol symbol) {
  switch (symbol) {
    case TransportFeedback::StatusSymbol::kNotReceived:
      return 0;
    case TransportFeedback::StatusSymbol::kReceivedSmallDelta:
      return 1;
    case TransportFeedback::StatusSymbol::kReceivedLargeDelta:
      return 2;
    default:
      RTC_NOTREACHED();
      return 0;
  }
}

TransportFeedback::StatusSymbol DecodeSymbol(uint8_t value) {
  switch (value) {
    case 0:
      return TransportFeedback::StatusSymbol::kNotReceived;
    case 1:
      return TransportFeedback::StatusSymbol::kReceivedSmallDelta;
    case 2:
      return TransportFeedback::StatusSymbol::kReceivedLargeDelta;
    default:
      RTC_NOTREACHED();
      return TransportFeedback::StatusSymbol::kNotReceived;
  }
}

TransportFeedback::TransportFeedback()
    : packet_sender_ssrc_(0),
      media_source_ssrc_(0),
      base_seq_(-1),
      base_time_(-1),
      feedback_seq_(0),
      last_seq_(-1),
      last_timestamp_(-1),
      first_symbol_cardinality_(0),
      vec_needs_two_bit_symbols_(false),
      size_bytes_(kHeaderSizeBytes) {
}

TransportFeedback::~TransportFeedback() {
  for (PacketStatusChunk* chunk : status_chunks_)
    delete chunk;
}

//  One Bit Status Vector Chunk
//
//  0                   1
//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |T|S|       symbol list         |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//  T = 1
//  S = 0
//  symbol list = 14 entries where 0 = not received, 1 = received

class OneBitVectorChunk : public PacketStatusChunk {
 public:
  static const int kCapacity = 14;

  explicit OneBitVectorChunk(
      std::deque<TransportFeedback::StatusSymbol>* symbols) {
    size_t input_size = symbols->size();
    for (size_t i = 0; i < kCapacity; ++i) {
      if (i < input_size) {
        symbols_[i] = symbols->front();
        symbols->pop_front();
      } else {
        symbols_[i] = TransportFeedback::StatusSymbol::kNotReceived;
      }
    }
  }

  virtual ~OneBitVectorChunk() {}

  uint16_t NumSymbols() const override { return kCapacity; }

  void AppendSymbolsTo(
      std::vector<TransportFeedback::StatusSymbol>* vec) const override {
    vec->insert(vec->end(), &symbols_[0], &symbols_[kCapacity]);
  }

  void WriteTo(uint8_t* buffer) const override {
    const int kSymbolsInFirstByte = 6;
    const int kSymbolsInSecondByte = 8;
    buffer[0] = 0x80u;
    for (int i = 0; i < kSymbolsInFirstByte; ++i) {
      uint8_t encoded_symbol = EncodeSymbol(symbols_[i]);
      RTC_DCHECK_LE(encoded_symbol, 1u);
      buffer[0] |= encoded_symbol << (kSymbolsInFirstByte - (i + 1));
    }
    buffer[1] = 0x00u;
    for (int i = 0; i < kSymbolsInSecondByte; ++i) {
      uint8_t encoded_symbol = EncodeSymbol(symbols_[i + kSymbolsInFirstByte]);
      RTC_DCHECK_LE(encoded_symbol, 1u);
      buffer[1] |= encoded_symbol << (kSymbolsInSecondByte - (i + 1));
    }
  }

  static OneBitVectorChunk* ParseFrom(const uint8_t* data) {
    OneBitVectorChunk* chunk = new OneBitVectorChunk();

    size_t index = 0;
    for (int i = 5; i >= 0; --i)  // Last 5 bits from first byte.
      chunk->symbols_[index++] = DecodeSymbol((data[0] >> i) & 0x01);
    for (int i = 7; i >= 0; --i)  // 8 bits from the last byte.
      chunk->symbols_[index++] = DecodeSymbol((data[1] >> i) & 0x01);

    return chunk;
  }

 private:
  OneBitVectorChunk() {}

  TransportFeedback::StatusSymbol symbols_[kCapacity];
};

//  Two Bit Status Vector Chunk
//
//  0                   1
//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |T|S|       symbol list         |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//  T = 1
//  S = 1
//  symbol list = 7 entries of two bits each, see (Encode|Decode)Symbol

class TwoBitVectorChunk : public PacketStatusChunk {
 public:
  static const int kCapacity = 7;

  explicit TwoBitVectorChunk(
      std::deque<TransportFeedback::StatusSymbol>* symbols) {
    size_t input_size = symbols->size();
    for (size_t i = 0; i < kCapacity; ++i) {
      if (i < input_size) {
        symbols_[i] = symbols->front();
        symbols->pop_front();
      } else {
        symbols_[i] = TransportFeedback::StatusSymbol::kNotReceived;
      }
    }
  }

  virtual ~TwoBitVectorChunk() {}

  uint16_t NumSymbols() const override { return kCapacity; }

  void AppendSymbolsTo(
      std::vector<TransportFeedback::StatusSymbol>* vec) const override {
    vec->insert(vec->end(), &symbols_[0], &symbols_[kCapacity]);
  }

  void WriteTo(uint8_t* buffer) const override {
    buffer[0] = 0xC0;
    buffer[0] |= EncodeSymbol(symbols_[0]) << 4;
    buffer[0] |= EncodeSymbol(symbols_[1]) << 2;
    buffer[0] |= EncodeSymbol(symbols_[2]);
    buffer[1] = EncodeSymbol(symbols_[3]) << 6;
    buffer[1] |= EncodeSymbol(symbols_[4]) << 4;
    buffer[1] |= EncodeSymbol(symbols_[5]) << 2;
    buffer[1] |= EncodeSymbol(symbols_[6]);
  }

  static TwoBitVectorChunk* ParseFrom(const uint8_t* buffer) {
    TwoBitVectorChunk* chunk = new TwoBitVectorChunk();

    chunk->symbols_[0] = DecodeSymbol((buffer[0] >> 4) & 0x03);
    chunk->symbols_[1] = DecodeSymbol((buffer[0] >> 2) & 0x03);
    chunk->symbols_[2] = DecodeSymbol(buffer[0] & 0x03);
    chunk->symbols_[3] = DecodeSymbol((buffer[1] >> 6) & 0x03);
    chunk->symbols_[4] = DecodeSymbol((buffer[1] >> 4) & 0x03);
    chunk->symbols_[5] = DecodeSymbol((buffer[1] >> 2) & 0x03);
    chunk->symbols_[6] = DecodeSymbol(buffer[1] & 0x03);

    return chunk;
  }

 private:
  TwoBitVectorChunk() {}

  TransportFeedback::StatusSymbol symbols_[kCapacity];
};

//  Two Bit Status Vector Chunk
//
//  0                   1
//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |T| S |       Run Length        |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//  T = 0
//  S = symbol, see (Encode|Decode)Symbol
//  Run Length = Unsigned integer denoting the run length of the symbol

class RunLengthChunk : public PacketStatusChunk {
 public:
  RunLengthChunk(TransportFeedback::StatusSymbol symbol, size_t size)
      : symbol_(symbol), size_(size) {
    RTC_DCHECK_LE(size, 0x1FFFu);
  }

  virtual ~RunLengthChunk() {}

  uint16_t NumSymbols() const override { return size_; }

  void AppendSymbolsTo(
      std::vector<TransportFeedback::StatusSymbol>* vec) const override {
    vec->insert(vec->end(), size_, symbol_);
  }

  void WriteTo(uint8_t* buffer) const override {
    buffer[0] = EncodeSymbol(symbol_) << 5;  // Write S (T = 0 implicitly)
    buffer[0] |= (size_ >> 8) & 0x1F;  // 5 most significant bits of run length.
    buffer[1] = size_ & 0xFF;  // 8 least significant bits of run length.
  }

  static RunLengthChunk* ParseFrom(const uint8_t* buffer) {
    RTC_DCHECK_EQ(0, buffer[0] & 0x80);
    TransportFeedback::StatusSymbol symbol =
        DecodeSymbol((buffer[0] >> 5) & 0x03);
    uint16_t count = (static_cast<uint16_t>(buffer[0] & 0x1F) << 8) | buffer[1];

    return new RunLengthChunk(symbol, count);
  }

 private:
  const TransportFeedback::StatusSymbol symbol_;
  const size_t size_;
};

// Unwrap to a larger type, for easier handling of wraps.
int64_t TransportFeedback::Unwrap(uint16_t sequence_number) {
  if (last_seq_ == -1)
    return sequence_number;

  int64_t delta = sequence_number - last_seq_;
  if (IsNewerSequenceNumber(sequence_number,
                            static_cast<uint16_t>(last_seq_))) {
    if (delta < 0)
      delta += (1 << 16);
  } else if (delta > 0) {
    delta -= (1 << 16);
  }

  return last_seq_ + delta;
}

void TransportFeedback::WithPacketSenderSsrc(uint32_t ssrc) {
  packet_sender_ssrc_ = ssrc;
}

void TransportFeedback::WithMediaSourceSsrc(uint32_t ssrc) {
  media_source_ssrc_ = ssrc;
}

uint32_t TransportFeedback::GetPacketSenderSsrc() const {
  return packet_sender_ssrc_;
}

uint32_t TransportFeedback::GetMediaSourceSsrc() const {
  return media_source_ssrc_;
}
void TransportFeedback::WithBase(uint16_t base_sequence,
                                 int64_t ref_timestamp_us) {
  RTC_DCHECK_EQ(-1, base_seq_);
  RTC_DCHECK_NE(-1, ref_timestamp_us);
  base_seq_ = base_sequence;
  last_seq_ = base_sequence;
  base_time_ = ref_timestamp_us / kBaseScaleFactor;
  last_timestamp_ = base_time_ * kBaseScaleFactor;
}

void TransportFeedback::WithFeedbackSequenceNumber(uint8_t feedback_sequence) {
  feedback_seq_ = feedback_sequence;
}

bool TransportFeedback::WithReceivedPacket(uint16_t sequence_number,
                                           int64_t timestamp) {
  RTC_DCHECK_NE(-1, base_seq_);
  int64_t seq = Unwrap(sequence_number);
  if (seq != base_seq_ && seq <= last_seq_)
    return false;

  // Convert to ticks and round.
  int64_t delta_full = timestamp - last_timestamp_;
  delta_full +=
      delta_full < 0 ? -(kDeltaScaleFactor / 2) : kDeltaScaleFactor / 2;
  delta_full /= kDeltaScaleFactor;

  int16_t delta = static_cast<int16_t>(delta_full);
  // If larger than 16bit signed, we can't represent it - need new fb packet.
  if (delta != delta_full) {
    LOG(LS_WARNING) << "Delta value too large ( >= 2^16 ticks )";
    return false;
  }

  StatusSymbol symbol;
  if (delta >= 0 && delta <= 0xFF) {
    symbol = StatusSymbol::kReceivedSmallDelta;
  } else {
    symbol = StatusSymbol::kReceivedLargeDelta;
  }

  if (!AddSymbol(symbol, seq))
    return false;

  receive_deltas_.push_back(delta);
  last_timestamp_ += delta * kDeltaScaleFactor;
  return true;
}

// Add a symbol for a received packet, with the given sequence number. This
// method will add any "packet not received" symbols needed before this one.
bool TransportFeedback::AddSymbol(StatusSymbol symbol, int64_t seq) {
  while (last_seq_ < seq - 1) {
    if (!Encode(StatusSymbol::kNotReceived))
      return false;
    ++last_seq_;
  }

  if (!Encode(symbol))
    return false;

  last_seq_ = seq;
  return true;
}

// Append a symbol to the internal symbol vector. If the new state cannot be
// represented using a single status chunk, a chunk will first be emitted and
// the associated symbols removed from the internal symbol vector.
bool TransportFeedback::Encode(StatusSymbol symbol) {
  if (last_seq_ - base_seq_ + 1 > 0xFFFF) {
    LOG(LS_WARNING) << "Packet status count too large ( >= 2^16 )";
    return false;
  }

  bool is_two_bit;
  int delta_size;
  switch (symbol) {
    case StatusSymbol::kReceivedSmallDelta:
      delta_size = 1;
      is_two_bit = false;
      break;
    case StatusSymbol::kReceivedLargeDelta:
      delta_size = 2;
      is_two_bit = true;
      break;
    case StatusSymbol::kNotReceived:
      is_two_bit = false;
      delta_size = 0;
      break;
    default:
      RTC_NOTREACHED();
      return false;
  }

  if (symbol_vec_.empty()) {
    if (size_bytes_ + delta_size + kChunkSizeBytes > kMaxSizeBytes)
      return false;

    symbol_vec_.push_back(symbol);
    vec_needs_two_bit_symbols_ = is_two_bit;
    first_symbol_cardinality_ = 1;
    size_bytes_ += delta_size + kChunkSizeBytes;
    return true;
  }
  if (size_bytes_ + delta_size > kMaxSizeBytes)
    return false;

  // Capacity, in number of symbols, that a vector chunk could hold.
  size_t capacity = vec_needs_two_bit_symbols_ ? kTwoBitVectorCapacity
                                               : kOneBitVectorCapacity;

  // first_symbol_cardinality_ is the number of times the first symbol in
  // symbol_vec is repeated. So if that is equal to the size of symbol_vec,
  // there is only one kind of symbol - we can potentially RLE encode it.
  // If we have less than (capacity) symbols in symbol_vec, we can't know
  // for certain this will be RLE-encoded; if a different symbol is added
  // these symbols will be needed to emit a vector chunk instead. However,
  // if first_symbol_cardinality_ > capacity, then we cannot encode the
  // current state as a vector chunk - we must first emit symbol_vec as an
  // RLE-chunk and then add the new symbol.
  bool rle_candidate = symbol_vec_.size() == first_symbol_cardinality_ ||
                       first_symbol_cardinality_ > capacity;
  if (rle_candidate) {
    if (symbol_vec_.back() == symbol) {
      ++first_symbol_cardinality_;
      if (first_symbol_cardinality_ <= capacity) {
        symbol_vec_.push_back(symbol);
      } else if (first_symbol_cardinality_ == kRunLengthCapacity) {
        // Max length for an RLE-chunk reached.
        EmitRunLengthChunk();
      }
      size_bytes_ += delta_size;
      return true;
    } else {
      // New symbol does not match what's already in symbol_vec.
      if (first_symbol_cardinality_ >= capacity) {
        // Symbols in symbol_vec can only be RLE-encoded. Emit the RLE-chunk
        // and re-add input. symbol_vec is then guaranteed to have room for the
        // symbol, so recursion cannot continue.
        EmitRunLengthChunk();
        return Encode(symbol);
      }
      // Fall through and treat state as non RLE-candidate.
    }
  }

  // If this code point is reached, symbols in symbol_vec cannot be RLE-encoded.

  if (is_two_bit && !vec_needs_two_bit_symbols_) {
    // If the symbols in symbol_vec can be encoded using a one-bit chunk but
    // the input symbol cannot, first check if we can simply change target type.
    vec_needs_two_bit_symbols_ = true;
    if (symbol_vec_.size() >= kTwoBitVectorCapacity) {
      // symbol_vec contains more symbols than we can encode in a single
      // two-bit chunk. Emit a new vector append to the remains, if any.
      if (size_bytes_ + delta_size + kChunkSizeBytes > kMaxSizeBytes)
        return false;
      EmitVectorChunk();
      // If symbol_vec isn't empty after emitting a vector chunk, we need to
      // account for chunk size (otherwise handled by Encode method).
      if (!symbol_vec_.empty())
        size_bytes_ += kChunkSizeBytes;
      return Encode(symbol);
    }
    // symbol_vec symbols fit within a single two-bit vector chunk.
    capacity = kTwoBitVectorCapacity;
  }

  symbol_vec_.push_back(symbol);
  if (symbol_vec_.size() == capacity)
    EmitVectorChunk();

  size_bytes_ += delta_size;
  return true;
}

// Upon packet completion, emit any remaining symbols in symbol_vec that have
// not yet been emitted in a status chunk.
void TransportFeedback::EmitRemaining() {
  if (symbol_vec_.empty())
    return;

  size_t capacity = vec_needs_two_bit_symbols_ ? kTwoBitVectorCapacity
                                               : kOneBitVectorCapacity;
  if (first_symbol_cardinality_ > capacity) {
    EmitRunLengthChunk();
  } else {
    EmitVectorChunk();
  }
}

void TransportFeedback::EmitVectorChunk() {
  if (vec_needs_two_bit_symbols_) {
    status_chunks_.push_back(new TwoBitVectorChunk(&symbol_vec_));
  } else {
    status_chunks_.push_back(new OneBitVectorChunk(&symbol_vec_));
  }
  // Update first symbol cardinality to match what is potentially left in in
  // symbol_vec.
  first_symbol_cardinality_ = 1;
  for (size_t i = 1; i < symbol_vec_.size(); ++i) {
    if (symbol_vec_[i] != symbol_vec_[0])
      break;
    ++first_symbol_cardinality_;
  }
}

void TransportFeedback::EmitRunLengthChunk() {
  RTC_DCHECK_GE(first_symbol_cardinality_, symbol_vec_.size());
  status_chunks_.push_back(
      new RunLengthChunk(symbol_vec_.front(), first_symbol_cardinality_));
  symbol_vec_.clear();
}

size_t TransportFeedback::BlockLength() const {
  return size_bytes_;
}

uint16_t TransportFeedback::GetBaseSequence() const {
  return base_seq_;
}

int64_t TransportFeedback::GetBaseTimeUs() const {
  return base_time_ * kBaseScaleFactor;
}

std::vector<TransportFeedback::StatusSymbol>
TransportFeedback::GetStatusVector() const {
  std::vector<TransportFeedback::StatusSymbol> symbols;
  for (PacketStatusChunk* chunk : status_chunks_)
    chunk->AppendSymbolsTo(&symbols);
  int64_t status_count = last_seq_ - base_seq_ + 1;
  // If packet ends with a vector chunk, it may contain extraneous "packet not
  // received"-symbols at the end. Crop any such symbols.
  symbols.erase(symbols.begin() + status_count, symbols.end());
  return symbols;
}

std::vector<int16_t> TransportFeedback::GetReceiveDeltas() const {
  return receive_deltas_;
}

std::vector<int64_t> TransportFeedback::GetReceiveDeltasUs() const {
  if (receive_deltas_.empty())
    return std::vector<int64_t>();

  std::vector<int64_t> us_deltas;
  for (int16_t delta : receive_deltas_)
    us_deltas.push_back(static_cast<int64_t>(delta) * kDeltaScaleFactor);

  return us_deltas;
}

// Serialize packet.
bool TransportFeedback::Create(uint8_t* packet,
                               size_t* position,
                               size_t max_length,
                               PacketReadyCallback* callback) const {
  if (base_seq_ == -1)
    return false;

  while (*position + size_bytes_ > max_length) {
    if (!OnBufferFull(packet, position, callback))
      return false;
  }

  CreateHeader(kFeedbackMessageType, kPayloadType, HeaderLength(), packet,
               position);
  ByteWriter<uint32_t>::WriteBigEndian(&packet[*position], packet_sender_ssrc_);
  *position += 4;
  ByteWriter<uint32_t>::WriteBigEndian(&packet[*position], media_source_ssrc_);
  *position += 4;

  RTC_DCHECK_LE(base_seq_, 0xFFFF);
  ByteWriter<uint16_t>::WriteBigEndian(&packet[*position], base_seq_);
  *position += 2;

  int64_t status_count = last_seq_ - base_seq_ + 1;
  RTC_DCHECK_LE(status_count, 0xFFFF);
  ByteWriter<uint16_t>::WriteBigEndian(&packet[*position], status_count);
  *position += 2;

  ByteWriter<int32_t, 3>::WriteBigEndian(&packet[*position],
                                         static_cast<int32_t>(base_time_));
  *position += 3;

  packet[(*position)++] = feedback_seq_;

  // TODO(sprang): Get rid of this cast.
  const_cast<TransportFeedback*>(this)->EmitRemaining();
  for (PacketStatusChunk* chunk : status_chunks_) {
    chunk->WriteTo(&packet[*position]);
    *position += 2;
  }

  for (int16_t delta : receive_deltas_) {
    if (delta >= 0 && delta <= 0xFF) {
      packet[(*position)++] = delta;
    } else {
      ByteWriter<int16_t>::WriteBigEndian(&packet[*position], delta);
      *position += 2;
    }
  }

  while ((*position % 4) != 0)
    packet[(*position)++] = 0;

  return true;
}

//    Message format
//
//     0                   1                   2                   3
//     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |V=2|P|  FMT=15 |    PT=205     |           length              |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |                     SSRC of packet sender                     |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |                      SSRC of media source                     |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |      base sequence number     |      packet status count      |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |                 reference time                | fb pkt. count |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |          packet chunk         |         packet chunk          |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    .                                                               .
//    .                                                               .
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |         packet chunk          |  recv delta   |  recv delta   |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    .                                                               .
//    .                                                               .
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |           recv delta          |  recv delta   | zero padding  |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

// De-serialize packet.
rtc::scoped_ptr<TransportFeedback> TransportFeedback::ParseFrom(
    const uint8_t* buffer,
    size_t length) {
  rtc::scoped_ptr<TransportFeedback> packet(new TransportFeedback());

  if (length < kMinSizeBytes) {
    LOG(LS_WARNING) << "Buffer too small (" << length
                    << " bytes) to fit a "
                       "FeedbackPacket. Minimum size = " << kMinSizeBytes;
    return nullptr;
  }

  RTCPUtility::RtcpCommonHeader header;
  if (!RtcpParseCommonHeader(buffer, length, &header))
    return nullptr;

  if (header.count_or_format != kFeedbackMessageType) {
    LOG(LS_WARNING) << "Invalid RTCP header: FMT must be "
                    << kFeedbackMessageType << " but was "
                    << header.count_or_format;
    return nullptr;
  }

  if (header.packet_type != kPayloadType) {
    LOG(LS_WARNING) << "Invalid RTCP header: PT must be " << kPayloadType
                    << " but was " << header.packet_type;
    return nullptr;
  }

  packet->packet_sender_ssrc_ = ByteReader<uint32_t>::ReadBigEndian(&buffer[4]);
  packet->media_source_ssrc_ = ByteReader<uint32_t>::ReadBigEndian(&buffer[8]);
  packet->base_seq_ = ByteReader<uint16_t>::ReadBigEndian(&buffer[12]);
  uint16_t num_packets = ByteReader<uint16_t>::ReadBigEndian(&buffer[14]);
  packet->base_time_ = ByteReader<int32_t, 3>::ReadBigEndian(&buffer[16]);
  packet->feedback_seq_ = buffer[19];
  size_t index = 20;
  const size_t end_index = kHeaderLength + header.payload_size_bytes;

  if (num_packets == 0) {
    LOG(LS_WARNING) << "Empty feedback messages not allowed.";
    return nullptr;
  }
  packet->last_seq_ = packet->base_seq_ + num_packets - 1;

  size_t packets_read = 0;
  while (packets_read < num_packets) {
    if (index + 2 > end_index) {
      LOG(LS_WARNING) << "Buffer overflow while parsing packet.";
      return nullptr;
    }

    PacketStatusChunk* chunk =
        ParseChunk(&buffer[index], num_packets - packets_read);
    if (chunk == nullptr)
      return nullptr;

    index += 2;
    packet->status_chunks_.push_back(chunk);
    packets_read += chunk->NumSymbols();
  }

  std::vector<StatusSymbol> symbols = packet->GetStatusVector();

  RTC_DCHECK_EQ(num_packets, symbols.size());

  for (StatusSymbol symbol : symbols) {
    switch (symbol) {
      case StatusSymbol::kReceivedSmallDelta:
        if (index + 1 > end_index) {
          LOG(LS_WARNING) << "Buffer overflow while parsing packet.";
          return nullptr;
        }
        packet->receive_deltas_.push_back(buffer[index]);
        ++index;
        break;
      case StatusSymbol::kReceivedLargeDelta:
        if (index + 2 > end_index) {
          LOG(LS_WARNING) << "Buffer overflow while parsing packet.";
          return nullptr;
        }
        packet->receive_deltas_.push_back(
            ByteReader<int16_t>::ReadBigEndian(&buffer[index]));
        index += 2;
        break;
      default:
        continue;
    }
  }

  RTC_DCHECK_GE(index, end_index - 3);
  RTC_DCHECK_LE(index, end_index);

  return packet;
}

PacketStatusChunk* TransportFeedback::ParseChunk(const uint8_t* buffer,
                                                 size_t max_size) {
  if (buffer[0] & 0x80) {
    // First bit set => vector chunk.
    std::deque<StatusSymbol> symbols;
    if (buffer[0] & 0x40) {
      // Second bit set => two bits per symbol vector.
      return TwoBitVectorChunk::ParseFrom(buffer);
    }

    // Second bit not set => one bit per symbol vector.
    return OneBitVectorChunk::ParseFrom(buffer);
  }

  // First bit not set => RLE chunk.
  RunLengthChunk* rle_chunk = RunLengthChunk::ParseFrom(buffer);
  if (rle_chunk->NumSymbols() > max_size) {
    LOG(LS_WARNING) << "Header/body mismatch. "
                       "RLE block of size " << rle_chunk->NumSymbols()
                    << " but only " << max_size << " left to read.";
    delete rle_chunk;
    return nullptr;
  }
  return rle_chunk;
}

}  // namespace rtcp
}  // namespace webrtc