text:
Framework '4.7'

###############################################################################
# Properties that are used by this psake
# script; these can be overridden when
# invoking this script
#
Properties {
    # buildconfig: the configuration used for building
    # note that this also determines the deployment configuration (SlowCheetah)
    $buildconfig = 'Debug'
    $buildPlatformTarget = 'AnyCpu'

    # chatter: number to indicate verbosity during the execution of tasks
    #   0 - no output
    #   1 - minimal output, tasks executed
    #   2 - extra output, steps within tasks
    #   3 - even more output
    $chatter = 1
    # chattercolor: foreground color to use for task output
    $chattercolor = 'Green'

    # choco installer directives
    $chocoIIncludeXmlFiles = $false
    $chocoIncludePdb = $false

    # used nunit version
    $nunitVersion = '3.8.0'
    $nUnitFramework = $null
}

#endregion

#region PRIVATE HELPERS

###############################################################################
### PRIVATE HELPERS                                                         ###
###############################################################################

###############################################################################
# Helper for printing out documentation
#
function PropertyDocumentation() {
    Write-Host 'Properties'
    Write-Host '----------'
    Write-Host "`$chatter                      The level of verbosity during task execution, defaults to 1."
    Write-Host  '                                0 - No output'
    Write-Host  '                                1 - Minimal output, tasks executed'
    Write-Host  '                                2 - Extra output, steps within tasks'
    Write-Host  '                                3 - Even more output, debug execution'
    Write-Host "`$chattercolor                 Foreground color to use for task output., defaults to Green"
    Write-Host "`$buildconfig                  Build configuration (Debug, Release), defaults to Debug."
    Write-Host "`$buildPlatformTarget          Build Target Platform (AnyCpu, x86, x64), defaults to AnyCpu."
    Write-Host "`$chocoIIncludeXmlFiles        When creating a chocolatey-package, we can specify to include Xml-Files, defaults to $false."
    Write-Host "`$chocoIncludePdb              When creating a chocolatey-package, we can specify to include Pdb-Files, defaults to $false."
    Write-Host "`$nunitVersion                 Version of nunit-runner, defaults to 3.8.0"
    Write-Host "`$nUnitFramework               RuntimeFramework for nunit-runner, defaults to $null, If not specified, tests will run under the framework they are compiled with"
}

###############################################################################
# Helper for chatter
#
function Chatter {
    param
    (
        [string]
        $msg = '.',

        [int]
        $level = 3
    )

    if ($level -le $chatter) {
        Write-Host $msg -ForegroundColor $chattercolor
    }
}

