text:
using System;
using Xunit;
using WmcSoft.TestTools.UnitTesting;

namespace WmcSoft
{
    public class OrdinalTests
    {
        [Fact]
        public void CheckInt32Ordinal()
        {
            var ordinal = new Int32Ordinal();

            ContractAssert.Ordinal(ordinal, 2, 5, 3);
        }

        [Fact]
        public void ChechYearOrdinal()
        {
            YearOrdinal ordinal;

            var expected = new DateTime(2017, 02, 28);
            var actual = ordinal.Advance(new DateTime(2016, 02, 29), 1);
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void CheckSequenceOrdinal()
        {
            var ordinal = new SequenceOrdinal<char>('a', 'e', 'i', 'o', 'u', 'y');
            ContractAssert.Ordinal(ordinal, 'a', 'u', 4);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package api

import (
	"fmt"
	"net/http"

	"github.com/NebulousLabs/Sia/modules"
	"github.com/NebulousLabs/Sia/types"

	"github.com/julienschmidt/httprouter"
)

type (
	// HostGET contains the information that is returned after a GET request to
	// /host.
	HostGET struct {
		Collateral   types.Currency     `json:"collateral"`
		NetAddress   modules.NetAddress `json:"netaddress"`
		MaxDuration  types.BlockHeight  `json:"maxduration"`
		MinDuration  types.BlockHeight  `json:"minduration"`
		Price        types.Currency     `json:"price"`
		TotalStorage int64              `json:"totalstorage"`
		UnlockHash   types.UnlockHash   `json:"unlockhash"`
		WindowSize   types.BlockHeight  `json:"windowsize"`

		NumContracts       uint64         `json:"numcontracts"`
		LostRevenue        types.Currency `json:"lostrevenue"`
		Revenue            types.Currency `json:"revenue"`
		StorageRemaining   int64          `json:"storageremaining"`
		AnticipatedRevenue types.Currency `json:"anticipatedrevenue"`

		RPCErrorCalls        uint64 `json:"rpcerrorcalls"`
		RPCUnrecognizedCalls uint64 `json:"rpcunrecognizedcalls"`
		RPCDownloadCalls     uint64 `json:"rpcdownloadcalls"`
		RPCRenewCalls        uint64 `json:"rpcrenewcalls"`
		RPCReviseCalls       uint64 `json:"rpcrevisecalls"`
		RPCSettingsCalls     uint64 `json:"rpcsettingscalls"`
		RPCUploadCalls       uint64 `json:"rpcuploadcalls"`
	}
)

// hostHandlerGET handles GET requests to the /host API endpoint.
func (srv *Server) hostHandlerGET(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	settings := srv.host.Settings()
	anticipatedRevenue, revenue, lostRevenue := srv.host.Revenue()
	rpcCalls := srv.host.RPCMetrics()
	hg := HostGET{
		Collateral:   settings.Collateral,
		NetAddress:   settings.NetAddress,
		MaxDuration:  settings.MaxDuration,
		MinDuration:  settings.MinDuration,
		Price:        settings.Price,
		TotalStorage: settings.TotalStorage,
		UnlockHash:   settings.UnlockHash,
		WindowSize:   settings.WindowSize,

		NumContracts:       srv.host.Contracts(),
		LostRevenue:        lostRevenue,
		Revenue:            revenue,
		StorageRemaining:   srv.host.Capacity(),
		AnticipatedRevenue: anticipatedRevenue,

		RPCErrorCalls:        rpcCalls.ErrorCalls,
		RPCUnrecognizedCalls: rpcCalls.UnrecognizedCalls,
		RPCDownloadCalls:     rpcCalls.DownloadCalls,
		RPCRenewCalls:        rpcCalls.RenewCalls,
		RPCReviseCalls:       rpcCalls.ReviseCalls,
		RPCSettingsCalls:     rpcCalls.SettingsCalls,
		RPCUploadCalls:       rpcCalls.UploadCalls,
	}
	writeJSON(w, hg)
}

// hostHandlerPOST handles POST request to the /host API endpoint.
func (srv *Server) hostHandlerPOST(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	// Map each query string to a field in the host settings.
	settings := srv.host.Settings()
	qsVars := map[string]interface{}{
		"collateral":   &settings.Collateral,
		"maxduration":  &settings.MaxDuration,
		"minduration":  &settings.MinDuration,
		"price":        &settings.Price,
		"totalstorage": &settings.TotalStorage,
		"windowsize":   &settings.WindowSize,
	}

	// Iterate through the query string and replace any fields that have been
	// altered.
	for qs := range qsVars {
		if req.FormValue(qs) != "" { // skip empty values
			_, err := fmt.Sscan(req.FormValue(qs), qsVars[qs])
			if err != nil {
				writeError(w, "Malformed "+qs, http.StatusBadRequest)
				return
			}
		}
	}
	srv.host.SetSettings(settings)
	writeSuccess(w)
}

// hostAnnounceHandler handles the API call to get the host to announce itself
// to the network.
func (srv *Server) hostAnnounceHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	var err error
	if addr := req.FormValue("netaddress"); addr != "" {
		err = srv.host.AnnounceAddress(modules.NetAddress(addr))
	} else {
		err = srv.host.Announce()
	}
	if err != nil {
		writeError(w, err.Error(), http.StatusBadRequest)
		return
	}
	writeSuccess(w)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <issue id="AllowBackup" severity="ignore" />
    <issue id="MissingApplicationIcon" severity="ignore" />
</lint>


text:
<?xml version="1.0" encoding="UTF-8"?>
<templateSet group="Buck">

  <!-- Top-level declarations -->
  <template
    name="load" value="load("$location$", "$symbol$")$END$"
    description="Insert load() directive to import a symbol from an extension file"
    toReformat="false"
    toShortenFQNames="false">
    <variable name="location" expression="" defaultValue="" alwaysStopAt="true"/>
    <variable name="symbol" expression="" defaultValue="" alwaysStopAt="true"/>
    <context>
      <option name="BUCK_DECLARATION" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <!-- Common expressions -->

  <template
    name="glob"
    value="glob(["$include$",], exclude = ["$exclude$"], include_dotfiles=$dotfiles$)"
    description="Expand glob() function with default named parameters"
    toReformat="false"
    toShortenFQNames="false">
    <variable name="include" expression="" defaultValue=""**/*.java"" alwaysStopAt="true"/>
    <variable name="exclude" expression="" defaultValue="" alwaysStopAt="true"/>
    <variable name="dotfiles" expression="" defaultValue=""False"" alwaysStopAt="true"/>
    <context>
      <option name="BUCK_EXPRESSION" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="read_config2"
    value="read_config("$section$", "$field$")$END$"
    description="Expand read_config() function"
    toReformat="false"

    toShortenFQNames="false">
    <variable name="section" expression="" defaultValue=""section"" alwaysStopAt="true"/>
    <variable name="field" expression="" defaultValue=""field"" alwaysStopAt="true"/>
    <context>
      <option name="BUCK_EXPRESSION" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="read_config3"
    value="read_config("$section$", "$field$", $default$)$END$"
    description="Expand read_config() function with a default value"
    toReformat="false"

    toShortenFQNames="false">
    <variable name="section" expression="" defaultValue=""section"" alwaysStopAt="true"/>
    <variable name="field" expression="" defaultValue=""field"" alwaysStopAt="true"/>
    <variable name="default" expression="" defaultValue=""None"" alwaysStopAt="true"/>
    <context>
      <option name="BUCK_EXPRESSION" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <!-- Some of the most common named arguments for rules -->

  <template
    name="name" value="name = "$name$"$END$"
    description="Expand name keyword to string"
    toReformat="true"
    toShortenFQNames="false">
    <variable name="name" expression="" defaultValue="" alwaysStopAt="true"/>
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="srcsg" value="srcs = glob$END$"
    description="Expand srcs keyword to glob"
    toReformat="true"
    toShortenFQNames="false">
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="srcsl" value="srcs = [ "$END$", ]"
    description="Expand srcs keyword to list of source files"
    toReformat="true"
    toShortenFQNames="false">
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="deps" value="deps = [ "$END$", ]"
    description="Expand deps keyword to list of targets"
    toReformat="true"
    toShortenFQNames="false">
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="exported_deps" value="exported_deps = [ "$END$", ]"
    description="exported_deps keyword to list of targets"
    toReformat="true"
    toShortenFQNames="false">
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="provided_deps" value="provided_deps = [ "$END$", ]"
    description="Expand provided_deps keyword to list of targets"
    toReformat="true"
    toShortenFQNames="false">
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="resourcesg" value="resources = glob$END$"
    description="Expand resources keyword to glob"
    toReformat="false"
    toShortenFQNames="false">
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="resourcesl" value="resources = [ "$END$", ]"
    description="Expand resources keyword to list of sources"
    toReformat="true"
    toShortenFQNames="false">
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="tests" value="tests = [ "$END$", ]"
    description="Expand tests keyword to list of targets"
    toReformat="true"
    toShortenFQNames="false">
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

  <template
    name="visibility" value="visibility = [ "$pattern$" ]"
    description="Expand visibility keyword to list of target patterns"
    toReformat="false"
    toShortenFQNames="false">
    <variable name="pattern" expression="" defaultValue=""PUBLIC"" alwaysStopAt="true"/>
    <context>
      <option name="BUCK_NAMED_ARGUMENT" value="true"/>
      <option name="OTHER" value="false"/>
    </context>
  </template>

</templateSet>


text:
namespace lslboost {
namespace bimaps {
namespace container_adaptor {

/// \brief Container adaptor to easily build a std::multiset signature compatible container.

template
<
    class Base,

    class Iterator,
    class ConstIterator,
    class ReverseIterator,
    class ConstReverseIterator,

    class IteratorToBaseConverter          = ::lslboost::mpl::na,
    class IteratorFromBaseConverter        = ::lslboost::mpl::na,
    class ReverseIteratorFromBaseConverter = ::lslboost::mpl::na,
    class ValueToBaseConverter             = ::lslboost::mpl::na,
    class ValueFromBaseConverter           = ::lslboost::mpl::na,
    class KeyToBaseConverter               = ::lslboost::mpl::na,

    class FunctorsFromDerivedClasses = mpl::vector<>
>
class multiset_adaptor :

    public ::lslboost::bimaps::container_adaptor::
                ordered_associative_container_adaptor
    <
        Base,
        Iterator, ConstIterator, ReverseIterator, ConstReverseIterator,
        BOOST_DEDUCED_TYPENAME Iterator::value_type,
        IteratorToBaseConverter, IteratorFromBaseConverter,
        ReverseIteratorFromBaseConverter,
        ValueToBaseConverter, ValueFromBaseConverter,
        KeyToBaseConverter,
        FunctorsFromDerivedClasses
    >
{

    typedef ::lslboost::bimaps::container_adaptor::
                ordered_associative_container_adaptor
    <
        Base,
        Iterator, ConstIterator, ReverseIterator, ConstReverseIterator,
        BOOST_DEDUCED_TYPENAME Iterator::value_type,
        IteratorToBaseConverter, IteratorFromBaseConverter,
        ReverseIteratorFromBaseConverter,
        ValueToBaseConverter, ValueFromBaseConverter,
        KeyToBaseConverter,
        FunctorsFromDerivedClasses

    > base_;

    // Access -----------------------------------------------------------------

    public:

    explicit multiset_adaptor(Base & c) :
        base_(c) {}

    protected:

    typedef multiset_adaptor multiset_adaptor_;

    public:

    BOOST_BIMAP_NON_UNIQUE_CONTAINER_ADAPTOR_INSERT_FUNCTIONS
};

} // namespace container_adaptor
} // namespace bimaps
} // namespace lslboost

#endif // BOOST_BIMAP_CONTAINER_ADAPTOR_MULTISET_ADAPTOR_HPP


text:
from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from pprint import pprint
from getpass import getpass

pwd = getpass()
a_device = Device(host='50.76.53.27', user='pyclass', password=pwd)
a_device.open()     # Establich connection to Juniper SRX device

# Instantiagte an EthPortTable object
ports = EthPortTable(a_device)

# Retrieve data from ports
ports.get()

# Retrieve port numbers and recursively obtain other info from there
for a_port in ports.keys():
    print ("Port: %s, Operating state: %s, Rx Packets: %s, Tx Packets: %s"
           % (a_port,
              ports[a_port]['oper'],
              ports[a_port]['rx_packets'],
              ports[a_port]['tx_packets']))
# mm = tamtamnewclass


text:
package main

import (
	"flag"
	"os"
	"os/signal"
	"syscall"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/vt/logutil"
	"github.com/youtube/vitess/go/vt/worker/vtworkerclient"
	"golang.org/x/net/context"

	logutilpb "github.com/youtube/vitess/go/vt/proto/logutil"
)

var (
	server = flag.String("server", "", "server to use for connection")
)

func main() {
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
	go func() {
		s := <-sigChan
		log.Errorf("Trying to cancel current command after receiving signal: %v", s)
		cancel()
	}()

	logger := logutil.NewConsoleLogger()

	err := vtworkerclient.RunCommandAndWait(
		ctx, *server, flag.Args(),
		func(e *logutilpb.Event) {
			logutil.LogEvent(logger, e)
		})
	if err != nil {
		log.Error(err)
		os.Exit(1)
	}
}


text:
package com.inari.dash.game.cave.unit.enemy;

import com.inari.commons.GeomUtils;
import com.inari.commons.geom.Direction;

public final class FireflyController extends FlyController {

    protected FireflyController( int id ) {
        super( id );
    }

    @Override
    protected final Direction changeDirection( Direction dir ) {
        return GeomUtils.rotateRight2( dir );
    }

    @Override
    protected final Direction getNewDirection( Direction dir ) {
        return GeomUtils.rotateLeft2( dir );
    }

}


text:
FoxCrypt
========

Easy to use encryption ciphers implemented in C++


text:
package org.nescent.VTO.diff;

public class VTOdiff {

	/**
	 * This is a separate tool for comparing a tab delimited file of taxa against the VTO
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


text:
#include "LightMemoryTest.h"

//
// Global:
// Since this driver will only ever produce one instance of the memory test
// protocol, so we do not need to dynamically allocate the PrivateData.
//
EFI_PHYSICAL_ADDRESS    mCurrentAddress;
LIST_ENTRY          *mCurrentLink;
NONTESTED_MEMORY_RANGE  *mCurrentRange;
UINT64                  mTestedSystemMemory;
UINT64                  mNonTestedSystemMemory;

UINT32                  GenericMemoryTestMonoPattern[GENERIC_CACHELINE_SIZE / 4] = {
  0x5a5a5a5a,
  0xa5a5a5a5,
  0x5a5a5a5a,
  0xa5a5a5a5,
  0x5a5a5a5a,
  0xa5a5a5a5,
  0x5a5a5a5a,
  0xa5a5a5a5,
  0x5a5a5a5a,
  0xa5a5a5a5,
  0x5a5a5a5a,
  0xa5a5a5a5,
  0x5a5a5a5a,
  0xa5a5a5a5,
  0x5a5a5a5a,
  0xa5a5a5a5
};

/**
  Compares the contents of two buffers.

  This function compares Length bytes of SourceBuffer to Length bytes of DestinationBuffer.
  If all Length bytes of the two buffers are identical, then 0 is returned.  Otherwise, the
  value returned is the first mismatched byte in SourceBuffer subtracted from the first
  mismatched byte in DestinationBuffer.

  If Length = 0, then ASSERT().

  @param[in] DestinationBuffer The pointer to the destination buffer to compare.
  @param[in] SourceBuffer      The pointer to the source buffer to compare.
  @param[in] Length            The number of bytes to compare.

  @return 0                 All Length bytes of the two buffers are identical.
  @retval Non-zero          The first mismatched byte in SourceBuffer subtracted from the first
                            mismatched byte in DestinationBuffer.

**/
INTN
EFIAPI
CompareMemWithoutCheckArgument (
  IN      CONST VOID                *DestinationBuffer,
  IN      CONST VOID                *SourceBuffer,
  IN      UINTN                     Length
  )
{
  ASSERT (Length > 0);
  while ((--Length != 0) &&
         (*(INT8*)DestinationBuffer == *(INT8*)SourceBuffer)) {
    DestinationBuffer = (INT8*)DestinationBuffer + 1;
    SourceBuffer = (INT8*)SourceBuffer + 1;
  }
  return (INTN)*(UINT8*)DestinationBuffer - (INTN)*(UINT8*)SourceBuffer;
}

/**
  Construct the system base memory range through GCD service.

  @param[in] Private  Point to generic memory test driver's private data.

  @retval EFI_SUCCESS          Successful construct the base memory range through GCD service.
  @retval EFI_OUT_OF_RESOURCE  Could not allocate needed resource from base memory.
  @retval Others               Failed to construct base memory range through GCD service.

**/
EFI_STATUS
ConstructBaseMemoryRange (
  IN  GENERIC_MEMORY_TEST_PRIVATE  *Private
  )
{
  UINTN                           NumberOfDescriptors;
  EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap;
  UINTN                           Index;

  //
  // Base memory will always below 4G
  //
  gDS->GetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap);

  for (Index = 0; Index < NumberOfDescriptors; Index++) {
    if ((MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeSystemMemory) ||
        (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeMoreReliable)) {
      Private->BaseMemorySize += MemorySpaceMap[Index].Length;
    }
  }

  return EFI_SUCCESS;
}

/**
  Destroy the link list base on the correspond link list type.

  @param[in] Private  Point to generic memory test driver's private data.

**/
VOID
DestroyLinkList (
  IN  GENERIC_MEMORY_TEST_PRIVATE  *Private
  )
{
  LIST_ENTRY          *Link;
  NONTESTED_MEMORY_RANGE  *NontestedRange;

  Link = Private->NonTestedMemRanList.BackLink;

  while (Link != &Private->NonTestedMemRanList) {
    RemoveEntryList (Link);
    NontestedRange = NONTESTED_MEMORY_RANGE_FROM_LINK (Link);
    gBS->FreePool (NontestedRange);
    Link = Private->NonTestedMemRanList.BackLink;;
  }
}

/**
  Convert the memory range to tested.

  @param BaseAddress  Base address of the memory range.
  @param Length       Length of the memory range.
  @param Capabilities Capabilities of the memory range.

  @retval EFI_SUCCESS The memory range is converted to tested.
  @retval others      Error happens.
**/
EFI_STATUS
ConvertToTestedMemory (
  IN UINT64           BaseAddress,
  IN UINT64           Length,
  IN UINT64           Capabilities
  )
{
  EFI_STATUS Status;
  Status = gDS->RemoveMemorySpace (
                  BaseAddress,
                  Length
                  );
  if (!EFI_ERROR (Status)) {
    Status = gDS->AddMemorySpace (
                    ((Capabilities & EFI_MEMORY_MORE_RELIABLE) == EFI_MEMORY_MORE_RELIABLE) ?
                    EfiGcdMemoryTypeMoreReliable : EfiGcdMemoryTypeSystemMemory,
                    BaseAddress,
                    Length,
                    Capabilities &~
                    (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME)
                    );
  }
  return Status;
}

/**
  Add the extened memory to whole system memory map.

  @param[in] Private  Point to generic memory test driver's private data.

  @retval EFI_SUCCESS Successful add all the extended memory to system memory map.
  @retval Others      Failed to add the tested extended memory.

**/
EFI_STATUS
UpdateMemoryMap (
  IN  GENERIC_MEMORY_TEST_PRIVATE  *Private
  )
{
  LIST_ENTRY          *Link;
  NONTESTED_MEMORY_RANGE  *Range;

  Link = Private->NonTestedMemRanList.ForwardLink;

  while (Link != &Private->NonTestedMemRanList) {
    Range = NONTESTED_MEMORY_RANGE_FROM_LINK (Link);

    ConvertToTestedMemory (
      Range->StartAddress,
      Range->Length,
      Range->Capabilities &~
      (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME)
      );
    Link = Link->ForwardLink;
  }

  return EFI_SUCCESS;
}

/**
  Test a range of the memory directly .

  @param[in] Private       Point to generic memory test driver's private data.
  @param[in] StartAddress  Starting address of the memory range to be tested.
  @param[in] Length        Length in bytes of the memory range to be tested.
  @param[in] Capabilities  The bit mask of attributes that the memory range supports.

  @retval EFI_SUCCESS      Successful test the range of memory.
  @retval Others           Failed to test the range of memory.

**/
EFI_STATUS
DirectRangeTest (
  IN  GENERIC_MEMORY_TEST_PRIVATE  *Private,
  IN  EFI_PHYSICAL_ADDRESS         StartAddress,
  IN  UINT64                       Length,
  IN  UINT64                       Capabilities
  )
{
  EFI_STATUS  Status;

  //
  // Perform a dummy memory test, so directly write the pattern to all range
  //
  WriteMemory (Private, StartAddress, Length);

  //
  // Verify the memory range
  //
  Status = VerifyMemory (Private, StartAddress, Length);
  if (EFI_ERROR (Status)) {
    return Status;
  }
  //
  // Add the tested compatible memory to system memory using GCD service
  //
  ConvertToTestedMemory (
      StartAddress,
      Length,
      Capabilities &~
      (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME)
      );

  return EFI_SUCCESS;
}

/**
  Construct the system non-tested memory range through GCD service.

  @param[in] Private  Point to generic memory test driver's private data.

  @retval EFI_SUCCESS          Successful construct the non-tested memory range through GCD service.
  @retval EFI_OUT_OF_RESOURCE  Could not allocate needed resource from base memory.
  @retval Others               Failed to construct non-tested memory range through GCD service.

**/
EFI_STATUS
ConstructNonTestedMemoryRange (
  IN  GENERIC_MEMORY_TEST_PRIVATE  *Private
  )
{
  NONTESTED_MEMORY_RANGE          *Range;
  BOOLEAN                         NoFound;
  UINTN                           NumberOfDescriptors;
  EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap;
  UINTN                           Index;

  //
  // Non tested memory range may be span 4G here
  //
  NoFound = TRUE;

  gDS->GetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap);

  for (Index = 0; Index < NumberOfDescriptors; Index++) {
    if (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeReserved &&
        (MemorySpaceMap[Index].Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) ==
          (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED)
          ) {
      NoFound = FALSE;
      //
      // Light version do not need to process >4G memory range
      //
      gBS->AllocatePool (
            EfiBootServicesData,
            sizeof (NONTESTED_MEMORY_RANGE),
            (VOID **) &Range
            );

      Range->Signature    = EFI_NONTESTED_MEMORY_RANGE_SIGNATURE;
      Range->StartAddress = MemorySpaceMap[Index].BaseAddress;
      Range->Length       = MemorySpaceMap[Index].Length;
      Range->Capabilities = MemorySpaceMap[Index].Capabilities;

      mNonTestedSystemMemory += MemorySpaceMap[Index].Length;
      InsertTailList (&Private->NonTestedMemRanList, &Range->Link);
    }
  }

  if (NoFound) {
    return EFI_NOT_FOUND;
  }

  return EFI_SUCCESS;
}

/**
  Write the memory test pattern into a range of physical memory.

  @param[in] Private  Point to generic memory test driver's private data.
  @param[in] Start    The memory range's start address.
  @param[in] Size     The memory range's size.

  @retval EFI_SUCCESS Successful write the test pattern into the non-tested memory.
  @retval Others      The test pattern may not really write into the physical memory.

**/
EFI_STATUS
WriteMemory (
  IN  GENERIC_MEMORY_TEST_PRIVATE  *Private,
  IN  EFI_PHYSICAL_ADDRESS         Start,
  IN  UINT64                       Size
  )
{
  EFI_PHYSICAL_ADDRESS  Address;

  Address = Start;

  //
  // Add 4G memory address check for IA32 platform
  // NOTE: Without page table, there is no way to use memory above 4G.
  //
  if (Start + Size > MAX_ADDRESS) {
    return EFI_SUCCESS;
  }

  while (Address < (Start + Size)) {
    CopyMem ((VOID *) (UINTN) Address, Private->MonoPattern, Private->MonoTestSize);
    Address += Private->CoverageSpan;
  }
  //
  // bug bug: we may need GCD service to make the code cache and data uncache,
  // if GCD do not support it or return fail, then just flush the whole cache.
  //
  if (Private->Cpu != NULL) {
    Private->Cpu->FlushDataCache (Private->Cpu, Start, Size, EfiCpuFlushTypeWriteBackInvalidate);
  }

  return EFI_SUCCESS;
}

/**
  Verify the range of physical memory which covered by memory test pattern.

  This function will also do not return any informatin just cause system reset,
  because the handle error encount fatal error and disable the bad DIMMs.

  @param[in] Private  Point to generic memory test driver's private data.
  @param[in] Start    The memory range's start address.
  @param[in] Size     The memory range's size.

  @retval EFI_SUCCESS Successful verify the range of memory, no errors' location found.
  @retval Others      The range of memory have errors contained.

**/
EFI_STATUS
VerifyMemory (
  IN  GENERIC_MEMORY_TEST_PRIVATE  *Private,
  IN  EFI_PHYSICAL_ADDRESS         Start,
  IN  UINT64                       Size
  )
{
  EFI_PHYSICAL_ADDRESS            Address;
  INTN                            ErrorFound;
  EFI_MEMORY_EXTENDED_ERROR_DATA  *ExtendedErrorData;

  Address           = Start;
  ExtendedErrorData = NULL;

  //
  // Add 4G memory address check for IA32 platform
  // NOTE: Without page table, there is no way to use memory above 4G.
  //
  if (Start + Size > MAX_ADDRESS) {
    return EFI_SUCCESS;
  }

  //
  // Use the software memory test to check whether have detected miscompare
  // error here. If there is miscompare error here then check if generic
  // memory test driver can disable the bad DIMM.
  //
  while (Address < (Start + Size)) {
    ErrorFound = CompareMemWithoutCheckArgument (
                  (VOID *) (UINTN) (Address),
                  Private->MonoPattern,
                  Private->MonoTestSize
                  );
    if (ErrorFound != 0) {
      //
      // Report uncorrectable errors
      //
      ExtendedErrorData = AllocateZeroPool (sizeof (EFI_MEMORY_EXTENDED_ERROR_DATA));
      if (ExtendedErrorData == NULL) {
        return EFI_OUT_OF_RESOURCES;
      }

      ExtendedErrorData->DataHeader.HeaderSize  = (UINT16) sizeof (EFI_STATUS_CODE_DATA);
      ExtendedErrorData->DataHeader.Size        = (UINT16) (sizeof (EFI_MEMORY_EXTENDED_ERROR_DATA) - sizeof (EFI_STATUS_CODE_DATA));
      ExtendedErrorData->Granularity            = EFI_MEMORY_ERROR_DEVICE;
      ExtendedErrorData->Operation              = EFI_MEMORY_OPERATION_READ;
      ExtendedErrorData->Syndrome               = 0x0;
      ExtendedErrorData->Address                = Address;
      ExtendedErrorData->Resolution             = 0x40;

      REPORT_STATUS_CODE_EX (
          EFI_ERROR_CODE,
          EFI_COMPUTING_UNIT_MEMORY | EFI_CU_MEMORY_EC_UNCORRECTABLE,
          0,
          &gEfiGenericMemTestProtocolGuid,
          NULL,
          (UINT8 *) ExtendedErrorData + sizeof (EFI_STATUS_CODE_DATA),
          ExtendedErrorData->DataHeader.Size
          );

      return EFI_DEVICE_ERROR;
    }

    Address += Private->CoverageSpan;
  }

  return EFI_SUCCESS;
}

/**
  Initialize the generic memory test.

  @param[in]  This                The protocol instance pointer.
  @param[in]  Level               The coverage level of the memory test.
  @param[out] RequireSoftECCInit  Indicate if the memory need software ECC init.

  @retval EFI_SUCCESS         The generic memory test is initialized correctly.
  @retval EFI_NO_MEDIA        The system had no memory to be tested.

**/
EFI_STATUS
EFIAPI
InitializeMemoryTest (
  IN EFI_GENERIC_MEMORY_TEST_PROTOCOL          *This,
  IN  EXTENDMEM_COVERAGE_LEVEL                 Level,
  OUT BOOLEAN                                  *RequireSoftECCInit
  )
{
  EFI_STATUS                  Status;
  GENERIC_MEMORY_TEST_PRIVATE *Private;
  EFI_CPU_ARCH_PROTOCOL       *Cpu;

  Private             = GENERIC_MEMORY_TEST_PRIVATE_FROM_THIS (This);
  *RequireSoftECCInit = FALSE;

  //
  // This is initialize for default value, but some value may be reset base on
  // platform memory test driver.
  //
  Private->CoverLevel   = Level;
  Private->BdsBlockSize = TEST_BLOCK_SIZE;
  Private->MonoPattern  = GenericMemoryTestMonoPattern;
  Private->MonoTestSize = GENERIC_CACHELINE_SIZE;

  //
  // Initialize several internal link list
  //
  InitializeListHead (&Private->NonTestedMemRanList);

  //
  // Construct base memory range
  //
  ConstructBaseMemoryRange (Private);

  //
  // get the cpu arch protocol to support flash cache
  //
  Status = gBS->LocateProtocol (
                  &gEfiCpuArchProtocolGuid,
                  NULL,
                  (VOID **) &Cpu
                  );
  if (!EFI_ERROR (Status)) {
    Private->Cpu = Cpu;
  }
  //
  // Create the CoverageSpan of the memory test base on the coverage level
  //
  switch (Private->CoverLevel) {
  case EXTENSIVE:
    Private->CoverageSpan = GENERIC_CACHELINE_SIZE;
    break;

  case SPARSE:
    Private->CoverageSpan = SPARSE_SPAN_SIZE;
    break;

  //
  // Even the BDS do not need to test any memory, but in some case it
  // still need to init ECC memory.
  //
  default:
    Private->CoverageSpan = QUICK_SPAN_SIZE;
    break;
  }
  //
  // This is the first time we construct the non-tested memory range, if no
  // extended memory found, we know the system have not any extended memory
  // need to be test
  //
  Status = ConstructNonTestedMemoryRange (Private);
  if (Status == EFI_NOT_FOUND) {
    return EFI_NO_MEDIA;
  }
  //
  // ready to perform the R/W/V memory test
  //
  mTestedSystemMemory = Private->BaseMemorySize;
  mCurrentLink        = Private->NonTestedMemRanList.ForwardLink;
  mCurrentRange       = NONTESTED_MEMORY_RANGE_FROM_LINK (mCurrentLink);
  mCurrentAddress     = mCurrentRange->StartAddress;

  return EFI_SUCCESS;
}

/**
  Perform the memory test.

  @param[in]  This              The protocol instance pointer.
  @param[out] TestedMemorySize  Return the tested extended memory size.
  @param[out] TotalMemorySize   Return the whole system physical memory size.
                                The total memory size does not include memory in a slot with a disabled DIMM.
  @param[out] ErrorOut          TRUE if the memory error occured.
  @param[in]  IfTestAbort       Indicates that the user pressed "ESC" to skip the memory test.

  @retval EFI_SUCCESS         One block of memory passed the test.
  @retval EFI_NOT_FOUND       All memory blocks have already been tested.
  @retval EFI_DEVICE_ERROR    Memory device error occured, and no agent can handle it.

**/
EFI_STATUS
EFIAPI
GenPerformMemoryTest (
  IN EFI_GENERIC_MEMORY_TEST_PROTOCOL          *This,
  OUT UINT64                                   *TestedMemorySize,
  OUT UINT64                                   *TotalMemorySize,
  OUT BOOLEAN                                  *ErrorOut,
  IN BOOLEAN                                   TestAbort
  )
{
  EFI_STATUS                      Status;
  GENERIC_MEMORY_TEST_PRIVATE     *Private;
  EFI_MEMORY_RANGE_EXTENDED_DATA  *RangeData;
  UINT64                          BlockBoundary;

  Private       = GENERIC_MEMORY_TEST_PRIVATE_FROM_THIS (This);
  *ErrorOut     = FALSE;
  RangeData     = NULL;
  BlockBoundary = 0;

  //
  // In extensive mode the boundary of "mCurrentRange->Length" may will lost
  // some range that is not Private->BdsBlockSize size boundary, so need
  // the software mechanism to confirm all memory location be covered.
  //
  if (mCurrentAddress < (mCurrentRange->StartAddress + mCurrentRange->Length)) {
    if ((mCurrentAddress + Private->BdsBlockSize) <= (mCurrentRange->StartAddress + mCurrentRange->Length)) {
      BlockBoundary = Private->BdsBlockSize;
    } else {
      BlockBoundary = mCurrentRange->StartAddress + mCurrentRange->Length - mCurrentAddress;
    }
    //
    // If TestAbort is true, means user cancel the memory test
    //
    if (!TestAbort && Private->CoverLevel != IGNORE) {
      //
      // Report status code of every memory range
      //
      RangeData                         = AllocateZeroPool (sizeof (EFI_MEMORY_RANGE_EXTENDED_DATA));
      if (RangeData == NULL) {
        return EFI_OUT_OF_RESOURCES;
      }
      RangeData->DataHeader.HeaderSize  = (UINT16) sizeof (EFI_STATUS_CODE_DATA);
      RangeData->DataHeader.Size        = (UINT16) (sizeof (EFI_MEMORY_RANGE_EXTENDED_DATA) - sizeof (EFI_STATUS_CODE_DATA));
      RangeData->Start                  = mCurrentAddress;
      RangeData->Length                 = BlockBoundary;

      REPORT_STATUS_CODE_EX (
          EFI_PROGRESS_CODE,
          EFI_COMPUTING_UNIT_MEMORY | EFI_CU_MEMORY_PC_TEST,
          0,
          &gEfiGenericMemTestProtocolGuid,
          NULL,
          (UINT8 *) RangeData + sizeof (EFI_STATUS_CODE_DATA),
          RangeData->DataHeader.Size
          );

      //
      // The software memory test (R/W/V) perform here. It will detect the
      // memory mis-compare error.
      //
      WriteMemory (Private, mCurrentAddress, BlockBoundary);

      Status = VerifyMemory (Private, mCurrentAddress, BlockBoundary);
      if (EFI_ERROR (Status)) {
        //
        // If perform here, means there is mis-compare error, and no agent can
        // handle it, so we return to BDS EFI_DEVICE_ERROR.
        //
        *ErrorOut = TRUE;
        return EFI_DEVICE_ERROR;
      }
    }

    mTestedSystemMemory += BlockBoundary;
    *TestedMemorySize = mTestedSystemMemory;

    //
    // If the memory test restart after the platform driver disable dimms,
    // the NonTestSystemMemory may be changed, but the base memory size will
    // not changed, so we can get the current total memory size.
    //
    *TotalMemorySize = Private->BaseMemorySize + mNonTestedSystemMemory;

    //
    // Update the current test address pointing to next BDS BLOCK
    //
    mCurrentAddress += Private->BdsBlockSize;

    return EFI_SUCCESS;
  }
  //
  // Change to next non tested memory range
  //
  mCurrentLink = mCurrentLink->ForwardLink;
  if (mCurrentLink != &Private->NonTestedMemRanList) {
    mCurrentRange   = NONTESTED_MEMORY_RANGE_FROM_LINK (mCurrentLink);
    mCurrentAddress = mCurrentRange->StartAddress;
    return EFI_SUCCESS;
  } else {
    //
    // Here means all the memory test have finished
    //
    *TestedMemorySize = mTestedSystemMemory;
    *TotalMemorySize  = Private->BaseMemorySize + mNonTestedSystemMemory;
    return EFI_NOT_FOUND;
  }

}

/**
  Finish the memory test.

  @param[in] This             The protocol instance pointer.

  @retval EFI_SUCCESS         Success. All resources used in the memory test are freed.

**/
EFI_STATUS
EFIAPI
GenMemoryTestFinished (
  IN EFI_GENERIC_MEMORY_TEST_PROTOCOL *This
  )
{
  EFI_STATUS                  Status;
  GENERIC_MEMORY_TEST_PRIVATE *Private;

  Private = GENERIC_MEMORY_TEST_PRIVATE_FROM_THIS (This);

  //
  // Perform Data and Address line test
  //
  Status = PerformAddressDataLineTest (Private);
  ASSERT_EFI_ERROR (Status);

  //
  // Add the non tested memory range to system memory map through GCD service
  //
  UpdateMemoryMap (Private);

  //
  // we need to free all the memory allocate
  //
  DestroyLinkList (Private);

  return EFI_SUCCESS;
}

/**
  Provides the capability to test the compatible range used by some special drivers.

  @param[in]  This              The protocol instance pointer.
  @param[in]  StartAddress      The start address of the compatible memory range that
                                must be below 16M.
  @param[in]  Length            The compatible memory range's length.

  @retval EFI_SUCCESS           The compatible memory range pass the memory test.
  @retval EFI_INVALID_PARAMETER The compatible memory range are not below Low 16M.

**/
EFI_STATUS
EFIAPI
GenCompatibleRangeTest (
  IN EFI_GENERIC_MEMORY_TEST_PROTOCOL         *This,
  IN EFI_PHYSICAL_ADDRESS                     StartAddress,
  IN UINT64                                   Length
  )
{
  EFI_STATUS                      Status;
  GENERIC_MEMORY_TEST_PRIVATE     *Private;
  EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor;
  EFI_PHYSICAL_ADDRESS            CurrentBase;
  UINT64                          CurrentLength;

  Private = GENERIC_MEMORY_TEST_PRIVATE_FROM_THIS (This);

  //
  // Check if the parameter is below 16MB
  //
  if (StartAddress + Length > 0x1000000) {
    return EFI_INVALID_PARAMETER;
  }
  CurrentBase = StartAddress;
  do {
    //
    // Check the required memory range status; if the required memory range span
    // the different GCD memory descriptor, it may be cause different action.
    //
    Status = gDS->GetMemorySpaceDescriptor (
                    CurrentBase,
                    &Descriptor
                    );
    if (EFI_ERROR (Status)) {
      return Status;
    }

    if (Descriptor.GcdMemoryType == EfiGcdMemoryTypeReserved &&
        (Descriptor.Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) ==
          (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED)
          ) {
      CurrentLength = Descriptor.BaseAddress + Descriptor.Length - CurrentBase;
      if (CurrentBase + CurrentLength > StartAddress + Length) {
        CurrentLength = StartAddress + Length - CurrentBase;
      }
      Status = DirectRangeTest (
                 Private,
                 CurrentBase,
                 CurrentLength,
                 Descriptor.Capabilities
                 );
      if (EFI_ERROR (Status)) {
        return Status;
      }
    }
    CurrentBase = Descriptor.BaseAddress + Descriptor.Length;
  } while (CurrentBase < StartAddress + Length);
  //
  // Here means the required range already be tested, so just return success.
  //
  return EFI_SUCCESS;
}

/**
  Perform the address line walking ones test.

  @param[in] Private  Point to generic memory test driver's private data.

  @retval EFI_SUCCESS          Successful finished walking ones test.
  @retval EFI_OUT_OF_RESOURCE  Could not get resource in base memory.
  @retval EFI_ACCESS_DENIED    Code may can not run here because if walking one test
                               failed, system may be already halt.

**/
EFI_STATUS
PerformAddressDataLineTest (
  IN  GENERIC_MEMORY_TEST_PRIVATE      *Private
  )
{
  LIST_ENTRY              *ExtendedLink;
  NONTESTED_MEMORY_RANGE  *ExtendedRange;
  BOOLEAN                 InExtendedRange;
  EFI_PHYSICAL_ADDRESS    TestAddress;

  //
  // Light version no data line test, only perform the address line test
  //
  TestAddress = (EFI_PHYSICAL_ADDRESS) 0x1;
  while (TestAddress < MAX_ADDRESS && TestAddress > 0) {
    //
    // only test if the address falls in the enabled range
    //
    InExtendedRange = FALSE;
    ExtendedLink    = Private->NonTestedMemRanList.BackLink;
    while (ExtendedLink != &Private->NonTestedMemRanList) {
      ExtendedRange = NONTESTED_MEMORY_RANGE_FROM_LINK (ExtendedLink);
      if ((TestAddress >= ExtendedRange->StartAddress) &&
          (TestAddress < (ExtendedRange->StartAddress + ExtendedRange->Length))
          ) {
        InExtendedRange = TRUE;
      }

      ExtendedLink = ExtendedLink->BackLink;
    }

    if (InExtendedRange) {
      *(EFI_PHYSICAL_ADDRESS *) (UINTN) TestAddress = TestAddress;
      Private->Cpu->FlushDataCache (Private->Cpu, TestAddress, 1, EfiCpuFlushTypeWriteBackInvalidate);
      if (*(EFI_PHYSICAL_ADDRESS *) (UINTN) TestAddress != TestAddress) {
        return EFI_ACCESS_DENIED;
      }
    }

    TestAddress = LShiftU64 (TestAddress, 1);
  }

  return EFI_SUCCESS;
}
//
// Driver entry here
//
GENERIC_MEMORY_TEST_PRIVATE mGenericMemoryTestPrivate = {
  EFI_GENERIC_MEMORY_TEST_PRIVATE_SIGNATURE,
  NULL,
  NULL,
  {
    InitializeMemoryTest,
    GenPerformMemoryTest,
    GenMemoryTestFinished,
    GenCompatibleRangeTest
  },
  (EXTENDMEM_COVERAGE_LEVEL) 0,
  0,
  0,
  NULL,
  0,
  0,
  {
    NULL,
    NULL
  }
};

/**
  The generic memory test driver's entry point.

  It initializes private data to default value.

  @param[in] ImageHandle  The firmware allocated handle for the EFI image.
  @param[in] SystemTable  A pointer to the EFI System Table.

  @retval EFI_SUCCESS     The entry point is executed successfully.
  @retval EFI_NOT_FOUND   Can't find HandOff Hob in HobList.
  @retval other           Some error occurs when executing this entry point.

**/
EFI_STATUS
EFIAPI
GenericMemoryTestEntryPoint (
  IN  EFI_HANDLE           ImageHandle,
  IN  EFI_SYSTEM_TABLE     *SystemTable
  )
{
  EFI_STATUS            Status;
  VOID                  *HobList;
  EFI_BOOT_MODE         BootMode;
  EFI_PEI_HOB_POINTERS  Hob;

  //
  // Use the generic pattern to test compatible memory range
  //
  mGenericMemoryTestPrivate.MonoPattern   = GenericMemoryTestMonoPattern;
  mGenericMemoryTestPrivate.MonoTestSize  = GENERIC_CACHELINE_SIZE;

  //
  // Get the platform boot mode
  //
  HobList = GetHobList ();

  Hob.Raw = HobList;
  if (Hob.Header->HobType != EFI_HOB_TYPE_HANDOFF) {
    return EFI_NOT_FOUND;
  }

  BootMode = Hob.HandoffInformationTable->BootMode;

  //
  // Get the platform boot mode and create the default memory test coverage
  // level and span size for compatible memory test using
  //
  switch (BootMode) {
  case BOOT_WITH_FULL_CONFIGURATION:
  case BOOT_WITH_DEFAULT_SETTINGS:
    mGenericMemoryTestPrivate.CoverageSpan = SPARSE_SPAN_SIZE;
    break;

  case BOOT_WITH_FULL_CONFIGURATION_PLUS_DIAGNOSTICS:
    mGenericMemoryTestPrivate.CoverageSpan = GENERIC_CACHELINE_SIZE;
    break;

  default:
    mGenericMemoryTestPrivate.CoverageSpan = QUICK_SPAN_SIZE;
    break;
  }
  //
  // Install the protocol
  //
  Status = gBS->InstallProtocolInterface (
                  &mGenericMemoryTestPrivate.Handle,
                  &gEfiGenericMemTestProtocolGuid,
                  EFI_NATIVE_INTERFACE,
                  &mGenericMemoryTestPrivate.GenericMemoryTest
                  );

  return Status;
}


text:
package AI::MXNet;
use v5.14.0;
use strict;
use warnings;
use AI::MXNet::Base;
use AI::MXNet::Callback;
use AI::MXNet::NDArray;
use AI::MXNet::Symbol;
use AI::MXNet::Executor;
use AI::MXNet::Executor::Group;
use AI::MXNet::CudaModule;
use AI::MXNet::Random;
use AI::MXNet::Initializer;
use AI::MXNet::Optimizer;
use AI::MXNet::KVStore;
use AI::MXNet::KVStoreServer;
use AI::MXNet::IO;
use AI::MXNet::Metric;
use AI::MXNet::LRScheduler;
use AI::MXNet::Monitor;
use AI::MXNet::Profiler;
use AI::MXNet::Module::Base;
use AI::MXNet::Module;
use AI::MXNet::Module::Bucketing;
use AI::MXNet::RNN;
use AI::MXNet::Visualization;
use AI::MXNet::RecordIO;
use AI::MXNet::Image;
use AI::MXNet::Contrib;
use AI::MXNet::CachedOp;
use AI::MXNet::AutoGrad;
use AI::MXNet::Gluon;
our $VERSION = '1.1';

sub import
{
    my ($class, $short_name) = @_;
    if($short_name)
    {
        $short_name =~ s/[^\w:]//g;
        if(length $short_name)
        {
            my $short_name_package =<<"EOP";
            package $short_name;
            no warnings 'redefine';
            sub nd { 'AI::MXNet::NDArray' }
            sub sym { 'AI::MXNet::Symbol' }
            sub symbol { 'AI::MXNet::Symbol' }
            sub init { 'AI::MXNet::Initializer' }
            sub initializer { 'AI::MXNet::Initializer' }
            sub optimizer { 'AI::MXNet::Optimizer' }
            sub opt { 'AI::MXNet::Optimizer' }
            sub rnd { 'AI::MXNet::Random' }
            sub random { 'AI::MXNet::Random' }
            sub Context { shift; AI::MXNet::Context->new(\@_) }
            sub context { 'AI::MXNet::Context' }
            sub cpu { AI::MXNet::Context->cpu(\$_[1]//0) }
            sub gpu { AI::MXNet::Context->gpu(\$_[1]//0) }
            sub kv { 'AI::MXNet::KVStore' }
            sub recordio { 'AI::MXNet::RecordIO' }
            sub io { 'AI::MXNet::IO' }
            sub metric { 'AI::MXNet::Metric' }
            sub mod { 'AI::MXNet::Module' }
            sub mon { 'AI::MXNet::Monitor' }
            sub viz { 'AI::MXNet::Visualization' }
            sub rnn { 'AI::MXNet::RNN' }
            sub callback { 'AI::MXNet::Callback' }
            sub img { 'AI::MXNet::Image' }
            sub image { 'AI::MXNet::Image' }
            sub contrib { 'AI::MXNet::Contrib' }
            sub autograd { 'AI::MXNet::AutoGrad' }
            sub name { '$short_name' }
            sub rtc { '$short_name' }
            sub CudaModule { shift; AI::MXNet::CudaModule->new(\@_) }
            sub AttrScope { shift; AI::MXNet::Symbol::AttrScope->new(\@_) }
            *AI::MXNet::Symbol::AttrScope::current = sub { \$${short_name}::AttrScope; };
            \$${short_name}::AttrScope = AI::MXNet::Symbol::AttrScope->new;
            sub Prefix { AI::MXNet::Symbol::Prefix->new(prefix => \$_[1]) }
            *AI::MXNet::Symbol::NameManager::current = sub { \$${short_name}::NameManager; };
            *AI::MXNet::Symbol::NameManager::set_current = sub { \$${short_name}::NameManager = \$_[1]; };
            \$${short_name}::NameManager = AI::MXNet::Symbol::NameManager->new;
            *AI::MXNet::Context::current_ctx = sub { \$${short_name}::Context; };
            *AI::MXNet::Context::current_context = sub { \$${short_name}::Context; };
            *AI::MXNet::Context::set_current = sub { \$${short_name}::Context = \$_[1]; };
            \$${short_name}::Context = AI::MXNet::Context->new(device_type => 'cpu', device_id => 0);
            1;
EOP
            eval $short_name_package;
        }
    }
}

1;
__END__

=encoding UTF-8

=head1 NAME

AI::MXNet - Perl interface to MXNet machine learning library

=head1 SYNOPSIS

    ## Convolutional NN for recognizing hand-written digits in MNIST dataset
    ## It's considered "Hello, World" for Neural Networks
    ## For more info about the MNIST problem please refer to http://neuralnetworksanddeeplearning.com/chap1.html

    use strict;
    use warnings;
    use AI::MXNet qw(mx);
    use AI::MXNet::TestUtils qw(GetMNIST_ubyte);
    use Test::More tests => 1;

    # symbol net
    my $batch_size = 100;

    ### model
    my $data = mx->symbol->Variable('data');
    my $conv1= mx->symbol->Convolution(data => $data, name => 'conv1', num_filter => 32, kernel => [3,3], stride => [2,2]);
    my $bn1  = mx->symbol->BatchNorm(data => $conv1, name => "bn1");
    my $act1 = mx->symbol->Activation(data => $bn1, name => 'relu1', act_type => "relu");
    my $mp1  = mx->symbol->Pooling(data => $act1, name => 'mp1', kernel => [2,2], stride =>[2,2], pool_type=>'max');

    my $conv2= mx->symbol->Convolution(data => $mp1, name => 'conv2', num_filter => 32, kernel=>[3,3], stride=>[2,2]);
    my $bn2  = mx->symbol->BatchNorm(data => $conv2, name=>"bn2");
    my $act2 = mx->symbol->Activation(data => $bn2, name=>'relu2', act_type=>"relu");
    my $mp2  = mx->symbol->Pooling(data => $act2, name => 'mp2', kernel=>[2,2], stride=>[2,2], pool_type=>'max');

    my $fl   = mx->symbol->Flatten(data => $mp2, name=>"flatten");
    my $fc1  = mx->symbol->FullyConnected(data => $fl,  name=>"fc1", num_hidden=>30);
    my $act3 = mx->symbol->Activation(data => $fc1, name=>'relu3', act_type=>"relu");
    my $fc2  = mx->symbol->FullyConnected(data => $act3, name=>'fc2', num_hidden=>10);
    my $softmax = mx->symbol->SoftmaxOutput(data => $fc2, name => 'softmax');

    # check data
    GetMNIST_ubyte();

    my $train_dataiter = mx->io->MNISTIter({
        image=>"data/train-images-idx3-ubyte",
        label=>"data/train-labels-idx1-ubyte",
        data_shape=>[1, 28, 28],
        batch_size=>$batch_size, shuffle=>1, flat=>0, silent=>0, seed=>10});
    my $val_dataiter = mx->io->MNISTIter({
        image=>"data/t10k-images-idx3-ubyte",
        label=>"data/t10k-labels-idx1-ubyte",
        data_shape=>[1, 28, 28],
        batch_size=>$batch_size, shuffle=>1, flat=>0, silent=>0});

    my $n_epoch = 1;
    my $mod = mx->mod->new(symbol => $softmax);
    $mod->fit(
        $train_dataiter,
        eval_data => $val_dataiter,
        optimizer_params=>{learning_rate=>0.01, momentum=> 0.9},
        num_epoch=>$n_epoch
    );
    my $res = $mod->score($val_dataiter, mx->metric->create('acc'));
    ok($res->{accuracy} > 0.8);

=head1 DESCRIPTION

    Perl interface to MXNet machine learning library.

=head1 BUGS AND INCOMPATIBILITIES

    Parity with Python interface is mostly achieved, few deprecated
    and not often used features left unported for now.

=head1 SEE ALSO

    http://mxnet.io/
    https://github.com/dmlc/mxnet/tree/master/perl-package
    Function::Parameters, Mouse

=head1 AUTHOR

    Sergey Kolychev, <sergeykolychev.github@gmail.com>

=head1 COPYRIGHT & LICENSE

    This library is licensed under Apache 2.0 license https://www.apache.org/licenses/LICENSE-2.0

=cut


text:
class BaseFeatureExtractor:
    def features(self, _string):
        raise NotImplementedError()

    def _each_cons(self, xs, n):
        return [xs[i:i+n] for i in range(len(xs)-n+1)]

    def _words_ngram(self, words, n, SENTINAL_CHAR):
        return [tuple(x) for x in self._each_cons([SENTINAL_CHAR] + words + [SENTINAL_CHAR], n)]


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

#include "chromeos/network/shill_property_util.h"

#include "base/i18n/icu_encoding_detection.h"
#include "base/i18n/icu_string_conversions.h"
#include "base/json/json_writer.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "base/values.h"
#include "chromeos/network/network_event_log.h"
#include "chromeos/network/network_ui_data.h"
#include "chromeos/network/onc/onc_utils.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace chromeos {

namespace shill_property_util {

namespace {

// Replace non UTF8 characters in |str| with a replacement character.
std::string ValidateUTF8(const std::string& str) {
  std::string result;
  for (int32 index = 0; index < static_cast<int32>(str.size()); ++index) {
    uint32 code_point_out;
    bool is_unicode_char = base::ReadUnicodeCharacter(
        str.c_str(), str.size(), &index, &code_point_out);
    const uint32 kFirstNonControlChar = 0x20;
    if (is_unicode_char && (code_point_out >= kFirstNonControlChar)) {
      base::WriteUnicodeCharacter(code_point_out, &result);
    } else {
      const uint32 kReplacementChar = 0xFFFD;
      // Puts kReplacementChar if character is a control character [0,0x20)
      // or is not readable UTF8.
      base::WriteUnicodeCharacter(kReplacementChar, &result);
    }
  }
  return result;
}

// If existent and non-empty, copies the string at |key| from |source| to
// |dest|. Returns true if the string was copied.
bool CopyStringFromDictionary(const base::DictionaryValue& source,
                              const std::string& key,
                              base::DictionaryValue* dest) {
  std::string string_value;
  if (!source.GetStringWithoutPathExpansion(key, &string_value) ||
      string_value.empty()) {
    return false;
  }
  dest->SetStringWithoutPathExpansion(key, string_value);
  return true;
}

// This is the same normalization that Shill applies to security types for the
// sake of comparing/identifying WiFi networks. See Shill's
// WiFiService::GetSecurityClass.
std::string GetSecurityClass(const std::string& security) {
  if (security == shill::kSecurityRsn || security == shill::kSecurityWpa)
    return shill::kSecurityPsk;
  else
    return security;
}

}  // namespace

void SetSSID(const std::string ssid, base::DictionaryValue* properties) {
  std::string hex_ssid = base::HexEncode(ssid.c_str(), ssid.size());
  properties->SetStringWithoutPathExpansion(shill::kWifiHexSsid, hex_ssid);
}

std::string GetSSIDFromProperties(const base::DictionaryValue& properties,
                                  bool* unknown_encoding) {
  if (unknown_encoding)
    *unknown_encoding = false;

  // Get name for debugging.
  std::string name;
  properties.GetStringWithoutPathExpansion(shill::kNameProperty, &name);

  std::string hex_ssid;
  properties.GetStringWithoutPathExpansion(shill::kWifiHexSsid, &hex_ssid);

  if (hex_ssid.empty()) {
    NET_LOG_DEBUG("GetSSIDFromProperties: No HexSSID set.", name);
    return std::string();
  }

  std::string ssid;
  std::vector<uint8> raw_ssid_bytes;
  if (base::HexStringToBytes(hex_ssid, &raw_ssid_bytes)) {
    ssid = std::string(raw_ssid_bytes.begin(), raw_ssid_bytes.end());
    NET_LOG_DEBUG(
        "GetSSIDFromProperties: " +
            base::StringPrintf("%s, SSID: %s", hex_ssid.c_str(), ssid.c_str()),
        name);
  } else {
    NET_LOG_ERROR(
        "GetSSIDFromProperties: " +
            base::StringPrintf("Error processing: %s", hex_ssid.c_str()),
        name);
    return std::string();
  }

  if (base::IsStringUTF8(ssid))
    return ssid;

  // Detect encoding and convert to UTF-8.
  std::string encoding;
  if (!base::DetectEncoding(ssid, &encoding)) {
    // TODO(stevenjb): This is currently experimental. If we find a case where
    // base::DetectEncoding() fails, we need to figure out whether we can use
    // country_code with ConvertToUtf8(). crbug.com/233267.
    properties.GetStringWithoutPathExpansion(shill::kCountryProperty,
                                             &encoding);
  }
  std::string utf8_ssid;
  if (!encoding.empty() &&
      base::ConvertToUtf8AndNormalize(ssid, encoding, &utf8_ssid)) {
    if (utf8_ssid != ssid) {
      NET_LOG_DEBUG(
          "GetSSIDFromProperties",
          base::StringPrintf(
              "Encoding=%s: %s", encoding.c_str(), utf8_ssid.c_str()));
    }
    return utf8_ssid;
  }

  if (unknown_encoding)
    *unknown_encoding = true;
  NET_LOG_DEBUG(
      "GetSSIDFromProperties: " +
          base::StringPrintf("Unrecognized Encoding=%s", encoding.c_str()),
      name);
  return ssid;
}

std::string GetNetworkIdFromProperties(
    const base::DictionaryValue& properties) {
  if (properties.empty())
    return "EmptyProperties";
  std::string result;
  if (properties.GetStringWithoutPathExpansion(shill::kGuidProperty, &result))
    return result;
  if (properties.GetStringWithoutPathExpansion(shill::kSSIDProperty, &result))
    return result;
  if (properties.GetStringWithoutPathExpansion(shill::kNameProperty, &result))
    return result;
  std::string type = "UnknownType";
  properties.GetStringWithoutPathExpansion(shill::kTypeProperty, &type);
  return "Unidentified " + type;
}

std::string GetNameFromProperties(const std::string& service_path,
                                  const base::DictionaryValue& properties) {
  std::string name;
  properties.GetStringWithoutPathExpansion(shill::kNameProperty, &name);

  std::string validated_name = ValidateUTF8(name);
  if (validated_name != name) {
    NET_LOG_DEBUG("GetNameFromProperties",
                  base::StringPrintf("Validated name %s: UTF8: %s",
                                     service_path.c_str(),
                                     validated_name.c_str()));
  }

  std::string type;
  properties.GetStringWithoutPathExpansion(shill::kTypeProperty, &type);
  if (type.empty()) {
    NET_LOG_ERROR("GetNameFromProperties: No type", service_path);
    return validated_name;
  }
  if (!NetworkTypePattern::WiFi().MatchesType(type))
    return validated_name;

  bool unknown_ssid_encoding = false;
  std::string ssid = GetSSIDFromProperties(properties, &unknown_ssid_encoding);
  if (ssid.empty())
    NET_LOG_ERROR("GetNameFromProperties", "No SSID set: " + service_path);

  // Use |validated_name| if |ssid| is empty.
  // And if the encoding of the SSID is unknown, use |ssid|, which contains raw
  // bytes in that case, only if |validated_name| is empty.
  if (ssid.empty() || (unknown_ssid_encoding && !validated_name.empty()))
    return validated_name;

  if (ssid != validated_name) {
    NET_LOG_DEBUG("GetNameFromProperties",
                  base::StringPrintf("%s: SSID: %s, Name: %s",
                                     service_path.c_str(),
                                     ssid.c_str(),
                                     validated_name.c_str()));
  }
  return ssid;
}

scoped_ptr<NetworkUIData> GetUIDataFromValue(const base::Value& ui_data_value) {
  std::string ui_data_str;
  if (!ui_data_value.GetAsString(&ui_data_str))
    return scoped_ptr<NetworkUIData>();
  if (ui_data_str.empty())
    return make_scoped_ptr(new NetworkUIData());
  scoped_ptr<base::DictionaryValue> ui_data_dict(
      chromeos::onc::ReadDictionaryFromJson(ui_data_str));
  if (!ui_data_dict)
    return scoped_ptr<NetworkUIData>();
  return make_scoped_ptr(new NetworkUIData(*ui_data_dict));
}

scoped_ptr<NetworkUIData> GetUIDataFromProperties(
    const base::DictionaryValue& shill_dictionary) {
  const base::Value* ui_data_value = NULL;
  shill_dictionary.GetWithoutPathExpansion(shill::kUIDataProperty,
                                           &ui_data_value);
  if (!ui_data_value) {
    VLOG(2) << "Dictionary has no UIData entry.";
    return scoped_ptr<NetworkUIData>();
  }
  scoped_ptr<NetworkUIData> ui_data = GetUIDataFromValue(*ui_data_value);
  if (!ui_data)
    LOG(ERROR) << "UIData is not a valid JSON dictionary.";
  return ui_data.Pass();
}

void SetUIData(const NetworkUIData& ui_data,
               base::DictionaryValue* shill_dictionary) {
  base::DictionaryValue ui_data_dict;
  ui_data.FillDictionary(&ui_data_dict);
  std::string ui_data_blob;
  base::JSONWriter::Write(&ui_data_dict, &ui_data_blob);
  shill_dictionary->SetStringWithoutPathExpansion(shill::kUIDataProperty,
                                                  ui_data_blob);
}

bool CopyIdentifyingProperties(const base::DictionaryValue& service_properties,
                               const bool properties_read_from_shill,
                               base::DictionaryValue* dest) {
  bool success = true;

  // GUID is optional.
  CopyStringFromDictionary(service_properties, shill::kGuidProperty, dest);

  std::string type;
  service_properties.GetStringWithoutPathExpansion(shill::kTypeProperty, &type);
  success &= !type.empty();
  dest->SetStringWithoutPathExpansion(shill::kTypeProperty, type);
  if (type == shill::kTypeWifi) {
    std::string security;
    service_properties.GetStringWithoutPathExpansion(shill::kSecurityProperty,
                                                     &security);
    if (security.empty()) {
      success = false;
    } else {
      dest->SetStringWithoutPathExpansion(shill::kSecurityProperty,
                                          GetSecurityClass(security));
    }
    success &=
        CopyStringFromDictionary(service_properties, shill::kWifiHexSsid, dest);
    success &= CopyStringFromDictionary(
        service_properties, shill::kModeProperty, dest);
  } else if (type == shill::kTypeVPN) {
    success &= CopyStringFromDictionary(
        service_properties, shill::kNameProperty, dest);

    // VPN Provider values are read from the "Provider" dictionary, but written
    // with the keys "Provider.Type" and "Provider.Host".
    // TODO(pneubeck): Simplify this once http://crbug.com/381135 is fixed.
    std::string vpn_provider_type;
    std::string vpn_provider_host;
    if (properties_read_from_shill) {
      const base::DictionaryValue* provider_properties = NULL;
      if (!service_properties.GetDictionaryWithoutPathExpansion(
              shill::kProviderProperty, &provider_properties)) {
        NET_LOG_ERROR("Missing VPN provider dict",
                      GetNetworkIdFromProperties(service_properties));
      }
      provider_properties->GetStringWithoutPathExpansion(shill::kTypeProperty,
                                                         &vpn_provider_type);
      provider_properties->GetStringWithoutPathExpansion(shill::kHostProperty,
                                                         &vpn_provider_host);
    } else {
      service_properties.GetStringWithoutPathExpansion(
          shill::kProviderTypeProperty, &vpn_provider_type);
      service_properties.GetStringWithoutPathExpansion(
          shill::kProviderHostProperty, &vpn_provider_host);
    }
    success &= !vpn_provider_type.empty();
    dest->SetStringWithoutPathExpansion(shill::kProviderTypeProperty,
                                        vpn_provider_type);

    success &= !vpn_provider_host.empty();
    dest->SetStringWithoutPathExpansion(shill::kProviderHostProperty,
                                        vpn_provider_host);
  } else if (type == shill::kTypeEthernet || type == shill::kTypeEthernetEap) {
    // Ethernet and EthernetEAP don't have any additional identifying
    // properties.
  } else {
    NOTREACHED() << "Unsupported network type " << type;
    success = false;
  }
  if (!success) {
    NET_LOG_ERROR("Missing required properties",
                  GetNetworkIdFromProperties(service_properties));
  }
  return success;
}

bool DoIdentifyingPropertiesMatch(const base::DictionaryValue& new_properties,
                                  const base::DictionaryValue& old_properties) {
  base::DictionaryValue new_identifying;
  if (!CopyIdentifyingProperties(
          new_properties,
          false /* properties were not read from Shill */,
          &new_identifying)) {
    return false;
  }
  base::DictionaryValue old_identifying;
  if (!CopyIdentifyingProperties(old_properties,
                                 true /* properties were read from Shill */,
                                 &old_identifying)) {
    return false;
  }

  return new_identifying.Equals(&old_identifying);
}

bool IsPassphraseKey(const std::string& key) {
  return key == shill::kEapPrivateKeyPasswordProperty ||
      key == shill::kEapPasswordProperty ||
      key == shill::kL2tpIpsecPasswordProperty ||
      key == shill::kOpenVPNPasswordProperty ||
      key == shill::kOpenVPNAuthUserPassProperty ||
      key == shill::kOpenVPNTLSAuthContentsProperty ||
      key == shill::kPassphraseProperty ||
      key == shill::kOpenVPNOTPProperty ||
      key == shill::kEapPrivateKeyProperty ||
      key == shill::kEapPinProperty ||
      key == shill::kApnPasswordProperty;
}

bool GetHomeProviderFromProperty(const base::Value& value,
                                 std::string* home_provider_id) {
  const base::DictionaryValue* dict = NULL;
  if (!value.GetAsDictionary(&dict))
    return false;
  std::string home_provider_country;
  std::string home_provider_name;
  dict->GetStringWithoutPathExpansion(shill::kOperatorCountryKey,
                                      &home_provider_country);
  dict->GetStringWithoutPathExpansion(shill::kOperatorNameKey,
                                      &home_provider_name);
  // Set home_provider_id
  if (!home_provider_name.empty() && !home_provider_country.empty()) {
    *home_provider_id = base::StringPrintf(
        "%s (%s)", home_provider_name.c_str(), home_provider_country.c_str());
  } else {
    if (!dict->GetStringWithoutPathExpansion(shill::kOperatorCodeKey,
                                             home_provider_id)) {
      return false;
    }
    LOG(WARNING)
        << "Provider name and country not defined, using code instead: "
        << *home_provider_id;
  }
  return true;
}

}  // namespace shill_property_util

}  // namespace chromeos


text:
package org.springframework.cloud.sleuth.exporter;

import java.util.Collection;
import java.util.Map;

import org.springframework.cloud.sleuth.Span;
import org.springframework.lang.Nullable;

/**
 * This API is inspired by OpenZipkin Brave (from {code MutableSpan}).
 *
 * Represents a span that has been finished and is ready to be sent to an external
 * location (e.g. Zipkin).
 *
 * @author OpenZipkin Brave Authors
 * @author Marcin Grzejszczak
 * @since 3.0.0
 */
public interface FinishedSpan {

	/**
	 * @return span's name
	 */
	String getName();

	/**
	 * @return span's start timestamp
	 */
	long getStartTimestamp();

	/**
	 * @return span's end timestamp
	 */
	long getEndTimestamp();

	/**
	 * @return span's tags
	 */
	Map<String, String> getTags();

	/**
	 * @return span's events as timestamp to value mapping
	 */
	Collection<Map.Entry<Long, String>> getEvents();

	/**
	 * @return span's span id
	 */
	String getSpanId();

	/**
	 * @return span's parent id or {@code null} if not set
	 */
	@Nullable
	String getParentId();

	/**
	 * @return span's remote ip
	 */
	@Nullable
	String getRemoteIp();

	/**
	 * @return span's local ip
	 */
	@Nullable
	default String getLocalIp() {
		return null;
	}

	/**
	 * @return span's remote port
	 */
	int getRemotePort();

	/**
	 * @return span's trace id
	 */
	String getTraceId();

	/**
	 * @return corresponding error or {@code null} if one was not thrown
	 */
	@Nullable
	Throwable getError();

	/**
	 * @return span's kind
	 */
	Span.Kind getKind();

	/**
	 * @return remote service name or {@code null} if not set
	 */
	@Nullable
	String getRemoteServiceName();

}


text:
package ninja.build;

import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.nio.file.SensitivityWatchEventModifier;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class WatchAndRestartMachine implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(WatchAndRestartMachine.class);

    private boolean shutdown;
    private final DelayedRestartTrigger restartTrigger;
    private final Set<String> includes;
    private final Set<String> excludes;
    private final WatchService watchService;
    private final Map<WatchKey, Path> mapOfWatchKeysToPaths;
    private final AtomicInteger takeCount;

    public WatchAndRestartMachine(
            Path directoryToRecursivelyWatch,
            Set<String> includes,
            Set<String> excludes,
            DelayedRestartTrigger restartTrigger) throws IOException {

        this(new HashSet<>(Arrays.asList(directoryToRecursivelyWatch)),
                includes, excludes, restartTrigger);

    }

    public WatchAndRestartMachine(
            Set<Path> directoriesToRecursivelyWatch,
            Set<String> includes,
            Set<String> excludes,
            DelayedRestartTrigger restartTrigger) throws IOException {

        this.watchService = FileSystems.getDefault().newWatchService();
        this.mapOfWatchKeysToPaths = new HashMap<>();
        this.includes = includes;
        this.excludes = excludes;
        this.restartTrigger = restartTrigger;
        this.takeCount = new AtomicInteger(0);
        for (Path path: directoriesToRecursivelyWatch) {
            registerAll(path);
        }

    }

    public void shutdown() {
        this.shutdown = true;
        // doesn't do anything but does prevent logging an error
    }

    private void registerAll(final Path path) throws IOException {
        // register directory and sub-directories
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path path,
                    BasicFileAttributes attrs)
                    throws IOException {
                register(path);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    /**
     * Register the given path with the WatchService
     */
    private void register(Path path) throws IOException {
        ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //// USUALLY THIS IS THE DEFAULT WAY TO REGISTER THE EVENTS:
        ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //        WatchKey watchKey = path.register(
        //                watchService,
        //                ENTRY_CREATE,
        //                ENTRY_DELETE,
        //                ENTRY_MODIFY);

        ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //// BUT THIS IS DAMN SLOW (at least on a Mac)
        //// THEREFORE WE USE EVENTS FROM COM.SUN PACKAGES THAT ARE WAY FASTER
        //// THIS MIGHT BREAK COMPATIBILITY WITH OTHER JDKs
        //// MORE: http://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else
        ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        WatchKey watchKey = path.register(
            watchService,
            new WatchEvent.Kind[]{
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE
            },
            SensitivityWatchEventModifier.HIGH);

        mapOfWatchKeysToPaths.put(watchKey, path);
    }

    @Override
    public void run() {

        for (;;) {

            WatchKey watchKey;
            try {
                watchKey = watchService.take();
                takeCount.incrementAndGet();
            } catch (InterruptedException e) {
                if (!shutdown) {
                    log.error("Unexpectedly interrupted while waiting for take()", e);
                }
                return;
            }

            Path path = mapOfWatchKeysToPaths.get(watchKey);
            if (path == null) {
                log.error("WatchKey not recognized!!");
                continue;
            }

            for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
                WatchEvent.Kind watchEventKind = watchEvent.kind();

                // TBD - provide example of how OVERFLOW watchEvent is handled
                if (watchEventKind == OVERFLOW) {
                    continue;
                }

                // Context for directory entry watchEvent is the file name of entry
                WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;
                Path name = ev.context();
                Path child = path.resolve(name);

                if (watchEventKind == ENTRY_MODIFY) {
                    // we are not interested in events from parent directories...
                    if (!child.toFile().isDirectory()) {
                        handleNewOrModifiedFile("Modified", child);
                    }
                }

                // if directory is created, then register it and its sub-directories recursively
                if (watchEventKind == ENTRY_CREATE) {

                    if (!child.toFile().isDirectory()) {
                        handleNewOrModifiedFile("New", child);
                    }
                    try {
                        if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                            registerAll(child);
                        }
                    } catch (IOException e) {
                        log.error("Something fishy happened. Unable to register new dir for watching", e);
                    }

                }

            }

            // reset watchKey and remove from set if directory no longer accessible
            boolean valid = watchKey.reset();
            if (!valid) {
                mapOfWatchKeysToPaths.remove(watchKey);

                // all directories are inaccessible
                if (mapOfWatchKeysToPaths.isEmpty()) {
                    break;
                }

            }

        }

    }

    public void handleNewOrModifiedFile(String newOrMod, Path path) {
        String f = path.toFile().getAbsolutePath();

        log.debug("{} file detected: {}", newOrMod, f);

        RuleMatch match = matchRule(includes, excludes, f);

        log.debug(" matched rule: type={}, pattern={}, proceed={}", match.type, match.pattern, match.proceed);

        if (match.proceed) {
            log.debug(" will trigger restart");
            restartTrigger.trigger();
        }
        else {
            log.debug(" will not trigger restart");
        }
    }

    public static enum RuleType {
        none,
        include,
        exclude
    }

    public static class RuleMatch {

        final RuleType type;
        final String pattern;
        final boolean proceed;

        public RuleMatch(RuleType type, String pattern, boolean proceed) {
            this.type = type;
            this.pattern = pattern;
            this.proceed = proceed;
        }

    }

    public static RuleMatch matchRule(Set<String> includes, Set<String> excludes, String string) {

        if (includes != null) {
            for (String regex: includes) {
                if (string.matches(regex)) {
                    return new RuleMatch(RuleType.include, regex, true);
                }
            }
        }

        if (excludes != null) {
            for (String regex: excludes) {
                if (string.matches(regex)) {
                    return new RuleMatch(RuleType.exclude, regex, false);
                }
            }
        }

        return new RuleMatch(RuleType.none, "", true);
    }

    public static boolean checkIfWouldBeExcluded(Set<String> patterns, String string) {
        // use "excludes" above to use this for testing
        return !matchRule(null, patterns, string).proceed;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns     = "http://www.w3.org/ns/widgets"
        xmlns:gap = "http://phonegap.com/ns/1.0"
        id        = "com.phonegap.ryanw.barcodedemo"
        version   = "2.0.0">
    <name>OmniCommerce</name>

    <description>
        You want it, you find it
    </description>

    <author href="http://phonegap.com" email="nevelezv@gmail.com">
        Nestor Velez
    </author>

    <gap:plugin name="org.apache.cordova.core.camera" />
    <gap:plugin name="com.phonegap.plugins.barcodescanner"/>

    <feature name="http://api.phonegap.com/1.0/device" />
    <feature name="debug-server" required="true">
       <param name="domain" value="http://debug.phonegap.com"/>
       <param name="key" value="willoughby"/>
    </feature>

    <preference name="phonegap-version" value="3.6.3" />
    <preference name="orientation"      value="default" />
    <preference name="target-device"    value="universal" />
    <preference name="fullscreen"       value="false" />
    <preference name="webviewbounce"    value="false" />

    <icon src="icon.png" />
    <icon src="res/icon/android/icon-36-ldpi.png"   gap:platform="android"    gap:density="ldpi" />
    <icon src="res/icon/android/icon-48-mdpi.png"   gap:platform="android"    gap:density="mdpi" />
    <icon src="res/icon/android/icon-72-hdpi.png"   gap:platform="android"    gap:density="hdpi" />
    <icon src="res/icon/android/icon-96-xhdpi.png"  gap:platform="android"    gap:density="xhdpi" />
    <icon src="res/icon/blackberry/icon-80.png"     gap:platform="blackberry" />
    <icon src="res/icon/blackberry/icon-80.png"     gap:platform="blackberry" gap:state="hover"/>
    <icon src="res/icon/ios/icon-57.png"            gap:platform="ios"        width="57" height="57" />
    <icon src="res/icon/ios/icon-72.png"            gap:platform="ios"        width="72" height="72" />
    <icon src="res/icon/ios/icon-57-2x.png"         gap:platform="ios"        width="114" height="114" />
    <icon src="res/icon/ios/icon-72-2x.png"         gap:platform="ios"        width="144" height="144" />
    <icon src="res/icon/ios/icon-180.png"         gap:platform="ios"        width="180" height="180" />
    <icon src="res/icon/webos/icon-64.png"          gap:platform="webos" />
    <icon src="res/icon/windows-phone/icon-48.png"  gap:platform="winphone" />
    <icon src="res/icon/windows-phone/icon-173.png" gap:platform="winphone"   gap:role="background" />

    <gap:splash src="res/screen/android/screen-ldpi-portrait.png"  gap:platform="android" gap:density="ldpi" />
    <gap:splash src="res/screen/android/screen-mdpi-portrait.png"  gap:platform="android" gap:density="mdpi" />
    <gap:splash src="res/screen/android/screen-hdpi-portrait.png"  gap:platform="android" gap:density="hdpi" />
    <gap:splash src="res/screen/android/screen-xhdpi-portrait.png" gap:platform="android" gap:density="xhdpi" />
    <gap:splash src="res/screen/blackberry/screen-225.png"         gap:platform="blackberry" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait.png"    gap:platform="ios"     width="320" height="480" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait-2x.png" gap:platform="ios"     width="640" height="960" />
    <gap:splash src="res/screen/ios/screen-ipad-portrait.png"      gap:platform="ios"     width="768" height="1024" />
    <gap:splash src="res/screen/ios/screen-ipad-landscape.png"     gap:platform="ios"     width="1024" height="768" />

    <gap:splash src="res/screen/ios/Splash-750x1334.png"     gap:platform="ios"     width="750" height="1334" />
    <gap:splash src="res/screen/ios/Splash-2208x1242.png"     gap:platform="ios"     width="1242" height="2208" />
    <gap:splash src="res/screen/ios/Splash-1242x2208.png"     gap:platform="ios"     width="2208" height="1242" />

    <gap:splash src="res/screen/windows-phone/screen-portrait.jpg" gap:platform="winphone" />

    <!-- content src="http://www.w3.org/2010/05/video/mediaevents.html" / -->
</widget>


text:
.paginator-block {
    margin-top: 20px;
    padding: 5px;
    background-color: #e4e4e4;
    font-size: 12px;
}

select {
    background: none repeat scroll 0 0 #FAFAFA;
    border: 1px solid #AAAAAA;
    border-radius: 3px 3px 3px 3px;
    color: black;
    font-size: 13px !important;
    font-weight: bold;
    padding: 3px;
    height: 28px;
    max-width: 250px;
    padding: 3px;
}

input[type=button] {
    height: 30px;
    padding-left: 10px;
    padding-right: 10px;
    cursor: pointer;
}

.selected-colors {
    margin-bottom: 20px;
}
.selected-colors h3 {
    font-weight: bold;
    padding-bottom: 4px;
}

.selected-colors .tag-color-item {
    overflow: hidden;
    padding-left: 10px;
}
.selected-colors .tag-color-item .tag-name,
.selected-colors .tag-color-item .tag-color,
.selected-colors .tag-color-item .tag-rm {
    float: left;
}

.selected-colors .tag-color-item .tag-name {
    width: 200px;
}

.selected-colors .tag-color-item .tag-color {
    width: 30px;
    height: 12px;
}

.selected-colors .tag-color-item .tag-rm {
    line-height: 12px;
    vertical-align: middle;
    padding-left: 15px;
    padding-right: 5px;
    font-size:14px;
    font-weight: bold;
    cursor: pointer;
}

.question-module {
    padding: 10px;
    margin-bottom: 10px;
    background-color: white;
    margin-bottom: 10px;
    border-bottom: 1px solid #eeeeee;
}

.question-module .question-header {
    font-size: 18px;
}
.question-module .question-header .title {
    font-size: 18px;
    font-weight: bold;
}

.questions-list .question-module .question-header .title {
    font-size: 14px;
}
.questions-list fieldset {
    padding: 10px;
    border: 1px solid #e4e4e4;
}

.questions-list .question-module {
    margin-bottom: 4px;
}
.question-module .question-header .small-header-row {
    font-size: 12px;
    padding: 4px;
    font-style: italic;
}

.question-module .question-body .content {
    margin-top: 10px;
    padding: 5px;
}

.question-responses-form {
    margin-top: 20px;
}

textarea#id_description,
textarea#id_content { width: 99%; height: 190px; }
.question-responses { overflow: hidden; }
.question-responses .question-response-item {
    float:right;
    width: 95%;
    margin-bottom: 5px;
    padding: 10px;
    background-color: #FCFCFC;
    border: 1px solid #EEE;
    border-radius: 5px;
}
.question-responses .question-response-item .created-date,
.question-responses .question-response-item .owner {
    padding-top: 5px;
    font-size: 12px;
    text-align: right;
}

div.highlight {
    padding: 10px;
    background-color: white;
    font-size: 12px;
    font-family: monospace;
    margin-top: 10px;
    margin-bottom: 10px;
}
div.highlight pre {
    font-family: Monaco, 'MonacoRegular', 'Courier New', monospace;
    white-space: pre-wrap;
}

/* Delete module */

.delete-module {
    padding: 10px;
    background-color: #eee;
    margin-bottom: 10px;
}
.delete-module .delete-header {
    font-size: 18px;
}
.delete-module .delete-header .title {
    font-size: 18px;
    font-weight: bold;
    display: block;
    padding-left:10px;
}
.delete-module .delete-header .small-header-row {
    font-size: 12px;
    padding: 4px;
    font-style: italic;
}

/* User list */

.user-module {
    padding: 3px;
    background-color: #EEE;
    margin-bottom: 10px;
    padding-left: 10px;
}

.user-module .user-header {
    font-size: 18px;
}
.user-module .user-header .title {
    font-size: 18px;
    font-weight: bold;
}

.users-list .user-module .user-header .title {
    font-size: 12px;
    line-height: 22px;
}
.users-list fieldset {
    padding: 10px;
    border: 1px solid #e4e4e4;
}

.users-list .user-module {
    margin-bottom: 4px;
}
.user-module .user-header {
    overflow: hidden;
}
.user-module .user-header .small-header-row {
    font-size: 12px;
    padding: 4px;
    font-style: italic;
    float: right;
}
.user-module .user-header .main-header-row {
    float:left;
}

.user-module .user-body .content {
    margin-top: 10px;
    padding: 5px;
}
.user-module .user-body .user-body-module {
    margin-top: 0px;
}

.wiki-page-edit #id_content {
    width: 945px;
    width:99%;
    height: 500px;
    font-size: 12px;
}

h1,
h2,
h3 {
    color: black;
    font-weight: bold;
    margin-bottom: 12px !important;
}

h1 { font-size: 22px; }
h2 { font-size: 18px; }
h3 { font-size: 16px; }

.changes-list .change-item .change-title {
    font-size: 12px;
    color: #aaa;
    border-bottom: 1px solid #aaa;
}
.changes-list .change-item .change-content {
    padding: 3px;
}

.changes-list .change-item .change-content .comment {
    padding: 5px;
    padding-left: 10px;
}
.changes-list .change-item .change-content .comment-attachments {
    padding-left: 10px;
}


text:
package org.apache.hadoop.mapreduce.lib.output.committer.manifest.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathIOException;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.mapreduce.lib.output.committer.manifest.files.AbstractManifestData;
import org.apache.hadoop.mapreduce.lib.output.committer.manifest.files.FileEntry;
import org.apache.hadoop.mapreduce.lib.output.committer.manifest.files.TaskManifest;
import org.apache.hadoop.util.JsonSerialization;

import static java.util.Objects.requireNonNull;
import static org.apache.hadoop.mapreduce.lib.output.committer.manifest.impl.InternalConstants.OPERATION_TIMED_OUT;

/**
 * Wrap an existing {@link ManifestStoreOperations} implementation and fail on
 * specific paths.
 * This is for testing. It could be implemented via
 * Mockito 2 spy code but is not so that:
 * 1. It can be backported to Hadoop versions using Mockito 1.x.
 * 2. It can be extended to use in production. This is why it is in
 * the production module -to allow for downstream tests to adopt it.
 * 3. You can actually debug what's going on.
 */
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class UnreliableManifestStoreOperations extends ManifestStoreOperations {

  private static final Logger LOG = LoggerFactory.getLogger(
      UnreliableManifestStoreOperations.class);

  /**
   * The timeout message ABFS raises.
   */
  public static final String E_TIMEOUT
      = "Operation could not be completed within the specified time";

  /**
   * Text to use in simulated failure exceptions.
   */
  public static final String SIMULATED_FAILURE = "Simulated failure";

  /**
   * Underlying store operations to wrap.
   */
  private final ManifestStoreOperations wrappedOperations;

  /**
   * Paths of delete operations to fail.
   */
  private final Set<Path> deletePathsToFail = new HashSet<>();

  /**
   * Paths of delete operations to time out, as ABFS may.
   */
  private final Set<Path> deletePathsToTimeOut = new HashSet<>();

  /**
   * Paths of List operations to fail.
   */
  private final Set<Path> listToFail = new HashSet<>();

  /**
   * Paths of mkdirs operations to fail.
   */
  private final Set<Path> mkdirsToFail = new HashSet<>();

  /**
   * Paths which don't exist.
   */
  private final Set<Path> pathNotFound = new HashSet<>();

  /**
   * Source file whose rename/commit will fail.
   */
  private final Set<Path> renameSourceFilesToFail = new HashSet<>();

  /**
   * Dest dir into which all renames/commits will fail.
   * Subdirectories under this are not checked.
   */
  private final Set<Path> renameDestDirsToFail = new HashSet<>();

  /**
   * Path of save() to fail.
   */
  private final Set<Path> saveToFail = new HashSet<>();

  /**
   * timeout sleep.
   */
  private int timeoutSleepTimeMillis;

  /**
   * Should rename thrown an exception or just return false.
   */
  private boolean renameToFailWithException = true;

  /**
   * Constructor.
   * @param wrappedOperations operations to wrap.
   */
  public UnreliableManifestStoreOperations(final ManifestStoreOperations wrappedOperations) {
    this.wrappedOperations = wrappedOperations;
  }

  /**
   * Reset everything.
   */
  public void reset() {
    deletePathsToFail.clear();
    deletePathsToTimeOut.clear();
    pathNotFound.clear();
    renameSourceFilesToFail.clear();
    renameDestDirsToFail.clear();
    timeoutSleepTimeMillis = 0;
  }

  public int getTimeoutSleepTimeMillis() {
    return timeoutSleepTimeMillis;
  }

  public void setTimeoutSleepTimeMillis(final int timeoutSleepTimeMillis) {
    this.timeoutSleepTimeMillis = timeoutSleepTimeMillis;
  }

  public boolean getRenameToFailWithException() {
    return renameToFailWithException;
  }

  public void setRenameToFailWithException(
      final boolean renameToFailWithException) {
    this.renameToFailWithException = renameToFailWithException;
  }

  /**
   * Add a path to the list of delete paths to fail.
   * @param path path to add.
   */
  public void addDeletePathToFail(Path path) {
    deletePathsToFail.add(requireNonNull(path));
  }

  /**
   * Add a path to the list of delete paths to time out.
   * @param path path to add.
   */
  public void addDeletePathToTimeOut(Path path) {
    deletePathsToTimeOut.add(requireNonNull(path));
  }

  /**
   * Add a path to the list of paths where list will fail.
   * @param path path to add.
   */
  public void addListToFail(Path path) {
    listToFail.add(requireNonNull(path));
  }

  /**
   * Add a path to the list of mkdir calls to fail.
   * @param path path to add.
   */
  public void addMkdirsToFail(Path path) {
    mkdirsToFail.add(requireNonNull(path));
  }

  /**
   * Add a path not found.
   * @param path path
   */
  public void addPathNotFound(Path path) {
    pathNotFound.add(requireNonNull(path));
  }

  /**
   * Add a path to the list of rename source paths to fail.
   * @param path path to add.
   */
  public void addRenameSourceFilesToFail(Path path) {
    renameSourceFilesToFail.add(requireNonNull(path));
  }

  /**
   * Add a path to the list of dest dirs to fail.
   * @param path path to add.
   */
  public void addRenameDestDirsFail(Path path) {
    renameDestDirsToFail.add(requireNonNull(path));
  }

  /**
   * Add a path to the list of paths where save will fail.
   * @param path path to add.
   */
  public void addSaveToFail(Path path) {
    saveToFail.add(requireNonNull(path));
  }

  /**
   * Raise an exception if the path is in the set of target paths.
   * @param operation operation which failed.
   * @param path path to check
   * @param paths paths to probe for {@code path} being in.
   * @throws IOException simulated failure
   */
  private void maybeRaiseIOE(String operation, Path path, Set<Path> paths)
      throws IOException {
    if (paths.contains(path)) {
      LOG.info("Simulating failure of {} with {}", operation, path);
      throw new PathIOException(path.toString(),
          SIMULATED_FAILURE + " of " + operation);
    }
  }

  /**
   * Verify that a path is not on the file not found list.
   * @param path path
   * @throws FileNotFoundException if configured to fail.
   */
  private void verifyExists(Path path) throws FileNotFoundException {
    if (pathNotFound.contains(path)) {
      throw new FileNotFoundException(path.toString());
    }
  }

  /**
   * Time out if the path is in the list of timeout paths.
   * Will sleep first, to help simulate delays.
   * @param operation operation which failed.
   * @param path path to check
   * @param paths paths to probe for {@code path} being in.
   * @throws IOException simulated timeout
   */
  private void maybeTimeout(String operation, Path path, Set<Path> paths)
      throws IOException {
    if (paths.contains(path)) {
      LOG.info("Simulating timeout of {} with {}", operation, path);
      try {
        if (timeoutSleepTimeMillis > 0) {
          Thread.sleep(timeoutSleepTimeMillis);
        }
      } catch (InterruptedException e) {
        throw new InterruptedIOException(e.toString());
      }
      throw new PathIOException(path.toString(),
          "ErrorCode=" + OPERATION_TIMED_OUT
              + " ErrorMessage=" + E_TIMEOUT);
    }
  }

  @Override
  public FileStatus getFileStatus(final Path path) throws IOException {
    verifyExists(path);
    return wrappedOperations.getFileStatus(path);
  }

  @Override
  public boolean delete(final Path path, final boolean recursive)
      throws IOException {
    String op = "delete";
    maybeTimeout(op, path, deletePathsToTimeOut);
    maybeRaiseIOE(op, path, deletePathsToFail);
    return wrappedOperations.delete(path, recursive);
  }

  @Override
  public boolean mkdirs(final Path path) throws IOException {
    maybeRaiseIOE("mkdirs", path, mkdirsToFail);
    return wrappedOperations.mkdirs(path);
  }

  @Override
  public boolean renameFile(final Path source, final Path dest)
      throws IOException {
    String op = "rename";
    if (renameToFailWithException) {
      maybeRaiseIOE(op, source, renameSourceFilesToFail);
      maybeRaiseIOE(op, dest.getParent(), renameDestDirsToFail);
    } else {
      if (renameSourceFilesToFail.contains(source)
          || renameDestDirsToFail.contains(dest.getParent())) {
        LOG.info("Failing rename({}, {})", source, dest);
        return false;
      }
    }
    return wrappedOperations.renameFile(source, dest);
  }

  @Override
  public RemoteIterator<FileStatus> listStatusIterator(final Path path)
      throws IOException {
    verifyExists(path);
    maybeRaiseIOE("listStatus", path, listToFail);
    return wrappedOperations.listStatusIterator(path);
  }

  @Override
  public TaskManifest loadTaskManifest(JsonSerialization<TaskManifest> serializer,
      final FileStatus st) throws IOException {
    verifyExists(st.getPath());
    return wrappedOperations.loadTaskManifest(serializer, st);
  }

  @Override
  public <T extends AbstractManifestData<T>> void save(T manifestData,
      final Path path,
      final boolean overwrite) throws IOException {
    maybeRaiseIOE("save", path, saveToFail);
    wrappedOperations.save(manifestData, path, overwrite);
  }

  @Override
  public void msync(Path path) throws IOException {
    wrappedOperations.msync(path);
  }

  @Override
  public String getEtag(FileStatus status) {
    return wrappedOperations.getEtag(status);
  }

  @Override
  public boolean storeSupportsResilientCommit() {
    return wrappedOperations.storeSupportsResilientCommit();
  }

  @Override
  public CommitFileResult commitFile(final FileEntry entry)
      throws IOException {
    if (renameToFailWithException) {
      maybeRaiseIOE("commitFile",
          entry.getSourcePath(), renameSourceFilesToFail);
      maybeRaiseIOE("commitFile",
          entry.getDestPath().getParent(), renameDestDirsToFail);
    }
    return wrappedOperations.commitFile(entry);
  }

  @Override
  public boolean storePreservesEtagsThroughRenames(Path path) {
    return wrappedOperations.storePreservesEtagsThroughRenames(path);
  }

  @Override
  public void close() throws IOException {
    wrappedOperations.close();
  }

}


text:
package utilities;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public abstract class Function<D, R> {
	public abstract R apply(D d);

	public List<R> map(Collection<D> ds) {
		List<R> output = new ArrayList<R>(ds.size());
		for (D d : ds) {
			output.add(this.apply(d));
		}
		return output;
	}

	public List<R> map(D[] ds) {
		List<R> output = new ArrayList<R>(ds.length);
		for (D d : ds) {
			output.add(this.apply(d));
		}
		return output;
	}

	public List<R> mapNotNull(Collection<D> ds) {
		List<R> output = new ArrayList<R>(ds.size());
		for (D d : ds) {
			R r = this.apply(d);
			if (r != null) {
				output.add(r);
			}
		}
		return output;
	}

	public List<R> mapNotNull(D[] ds) {
		List<R> output = new ArrayList<R>(ds.length);
		for (D d : ds) {
			R r = this.apply(d);
			if (r != null) {
				output.add(r);
			}
		}
		return output;
	}

	public Function<D, D> identity() {
		return new Function<D, D>() {
			@Override
			public D apply(D d) {
				return d;
			}
		};
	}

	public static Function<Void, Void> nullFunction() {
		return new Function<Void, Void>() {
			@Override
			public Void apply(Void r) {
				return null;
			}
		};
	}

	public static <E> Function<E, Boolean> trueFunction() {
		return new Function<E, Boolean>() {
			@Override
			public Boolean apply(E e) {
				return true;
			}
		};
	}

	public static <E> Function<E, Boolean> falseFunction() {
		return new Function<E, Boolean>() {
			@Override
			public Boolean apply(E e) {
				return false;
			}
		};
	}
}


text:
import { WaitForResult, waitForArr } from "../helpers";
import { expect } from "chai";
import isMatch from "lodash.ismatch";

export class InteropMock {
    private methodExpectations: Array<WaitForResult<any>> = [];
    private methodsRepo: Array<{ name: string }> = [];

    public addMethod(name: string) {
        this.methodsRepo.push({ name });
    }

    public invoke(method: any, argumentObj?: object): Promise<any> {
        argumentObj = argumentObj ?? {};
        const methodName = method.name || method;
        const expectation = this.methodExpectations.find((wf) => wf.tag.method === methodName);
        if (expectation) {
            const next = expectation.next();
            if (expectation.tag.check === "strict") {
                expect(next).to.eql(argumentObj);
            } else {
                const matching = isMatch(argumentObj, next);
                expect(matching).to.eql(true);
            }
            expectation.fn(next);
        }
        return Promise.resolve();
    }

    public methods(filter?: any) {
        return this.methods;
    }

    public expectMethodToBeInvokedWith(method: string, args: any[], check: "strict" | "subset" = "strict") {
        this.addMethod(method);
        const wf = waitForArr(args, true, { method, check });
        this.methodExpectations.push(wf);
        return wf.promise;
    }
}