text:
package bddtests

import (
	"fmt"
	"strconv"
	"time"

	"strings"

	"github.com/DATA-DOG/godog"
	"github.com/DATA-DOG/godog/gherkin"
	"github.com/hyperledger/fabric/core/util"
	pb "github.com/hyperledger/fabric/protos"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

func (b *BDDContext) weCompose(composeFiles string) error {
	if b.composition != nil {
		return fmt.Errorf("Already have composition in BDD context (%s)", b.composition.projectName)
	}
	// Need a unique name, but docker does not allow '-' in names
	composeProjectName := strings.Replace(util.GenerateUUID(), "-", "", -1)
	newComposition, err := NewComposition(composeProjectName, composeFiles)
	if err != nil {
		return fmt.Errorf("Error composing system in BDD context:  %s", err)
	}
	b.composition = newComposition
	return nil
}

func (b *BDDContext) requestingFrom(arg1, arg2 string) error {
	return godog.ErrPending
}

func (b *BDDContext) iShouldGetAJSONResponseWithArrayContainsElements(arg1, arg2 string) error {
	return godog.ErrPending
}

func (b *BDDContext) iWaitSeconds(seconds string) error {
	waitInSecs, err := strconv.Atoi(seconds)
	if err != nil {
		return err
	}
	time.Sleep(time.Duration(waitInSecs) * time.Second)
	return nil
}

func (b *BDDContext) iRegisterWithCASupplyingUsernameAndSecretOnPeers(enrollID, secret string, tableOfPeers *gherkin.DataTable) error {
	return b.registerUser(enrollID, secret)
}

func (b *BDDContext) userCreatesAChaincodeSpecOfTypeForChaincodeWithArgs(enrollID, ccSpecAlias, ccType, chaincodePath string, argsTable *gherkin.DataTable) error {
	userRegistration, err := b.GetUserRegistration(enrollID)
	if err != nil {
		return err
	}

	args, err := b.GetArgsForUser(argsTable.Rows[1].Cells, userRegistration)
	//fmt.Printf("Args for user: %v, with err = %s", args, err)
	ccSpec := createChaincodeSpec(ccType, chaincodePath, util.ToChaincodeArgs(args...))
	userRegistration.lastResult = ccSpec
	userRegistration.tags[ccSpecAlias] = userRegistration.lastResult

	return nil
}

func (b *BDDContext) userCreatesADeploymentProposalUsingChaincodeDeploymentSpec(enrollID, proposalAlias, ccDeploymentSpecAlias string) (err error) {
	var userRegistration *UserRegistration
	var ccDeploymentSpec *pb.ChaincodeDeploymentSpec
	errRetFunc := func() error {
		return fmt.Errorf("Error creating chaincode proposal for user '%s' from chaincodeDeploymentSpec '%s':  %s", enrollID, ccDeploymentSpecAlias, err)
	}
	if userRegistration, err = b.GetUserRegistration(enrollID); err != nil {
		return errRetFunc()
	}
	if ccDeploymentSpec, err = userRegistration.GetChaincodeDeploymentSpec(ccDeploymentSpecAlias); err != nil {
		return errRetFunc()
	}
	var proposal *pb.Proposal
	if proposal, err = createProposalForChaincode(ccDeploymentSpec); err != nil {

	}
	if _, err = userRegistration.SetTagValue(proposalAlias, proposal); err != nil {
		return errRetFunc()
	}
	return nil
}

func (b *BDDContext) userCreatesADeploymentSpecUsingChaincodeSpecAndDevopsOnPeer(enrollID, ccDeploymentSpecAlias, ccSpecAlias, devopsPeerComposeService string) (err error) {
	var ccSpec *pb.ChaincodeSpec
	var userRegistration *UserRegistration
	errRetFunc := func() error {
		return fmt.Errorf("Error creating deployment spec '%s' for user '%s' from chaincode spec '%s':  %s", ccDeploymentSpecAlias, enrollID, ccSpecAlias, err)
	}
	if userRegistration, err = b.GetUserRegistration(enrollID); err != nil {
		return errRetFunc()
	}
	if ccSpec, err = userRegistration.GetChaincodeSpec(ccSpecAlias); err != nil {
		return errRetFunc()
	}

	// Now use the devops client to create the deployment spec
	var grpcClient *grpc.ClientConn
	if grpcClient, err = b.getGrpcClientForComposeService(devopsPeerComposeService); err != nil {
		return errRetFunc()
	}
	defer grpcClient.Close()
	devopsClient := pb.NewDevopsClient(grpcClient)
	var ccDeploymentSpec *pb.ChaincodeDeploymentSpec
	if ccDeploymentSpec, err = devopsClient.Build(context.Background(), ccSpec); err != nil {
		return errRetFunc()
	}
	// Now store the chaincode deployment spec
	if _, err = userRegistration.SetTagValue(ccDeploymentSpecAlias, ccDeploymentSpec); err != nil {
		return errRetFunc()
	}
	return err
}

func getContextAndCancelForTimeoutInSecs(parentCtx context.Context, timeoutInSecs string) (context.Context, context.CancelFunc, error) {
	var err error
	errRetFunc := func() error {
		return fmt.Errorf("Error building context and cancel func with timout '%s':  %s", timeoutInSecs, err)
	}
	var (
		durationToWait time.Duration
		ctx            context.Context
		cancel         context.CancelFunc
	)
	if durationToWait, err = time.ParseDuration(fmt.Sprintf("%ss", timeoutInSecs)); err != nil {
		return nil, nil, errRetFunc()
	}
	ctx, cancel = context.WithTimeout(parentCtx, durationToWait)
	return ctx, cancel, nil
}

func (b *BDDContext) invokeOnWithTimeout(composeServices []string, timeoutInSecs string, callBack func(context.Context, pb.EndorserClient) (proposalResponse *pb.ProposalResponse, err error)) (map[string]*pb.ProposalResponse, error) {
	var err error
	resultsMap := make(map[string]*pb.ProposalResponse)
	errRetFunc := func() error {
		return fmt.Errorf("Error when invoking endorser(s) on '%s':  %s", composeServices, err)
	}
	var (
		durationToWait time.Duration
		ctx            context.Context
		cancel         context.CancelFunc
	)
	if durationToWait, err = time.ParseDuration(fmt.Sprintf("%ss", timeoutInSecs)); err != nil {
		return nil, errRetFunc()
	}
	ctx, cancel = context.WithTimeout(context.Background(), durationToWait)
	defer cancel()
	cancel()
	for _, cs := range composeServices {
		go func(composeService string) {
			var proposalResponse *pb.ProposalResponse
			// Now use the endorser client to create the send the proposal
			println("Calling endorser for compose service:", composeService)
			var grpcClient *grpc.ClientConn
			if grpcClient, err = NewGrpcClient("172.17.0.4:7051"); err != nil {
				return
			}
			defer grpcClient.Close()
			endorserClient := pb.NewEndorserClient(grpcClient)
			if proposalResponse, err = callBack(ctx, endorserClient); err != nil {
				return
			}
			resultsMap[composeService] = proposalResponse
		}(cs)
	}
	return resultsMap, err
}

func (b *BDDContext) getGrpcClientForComposeService(composeService string) (grpcClient *grpc.ClientConn, err error) {
	var ipAddress string
	errRetFunc := func() error {
		return fmt.Errorf("Error getting grpc client conn for compose service '%s':  %s", composeService, err)
	}
	if ipAddress, err = b.composition.GetIPAddressForComposeService(composeService); err != nil {
		return nil, errRetFunc()
	}
	if grpcClient, err = NewGrpcClient(fmt.Sprintf("%s:%d", ipAddress, b.grpcClientPort)); err != nil {
		return nil, errRetFunc()
	}
	return grpcClient, err
}

func (b *BDDContext) userSendsProposalToEndorsersWithTimeoutOfSeconds(enrollID, proposalAlias, timeoutInSecs string, endorsersTable *gherkin.DataTable) (err error) {
	var proposal *pb.Proposal
	var keyedProposalResponsesMap KeyedProposalResponseMap
	keyedProposalResponsesMap = make(KeyedProposalResponseMap)
	errRetFunc := func() error {
		return fmt.Errorf("Error sending proposal '%s' for user '%s':  %s", proposalAlias, enrollID, err)
	}
	var userRegistration *UserRegistration
	if userRegistration, err = b.GetUserRegistration(enrollID); err != nil {
		return errRetFunc()
	}
	// Get the proposal from the user
	if proposal, err = userRegistration.GetProposal(proposalAlias); err != nil {
		return errRetFunc()
	}

	var ctx context.Context
	var cancel context.CancelFunc
	if ctx, cancel, err = getContextAndCancelForTimeoutInSecs(context.Background(), timeoutInSecs); err != nil {
		return errRetFunc()
	}
	defer cancel()
	// Loop through endorsers and send proposals
	var endorsers []string
	if endorsers, err = b.GetArgsForUser(endorsersTable.Rows[0].Cells, userRegistration); err != nil {
		return errRetFunc()
	}
	respQueue := make(chan *KeyedProposalResponse)
	for _, e := range endorsers {
		go func(endorser string) {
			var localErr error
			var proposalResponse *pb.ProposalResponse
			// Now use the endorser client to send the proposal
			var grpcClient *grpc.ClientConn
			if grpcClient, localErr = b.getGrpcClientForComposeService(endorser); localErr != nil {
				respQueue <- &KeyedProposalResponse{endorser, nil, fmt.Errorf("Error calling endorser '%s': %s", endorser, localErr)}
				return
			}
			defer grpcClient.Close()

			endorserClient := pb.NewEndorserClient(grpcClient)
			if proposalResponse, localErr = endorserClient.ProcessProposal(ctx, proposal); localErr != nil {
				respQueue <- &KeyedProposalResponse{endorser, nil, fmt.Errorf("Error calling endorser '%s':  %s", endorser, localErr)}
				return
			}
			respQueue <- &KeyedProposalResponse{endorser, proposalResponse, nil}
		}(e)
	}
	go func() {
		for i := 0; i < len(endorsers); i++ {
			result := <-respQueue
			keyedProposalResponsesMap[result.endorser] = result
			if result.err != nil {
				// TODO: think about whether to break on first failure, or allow to collect
			}
		}
		cancel()
	}()
	<-ctx.Done()
	if ctx.Err() != context.Canceled {
		err = ctx.Err()
		return errRetFunc()
	}
	userRegistration.lastResult = keyedProposalResponsesMap
	return nil
}

func (b *BDDContext) userStoresTheirLastResultAs(enrollID, tagName string) error {
	userRegistration, err := b.GetUserRegistration(enrollID)
	if err != nil {
		return err
	}
	userRegistration.tags[tagName] = userRegistration.lastResult
	return nil
}

func (b *BDDContext) userExpectsProposalResponsesWithStatusFromEndorsers(enrollID, proposalResponseAlias, respStatusCode string, endorsersTable *gherkin.DataTable) (err error) {
	var userRegistration *UserRegistration
	var keyedProposalResponseMap KeyedProposalResponseMap
	errRetFunc := func() error {
		return fmt.Errorf("Error verifying proposal reponse '%s' for user '%s' with expected response code of '%s':  %s", proposalResponseAlias, enrollID, respStatusCode, err)
	}
	if userRegistration, err = b.GetUserRegistration(enrollID); err != nil {
		return errRetFunc()
	}
	if keyedProposalResponseMap, err = userRegistration.GetKeyedProposalResponseDict(proposalResponseAlias); err != nil {
		return errRetFunc()
	}
	for endorserComposeService, keyedProposalResponse := range keyedProposalResponseMap {
		// If their is an err in getting the proposal response, fail
		if keyedProposalResponse.err != nil {
			err = fmt.Errorf("Received error in keyedProposalResponse for endorser '%s':  %s", endorserComposeService, keyedProposalResponse.err)
			return errRetFunc()
		}
		if keyedProposalResponse.proposal == nil {
			err = fmt.Errorf("keyedProposalResponse.proposal value was nil for endorser '%s':  %s", endorserComposeService, keyedProposalResponse.err)
			return errRetFunc()
		}
		if fmt.Sprintf("%d", keyedProposalResponse.proposal.Response.Status) != respStatusCode {
			err = fmt.Errorf("Expected ProposalResponse.Response.Status to be '%s', received '%d'", respStatusCode, keyedProposalResponse.proposal.Response.Status)
			return errRetFunc()
		}
	}
	return nil
}

func (b *BDDContext) userSetsESCCToForChaincodeSpec(arg1, arg2, arg3 string) error {
	return godog.ErrPending
}

func (b *BDDContext) userSetsVSCCToForChaincodeSpec(arg1, arg2, arg3 string) error {
	return godog.ErrPending
}

func (b *BDDContext) beforeScenario(scenarioOrScenarioOutline interface{}) {
	b.scenarioOrScenarioOutline = scenarioOrScenarioOutline
	//switch t := scenarioOrScenarioOutline.(type) {
	//case *gherkin.Scenario:
	//	fmt.Printf("Scenario recieved %v", t)
	//case *gherkin.ScenarioOutline:
	//	fmt.Printf("ScenarioOutline recieved %v", t)
	//}
}

func (b *BDDContext) afterScenarioDecompose(interface{}, error) {
	if b.hasTag("@doNotDecompose") == true {
		fmt.Printf("Not decomposing:  %s", b.getScenarioDefinition().Name)
	} else {
		b.composition.Decompose()
	}
	// Now clear the users
	b.composition = nil
	b.users = make(map[string]*UserRegistration)
}

func FeatureContext(s *godog.Suite) {
	bddCtx := &BDDContext{godogSuite: s, users: make(map[string]*UserRegistration), grpcClientPort: 7051}

	s.BeforeScenario(bddCtx.beforeScenario)
	s.AfterScenario(bddCtx.afterScenarioDecompose)
	s.Step(`^we compose "([^"]*)"$`, bddCtx.weCompose)
	s.Step(`^requesting "([^"]*)" from "([^"]*)"$`, bddCtx.requestingFrom)
	s.Step(`^I should get a JSON response with array "([^"]*)" contains "([^"]*)" elements$`, bddCtx.iShouldGetAJSONResponseWithArrayContainsElements)
	s.Step(`^I wait "([^"]*)" seconds$`, bddCtx.iWaitSeconds)
	s.Step(`^I register with CA supplying username "([^"]*)" and secret "([^"]*)" on peers:$`, bddCtx.iRegisterWithCASupplyingUsernameAndSecretOnPeers)
	s.Step(`^user "([^"]*)" creates a chaincode spec "([^"]*)" of type "([^"]*)" for chaincode "([^"]*)" with args$`, bddCtx.userCreatesAChaincodeSpecOfTypeForChaincodeWithArgs)

	s.Step(`^user "([^"]*)" creates a deployment spec "([^"]*)" using chaincode spec "([^"]*)" and devops on peer "([^"]*)"$`, bddCtx.userCreatesADeploymentSpecUsingChaincodeSpecAndDevopsOnPeer)
	//s.Step(`^user "([^"]*)" creates a deployment spec "([^"]*)" using chaincode spec "([^"]*)"$`, bddCtx.userCreatesADeploymentSpecUsingChaincodeSpec)

	s.Step(`^user "([^"]*)" creates a deployment proposal "([^"]*)" using chaincode deployment spec "([^"]*)"$`, bddCtx.userCreatesADeploymentProposalUsingChaincodeDeploymentSpec)
	s.Step(`^user "([^"]*)" sends proposal "([^"]*)" to endorsers with timeout of "([^"]*)" seconds:$`, bddCtx.userSendsProposalToEndorsersWithTimeoutOfSeconds)
	s.Step(`^user "([^"]*)" stores their last result as "([^"]*)"$`, bddCtx.userStoresTheirLastResultAs)
	s.Step(`^user "([^"]*)" expects proposal responses "([^"]*)" with status "([^"]*)" from endorsers:$`, bddCtx.userExpectsProposalResponsesWithStatusFromEndorsers)
	s.Step(`^user "([^"]*)" sets ESCC to "([^"]*)" for chaincode spec "([^"]*)"$`, bddCtx.userSetsESCCToForChaincodeSpec)
	s.Step(`^user "([^"]*)" sets VSCC to "([^"]*)" for chaincode spec "([^"]*)"$`, bddCtx.userSetsVSCCToForChaincodeSpec)
}


text:
package com.xeiam.xchange.examples.bitcoinaverage;

import java.io.IOException;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.ExchangeFactory;
import com.xeiam.xchange.bitcoinaverage.BitcoinAverageExchange;

public class BitcoinAverageMetaDataDemo {

  public static void main(String[] args) throws IOException {

    Exchange anx = ExchangeFactory.INSTANCE.createExchange(BitcoinAverageExchange.class.getName());

    System.out.println(anx.getMetaData().toString());

  }

}

redpajama_set_name: RedPajamaGithub


text:
EasyHtmlElement

An easy way to create simple or complex HTML elements in PHP.

---

##Getting started

The purpose of **EasyHtmlElement** is to centralise the HTML elements definition in a _map_ (a simple PHP array) to make you able to use or reuse it easily and where you want in your HTML code.

You can define dependencies between your elements, any attribute you want, any type of element, use parameters to make your elements dynamics. So let us to show you all possibilities!

####Map structure
The map is the PHP array where you will define all your HTML elements.

``` php
$map = array(
    'elementName' => array(/* element definition */),
    'anotherElementName' => array(/* element definition */),

    //Any elements you want...
);
```

You will use the _elementName_ key to generate the HTML code later so it must be **unique** in the map.

####Element definition
The default element representation it's the next:

``` php
$map = array(
    'elementName' => array(
        'class' => NatePage\EasyHtmlElement\Element::class,
        'type' => null,
        'text' => null,
        'attr' => array(),
        'parent' => null,
        'children' => array(),
        'extends' => array()
    )
);
```

* **(string) class:** EasyHtmlElement use the map to generate PHP objects, by default generated objects use the _NatePage\EasyHtmlElement\Element::class_. If you want to use your own class to customize elements logic, read [customization](customization.md).

* **(string | null) type:** The type of the generated HTML tag. By example, `<div></div>` is a HTML tag with a `div` type. By default it's null so the generated value will be a simple string, define you own type with `'type' => 'div'`.

* **(string | null) text:** The element content. You can put whatever you want as string value, by default HTML escaping strategy is applied on it to secure the generated code. More informations from [escaping](escaping.md).

* **(array) attr:** The element attributes. It works like `array('attrName' => 'value')`. You can define any attributes you want. By default HTML attributes escaping strategy is applied on it to secure the generated code. More informations from [attributes](attributes.md) or [escaping](escaping.md).

* **(string | array | null) parent:** The element parent which will frame the current element. By example a `span` element with a `div` parent will generate `<div><span></span></div>`. It could be the name of another defined element in the map. It could be an array which defines a dynamic element. By default is null, you can keep it if you don't want to define a parent for the current element. More informations from [parent](parent.md).

* **(array) children:** The element children. It defines all the elements which will be framed by the current element. It could contains the names of another defined elements in the map or array to define children dynamically. More informations from [children](children.md).

* **(array) extends:** It defines all the elements which the current element extends. When an element extends another one, all options above not defined are overridden by the extended elements. Attributes _class_ and _style_ are defined as mergeable so their values or not overridden but merged, so the current element will have its own values + extended elements values. More informations from [extends](extends.md).

####Usage
Everybody has a nice HTML elements map? Nice, now how to generate the HTML code?

``` php
$map = array(/* You wonderful map */);

$htmlElement = new NatePage\EasyHtmlElement\HtmlElement($map);

$myElement = $htmlElement->load('myElement');

echo $myElement->render();
```

Or maybe you want something simplier? EasyHtmlElement uses the magic methods `__call()` and `__toString()` to allow you to do something like:

``` php
$map = array(/* You wonderful map */);

$htmlElement = new NatePage\EasyHtmlElement\HtmlElement($map);

$myElement = $htmlElement->myElement();

echo $myElement;
```

That's it! Cool, isn't it?


text:
#include "orderings.h"
#include "plans.h"
#include "heuristics.h"
#include "domains.h"
#include "expressions.h"
#include "debug.h"
#include <limits>
#include <climits>

/* ====================================================================== */
/* StepTime */

const StepTime StepTime::AT_START(StepTime::START, StepTime::AT);
const StepTime StepTime::AFTER_START(StepTime::START, StepTime::AFTER);
const StepTime StepTime::BEFORE_END(StepTime::END, StepTime::BEFORE);
const StepTime StepTime::AT_END(StepTime::END, StepTime::AT);

bool operator<(const StepTime& st1, const StepTime& st2) {
  return (st1.point < st2.point
	  || (st1.point == st2.point && st1.rel < st2.rel));
}

bool operator<=(const StepTime& st1, const StepTime& st2) {
  return (st1.point <= st2.point
	  || (st1.point == st2.point && st1.rel <= st2.rel));
}

bool operator>=(const StepTime& st1, const StepTime& st2) {
  return (st1.point >= st2.point
	  || (st1.point == st2.point && st1.rel >= st2.rel));
}

bool operator>(const StepTime& st1, const StepTime& st2) {
  return (st1.point > st2.point
	  || (st1.point == st2.point && st1.rel > st2.rel));
}

/* Returns the step time corresponding to the end time of the given
   effect. */
StepTime end_time(const Effect& e) {
  if (e.when() == Effect::AT_START) {
    return StepTime::AT_START;
  } else {
    return StepTime::AT_END;
  }
}

/* Returns the step time corresponding to the end time of the given
   formula time. */
StepTime end_time(FormulaTime ft) {
  if (ft == AT_START) {
    return StepTime::AT_START;
  } else if (ft == AT_END) {
    return StepTime::AT_END;
  } else {
    return StepTime::BEFORE_END;
  }
}

/* Returns the step time corresponding to the start time of the given
   literal. */
StepTime start_time(FormulaTime ft) {
  if (ft == AT_START) {
    return StepTime::AT_START;
  } else if (ft == AT_END) {
    return StepTime::AT_END;
  } else {
    return StepTime::AFTER_START;
  }
}

/* ====================================================================== */
/* BoolVector */

/*
 * A collectible bool vector.
 */
struct BoolVector : public std::vector<bool> {
  /* Register use of the given vector. */
  static void register_use(const BoolVector* v) {
    if (v != NULL) {
      v->ref_count_++;
    }
  }

  /* Unregister use of the given vector. */
  static void unregister_use(const BoolVector* v) {
    if (v != NULL) {
      v->ref_count_--;
      if (v->ref_count_ == 0) {
	delete v;
      }
    }
  }

  /* Constructs a vector with n copies of b. */
  BoolVector(size_t n, bool b)
    : std::vector<bool>(n, b), ref_count_(0) {
#ifdef DEBUG_MEMORY
    created_bool_vectors++;
#endif
  }

  /* Constructs a copy of the given vector. */
  BoolVector(const BoolVector& v)
    : std::vector<bool>(v), ref_count_(0) {
#ifdef DEBUG_MEMORY
    created_bool_vectors++;
#endif
  }

#ifdef DEBUG_MEMORY
  /* Deletes this vector. */
  ~BoolVector() {
    deleted_bool_vectors++;
  }
#endif

private:
  /* Reference counter. */
  mutable size_t ref_count_;
};

/* ====================================================================== */
/* IntVector */

/*
 * A collectible int vector.
 */
struct IntVector : public std::vector<int> {
  /* Register use of the given vector. */
  static void register_use(const IntVector* v) {
    if (v != NULL) {
      v->ref_count_++;
    }
  }

  /* Unregister use of the given vector. */
  static void unregister_use(const IntVector* v) {
    if (v != NULL) {
      v->ref_count_--;
      if (v->ref_count_ == 0) {
	delete v;
      }
    }
  }

  /* Constructs a vector with n copies of b. */
  IntVector(size_t n, int f)
    : std::vector<int>(n, f), ref_count_(0) {
#ifdef DEBUG_MEMORY
    created_float_vectors++;
#endif
  }

  /* Constructs a copy of the given vector. */
  IntVector(const IntVector& v)
    : std::vector<int>(v), ref_count_(0) {
#ifdef DEBUG_MEMORY
    created_float_vectors++;
#endif
  }

#ifdef DEBUG_MEMORY
  /* Deletes this vector. */
  ~IntVector() {
    deleted_float_vectors++;
  }
#endif

private:
  /* Reference counter. */
  mutable size_t ref_count_;
};

/* ====================================================================== */
/* Orderings */

/* Minimum distance between two ordered steps. */
float Orderings::threshold = 0.01f;

/* Constructs an empty ordering collection. */
Orderings::Orderings()
  : ref_count_(0) {
#ifdef DEBUG_MEMORY
    created_orderings++;
#endif
}

/* Constructs a copy of this ordering collection. */
Orderings::Orderings(const Orderings& o)
  : ref_count_(0) {
#ifdef DEBUG_MEMORY
    created_orderings++;
#endif
}

/* Deletes this ordering collection. */
Orderings::~Orderings() {
#ifdef DEBUG_MEMORY
    deleted_orderings++;
#endif
}

/* Output operator for orderings. */
std::ostream& operator<<(std::ostream& os, const Orderings& o) {
  o.print(os);
  return os;
}

/* ====================================================================== */
/* BinaryOrderings */

/* Constructs an empty ordering collection. */
BinaryOrderings::BinaryOrderings() {}

/* Constructs a copy of this ordering collection. */
BinaryOrderings::BinaryOrderings(const BinaryOrderings& o)
  : Orderings(o), before_(o.before_) {
  size_t n = before_.size();
  for (size_t i = 0; i < n; i++) {
    BoolVector::register_use(before_[i]);
  }
}

/* Deletes this ordering collection. */
BinaryOrderings::~BinaryOrderings() {
  size_t n = before_.size();
  for (size_t i = 0; i < n; i++) {
    BoolVector::unregister_use(before_[i]);
  }
}

/* Checks if the first step could be ordered before the second step. */
bool BinaryOrderings::possibly_before(size_t id1, StepTime t1,
				      size_t id2, StepTime t2) const {
  if (id1 == id2) {
    return false;
  } else if (id1 == 0 || id2 == Plan::GOAL_ID) {
    return true;
  } else if (id1 == Plan::GOAL_ID || id2 == 0) {
    return false;
  } else {
    return !before(id2, id1);
  }
}

/* Checks if the first step could be ordered after or at the same
   time as the second step. */
bool BinaryOrderings::possibly_not_before(size_t id1, StepTime t1,
					  size_t id2, StepTime t2) const {
  return possibly_after(id1, t1, id2, t2);
}

/* Checks if the first step could be ordered after the second step. */
bool BinaryOrderings::possibly_after(size_t id1, StepTime t1,
				     size_t id2, StepTime t2) const {
  if (id1 == id2) {
    return false;
  } else if (id1 == 0 || id2 == Plan::GOAL_ID) {
    return false;
  } else if (id1 == Plan::GOAL_ID || id2 == 0) {
    return true;
  } else {
    return !before(id1, id2);
  }
}

/* Checks if the first step could be ordered before or at the same
   time as the second step. */
bool BinaryOrderings::possibly_not_after(size_t id1, StepTime t1,
					 size_t id2, StepTime t2) const {
  return possibly_before(id1, t1, id2, t2);
}

/* Checks if the two steps are possibly concurrent. */
bool BinaryOrderings::possibly_concurrent(size_t id1, size_t id2,
					  bool& ss, bool& se,
					  bool& es, bool& ee) const {
  if (id1 == id2 || id1 == 0 || id1 == Plan::GOAL_ID
      || id2 == 0 || id2 == Plan::GOAL_ID) {
    return false;
  } else {
    return ss = se = es = ee = !before(id1, id2) && !before(id2, id1);
  }
}

/* Returns the the ordering collection with the given additions. */
const BinaryOrderings*
BinaryOrderings::refine(const Ordering& new_ordering) const {
  if (new_ordering.before_id() != 0
      && new_ordering.after_id() != Plan::GOAL_ID
      && possibly_not_before(new_ordering.before_id(),
			     new_ordering.before_time(),
			     new_ordering.after_id(),
			     new_ordering.after_time())) {
    BinaryOrderings& orderings = *new BinaryOrderings(*this);
    std::map<size_t, BoolVector*> own_data;
    orderings.fill_transitive(own_data, new_ordering);
    return &orderings;
  } else {
    return this;
  }
}

/* Returns the the ordering collection with the given additions. */
const BinaryOrderings*
BinaryOrderings::refine(const Ordering& new_ordering,
			const Step& new_step, const PlanningGraph* pg,
			const Bindings* bindings) const {
  if (new_step.id() != 0 && new_step.id() != Plan::GOAL_ID) {
    BinaryOrderings& orderings = *new BinaryOrderings(*this);
    std::map<size_t, BoolVector*> own_data;
    if (new_step.id() > before_.size() + 1) {
      if (new_step.id() > 1) {
	BoolVector* bv = new BoolVector(2*new_step.id() - 2, false);
	own_data.insert(std::make_pair(orderings.before_.size(), bv));
	orderings.before_.push_back(bv);
	BoolVector::register_use(bv);
      }
    }
    if (new_ordering.before_id() != 0
	&& new_ordering.after_id() != Plan::GOAL_ID) {
      orderings.fill_transitive(own_data, new_ordering);
    }
    return &orderings;
  } else {
    return this;
  }
}

/* Fills the given tables with distances for each step from the
   start step, and returns the greatest distance. */
float BinaryOrderings::schedule(std::map<size_t, float>& start_times,
				std::map<size_t, float>& end_times) const {
  float max_dist = 0.0f;
  size_t n = before_.size() + 1;
  for (size_t i = 1; i <= n; i++) {
    float ed = schedule(start_times, end_times, i);
    if (ed > max_dist) {
      max_dist = ed;
    }
  }
  return max_dist;
}

/* Returns the makespan of this ordering collection. */
float
BinaryOrderings::makespan(const std::map<std::pair<size_t,
			  StepTime::StepPoint>, float>& min_times) const {
  std::map<size_t, float> start_times, end_times;
  float max_dist = 0.0f;
  size_t n = before_.size() + 1;
  for (size_t i = 1; i <= n; i++) {
    float ed = schedule(start_times, end_times, i, min_times);
    if (ed > max_dist) {
      max_dist = ed;
    }
  }
  std::map<std::pair<size_t, StepTime::StepPoint>, float>::const_iterator md =
    min_times.find(std::make_pair(Plan::GOAL_ID, StepTime::START));
  if (md != min_times.end()) {
    if ((*md).second > max_dist) {
      max_dist = (*md).second;
    }
  }
  return max_dist;
}

/* Schedules the given instruction with the given constraints. */
float BinaryOrderings::schedule(std::map<size_t, float>& start_times,
				std::map<size_t, float>& end_times,
				size_t step_id) const {
  std::map<size_t, float>::const_iterator d = start_times.find(step_id);
  if (d != start_times.end()) {
    return (*d).second;
  } else {
    float sd = 1.0f;
    size_t n = before_.size() + 1;
    for (size_t j = 1; j <= n; j++) {
      if (step_id != j && before(j, step_id)) {
	float ed = 1.0f + schedule(start_times, end_times, j);
	if (ed > sd) {
	  sd = ed;
	}
      }
    }
    start_times.insert(std::make_pair(step_id, sd));
    end_times.insert(std::make_pair(step_id, sd));
    return sd;
  }
}

/* Schedules the given instruction with the given constraints. */
float
BinaryOrderings::schedule(std::map<size_t, float>& start_times,
			  std::map<size_t, float>& end_times, size_t step_id,
			  const std::map<std::pair<size_t,
			  StepTime::StepPoint>, float>& min_times) const {
  std::map<size_t, float>::const_iterator d = start_times.find(step_id);
  if (d != start_times.end()) {
    return (*d).second;
  } else {
    float sd = threshold;
    size_t n = before_.size() + 1;
    for (size_t j = 1; j <= n; j++) {
      if (step_id != j && before(j, step_id)) {
	float ed = threshold + schedule(start_times, end_times, j, min_times);
	if (ed > sd) {
	  sd = ed;
	}
      }
    }
    std::map<std::pair<size_t, StepTime::StepPoint>, float>::const_iterator
      md = min_times.find(std::make_pair(step_id, StepTime::START));
    if (md == min_times.end()) {
      md = min_times.find(std::make_pair(step_id, StepTime::END));
    }
    if (md != min_times.end()) {
      if ((*md).second > sd) {
	sd = (*md).second;
      }
    }
    start_times.insert(std::make_pair(step_id, sd));
    end_times.insert(std::make_pair(step_id, sd));
    return sd;
  }
}

/* Returns true iff the first step is ordered before the second step. */
bool BinaryOrderings::before(size_t id1, size_t id2) const {
  if (id1 == id2) {
    return false;
  } else if (id1 < id2) {
    return (*before_[id2 - 2])[id1 - 1];
  } else {
    return (*before_[id1 - 2])[2*id1 - 2 - id2];
  }
}

/* Orders the first step before the second step. */
void
BinaryOrderings::set_before(std::map<size_t, BoolVector*>& own_data,
			    size_t id1, size_t id2) {
  if (id1 != id2) {
    size_t i = std::max(id1, id2) - 2;
    BoolVector* bv;
    std::map<size_t, BoolVector*>::const_iterator vi = own_data.find(i);
    if (vi != own_data.end()) {
      bv = (*vi).second;
    } else {
      const BoolVector* old_bv = before_[i];
      bv = new BoolVector(*old_bv);
      BoolVector::register_use(bv);
      BoolVector::unregister_use(old_bv);
      before_[i] = bv;
      own_data.insert(std::make_pair(i, bv));
    }
    if (id1 < id2) {
      (*bv)[id1 - 1] = true;
    } else {
      (*bv)[2*id1 - 2 - id2] = true;
    }
  }
}

/* Updates the transitive closure given a new ordering constraint. */
void BinaryOrderings::fill_transitive(std::map<size_t, BoolVector*>& own_data,
				      const Ordering& ordering) {
  size_t i = ordering.before_id();
  size_t j = ordering.after_id();
  if (!before(i, j)) {
    /*
     * All steps ordered before i (and i itself) must be ordered
     * before j and all steps ordered after j.
     */
    size_t n = before_.size() + 1;
    for (size_t k = 1; k <= n; k++) {
      if ((k == i || before(k, i)) && !before(k, j)) {
	for (size_t l = 1; l <= n; l++) {
	  if ((j == l || before(j, l)) && !before(k, l)) {
	    set_before(own_data, k, l);
	  }
	}
      }
    }
  }
}

/* Prints this ordering collection on the given stream. */
void BinaryOrderings::print(std::ostream& os) const {
  os << "{";
  size_t n = before_.size() + 1;
  for (size_t i = 1; i <= n; i++) {
    for (size_t j = 1; j <= n; j++) {
      if (before(i, j)) {
	os << ' ' << i << '<' << j;
      }
    }
  }
  os << " }";
}

/* ====================================================================== */
/* TemporalOrderings */

/* Constructs an empty ordering collection. */
TemporalOrderings::TemporalOrderings()
  : goal_achievers_(NULL) {}

/* Constructs a copy of this ordering collection. */
TemporalOrderings::TemporalOrderings(const TemporalOrderings& o)
  : Orderings(o), distance_(o.distance_), goal_achievers_(o.goal_achievers_) {
  size_t n = distance_.size();
  for (size_t i = 0; i < n; i++) {
    IntVector::register_use(distance_[i]);
  }
  RCObject::ref(goal_achievers_);
}

/* Deletes this ordering collection. */
TemporalOrderings::~TemporalOrderings() {
  size_t n = distance_.size();
  for (size_t i = 0; i < n; i++) {
    IntVector::unregister_use(distance_[i]);
  }
  RCObject::destructive_deref(goal_achievers_);
}

/* Checks if the first step could be ordered before the second step. */
bool TemporalOrderings::possibly_before(size_t id1, StepTime t1,
					size_t id2, StepTime t2) const {
  if (id1 == id2 && t1 >= t2) {
    return false;
  } else if (id1 == 0 || id2 == Plan::GOAL_ID) {
    return true;
  } else if (id1 == Plan::GOAL_ID || id2 == 0) {
    return false;
  } else {
    int dist = distance(time_node(id1, t1), time_node(id2, t2));
    return dist > 0 || (dist == 0 && t1.rel < t2.rel);
  }
}

/* Checks if the first step could be ordered after or at the same
   time as the second step. */
bool TemporalOrderings::possibly_not_before(size_t id1, StepTime t1,
					    size_t id2, StepTime t2) const {
  if (id1 == id2 && t1 < t2) {
    return false;
  } else if (id1 == 0 || id2 == Plan::GOAL_ID) {
    return false;
  } else if (id1 == Plan::GOAL_ID || id2 == 0) {
    return true;
  } else {
    int dist = distance(time_node(id2, t2), time_node(id1, t1));
    return dist > 0 || (dist == 0 && t2.rel <= t1.rel);
  }
}

/* Checks if the first step could be ordered after the second step. */
bool TemporalOrderings::possibly_after(size_t id1, StepTime t1,
				       size_t id2, StepTime t2) const {
  if (id1 == id2 && t1 <= t2) {
    return false;
  } else if (id1 == 0 || id2 == Plan::GOAL_ID) {
    return false;
  } else if (id1 == Plan::GOAL_ID || id2 == 0) {
    return true;
  } else {
    int dist = distance(time_node(id2, t2), time_node(id1, t1));
    return dist > 0 || (dist == 0 && t2.rel < t1.rel);
  }
}

/* Checks if the first step could be ordered before or at the same
   time as the second step. */
bool TemporalOrderings::possibly_not_after(size_t id1, StepTime t1,
					   size_t id2, StepTime t2) const {
  if (id1 == id2 && t1 > t2) {
    return false;
  } else if (id1 == 0 || id2 == Plan::GOAL_ID) {
    return true;
  } else if (id1 == Plan::GOAL_ID || id2 == 0) {
    return false;
  } else {
    int dist = distance(time_node(id1, t1), time_node(id2, t2));
    return dist > 0 || (dist == 0 && t1.rel <= t2.rel);
  }
}

/* Checks if the two steps are possibly concurrent. */
bool TemporalOrderings::possibly_concurrent(size_t id1, size_t id2,
					    bool& ss, bool& se,
					    bool& es, bool& ee) const {
  if (id1 == id2 || id1 == 0 || id1 == Plan::GOAL_ID
      || id2 == 0 || id2 == Plan::GOAL_ID) {
    return false;
  } else {
    size_t t1s = time_node(id1, StepTime::AT_START);
    size_t t1e = time_node(id1, StepTime::AT_END);
    size_t t2s = time_node(id2, StepTime::AT_START);
    size_t t2e = time_node(id2, StepTime::AT_END);
    ss = distance(t1s, t2s) >= 0 && distance(t2s, t1s) >= 0;
    se = distance(t1s, t2e) >= 0 && distance(t2e, t1s) >= 0;
    es = distance(t1e, t2s) >= 0 && distance(t2s, t1e) >= 0;
    ee = distance(t1e, t2e) >= 0 && distance(t2e, t1e) >= 0;
    return ss || se || es || ee;
  }
}

/* Returns the ordering collection with the given additions. */
const TemporalOrderings* TemporalOrderings::refine(size_t step_id,
						   float min_start,
						   float min_end) const {
  if (step_id != 0 && step_id != Plan::GOAL_ID) {
    size_t i = time_node(step_id, StepTime::AT_START);
    size_t j = time_node(step_id, StepTime::AT_END);
    int start = int(min_start/threshold + 0.5);
    int end = int(min_end/threshold + 0.5);
    if (-distance(i, 0) >= start && -distance(j, 0) >= end) {
      return this;
    } else if (distance(0, i) < start || distance(0, j) < end) {
      return NULL;
    } else {
      TemporalOrderings& orderings = *new TemporalOrderings(*this);
      std::map<size_t, IntVector*> own_data;
      if (orderings.fill_transitive(own_data, 0, i, start)
	  && orderings.fill_transitive(own_data, 0, j, end)) {
	return &orderings;
      } else {
	delete &orderings;
	return NULL;
      }
    }
  } else {
    return this;
  }
}

/* Returns the ordering collection with the given additions. */
const TemporalOrderings*
TemporalOrderings::refine(float time, const Step& new_step) const {
  if (new_step.id() != 0 && new_step.id() != Plan::GOAL_ID
      && new_step.id() > distance_.size()/2) {
    int itime = int(time/threshold + 0.5);
    TemporalOrderings& orderings = *new TemporalOrderings(*this);
    IntVector* fv = new IntVector(4*new_step.id() - 2, INT_MAX);
    /* Time for start of new step. */
    (*fv)[0] = itime;
    (*fv)[4*new_step.id() - 3] = -itime;
    for (size_t id = 1; id < new_step.id(); id++) {
      int t = itime - (*distance_[2*id - 1])[0];
      (*fv)[2*id - 1] = (*fv)[2*id] = t;
      (*fv)[4*new_step.id() - 2*id - 2] = -t;
      (*fv)[4*new_step.id() - 2*id - 3] = -t;
    }
    orderings.distance_.push_back(fv);
    IntVector::register_use(fv);
    fv = new IntVector(4*new_step.id(), INT_MAX);
    /* Time for end of new step. */
    (*fv)[0] = itime;
    (*fv)[4*new_step.id() - 1] = -itime;
    for (size_t id = 1; id < new_step.id(); id++) {
      int t = itime - (*distance_[2*id - 1])[0];
      (*fv)[2*id - 1] = (*fv)[2*id] = t;
      (*fv)[4*new_step.id() - 2*id] = -t;
      (*fv)[4*new_step.id() - 2*id - 1] = -t;
    }
    (*fv)[2*new_step.id() - 1] = (*fv)[2*new_step.id()] = 0;
    orderings.distance_.push_back(fv);
    IntVector::register_use(fv);
    return &orderings;
  } else {
    return this;
  }
}

/* Returns the the ordering collection with the given additions. */
const TemporalOrderings*
TemporalOrderings::refine(const Ordering& new_ordering) const {
  if (new_ordering.before_id() != 0
      && new_ordering.after_id() != Plan::GOAL_ID
      && possibly_not_before(new_ordering.before_id(),
			     new_ordering.before_time(),
			     new_ordering.after_id(),
			     new_ordering.after_time())) {
    TemporalOrderings& orderings = *new TemporalOrderings(*this);
    std::map<size_t, IntVector*> own_data;
    size_t i = time_node(new_ordering.before_id(), new_ordering.before_time());
    size_t j = time_node(new_ordering.after_id(), new_ordering.after_time());
    int dist;
    if (new_ordering.before_time().rel < new_ordering.after_time().rel) {
      dist = 0;
    } else {
      dist = 1;
    }
    if (orderings.fill_transitive(own_data, i, j, dist)) {
      return &orderings;
    } else {
      delete &orderings;
      return NULL;
    }
  } else {
    return this;
  }
}

/* Returns the the ordering collection with the given additions. */
const TemporalOrderings*
TemporalOrderings::refine(const Ordering& new_ordering,
			  const Step& new_step, const PlanningGraph* pg,
			  const Bindings* bindings) const {
  if (new_step.id() != 0 && new_step.id() != Plan::GOAL_ID) {
    TemporalOrderings& orderings = *new TemporalOrderings(*this);
    std::map<size_t, IntVector*> own_data;
    if (new_step.id() > distance_.size()/2) {
      const Value* min_v =
	dynamic_cast<const Value*>(&new_step.action().min_duration());
      if (min_v == NULL) {
	throw std::runtime_error("non-constant minimum duration");
      }
      const Value* max_v =
	dynamic_cast<const Value*>(&new_step.action().max_duration());
      if (max_v == NULL) {
	throw std::runtime_error("non-constant maximum duration");
      }
      float start_time = threshold;
      float end_time;
      if (pg != NULL) {
	HeuristicValue h, hs;
	new_step.action().condition().heuristic_value(h, hs, *pg,
						      new_step.id(), bindings);
	if (hs.makespan() > start_time) {
	  start_time = hs.makespan();
	}
	end_time = start_time + min_v->value();
	if (h.makespan() > end_time) {
	  end_time = h.makespan();
	}
      } else {
	end_time = threshold + min_v->value();
      }
      IntVector* fv = new IntVector(4*new_step.id() - 2, INT_MAX);
      /* Earliest time for start of new step. */
      (*fv)[4*new_step.id() - 3] = -int(start_time/threshold + 0.5);
      own_data.insert(std::make_pair(orderings.distance_.size(), fv));
      orderings.distance_.push_back(fv);
      IntVector::register_use(fv);
      fv = new IntVector(4*new_step.id(), INT_MAX);
      /* Earliest time for end of new step. */
      (*fv)[4*new_step.id() - 1] = -int(end_time/threshold + 0.5);
      if (max_v->value() != std::numeric_limits<float>::infinity()) {
	(*fv)[2*new_step.id() - 1] = int(max_v->value()/threshold + 0.5);
      }
      (*fv)[2*new_step.id()] = -int(min_v->value()/threshold + 0.5);
      own_data.insert(std::make_pair(orderings.distance_.size(), fv));
      orderings.distance_.push_back(fv);
      IntVector::register_use(fv);
    }
    if (new_ordering.before_id() != 0) {
      if (new_ordering.after_id() != Plan::GOAL_ID) {
	size_t i = time_node(new_ordering.before_id(),
			     new_ordering.before_time());
	size_t j = time_node(new_ordering.after_id(),
			     new_ordering.after_time());
	int dist;
	if (new_ordering.before_time().rel < new_ordering.after_time().rel) {
	  dist = 0;
	} else {
	  dist = 1;
	}
	if (orderings.fill_transitive(own_data, i, j, dist)) {
	  return &orderings;
	} else {
	  delete &orderings;
	  return NULL;
	}
      } else {
	orderings.goal_achievers_ =
	  new Chain<size_t>(new_ordering.before_id(),
			    orderings.goal_achievers_);
	RCObject::ref(orderings.goal_achievers_);
      }
    }
    return &orderings;
  } else {
    return this;
  }
}

/* Fills the given tables with distances for each step from the
   start step, and returns the greatest distance. */
float
TemporalOrderings::schedule(std::map<size_t, float>& start_times,
			    std::map<size_t, float>& end_times) const {
  float max_dist = 0.0f;
  size_t n = distance_.size()/2;
  for (size_t i = 1; i <= n; i++) {
    float sd = -distance(time_node(i, StepTime::AT_START), 0)*threshold;
    start_times.insert(std::make_pair(i, sd));
    float ed = -distance(time_node(i, StepTime::AT_END), 0)*threshold;
    end_times.insert(std::make_pair(i, ed));
    if (ed > max_dist
	&& goal_achievers_ != NULL && goal_achievers_->contains(i)) {
      max_dist = ed;
    }
  }
  return max_dist;
}

/* Returns the makespan of this ordering collection. */
float
TemporalOrderings::makespan(const std::map<std::pair<size_t,
			    StepTime::StepPoint>, float>& min_times) const {
  float max_dist = 0.0f;
  size_t n = distance_.size()/2;
  for (size_t i = 1; i <= n; i++) {
    float ed = -distance(time_node(i, StepTime::AT_END), 0)*threshold;
    if (ed > max_dist
	&& goal_achievers_ != NULL && goal_achievers_->contains(i)) {
      max_dist = ed;
    }
  }
  return max_dist;
}

/* Returns the maximum distance from the first and the second time node. */
int TemporalOrderings::distance(size_t t1, size_t t2) const {
  if (t1 == t2) {
    return 0;
  } else if (t1 < t2) {
    return (*distance_[t2 - 1])[t1];
  } else {
    return (*distance_[t1 - 1])[2*t1 - 1 - t2];
  }
}

/* Sets the maximum distance from the first and the second time node. */
void TemporalOrderings::set_distance(std::map<size_t, IntVector*>& own_data,
				     size_t t1, size_t t2, int d) {
  if (t1 != t2) {
    size_t i = std::max(t1, t2) - 1;
    IntVector* fv;
    std::map<size_t, IntVector*>::const_iterator vi = own_data.find(i);
    if (vi != own_data.end()) {
      fv = (*vi).second;
    } else {
      const IntVector* old_fv = distance_[i];
      fv = new IntVector(*old_fv);
      IntVector::register_use(fv);
      IntVector::unregister_use(old_fv);
      distance_[i] = fv;
      own_data.insert(std::make_pair(i, fv));
    }
    if (t1 < t2) {
      (*fv)[t1] = d;
    } else {
      (*fv)[2*t1 - 1 - t2] = d;
    }
  }
}

/* Updates the transitive closure given a new ordering constraint. */
bool
TemporalOrderings::fill_transitive(std::map<size_t, IntVector*>& own_data,
				   size_t i, size_t j, int dist) {
  if (distance(j, i) > -dist) {
    /*
     * Update the temporal constraints.
     *
     * Make sure that -d_ij <= d_ji always holds.
     */
    size_t n = distance_.size();
    for (size_t k = 0; k <= n; k++) {
      int d_ik = distance(i, k);
      if (d_ik < INT_MAX && distance(j, k) > d_ik - dist) {
	for (size_t l = 0; l <= n; l++) {
	  int d_lj = distance(l, j);
	  int new_d = d_ik + d_lj - dist;
	  if (d_lj < INT_MAX && distance(l, k) > new_d) {
	    set_distance(own_data, l, k, new_d);
	    if (-distance(k, l) > new_d) {
	      return false;
	    }
	  }
	}
      }
    }
  }
  return true;
}

/* Prints this ordering collection on the given stream. */
void TemporalOrderings::print(std::ostream& os) const {
  size_t n = distance_.size();
  for (size_t r = 0; r <= n; r++) {
    os << std::endl;
    for (size_t c = 0; c <= n; c++) {
      os.width(7);
      int d = distance(r, c);
      if (d < INT_MAX) {
	os << d;
      } else {
	os << "inf";
      }
    }
  }
}


text:
package com.manulaiko.tabitha.utils;

/**
 * Argument handler.
 * =================
 *
 * Base class for all argument handlers.
 *
 * The method `handle` is executed when an argument can be handled by the instance.
 *
 * @author Manulaiko <manulaiko@gmail.com>
 */
public abstract class Argument
{
    /**
     * Argument name.
     */
    private String _name = "";

    /**
     * Argument value.
     */
    private String _value = "";

    /**
     * Sets argument name.
     *
     * @param name New argument name.
     */
    public void name(String name)
    {
        this._name = name;
    }

    /**
     * Returns argument name.
     *
     * @return Argument name.
     */
    public String name()
    {
        return this._name;
    }

    /**
     * Sets argument value.
     *
     * @param value New argument value.
     */
    public void value(String value)
    {
        this._value = value;
    }

    /**
     * Returns argument value.
     *
     * @return Argument value.
     */
    public String value()
    {
        return this._value;
    }

    /**
     * Checks that the argument can be handled
     * by this instance.
     *
     * @param arg Argument.
     *
     * @return `true` if the argument can be handled by this instance, `false` if not.
     */
    public abstract boolean canHandle(String arg);

    /**
     * Handles the argument.
     */
    public abstract void handle();
}


text:
<md-dialog aria-label="Mango (Fruit)">
    <md-content class="sticky-container">
        <md-subheader class="md-sticky-no-effect" layout-align="center">TẠO CHIẾN DỊCH</md-subheader>

            <form name="campaignForm">
                <md-input-container>
                    Tên chiến dịch

                    <input required name="campaignName" ng-model="campaign.campaignName">

Bắt buộc nhập.

                </md-input-container>
            </form>

    </md-content>

        <md-button ng-click="cancel()">
            Huỷ
        </md-button>
        <md-button ng-click="created(campaign.campaignName)" class="md-primary">
            Tạo mới
        </md-button>

</md-dialog>


text:
import React from "react";

export default class Header extends React.Component {

  render() {
    return

{this.props.headerTitle}

;
  }

}


text:
@protocol ETUpdateTaskDelegate<NSObject>
@required
-(void) didUpdateTask: (ETTask*) task;
-(void) didCancelEdit;
@end

@interface ETEditTaskViewController : UIViewController<UITextViewDelegate>
- (IBAction)cancelButtonPressed:(UIBarButtonItem *)sender;
- (IBAction)saveTaskButtonPressed:(UIBarButtonItem *)sender;

@property (strong, nonatomic) ETTask* task;
@property (strong, nonatomic) IBOutlet UITextField *taskNameTextField;
@property (strong, nonatomic) IBOutlet UITextView *taskDescriptionTextView;
@property (strong, nonatomic) IBOutlet UISwitch *taskCompletedSwitch;

@property (strong, nonatomic) IBOutlet UIDatePicker *taskDatePicker;
@property (weak,nonatomic) id<ETUpdateTaskDelegate> delegate;
@end


text:
package edu.ptu.navpattern.tooltip;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.SystemClock;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.support.v4.content.res.ResourcesCompat;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import edu.ptu.navpattern.R;

/**
 * Tooltip
 */
public final class Tooltip {

    private final boolean isCancelable;
    private final boolean isDismissOnClick;

    private final int mGravity;

    private final float mMargin;

    private final View mAnchorView;
    private final PopupWindow mPopupWindow;

    private OnDismissListener mOnDismissListener;

    private LinearLayout mContentView;
    private ImageView mArrowView;

    private Tooltip(Builder builder) {
        isCancelable = builder.isCancelable;
        isDismissOnClick = builder.isDismissOnClick;

        mGravity = builder.mGravity;
        mMargin = builder.mMargin;
        mAnchorView = builder.mAnchorView;
        mOnDismissListener = builder.mOnDismissListener;

        mPopupWindow = new PopupWindow(builder.mContext);
        mPopupWindow.setBackgroundDrawable(null);
        mPopupWindow.setClippingEnabled(false);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setContentView(getContentView(builder));
        mPopupWindow.setOutsideTouchable(builder.isCancelable);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mAnchorView.removeOnAttachStateChangeListener(mOnAttachStateChangeListener);

                if (mOnDismissListener != null) {
                    mOnDismissListener.onDismiss();
                }
            }
        });
    }

    private View getContentView(final Builder builder) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setColor(builder.mBackgroundColor);
        drawable.setCornerRadius(builder.mCornerRadius);
        LinearLayout vgContent = new LinearLayout(builder.mContext);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            vgContent.setBackground(drawable);
        } else {
            //noinspection deprecation
            vgContent.setBackgroundDrawable(drawable);
        }
        int padding = (int) builder.mPadding;
        vgContent.setPadding(padding, padding, padding, padding);
        vgContent.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0);
        textViewParams.gravity = Gravity.CENTER;
        textViewParams.topMargin = 1;
        vgContent.setLayoutParams(textViewParams);
        vgContent.setDividerDrawable(vgContent.getResources().getDrawable(R.drawable.divider_line));
        vgContent.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);

        if (builder.itemText != null && builder.itemText.length > 0) {
            for (int i = 0; i < builder.itemText.length; i++) {

                TextView textView = new TextView(builder.mContext);
                textView.setText(builder.itemText[i]);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,44);
                textView.setTextColor(0xffffffff);
                textView.setGravity(Gravity.CENTER_VERTICAL);
                if (builder.itemLogo != null && builder.itemLogo.length > i) {
                    Drawable drawableLeft = builder.mContext.getResources().getDrawable(builder.itemLogo[i]);
/// 这一步必须要做,否则不会显示.
//                    drawableLeft.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                    textView.setCompoundDrawables(drawableLeft, null, null, null);
//                    textView.setCompoundDrawablePadding(4);
//                    textView.setBackgroundDrawable(drawableLeft);
                    LinearLayout linearLayout = new LinearLayout(builder.mContext);
                    linearLayout.setMinimumHeight((int) dpToPx(44f));
                    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                    linearLayout.setGravity(Gravity.CENTER_VERTICAL);
                    ImageView icon = new ImageView(builder.mContext);
                    icon.setImageDrawable(drawableLeft);
                    linearLayout.addView(icon);
                    linearLayout.addView(textView);
                    vgContent.addView(linearLayout);
                    final int position = i;
                    linearLayout.setClickable(false);
                    linearLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (builder.mOnItemClickListener != null) {
                                builder.mOnItemClickListener.onClick(position);
                            }
                            mTouchListener.onTouch(v,MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, v.getLeft()+5, v.getTop()+5, 0));
                        }
                    });
                } else {
                    vgContent.addView(textView);
                    final int position = i;
                    textView.setClickable(false);
                    textView.setMinimumHeight((int) dpToPx(44f));
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (builder.mOnItemClickListener != null) {
                                builder.mOnItemClickListener.onClick(position);
                            }
                            mTouchListener.onTouch(v,null);
                        }
                    });
                }
            }

        }

        mArrowView = new ImageView(builder.mContext);
        mArrowView.setImageDrawable(builder.mArrowDrawable);

        LinearLayout.LayoutParams arrowLayoutParams;
        if (mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM) {
            arrowLayoutParams = new LinearLayout.LayoutParams((int) builder.mArrowWidth, (int) builder.mArrowHeight, 0);
        } else {
            arrowLayoutParams = new LinearLayout.LayoutParams((int) builder.mArrowHeight, (int) builder.mArrowWidth, 0);
        }
        arrowLayoutParams.gravity = Gravity.CENTER;
        mArrowView.setLayoutParams(arrowLayoutParams);

        mContentView = new LinearLayout(builder.mContext);
        mContentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mContentView.setOrientation(mGravity == Gravity.START || mGravity == Gravity.END ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);

        padding = (int) dpToPx(5);

        switch (mGravity) {
            case Gravity.START:
                mContentView.setPadding(0, 0, padding, 0);
                break;
            case Gravity.TOP:
            case Gravity.BOTTOM:
                mContentView.setPadding(padding, 0, padding, 0);
                break;
            case Gravity.END:
                mContentView.setPadding(padding, 0, 0, 0);
                break;
        }

        if (mGravity == Gravity.TOP || mGravity == Gravity.START) {
            mContentView.addView(vgContent);
            mContentView.addView(mArrowView);
        } else {
            mContentView.addView(mArrowView);
            mContentView.addView(vgContent);
        }

        if (builder.isCancelable || builder.isDismissOnClick) {
            mContentView.setOnTouchListener(mTouchListener);
        }
        return mContentView;
    }

    /**
     *
Indicate whether this Tooltip is showing on screen.

     *
     * @return true if the Tooltip is showing, false otherwise
     */
    public boolean isShowing() {
        return mPopupWindow.isShowing();
    }

    /**
     * Display the Tooltip anchored to the custom gravity of the anchor view.
     *
     * @see #dismiss()
     */
    public void show() {
        if (!isShowing()) {
            mContentView.getViewTreeObserver().addOnGlobalLayoutListener(mLocationLayoutListener);

            mAnchorView.addOnAttachStateChangeListener(mOnAttachStateChangeListener);
            mAnchorView.post(new Runnable() {
                @Override
                public void run() {
                    mPopupWindow.showAsDropDown(mAnchorView);
                }
            });
        }
    }

    /**
     * Disposes of the Tooltip. This method can be invoked only after
     * {@link #show()} has been executed. Failing
     * that, calling this method will have no effect.
     *
     * @see #show()
     */
    public void dismiss() {
        mPopupWindow.dismiss();
    }

    public void cancel() {

    }

    /**
     * Sets the listener to be called when Tooltip is dismissed.
     *
     * @param listener The listener.
     */
    public void setOnDismissListener(OnDismissListener listener) {
        mOnDismissListener = listener;
    }

    private PointF calculateLocation() {
        PointF location = new PointF();

        final RectF anchorRect = calculateRectInWindow(mAnchorView);
        final PointF anchorCenter = new PointF(anchorRect.centerX(), anchorRect.centerY());

        switch (mGravity) {
            case Gravity.START:
                location.x = anchorRect.left - mContentView.getWidth() - mMargin;
                location.y = anchorCenter.y - mContentView.getHeight() / 2f;
                break;
            case Gravity.END:
                location.x = anchorRect.right + mMargin;
                location.y = anchorCenter.y - mContentView.getHeight() / 2f;
                break;
            case Gravity.TOP:
                location.x = anchorCenter.x - mContentView.getWidth() / 2f;
                location.y = anchorRect.top - mContentView.getHeight() - mMargin;
                break;
            case Gravity.BOTTOM:
                location.x = anchorCenter.x - mContentView.getWidth() / 2f;
                location.y = anchorRect.bottom + mMargin;
                break;
        }

        return location;
    }

    private final View.OnTouchListener mTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if ((isCancelable && event.getAction() == MotionEvent.ACTION_OUTSIDE) || (isDismissOnClick && event.getAction() == MotionEvent.ACTION_UP)) {
                dismiss();
                return true;
            }
            return false;
        }
    };

    private final ViewTreeObserver.OnGlobalLayoutListener mLocationLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            removeOnGlobalLayoutListener(mContentView, this);

            mContentView.getViewTreeObserver().addOnGlobalLayoutListener(mArrowLayoutListener);
            PointF location = calculateLocation();
            mPopupWindow.setClippingEnabled(true);
            mPopupWindow.update((int) location.x, (int) location.y, mPopupWindow.getWidth(), mPopupWindow.getHeight());
        }
    };

    private final ViewTreeObserver.OnGlobalLayoutListener mArrowLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            removeOnGlobalLayoutListener(mContentView, this);

            RectF anchorRect = calculateRectOnScreen(mAnchorView);
            RectF contentViewRect = calculateRectOnScreen(mContentView);
            float x, y;
            if (mGravity == Gravity.BOTTOM || mGravity == Gravity.TOP) {
                x = mContentView.getPaddingLeft() + dpToPx(2);
                float centerX = (contentViewRect.width() / 2f) - (mArrowView.getWidth() / 2f);
                float newX = centerX - (contentViewRect.centerX() - anchorRect.centerX());
                if (newX > x) {
                    if (newX + mArrowView.getWidth() + x > contentViewRect.width()) {
                        x = contentViewRect.width() - mArrowView.getWidth() - x;
                    } else {
                        x = newX;
                    }
                }
                y = mArrowView.getTop();
                y = y + (mGravity == Gravity.TOP ? -1 : +1);
            } else {
                y = mContentView.getPaddingTop() + dpToPx(2);
                float centerY = (contentViewRect.height() / 2f) - (mArrowView.getHeight() / 2f);
                float newY = centerY - (contentViewRect.centerY() - anchorRect.centerY());
                if (newY > y) {
                    if (newY + mArrowView.getHeight() + y > contentViewRect.height()) {
                        y = contentViewRect.height() - mArrowView.getHeight() - y;
                    } else {
                        y = newY;
                    }
                }
                x = mArrowView.getLeft();
                x = x + (mGravity == Gravity.START ? -1 : +1);
            }
            mArrowView.setX(x);
            mArrowView.setY(y);
        }
    };

    private final View.OnAttachStateChangeListener mOnAttachStateChangeListener = new View.OnAttachStateChangeListener() {
        @Override
        public void onViewAttachedToWindow(View v) {

        }

        @Override
        public void onViewDetachedFromWindow(View v) {
            dismiss();
        }
    };

    public static final class Builder {
        private boolean isDismissOnClick=true;
        private boolean isCancelable=true;

        private int mGravity=Gravity.BOTTOM;
        private int mBackgroundColor = 0x39302f;

        private float mCornerRadius=dpToPx(3);
        private float mArrowHeight;
        private float mArrowWidth;
        private float mMargin;
        private float mPadding;
        private String[] itemText;
        private
        @DrawableRes
        int[] itemLogo;

        private Drawable mArrowDrawable;
        private Context mContext;
        private View mAnchorView;
        private OnDismissListener mOnDismissListener;
        private OnItemClickListener mOnItemClickListener;

        public Builder(@NonNull MenuItem anchorMenuItem) {
            this(anchorMenuItem, 0);
        }

        public Builder(@NonNull MenuItem anchorMenuItem, @StyleRes int resId) {
            View anchorView = anchorMenuItem.getActionView();
            if (anchorView != null) {
                init(anchorView.getContext(), anchorView, resId);
            } else {
                throw new NullPointerException("anchor menuItem haven`t actionViewClass");
            }
        }

        public Builder(@NonNull View anchorView) {
            this(anchorView, 0);
        }

        public Builder(@NonNull View anchorView, @StyleRes int resId) {
            init(anchorView.getContext(), anchorView, resId);
        }

        private void init(@NonNull Context context, @NonNull View anchorView, @StyleRes int resId) {
            mContext = context;
            mAnchorView = anchorView;
        }

        /**
         * Sets whether Tooltip is cancelable or not. Default is {@code false}.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setCancelable(boolean cancelable) {
            isCancelable = cancelable;
            return this;
        }

        /**
         * Sets whether Tooltip is dismissing on click or not. Default is {@code false}.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setDismissOnClick(boolean isDismissOnClick) {
            this.isDismissOnClick = isDismissOnClick;
            return this;
        }

        /**
         * Sets Tooltip background drawable corner radius.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setCornerRadius(float radius) {
            mCornerRadius = radius;
            return this;
        }

        /**
         * Sets Tooltip arrow height from resource.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setArrowHeight(@DimenRes int resId) {
            return setArrowHeight(mContext.getResources().getDimension(resId));
        }

        /**
         * Sets Tooltip arrow height.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setArrowHeight(float height) {
            mArrowHeight = height;
            return this;
        }

        /**
         * Sets Tooltip arrow width from resource.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setArrowWidth(@DimenRes int resId) {
            return setArrowWidth(mContext.getResources().getDimension(resId));
        }

        /**
         * Sets Tooltip arrow width.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setArrowWidth(float width) {
            mArrowWidth = width;
            return this;
        }

        /**
         * Sets Tooltip arrow drawable from resources.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setArrow(@DrawableRes int resId) {
            return setArrow(ResourcesCompat.getDrawable(mContext.getResources(), resId, null));
        }

        /**
         * Sets Tooltip arrow drawable.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setArrow(Drawable arrowDrawable) {
            mArrowDrawable = arrowDrawable;
            return this;
        }

        /**
         * Sets Tooltip margin from resource.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setMargin(@DimenRes int resId) {
            return setMargin(mContext.getResources().getDimension(resId));
        }

        /**
         * Sets Tooltip margin.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setMargin(float margin) {
            mMargin = margin;
            return this;
        }

        /**
         * Sets Tooltip padding from resource.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setPadding(@DimenRes int resId) {
            return setPadding(mContext.getResources().getDimension(resId));
        }

        /**
         * Sets Tooltip padding.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setPadding(float padding) {
            mPadding = padding;
            return this;
        }

        /**
         * Sets Tooltip gravity.
         *
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder setGravity(int gravity) {
            mGravity = gravity;
            return this;
        }

        /**
         * Sets listener to be called when the Tooltip is dismissed.
         *
         * @param listener The listener.
         */
        public Builder setOnDismissListener(OnDismissListener listener) {
            mOnDismissListener = listener;
            return this;
        }

        public Builder setmOnItemClickListener(OnItemClickListener mOnItemClickListener) {
            this.mOnItemClickListener = mOnItemClickListener;
            return this;
        }

        /**
         * Creates a {@link Tooltip} with the arguments supplied to this builder. It does not
         * {@link Tooltip#show()} the tooltip. This allows the user to do any extra processing
         * before displaying the tooltip. Use {@link #show()} if you don't have any other processing
         * to do and want this to be created and displayed.
         */
        public Tooltip build() {
            if (!Gravity.isHorizontal(mGravity) && !Gravity.isVertical(mGravity)) {
                throw new IllegalArgumentException("Gravity must have be START, END, TOP or BOTTOM.");
            }

            mArrowHeight = dpToPx(7) - 1;
            mArrowWidth = dpToPx(12);
            if (mArrowDrawable == null) {
                mArrowDrawable = new ArrowDrawable(mBackgroundColor, mGravity);
            }
            if (mMargin == -1) {
                mMargin = 0;
            }
            mPadding = dpToPx(5);//5
            return new Tooltip(this);
        }

        /**
         * Builds a {@link Tooltip} with builder attributes and {@link Tooltip#show()}'s the tooltip.
         */
        public Tooltip show() {
            Tooltip tooltip = build();
            tooltip.show();
            return tooltip;
        }

        public Builder setItemText(String[] itemText, int[] itemLogo) {
            this.itemText = itemText;
            this.itemLogo = itemLogo;
            return this;
        }

        public Builder setItemText(String[] itemText) {
            this.itemText = itemText;
            return this;
        }
    }

    public static float dpToPx(float dp) {
        return dp * Resources.getSystem().getDisplayMetrics().density;
    }

    public static RectF calculateRectInWindow(View view) {
        int[] location = new int[2];
        view.getLocationInWindow(location);
        return new RectF(location[0], location[1], location[0] + view.getMeasuredWidth(), location[1] + view.getMeasuredHeight());
    }

    public static void removeOnGlobalLayoutListener(View view, ViewTreeObserver.OnGlobalLayoutListener listener) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
        } else {
            //noinspection deprecation
            view.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
        }
    }

    public static RectF calculateRectOnScreen(View view) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        return new RectF(location[0], location[1], location[0] + view.getMeasuredWidth(), location[1] + view.getMeasuredHeight());
    }
}


