text:
<!DOCTYPE html>
<?php

session_start();
if (!isset($_SESSION["guest"])) {
  header("login.php");
}

?>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Flaming Wings | View Recipe</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">

    <link rel="stylesheet" href="dist/css/AdminLTE.min.css">

    <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">

    <link rel="stylesheet" href="plugins/iCheck/flat/blue.css">

    <link rel="stylesheet" href="plugins/morris/morris.css">

    <link rel="stylesheet" href="plugins/jvectormap/jquery-jvectormap-1.2.2.css">

    <link rel="stylesheet" href="plugins/datepicker/datepicker3.css">

    <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker-bs3.css">

    <link rel="stylesheet" href="plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">

   <?PHP
   include("dbconnection.php")

   ?>

            Toggle navigation

                  10

You have 10 notifications

                           5 new members joined today

                           Very long description here that may not fit into the page and may cause design problems

                           5 new members joined

                           25 sales made

                           You changed your username

View all

                  Brooklyn Beckham

                      Brooklyn Beckham - Manager
                      Member since Nov. 2016

Brooklyn Beckham

               Online

MAIN NAVIGATION

                 Dashboard

                Recipe

 Search Recipe

 Add Recipe

 Edit Recipe

 Deactivate Recipe

                Stocks

 Search Stock

 Add new stock

 Replenish stock

 Edit stock

 Withdraw stock

                Inventory Reports

 Inventory Report

Stock Controller

 Most sold order

                Conversion

Conversion Table

                                <?php
                                 $sql_query = "SELECT recipe_name FROM recipe WHERE recipe_id=1";
                                    mysqli_query($connect, $sql_query);

                                    echo "" .$_POST['recipe_name']; "	"

                                ?>
                                Go Back

                    </form>

Recipes

                        ID
                        Recipe Type
                        Recipe Name

                        <?php
                        $stock_code = isset($_GET['recipe_name']) ? $_GET['recipe_name'] : '';
                        $sql = mysqli_query($connect, "SELECT * FROM recipe r JOIN recipetype rtype WHERE r.recipe_typeid=rtype.recipe_typeid");
                        while ($row = mysqli_fetch_array($sql)){
                          echo "
";
                          echo "".$row['recipe_id']."	"; //recipe id
                          echo "".$row["recipe_type"]."	"; //type
                          echo "".$row["recipe_name"]."	"; //recipe name
                          echo '  <button type="button" class="btn btn-block btn-default btn-sm" data-toggle="modal" data-target="#view" aria-hidden="true">View</button>	';
                          echo "
";

                        }
                         ?>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Linq;

namespace Microsoft.CodeAnalysis.Editor
{
    internal class SolutionChangeSummary
    {
        public readonly Solution OldSolution;
        public readonly Solution NewSolution;

        public readonly int TotalFilesAffected;
        public readonly int TotalProjectsAffected;