###############################################################################
# Helper for to see if we run with Administrator privileges
#
function Test-Administrator
{
    $user = [Security.Principal.WindowsIdentity]::GetCurrent();
    (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

###############################################################################
# Helper to determine our msbuild parameters
#
function Get-DefaultMsBuildParameters
{
    Param (
        [Parameter(Mandatory = $true)]
        [string]$solution,

        [Parameter(Mandatory = $true)]
        [Array]$tasks,

        [Parameter(Mandatory = $true)]
        [string]$configuration,

        [Parameter(Mandatory = $false)]
        [string[]]$additionalParameters
    )

    $concatedTasks = ($tasks -join ';')
    $params = @(
        """$solution"""
        "/t:$concatedTasks"
        "/m"
        "/nr:false"
        "/v:quiet"
        "/nologo"
        "/p:Configuration=$configuration"
    )

    if ($additionalParameters) {
        foreach($param in $additionalParameters) {
            $params += $param
        }
    }

    $params
}

###############################################################################
# Helper to invoke msbuild
#
function Invoke-MsBuild
{
    Param (
        [Parameter(Mandatory = $true)]
        [string]$solution,

        [Parameter(Mandatory = $true)]
        [Array]$tasks,

        [Parameter(Mandatory = $true)]
        [string]$configuration,

        [Parameter(Mandatory = $false)]
        [string[]]$additionalParameters
    )

    $msbuildParams = Get-DefaultMsBuildParameters -solution $solution -tasks $tasks -configuration $configuration -additionalParameters $additionalParameters
    Chatter "msbuild $msbuildParams" 3
    Exec { msbuild $msbuildParams }
}

#endregion

#region TASKS

###############################################################################
### TASKS                                                                   ###
###############################################################################

###############################################################################
# Default task, executed when no task is
# given explicitly
#
Task Default -depends ?

###############################################################################
# Help
#
Task ? -description 'Show help.' {
    Write-Host
    PropertyDocumentation
    WriteDocumentation
}

###############################################################################
# Helper to chat our properties
#
Task ShowProperties -description 'Show running properties' {
    Chatter "Properties used:" 1
    Chatter "  buildconfig=$buildconfig" 1
    Chatter "  buildPlatformTarget=$buildPlatformTarget" 1
    Chatter "  chocoIIncludeXmlFiles=$chocoIIncludeXmlFiles" 1
    Chatter "  chocoIIncludeXmlFiles=$chocoIIncludeXmlFiles" 1
    Chatter "  nunitVersion=$nunitVersion" 1
    Chatter "  nUnitFramework=$nUnitFramework" 1
}

###############################################################################
# Clean build artifacts and temporary files
#
Task Clean -description 'Clean build output.' -depends ShowProperties {

    Push-Location
    try
    {
        Chatter 'Cleaning solution' 2
        Set-Location 'src'
        $solution = Get-Item '*.sln' | Select-Object -First 1

        # msbuild clean
        Invoke-MsBuild -solution $solution.Name -tasks @('Clean') -configuration $buildconfig
        Set-Location '..'

        # clean up scratch folder
        Chatter 'Cleaning scratch' 2
        $path = "scratch"
        if (Test-Path $path) {
            Remove-Item -Path $path -Recurse -Force
        }

        # clean up bin/obj folders
        Chatter 'Cleaning bin/obj' 2
        Remove-Item -Path (Join-Path (Join-Path "src" "*") "bin"),(Join-Path (Join-Path "src" "*") "obj") -Recurse -Force
    }
    finally
    {
        Pop-Location
    }
}

###############################################################################
# Clean ReSharper cache folder
#
Task ReSharperClean -description 'Clean ReSharper cache folders.' -depends ShowProperties {

    Push-Location
    try
    {
        # clean up cache folder
        $path = Join-Path "src" "_ReSharper.Caches"
        if (Test-Path $path) {
            Remove-Item -Path $path -Recurse -Force
        }
    }
    finally
    {
        Pop-Location
    }
}

###############################################################################
# Clean packages folder
#
# Depends on ReSharperClean to prevent cached references to removed packages.
#
Task PackageClean -description 'Clean NuGet packages folder.' -depends ReSharperClean {

    Push-Location
    try
    {
        # clean up packages folder
        $path = Join-Path "src" "packages"
        if (Test-Path $path) {
            Remove-Item -Path $path -Recurse -Force
        }
    }
    finally
    {
        Pop-Location
    }
}

###############################################################################
# Full clean
#
Task FullClean -description 'Clean build output, generated packages and NuGet packages folder.' -depends Clean,PackageClean

###############################################################################
# Restore packages
#
Task PackageRestore -description 'Restore NuGet package dependencies.' -depends PackageClean {

    Push-Location
    try
    {
        Set-Location 'src'
        $solution = Get-Item '*.sln' | Select-Object -First 1

        # traditional nuget command-line restore
        # note, nuget commandline transparantly calls msbuild "restore" for new type csproj files
        $nugetRestoreParams = @(
            "$solution"
            "-NonInteractive"
            "-Verbosity quiet"
        )
        Chatter "nuget restore $nugetRestoreParams" 3
        Exec { Invoke-Expression "nuget restore $nugetRestoreParams" }
    }
    finally
    {
        Pop-Location
    }
}

###############################################################################
# Restore
#
# Depends on PackageRestore to restore packages, and Clean to put the solution
# in a clean state so VS2017 is willing to open it without complaints.
#
Task Restore -description 'Restore solution.' -depends PackageRestore,Clean {
}

###############################################################################
# Build the solution
#
# Depends on Clean to ensure a clean build, not using any left-over compile artifacts.
#
Task Build -description 'Build the solution.' -depends Clean {

    Push-Location
    try
    {
        Set-Location 'src'
        $solution = Get-Item '*.sln' | Select-Object -First 1
        Invoke-MsBuild -solution $solution.Name -tasks @('Restore', 'Build') -configuration $buildconfig
    }
    finally
    {
        Pop-Location
    }
}

###############################################################################
# Full build
#
Task FullBuild -description 'Do a full build starting from a clean solution.' -depends Restore,Build

###############################################################################
# Create a NuGet package
#
# Depends on Clean to ensure a clean build, not using any left-over compile artifacts.
#
Task Pack -description 'Create a nuget-package (new 2017 VS csproj).' -depends FullClean {

    Push-Location
    try
    {
        Push-Location 'src'
        try {
            $solution = Get-Item '*.sln' | Select-Object -First 1
            if ($solution) {
                $additionalParameters = @(
                    "/p:IncludeSymbols=True"
                    "/p:IncludeSource=True"
                )
                Invoke-MsBuild -solution $solution.Name -tasks @('Restore','Pack') -configuration $buildconfig -additionalParameters $additionalParameters
            }
        }
        finally {
            Pop-Location
        }
    }
    finally
    {
        Pop-Location
    }
}

###############################################################################
# Run unit tests
#
Task Test -description 'Run the unit tests using NUnit console test runner.' -depends FullBuild {

    Push-Location
    try
    {
        $nunitApplicationName = 'nunit3-console.exe'
        $nunitNugetPackageName = 'NUnit.ConsoleRunner'
        $nunitNugetVersionedPackageName = "$nunitNugetPackageName.$($nunitVersion)"
        $packageNUnitPath = `
            Join-Path -Path 'src' -ChildPath 'packages' | `
            Join-Path -ChildPath $nunitNugetVersionedPackageName

        # Can we find nunit-runner in our traditional packages directory?
        $runner = $null
        $runnerPath = `
            Join-Path -Path $packageNUnitPath -ChildPath 'tools' | `
            Join-Path -ChildPath $nunitApplicationName
        if (Test-Path $runnerPath) {
            $runner = Get-Item -Path $runnerPath
        }

        # If we didn't found it, install nunit-runner in our scratch directory
        if ($null -eq $runner) {
            $scratchNUnitPath = Join-Path -Path '.\scratch' -ChildPath 'nunit'

            $nugetRestoreParams = @(
                "$nunitNugetPackageName"
                "-Version '$($nunitVersion)'"
                "-OutputDirectory ""$scratchNUnitPath"""
                "-NonInteractive"
                "-Verbosity quiet"
            )
            Chatter "nuget install $nugetRestoreParams" 3
            Exec { Invoke-Expression "nuget install $nugetRestoreParams" }

            $runnerPath = `
                Join-Path -Path $scratchNUnitPath -ChildPath $nunitNugetVersionedPackageName | `
                Join-Path -ChildPath 'tools' | `
                Join-Path -ChildPath $nunitApplicationName
            if (Test-Path $runnerPath) {
                $runner = Get-Item $runnerPath
            }
        }

        # stop if we don't have a nunit-runner
        if ($null -eq $runner)
        {
            throw 'Cannot find or fetch nunit runner.'
        }

        Chatter "Found nunit runner: $runner" 3

        # find unit test dlls
        Chatter 'Searching test projects ...' 3
        Get-ChildItem -Path (Join-Path -Path 'scratch' -ChildPath 'bin') -Filter *Tests.dll -Recurse | ForEach-Object {
            # generate folder for test output
            Chatter "  Found test project: $_.Name" 3

            $nunitFolder = New-Item -ItemType Directory -Path (Join-Path -Path "scratch" -ChildPath "nunit") -Force
            $work = Join-Path $nunitFolder $testdll.BaseName

            # intialise runner args
            $testrunnerargs = @(
                "--work:$work"
                '--result:nunit-test-results.xml'
                '--out:nunit-stdout.txt'
                '--err:nunit-stderr.txt'
                '--labels:all'
            )

            if ($null -ne $nUnitFramework) {
                $testrunnerargs += "--framework:$nUnitFramework"
            }

            # execute runner
            Chatter "$($runner.FullName) $_.FullName $testrunnerargs" 3
            Exec { & "$($runner.FullName)" $_.FullName $testrunnerargs }
        }
    }
    finally
    {
        Pop-Location
    }
}

###############################################################################
# WixInstaller, build each wixproj in our src directory
#
Task WixInstaller -description 'Do a full build starting from a clean solution and create all WixInstaller(s)' -depends FullBuild {

    Push-Location
    try
    {
        Get-ChildItem -Path 'src' -Filter '*.wixproj' -Recurse | ForEach-Object {
            Invoke-MsBuild -solution $_.FullName -tasks @('Build') -configuration $buildconfig
        }
    }
    finally {
        Pop-Location
    }
}

###############################################################################
# ChocoInstaller, build our choco-installer (portable version)
#
Task ChocoInstaller `
    -description 'Do a full build starting from a clean solution and create our portable chocolatey-package' `
    -depends FullBuild {

    Push-Location
    try
    {
        if ($env:ChocolateyInstall) {
            # There should be 2 folder(s)
            #  - choco-scripts, contains specific powershell chocolatey files (install, uninstall, ...)
            #  - choco-nuspecs, contains all nupsec to build
            if ((Test-Path -Path 'choco-scripts') -and (Test-Path -Path 'choco-nuspecs')) {
                $chocoScripts = Get-item 'choco-scripts'
                $chocoNuSpecs = Get-Item 'choco-nuspecs'
                $chocoScratch = Join-Path -Path 'scratch' -ChildPath 'choco'
                $chocoDestination = New-Item -ItemType Directory -Path $chocoScratch -Force

                # copy content of our 2 choco folders to our scratch choco folder
                Copy-item -Force "$($chocoScripts.FullName)\*" -Destination $chocoDestination.FullName -Exclude '.git'
                Copy-item -Force "$($chocoNuSpecs.FullName)\*" -Destination $chocoDestination.FullName -Exclude '.git'

                #search for a nuspec file
                Get-ChildItem -Path $chocoDestination.FullName -Filter *.nuspec | ForEach-Object {
                    $nuspecFile = $_
                    Chatter "  Processing $($nuspecFile.Name)" 1
                    $packageFolder= "$($nuspecFile.BaseName)-$buildconfig-$buildPlatformTarget"
                    Chatter "  Searching for PackageFolder $packageFolder" 3
                    # search for a folder, simular to our nuspec file
                    $scratchBin = Join-Path -Path 'scratch' -ChildPath 'bin'
                    $packageFolder = `
                        Get-ChildItem $scratchBin.FullName -Recurse `
                            | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match $packageFolder} `
                            | Select-Object -First 1
                    if ($packageFolder) {
                        # search for a executable file, simular to our nuspec file
                        Chatter "  Searching for *$($nuspecFile.BaseName).exe inside PackageFolder" 3
                        $targetFileName = `
                            Get-ChildItem $($packageFolder.FullName) -Recurse -Filter *$($nuspecFile.BaseName).exe `
                                | Select-Object -First 1
                        if (-Not $targetFileName) {
                            Chatter "  Searching for *$($nuspecFile.BaseName).dll inside PackageFolder" 3
                            $targetFileName = `
                            Get-ChildItem $($packageFolder.FullName) -Recurse -Filter *$($nuspecFile.BaseName).dll `
                                | Select-Object -First 1
                        }

                        if ($targetFileName) {
                            $targetVersionInfo = (Get-Item $targetFileName.FullName).VersionInfo
                            $id = $targetVersionInfo.FileDescription
                            $zipProg = Join-Path (Join-Path $env:ChocolateyInstall "tools") "7z.exe"
                            $zipPackage = (Join-Path $chocoDestination.FullName $id) + ".7z"

                            $zipProgParams = @(
                                "a '$zipPackage'"
                                "$($packageFolder.FullName)\*"
                                "-t7z -r -m0=BCJ2 -m1=LZMA2:d=1024m -aoa"
                            )

                            if ($chocoIIncludeXmlFiles -eq $false) {
                                $zipProgParams += "'-x!*.xml'"
                            }

                            if ($chocoIncludePdb -eq $false) {
                                $zipProgParams += "'-x!*.pdb'"
                            }

                            Chatter "$zipProg $zipProgParams" 3
                            Exec { Invoke-Expression "$zipProg $zipProgParams" } "7z not available or something went wrong"

                            Push-Location $chocoDestination.FullName
                            try {
                                $version = $targetVersionInfo.ProductVersion
                                $description = $targetVersionInfo.Comments
                                $author = $targetVersionInfo.CompanyName
                                $title = $targetVersionInfo.ProductName
                                $copyright = $targetVersionInfo.LegalCopyright
                                $zipPackage = $id

                                $chocoPackParams = @(
                                    "'$($nuspecFile.Name)'"
                                    "--version '$version'"
                                    "id='$id'"
                                    "description='$description'"
                                    "author='$author'"
                                    "title='$title'"
                                    "copyright='$copyright'"
                                    "zipPackage='$zipPackage'"
                                );
                                Chatter "choco pack $chocoPackParams" 3
                                Exec { Invoke-Expression "choco pack $chocoPackParams" } "choco pack went wrong"
                            }
                            finally {
                                Pop-Location
                            }
                        }
                    }
                }
            }
        }
    }
    finally {
        Pop-Location
    }
}

###############################################################################
# ChocoInstall, build our choco-installer (portable version) and install it
#
Task ChocoInstall `
    -description 'Do a full build starting from a clean solution and create our portable chocolatey-package and install it (Requires Administrator rights)' `
    -depends ChocoInstaller {

    if (Test-Administrator) {
        Push-Location
        try
        {
            # choco should be installed
            if ($env:ChocolateyInstall) {
                $chocoDestination = Get-Item -Path (Join-Path "scratch" "choco")
                Chatter $chocoDestination 3
                Get-ChildItem $chocoDestination.FullName -Filter *.nuspec | ForEach-Object {
                    Chatter "  Searching for *$($nuspecFile.BaseName).exe inside PackageFolder" 3
                    $targetFileName = `
                        Get-ChildItem $($packageFolder.FullName) -Recurse -Filter *$($nuspecFile.BaseName).exe `
                            | Select-Object -First 1
                    if (-Not $targetFileName) {
                        Chatter "  Searching for *$($nuspecFile.BaseName).dll inside PackageFolder" 3
                        $targetFileName = `
                        Get-ChildItem $($packageFolder.FullName) -Recurse -Filter *$($nuspecFile.BaseName).dll `
                            | Select-Object -First 1
                    }

                    if ($targetFileName) {
                        $targetVersionInfo = (Get-Item $targetFileName.FullName).VersionInfo
                        $id = $targetVersionInfo.FileDescription
                        $version = $targetVersionInfo.ProductVersion
                        $chocoInstallParams = @(
                            "'$id'"
                            "--version $version"
                            "--source '$($chocoDestination.FullName)'"
                            "-yes"
                            "--side-by-side"
                            "--params '/CONFIG:$buildConfig'"
                        )
                        Chatter "choco install $chocoInstallParams" 3
                        Exec { Invoke-Expression "choco install $chocoInstallParams" } "choco install went wrong"
                    }
                }
            }
        }
        finally {
            Pop-Location
        }
    }
    else {
        Chatter "This taks is only available when running asn an administrator."
    }
}