text:
import { __spreadArrays } from "tslib";
import { AnyT } from './type-descriptor';
export var LAZY_TYPE_EXPLANATION = "If the type is not yet defined, for example due to circular references, add '() => ' before it. E.g. @jsonMember(() => Foo)";
export var MISSING_REFLECT_CONF_MSG = 'Make sure that you have both "experimentalDecorators"'
    + ' and "emitDecoratorMetadata" enabled in your tsconfig.json';
export function isDirectlySerializableNativeType(type) {
    return [Date, Number, String, Boolean].indexOf(type) !== -1;
}
export function isDirectlyDeserializableNativeType(type) {
    return [Number, String, Boolean].indexOf(type) !== -1;
}
export function isTypeTypedArray(type) {
    return [
        Float32Array,
        Float64Array,
        Int8Array,
        Uint8Array,
        Uint8ClampedArray,
        Int16Array,
        Uint16Array,
        Int32Array,
        Uint32Array,
    ].indexOf(type) !== -1;
}
export function isObject(value) {
    return typeof value === 'object';
}
export function shouldOmitParseString(jsonStr, expectedType) {
    var expectsTypesSerializedAsStrings = expectedType === String
        || expectedType === ArrayBuffer
        || expectedType === DataView;
    var hasQuotes = jsonStr.length >= 2
        && jsonStr[0] === '"'
        && jsonStr[jsonStr.length - 1] === '"';
    if (expectedType === Date) {
        var isNumber = !isNaN(Number(jsonStr.trim()));
        return !hasQuotes && !isNumber;
    }
    return expectsTypesSerializedAsStrings && !hasQuotes;
}
export function parseToJSObject(json, expectedType) {
    if (typeof json !== 'string' || shouldOmitParseString(json, expectedType)) {
        return json;
    }
    return JSON.parse(json);
}
export function isSubtypeOf(A, B) {
    return A === B || A.prototype instanceof B;
}
export function logError(message) {
    var optionalParams = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        optionalParams[_i - 1] = arguments[_i];
    }
    if (typeof console === 'object' && typeof console.error === 'function') {
        console.error.apply(console, __spreadArrays([message], optionalParams));
    }
    else if (typeof console === 'object' && typeof console.log === 'function') {
        console.log.apply(console, __spreadArrays(["ERROR: " + message], optionalParams));
    }
}
export function logMessage(message) {
    var optionalParams = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        optionalParams[_i - 1] = arguments[_i];
    }
    if (typeof console === 'object' && typeof console.log === 'function') {
        console.log.apply(console, __spreadArrays([message], optionalParams));
    }
}
export function logWarning(message) {
    var optionalParams = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        optionalParams[_i - 1] = arguments[_i];
    }
    if (typeof console === 'object' && typeof console.warn === 'function') {
        console.warn.apply(console, __spreadArrays([message], optionalParams));
    }
    else if (typeof console === 'object' && typeof console.log === 'function') {
        console.log.apply(console, __spreadArrays(["WARNING: " + message], optionalParams));
    }
}
export function isValueDefined(value) {
    return !(typeof value === 'undefined' || value === null);
}
export function isInstanceOf(value, constructor) {
    if (constructor === AnyT.ctor) {
        return true;
    }
    else if (typeof value === 'number') {
        return constructor === Number;
    }
    else if (typeof value === 'string') {
        return constructor === String;
    }
    else if (typeof value === 'boolean') {
        return constructor === Boolean;
    }
    else if (isObject(value)) {
        return value instanceof constructor;
    }
    return false;
}
export var isReflectMetadataSupported = typeof Reflect === 'object' && typeof Reflect.getMetadata === 'function';
export function nameof(fn) {
    if (typeof fn.name === 'string') {
        return fn.name;
    }
    return 'undefined';
}
export function identity(arg) {
    return arg;
}
//# sourceMappingURL=helpers.js.map