        public SolutionChangeSummary(Solution oldSolution, Solution newSolution, SolutionChanges changes)
        {
            OldSolution = oldSolution;
            NewSolution = newSolution;

            foreach (var p in changes.GetProjectChanges())
            {
                TotalProjectsAffected += 1;

                TotalFilesAffected += p.GetAddedDocuments().Count() +
                                      p.GetChangedDocuments().Count() +
                                      p.GetRemovedDocuments().Count() +
                                      p.GetAddedAdditionalDocuments().Count() +
                                      p.GetChangedAdditionalDocuments().Count() +
                                      p.GetRemovedAdditionalDocuments().Count() +
                                      p.GetAddedAnalyzerConfigDocuments().Count() +
                                      p.GetChangedAnalyzerConfigDocuments().Count() +
                                      p.GetRemovedAnalyzerConfigDocuments().Count();

                if (p.GetAddedDocuments().Any() || p.GetRemovedDocuments().Any() ||
                    p.GetAddedAdditionalDocuments().Any() || p.GetRemovedAdditionalDocuments().Any() ||
                    p.GetAddedAnalyzerConfigDocuments().Any() || p.GetRemovedAnalyzerConfigDocuments().Any() ||
                    p.GetAddedMetadataReferences().Any() || p.GetRemovedMetadataReferences().Any() ||
                    p.GetAddedProjectReferences().Any() || p.GetRemovedProjectReferences().Any() ||
                    p.GetAddedAnalyzerReferences().Any() || p.GetRemovedAnalyzerReferences().Any())
                {
                    TotalFilesAffected += 1;  // The project file itself was affected too.
                }
            }

            var totalProjectsAddedOrRemoved = changes.GetAddedProjects().Count() + changes.GetRemovedProjects().Count();

            TotalFilesAffected += totalProjectsAddedOrRemoved;
            TotalProjectsAffected += totalProjectsAddedOrRemoved;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2010-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala
package collection
package generic

import scala.language.higherKinds
import scala.reflect.ClassTag

/** A template for companion objects of `ClassTagTraversable` and
 *  subclasses thereof.
 *
 *  @define coll collection
 *  @define Coll `Traversable`
 *  @define genericCanBuildFromInfo
 *    The standard `CanBuildFrom` instance for $Coll objects.
 *    @author Aleksandar Prokopec
 *    @since 2.8
 */
abstract class ClassTagTraversableFactory[CC[X] <: Traversable[X] with GenericClassTagTraversableTemplate[X, CC]]
              extends GenericClassTagCompanion[CC] {

  class GenericCanBuildFrom[A](implicit tag: ClassTag[A]) extends CanBuildFrom[CC[_], A, CC[A]] {
    def apply(from: CC[_]) = from.genericClassTagBuilder[A]
    def apply = newBuilder[A]
  }
}


text:
require 'yaml'
require 'date'
require 'digest/md5'

module ZAWS
  class Repository
    class Filestore
      attr_accessor :location
      attr_accessor :timeout

      def initialize(empty=false)
        @empty=empty
      end

      def store(key,value,expires,command=nil)
        return if @empty
         storage = {}
         storage['value']=value
         storage['expires']=expires.strftime('%s')
         if command.nil?
           filename=key
         else
           storage['command']=command
           filename=key+Digest::MD5.hexdigest(command)
         end
         File.open("#{@location}/#{filename}","w") do |file|
           file.write storage.to_yaml
         end
      end

      def retrieve(key,command=nil)
        return if @empty
        if command.nil?
           filename=key
        else
           filename=key+Digest::MD5.hexdigest(command)
        end
        if File.exists?("#{@location}/#{filename}")
          storage = YAML.load(File.read("#{@location}/#{filename}"))
          if storage['expires'].to_i > Time.now.to_i
            return storage['value']
          end
        end
      end

    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_margin="5dp"
  android:layout_weight="1"
  android:orientation="vertical">
  <TextView
    android:id="@+id/title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"/>
  <TextView
    android:id="@+id/description"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="12sp"/>
</LinearLayout>


text:
package flex2.compiler.mxml.dom;

import flex2.compiler.mxml.lang.StandardDefs;
import flex2.compiler.util.QName;

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

/**
 * Represents a <Vector> tag in the MXML 2009 language
 * namespace.
 */
public class VectorNode extends Node
{
	public static final Set<QName> attributes;

	static
	{
		attributes = new HashSet<QName>();
		attributes.add(new QName("", StandardDefs.PROP_ID));
		attributes.add(new QName("", StandardDefs.PROP_TYPE));
		attributes.add(new QName("", StandardDefs.PROP_FIXED));
		attributes.add(new QName("", StandardDefs.PROP_INCLUDE_STATES));
		attributes.add(new QName("", StandardDefs.PROP_EXCLUDE_STATES));
		attributes.add(new QName("", StandardDefs.PROP_ITEM_CREATION_POLICY));
		attributes.add(new QName("", StandardDefs.PROP_ITEM_DESTRUCTION_POLICY));
	}

	VectorNode(String uri, String localName, int size)
	{
		super(uri, localName, size);
	}

	public void analyze(Analyzer analyzer)
	{
		analyzer.prepare(this);
		analyzer.analyze(this);
	}
}


text:
def log(level, msg, update_message = false)
  $evm.log(level, "#{msg}")
  $evm.root['miq_provision'].message = "#{msg}" if $evm.root['miq_provision'] && update_message
end

def generate_unique_macaddress(nic_prefix)
  # Check up to 50 times for the existence of a randomly generated mac address
  for i in (1..50)
    new_macaddress = "#{nic_prefix}"+"#{("%02X" % rand(0x3F)).downcase}:#{("%02X" % rand(0xFF)).downcase}:#{("%02X" % rand(0xFF)).downcase}"
    log(:info, "Attempt #{i} - Checking for existence of mac_address: #{new_macaddress}")
    vm = $evm.vmdb('vm').all.detect {|v| v.mac_addresses.include?(new_macaddress)}
    return new_macaddress if vm.nil?
  end
end

nic_prefix = '00:1a:4a:'

case $evm.root['vmdb_object_type']
when 'miq_provision'
  # Get provisioning object
  prov = $evm.root["miq_provision"]
  log(:info, "Provision: #{prov.id} Request: #{prov.miq_provision_request.id} Type: #{prov.type}")

  if prov.type == 'MiqProvisionRedhatViaPxe'
    macaddress = generate_unique_macaddress(nic_prefix)
    #prov.set_network_adapter(0, {:mac_address => macaddress})
    prov.set_option(:mac_address, macaddress)
    log(:info, "Provisioning object updated {:mac_address => #{prov.get_option(:mac_address).inspect}}", true)
  end

  # if prov.type == 'MiqProvisionRedhatViaIso'
  #   macaddress = generate_unique_macaddress(nic_prefix)
  #   #prov.set_network_adapter(0, {:mac_address => macaddress})
  #   prov.set_option(:mac_address, macaddress)
  #   log(:info, "Provisioning object updated {:mac_address => #{prov.get_option(:mac_address).inspect}}", true)
  # end

  # if prov.type == 'MiqProvisionRedhat'
  #   macaddress = generate_unique_macaddress(nic_prefix)
  #   #prov.set_network_adapter(0, {:mac_address => macaddress})
  #   prov.set_option(:mac_address, macaddress)
  #   log(:info, "Provisioning object updated {:mac_address => #{prov.get_option(:mac_address).inspect}}", true)
  # end

when 'vm'
  vm = $evm.root['vm']
  log(:info, "VM: #{vm.name} mac_addresses: #{vm.mac_addresses}")
  macaddress = generate_unique_macaddress(nic_prefix)
  raise if macaddress.nil?
  log(:info, "Found available macaddress: #{macaddress}")
end


text:
<?php

namespace Sitpac\ExtranetBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ServicioAlimentacionRepository extends EntityRepository
{

	public function findtodosalim($estado)
	{
		$em = $this->getEntityManager();
		$consulta = $em->createQuery('
		SELECT s FROM ExtranetBundle:ServicioAlimentacion s
		WHERE  s.estado = :estado
		ORDER BY s.fechaCreacion DESC');
		$consulta->setParameter('estado', $estado);

		return $consulta->getResult();
	}

	public function findserviciosPalim($idprod, $estado)
	{
		$em = $this->getEntityManager();
		$consulta = $em->createQuery('
		SELECT s FROM ExtranetBundle:ServicioAlimentacion s
		WHERE  s.productoproducto = :idprod and s.estado = :estado
		ORDER BY s.fechaCreacion DESC');
		$consulta->setParameter('estado', $estado);
		$consulta->setParameter('idprod', $idprod);

		return $consulta->getResult();
	}

}


text:
package org.pentaho.big.data.api.jdbc.impl;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.osgi.framework.ServiceReference;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Created by bryan on 4/29/16.
 */
@RunWith( MockitoJUnitRunner.class )
public class LazyDelegatingDriverTest {
  @Mock DriverLocatorImpl driverRegistry;
  @Mock HasRegisterDriver hasRegisterDriver;
  @Mock ServiceReference<Driver> badDriverServiceReference;
  @Mock Driver badDriver;
  @Mock ServiceReference<Driver> goodDriverServiceReference;
  @Mock Driver driver;
  @Mock Connection connection;
  @Mock DriverPropertyInfo driverPropertyInfo;
  @Mock Logger logger;
  List<Map.Entry<ServiceReference<Driver>, Driver>> drivers;
  LazyDelegatingDriver lazyDelegatingDriver;
  String testUrl;
  int majorVersion;
  int minorVersion;

  private Map.Entry<ServiceReference<Driver>, Driver> makeEntry( ServiceReference<Driver> serviceReference,
                                                                 Driver driver ) {
    Map.Entry<ServiceReference<Driver>, Driver> entry = mock( Map.Entry.class );
    when( entry.getKey() ).thenReturn( serviceReference );
    when( entry.getValue() ).thenReturn( driver );
    return entry;
  }

  @Before
  public void setup() throws SQLException {
    testUrl = "testUrl";
    majorVersion = 10;
    minorVersion = 11;
    lazyDelegatingDriver = new LazyDelegatingDriver( driverRegistry, hasRegisterDriver );
    drivers = new ArrayList<>();
    drivers.add( makeEntry( badDriverServiceReference, badDriver ) );
    drivers.add( makeEntry( goodDriverServiceReference, driver ) );
    when( driver.connect( testUrl, null ) ).thenReturn( connection );
    when( driver.acceptsURL( testUrl ) ).thenReturn( true );
    when( driver.getPropertyInfo( testUrl, null ) ).thenReturn( new DriverPropertyInfo[] { driverPropertyInfo } );
    when( driver.getMajorVersion() ).thenReturn( majorVersion );
    when( driver.getMinorVersion() ).thenReturn( minorVersion );
    when( driver.getParentLogger() ).thenReturn( logger );
    when( driverRegistry.getDrivers() ).thenReturn( drivers.iterator() );
  }

  @Test
  public void testSimpleConstructor() throws SQLException {
    assertNotNull( new LazyDelegatingDriver( driverRegistry ) );
  }

  @Test
  public void testConnectMatch() throws SQLException {
    assertEquals( connection, lazyDelegatingDriver.connect( testUrl, null ) );
    drivers.clear();
    assertEquals( connection, lazyDelegatingDriver.connect( testUrl, null ) );
  }

  @Test
  public void testConnectNoMatch() throws SQLException {
    assertNull( lazyDelegatingDriver.connect( "badurl", null ) );
  }

  @Test
  public void testAcceptsMatch() throws SQLException {
    assertTrue( lazyDelegatingDriver.acceptsURL( testUrl ) );
    drivers.clear();
    assertTrue( lazyDelegatingDriver.acceptsURL( testUrl ) );
  }

  @Test
  public void testGetPropertyInfoEmpty() throws SQLException {
    assertEquals( 0, lazyDelegatingDriver.getPropertyInfo( testUrl, null ).length );
  }

  @Test
  public void testGetPropertyInfoNotEmpty() throws SQLException {
    assertTrue( lazyDelegatingDriver.acceptsURL( testUrl ) );
    assertEquals( 1, lazyDelegatingDriver.getPropertyInfo( testUrl, null ).length );
    assertEquals( driverPropertyInfo, lazyDelegatingDriver.getPropertyInfo( testUrl, null )[ 0 ] );
  }

  @Test
  public void testGetMajorVersionEmpty() {
    assertEquals( 0, lazyDelegatingDriver.getMajorVersion() );
  }

  @Test
  public void testGetMajorVersionNotEmpty() throws SQLException {
    assertTrue( lazyDelegatingDriver.acceptsURL( testUrl ) );
    assertEquals( majorVersion, lazyDelegatingDriver.getMajorVersion() );
  }

  @Test
  public void testGetMinorVersion() throws SQLException {
    assertTrue( lazyDelegatingDriver.acceptsURL( testUrl ) );
    assertEquals( minorVersion, lazyDelegatingDriver.getMinorVersion() );
  }

  @Test
  public void testGetJdbcCompliant() throws SQLException {
    when( driver.jdbcCompliant() ).thenReturn( true ).thenReturn( false );
    assertTrue( lazyDelegatingDriver.acceptsURL( testUrl ) );
    assertTrue( lazyDelegatingDriver.jdbcCompliant() );
    assertFalse( lazyDelegatingDriver.jdbcCompliant() );
  }

  @Test
  public void testGetParentLoggerEmpty() throws SQLFeatureNotSupportedException {
    assertNull( lazyDelegatingDriver.getParentLogger() );
  }

  @Test
  public void testGetParentLoggerNotEmpty() throws SQLException {
    assertTrue( lazyDelegatingDriver.acceptsURL( testUrl ) );
    assertEquals( logger, lazyDelegatingDriver.getParentLogger() );
  }
}


text:
package org.mitre.midiki.workshop;

import java.io.Serializable;

/**
 * Represents a physical symptom, and whether the symptom must
 * be present or absent. Typically, disease descriptions show those symptoms
 * which must be present, while diagnosis queries may contain symptoms which
 * have been identified as absent (as distinct from symptoms whose status
 * is unknown).
 *
 * @author Carl Burke
 * @version 1.0
 * @since 1.0
 * @see Serializable
 */
public class Symptom implements Serializable
{
    /**
     * The name of the symptom.
     */
    public String name;
    /**
     * true if the symptom is required vs suggestive.
     */
    public boolean required;
    /**
     * true if the symptom is present.
     */
    public boolean present;

    /**
     * Generates a string representation of the symptom.
     *
     * @return a String value
     */
    public String toString()
    {
        StringBuffer sb = new StringBuffer(128);
        sb.append("Symptom(");
        sb.append(name);
        sb.append(",");
        if (required) {
            sb.append("required=yes,");
        } else {
            sb.append("required=no,");
        }
        if (present) {
            sb.append("present=yes");
        } else {
            sb.append("present=no");
        }
        sb.append(")");
        return sb.toString();
    }

    /**
     * Returns true if the symptom matches the query.
     * Since synonyms are not considered, this is a less powerful
     * match than the one performed by WorkshopDatabase
     * in calculating a diagnosis.
     *
     * @param s a Symptom value
     * @return a boolean value
     */
    public boolean matches(Symptom s)
    {
        if (!name.equalsIgnoreCase(s.name)) return false;
        return (present==s.present);
    }

    /**
     * Empty constructor.
     *
     */
    public Symptom()
    {
    }

    /**
     * Creates a new Symptom instance.
     *
     * @param n a String value
     * @param q a boolean value
     * @param p a boolean value
     */
    public Symptom(String n, boolean q, boolean p)
    {
        this();
        name=n; required=q; present=p;
    }

}


text:
"""
    fabcloudkit

    :copyright: (c) 2013 by Rick Bohrer.
    :license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

# pypi
from fabric.context_managers import cd, prefix, settings
from fabric.operations import run, sudo
from fabric.state import env

# package
from fabcloudkit import ctx
from ..build import build_repo, BuildInfo
from ..internal import *
from ..toolbase import Tool
from ..tool.virtualenv import VirtualEnvTool
from ..util import copy_file_from

class PythonBuildTool(Tool):
    def build(self, repos, reference_repo=None, post_build=None, interpreter=None, tarball=False, unittest=None):
        """Performs a 'python' build.

        Performs a python build by running setup.py in each identified repo. If desired, repos can
        be refreshed first (e.g., via git pull).

        :param repos:
            specifies the list of repos in which to run setup.py.

        :param reference_repo:
            optional; the reference repo from which to retrieve the head commit id.
            this id used as a component of the build name. if not specified, the
            first repo in the context is used.

        :param post_build:
            a list of post-build commands. a list of dictionaries. each dict must
            contain the key "command" that specifies the command to execute. optionally,
            it may include a "sudo" value of [True|False], and an "ignore_fail" value
            of [True|False].

        :param interpreter:
            specifies the Python interpreter to use in the build's virtualenv. if
            not specified, the operating system default interpreter is used. note
            that the interpreter must already exist on the system.

        :param tarball:
            True to create a tarball of the build; this is required if any other
            instance will use "copy_from".

        :param unittest:
            TBD

        :return:
            the new build name
        """
        start_msg('Executing build for instance in role "{0}":'.format(env.role_name))

        # increment the build name and create a new virtualenv for the build.
        build_name = self._increment_name(reference_repo)
        build_env_dir = ctx().build_path(build_name)
        VirtualEnvTool().ensure(build_env_dir, interpreter)

        # run "setup.py install" in each repo.
        for repo_name in ([repos] if isinstance(repos, basestring) else repos):
            build_repo(build_env_dir, ctx().get_repo(repo_name))

        # run tests.
        self._unittest(unittest, build_name)

        # save the last known good build-name.
        BuildInfo.set_last_good(build_name)
        if tarball:
            self._tarball(build_name)

        # execute any post-build commands.
        if post_build:
            self._execute_post_build(post_build, build_name)

        # make the build_name available to the caller; it'll be set as an instance-tag.
        succeed_msg('Build completed successfully for role "{0}".'.format(env.role_name))
        env.role.set_env(build_result=build_name)
        return self

    def copy_from(self, role_name, post_build=None, delete_tar=True):
        """Copies an existing build from an instance in the specified role.

        Instead of building itself, a build is copied from another instance to the current
        instance.

        :param role_name: the role of the instance to copy the build tarball from.
        :param post_build: list of post-build commands to execute.
        :param delete_tar: True to delete the tarball, False otherwise.
        :return: the name of the copied build.
        """
        # get the last known good build from the source machine.
        # note: we could alternatively get this from an instance tag.
        message('Copying build from instance in role: "{0}"'.format(role_name))
        inst, role = ctx().get_host_in_role(role_name)
        with settings(host_string=inst.public_dns_name, user=role.user):
            message('Getting last good build-name from: "{0}"'.format(role_name))
            src_build_name = BuildInfo().get_last_good()

        # copy it from the source machine. note that all machines must have been provisioned
        # properly to allow the current machine access to the source machine.
        tarball = self._tarball_name(src_build_name)
        path = ctx().build_path(tarball)
        copy_file_from(role.user, inst.private_dns_name, path, path)

        with cd(ctx().builds_root()):
            # untar it.
            command = 'tar -x --file={tarball}'.format(**locals())
            result = run(command)
            if result.failed:
                raise HaltError('Failed to untar: "{0}"'.format(path))

            # delete the tar.
            if delete_tar:
                run('rm {tarball}'.format(**locals()))

        # update the build information.
        BuildInfo().set_last_good(src_build_name)

        # execute any post-build commands.
        if post_build:
            self._execute_post_build(post_build, src_build_name)

        succeed_msg('Successfully copied build: "{0}"'.format(src_build_name))
        return src_build_name

    def _execute_post_build(self, cmd_lst, build_name):
        message('Running post-build commands:')
        with prefix(VirtualEnvTool.activate_prefix(ctx().build_path(build_name))):
            for desc in cmd_lst:
                f = sudo if desc.get('sudo', False) else run
                result = f(desc['command'])
                if result.failed and not desc.get('ignore_fail', False):
                    raise HaltError('Post-build command failed: "{0}"'.format(desc['command']))
        message('Completed post-build commands.')
        return self

    def _increment_name(self, ref_repo_name):
        # some projects have more than one repo. in this case one is designated as the "reference".
        # the reference repo gives it's most recent commit ID that's used in the new build name.
        # if no reference is given, just use the first (hopefully, the only) repo in the Context.
        if ref_repo_name:
            ref_repo = ctx().get_repo(ref_repo_name)
        else:
            ref_repo = ctx().repos()[0]

        name = BuildInfo.next(ref_repo.dir)
        succeed_msg('Created new build name: "{0}"'.format(name))
        return name

    def _tarball(self, build_name):
        tarball = self._tarball_name(build_name)
        dir_to_tar = ctx().build_path(build_name)

        with cd(ctx().builds_root()):
            options = '--create --gzip --format=ustar --owner=0 --group=0'
            command = 'tar {options} --file={tarball} {build_name}'.format(**locals())
            result = run(command)

        if result.failed:
            raise HaltError('Failed to create tarball for: "{0}"'.format(dir_to_tar))
        succeed_msg('Created build tarball: "{0}"'.format(tarball))
        return self

    def _tarball_name(self, build_name):
        return '{build_name}.tar.gz'.format(**locals())

    def _unittest(self, plan, build_name):
        failed_msg('The action "unittest" is not implemented (yet).')
        return self

# register.
Tool.__tools__['python_build'] = PythonBuildTool


text:
zfs-snapshots
=============

A set of scripts for FreeBSD `periodic(8)` for automated snapshots and backups.

An external script can be triggered for postprocessing of the generated
backups, cleanup of snapshots and cleanup of backups.

Example scripts for encrypted remote storage accessible via FTP are
provided.

Installation
============
1. Copy the periodic scripts in `usr/local/etc/periodic/daily` on your
   system. Place them in `/usr/local/etc/periodic/daily/`
2. Copy the scripts in `usr/local/sbin` onto your system. Place them in
   `/usr/local/sbin/` or where you would prefer them to be.
3. Add the following entries to your `/etc/periodic.conf.local`:

* `daily_zfs_snapshots_enable="YES"`

  Enable or disable the snapshot creation

* `daily_zfs_snapshots_create_weekly="YES"`

  Tag the snapshot on each saturday as weekly

* `daily_zfs_snapshots_create_monthly="YES"`

  Tag the snapshot on the first of each month as monthly

* `daily_zfs_snapshots_datasets_ignore="pool/backup"`

  Which dataset to not create snapshots for. This can be a comma
  separated list of datasets. Child datasets are ignored as well.
  So "pool/backup" also ignores "pool/backup/restore" and
  "pool/backup/test" for example.

* `daily_zfs_snapshots_user_namespace="com.1and1.periodic"`

  The user namespace used for snapshot user properties. Change as you like,
  but needs to be set to a valid value. See `zfs(1)`.

* `daily_zfs_snapshots_backup_enable="YES"`

  Enable or disable the creation of backups from the snapshots.

* `daily_zfs_snapshots_backup_daily_style="differential"`

  This governs how backups from daily snapshots are created. Monthly
  snapshots always create a full stream. Weekly snapshots create an
  incremental stream against the last monthly, or full streams if no
  monthly exists. If this is set to "incremental", the daily snapshots
  always trigger incremental streams against the day before. If set to
  "differential", then incremental streams are generated against the
  last weekly or monthly, whichever is newer. If only daily snapshots
  exist, differential behaves the same as incremental.
  If no prior snapshot exists, a full stream is generated.

* `daily_zfs_snapshots_backup_storage_dir="/backup"`

  Path where the backup streams are to be written to.

* `daily_zfs_snapshots_backup_send_flags="-Dp"`

  Flags to pass to `zfs send.`

* `daily_zfs_snapshots_cleanup_enable="YES"`

  Enable or disable the cleanup routines. Needs to be set to YES for
  the more specific routine's enable/disable to be evaluated.

* `daily_zfs_snapshots_cleanup_viability="10"`

  How many days of snapshots and backups you want to keep. Defaults to
  10 days if unset.

* `daily_zfs_snapshots_cleanup_clear_snapshots="YES"`

  Enable or disable the cleanup of snapshots. All snapshots older than
  specified in the viability option are destroyed. The newest monthly
  as well as the newest weekly snapshot are always kept, if they are
  created.

* `daily_zfs_snapshots_cleanup_script_snapshots="/usr/local/sbin/zfs-snapshots-clean.pl"`

  The script that implements the snapshot cleanup. Adjust to the path
  you used. If you want to trigger your own script, it must implement
  a `-d $days` command line option that the number of days can be
  passed along to.

Enable backup processing
========================

zfs-snapshots can be configured to execute a processing script for every
stream it generated. This script is passed the absolute path of the
generated streamfile as first and only argument. You can enable this by
setting the following option in `periodic.conf.local` to the absolute path
of your processing script:

```
daily_zfs_snapshots_backup_postprocessing="/usr/local/sbin/zfs-snapshots-processing.sh"
```

The example processing script:

1. Generates a random encryption key
2. Encrypts the backup stream with the generated key (AES-256-OFB)
3. Generates an HMAC for the encrypted backup file (SHA512)
4. Encrypts the random key with a RSA public key
5. Packs the encrypted backup, the HMAC and the encrypted key in a tarball
6. Creates a parity2 checksum for the tarball with 3% redundancy
7. Uploads the tarball and the parity2 data to an FTP
8. Cleans up the local files if the upload was successful

This processing script needs to be adjusted for your environment. Maybe
you have SFTP or rsync over SSH available. Maybe you do not need to push
your backups since they are collected? Maybe you do not want to encrypt
your backup (why?!).

Enable storage cleanup
======================

In addition to the snapshot cleanup script, zfs-snapshots can be
configured to trigger a secondary script to cleanup your backup storage.
You can configure this by setting the following two options in
`periodic.conf.local`:

* `daily_zfs_snapshots_cleanup_clear_storage="YES"`

  Enable or disable the storage cleanup script.

* `daily_zfs_snapshots_cleanup_script_storage="/usr/local/sbin/zfs-snapshots-tidy.pl"`

  Absolute path to your storage cleanup script. This too needs to
  implement a `-d $days` command line option if you want to replace it
  with a script for your environment.

The example cleanup script:

1. Retrieves a list of all files on the FTP
2. Filter the list by first removing all par2 files, then all files that
   do not match the regexp that all files created by zfs-snapshots
   should match
3. Marks all backup files that were created in the current period of validity.
   The most recent backup is always marked valid - the script will never
   delete your last backup (unless it has a bug).
4. Marks all backup files that are referenced by a valid incremental
   backup
5. Delete all unmarked files on the list, as well as their par2 recovery
   data.

Best case, the FTP path only contains files uploaded by the example
processing script. It may contain more, but you need to make sure that
those filenames do not match the filter regexp.
Unless of course you want it to also be deleted according to the same
rules. Then go ahead.

Configure the example processing script
=======================================

1. Setup your `/root/.netrc` so it can be used by curl to FTP upload
   the backups. Check the permissions on `/root` and the file itself.
   Be sad that you are stuck with FTP.
2. Specify your RSA public key in line 40 of the script. See the README
   in `usr/local/libdata/zfs-snapshots/` for information how to create a
   RSA keypair with `openssl`'s commandline tools.
3. Specify the FQDN of the FTP server in line 41 of the script
4. Specify the path where the encryption keys should be generated in
   line 42 of the script
5. Remove the exit statement in line 44 of the script
6. Ensure the following commands are available on your system: `openssl`,
   `tar`, `curl`, `par2`

For the path where the encryption keys are generated, you can use a
small `tmpfs`. Remember that ZFS is copy-on-write, so there is really no
secure deletion by selectively overwriting stuff. Use the `late` option
in `fstab` if you need to mount the `tmpfs` into a path created by zfs.

Or read all the rc scripts to know when ftab is processed in relation to
`zfs_enable=YES` automounts.

Configure the example storage cleanup script
============================================

1. Add username, passwort and FQDN information for the FTP to the script
   in lines 64-66.
2. Check that all required Perl modules are available on the system. You
   can check this by using:
   `perl -c /usr/local/sbin/zfs-snapshots-tidy.pl`

LICENSE
======================
This software is released under a 2-clause BSD license.

Additional information
======================
Use at your own risk. Slippery when wet.


text:
/**
 *
 */
package com.google.code.morphia.mapping.validation.fieldrules;

import java.util.Set;

import com.google.code.morphia.annotations.Serialized;
import com.google.code.morphia.mapping.MappedClass;
import com.google.code.morphia.mapping.MappedField;
import com.google.code.morphia.mapping.validation.ConstraintViolation;
import com.google.code.morphia.mapping.validation.ConstraintViolation.Level;
import com.google.code.morphia.utils.ReflectionUtils;

/**
 * @author Uwe Schaefer, (us@thomas-daily.de)
 *
 */
@SuppressWarnings("unchecked")
public class MapKeyDifferentFromString extends FieldConstraint {
	final private static String supportedExample = "(Map<String/Enum/Long/..., ?>)";
	@Override
	protected void check(MappedClass mc, MappedField mf, Set<ConstraintViolation> ve) {
		if (mf.isMap() && (!mf.hasAnnotation(Serialized.class))) {
			Class parameterizedClass = ReflectionUtils.getParameterizedClass(mf.getField(), 0);
			if (parameterizedClass == null) {
				ve.add(new ConstraintViolation(Level.WARNING, mc, mf, this.getClass(),
						"Maps cannot be keyed by Object (Map<Object,?>); Use a parametrized type that is supported " + supportedExample));
			} else if (!parameterizedClass.equals(String.class) && !ReflectionUtils.isPrimitiveLike(parameterizedClass))
				ve
						.add(new ConstraintViolation(Level.FATAL, mc, mf, this.getClass(),
								"Maps must be keyed by a simple type " + supportedExample + "; " + parameterizedClass + " is not supported as a map key type."));
		}
	}
}


text:
package io.grpc.testing.integration;

import static io.grpc.testing.integration.Messages.PayloadType.COMPRESSABLE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;

import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.ComputeEngineCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.OAuth2Credentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.census.CensusContextFactory;
import com.google.census.RpcConstants;
import com.google.census.TagValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.net.HostAndPort;
import com.google.protobuf.ByteString;
import com.google.protobuf.EmptyProtos.Empty;
import com.google.protobuf.MessageLite;

import io.grpc.CallOptions;
import io.grpc.ClientCall;
import io.grpc.Grpc;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.Server;
import io.grpc.ServerCall;
import io.grpc.ServerInterceptor;
import io.grpc.ServerInterceptors;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.auth.MoreCallCredentials;
import io.grpc.internal.AbstractServerImplBuilder;
import io.grpc.internal.GrpcUtil;
import io.grpc.internal.testing.CensusTestUtils.FakeCensusContextFactory;
import io.grpc.internal.testing.CensusTestUtils.MetricsRecord;
import io.grpc.protobuf.ProtoUtils;
import io.grpc.stub.MetadataUtils;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.StreamRecorder;
import io.grpc.testing.TestUtils;
import io.grpc.testing.integration.Messages.Payload;
import io.grpc.testing.integration.Messages.PayloadType;
import io.grpc.testing.integration.Messages.ResponseParameters;
import io.grpc.testing.integration.Messages.SimpleRequest;
import io.grpc.testing.integration.Messages.SimpleResponse;
import io.grpc.testing.integration.Messages.StreamingInputCallRequest;
import io.grpc.testing.integration.Messages.StreamingInputCallResponse;
import io.grpc.testing.integration.Messages.StreamingOutputCallRequest;
import io.grpc.testing.integration.Messages.StreamingOutputCallResponse;

import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.verification.VerificationMode;

import java.io.IOException;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;

/**
 * Abstract base class for all GRPC transport tests.
 */
public abstract class AbstractInteropTest {
  /** Must be at least {@link #unaryPayloadLength()}, plus some to account for encoding overhead. */
  public static final int MAX_MESSAGE_SIZE = 16 * 1024 * 1024;
  public static final Metadata.Key<Messages.SimpleContext> METADATA_KEY =
      ProtoUtils.keyForProto(Messages.SimpleContext.getDefaultInstance());
  private static final AtomicReference<ServerCall<?, ?>> serverCallCapture =
      new AtomicReference<ServerCall<?, ?>>();
  private static final AtomicReference<Metadata> requestHeadersCapture =
      new AtomicReference<Metadata>();
  private static ScheduledExecutorService testServiceExecutor;
  private static Server server;
  private static final FakeCensusContextFactory clientCensusFactory =
      new FakeCensusContextFactory();
  private static final FakeCensusContextFactory serverCensusFactory =
      new FakeCensusContextFactory();
  protected static final Empty EMPTY = Empty.getDefaultInstance();

  protected static void startStaticServer(
      AbstractServerImplBuilder<?> builder, ServerInterceptor ... interceptors) {
    testServiceExecutor = Executors.newScheduledThreadPool(2);

    List<ServerInterceptor> allInterceptors = ImmutableList.<ServerInterceptor>builder()
        .add(TestUtils.recordServerCallInterceptor(serverCallCapture))
        .add(TestUtils.recordRequestHeadersInterceptor(requestHeadersCapture))
        .add(TestUtils.echoRequestHeadersInterceptor(Util.METADATA_KEY))
        .add(interceptors)
        .build();

    builder.addService(ServerInterceptors.intercept(
        new TestServiceImpl(testServiceExecutor),
        allInterceptors));
    builder.censusContextFactory(serverCensusFactory);
    try {
      server = builder.build().start();
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }

  protected static void stopStaticServer() {
    server.shutdownNow();
    testServiceExecutor.shutdown();
  }

  @VisibleForTesting
  static int getPort() {
    return server.getPort();
  }

  protected ManagedChannel channel;
  protected TestServiceGrpc.TestServiceBlockingStub blockingStub;
  protected TestServiceGrpc.TestServiceStub asyncStub;

  /**
   * Must be called by the subclass setup method if overridden.
   */
  @Before
  public void setUp() {
    channel = createChannel();
    blockingStub = TestServiceGrpc.newBlockingStub(channel);
    asyncStub = TestServiceGrpc.newStub(channel);
    requestHeadersCapture.set(null);
    clientCensusFactory.rolloverRecords();
    serverCensusFactory.rolloverRecords();
  }

  /** Clean up. */
  @After
  public void tearDown() throws Exception {
    if (channel != null) {
      channel.shutdown();
    }
  }

  protected abstract ManagedChannel createChannel();

  protected final CensusContextFactory getClientCensusFactory() {
    return clientCensusFactory;
  }

  protected boolean metricsExpected() {
    return true;
  }

  @Test(timeout = 10000)
  public void emptyUnary() throws Exception {
    assertEquals(EMPTY, blockingStub.emptyCall(EMPTY));
  }

  @Test(timeout = 10000)
  public void largeUnary() throws Exception {
    assumeEnoughMemory();
    final SimpleRequest request = SimpleRequest.newBuilder()
        .setResponseSize(314159)
        .setResponseType(PayloadType.COMPRESSABLE)
        .setPayload(Payload.newBuilder()
            .setBody(ByteString.copyFrom(new byte[271828])))
        .build();
    final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
        .setPayload(Payload.newBuilder()
            .setType(PayloadType.COMPRESSABLE)
            .setBody(ByteString.copyFrom(new byte[314159])))
        .build();

    assertEquals(goldenResponse, blockingStub.unaryCall(request));

    if (metricsExpected()) {
      assertMetrics("grpc.testing.TestService/UnaryCall", Status.Code.OK,
          Collections.singleton(request), Collections.singleton(goldenResponse));
    }
  }

  @Test(timeout = 10000)
  public void serverStreaming() throws Exception {
    final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
        .setResponseType(PayloadType.COMPRESSABLE)
        .addResponseParameters(ResponseParameters.newBuilder()
            .setSize(31415))
        .addResponseParameters(ResponseParameters.newBuilder()
            .setSize(9))
        .addResponseParameters(ResponseParameters.newBuilder()
            .setSize(2653))
        .addResponseParameters(ResponseParameters.newBuilder()
            .setSize(58979))
        .build();
    final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[31415])))
            .build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[9])))
            .build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[2653])))
            .build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[58979])))
            .build());

    StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
    asyncStub.streamingOutputCall(request, recorder);
    recorder.awaitCompletion();
    assertSuccess(recorder);
    assertEquals(goldenResponses, recorder.getValues());
  }

  @Test(timeout = 10000)
  public void clientStreaming() throws Exception {
    final List<StreamingInputCallRequest> requests = Arrays.asList(
        StreamingInputCallRequest.newBuilder()
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[27182])))
            .build(),
        StreamingInputCallRequest.newBuilder()
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[8])))
            .build(),
        StreamingInputCallRequest.newBuilder()
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[1828])))
            .build(),
        StreamingInputCallRequest.newBuilder()
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[45904])))
            .build());
    final StreamingInputCallResponse goldenResponse = StreamingInputCallResponse.newBuilder()
        .setAggregatedPayloadSize(74922)
        .build();

    StreamRecorder<StreamingInputCallResponse> responseObserver = StreamRecorder.create();
    StreamObserver<StreamingInputCallRequest> requestObserver =
        asyncStub.streamingInputCall(responseObserver);
    for (StreamingInputCallRequest request : requests) {
      requestObserver.onNext(request);
    }
    requestObserver.onCompleted();
    assertEquals(goldenResponse, responseObserver.firstValue().get());
    responseObserver.awaitCompletion();
  }

  @Test(timeout = 10000)
  public void pingPong() throws Exception {
    final List<StreamingOutputCallRequest> requests = Arrays.asList(
        StreamingOutputCallRequest.newBuilder()
            .addResponseParameters(ResponseParameters.newBuilder()
                .setSize(31415))
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[27182])))
            .build(),
        StreamingOutputCallRequest.newBuilder()
            .addResponseParameters(ResponseParameters.newBuilder()
                .setSize(9))
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[8])))
            .build(),
        StreamingOutputCallRequest.newBuilder()
            .addResponseParameters(ResponseParameters.newBuilder()
                .setSize(2653))
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[1828])))
            .build(),
        StreamingOutputCallRequest.newBuilder()
            .addResponseParameters(ResponseParameters.newBuilder()
                .setSize(58979))
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[45904])))
            .build());
    final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[31415])))
            .build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[9])))
            .build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[2653])))
            .build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[58979])))
            .build());

    @SuppressWarnings("unchecked")
    StreamObserver<StreamingOutputCallResponse> responseObserver = mock(StreamObserver.class);
    StreamObserver<StreamingOutputCallRequest> requestObserver
        = asyncStub.fullDuplexCall(responseObserver);
    for (int i = 0; i < requests.size(); i++) {
      requestObserver.onNext(requests.get(i));
      verify(responseObserver, timeout(operationTimeoutMillis())).onNext(goldenResponses.get(i));
      verifyNoMoreInteractions(responseObserver);
    }
    requestObserver.onCompleted();
    verify(responseObserver, timeout(operationTimeoutMillis())).onCompleted();
    verifyNoMoreInteractions(responseObserver);
  }

  @Test(timeout = 10000)
  public void emptyStream() throws Exception {
    @SuppressWarnings("unchecked")
    StreamObserver<StreamingOutputCallResponse> responseObserver = mock(StreamObserver.class);
    StreamObserver<StreamingOutputCallRequest> requestObserver
        = asyncStub.fullDuplexCall(responseObserver);
    requestObserver.onCompleted();
    verify(responseObserver, timeout(operationTimeoutMillis())).onCompleted();
    verifyNoMoreInteractions(responseObserver);
  }

  @Test(timeout = 10000)
  public void cancelAfterBegin() throws Exception {
    StreamRecorder<StreamingInputCallResponse> responseObserver = StreamRecorder.create();
    StreamObserver<StreamingInputCallRequest> requestObserver =
        asyncStub.streamingInputCall(responseObserver);
    requestObserver.onError(new RuntimeException());
    responseObserver.awaitCompletion();
    assertEquals(Arrays.<StreamingInputCallResponse>asList(), responseObserver.getValues());
    assertEquals(Status.Code.CANCELLED,
        Status.fromThrowable(responseObserver.getError()).getCode());

    if (metricsExpected()) {
      assertClientMetrics("grpc.testing.TestService/StreamingInputCall", Status.Code.CANCELLED);
      // Do not check server-side metrics, because the status on the server side is undetermined.
    }
  }

  @Test(timeout = 10000)
  public void cancelAfterFirstResponse() throws Exception {
    final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
        .addResponseParameters(ResponseParameters.newBuilder()
            .setSize(31415))
        .setPayload(Payload.newBuilder()
            .setBody(ByteString.copyFrom(new byte[27182])))
        .build();
    final StreamingOutputCallResponse goldenResponse = StreamingOutputCallResponse.newBuilder()
        .setPayload(Payload.newBuilder()
            .setType(PayloadType.COMPRESSABLE)
            .setBody(ByteString.copyFrom(new byte[31415])))
        .build();

    @SuppressWarnings("unchecked")
    StreamObserver<StreamingOutputCallResponse> responseObserver = mock(StreamObserver.class);
    StreamObserver<StreamingOutputCallRequest> requestObserver
        = asyncStub.fullDuplexCall(responseObserver);
    requestObserver.onNext(request);
    verify(responseObserver, timeout(operationTimeoutMillis())).onNext(goldenResponse);
    verifyNoMoreInteractions(responseObserver);

    requestObserver.onError(new RuntimeException());
    ArgumentCaptor<Throwable> captor = ArgumentCaptor.forClass(Throwable.class);
    verify(responseObserver, timeout(operationTimeoutMillis())).onError(captor.capture());
    assertEquals(Status.Code.CANCELLED, Status.fromThrowable(captor.getValue()).getCode());
    verifyNoMoreInteractions(responseObserver);

    if (metricsExpected()) {
      assertMetrics("grpc.testing.TestService/FullDuplexCall", Status.Code.CANCELLED);
    }
  }

  @Test(timeout = 10000)
  public void fullDuplexCallShouldSucceed() throws Exception {
    // Build the request.
    List<Integer> responseSizes = Arrays.asList(50, 100, 150, 200);
    StreamingOutputCallRequest.Builder streamingOutputBuilder =
        StreamingOutputCallRequest.newBuilder();
    streamingOutputBuilder.setResponseType(COMPRESSABLE);
    for (Integer size : responseSizes) {
      streamingOutputBuilder.addResponseParametersBuilder().setSize(size).setIntervalUs(0);
    }
    final StreamingOutputCallRequest request = streamingOutputBuilder.build();

    StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
    StreamObserver<StreamingOutputCallRequest> requestStream =
        asyncStub.fullDuplexCall(recorder);

    final int numRequests = 10;
    List<StreamingOutputCallRequest> requests =
        new ArrayList<StreamingOutputCallRequest>(numRequests);
    for (int ix = numRequests; ix > 0; --ix) {
      requests.add(request);
      requestStream.onNext(request);
    }
    requestStream.onCompleted();
    recorder.awaitCompletion();
    assertSuccess(recorder);
    assertEquals(responseSizes.size() * numRequests, recorder.getValues().size());
    for (int ix = 0; ix < recorder.getValues().size(); ++ix) {
      StreamingOutputCallResponse response = recorder.getValues().get(ix);
      assertEquals(COMPRESSABLE, response.getPayload().getType());
      int length = response.getPayload().getBody().size();
      int expectedSize = responseSizes.get(ix % responseSizes.size());
      assertEquals("comparison failed at index " + ix, expectedSize, length);
    }

    if (metricsExpected()) {
      assertMetrics("grpc.testing.TestService/FullDuplexCall", Status.Code.OK, requests,
          recorder.getValues());
    }
  }

  @Test(timeout = 10000)
  public void halfDuplexCallShouldSucceed() throws Exception {
    // Build the request.
    List<Integer> responseSizes = Arrays.asList(50, 100, 150, 200);
    StreamingOutputCallRequest.Builder streamingOutputBuilder =
        StreamingOutputCallRequest.newBuilder();
    streamingOutputBuilder.setResponseType(COMPRESSABLE);
    for (Integer size : responseSizes) {
      streamingOutputBuilder.addResponseParametersBuilder().setSize(size).setIntervalUs(0);
    }
    final StreamingOutputCallRequest request = streamingOutputBuilder.build();

    StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
    StreamObserver<StreamingOutputCallRequest> requestStream = asyncStub.halfDuplexCall(recorder);

    final int numRequests = 10;
    List<StreamingOutputCallRequest> requests =
        new ArrayList<StreamingOutputCallRequest>(numRequests);
    for (int ix = numRequests; ix > 0; --ix) {
      requests.add(request);
      requestStream.onNext(request);
    }
    requestStream.onCompleted();
    recorder.awaitCompletion();
    assertSuccess(recorder);
    assertEquals(responseSizes.size() * numRequests, recorder.getValues().size());
    for (int ix = 0; ix < recorder.getValues().size(); ++ix) {
      StreamingOutputCallResponse response = recorder.getValues().get(ix);
      assertEquals(COMPRESSABLE, response.getPayload().getType());
      int length = response.getPayload().getBody().size();
      int expectedSize = responseSizes.get(ix % responseSizes.size());
      assertEquals("comparison failed at index " + ix, expectedSize, length);
    }
  }

  @Test(timeout = 10000)
  public void serverStreamingShouldBeFlowControlled() throws Exception {
    final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
        .setResponseType(COMPRESSABLE)
        .addResponseParameters(ResponseParameters.newBuilder().setSize(100000))
        .addResponseParameters(ResponseParameters.newBuilder().setSize(100001))
        .build();
    final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[100000]))).build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[100001]))).build());

    long start = System.nanoTime();

    final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(10);
    ClientCall<StreamingOutputCallRequest, StreamingOutputCallResponse> call =
        channel.newCall(TestServiceGrpc.METHOD_STREAMING_OUTPUT_CALL, CallOptions.DEFAULT);
    call.start(new ClientCall.Listener<StreamingOutputCallResponse>() {
      @Override
      public void onHeaders(Metadata headers) {}

      @Override
      public void onMessage(final StreamingOutputCallResponse message) {
        queue.add(message);
      }

      @Override
      public void onClose(Status status, Metadata trailers) {
        queue.add(status);
      }
    }, new Metadata());
    call.sendMessage(request);
    call.halfClose();

    // Time how long it takes to get the first response.
    call.request(1);
    assertEquals(goldenResponses.get(0),
        queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
    long firstCallDuration = System.nanoTime() - start;

    // Without giving additional flow control, make sure that we don't get another response. We wait
    // until we are comfortable the next message isn't coming. We may have very low nanoTime
    // resolution (like on Windows) or be using a testing, in-process transport where message
    // handling is instantaneous. In both cases, firstCallDuration may be 0, so round up sleep time
    // to at least 1ms.
    assertNull(queue.poll(Math.max(firstCallDuration * 4, 1 * 1000 * 1000), TimeUnit.NANOSECONDS));

    // Make sure that everything still completes.
    call.request(1);
    assertEquals(goldenResponses.get(1),
        queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
    assertEquals(Status.OK, queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
  }

  @Test(timeout = 30000)
  public void veryLargeRequest() throws Exception {
    assumeEnoughMemory();
    final SimpleRequest request = SimpleRequest.newBuilder()
        .setPayload(Payload.newBuilder()
            .setType(PayloadType.COMPRESSABLE)
            .setBody(ByteString.copyFrom(new byte[unaryPayloadLength()])))
        .setResponseSize(10)
        .setResponseType(PayloadType.COMPRESSABLE)
        .build();
    final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
        .setPayload(Payload.newBuilder()
            .setType(PayloadType.COMPRESSABLE)
            .setBody(ByteString.copyFrom(new byte[10])))
        .build();

    assertEquals(goldenResponse, blockingStub.unaryCall(request));
  }

  @Test(timeout = 30000)
  public void veryLargeResponse() throws Exception {
    assumeEnoughMemory();
    final SimpleRequest request = SimpleRequest.newBuilder()
        .setResponseSize(unaryPayloadLength())
        .setResponseType(PayloadType.COMPRESSABLE)
        .build();
    final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
        .setPayload(Payload.newBuilder()
            .setType(PayloadType.COMPRESSABLE)
            .setBody(ByteString.copyFrom(new byte[unaryPayloadLength()])))
        .build();

    assertEquals(goldenResponse, blockingStub.unaryCall(request));
  }

  @Test(timeout = 10000)
  public void exchangeMetadataUnaryCall() throws Exception {
    TestServiceGrpc.TestServiceBlockingStub stub =
        TestServiceGrpc.newBlockingStub(channel);

    // Capture the metadata exchange
    Metadata fixedHeaders = new Metadata();
    // Send a context proto (as it's in the default extension registry)
    Messages.SimpleContext contextValue =
        Messages.SimpleContext.newBuilder().setValue("dog").build();
    fixedHeaders.put(METADATA_KEY, contextValue);
    stub = MetadataUtils.attachHeaders(stub, fixedHeaders);
    // .. and expect it to be echoed back in trailers
    AtomicReference<Metadata> trailersCapture = new AtomicReference<Metadata>();
    AtomicReference<Metadata> headersCapture = new AtomicReference<Metadata>();
    stub = MetadataUtils.captureMetadata(stub, headersCapture, trailersCapture);

    assertNotNull(stub.emptyCall(EMPTY));

    // Assert that our side channel object is echoed back in both headers and trailers
    Assert.assertEquals(contextValue, headersCapture.get().get(METADATA_KEY));
    Assert.assertEquals(contextValue, trailersCapture.get().get(METADATA_KEY));
  }

  @Test(timeout = 10000)
  public void exchangeMetadataStreamingCall() throws Exception {
    TestServiceGrpc.TestServiceStub stub = TestServiceGrpc.newStub(channel);

    // Capture the metadata exchange
    Metadata fixedHeaders = new Metadata();
    // Send a context proto (as it's in the default extension registry)
    Messages.SimpleContext contextValue =
        Messages.SimpleContext.newBuilder().setValue("dog").build();
    fixedHeaders.put(METADATA_KEY, contextValue);
    stub = MetadataUtils.attachHeaders(stub, fixedHeaders);
    // .. and expect it to be echoed back in trailers
    AtomicReference<Metadata> trailersCapture = new AtomicReference<Metadata>();
    AtomicReference<Metadata> headersCapture = new AtomicReference<Metadata>();
    stub = MetadataUtils.captureMetadata(stub, headersCapture, trailersCapture);

    List<Integer> responseSizes = Arrays.asList(50, 100, 150, 200);
    Messages.StreamingOutputCallRequest.Builder streamingOutputBuilder =
        Messages.StreamingOutputCallRequest.newBuilder();
    streamingOutputBuilder.setResponseType(COMPRESSABLE);
    for (Integer size : responseSizes) {
      streamingOutputBuilder.addResponseParametersBuilder().setSize(size).setIntervalUs(0);
    }
    final Messages.StreamingOutputCallRequest request = streamingOutputBuilder.build();

    StreamRecorder<Messages.StreamingOutputCallResponse> recorder = StreamRecorder.create();
    StreamObserver<Messages.StreamingOutputCallRequest> requestStream =
        stub.fullDuplexCall(recorder);

    final int numRequests = 10;
    List<StreamingOutputCallRequest> requests =
        new ArrayList<StreamingOutputCallRequest>(numRequests);

    for (int ix = numRequests; ix > 0; --ix) {
      requests.add(request);
      requestStream.onNext(request);
    }
    requestStream.onCompleted();
    recorder.awaitCompletion();
    assertSuccess(recorder);
    org.junit.Assert.assertEquals(responseSizes.size() * numRequests, recorder.getValues().size());

    // Assert that our side channel object is echoed back in both headers and trailers
    Assert.assertEquals(contextValue, headersCapture.get().get(METADATA_KEY));
    Assert.assertEquals(contextValue, trailersCapture.get().get(METADATA_KEY));
  }

  @Test(timeout = 10000)
  public void sendsTimeoutHeader() {
    long configuredTimeoutMinutes = 100;
    TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel)
        .withDeadlineAfter(configuredTimeoutMinutes, TimeUnit.MINUTES);
    stub.emptyCall(EMPTY);
    long transferredTimeoutMinutes = TimeUnit.NANOSECONDS.toMinutes(
        requestHeadersCapture.get().get(GrpcUtil.TIMEOUT_KEY));
    Assert.assertTrue(
        "configuredTimeoutMinutes=" + configuredTimeoutMinutes
            + ", transferredTimeoutMinutes=" + transferredTimeoutMinutes,
        configuredTimeoutMinutes - transferredTimeoutMinutes >= 0
            && configuredTimeoutMinutes - transferredTimeoutMinutes <= 1);
  }

  @Test
  public void deadlineNotExceeded() {
    // warm up the channel and JVM
    blockingStub.emptyCall(Empty.getDefaultInstance());
    TestServiceGrpc.newBlockingStub(channel)
        .withDeadlineAfter(10, TimeUnit.SECONDS)
        .streamingOutputCall(StreamingOutputCallRequest.newBuilder()
            .addResponseParameters(ResponseParameters.newBuilder()
                .setIntervalUs(0))
                .build()).next();
  }

  @Test(timeout = 10000)
  public void deadlineExceeded() {
    // warm up the channel and JVM
    blockingStub.emptyCall(Empty.getDefaultInstance());
    TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel)
        .withDeadlineAfter(10, TimeUnit.MILLISECONDS);
    StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
        .addResponseParameters(ResponseParameters.newBuilder()
            .setIntervalUs(20000))
        .build();
    try {
      stub.streamingOutputCall(request).next();
      fail("Expected deadline to be exceeded");
    } catch (StatusRuntimeException ex) {
      assertEquals(Status.DEADLINE_EXCEEDED.getCode(), ex.getStatus().getCode());
    }
    if (metricsExpected()) {
      assertMetrics("grpc.testing.TestService/EmptyCall", Status.Code.OK);
      assertClientMetrics("grpc.testing.TestService/StreamingOutputCall",
          Status.Code.DEADLINE_EXCEEDED);
      // Do not check server-side metrics, because the status on the server side is undetermined.
    }
  }

  @Test(timeout = 10000)
  public void deadlineExceededServerStreaming() throws Exception {
    // warm up the channel and JVM
    blockingStub.emptyCall(Empty.getDefaultInstance());
    ResponseParameters.Builder responseParameters = ResponseParameters.newBuilder()
        .setSize(1)
        .setIntervalUs(10000);
    StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
        .setResponseType(PayloadType.COMPRESSABLE)
        .addResponseParameters(responseParameters)
        .addResponseParameters(responseParameters)
        .addResponseParameters(responseParameters)
        .addResponseParameters(responseParameters)
        .build();
    StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
    TestServiceGrpc.newStub(channel)
        .withDeadlineAfter(30, TimeUnit.MILLISECONDS)
        .streamingOutputCall(request, recorder);
    recorder.awaitCompletion();
    assertEquals(Status.DEADLINE_EXCEEDED.getCode(),
        Status.fromThrowable(recorder.getError()).getCode());
    if (metricsExpected()) {
      assertMetrics("grpc.testing.TestService/EmptyCall", Status.Code.OK);
      assertClientMetrics("grpc.testing.TestService/StreamingOutputCall",
          Status.Code.DEADLINE_EXCEEDED);
      // Do not check server-side metrics, because the status on the server side is undetermined.
    }
  }

  @Test(timeout = 10000)
  public void deadlineInPast() throws Exception {
    // Test once with idle channel and once with active channel
    try {
      TestServiceGrpc.newBlockingStub(channel)
          .withDeadlineAfter(-10, TimeUnit.SECONDS)
          .emptyCall(Empty.getDefaultInstance());
      fail("Should have thrown");
    } catch (StatusRuntimeException ex) {
      assertEquals(Status.Code.DEADLINE_EXCEEDED, ex.getStatus().getCode());
    }
    if (metricsExpected()) {
      assertClientMetrics("grpc.testing.TestService/EmptyCall", Status.Code.DEADLINE_EXCEEDED);
    }

    // warm up the channel
    blockingStub.emptyCall(Empty.getDefaultInstance());
    try {
      TestServiceGrpc.newBlockingStub(channel)
          .withDeadlineAfter(-10, TimeUnit.SECONDS)
          .emptyCall(Empty.getDefaultInstance());
      fail("Should have thrown");
    } catch (StatusRuntimeException ex) {
      assertEquals(Status.Code.DEADLINE_EXCEEDED, ex.getStatus().getCode());
    }
    if (metricsExpected()) {
      assertMetrics("grpc.testing.TestService/EmptyCall", Status.Code.OK);
      assertClientMetrics("grpc.testing.TestService/EmptyCall", Status.Code.DEADLINE_EXCEEDED);
    }
  }

  protected int unaryPayloadLength() {
    // 10MiB.
    return 10485760;
  }

  @Test(timeout = 10000)
  public void gracefulShutdown() throws Exception {
    final List<StreamingOutputCallRequest> requests = Arrays.asList(
        StreamingOutputCallRequest.newBuilder()
            .addResponseParameters(ResponseParameters.newBuilder()
                .setSize(3))
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[2])))
            .build(),
        StreamingOutputCallRequest.newBuilder()
            .addResponseParameters(ResponseParameters.newBuilder()
                .setSize(1))
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[7])))
            .build(),
        StreamingOutputCallRequest.newBuilder()
            .addResponseParameters(ResponseParameters.newBuilder()
                .setSize(4))
            .setPayload(Payload.newBuilder()
                .setBody(ByteString.copyFrom(new byte[1])))
            .build());
    final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[3])))
            .build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[1])))
            .build(),
        StreamingOutputCallResponse.newBuilder()
            .setPayload(Payload.newBuilder()
                .setType(PayloadType.COMPRESSABLE)
                .setBody(ByteString.copyFrom(new byte[4])))
            .build());

    @SuppressWarnings("unchecked")
    StreamObserver<StreamingOutputCallResponse> responseObserver = mock(StreamObserver.class);
    StreamObserver<StreamingOutputCallRequest> requestObserver
        = asyncStub.fullDuplexCall(responseObserver);
    requestObserver.onNext(requests.get(0));
    verify(responseObserver, timeout(operationTimeoutMillis())).onNext(goldenResponses.get(0));
    // Initiate graceful shutdown.
    channel.shutdown();
    requestObserver.onNext(requests.get(1));
    verify(responseObserver, timeout(operationTimeoutMillis())).onNext(goldenResponses.get(1));
    // The previous ping-pong could have raced with the shutdown, but this one certainly shouldn't.
    requestObserver.onNext(requests.get(2));
    verify(responseObserver, timeout(operationTimeoutMillis())).onNext(goldenResponses.get(2));
    requestObserver.onCompleted();
    verify(responseObserver, timeout(operationTimeoutMillis())).onCompleted();
    verifyNoMoreInteractions(responseObserver);
  }

  /** Sends an rpc to an unimplemented method within TestService. */
  @Test(timeout = 10000)
  public void unimplementedMethod() {
    try {
      blockingStub.unimplementedCall(Empty.getDefaultInstance());
      fail();
    } catch (StatusRuntimeException e) {
      assertEquals(Status.UNIMPLEMENTED.getCode(), e.getStatus().getCode());
    }

    if (metricsExpected()) {
      assertClientMetrics("grpc.testing.TestService/UnimplementedCall",
          Status.Code.UNIMPLEMENTED);
    }
  }

  /** Sends an rpc to an unimplemented service on the server. */
  @Test(timeout = 10000)
  public void unimplementedService() {
    UnimplementedServiceGrpc.UnimplementedServiceBlockingStub stub =
        UnimplementedServiceGrpc.newBlockingStub(channel);
    try {
      stub.unimplementedCall(Empty.getDefaultInstance());
      fail();
    } catch (StatusRuntimeException e) {
      assertEquals(Status.UNIMPLEMENTED.getCode(), e.getStatus().getCode());
    }

    if (metricsExpected()) {
      assertMetrics("grpc.testing.UnimplementedService/UnimplementedCall",
          Status.Code.UNIMPLEMENTED);
    }
  }

  /** Start a fullDuplexCall which the server will not respond, and verify the deadline expires. */
  @Test(timeout = 10000)
  public void timeoutOnSleepingServer() {
    TestServiceGrpc.TestServiceStub stub = TestServiceGrpc.newStub(channel)
        .withDeadlineAfter(1, TimeUnit.MILLISECONDS);
    @SuppressWarnings("unchecked")
    StreamObserver<StreamingOutputCallResponse> responseObserver = mock(StreamObserver.class);
    StreamObserver<StreamingOutputCallRequest> requestObserver
        = stub.fullDuplexCall(responseObserver);

    StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
        .setPayload(Payload.newBuilder()
            .setBody(ByteString.copyFrom(new byte[27182])))
        .build();
    try {
      requestObserver.onNext(request);
    } catch (IllegalStateException expected) {
      // This can happen if the stream has already been terminated due to deadline exceeded.
    }

    ArgumentCaptor<Throwable> captor = ArgumentCaptor.forClass(Throwable.class);
    verify(responseObserver, timeout(operationTimeoutMillis())).onError(captor.capture());
    assertEquals(Status.DEADLINE_EXCEEDED.getCode(),
        Status.fromThrowable(captor.getValue()).getCode());
    verifyNoMoreInteractions(responseObserver);

    if (metricsExpected()) {
      assertClientMetrics("grpc.testing.TestService/FullDuplexCall", Status.Code.DEADLINE_EXCEEDED);
      // Do not check server-side metrics, because the status on the server side is undetermined.
    }
  }

  /** Sends a large unary rpc with service account credentials. */
  public void serviceAccountCreds(String jsonKey, InputStream credentialsStream, String authScope)
      throws Exception {
    // cast to ServiceAccountCredentials to double-check the right type of object was created.
    GoogleCredentials credentials =
        ServiceAccountCredentials.class.cast(GoogleCredentials.fromStream(credentialsStream));
    credentials = credentials.createScoped(Arrays.<String>asList(authScope));
    TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
        .withCallCredentials(MoreCallCredentials.from(credentials));
    final SimpleRequest request = SimpleRequest.newBuilder()
        .setFillUsername(true)
        .setFillOauthScope(true)
        .setResponseSize(314159)
        .setResponseType(PayloadType.COMPRESSABLE)
        .setPayload(Payload.newBuilder()
            .setBody(ByteString.copyFrom(new byte[271828])))
        .build();

    final SimpleResponse response = stub.unaryCall(request);
    assertFalse(response.getUsername().isEmpty());
    assertTrue("Received username: " + response.getUsername(),
        jsonKey.contains(response.getUsername()));
    assertFalse(response.getOauthScope().isEmpty());
    assertTrue("Received oauth scope: " + response.getOauthScope(),
        authScope.contains(response.getOauthScope()));

    final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
        .setOauthScope(response.getOauthScope())
        .setUsername(response.getUsername())
        .setPayload(Payload.newBuilder()
            .setType(PayloadType.COMPRESSABLE)
            .setBody(ByteString.copyFrom(new byte[314159])))
        .build();
    assertEquals(goldenResponse, response);
  }

  /** Sends a large unary rpc with compute engine credentials. */
  public void computeEngineCreds(String serviceAccount, String oauthScope) throws Exception {
    ComputeEngineCredentials credentials = new ComputeEngineCredentials();
    TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
        .withCallCredentials(MoreCallCredentials.from(credentials));
    final SimpleRequest request = SimpleRequest.newBuilder()
        .setFillUsername(true)
        .setFillOauthScope(true)
        .setResponseSize(314159)
        .setResponseType(PayloadType.COMPRESSABLE)
        .setPayload(Payload.newBuilder()
            .setBody(ByteString.copyFrom(new byte[271828])))
        .build();

    final SimpleResponse response = stub.unaryCall(request);
    assertEquals(serviceAccount, response.getUsername());
    assertFalse(response.getOauthScope().isEmpty());
    assertTrue("Received oauth scope: " + response.getOauthScope(),
        oauthScope.contains(response.getOauthScope()));

    final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
        .setOauthScope(response.getOauthScope())
        .setUsername(response.getUsername())
        .setPayload(Payload.newBuilder()
            .setType(PayloadType.COMPRESSABLE)
            .setBody(ByteString.copyFrom(new byte[314159])))
        .build();
    assertEquals(goldenResponse, response);
  }

  /** Test JWT-based auth. */
  public void jwtTokenCreds(InputStream serviceAccountJson) throws Exception {
    final SimpleRequest request = SimpleRequest.newBuilder()
        .setResponseType(PayloadType.COMPRESSABLE)
        .setResponseSize(314159)
        .setPayload(Payload.newBuilder()
            .setBody(ByteString.copyFrom(new byte[271828])))
        .setFillUsername(true)
        .build();

    ServiceAccountCredentials credentials = (ServiceAccountCredentials)
        GoogleCredentials.fromStream(serviceAccountJson);
    TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
        .withCallCredentials(MoreCallCredentials.from(credentials));
    SimpleResponse response = stub.unaryCall(request);
    assertEquals(credentials.getClientEmail(), response.getUsername());
    assertEquals(314159, response.getPayload().getBody().size());
  }

  /** Sends a unary rpc with raw oauth2 access token credentials. */
  public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope)
      throws Exception {
    GoogleCredentials utilCredentials =
        GoogleCredentials.fromStream(credentialsStream);
    utilCredentials = utilCredentials.createScoped(Arrays.<String>asList(authScope));
    AccessToken accessToken = utilCredentials.refreshAccessToken();

    // TODO(madongfly): The Auth library may have something like AccessTokenCredentials in the
    // future, change to the official implementation then.
    OAuth2Credentials credentials = new OAuth2Credentials(accessToken) {
      @Override
      public AccessToken refreshAccessToken() throws IOException {
        throw new IOException("This credential is based on a certain AccessToken, "
            + "so you can not refresh AccessToken");
      }
    };

    TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
        .withCallCredentials(MoreCallCredentials.from(credentials));
    final SimpleRequest request = SimpleRequest.newBuilder()
        .setFillUsername(true)
        .setFillOauthScope(true)
        .build();

    final SimpleResponse response = stub.unaryCall(request);
    assertFalse(response.getUsername().isEmpty());
    assertTrue("Received username: " + response.getUsername(),
        jsonKey.contains(response.getUsername()));
    assertFalse(response.getOauthScope().isEmpty());
    assertTrue("Received oauth scope: " + response.getOauthScope(),
        authScope.contains(response.getOauthScope()));
  }

  /** Sends a unary rpc with "per rpc" raw oauth2 access token credentials. */
  public void perRpcCreds(String jsonKey, InputStream credentialsStream, String oauthScope)
      throws Exception {
    // In gRpc Java, we don't have per Rpc credentials, user can use an intercepted stub only once
    // for that purpose.
    // So, this test is identical to oauth2_auth_token test.
    oauth2AuthToken(jsonKey, credentialsStream, oauthScope);
  }

  protected static void assertSuccess(StreamRecorder<?> recorder) {
    if (recorder.getError() != null) {
      throw new AssertionError(recorder.getError());
    }
  }

  /** Helper for asserting remote address {@link io.grpc.ServerCall#attributes()} */
  protected void assertRemoteAddr(String expectedRemoteAddress) {
    TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel)
            .withDeadlineAfter(5, TimeUnit.SECONDS);

    stub.unaryCall(SimpleRequest.getDefaultInstance());

    HostAndPort remoteAddress = HostAndPort.fromString(serverCallCapture.get().attributes()
            .get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR).toString());
    assertEquals(expectedRemoteAddress, remoteAddress.getHostText());
  }

  /** Helper for asserting TLS info in SSLSession {@link io.grpc.ServerCall#attributes()} */
  protected void assertX500SubjectDn(String tlsInfo) {
    TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel)
            .withDeadlineAfter(5, TimeUnit.SECONDS);

    stub.unaryCall(SimpleRequest.getDefaultInstance());

    List<Certificate> certificates = Lists.newArrayList();
    SSLSession sslSession =
        serverCallCapture.get().attributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION);
    try {
      certificates = Arrays.asList(sslSession.getPeerCertificates());
    } catch (SSLPeerUnverifiedException e) {
      fail("No cert");
    }

    X509Certificate x509cert = (X509Certificate) certificates.get(0);

    assertEquals(1, certificates.size());
    assertEquals(tlsInfo, x509cert.getSubjectDN().toString());
  }

  protected int operationTimeoutMillis() {
    return 5000;
  }

  /**
   * Some tests run on memory constrained environments.  Rather than OOM, just give up.  64 is
   * choosen as a maximum amount of memory a large test would need.
   */
  private static void assumeEnoughMemory() {
    Runtime r = Runtime.getRuntime();
    long usedMem = r.totalMemory() - r.freeMemory();
    long actuallyFreeMemory = r.maxMemory() - usedMem;
    Assume.assumeTrue(
        actuallyFreeMemory + " is not sufficient to run this test",
        actuallyFreeMemory >= 64 * 1024 * 1024);
  }

  /**
   * Wrapper around {@link Mockito#verify}, to keep log spam down on failure.
   */
  private static <T> T verify(T mock, VerificationMode mode) {
    try {
      return Mockito.verify(mock, mode);
    } catch (AssertionError e) {
      String msg = e.getMessage();
      if (msg.length() >= 256) {
        throw new AssertionError(msg.substring(0, 256), e);
      }
      throw e;
    }

  }

  /**
   * Wrapper around {@link Mockito#verify}, to keep log spam down on failure.
   */
  private static void verifyNoMoreInteractions(Object... mocks) {
    try {
      Mockito.verifyNoMoreInteractions(mocks);
    } catch (AssertionError e) {
      String msg = e.getMessage();
      if (msg.length() >= 256) {
        throw new AssertionError(msg.substring(0, 256), e);
      }
      throw e;
    }
  }

  /**
   * Poll the next metrics record and check it against the provided information, including the
   * message sizes.
   */
  private void assertMetrics(String method, Status.Code status,
      Collection<? extends MessageLite> requests,
      Collection<? extends MessageLite> responses) {
    assertClientMetrics(method, status, requests, responses);
    assertServerMetrics(method, status, requests, responses);
  }

  /**
   * Poll the next metrics record and check it against the provided information, without checking
   * the message sizes.
   */
  private void assertMetrics(String method, Status.Code status) {
    assertMetrics(method, status, null, null);
  }

  private void assertClientMetrics(String method, Status.Code status,
      Collection<? extends MessageLite> requests, Collection<? extends MessageLite> responses) {
    MetricsRecord clientRecord = clientCensusFactory.pollRecord();
    assertNotNull("clientRecord is not null", clientRecord);
    checkTags(clientRecord, false, method, status);
    if (requests != null && responses != null) {
      checkMetrics(clientRecord, false, requests, responses);
    }
  }

  private void assertClientMetrics(String method, Status.Code status) {
    assertClientMetrics(method, status, null, null);
  }

  private void assertServerMetrics(String method, Status.Code status,
      Collection<? extends MessageLite> requests, Collection<? extends MessageLite> responses) {
    AssertionError checkFailure = null;
    // Because the server doesn't restart between tests, it may still be processing the requests
    // from the previous tests when a new test starts, thus the test may see metrics from previous
    // tests.  The best we can do here is to exhaust all records and find one that matches the given
    // conditions.
    while (true) {
      MetricsRecord serverRecord;
      try {
        // On the server, the stats is finalized in ServerStreamListener.closed(), which can be run
        // after the client receives the final status.  So we use a timeout.
        serverRecord = serverCensusFactory.pollRecord(1, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      if (serverRecord == null) {
        break;
      }
      try {
        checkTags(serverRecord, true, method, status);
        if (requests != null && responses != null) {
          checkMetrics(serverRecord, true, requests, responses);
        }
        return;  // passed
      } catch (AssertionError e) {
        // May be the fallout from a previous test, continue trying
        checkFailure = e;
      }
    }
    if (checkFailure == null) {
      throw new AssertionError("No record found");
    }
    throw checkFailure;
  }

  private static void checkTags(
      MetricsRecord record, boolean server, String methodName, Status.Code status) {
    TagValue methodNameTag = record.tags.get(
        server ? RpcConstants.RPC_SERVER_METHOD : RpcConstants.RPC_CLIENT_METHOD);
    assertNotNull("method name tagged", methodNameTag);
    assertEquals("method names match", methodName, methodNameTag.toString());
    TagValue statusTag = record.tags.get(RpcConstants.RPC_STATUS);
    assertNotNull("status tagged", statusTag);
    assertEquals(status.toString(), statusTag.toString());
  }

  private static void checkMetrics(MetricsRecord record, boolean server,
      Collection<? extends MessageLite> requests, Collection<? extends MessageLite> responses) {
    int uncompressedRequestsSize = 0;
    for (MessageLite request : requests) {
      uncompressedRequestsSize += request.getSerializedSize();
    }
    int uncompressedResponsesSize = 0;
    for (MessageLite response : responses) {
      uncompressedResponsesSize += response.getSerializedSize();
    }
    if (server) {
      assertEquals(uncompressedRequestsSize,
          record.getMetricAsLongOrFail(RpcConstants.RPC_SERVER_UNCOMPRESSED_REQUEST_BYTES));
      assertEquals(uncompressedResponsesSize,
          record.getMetricAsLongOrFail(RpcConstants.RPC_SERVER_UNCOMPRESSED_RESPONSE_BYTES));
      // It's impossible to get the expected wire sizes because it may be compressed, so we just
      // check if they are recorded.
      assertNotNull(record.getMetric(RpcConstants.RPC_SERVER_REQUEST_BYTES));
      assertNotNull(record.getMetric(RpcConstants.RPC_SERVER_RESPONSE_BYTES));
    } else {
      assertEquals(uncompressedRequestsSize,
          record.getMetricAsLongOrFail(RpcConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
      assertEquals(uncompressedResponsesSize,
          record.getMetricAsLongOrFail(RpcConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
      // It's impossible to get the expected wire sizes because it may be compressed, so we just
      // check if they are recorded.
      assertNotNull(record.getMetric(RpcConstants.RPC_CLIENT_REQUEST_BYTES));
      assertNotNull(record.getMetric(RpcConstants.RPC_CLIENT_RESPONSE_BYTES));
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuizzByLeapMotionProject
{
    class Quiz
    {
        private int id;
        private String ListQuestion;
        private String[] ListReponse;

        public Quiz(int id, String Question, String[] Reponse)
        {
            this.id = id;
            this.ListQuestion = Question;
            this.ListReponse = Reponse;
        }

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

        public String getQuestion()
        {
            return this.ListQuestion;
        }

        public void setQuestion(String question)
        {
            this.ListQuestion = question;
        }

        public String[] getListReponse()
        {
            return this.ListReponse;
        }

        public void setListReponse(String[] reponse)
        {
            this.ListReponse = reponse;
        }
    }
}


text:
<?php

namespace BitWeb\Stdlib;

abstract class AbstractConfiguration
{
    public function __construct($config = null)
    {
        if (null !== $config) {
            if (is_array($config)) {
                $this->processArray($config);
            } else {
                throw new \InvalidArgumentException(
                    'Parameter to ' . get_class($this) . ' \'s constructor must be an array'
                );
            }
        }
    }

    protected function processArray($config)
    {
        foreach ($config as $key => $value) {
            $setter = $this->assembleSetterNameFromConfigKey($key);
            $this->{$setter}($value);
        }
    }

    protected function assembleSetterNameFromConfigKey($key)
    {
        $parts = explode('_', $key);
        $parts = array_map('ucfirst', $parts);
        $setter = 'set' . implode('', $parts);
        if (!method_exists($this, $setter)) {
            throw new \BadMethodCallException(
                'The configuration key "' . $key . '" does not have a matching ' . $setter . ' setter method which must be defined'
            );
        }
        return $setter;
    }
}


text:
package com.octopod.suite;

import com.octopod.suite.build.BukgetPluginFinder;
import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;

public class PluginSuitePlugin extends JavaPlugin{

	final static public String pre = ChatColor.DARK_GRAY + "[" + ChatColor.LIGHT_PURPLE + "PluginSuite" + ChatColor.DARK_GRAY + "] " + ChatColor.WHITE;

	static public PluginSuitePlugin self;

    @Override
    public void onEnable()
	{
        self = this;

		PluginSuite.registerFinder("bukget", new BukgetPluginFinder());
		//PluginSuite.registerRepo("jenkins", new JenkinsPluginFinder());
        getCommand("suite").setExecutor(new CommandGeneric());

    }

    @Override
    public void onDisable()
	{

    }

}


text:
package org.apache.hadoop.fs.http.server;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.http.client.HttpFSFileSystem;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * Filter that Enforces the content-type to be application/octet-stream for
 * POST and PUT requests.
 */
@InterfaceAudience.Private
public class CheckUploadContentTypeFilter implements Filter {

  private static final Set<String> UPLOAD_OPERATIONS = new HashSet<>();

  static {
    UPLOAD_OPERATIONS.add(HttpFSFileSystem.Operation.APPEND.toString());
    UPLOAD_OPERATIONS.add(HttpFSFileSystem.Operation.CREATE.toString());
  }

  /**
   * Initializes the filter.
   *

   * This implementation is a NOP.
   *
   * @param config
   *     filter configuration.
   * @throws ServletException
   *     thrown if the filter could not be initialized.
   */
  @Override
  public void init(FilterConfig config) throws ServletException {
  }

  /**
   * Enforces the content-type to be application/octet-stream for
   * POST and PUT requests.
   *
   * @param request servlet request.
   * @param response servlet response.
   * @param chain filter chain.
   *
   * @throws IOException thrown if an IO error occurs.
   * @throws ServletException thrown if a servlet error occurs.
   */
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    boolean contentTypeOK = true;
    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    String method = httpReq.getMethod();
    if (method.equals("PUT") || method.equals("POST")) {
      String op = httpReq.getParameter(HttpFSFileSystem.OP_PARAM);
      if (op != null && UPLOAD_OPERATIONS.contains(op.toUpperCase())) {
        if ("true".equalsIgnoreCase(
            httpReq.getParameter(HttpFSParametersProvider.DataParam.NAME))) {
          String contentType = httpReq.getContentType();
          contentTypeOK = HttpFSFileSystem.UPLOAD_CONTENT_TYPE
              .equalsIgnoreCase(contentType);
        }
      }
    }
    if (contentTypeOK) {
      chain.doFilter(httpReq, httpRes);
    } else {
      httpRes.sendError(HttpServletResponse.SC_BAD_REQUEST,
          "Data upload requests must have content-type set to '" +
              HttpFSFileSystem.UPLOAD_CONTENT_TYPE + "'");

    }
  }

  /**
   * Destroys the filter.
   *

   * This implementation is a NOP.
   */
  @Override
  public void destroy() {
  }

}


text:
class QTimer;
class ContinuousUpdater
{
public:
    using Updater = DAVA::Function<void()>;
    using Stopper = DAVA::Function<bool()>;

    ContinuousUpdater(int updateInterval);
    ~ContinuousUpdater();

    void SetUpdater(const Updater& updater);
    void SetStopper(const Stopper& stopper);

    void Update();
    void Stop(); //sync method to stop timer and call Update
    void Abort(); //sync method to stop timer and don't call update

    void OnTimer();

private:
    Updater updater;
    Stopper stopper;
    std::unique_ptr<QTimer> timer;
    DAVA::QtDelayedExecutor delayedExecutor;
    bool needUpdate = false;
};


text:
__author__ = 'JinXing'

import threading
import struct
import ctypes
import logging

logger = logging
logging.basicConfig(level=logging.DEBUG)

MAX_BUF_LEN = 65536

# From /usr/include/linux/icmp.h
ICMP_ECHO_REPLY = 0
ICMP_ECHO = 8

config = {
    "peer": "14.17.123.11",
    "target_ip": "www.baidu.com",
    "target_port": 80
}

class SeqBuilder(object):
    def __init__(self):
        self.seq_lock = threading.RLock()
        self.seq_num = 0

    def __call__(self):
        with self.seq_lock:
            ret = self.seq_num
            self.seq_num += 1
        return ret

get_seq = SeqBuilder()

def checksum(source_string):
    """
    I'm not too confident that this is right but testing seems
    to suggest that it gives the same answers as in_cksum in ping.c
    """
    sum_ = 0
    count_to = (len(source_string) / 2) * 2
    for count in xrange(0, count_to, 2):
        this = ord(source_string[count + 1]) * 256 + ord(source_string[count])
        sum_ += this
        sum_ &= 0xffffffff  # Necessary?

    if count_to < len(source_string):
        sum_ += ord(source_string[len(source_string) - 1])
        sum_ &= 0xffffffff  # Necessary?

    sum_ = (sum_ >> 16) + (sum_ & 0xffff)
    sum_ += (sum_ >> 16)
    answer = ~sum_
    answer &= 0xffff

    # Swap bytes. Bugger me if I know why.
    answer = answer >> 8 | (answer << 8 & 0xff00)

    return answer

class ICMPPacket(object):
    @classmethod
    def _checksum(cls, data):
        if len(data) % 2:
            odd_byte = ord(data[-1])
            data = data[:-1]
        else:
            odd_byte = 0
        words = struct.unpack("!%sH" % (len(data) / 2), data)
        total = 0
        for word in words:
            total += word
        else:
            total += odd_byte
        total = (total >> 16) + (total & 0xffff)
        total += total >> 16
        return ctypes.c_ushort(~total).value

    @classmethod
    def parse(cls, buf):
        type_, code, checksum, id_, seq = struct.unpack("!BBHHH", buf[20:28])
        return type_, id_, seq, buf[28:]

    @classmethod
    def create(cls, type_, code, id_, seq, data):
        packfmt = "!BBHHH%ds" % (len(data))
        args = [type_, code, 0, id_, seq, data]
        args[2] = cls._checksum(struct.pack(packfmt, *args))
        return struct.pack(packfmt, *args)

if __name__ == "__main__":
    import socket
    import os
    icmp = socket.getprotobyname("icmp")
    icmp_sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    send_data = ICMPPacket.create(ICMP_ECHO, 0, os.getpid(), 0, "x"*64)
    icmp_sock.sendto(send_data, (socket.gethostbyname("10.19.190.24"), 0))
    data, addr = icmp_sock.recvfrom(MAX_BUF_LEN)
    print addr, ICMPPacket.parse(data)


text:
<?php
/**
 * User create request.
 *
 * @author    MyBB Group
 * @version   2.0.0
 * @package   mybb/core
 * @license   http://www.mybb.com/licenses/bsd3 BSD-3
 */

namespace MyBB\Core\Http\Requests\User;

use MyBB\Core\Http\Requests\AbstractRequest;

class CreateRequest extends AbstractRequest
{
    /**
     * @return array
     */
    public function rules()
    {
        return [
            'name'      => 'required|max:255|unique:users',
            'email'     => 'required|email|max:255|unique:users',
            'password'  => 'required|confirmed|min:6',
        ];
    }

    /**
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}


text:
var searchData=
[
  ['modifiers',['modifiers',['../class_qwt_event_pattern_1_1_mouse_pattern.html#ad12c724aac7bba9f16540c604dc108f9',1,'QwtEventPattern::MousePattern::modifiers()'],['../class_qwt_event_pattern_1_1_key_pattern.html#a1db88ed291d4ba49fa84e32e86fa10d1',1,'QwtEventPattern::KeyPattern::modifiers()']]]
];