###############################################################################
# Installers, build our nuget-packages, choco-installer (portable version)
# and WixInstallers
#
Task Installers `
    -description 'Do a full build starting from a clean solution and create our nuget-packages, choco-installer and wix-installers' `
    -depends FullBuild,Pack,ChocoInstaller,WixInstaller {

    Push-Location
    try
    {
        if (Test-Path -Path 'scratch') {
            Set-Location 'scratch'
            $nupkgDestination = New-Item -ItemType Directory -Path packages -Force
            Get-ChildItem -Path bin -Filter *.nupkg -Recurse | ForEach-Object {
                $nupkgFile = $_
                Copy-item -Force $nupkgFile.FullName -Destination $nupkgDestination.FullName
            }
        }
    }
    finally {
        Pop-Location
    }
}

#endregion

redpajama_set_name: RedPajamaGithub


text:
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch

import pytest

from pythonfmu.builder import FmuBuilder
from pythonfmu.deploy import deploy

PYTHON_SLAVE = Path(__file__).parent / "slaves/pythonslave.py"

@pytest.mark.parametrize("test_manager", [None, "pip", "conda"])
@pytest.mark.parametrize(
    "requirements, test_requirements, expected", [
        (None, None, ValueError),
        (None, "requirements.txt", ValueError),
        (None, "environment.yaml", ValueError),
        ("requirements.txt", None, "pip"),
        ("environment.yaml", None, "conda"),
        ("environment.yml", None, "conda"),
        ("req.txt", "req.txt", "pip"),
        ("env.yml", "env.yml", "conda"),
    ]
)
def test_deploy(tmp_path, test_manager, requirements, test_requirements, expected):

    dummy_requirements = """numpy=1.16
scipy
"""
    if requirements is not None:
        with TemporaryDirectory() as tempd:
            requirements_file = Path(tempd) / requirements
            requirements_file.write_text(dummy_requirements)
            fmu = FmuBuilder.build_FMU(PYTHON_SLAVE, dest=tmp_path, project_files=[requirements_file, ])
    else:
        fmu = FmuBuilder.build_FMU(PYTHON_SLAVE, dest=tmp_path)
    assert fmu.exists()

    with patch("subprocess.run") as run:
        if isinstance(expected, type) and issubclass(expected, Exception):
            with pytest.raises(expected):
                deploy(fmu, environment=test_requirements, package_manager=test_manager)
            run.assert_not_called()
        else:
            deploy(fmu, environment=test_requirements, package_manager=test_manager)

            run.assert_called_once()
            assert (test_manager or expected) in " ".join(run.call_args[0][0])


text:
//===- ChainedIncludesSource.cpp - Chained PCHs in Memory -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file defines the ChainedIncludesSource class, which converts headers
//  to chained PCHs in memory, mainly used for testing.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/ParseAST.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Serialization/ASTWriter.h"
#include "llvm/Support/MemoryBuffer.h"

using namespace clang;

namespace {
class ChainedIncludesSource : public ExternalSemaSource {
public:
  virtual ~ChainedIncludesSource();

  ExternalSemaSource &getFinalReader() const { return *FinalReader; }

  std::vector<CompilerInstance *> CIs;
  IntrusiveRefCntPtr<ExternalSemaSource> FinalReader;

protected:
  //===----------------------------------------------------------------------===//
  // ExternalASTSource interface.
  //===----------------------------------------------------------------------===//

  Decl *GetExternalDecl(uint32_t ID) override;
  Selector GetExternalSelector(uint32_t ID) override;
  uint32_t GetNumExternalSelectors() override;
  Stmt *GetExternalDeclStmt(uint64_t Offset) override;
  CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
  bool FindExternalVisibleDeclsByName(const DeclContext *DC,
                                      DeclarationName Name) override;
  ExternalLoadResult
  FindExternalLexicalDecls(const DeclContext *DC,
                           bool (*isKindWeWant)(Decl::Kind),
                           SmallVectorImpl<Decl *> &Result) override;
  void CompleteType(TagDecl *Tag) override;
  void CompleteType(ObjCInterfaceDecl *Class) override;
  void StartedDeserializing() override;
  void FinishedDeserializing() override;
  void StartTranslationUnit(ASTConsumer *Consumer) override;
  void PrintStats() override;

  /// Return the amount of memory used by memory buffers, breaking down
  /// by heap-backed versus mmap'ed memory.
  void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;

  //===----------------------------------------------------------------------===//
  // ExternalSemaSource interface.
  //===----------------------------------------------------------------------===//

  void InitializeSema(Sema &S) override;
  void ForgetSema() override;
  void ReadMethodPool(Selector Sel) override;
  bool LookupUnqualified(LookupResult &R, Scope *S) override;
};
}

static ASTReader *
createASTReader(CompilerInstance &CI, StringRef pchFile,
                SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
                SmallVectorImpl<std::string> &bufNames,
                ASTDeserializationListener *deserialListener = nullptr) {
  Preprocessor &PP = CI.getPreprocessor();
  std::unique_ptr<ASTReader> Reader;
  Reader.reset(new ASTReader(PP, CI.getASTContext(), /*isysroot=*/"",
                             /*DisableValidation=*/true));
  for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
    StringRef sr(bufNames[ti]);
    Reader->addInMemoryBuffer(sr, std::move(MemBufs[ti]));
  }
  Reader->setDeserializationListener(deserialListener);
  switch (Reader->ReadAST(pchFile, serialization::MK_PCH, SourceLocation(),
                          ASTReader::ARR_None)) {
  case ASTReader::Success:
    // Set the predefines buffer as suggested by the PCH reader.
    PP.setPredefines(Reader->getSuggestedPredefines());
    return Reader.release();

  case ASTReader::Failure:
  case ASTReader::Missing:
  case ASTReader::OutOfDate:
  case ASTReader::VersionMismatch:
  case ASTReader::ConfigurationMismatch:
  case ASTReader::HadErrors:
    break;
  }
  return nullptr;
}

ChainedIncludesSource::~ChainedIncludesSource() {
  for (unsigned i = 0, e = CIs.size(); i != e; ++i)
    delete CIs[i];
}

IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource(
    CompilerInstance &CI, IntrusiveRefCntPtr<ExternalSemaSource> &Reader) {

  std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes;
  assert(!includes.empty() && "No '-chain-include' in options!");

  IntrusiveRefCntPtr<ChainedIncludesSource> source(new ChainedIncludesSource());
  InputKind IK = CI.getFrontendOpts().Inputs[0].getKind();

  SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> SerialBufs;
  SmallVector<std::string, 4> serialBufNames;

  for (unsigned i = 0, e = includes.size(); i != e; ++i) {
    bool firstInclude = (i == 0);
    std::unique_ptr<CompilerInvocation> CInvok;
    CInvok.reset(new CompilerInvocation(CI.getInvocation()));

    CInvok->getPreprocessorOpts().ChainedIncludes.clear();
    CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear();
    CInvok->getPreprocessorOpts().ImplicitPTHInclude.clear();
    CInvok->getPreprocessorOpts().DisablePCHValidation = true;
    CInvok->getPreprocessorOpts().Includes.clear();
    CInvok->getPreprocessorOpts().MacroIncludes.clear();
    CInvok->getPreprocessorOpts().Macros.clear();

    CInvok->getFrontendOpts().Inputs.clear();
    FrontendInputFile InputFile(includes[i], IK);
    CInvok->getFrontendOpts().Inputs.push_back(InputFile);

    TextDiagnosticPrinter *DiagClient =
      new TextDiagnosticPrinter(llvm::errs(), new DiagnosticOptions());
    IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
        new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(), DiagClient));

    std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
    Clang->setInvocation(CInvok.release());
    Clang->setDiagnostics(Diags.get());
    Clang->setTarget(TargetInfo::CreateTargetInfo(
        Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
    Clang->createFileManager();
    Clang->createSourceManager(Clang->getFileManager());
    Clang->createPreprocessor(TU_Prefix);
    Clang->getDiagnosticClient().BeginSourceFile(Clang->getLangOpts(),
                                                 &Clang->getPreprocessor());
    Clang->createASTContext();

    SmallVector<char, 256> serialAST;
    llvm::raw_svector_ostream OS(serialAST);
    auto consumer =
        llvm::make_unique<PCHGenerator>(Clang->getPreprocessor(), "-", nullptr,
                                        /*isysroot=*/"", &OS);
    Clang->getASTContext().setASTMutationListener(
                                            consumer->GetASTMutationListener());
    Clang->setASTConsumer(std::move(consumer));
    Clang->createSema(TU_Prefix, nullptr);

    if (firstInclude) {
      Preprocessor &PP = Clang->getPreprocessor();
      PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
                                             PP.getLangOpts());
    } else {
      assert(!SerialBufs.empty());
      SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> Bufs;
      // TODO: Pass through the existing MemoryBuffer instances instead of
      // allocating new ones.
      for (auto &SB : SerialBufs)
        Bufs.push_back(llvm::MemoryBuffer::getMemBuffer(SB->getBuffer()));
      std::string pchName = includes[i-1];
      llvm::raw_string_ostream os(pchName);
      os << ".pch" << i-1;
      serialBufNames.push_back(os.str());

      IntrusiveRefCntPtr<ASTReader> Reader;
      Reader = createASTReader(
          *Clang, pchName, Bufs, serialBufNames,
          Clang->getASTConsumer().GetASTDeserializationListener());
      if (!Reader)
        return nullptr;
      Clang->setModuleManager(Reader);
      Clang->getASTContext().setExternalSource(Reader);
    }

    if (!Clang->InitializeSourceManager(InputFile))
      return nullptr;

    ParseAST(Clang->getSema());
    Clang->getDiagnosticClient().EndSourceFile();
    SerialBufs.push_back(llvm::MemoryBuffer::getMemBufferCopy(OS.str()));
    source->CIs.push_back(Clang.release());
  }

  assert(!SerialBufs.empty());
  std::string pchName = includes.back() + ".pch-final";
  serialBufNames.push_back(pchName);
  Reader = createASTReader(CI, pchName, SerialBufs, serialBufNames);
  if (!Reader)
    return nullptr;

  source->FinalReader = Reader;
  return source;
}