text:
package com.google.javascript.refactoring;

import com.google.javascript.jscomp.NodeUtil;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import org.jspecify.nullness.Nullable;

/**
 * Class that contains common Matchers that are useful to everyone.
 */
public final class Matchers {
  // TODO(mknichel): Make sure all this code works with goog.scope.

  /**
   * Returns a Matcher that matches every node.
   */
  public static Matcher anything() {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        return true;
      }
    };
  }

  /**
   * Returns a Matcher that returns true only if all of the provided
   * matchers match.
   */
  public static Matcher allOf(final Matcher... matchers) {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        for (Matcher m : matchers) {
          if (!m.matches(node, metadata)) {
            return false;
          }
        }
        return true;
      }
    };
  }

  /**
   * Returns a Matcher that returns true if any of the provided matchers match.
   */
  public static Matcher anyOf(final Matcher... matchers) {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        for (Matcher m : matchers) {
          if (m.matches(node, metadata)) {
            return true;
          }
        }
        return false;
      }
    };
  }

  /**
   * Returns a Matcher that matches the opposite of the provided matcher.
   */
  public static Matcher not(final Matcher matcher) {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        return !matcher.matches(node, metadata);
      }
    };
  }

  /**
   * Returns a matcher that matches any constructor definitions.
   */
  public static Matcher constructor() {
    return constructor(null);
  }

  /**
   * Returns a matcher that matches constructor definitions of the specified name.
   *
   * @param name The name of the class constructor to match.
   */
  public static Matcher constructor(final @Nullable String name) {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        JSDocInfo info = node.getJSDocInfo();
        if (info != null && info.isConstructor()) {
          Node firstChild = node.getFirstChild();
          // TODO(mknichel): Make sure this works with the following cases:
          // ns = {
          //   /** @constructor */
          //   name: function() {}
          // }
          if (name == null) {
            return true;
          }
          if ((firstChild.isGetProp() || firstChild.isName())
              && firstChild.matchesQualifiedName(name)) {
            return true;
          }
        }
        return false;
      }
    };
  }

  /**
   * Returns a Matcher that matches constructing new objects. This will match
   * the NEW node of the JS Compiler AST.
   */
  public static Matcher newClass() {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        return node.isNew();
      }
    };
  }

  /**
   * Returns a Matcher that matches constructing objects of the provided class
   * name. This will match the NEW node of the JS Compiler AST.
   * @param className The name of the class to return matching NEW nodes.
   */
  public static Matcher newClass(final String className) {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        if (!node.isNew()) {
          return false;
        }
        JSType providedJsType = getJsType(metadata, className);
        if (providedJsType == null) {
          return false;
        }

        JSType jsType = node.getJSType();
        if (jsType == null) {
          return false;
        }
        jsType = jsType.restrictByNotNullOrUndefined();
        return areTypesEquivalentIgnoringGenerics(jsType, providedJsType);
      }
    };
  }

  /**
   * Returns a Matcher that matches any function call.
   */
  public static Matcher functionCall() {
    return functionCall(null);
  }

  /**
   * Returns a Matcher that matches all nodes that are function calls that match the provided name.
   *
   * @param name The name of the function to match. For non-static functions, this must be the fully
   *     qualified name that includes the type of the object. For instance: {@code
   *     ns.AppContext.prototype.get} will match {@code appContext.get} and {@code this.get} when
   *     called from the AppContext class.
   */
  public static Matcher functionCall(final @Nullable String name) {
    return new Matcher() {
      @Override
      public boolean matches(Node node, NodeMetadata metadata) {
        // TODO(mknichel): Handle the case when functions are applied through .call or .apply.
        return node.isCall() && propertyAccess(name).matches(node.getFirstChild(), metadata);
      }
    };
  }

  /**
   * Returns a Matcher that matches any function call that has the given
   * number of arguments.
   */
  public static Matcher functionCallWithNumArgs(final int numArgs) {
    return new Matcher() {
      @Override
      public boolean matches(Node node, NodeMetadata metadata) {
        return node.isCall() && node.hasXChildren(numArgs + 1);
      }
    };
  }

  /**
   * Returns a Matcher that matches any function call that has the given
   * number of arguments and the given name.
   * @param name The name of the function to match. For non-static functions,
   *     this must be the fully qualified name that includes the type of the
   *     object. For instance: {@code ns.AppContext.prototype.get} will match
   *     {@code appContext.get} and {@code this.get} when called from the
   *     AppContext class.
   */
  public static Matcher functionCallWithNumArgs(final String name, final int numArgs) {
    return allOf(functionCallWithNumArgs(numArgs), functionCall(name));
  }

  public static Matcher googRequirelike(final String namespace) {
    return (Node node, NodeMetadata metadata) ->
        googRequirelike().matches(node, metadata)
            && node.getSecondChild().isStringLit()
            && node.getSecondChild().getString().equals(namespace);
  }

  public static Matcher googRequirelike() {
    return anyOf(googRequire(), googRequireType(), googForwardDeclare());
  }

  public static Matcher googRequire() {
    return functionCall("goog.require");
  }

  public static Matcher googRequireType() {
    return functionCall("goog.requireType");
  }

  public static Matcher googForwardDeclare() {
    return functionCall("goog.forwardDeclare");
  }

  public static Matcher googModule() {
    return functionCall("goog.module");
  }

  public static Matcher googModuleOrProvide() {
    return anyOf(googModule(), functionCall("goog.provide"));
  }

  /**
   * Returns a Matcher that matches any property access.
   */
  public static Matcher propertyAccess() {
    return propertyAccess(null);
  }

  /**
   * Returns a Matcher that matches nodes representing a GETPROP access of an object property.
   *
   * @param name The name of the property to match. For non-static properties, this must be the
   *     fully qualified name that includes the type of the object. For instance: {@code
   *     ns.AppContext.prototype.root} will match {@code appContext.root} and {@code this.root} when
   *     accessed from the AppContext.
   */
  public static Matcher propertyAccess(final @Nullable String name) {
    return new Matcher() {
      @Override
      public boolean matches(Node node, NodeMetadata metadata) {
        if (node.isGetProp()) {
          if (name == null) {
            return true;
          }
          if (node.matchesQualifiedName(name)) {
            return true;
          } else if (name.contains(".prototype.")) {
            return matchesPrototypeInstanceVar(node, metadata, name);
          }
        }
        return false;
      }
    };
  }

  /**
   * Returns a Matcher that matches definitions of any enum.
   */
  public static Matcher enumDefinition() {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        JSType jsType = node.getJSType();
        return jsType != null && jsType.isEnumType();
      }
    };
  }

  /**
   * Returns a Matcher that matches definitions of an enum of the given type.
   */
  public static Matcher enumDefinitionOfType(final String type) {
    return new Matcher() {
      @Override
      public boolean matches(Node node, NodeMetadata metadata) {
        JSType providedJsType = getJsType(metadata, type);
        if (providedJsType == null) {
          return false;
        }
        providedJsType = providedJsType.restrictByNotNullOrUndefined();

        JSType jsType = node.getJSType();
        return jsType != null
            && jsType.isEnumType()
            && providedJsType.equals(jsType.toMaybeEnumType().getElementsType().getPrimitiveType());
      }
    };
  }

  /**
   * Returns a Matcher that matches an ASSIGN node where the RHS of the assignment matches the given
   * rhsMatcher.
   */
  public static Matcher assignmentWithRhs(final Matcher rhsMatcher) {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        return node.isAssign() && rhsMatcher.matches(node.getLastChild(), metadata);
      }
    };
  }

  /**
   * Returns a Matcher that matches a declaration of a variable on the
   * prototype of a class.
   */
  public static Matcher prototypeVariableDeclaration() {
    return matcherForPrototypeDeclaration(/* requireFunctionType= */ false);
  }

  /**
   * Returns a Matcher that matches a declaration of a method on the
   * prototype of a class.
   */
  public static Matcher prototypeMethodDeclaration() {
    return matcherForPrototypeDeclaration(/* requireFunctionType= */ true);
  }

  /**
   * Returns a Matcher that matches nodes that contain JS Doc that specify the
   * {@code @type} annotation equivalent to the provided type.
   */
  public static Matcher jsDocType(final String type) {
    return new Matcher() {
      @Override
      public boolean matches(Node node, NodeMetadata metadata) {
        JSType providedJsType = getJsType(metadata, type);
        if (providedJsType == null) {
          return false;
        }
        providedJsType = providedJsType.restrictByNotNullOrUndefined();
        // The JSDoc for a variable declaration is on the VAR/CONST/LET node, but the type only
        // exists on the NAME node.
        // TODO(mknichel): Make NodeUtil.getBestJSDoc public and use that.
        JSDocInfo jsDoc =
            NodeUtil.isNameDeclaration(node.getParent())
                ? node.getParent().getJSDocInfo()
                : node.getJSDocInfo();
        JSType jsType = node.getJSType();
        return jsDoc != null
            && jsDoc.hasType()
            && jsType != null
            && providedJsType.equals(jsType.restrictByNotNullOrUndefined());
      }
    };
  }

  /**
   * Returns a Matcher that matches against properties that are declared in the constructor.
   */
  public static Matcher constructorPropertyDeclaration() {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        // This will match against code that looks like:
        // /** @constructor */
        // function constructor() {
        //   this.variable = 3;
        // }
        if (!node.isAssign()
            || !node.getFirstChild().isGetProp()
            || !node.getFirstFirstChild().isThis()) {
          return false;
        }
        while (node != null && !node.isFunction()) {
          node = node.getParent();
        }
        if (node != null && node.isFunction()) {
          JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(node);
          if (jsDoc != null) {
            return jsDoc.isConstructor();
          }
        }
        return false;
      }
    };
  }

  /**
   * Returns a Matcher that matches against nodes that are declared {@code @private}.
   */
  public static Matcher isPrivate() {
    return new Matcher() {
      @Override public boolean matches(Node node, NodeMetadata metadata) {
        JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(node);
        if (jsDoc != null) {
          return jsDoc.getVisibility() == Visibility.PRIVATE;
        }
        return false;
      }
    };
  }

  private static JSType getJsType(NodeMetadata metadata, String type) {
    return metadata.getCompiler().getTypeRegistry().getGlobalType(type);
  }

  private static JSType getJsType(NodeMetadata metadata, JSTypeNative nativeType) {
    return metadata.getCompiler().getTypeRegistry().getNativeType(nativeType);
  }

  private static boolean areTypesEquivalentIgnoringGenerics(JSType a, JSType b) {
    boolean equivalent = a.equals(b);
    if (equivalent) {
      return true;
    }
    if (a.isTemplatizedType()) {
      return a.toMaybeTemplatizedType().getReferencedType().equals(b);
    }
    return false;
  }

  /**
   * Checks to see if the node represents an access of an instance variable
   * on an object given a prototype declaration of an object. For instance,
   * {@code ns.AppContext.prototype.get} will match {@code appContext.get}
   * or {@code this.get} when accessed from within the AppContext object.
   */
  private static boolean matchesPrototypeInstanceVar(Node node, NodeMetadata metadata,
      String name) {
    String[] parts = name.split(".prototype.");
    String className = parts[0];
    String propertyName = parts[1];
    JSType providedJsType = getJsType(metadata, className);
    if (providedJsType == null) {
      return false;
    }
    JSType jsType = null;
    if (node.hasChildren()) {
      jsType = node.getFirstChild().getJSType();
    }
    if (jsType == null) {
      return false;
    }
    jsType = jsType.restrictByNotNullOrUndefined();
    if (!jsType.isUnknownType()
        && !jsType.isAllType()
        && jsType.isSubtypeOf(providedJsType)) {
      if (node.isName() && propertyName.equals(node.getString())) {
        return true;
      } else if (node.isGetProp() && propertyName.equals(node.getString())) {
        return true;
      }
    }
    return false;
  }

  private static Matcher matcherForPrototypeDeclaration(final boolean requireFunctionType) {
    return new Matcher() {
      @Override
      public boolean matches(Node node, NodeMetadata metadata) {
        // TODO(mknichel): Figure out which node is the best to return for this
        // function: the GETPROP node, or the ASSIGN node when the property is
        // being assigned to.
        // TODO(mknichel): Support matching:
        // foo.prototype = {
        //   bar: 1
        // };
        Node firstChild = node.getFirstChild();
        if (node.isGetProp()
            && firstChild.isGetProp()
            && "prototype".equals(firstChild.getString())) {
          JSType fnJsType = getJsType(metadata, JSTypeNative.FUNCTION_FUNCTION_TYPE);
          JSType jsType = node.getJSType();
          if (jsType == null) {
            return false;
          } else if (requireFunctionType) {
            return jsType.canCastTo(fnJsType);
          } else {
            return !jsType.canCastTo(fnJsType);
          }
        }
        return false;
      }
    };
  }

  // TODO(mknichel): Add matchers for:
  // - Constructor with argument types
  // - Function call with argument types
  // - Function definitions.
  // - Property definitions, references
  // - IsStatic
  // - JsDocMatcher

  /** Prevent instantiation. */
  private Matchers() {}
}


text:
using Abot.Util;
using NUnit.Framework;
using System;
using System.Threading;

namespace Abot.Tests.Unit.Util
{
    [TestFixture]
    public abstract class ThreadManagerTest
    {
        IThreadManager _unitUnderTest;
        const int MAXTHREADS = 10;
        protected abstract IThreadManager GetInstance(int maxThreads);

        [SetUp]
        public void SetUp()
        {
            _unitUnderTest = GetInstance(MAXTHREADS);
        }

        [TearDown]
        public void TearDown()
        {
            if (_unitUnderTest != null)
                _unitUnderTest.Dispose();
        }

        [Test]
        public void Constructor_CreatesDefaultInstance()
        {
            Assert.IsNotNull(_unitUnderTest);
            Assert.AreEqual(MAXTHREADS, _unitUnderTest.MaxThreads);
        }

        [Test]
        [ExpectedException(typeof(ArgumentException))]
        public void Constructor_OverMax()
        {
            _unitUnderTest = GetInstance(101);
        }

        [Test]
        [ExpectedException(typeof(ArgumentException))]
        public void Constructor_BelowMinimum()
        {
            _unitUnderTest = GetInstance(0);
        }

        [Test]
        public void HasRunningThreads()
        {
            //No threads should be running
            Assert.IsFalse(_unitUnderTest.HasRunningThreads());

            //Add word to be run on a thread
            _unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(300));
            System.Threading.Thread.Sleep(20);