//===----------------------------------------------------------------------===//
// ExternalASTSource interface.
//===----------------------------------------------------------------------===//

Decl *ChainedIncludesSource::GetExternalDecl(uint32_t ID) {
  return getFinalReader().GetExternalDecl(ID);
}
Selector ChainedIncludesSource::GetExternalSelector(uint32_t ID) {
  return getFinalReader().GetExternalSelector(ID);
}
uint32_t ChainedIncludesSource::GetNumExternalSelectors() {
  return getFinalReader().GetNumExternalSelectors();
}
Stmt *ChainedIncludesSource::GetExternalDeclStmt(uint64_t Offset) {
  return getFinalReader().GetExternalDeclStmt(Offset);
}
CXXBaseSpecifier *
ChainedIncludesSource::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
  return getFinalReader().GetExternalCXXBaseSpecifiers(Offset);
}
bool
ChainedIncludesSource::FindExternalVisibleDeclsByName(const DeclContext *DC,
                                                      DeclarationName Name) {
  return getFinalReader().FindExternalVisibleDeclsByName(DC, Name);
}
ExternalLoadResult
ChainedIncludesSource::FindExternalLexicalDecls(const DeclContext *DC,
                                      bool (*isKindWeWant)(Decl::Kind),
                                      SmallVectorImpl<Decl*> &Result) {
  return getFinalReader().FindExternalLexicalDecls(DC, isKindWeWant, Result);
}
void ChainedIncludesSource::CompleteType(TagDecl *Tag) {
  return getFinalReader().CompleteType(Tag);
}
void ChainedIncludesSource::CompleteType(ObjCInterfaceDecl *Class) {
  return getFinalReader().CompleteType(Class);
}
void ChainedIncludesSource::StartedDeserializing() {
  return getFinalReader().StartedDeserializing();
}
void ChainedIncludesSource::FinishedDeserializing() {
  return getFinalReader().FinishedDeserializing();
}
void ChainedIncludesSource::StartTranslationUnit(ASTConsumer *Consumer) {
  return getFinalReader().StartTranslationUnit(Consumer);
}
void ChainedIncludesSource::PrintStats() {
  return getFinalReader().PrintStats();
}
void ChainedIncludesSource::getMemoryBufferSizes(MemoryBufferSizes &sizes)const{
  for (unsigned i = 0, e = CIs.size(); i != e; ++i) {
    if (const ExternalASTSource *eSrc =
        CIs[i]->getASTContext().getExternalSource()) {
      eSrc->getMemoryBufferSizes(sizes);
    }
  }

  getFinalReader().getMemoryBufferSizes(sizes);
}

void ChainedIncludesSource::InitializeSema(Sema &S) {
  return getFinalReader().InitializeSema(S);
}
void ChainedIncludesSource::ForgetSema() {
  return getFinalReader().ForgetSema();
}
void ChainedIncludesSource::ReadMethodPool(Selector Sel) {
  getFinalReader().ReadMethodPool(Sel);
}
bool ChainedIncludesSource::LookupUnqualified(LookupResult &R, Scope *S) {
  return getFinalReader().LookupUnqualified(R, S);
}


text:
<!--

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.hyperledger</groupId>
    <artifactId>hyperledger</artifactId>
    <version>2.0.0-SNAPSHOT</version>
    <name>hyperledger</name>
    <description>The HyperLedger block chain technology stack</description>
    <packaging>pom</packaging>

    <organization>
        <name>HyperLedger</name>
        <url>https://hyperledger.com</url>
    </organization>

    <licenses>
    </licenses>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.compiler.version>1.8</java.compiler.version>
        <scala.version>2.11.7</scala.version>
        <scalaz.version>7.1.3</scalaz.version>
        <typesafe-config.version>1.2.1</typesafe-config.version>
        <akka.version>2.3.14</akka.version>
        <akka-stream.version>2.0.1</akka-stream.version>
        <scodec-bits.version>1.0.11</scodec-bits.version>
        <scodec-core.version>1.8.3</scodec-core.version>
        <scodec-scalaz.version>1.1.0</scodec-scalaz.version>
        <scalatest.version>2.2.4</scalatest.version>
        <scalacheck.version>1.12.4</scalacheck.version>
        <scalamock.version>3.2</scalamock.version>
        <bouncycastle.version>1.52</bouncycastle.version>
        <protobuf.version>2.5.0</protobuf.version>
        <leveldbjni.version>1.8</leveldbjni.version>
        <scijava.version>2.1.0</scijava.version>
        <jna.version>4.2.1</jna.version>
        <dropwizard.version>0.8.4</dropwizard.version>
        <jackson.version>2.5.1</jackson.version>
        <guava.version>18.0</guava.version>
        <activemq.version>5.8.0</activemq.version>
        <jersey.version>2.21</jersey.version>
        <mockito.version>1.10.19</mockito.version>
        <javax.validation.version>1.1.0.Final</javax.validation.version>
        <assertj.version>2.0.0</assertj.version>
        <json.version>20090211</json.version>
        <slf4j.version>1.7.7</slf4j.version>
        <logback.version>1.1.2</logback.version>
        <junit.version>4.12</junit.version>
        <scijava.version>2.1.1</scijava.version>
        <jna.version>4.2.1</jna.version>
        <commons.math3.version>3.6</commons.math3.version>
    </properties>

    <modules>
        <module>client</module>
        <module>server</module>
        <module>examples</module>
        <module>accountimport</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.scala-lang</groupId>
                <artifactId>scala-library</artifactId>
                <version>${scala.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-client-api</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-client-jms</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-server-regtest</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-client-jackson</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-server-dropwizard</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-server-core</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-server-main</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-server-nativelibs</artifactId>
                <version>${project.version}</version>
                <type>jar</type>
            </dependency>
            <dependency>
                <groupId>org.hyperledger</groupId>
                <artifactId>hyperledger-server-network</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.scalaz</groupId>
                <artifactId>scalaz-core_2.11</artifactId>
                <version>${scalaz.version}</version>
            </dependency>
            <dependency>
                <groupId>org.scodec</groupId>
                <artifactId>scodec-bits_2.11</artifactId>
                <version>${scodec-bits.version}</version>
            </dependency>
            <dependency>
                <groupId>org.scodec</groupId>
                <artifactId>scodec-core_2.11</artifactId>
                <version>${scodec-core.version}</version>
            </dependency>
            <dependency>
                <groupId>org.scodec</groupId>
                <artifactId>scodec-scalaz_2.11</artifactId>
                <version>${scodec-scalaz.version}</version>
            </dependency>
            <dependency>
                <groupId>com.typesafe</groupId>
                <artifactId>config</artifactId>
                <version>${typesafe-config.version}</version>
            </dependency>
            <dependency>
                <groupId>com.typesafe.akka</groupId>
                <artifactId>akka-stream-experimental_2.11</artifactId>
                <version>${akka-stream.version}</version>
            </dependency>
            <dependency>
                <groupId>com.typesafe.akka</groupId>
                <artifactId>akka-stream-testkit-experimental_2.11</artifactId>
                <version>${akka-stream.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>com.typesafe.akka</groupId>
                <artifactId>akka-cluster_2.11</artifactId>
                <version>${akka.version}</version>
            </dependency>
            <dependency>
                <groupId>com.typesafe.akka</groupId>
                <artifactId>akka-slf4j_2.11</artifactId>
                <version>${akka.version}</version>
            </dependency>
            <dependency>
                <groupId>com.typesafe.akka</groupId>
                <artifactId>akka-agent_2.11</artifactId>
                <version>${akka.version}</version>
            </dependency>
            <dependency>
                <groupId>com.typesafe.akka</groupId>
                <artifactId>akka-testkit_2.11</artifactId>
                <version>${akka.version}</version>
            </dependency>
            <dependency>
                <groupId>org.scalatest</groupId>
                <artifactId>scalatest_2.11</artifactId>
                <version>${scalatest.version}</version>
            </dependency>
            <dependency>
                <groupId>org.scalacheck</groupId>
                <artifactId>scalacheck_2.11</artifactId>
                <version>${scalacheck.version}</version>
            </dependency>
            <dependency>
                <groupId>org.scalamock</groupId>
                <artifactId>scalamock-scalatest-support_2.11</artifactId>
                <version>${scalamock.version}</version>
            </dependency>
            <dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcprov-jdk15on</artifactId>
                <version>${bouncycastle.version}</version>
            </dependency>
            <dependency>
                <groupId>com.google.protobuf</groupId>
                <artifactId>protobuf-java</artifactId>
                <version>${protobuf.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-client</artifactId>
                <version>${activemq.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-broker</artifactId>
                <version>${activemq.version}</version>
            </dependency>
            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>${guava.version}</version>
            </dependency>
            <dependency>
                <groupId>org.fusesource.leveldbjni</groupId>
                <artifactId>leveldbjni-all</artifactId>
                <version>${leveldbjni.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.dataformat</groupId>
                <artifactId>jackson-dataformat-yaml</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.jaxrs</groupId>
                <artifactId>jackson-jaxrs-json-provider</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>org.glassfish.jersey.core</groupId>
                <artifactId>jersey-client</artifactId>
                <version>${jersey.version}</version>
            </dependency>
            <dependency>
                <groupId>org.json</groupId>
                <artifactId>json</artifactId>
                <version>${json.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.module</groupId>
                <artifactId>jackson-module-jsonSchema</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.validation</groupId>
                <artifactId>validation-api</artifactId>
                <version>${javax.validation.version}</version>
            </dependency>
            <dependency>
                <groupId>org.assertj</groupId>
                <artifactId>assertj-core</artifactId>
                <version>${assertj.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>${logback.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jul-to-slf4j</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
                <version>${mockito.version}</version>
            </dependency>
            <dependency>
                <groupId>org.scijava</groupId>
                <artifactId>native-lib-loader</artifactId>
                <version>${scijava.version}</version>
            </dependency>
            <dependency>
                <groupId>net.java.dev.jna</groupId>
                <artifactId>jna</artifactId>
                <version>${jna.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-math3</artifactId>
                <version>${commons.math3.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <developers>
    </developers>

    <scm>
        <connection>scm:git:git@github.com:DACH-NY/hyperledger.git</connection>
        <developerConnection>scm:git:git@github.com:DACH-NY/hyperledger.git</developerConnection>
        <url>https://github.com/DACH-NY/hyperledger.git</url>
        <tag>HEAD</tag>
    </scm>

    <contributors>
    </contributors>

    <repositories>
        <repository>
            <id>fusesource.nexus.snapshot</id>
            <name>FuseSource Community Snapshot Repository</name>
            <url>http://repo.fusesource.com/nexus/content/groups/public-snapshots</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>central</id>
            <url>https://repo1.maven.org/maven2</url>
        </pluginRepository>
        <pluginRepository>
            <id>dtrott</id>
            <url>http://maven.davidtrott.com/repository</url>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.compiler.version}</source>
                    <target>${java.compiler.version}</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>2.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.2.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19</version>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <aggregate>true</aggregate>
                    <outputDirectory>coverageReports</outputDirectory>
                    <formats>
                        <format>html</format>
                        <format>xml</format>
                    </formats>
                    <instrumentation>
                        <excludes>
                            <!-- ignore java files that JavaNCSS can't parse -->
                            <!-- these must be repeated in reporting section below -->
                            <exclude>**/BCSAPIServer.java</exclude>
                            <exclude>**/TestServer.java</exclude>
                            <exclude>**/HyperLedgerBundle.java</exclude>
                            <exclude>**/SignaturOperationCounter.java</exclude>
                            <exclude>**/BitcoinPersistentBlocks.java</exclude>
                            <exclude>**/UnitTestBitcoinValidatorFactory.java</exclude>
                            <exclude>**/Mempool.java</exclude>
                            <exclude>**/DefaultBlockStore.java</exclude>
                            <exclude>**/CoreOutbox.java</exclude>
                            <exclude>**/TransactionRepresentation.java</exclude>
                            <exclude>**/BlockRepresentation.java</exclude>
                            <exclude>**/SupernodeModule.java</exclude>
                            <exclude>**/InMemoryConnector.java</exclude>
                            <exclude>**/BCSAPIClient.java</exclude>
                            <exclude>**/WireFormatter.java</exclude>
                            <exclude>**/Transaction.java</exclude>
                            <exclude>**/ScriptBuilder.java</exclude>
                            <exclude>**/Block.java</exclude>
                            <exclude>**/APITransaction.java</exclude>
                            <exclude>**/APIBlock.java</exclude>
                            <exclude>**/TransactionFactory.java</exclude>
                            <exclude>**/MultiSigSigner.java</exclude>
                            <exclude>**/MasterPublicChain.java</exclude>
                            <exclude>**/MasterPrivateChain.java</exclude>
                        </excludes>
                    </instrumentation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.mycila</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <version>2.11</version>
                <configuration>
                    <header>misc/APACHE-2-header.txt</header>
                    <includes>
                        <include>**/*.java</include>
                        <include>**/*.scala</include>
                    </includes>
                </configuration>
                <executions>
                    <execution>
                        <phase>
                            process-resources
                        </phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.rodiontsev.maven.plugins</groupId>
                <artifactId>build-info-maven-plugin</artifactId>
                <version>1.1</version>
                <configuration>
                    <filename>build-info-${project.name}.properties</filename>
                    <projectProperties>
                        <projectProperty>project.id</projectProperty>
                        <projectProperty>project.groupId</projectProperty>
                        <projectProperty>project.artifactId</projectProperty>
                        <projectProperty>project.version</projectProperty>
                        <projectProperty>project.name</projectProperty>
                    </projectProperties>
                    <dateTimePattern>yyyy-MM-dd HH:mm:ss</dateTimePattern>
                    <includeVcsInfo>true</includeVcsInfo>
                    <systemProperties>
                        <systemProperty>user.name</systemProperty>
                        <systemProperty>user.timezone</systemProperty>
                        <systemProperty>java.vm.vendor</systemProperty>
                        <systemProperty>java.vm.version</systemProperty>
                        <systemProperty>java.vm.name</systemProperty>
                        <systemProperty>java.runtime.version</systemProperty>
                        <systemProperty>os.name</systemProperty>
                        <systemProperty>os.version</systemProperty>
                        <systemProperty>os.arch</systemProperty>
                    </systemProperties>
                    <environmentVariables>
                        <environmentVariable>JAVA_HOME</environmentVariable>
                    </environmentVariables>
                </configuration>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>extract</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.servicemix.tooling</groupId>
                <artifactId>depends-maven-plugin</artifactId>
                <version>1.3.1</version>
                <executions>
                    <execution>
                        <id>generate-depends-file</id>
                        <goals>
                            <goal>generate-depends-file</goal>
                        </goals>
                        <configuration>
                            <outputFile>
                                target/dependency-info-${project.name}.properties
                            </outputFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>target/</directory>
                <includes>
                    <include>build-info-*.properties</include>
                    <include>dependency-info-*.properties</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources/</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
        </resources>
    </build>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <instrumentation>
                        <excludes>
                            <!-- ignore java files that JavaNCSS can't parse -->
                            <!-- these must be repeated in plugin section above -->
                            <exclude>**/BCSAPIServer.java</exclude>
                            <exclude>**/TestServer.java</exclude>
                            <exclude>**/HyperLedgerBundle.java</exclude>
                            <exclude>**/SignaturOperationCounter.java</exclude>
                            <exclude>**/BitcoinPersistentBlocks.java</exclude>
                            <exclude>**/UnitTestBitcoinValidatorFactory.java</exclude>
                            <exclude>**/Mempool.java</exclude>
                            <exclude>**/DefaultBlockStore.java</exclude>
                            <exclude>**/CoreOutbox.java</exclude>
                            <exclude>**/TransactionRepresentation.java</exclude>
                            <exclude>**/BlockRepresentation.java</exclude>
                            <exclude>**/SupernodeModule.java</exclude>
                            <exclude>**/InMemoryConnector.java</exclude>
                            <exclude>**/BCSAPIClient.java</exclude>
                            <exclude>**/WireFormatter.java</exclude>
                            <exclude>**/Transaction.java</exclude>
                            <exclude>**/ScriptBuilder.java</exclude>
                            <exclude>**/Block.java</exclude>
                            <exclude>**/APITransaction.java</exclude>
                            <exclude>**/APIBlock.java</exclude>
                            <exclude>**/TransactionFactory.java</exclude>
                            <exclude>**/MultiSigSigner.java</exclude>
                            <exclude>**/MasterPublicChain.java</exclude>
                            <exclude>**/MasterPrivateChain.java</exclude>
                        </excludes>
                    </instrumentation>
                    <formats>
                        <format>html</format>
                        <format>xml</format>
                    </formats>
                    <check/>
                </configuration>
            </plugin>
        </plugins>
    </reporting>

</project>


text:
from telemetry.page.page_set import PageSet

class TestSimpleTwoPageSet(PageSet):
  def __init__(self):
    super(TestSimpleTwoPageSet, self).__init__(
      description='A pageset for testing purpose',
      archive_data_file='data/test.json',
      credentials_path='data/credential',
      user_agent_type='desktop')


text:
#include <algorithm>
#include <string.h>
#include "preflate_statistical_codec.h"
#include "preflate_statistical_model.h"
#include "support/array_helper.h"
#include "support/bit_helper.h"
#include <stdint.h>

template <unsigned N>
bool PreflateSubModel<N>::isEqualTo(const PreflateSubModel<N>& m) const {
  if (N == 0 || m.bounds[N] == 0) {
    return true;
  }
  for (unsigned i = 0; i < N; ++i) {
    if (bounds[i] != m.bounds[i]) {
      return false;
    }
    if (bounds[i + 1] > 0 && ids[i] != m.ids[i]) {
      return false;
    }
  }
  if (bounds[N] != m.bounds[N]) {
    return false;
  }
  return true;
}

template <unsigned NEG, unsigned POS>
bool PreflateCorrectionSubModel<NEG, POS>::isEqualTo(const PreflateCorrectionSubModel<NEG, POS>& m) const {
  return sign.isEqualTo(m.sign)
    && pos.isEqualTo(m.pos)
    && neg.isEqualTo(m.neg);
}

bool PreflateBlockPredictionModel::isEqualTo(const PreflateBlockPredictionModel& m) const {
  return blockType.isEqualTo(m.blockType)
    && EOBMisprediction.isEqualTo(m.EOBMisprediction)
    && nonZeroPadding.isEqualTo(m.nonZeroPadding);
}
bool PreflateTreeCodePredictionModel::isEqualTo(const PreflateTreeCodePredictionModel& m) const {
  return TCBitlengthCorrection.isEqualTo(m.TCBitlengthCorrection)
    && TCCountMisprediction.isEqualTo(m.TCCountMisprediction)
    && LCountMisprediction.isEqualTo(m.LCountMisprediction)
    && DCountMisprediction.isEqualTo(m.DCountMisprediction)
    && LDTypeMisprediction[0].isEqualTo(m.LDTypeMisprediction[0])
    && LDTypeMisprediction[1].isEqualTo(m.LDTypeMisprediction[1])
    && LDTypeMisprediction[2].isEqualTo(m.LDTypeMisprediction[2])
    && LDTypeMisprediction[3].isEqualTo(m.LDTypeMisprediction[3])
    && LDTypeReplacementBase.isEqualTo(m.LDTypeReplacementBase)
    && LDRepeatCountCorrection.isEqualTo(m.LDRepeatCountCorrection)
    && LDBitlengthCorrection.isEqualTo(m.LDBitlengthCorrection);
}
bool PreflateTokenPredictionModel::isEqualTo(const PreflateTokenPredictionModel& m) const {
  return LITMisprediction.isEqualTo(m.LITMisprediction)
    && REFMisprediction.isEqualTo(m.REFMisprediction)
    && LENCorrection.isEqualTo(m.LENCorrection)
    && DISTAfterLenCorrection.isEqualTo(m.DISTAfterLenCorrection)
    && DISTOnlyCorrection.isEqualTo(m.DISTOnlyCorrection)
    && IrregularLen258Encoding.isEqualTo(m.IrregularLen258Encoding);
}

bool PreflatePredictionModel::isEqualTo(const PreflatePredictionModel& m) const {
  return block.isEqualTo(m.block)
    && treecode.isEqualTo(m.treecode)
    && token.isEqualTo(m.token);
}

bool isEqual(const PreflatePredictionModel& m1, const PreflatePredictionModel& m2) {
  return m1.isEqualTo(m2);
}

// ----------------------------

void printFlagStatistics(const char *txt, unsigned(&flag)[2]) {
  if (flag[1]) {
    printf("%s %g%% (%d)", txt, flag[1] * 100.0 / (flag[0] + flag[1]), flag[0] + flag[1]);
  }
}
void printCorrectionStatistics(const char *txt,
                               unsigned data[], unsigned size, unsigned sum, unsigned offset) {
  if (data[offset] == sum) {
    return;
  }
  bool on = false;
  for (unsigned i = 0; i < size; ++i) {
    if (data[i]) {
      if (!on) {
        printf("%s:", txt);
      }
      on = true;
      if (i != offset && (i == 0 || i + 1 == size)) {
        printf(" %sx %g%%", i == 0 ? "-" : "+", data[i] * 100.0 / sum);
      } else {
        printf(" %s%d %g%%", i == offset ? "" : (i < offset ? "-" : "+"), (int)labs((int)(i - offset)), data[i] * 100.0 / sum);
      }
    }
  }
  if (on) {
    printf(" (%d)", sum);
  }
}
template <unsigned N>
void printCorrectionStatistics(const char *txt, unsigned (&data)[N], unsigned sum, int offset) {
  printCorrectionStatistics(txt, data, N, sum, offset);
}

// ----------------------------

void PreflateStatisticsCounter::BlockPrediction::print() {
  unsigned sum = sumArray(blockType);
  if (blockType[0]) {
    printf(" ->STORE %g%%", blockType[0] * 100.0 / sum);
  }
  if (blockType[1] && blockType[1] != sum) {
    printf(" ->DYNHUF %g%%", blockType[1] * 100.0 / sum);
  }
  if (blockType[2]) {
    printf(" ->STATHUF %g%%", blockType[2] * 100.0 / sum);
  }
  printFlagStatistics(", EOB MP", EOBMisprediction);
  printFlagStatistics(", PAD!=0", nonZeroPadding);
}

void PreflateStatisticsCounter::TreeCodePrediction::print() {
  printFlagStatistics(", !CT SZ MP", TCCountMisprediction);
  printFlagStatistics(", !L SZ MP", LCountMisprediction);
  printFlagStatistics(", !D SZ MP", DCountMisprediction);
  printFlagStatistics(", !T B MP", LDTypeMisprediction[0]);
  printFlagStatistics(", !T R MP", LDTypeMisprediction[1]);
  printFlagStatistics(", !T 0s MP", LDTypeMisprediction[2]);
  printFlagStatistics(", !T 0l MP", LDTypeMisprediction[3]);
  unsigned sum = sumArray(LDTypeReplacement);
  if (LDTypeReplacement[0]) {
    printf(" ->T B %g", LDTypeReplacement[0] * 100.0 / sum);
  }
  if (LDTypeReplacement[1]) {
    printf(" ->T R %g", LDTypeReplacement[1] * 100.0 / sum);
  }
  if (LDTypeReplacement[2]) {
    printf(" ->T 0s %g", LDTypeReplacement[2] * 100.0 / sum);
  }
  if (LDTypeReplacement[3]) {
    printf(" ->T 0l %g", LDTypeReplacement[3] * 100.0 / sum);
  }
  sum = sumArray(TCBitlengthCorrection);
  printCorrectionStatistics(", C BL", TCBitlengthCorrection, sum, 3);
  sum = sumArray(LDRepeatCountCorrection);
  printCorrectionStatistics(" LD RP", LDRepeatCountCorrection, sum, 1);
  sum = sumArray(LDBitlengthCorrection);
  printCorrectionStatistics(", LD BL", LDBitlengthCorrection, sum, 4);
}

void PreflateStatisticsCounter::TokenPrediction::print() {
  printFlagStatistics(", !LIT MP", LITMisprediction);
  printFlagStatistics(", !REF MP", REFMisprediction);
  unsigned sum = sumArray(LENCorrection);
  printCorrectionStatistics(" L", LENCorrection, sum, 6);
  sum = sumArray(DISTAfterLenCorrection);
  printCorrectionStatistics(" L->D+", DISTAfterLenCorrection, sum, 0);
  sum = sumArray(DISTOnlyCorrection);
  printCorrectionStatistics(" ->D+", DISTOnlyCorrection, sum, 0);
  printFlagStatistics(", !L258 MP", LEN258IrregularEncoding);
}

void PreflateStatisticsCounter::print() {
  block.print();
  treecode.print();
  token.print();
  printf("\n");
}


text:
package com.avenwu.himusic.utils;

import android.database.Cursor;
import android.provider.MediaStore;

import com.avenwu.himusic.modle.SongDetail;

/**
 * @author chaobin
 * @date 11/18/13.
 */
public class CursorHelper {

    public static int getInt(Cursor cursor, String columnName) {
        return cursor.getInt(cursor.getColumnIndex(columnName));
    }

    public static long getLong(Cursor cursor, String columnName) {
        return cursor.getLong(cursor.getColumnIndex(columnName));
    }

    public static String getString(Cursor cursor, String columnName) {
        return cursor.getString(cursor.getColumnIndex(columnName));

    }

    public static SongDetail getSongDetail(Cursor cursor) {
        SongDetail item = new SongDetail();
        item.id = CursorHelper.getLong(cursor, MediaStore.Audio.Media._ID);
        item.artist = CursorHelper.getString(cursor, MediaStore.Audio.Media.ARTIST);
        item.title = CursorHelper.getString(cursor, MediaStore.Audio.Media.TITLE);
        item.size = CursorHelper.getLong(cursor, MediaStore.Audio.Media.SIZE);
        item.duration = CursorHelper.getLong(cursor, MediaStore.Audio.Media.DURATION);
        return item;
    }
}


text:
use fail::{EINTR, abort, assert};
use mem::uninit;
use c_types::{c_int, time_t, clockid_t, timespec};
use cmp::{Eq, Ord};

static CLOCK_REALTIME: clockid_t = 0;
static CLOCK_MONOTONIC: clockid_t = 1;
static TIMER_ABSTIME: c_int = 1;

pub struct Time {
    time: timespec
}

impl Time {
    pub fn from_seconds(seconds: time_t) -> Time {
        Time { time: timespec { tv_sec: seconds, tv_nsec: 0 } }
    }

    pub fn from_timespec(time: timespec) -> Time {
        Time { time: time }
    }

    pub fn to_timespec(&self) -> timespec {
        self.time
    }
}

impl Eq for Time {
    fn eq(&self, other: &Time) -> bool {
        self.time.tv_sec == other.time.tv_sec && self.time.tv_nsec == other.time.tv_nsec
    }
}

impl Ord for Time {
    fn lt(&self, other: &Time) -> bool {
        self.time.tv_sec < other.time.tv_sec || self.time.tv_nsec < other.time.tv_nsec
    }
}

extern {
    fn clock_gettime(clock_id: clockid_t, tp: *mut timespec) -> c_int;
    fn clock_nanosleep(clock_id: clockid_t, flags: c_int, rqtp: *timespec,
                       rmtp: *mut timespec) -> c_int;
}

fn get_time(clock: clockid_t) -> Time {
    unsafe {
        let mut time = uninit();
        if clock_gettime(clock, &mut time) != 0 {
            abort()
        }
        Time { time: time }
    }
}

pub fn real() -> Time {
    get_time(CLOCK_REALTIME)
}

pub fn monotonic() -> Time {
    get_time(CLOCK_MONOTONIC)
}

fn sleep_absolute(clock_id: clockid_t, abstime: Time) {
    loop {
        let ret = unsafe {
            clock_nanosleep(clock_id, TIMER_ABSTIME, &abstime.time, 0 as *mut timespec)
        };
        if ret != EINTR {
            assert(ret == 0);
            break
        }
    }
}

pub fn sleep_until(abstime: Time) {
    sleep_absolute(CLOCK_REALTIME, abstime)
}

pub fn monotonic_sleep_until(abstime: Time) {
    sleep_absolute(CLOCK_MONOTONIC, abstime)
}

pub fn sleep(mut reltime: Time) {
    loop {
        unsafe {
            let mut remain = uninit();
            let ret = clock_nanosleep(CLOCK_MONOTONIC, 0, &reltime.time, &mut remain);
            if ret != EINTR {
                assert(ret == 0);
                break
            }
            reltime.time = remain;
        }
    }
}


text:
using namespace eeros;
using namespace eeros::hal;

TEST(halHalManagerTest, availableDigInOut){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("ioIn");
		hal.getLogicOutput("io1");
		hal.getLogicOutput("ioOut");
		hal.getLogicOutput("ioOut4");

		hal.getScalableOutput("aOut0");

		hal.getScalableInput("aIn0");

		hal.releaseInput("ioIn");
		hal.releaseOutput("io1");
		hal.releaseOutput("ioOut");
		hal.releaseOutput("ioOut4");
		hal.releaseOutput("aOut0");
		hal.releaseInput("aIn0");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, notAvailableDigInOut){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("enable56");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system input 'enable56' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, emptySignalIdLogicIn){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system input '' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, emptySignalIdLogicOut){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicOutput("");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system output '' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, emptySignalIdRealIn){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system input '' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, emptySignalIdRealOut){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableOutput("");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system output '' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, wrongTypeRealIn){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableInput("ioIn");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system input 'ioIn' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, wrongTypeRealOut){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableOutput("ioOut");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system output 'ioOut' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, wrongTypeLogicIn){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("aIn0");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system input 'aIn0' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, wrongTypeLogicOut){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicOutput("aOut0");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system output 'aOut0' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, wrongDirectionLogicIn){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("ioOut");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system input 'ioOut' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, wrongDirectionLogicOut){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicOutput("ioIn");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system output 'ioIn' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, wrongDirectionRealIn){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableInput("aOut0");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system input 'aOut0' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, wrongDirectionRealOut){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableOutput("aIn0");
		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system output 'aIn0' not found!"));
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimReservedInput){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("ioIn");
		hal.getLogicInput("ioIn");

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system input 'ioIn' is exclusive reserved!"));
		hal.releaseInput("ioIn");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveInput){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("ioIn", false);
		hal.getLogicInput("ioIn", false);
		hal.getLogicInput("ioIn", false);

		hal.releaseInput("ioIn");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveThenExclusiveInput){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("ioIn", false);

		hal.releaseInput("ioIn");

		hal.getLogicInput("ioIn");

		hal.releaseInput("ioIn");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveThenExclusiveInputFail){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("ioIn", false);
		hal.getLogicInput("ioIn");

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system input 'ioIn' is already claimed as non-exclusive input!"));
		hal.releaseInput("ioIn");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimReservedNonExclusiveInput){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicInput("ioIn");
		hal.getLogicInput("ioIn", false);

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system input 'ioIn' is exclusive reserved!"));
		hal.releaseInput("ioIn");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimReservedOutput){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicOutput("ioOut");
		hal.getLogicOutput("ioOut");

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system output 'ioOut' is exclusive reserved!"));
		hal.releaseOutput("ioOut");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveOutput){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicOutput("ioOut", false);
		hal.getLogicOutput("ioOut", false);
		hal.getLogicOutput("ioOut", false);

		hal.releaseOutput("ioOut");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveThenExclusiveOutput){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicOutput("ioOut", false);

		hal.releaseOutput("ioOut");

		hal.getLogicOutput("ioOut");

		hal.releaseOutput("ioOut");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveThenExclusiveOutputFail){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicOutput("ioOut", false);
		hal.getLogicOutput("ioOut");

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system output 'ioOut' is already claimed as non-exclusive output!"));
		hal.releaseOutput("ioOut");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimReservedNonExclusiveOutput){
	HAL& hal = HAL::instance();

	try{
		hal.getLogicOutput("ioOut");
		hal.getLogicOutput("ioOut", false);

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Logic system output 'ioOut' is exclusive reserved!"));
		hal.releaseOutput("ioOut");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimReservedRealInput){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableInput("aIn0");
		hal.getScalableInput("aIn0");

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system input 'aIn0' is exclusive reserved!"));
		hal.releaseInput("aIn0");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveRealInput){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableInput("aIn0", false);
		hal.getScalableInput("aIn0", false);
		hal.getScalableInput("aIn0", false);

		hal.releaseInput("aIn0");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveThenExclusiveRealInput){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableInput("aIn0", false);

		hal.releaseInput("aIn0");

		hal.getScalableInput("aIn0");

		hal.releaseInput("aIn0");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveThenExclusiveRealInputFail){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableInput("aIn0", false);
		hal.getScalableInput("aIn0");

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system input 'aIn0' is already claimed as non-exclusive input!"));
		hal.releaseInput("aIn0");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimReservedNonExclusiveRealInput){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableInput("aIn0");
		hal.getScalableInput("aIn0", false);

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system input 'aIn0' is exclusive reserved!"));
		hal.releaseInput("aIn0");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimReservedRealOutput){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableOutput("aOut0");
		hal.getScalableOutput("aOut0");

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system output 'aOut0' is exclusive reserved!"));
		hal.releaseOutput("aOut0");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveRealOutput){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableOutput("aOut0", false);
		hal.getScalableOutput("aOut0", false);
		hal.getScalableOutput("aOut0", false);

		hal.releaseOutput("aOut0");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveThenExclusiveRealOutput){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableOutput("aOut0", false);

		hal.releaseOutput("aOut0");

		hal.getScalableOutput("aOut0");

		hal.releaseOutput("aOut0");
	}
	catch(eeros::Fault const & err){
		FAIL() << err.what();
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimNonExclusiveThenExclusiveRealOutputFail){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableOutput("aOut0", false);
		hal.getScalableOutput("aOut0");

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system output 'aOut0' is already claimed as non-exclusive output!"));
		hal.releaseOutput("aOut0");
	}
	catch(...){
		FAIL();
	}
}

TEST(halHalManagerTest, claimReservedNonExclusiveRealOutput){
	HAL& hal = HAL::instance();

	try{
		hal.getScalableOutput("aOut0");
		hal.getScalableOutput("aOut0", false);

		FAIL();
	}
	catch(eeros::Fault const & err){
		EXPECT_EQ(err.what(), std::string("Scalable system output 'aOut0' is exclusive reserved!"));
		hal.releaseOutput("aOut0");
	}
	catch(...){
		FAIL();
	}
}


text:
//
//  NSView+TKCategory.h
//  Created by Devin Ross on 10/21/15.
//

@import Cocoa;

@interface NSView (TKCategory)

/** The opposite of hidden. */
@property (nonatomic,assign) BOOL visible;

/** Adds a view to the beginning of the receiver's list of subviews.
 @param view The view to be added. This view is retained by the receiver. After being added, this view appears below of any other subviews.
 */
- (void) addSubviewToBack:(NSView*)view;

@end


text:
package org.pentaho.di.connections.vfs;

import org.apache.commons.vfs2.FileSystemOptions;
import org.pentaho.di.connections.ConnectionManager;

/**
 * Created by bmorrise on 2/13/19.
 */
public class VFSHelper {
  public static FileSystemOptions getOpts( String file, String connection ) {
    VFSConnectionDetails vfsConnectionDetails =
      (VFSConnectionDetails) ConnectionManager.getInstance().getConnectionDetails( file, connection );
    VFSConnectionProvider<VFSConnectionDetails> vfsConnectionProvider =
      (VFSConnectionProvider<VFSConnectionDetails>) ConnectionManager.getInstance().getConnectionProvider( file );
    if ( vfsConnectionProvider != null ) {
      return vfsConnectionProvider.getOpts( vfsConnectionDetails );
    }
    return null;
  }
}


text:
const DrawCard = require('../../drawcard.js');

class AGiftOfArborRed extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Reveal top 4 cards of each deck',
            cost: ability.costs.kneelFactionCard(),
            handler: () => {
                let opponents = this.game.getOpponents(this.controller);
                let opponentCards = opponents.map(opponent => {
                    return { player: opponent, cards: opponent.searchDrawDeck(4) };
                });

                this.revealedCards = [
                    { player: this.controller, cards: this.controller.searchDrawDeck(4) }
                ].concat(opponentCards);

                for(let revealed of this.revealedCards) {
                    this.game.addMessage('{0} uses {1} and kneels their faction card to reveal the top 4 cards of {2}\'s deck as: {3}', this.controller, this, revealed.player, revealed.cards);
                }

                this.promptToAddToHand();
            }
        });
    }

    promptToAddToHand() {
        if(this.revealedCards.length === 0) {
            return;
        }

        let currentRevealed = this.revealedCards[0];

        let title = currentRevealed.player === this.controller ? 'Choose a card to add to your hand' : `Choose a card to add to ${currentRevealed.player.name}'s hand`;
        let buttons = currentRevealed.cards.map(card => ({
            method: 'selectCardForHand', card: card
        }));

        this.game.promptWithMenu(this.controller, this, {
            activePrompt: {
                menuTitle: title,
                buttons: buttons
            },
            source: this
        });
    }

    selectCardForHand(player, cardId) {
        let current = this.revealedCards.shift();
        let card = current.cards.find(card => card.uuid === cardId);

        current.player.moveCard(card, 'hand');
        current.player.shuffleDrawDeck();

        this.game.addMessage('{0} adds {1} to {2}\'s hand and shuffles their deck',
            this.controller, card, current.player);

        this.promptToAddToHand();

        return true;
    }
}

AGiftOfArborRed.code = '02104';

module.exports = AGiftOfArborRed;


text:
/// <reference path="_references.ts"/>

module jsCommon {
    /**
     * DOM constants.
     */
    export module DOMConstants {

        /**
         * Integer codes corresponding to individual keys on the keyboard.
         */
        export const escKeyCode = 27;
        export const enterKeyCode = 13;
        export const tabKeyCode = 9;
        export const upArrowKeyCode = 38;
        export const downArrowKeyCode = 40;
        export const leftArrowKeyCode = 37;
        export const rightArrowKeyCode = 39;
        export const homeKeyCode = 36;
        export const endKeyCode = 35;
        export const backSpaceKeyCode = 8;
        export const deleteKeyCode = 46;
        export const spaceKeyCode = 32;
        export const shiftKeyCode = 16;
        export const ctrlKeyCode = 17;
        export const altKeyCode = 18;

        export const aKeyCode = 65;
        export const cKeyCode = 67;
        export const sKeyCode = 83;
        export const vKeyCode = 86;
        export const xKeyCode = 88;
        export const yKeyCode = 89;
        export const zKeyCode = 90;

        /**
         * DOM Elements.
         */
        export const DocumentBody = 'body';
        export const Anchor = 'a';
        export const EditableTextElements = ':text, textarea';

        /**
         * DOM Attributes and values.
         */
        export const disabledAttributeOrValue = 'disabled';
        export const readonlyAttributeOrValue = 'readonly';
        export const idAttribute = 'id';
        export const styleAttribute = 'style';
        export const hrefAttribute = 'href';
        export const targetAttribute = 'target';
        export const blankValue = '_blank';
        export const selfValue = '_self';
        export const classAttribute = 'class';
        export const titleAttribute = 'title';
        export const srcAttribute = 'src';

        /**
         * DOM event names.
         */
        export const contextmenuEventName = 'contextmenu';
        export const blurEventName = 'blur';
        export const keyUpEventName = 'keyup';
        export const inputEventName = 'input';
        export const changeEventName = 'change';
        export const cutEventName = 'cut';
        export const keyDownEventName = 'keydown';
        export const mouseMoveEventName = 'mousemove';
        export const mouseDownEventName = 'mousedown';
        export const mouseEnterEventName = 'mouseenter';
        export const mouseLeaveEventName = 'mouseleave';
        export const mouseOverEventName = 'mouseover';
        export const mouseOutEventName = 'mouseout';
        export const mouseClickEventName = 'click';
        export const pasteEventName = 'paste';
        export const scrollEventName = 'scroll';
        export const dropEventName = 'drop';
        export const focusEventName = 'focus';
        export const focusInEventName = 'focusin';
        export const focusOutEventName = 'focusout';
        export const selectEventName = 'select';
        export const messageEventName = 'message';
        export const loadEventName = 'load';
        export const beforeUnload = 'beforeunload';

        /**
         * Common DOM event combination names.
         */
        export const inputAndSelectEventNames = 'input, select';
    }
}


text:
repositorio para desarrollo sistema netafim
instrucciones en construccion


text:
<!--
   This file is part of the X12Parser library that provides tools to
   manipulate X12 messages using Ruby native syntax.

   http://x12parser.rubyforge.org

   Copyright (C) 2009 APP Design, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

   $Id: BX.xml 78 2009-05-12 22:27:26Z ikk $
-->

<Segment name="BX" comment="To transmit identification numbers and other basic shipment data">
  <Field name="TransactionSetPurposeCode" min="2" max="2" validation="T353" comment="Code identifying purpose of transaction set"/>
  <Field name="TransportationMethodTypeCode" min="1" max="2" validation="T91" comment="Code specifying the method or type of transportation for the shipment"/>
  <Field name="ShipmentMethodOfPayment" min="2" max="2" validation="T146" comment="Code identifying payment terms for transportation charges"/>
  <Field name="ShipmentIdentificationNumber" required="y" min="1" max="30" comment="Identification number assigned to the shipment by the shipper that uniquely identifies the shipment from origin to ultimate destination and is not subject to modification; (Does not contain blanks or special characters)"/>
  <Field name="StandardCarrierAlphaCode" required="y" min="2" max="4" comment="Standard Carrier Alpha Code"/>
  <Field name="WeightUnitCode" required="y" min="1" max="1" validation="T188" comment="Code specifying the weight unit"/>
  <Field name="ShipmentQualifier" required="y" min="1" max="1" validation="T147" comment="Code defining relationship of this shipment with respect to other shipments given to the carrier at the same time"/>
  <Field name="SectionSevenCode" required="y" min="1" max="1" validation="T226" comment="Code indicating applicability of section seven option (if not transmitted assume not in effect)"/>
  <Field name="CapacityLoadCode" required="y" min="1" max="1" validation="T195" comment="Code specifying type of capacity load"/>
  <Field name="StatusReportRequestCode" required="y" min="1" max="1" validation="T160" comment="Code used by the shipper to specify that an automatic status report is requested when the shipment is delivered"/>
  <Field name="CustomsDocumentationHandlingCode" required="y" min="2" max="2" validation="T501" comment="Code defining method of handling for documentation"/>
  <Field name="ConfidentialBillingRequestCode" required="y" min="1" max="1" validation="T199" comment="Code used by the shipper to request that the carrier inhibit origin identification information from the invoice transaction sets and/or rate and charges from waybill documents and transaction sets when shipment moves under confidential contract rates"/>
  <Field name="GoodsAndServicesTaxReasonCode" required="y" min="1" max="1" validation="T714" comment="Code required to identify the reason for a 0% rated goods and services tax"/>
  <Field name="ApplicationType" required="y" min="2" max="2" validation="T346" comment="Code identifying an application"/>
</Segment>


text:
var request = require('superagent');
var config = require('../config');
var utils = require('./utils');
var extend = require('extend');

var count = 1;
var query = {
  view : 'pointToSOIL(-121.9921875,39.02771884021161,8192)',
  tq : 'SELECT *',
  tqx : 'reqId:'
};

module.exports = {
    getAll : getAll
};

function getAll(query, callback) {

  request
    .post(config().ahbServer+config().ahbBulkSoilUrl)
    .send({coordinates: query})
    .end(function(err, resp){
      if( err ) {
        return callback(err);
      }

      resp = resp.body;

      // HACK
      resp.coordinates.forEach(function(item){
        item.maxAWS = item.maxaws;
        delete item.maxaws;

        for( var key in item ) {
          item[key] = parseFloat(item[key]);
        }
      });

      callback(null, resp.coordinates);
    });
}