            //Should have 1 running thread
            Assert.IsTrue(_unitUnderTest.HasRunningThreads());

            //Wait for the 1 running thread to finish
            System.Threading.Thread.Sleep(400);

            //Should have 0 threads running since the thread should have completed by now
            Assert.IsFalse(_unitUnderTest.HasRunningThreads());
        }

        [Test]
        public void DoWork_WorkItemsEqualToThreads_WorkIsCompletedAsync()
        {
            int count = 0;

            for (int i = 0; i < MAXTHREADS; i++)
            {
                _unitUnderTest.DoWork(() =>
                {
                    System.Threading.Thread.Sleep(5);
                    Interlocked.Increment(ref count);
                });
            }

            Assert.IsTrue(count < MAXTHREADS);
            System.Threading.Thread.Sleep(80);//was 20 but had to bump it up or the TaskThreadManager would fail, its way slower
            Assert.AreEqual(MAXTHREADS, count);
        }

        [Test]
        public void DoWork_MoreWorkThenThreads_WorkIsCompletedAsync()
        {
            int count = 0;
            for (int i = 0; i < 2 * MAXTHREADS; i++)
            {
                _unitUnderTest.DoWork(() =>
                {
                    System.Threading.Thread.Sleep(5);
                    Interlocked.Increment(ref count);
                });
            }

            //Assert.IsTrue(count < MAXTHREADS);//Manual has completed more then the thread count by the time it gets here
            System.Threading.Thread.Sleep(80);//was 20 but had to bump it up or the TaskThreadManager would fail, its way slower
            Assert.AreEqual(2 * MAXTHREADS, count);
        }

        [Test]
        public void DoWork_SingleThreaded_WorkIsCompletedSynchronously()
        {
            _unitUnderTest = GetInstance(1);

            int count = 0;
            for (int i = 0; i < MAXTHREADS; i++)
            {
                _unitUnderTest.DoWork(() =>
                {
                    System.Threading.Thread.Sleep(5);
                    Interlocked.Increment(ref count);
                });
            }

            Assert.AreEqual(MAXTHREADS, count);
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void DoWork_ActionIsNull()
        {
            _unitUnderTest.DoWork(null);
        }

        [Test]
        [ExpectedException(typeof(InvalidOperationException))]
        public void DoWork_CalledAfterAbortAll()
        {
            _unitUnderTest.AbortAll();
            _unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(10));
        }

        [Test]
        public void Dispose()
        {
            Assert.IsTrue(_unitUnderTest is IDisposable);
        }

        [Test]
        public void Abort_SetsHasRunningThreadsToZero()
        {
            for (int i = 0; i < 2 * MAXTHREADS; i++)
            {
                _unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(5));
            }

            _unitUnderTest.AbortAll();
            Assert.IsFalse(_unitUnderTest.HasRunningThreads());
        }
    }
}


text:
/**
 * Created by CCristi on 2/16/17.
 */

'use strict';

module.exports = class Replicate {
  constructor(replicaTable) {
    this._replicaTable = replicaTable;
  }

  get replicaTable() {
    return this._replicaTable;
  }

  replicate(records) {
    return new Promise((resolve, reject) => reject(new Error(`${this.constructor.name}.replicate() not implemented.`)));
  }

  _calculateBackoffTimeout(timeout) {
    return timeout ? (timeout * 2 + Math.round(Math.random() * 1000)) : 1000;
  }

  _isDynamodbErrorToSkip(error) {
    return Replicate.ERRORS_TO_SKIP.indexOf(error.code) !== -1;
  }

  static get ERRORS_TO_SKIP() {
    return [
      'MultipleValidationErrors',
      'ValidationException',
      'ResourceNotFoundException',
      'ItemCollectionSizeLimitExceededException',
      'ConditionalCheckFailedException',
    ];
  }
};


text:
namespace crypto {
namespace tink {
namespace subtle {

class AesCmacBoringSsl : public Mac {
 public:
  static crypto::tink::util::StatusOr<std::unique_ptr<Mac>> New(
      util::SecretData key, uint32_t tag_size);

  // Computes and returns the CMAC for 'data'.
  crypto::tink::util::StatusOr<std::string> ComputeMac(
      absl::string_view data) const override;

  // Verifies if 'mac' is a correct CMAC for 'data'.
  // Returns Status::OK if 'mac' is correct, and a non-OK-Status otherwise.
  crypto::tink::util::Status VerifyMac(absl::string_view mac,
                                       absl::string_view data) const override;

  static constexpr crypto::tink::internal::FipsCompatibility kFipsStatus =
      crypto::tink::internal::FipsCompatibility::kNotFips;

 private:
  AesCmacBoringSsl(util::SecretData key, uint32_t tag_size)
      : key_(std::move(key)), tag_size_(tag_size) {}

  const util::SecretData key_;
  const uint32_t tag_size_;
};

}  // namespace subtle
}  // namespace tink
}  // namespace crypto

#endif  // TINK_SUBTLE_AES_CMAC_BORINGSSL_H_