text:
"""
This module contains code for dealing with associations between
consumers and servers. Associations contain a shared secret that is
used to sign C{openid.mode=id_res} messages.

Users of the library should not usually need to interact directly with
associations. The L{store<openid.store>}, L{server<openid.server.server>}
and L{consumer<openid.consumer.consumer>} objects will create and manage
the associations. The consumer and server code will make use of a
C{L{SessionNegotiator}} when managing associations, which enables
users to express a preference for what kind of associations should be
allowed, and what kind of exchange should be done to establish the
association.

@var default_negotiator: A C{L{SessionNegotiator}} that allows all
    association types that are specified by the OpenID
    specification. It prefers to use HMAC-SHA1/DH-SHA1, if it's
    available. If HMAC-SHA256 is not supported by your Python runtime,
    HMAC-SHA256 and DH-SHA256 will not be available.

@var encrypted_negotiator: A C{L{SessionNegotiator}} that
    does not support C{'no-encryption'} associations. It prefers
    HMAC-SHA1/DH-SHA1 association types if available.
"""

__all__ = [
    'default_negotiator',
    'encrypted_negotiator',
    'SessionNegotiator',
    'Association',
]

import time

from openid import cryptutil
from openid import kvform
from openid import oidutil
from openid.message import OPENID_NS

all_association_types = [
    'HMAC-SHA1',
    'HMAC-SHA256',
]

if hasattr(cryptutil, 'hmacSha256'):
    supported_association_types = list(all_association_types)

    default_association_order = [
        ('HMAC-SHA1', 'DH-SHA1'),
        ('HMAC-SHA1', 'no-encryption'),
        ('HMAC-SHA256', 'DH-SHA256'),
        ('HMAC-SHA256', 'no-encryption'),
    ]

    only_encrypted_association_order = [
        ('HMAC-SHA1', 'DH-SHA1'),
        ('HMAC-SHA256', 'DH-SHA256'),
    ]
else:
    supported_association_types = ['HMAC-SHA1']

    default_association_order = [
        ('HMAC-SHA1', 'DH-SHA1'),
        ('HMAC-SHA1', 'no-encryption'),
    ]

    only_encrypted_association_order = [
        ('HMAC-SHA1', 'DH-SHA1'),
    ]

def getSessionTypes(assoc_type):
    """Return the allowed session types for a given association type"""
    assoc_to_session = {
        'HMAC-SHA1': ['DH-SHA1', 'no-encryption'],
        'HMAC-SHA256': ['DH-SHA256', 'no-encryption'],
        }
    return assoc_to_session.get(assoc_type, [])

def checkSessionType(assoc_type, session_type):
    """Check to make sure that this pair of assoc type and session
    type are allowed"""
    if session_type not in getSessionTypes(assoc_type):
        raise ValueError(
            'Session type %r not valid for assocation type %r'
            % (session_type, assoc_type))

class SessionNegotiator(object):
    """A session negotiator controls the allowed and preferred
    association types and association session types. Both the
    C{L{Consumer<openid.consumer.consumer.Consumer>}} and
    C{L{Server<openid.server.server.Server>}} use negotiators when
    creating associations.

    You can create and use negotiators if you:

     - Do not want to do Diffie-Hellman key exchange because you use
       transport-layer encryption (e.g. SSL)

     - Want to use only SHA-256 associations

     - Do not want to support plain-text associations over a non-secure
       channel

    It is up to you to set a policy for what kinds of associations to
    accept. By default, the library will make any kind of association
    that is allowed in the OpenID 2.0 specification.

    Use of negotiators in the library
    =================================

    When a consumer makes an association request, it calls
    C{L{getAllowedType}} to get the preferred association type and
    association session type.

    The server gets a request for a particular association/session
    type and calls C{L{isAllowed}} to determine if it should
    create an association. If it is supported, negotiation is
    complete. If it is not, the server calls C{L{getAllowedType}} to
    get an allowed association type to return to the consumer.

    If the consumer gets an error response indicating that the
    requested association/session type is not supported by the server
    that contains an assocation/session type to try, it calls
    C{L{isAllowed}} to determine if it should try again with the
    given combination of association/session type.

    @ivar allowed_types: A list of association/session types that are
        allowed by the server. The order of the pairs in this list
        determines preference. If an association/session type comes
        earlier in the list, the library is more likely to use that
        type.
    @type allowed_types: [(str, str)]
    """

    def __init__(self, allowed_types):
        self.setAllowedTypes(allowed_types)

    def copy(self):
        return self.__class__(list(self.allowed_types))

    def setAllowedTypes(self, allowed_types):
        """Set the allowed association types, checking to make sure
        each combination is valid."""
        for (assoc_type, session_type) in allowed_types:
            checkSessionType(assoc_type, session_type)

        self.allowed_types = allowed_types

    def addAllowedType(self, assoc_type, session_type=None):
        """Add an association type and session type to the allowed
        types list. The assocation/session pairs are tried in the
        order that they are added."""
        if self.allowed_types is None:
            self.allowed_types = []

        if session_type is None:
            available = getSessionTypes(assoc_type)

            if not available:
                raise ValueError('No session available for association type %r'
                                 % (assoc_type,))

            for session_type in getSessionTypes(assoc_type):
                self.addAllowedType(assoc_type, session_type)
        else:
            checkSessionType(assoc_type, session_type)
            self.allowed_types.append((assoc_type, session_type))

    def isAllowed(self, assoc_type, session_type):
        """Is this combination of association type and session type allowed?"""
        assoc_good = (assoc_type, session_type) in self.allowed_types
        matches = session_type in getSessionTypes(assoc_type)
        return assoc_good and matches

    def getAllowedType(self):
        """Get a pair of assocation type and session type that are
        supported"""
        try:
            return self.allowed_types[0]
        except IndexError:
            return (None, None)

default_negotiator = SessionNegotiator(default_association_order)
encrypted_negotiator = SessionNegotiator(only_encrypted_association_order)

def getSecretSize(assoc_type):
    if assoc_type == 'HMAC-SHA1':
        return 20
    elif assoc_type == 'HMAC-SHA256':
        return 32
    else:
        raise ValueError('Unsupported association type: %r' % (assoc_type,))

class Association(object):
    """
    This class represents an association between a server and a
    consumer.  In general, users of this library will never see
    instances of this object.  The only exception is if you implement
    a custom C{L{OpenIDStore<openid.store.interface.OpenIDStore>}}.

    If you do implement such a store, it will need to store the values
    of the C{L{handle}}, C{L{secret}}, C{L{issued}}, C{L{lifetime}}, and
    C{L{assoc_type}} instance variables.

    @ivar handle: This is the handle the server gave this association.

    @type handle: C{str}

    @ivar secret: This is the shared secret the server generated for
        this association.

    @type secret: C{str}

    @ivar issued: This is the time this association was issued, in
        seconds since 00:00 GMT, January 1, 1970.  (ie, a unix
        timestamp)

    @type issued: C{int}

    @ivar lifetime: This is the amount of time this association is
        good for, measured in seconds since the association was
        issued.

    @type lifetime: C{int}

    @ivar assoc_type: This is the type of association this instance
        represents.  The only valid value of this field at this time
        is C{'HMAC-SHA1'}, but new types may be defined in the future.

    @type assoc_type: C{str}

    @sort: __init__, fromExpiresIn, expiresIn, __eq__, __ne__,
        handle, secret, issued, lifetime, assoc_type
    """

    # The ordering and name of keys as stored by serialize
    assoc_keys = [
        'version',
        'handle',
        'secret',
        'issued',
        'lifetime',
        'assoc_type',
    ]

    _macs = {
        'HMAC-SHA1': cryptutil.hmacSha1,
        'HMAC-SHA256': cryptutil.hmacSha256,
    }

    @classmethod
    def fromExpiresIn(cls, expires_in, handle, secret, assoc_type):
        """
        This is an alternate constructor used by the OpenID consumer
        library to create associations.  C{L{OpenIDStore
        <openid.store.interface.OpenIDStore>}} implementations
        shouldn't use this constructor.

        @param expires_in: This is the amount of time this association
            is good for, measured in seconds since the association was
            issued.

        @type expires_in: C{int}

        @param handle: This is the handle the server gave this
            association.

        @type handle: C{str}

        @param secret: This is the shared secret the server generated
            for this association.

        @type secret: C{str}

        @param assoc_type: This is the type of association this
            instance represents.  The only valid value of this field
            at this time is C{'HMAC-SHA1'}, but new types may be
            defined in the future.

        @type assoc_type: C{str}
        """
        issued = int(time.time())
        lifetime = expires_in
        return cls(handle, secret, issued, lifetime, assoc_type)

    def __init__(self, handle, secret, issued, lifetime, assoc_type):
        """
        This is the standard constructor for creating an association.

        @param handle: This is the handle the server gave this
            association.

        @type handle: C{str}

        @param secret: This is the shared secret the server generated
            for this association.

        @type secret: C{str}

        @param issued: This is the time this association was issued,
            in seconds since 00:00 GMT, January 1, 1970.  (ie, a unix
            timestamp)

        @type issued: C{int}

        @param lifetime: This is the amount of time this association
            is good for, measured in seconds since the association was
            issued.

        @type lifetime: C{int}

        @param assoc_type: This is the type of association this
            instance represents.  The only valid value of this field
            at this time is C{'HMAC-SHA1'}, but new types may be
            defined in the future.

        @type assoc_type: C{str}
        """
        if assoc_type not in all_association_types:
            fmt = '%r is not a supported association type'
            raise ValueError(fmt % (assoc_type,))

        # secret_size = getSecretSize(assoc_type)
        # if len(secret) != secret_size:
        #     fmt = 'Wrong size secret (%s bytes) for association type %s'
        #     raise ValueError(fmt % (len(secret), assoc_type))

        self.handle = handle

        if isinstance(secret, str):
            secret = secret.encode("utf-8")  # should be bytes
        self.secret = secret

        self.issued = issued
        self.lifetime = lifetime
        self.assoc_type = assoc_type

    @property
    def expiresIn(self, now=None):
        """
        This returns the number of seconds this association is still
        valid for, or C{0} if the association is no longer valid.

        @return: The number of seconds this association is still valid
            for, or C{0} if the association is no longer valid.

        @rtype: C{int}
        """
        if now is None:
            now = int(time.time())

        return max(0, self.issued + self.lifetime - now)

    def __eq__(self, other):
        """
        This checks to see if two C{L{Association}} instances
        represent the same association.

        @return: C{True} if the two instances represent the same
            association, C{False} otherwise.

        @rtype: C{bool}
        """
        return type(self) is type(other) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        This checks to see if two C{L{Association}} instances
        represent different associations.

        @return: C{True} if the two instances represent different
            associations, C{False} otherwise.

        @rtype: C{bool}
        """
        return not (self == other)

    def serialize(self):
        """
        Convert an association to KV form.

        @return: String in KV form suitable for deserialization by
            deserialize.

        @rtype: str
        """
        data = {
            'version': '2',
            'handle': self.handle,
            'secret': oidutil.toBase64(self.secret),
            'issued': str(int(self.issued)),
            'lifetime': str(int(self.lifetime)),
            'assoc_type': self.assoc_type
        }

        assert len(data) == len(self.assoc_keys)

        pairs = []
        for field_name in self.assoc_keys:
            pairs.append((field_name, data[field_name]))

        return kvform.seqToKV(pairs, strict=True)

    @classmethod
    def deserialize(cls, assoc_s):
        """
        Parse an association as stored by serialize().

        inverse of serialize

        @param assoc_s: Association as serialized by serialize()
        @type assoc_s: bytes

        @return: instance of this class
        """
        pairs = kvform.kvToSeq(assoc_s, strict=True)
        keys = []
        values = []
        for k, v in pairs:
            keys.append(k)
            values.append(v)

        if keys != cls.assoc_keys:
            raise ValueError('Unexpected key values: %r', keys)

        version, handle, secret, issued, lifetime, assoc_type = values
        if version != '2':
            raise ValueError('Unknown version: %r' % version)
        issued = int(issued)
        lifetime = int(lifetime)
        secret = oidutil.fromBase64(secret)
        return cls(handle, secret, issued, lifetime, assoc_type)

    def sign(self, pairs):
        """
        Generate a signature for a sequence of (key, value) pairs

        @param pairs: The pairs to sign, in order
        @type pairs: sequence of (str, str)

        @return: The binary signature of this sequence of pairs
        @rtype: bytes
        """
        kv = kvform.seqToKV(pairs)

        try:
            mac = self._macs[self.assoc_type]
        except KeyError:
            raise ValueError(
                'Unknown association type: %r' % (self.assoc_type,))

        return mac(self.secret, kv)

    def getMessageSignature(self, message):
        """Return the signature of a message.

        If I am not a sign-all association, the message must have a
        signed list.

        @return: the signature, base64 encoded

        @rtype: bytes

        @raises ValueError: If there is no signed list and I am not a sign-all
            type of association.
        """
        pairs = self._makePairs(message)
        return oidutil.toBase64(self.sign(pairs))

    def signMessage(self, message):
        """Add a signature (and a signed list) to a message.

        @return: a new Message object with a signature
        @rtype: L{openid.message.Message}
        """
        if (message.hasKey(OPENID_NS, 'sig') or
            message.hasKey(OPENID_NS, 'signed')):
            raise ValueError('Message already has signed list or signature')

        extant_handle = message.getArg(OPENID_NS, 'assoc_handle')
        if extant_handle and extant_handle != self.handle:
            raise ValueError("Message has a different association handle")

        signed_message = message.copy()
        signed_message.setArg(OPENID_NS, 'assoc_handle', self.handle)
        message_keys = list(signed_message.toPostArgs().keys())
        signed_list = [k[7:] for k in message_keys
                       if k.startswith('openid.')]
        signed_list.append('signed')
        signed_list.sort()
        signed_message.setArg(OPENID_NS, 'signed', ','.join(signed_list))
        sig = self.getMessageSignature(signed_message)
        signed_message.setArg(OPENID_NS, 'sig', sig)
        return signed_message

    def checkMessageSignature(self, message):
        """Given a message with a signature, calculate a new signature
        and return whether it matches the signature in the message.

        @raises ValueError: if the message has no signature or no signature
            can be calculated for it.
        """
        message_sig = message.getArg(OPENID_NS, 'sig')
        if not message_sig:
            raise ValueError("%s has no sig." % (message,))
        calculated_sig = self.getMessageSignature(message)
        # remember, getMessageSignature returns bytes
        calculated_sig = calculated_sig.decode('utf-8')
        return cryptutil.const_eq(calculated_sig, message_sig)

    def _makePairs(self, message):
        signed = message.getArg(OPENID_NS, 'signed')
        if not signed:
            raise ValueError('Message has no signed list: %s' % (message,))

        signed_list = signed.split(',')
        pairs = []
        data = message.toPostArgs()
        for field in signed_list:
            pairs.append((field, data.get('openid.' + field, '')))
        return pairs

    def __repr__(self):
        return "<%s.%s %s %s>" % (
            self.__class__.__module__,
            self.__class__.__name__,
            self.assoc_type,
            self.handle)


text:
from django.contrib import admin
from pmtour.models import Player, Tournament, Log, Turn

models = (
    Player,
    Tournament,
    Log,
    Turn
)
for model in models:
    admin.site.register(model)

redpajama_set_name: RedPajamaGithub


text:
from abc import ABCMeta, abstractmethod

class PatcherInterface:
    __metaclass__=ABCMeta

    @abstractmethod
    def patch(self):
        pass


text:
package reads

import (
	"regexp"

	"github.com/influxdata/influxdb/v2/storage/reads/datatypes"
	"github.com/influxdata/influxql"
	"github.com/pkg/errors"
)

const (
	fieldRef = "$"
)

// NodeToExpr transforms a predicate node to an influxql.Expr.
func NodeToExpr(node *datatypes.Node, remap map[string]string) (influxql.Expr, error) {
	v := &nodeToExprVisitor{remap: remap}
	WalkNode(v, node)
	if err := v.Err(); err != nil {
		return nil, err
	}

	if len(v.exprs) > 1 {
		return nil, errors.New("invalid expression")
	}

	if len(v.exprs) == 0 {
		return nil, nil
	}

	// TODO(edd): It would be preferable if RewriteRegexConditions was a
	// package level function in influxql.
	stmt := &influxql.SelectStatement{
		Condition: v.exprs[0],
	}
	stmt.RewriteRegexConditions()
	return stmt.Condition, nil
}

type nodeToExprVisitor struct {
	remap map[string]string
	exprs []influxql.Expr
	err   error
}

func (v *nodeToExprVisitor) Visit(n *datatypes.Node) NodeVisitor {
	if v.err != nil {
		return nil
	}

	switch n.NodeType {
	case datatypes.NodeTypeLogicalExpression:
		if len(n.Children) > 1 {
			op := influxql.AND
			if n.GetLogical() == datatypes.LogicalOr {
				op = influxql.OR
			}

			WalkNode(v, n.Children[0])
			if v.err != nil {
				return nil
			}

			for i := 1; i < len(n.Children); i++ {
				WalkNode(v, n.Children[i])
				if v.err != nil {
					return nil
				}

				if len(v.exprs) >= 2 {
					lhs, rhs := v.pop2()
					v.exprs = append(v.exprs, &influxql.BinaryExpr{LHS: lhs, Op: op, RHS: rhs})
				}
			}

			return nil
		}

	case datatypes.NodeTypeParenExpression:
		if len(n.Children) != 1 {
			v.err = errors.New("parenExpression expects one child")
			return nil
		}

		WalkNode(v, n.Children[0])
		if v.err != nil {
			return nil
		}

		if len(v.exprs) > 0 {
			v.exprs = append(v.exprs, &influxql.ParenExpr{Expr: v.pop()})
		}

		return nil

	case datatypes.NodeTypeComparisonExpression:
		WalkChildren(v, n)

		if len(v.exprs) < 2 {
			v.err = errors.New("comparisonExpression expects two children")
			return nil
		}

		lhs, rhs := v.pop2()

		be := &influxql.BinaryExpr{LHS: lhs, RHS: rhs}
		switch n.GetComparison() {
		case datatypes.ComparisonEqual:
			be.Op = influxql.EQ
		case datatypes.ComparisonNotEqual:
			be.Op = influxql.NEQ
		case datatypes.ComparisonStartsWith:
			// TODO(sgc): rewrite to anchored RE, as index does not support startsWith yet
			v.err = errors.New("startsWith not implemented")
			return nil
		case datatypes.ComparisonRegex:
			be.Op = influxql.EQREGEX
		case datatypes.ComparisonNotRegex:
			be.Op = influxql.NEQREGEX
		case datatypes.ComparisonLess:
			be.Op = influxql.LT
		case datatypes.ComparisonLessEqual:
			be.Op = influxql.LTE
		case datatypes.ComparisonGreater:
			be.Op = influxql.GT
		case datatypes.ComparisonGreaterEqual:
			be.Op = influxql.GTE
		default:
			v.err = errors.New("invalid comparison operator")
			return nil
		}

		v.exprs = append(v.exprs, be)

		return nil

	case datatypes.NodeTypeTagRef:
		ref := n.GetTagRefValue()
		if v.remap != nil {
			if nk, ok := v.remap[ref]; ok {
				ref = nk
			}
		}

		v.exprs = append(v.exprs, &influxql.VarRef{Val: ref, Type: influxql.Tag})
		return nil

	case datatypes.NodeTypeFieldRef:
		v.exprs = append(v.exprs, &influxql.VarRef{Val: fieldRef})
		return nil

	case datatypes.NodeTypeLiteral:
		switch val := n.Value.(type) {
		case *datatypes.Node_StringValue:
			v.exprs = append(v.exprs, &influxql.StringLiteral{Val: val.StringValue})

		case *datatypes.Node_RegexValue:
			// TODO(sgc): consider hashing the RegexValue and cache compiled version
			re, err := regexp.Compile(val.RegexValue)
			if err != nil {
				v.err = err
			}
			v.exprs = append(v.exprs, &influxql.RegexLiteral{Val: re})
			return nil

		case *datatypes.Node_IntegerValue:
			v.exprs = append(v.exprs, &influxql.IntegerLiteral{Val: val.IntegerValue})

		case *datatypes.Node_UnsignedValue:
			v.exprs = append(v.exprs, &influxql.UnsignedLiteral{Val: val.UnsignedValue})

		case *datatypes.Node_FloatValue:
			v.exprs = append(v.exprs, &influxql.NumberLiteral{Val: val.FloatValue})

		case *datatypes.Node_BooleanValue:
			v.exprs = append(v.exprs, &influxql.BooleanLiteral{Val: val.BooleanValue})

		default:
			v.err = errors.New("unexpected literal type")
			return nil
		}

		return nil

	default:
		return v
	}
	return nil
}

func (v *nodeToExprVisitor) Err() error {
	return v.err
}

func (v *nodeToExprVisitor) pop() influxql.Expr {
	if len(v.exprs) == 0 {
		panic("stack empty")
	}

	var top influxql.Expr
	top, v.exprs = v.exprs[len(v.exprs)-1], v.exprs[:len(v.exprs)-1]
	return top
}

func (v *nodeToExprVisitor) pop2() (influxql.Expr, influxql.Expr) {
	if len(v.exprs) < 2 {
		panic("stack empty")
	}

	rhs := v.exprs[len(v.exprs)-1]
	lhs := v.exprs[len(v.exprs)-2]
	v.exprs = v.exprs[:len(v.exprs)-2]
	return lhs, rhs
}

func IsTrueBooleanLiteral(expr influxql.Expr) bool {
	b, ok := expr.(*influxql.BooleanLiteral)
	if ok {
		return b.Val
	}
	return false
}

func RewriteExprRemoveFieldValue(expr influxql.Expr) influxql.Expr {
	return influxql.RewriteExpr(expr, func(expr influxql.Expr) influxql.Expr {
		if be, ok := expr.(*influxql.BinaryExpr); ok {
			if ref, ok := be.LHS.(*influxql.VarRef); ok {
				if ref.Val == fieldRef {
					return &influxql.BooleanLiteral{Val: true}
				}
			}
		}

		return expr
	})
}

type hasRefs struct {
	refs  []string
	found []bool
}

func (v *hasRefs) allFound() bool {
	for _, val := range v.found {
		if !val {
			return false
		}
	}
	return true
}

func (v *hasRefs) Visit(node influxql.Node) influxql.Visitor {
	if v.allFound() {
		return nil
	}

	if n, ok := node.(*influxql.VarRef); ok {
		for i, r := range v.refs {
			if !v.found[i] && r == n.Val {
				v.found[i] = true
				if v.allFound() {
					return nil
				}
			}
		}
	}
	return v
}

func HasFieldValueKey(expr influxql.Expr) bool {
	refs := hasRefs{refs: []string{fieldRef}, found: make([]bool, 1)}
	influxql.Walk(&refs, expr)
	return refs.found[0]
}


text:
GOPATHP?=$(PWD)/../../../../..
GOPATHD?=$(HOME)/go

PB_HOME?=rabbitmq-operator
BIN_NAME?=rabbitmq-operator
IMG_NS?=docker.io/tangfeixiong
IMG_REPO?=rabbitmq-operator
IMG_TAG?=latest

GIT_COMMIT=$(shell date +%y%m%d%H%M)-git$(shell git rev-parse --short=7 HEAD)

DOCKER_FILE?=Dockerfile.busybox
DOCKER_REGISTRY?=172.17.4.59:5000/admin

all: protoc-grpc go-bindata-artifacts docker-push

protoc-grpc:
	@if [[ ! -e $(GOPATHD) ]] ; \
	then \
		ln -sf /Users/fanhongling/go $(GOPATHD) ; \
	fi

	@protoc -I/usr/local/include -I. \
		-I${GOPATHP}/src \
		-I${GOPATHD}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
		-I${GOPATHD}/src/github.com/gogo/protobuf \
		-I${GOPATHD}/src \
		--gogo_out=Mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto,Mpb/datatype.proto=github.com/tangfeixiong/go-to-kubernetes/$(PB_HOME)/pb,plugins=grpc:. \
		pb/service.proto pb/datatype.proto
	@protoc -I/usr/local/include -I. \
		-I${GOPATHP}/src \
		-I${GOPATHD}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
		-I${GOPATHD}/src/github.com/gogo/protobuf \
		-I${GOPATHD}/src \
		--grpc-gateway_out=logtostderr=true:. \
		pb/service.proto

go-bindata-web:
	@pkg=webapp; src=static/...; output_file=pkg/ui/data/$${pkg}/datafile.go; \
		go-bindata -nocompress -o $${output_file} -prefix $${PWD} -pkg $${pkg} $${src}

go-bindata-artifacts:
	@pkg=artifact; src=template/...; output_file=pkg/spec/$${pkg}/artifacts.go; \
		go-bindata -nocompress -o $${output_file} -prefix $${PWD} -pkg $${pkg} $${src}

go-build: go-bindata-artifacts
	#@CGO_ENABLED=0 go build -a -v -o ./bin/$(BIN_NAME) --installsuffix cgo -ldflags "-s" ./
	@CGO_ENABLED=0 go build -a -v -o ./bin/$(BIN_NAME) -ldflags '-extldflags "-static"' ./

go-install: go-bindata-artifacts
	@go install -v ./

docker-build: go-build
	#@docker build --no-cache --force-rm -t $(IMG_NS)/$(IMG_REPO):$(GIT_COMMIT) ./
	@docker build --no-cache --force-rm -t $(IMG_NS)/$(IMG_REPO):$(IMG_TAG) -f $(DOCKER_FILE) ./

docker-push: docker-build
	@docker push $(IMG_NS)/$(IMG_REPO):$(IMG_TAG)

.PHONY: all protoc-grpc go-bindata-artifacts go-build go-install docker-build docker-push


text:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.Linq;
using WSCData.Migrations.Seed;
using WSCData.Models;
using WSCData.Models.Entities;
using WSCTools.WSCExceptions;
using static WSCData.Utils.WSCConsts;

namespace WSCData.Migrations.BasicSeeders
{
    class UsersSeeder : IDataSeeder
    {
        private List<UserWrapper> _users = new List<UserWrapper>
        {
            new UserWrapper {UserName = "bz", Email="bz@ss.pl", Password="123", Role=ROLES.ADMIN},
            new UserWrapper {UserName = "mf", Email="mf@ss.pl", Password="123", Role=ROLES.MODERATOR},
            new UserWrapper {UserName = "kp", Email="kp@ss.pl", Password="123", Role=ROLES.USER},
            new UserWrapper {UserName = "kt", Email="kt@ss.pl", Password="123", Role=ROLES.USER},
            new UserWrapper {UserName = "mk", Email="mk@ss.pl", Password="123", Role=ROLES.USER}
        };

        public static readonly string NAME = SEEDERS.USERS_SEEDER;

        public void Seed(WSCDbContext dbContext)
        {
            foreach (var user in _users)
            {
                if (!dbContext.Users.Any(u => u.UserName == user.UserName))
                {
                    using (var store = new UserStore<User>(dbContext))
                    {
                        var manager = new UserManager<User>(store);
                        manager.PasswordValidator = SetUpPasswordValidator();
                        var userToInsert = new User { UserName = user.UserName, Email = user.Email };
                        var userResult = manager.Create(userToInsert, user.Password);
                        if (userResult.Succeeded)
                            manager.AddToRole(userToInsert.Id, user.Role);
                        else
                            throw new UnableToAddUserException(userResult.Errors);
                    }
                }
            }
        }

        private IIdentityValidator<string> SetUpPasswordValidator()
        {
            return new PasswordValidator
            {
                RequiredLength = 3,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
            };
        }

        internal class UserWrapper
        {
            public string UserName { get; set; }
            public string Email { get; set; }
            public string Password { get; set; }
            public string Role { get; set; }
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width"/>
<title>Login Demo - Kakao JavaScript SDK</title>

      Login Token:

      User string:

      Cognito Access Token:


text:
define([
  'mocks/index'
], function (mocks) {

  return function () {
    describe('ssSearch', function () {
      var $httpBackend;
      var ssSearch;
      var mlUtil;

      beforeEach(function (done) {
        angular.mock.module('app');
        inject(
          function (_$httpBackend_, _ssSearch_, _mlUtil_) {
            $httpBackend = _$httpBackend_;
            ssSearch = _ssSearch_;
            mlUtil = _mlUtil_;
            done();
          }
        );
      });

      it('should be produce a valid range query', function () {
        var self = this;
        var s = ssSearch.create({
          criteria: { constraints: { dateStart: {
            value: mlUtil.moment('2014-08-01T00:00:00.000-05:00')
          } } }
        });
        $httpBackend.expectPOST(
          '/v1/search',
          {
            search: {
              qtext: [''],
              query: {
                'and-query': {
                  queries: [ {
                    'range-constraint-query': {
                      'constraint-name': 'lastActivity',
                      'value': mlUtil.moment('2014-08-01T00:00:00.000-05:00'),
                      'range-operator': 'GE'
                    }
                  } ]
                }
              },
              timezone: window.jstz.determine().name()
            }
          }
        ).respond(500);
        // keep it from trying to parse the reponse by sending an error,
        // we only care that the request was valid
        s.post();
        $httpBackend.flush();
        assert(true);
      });

      it('should produce a query for "resolved"', function () {
        var self = this;
        var s = ssSearch.create({
          criteria: { constraints: { resolved: {
            value: true
          } } }
        });
        $httpBackend.expectPOST(
          '/v1/search',
          {
            search: {
              qtext: [''],
              query: {
                'and-query': {
                  queries: [ {
                    'value-constraint-query': {
                      'constraint-name': 'resolved',
                      'text': true
                    }
                  } ]
                }
              },
              timezone: window.jstz.determine().name()
            }
          }
        ).respond(500);
        // keep it from trying to parse the reponse by sending an error,
        // we only care that the request was valid
        s.post();
        $httpBackend.flush();
        assert(true);
      });

      it('should get back an object for tags facet results', function (done) {
        var s = ssSearch.create();
        $httpBackend.expectPOST('/v1/search').respond(mocks.searchResponse);
        s.post().$ml.waiting.then(
          function () {
            expect(s.results.facets.tags).not.to.be.an('array');
            done();
          }
        );
        $httpBackend.flush();
      });

      it('should get back an array for dates facet results', function (done) {
        var s = ssSearch.create();
        $httpBackend.expectPOST('/v1/search').respond(mocks.searchResponse);
        s.post().$ml.waiting.then(
          function () {
            expect(s.results.facets.dates).to.be.an('array');
            done();
          }
        );
        $httpBackend.flush();
      });

      it('should have shadows dates', function (done) {
        var s = ssSearch.create();
        $httpBackend.expectPOST('/v1/search').respond(mocks.searchResponse);
        $httpBackend.expectPOST('/v1/search').respond(mocks.searchResponse);
        $httpBackend.expectPOST('/v1/search').respond(mocks.searchResponse);
        s.shadowSearch().then(
          function () {
            expect(s.results.facets.dates[0].shadow).to.be.ok;
            done();
          }
        );
        $httpBackend.flush();
      });

    });

  };

});


text:
/**
 *
 */
package de.piratenpartei.berlin.ldadmin.app.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import de.piratenpartei.berlin.ldadmin.app.model.User;

/**
 * @author ivangsa
 */
@Component("passwordTokenManager")
public class PasswordTokenManagerImpl implements PasswordTokenManager {
    private final SimpleDateFormat expirationTimeFormat = new SimpleDateFormat("yyyyMMddHHmm");
    private final int expirationTimeTokenLength = expirationTimeFormat.toPattern().length();

    @Qualifier("passwordTokenEncoder")
    @Autowired
    private PasswordEncoder passwordTokenEncoder;

    /**
     * {@inheritDoc}
     */
    @Override
    public String generateRecoveryToken(final User user) {
        if (user != null) {
            final String tokenSource = getTokenSource(user);
            final String expirationTimeStamp = expirationTimeFormat.format(getExpirationTime());
            return expirationTimeStamp + passwordTokenEncoder.encode(expirationTimeStamp + tokenSource);
        }
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRecoveryTokenValid(final User user, final String token) {
        if (user != null && token != null) {
            final String expirationTimeStamp = getTimestamp(token);
            final String tokenWithoutTimestamp = getTokenWithoutTimestamp(token);
            final String tokenSource = expirationTimeStamp + getTokenSource(user);
            final Date expirationTime = parseTimestamp(expirationTimeStamp);

            return expirationTime != null && expirationTime.after(new Date())
                    && passwordTokenEncoder.matches(tokenSource, tokenWithoutTimestamp);
        }
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void invalidateRecoveryToken(User user, String token) {
        // NOP
    }

    /**
     * Return tokens expiration time, now + 1 day.
     *
     * @return
     */
    private Date getExpirationTime() {
        return DateUtils.addDays(new Date(), 1);
    }

    private String getTimestamp(final String token) {
        return StringUtils.substring(token, 0, expirationTimeTokenLength);
    }

    /**
     * @param user
     * @return
     */
    private String getTokenSource(final User user) {
        return user.getEmail() + user.getVersion() + user.getPassword();
    }

    private String getTokenWithoutTimestamp(final String token) {
        return StringUtils.substring(token, expirationTimeTokenLength, token.length());
    }

    private Date parseTimestamp(final String timestamp) {
        try {
            return expirationTimeFormat.parse(timestamp);
        } catch (final ParseException e) {
            return null;
        }
    }

}


text:
@implementation NSString (Hash)

- (NSData *)md5HashData
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] md5HashData];
}

- (NSString *)md5HashString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] md5HashString];
}

- (NSData *)sha1HashData
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha1HashData];
}
- (NSString *)sha1HashString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha1HashString];
}

- (NSData *)sha224HashData
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha224HashData];
}
- (NSString *)sha224HashString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha224HashString];
}

- (NSData *)sha256HashData
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha256HashData];
}
- (NSString *)sha256HashString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha256HashString];
}

- (NSData *)sha384HashData
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha384HashData];
}
- (NSString *)sha384HashString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha384HashString];
}

- (NSData *)sha512HashData
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha512HashData];
}
- (NSString *)sha512HashString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] sha512HashString];
}

- (NSData *)base64EncodedData
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedData];
}

- (NSString *)base64EncodedString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
}

- (NSData *)base64DecodedData
{
    return [[NSData alloc] initWithBase64EncodedString:self options:0];
}

- (NSString *)base64DecodedString
{
    return [[self base64DecodedData] stringValue];
}

@end


text:
google-places
=============

wrapper to the google places API


text:
package info.inkstack.troll.seg;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

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

import com.chenlb.mmseg4j.Dictionary;
import com.chenlb.mmseg4j.MMSeg;
import com.chenlb.mmseg4j.Seg;
import com.chenlb.mmseg4j.Word;

/**
 * 基于com.chenlb.mmseg4j的分词实现
 *
 * @author Halo9Pan
 *
 */
public abstract class MMSegSegment implements ISegment {

	private static Logger logger = LoggerFactory.getLogger(MMSegSegment.class);

	protected Dictionary dict;

	public MMSegSegment() {
		this.dict = Dictionary.getInstance();
	}

	/**
	 * 返回com.chenlb.mmseg4j不同的分词实现
	 *
	 * @return
	 */
	protected abstract Seg initializeSeg();

	/*
	 * (non-Javadoc)
	 *
	 * @see com.iqiyi.lego.tags.seg.ISegment#segWords(java.lang.String)
	 */
	public List<String> segWords(String content) {
		Reader reader = new StringReader(content);
		List<String> list = this.segWords(reader);
		return list;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see info.inkstack.troll.seg.ISegment#segWords(java.io.File)
	 */
	public List<String> segWords(File file) throws FileNotFoundException {
		Reader reader = new FileReader(file);
		List<String> list = this.segWords(reader);
		return list;
	}

	private List<String> segWords(Reader reader) {
		List<String> list = new ArrayList<String>();
		Seg seg = this.initializeSeg(); // 取得不同的分词具体算法
		MMSeg mmSeg = new MMSeg(reader, seg);
		Word word = null;
		try {
			while ((word = mmSeg.next()) != null) {
				String w = word.getString();
				list.add(w);
			}
		} catch (IOException e) {
			logger.warn("Exception when segging words.", e);
		}
		return list;
	}

}


text:
package org.apache.camel.component.braintree.internal;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

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

/*
 * Simplified version of org.slf4j.bridge.SLF4JBridgeHandler
 */
public final class BraintreeLogHandler extends Handler {
    public static final Handler INSTANCE = new BraintreeLogHandler();
    public static final Level DEFAULT_LOGGER_VERSION = Level.WARNING;
    public static final String DEFAULT_LOGGER_NAME = "org.apache.camel.component.braintree.camel-braintree";

    private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue();
    private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue();
    private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue();
    private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue();

    @Override
    public void flush() {
        // no-op
    }

    @Override
    public void close() throws SecurityException {
        // no-op
    }

    @Override
    public void publish(LogRecord record) {
        if (record != null) {
            final Logger logger = getLogger(record);
            final String message = formatMessage(record);

            int level = record.getLevel().intValue();
            if (level <= TRACE_LEVEL_THRESHOLD) {
                logger.trace(message, record.getThrown());
            } else if (level <= DEBUG_LEVEL_THRESHOLD) {
                logger.debug(message, record.getThrown());
            } else if (level <= INFO_LEVEL_THRESHOLD) {
                logger.info(message, record.getThrown());
            } else if (level <= WARN_LEVEL_THRESHOLD) {
                logger.warn(message, record.getThrown());
            } else {
                logger.error(message, record.getThrown());
            }
        }
    }

    private Logger getLogger(LogRecord record) {
        String name = record.getLoggerName();
        if (name == null) {
            name = DEFAULT_LOGGER_NAME;
        }
        return LoggerFactory.getLogger(name);
    }

    private String formatMessage(LogRecord record) {
        String message = record.getMessage();
        if (message != null) {

            ResourceBundle bundle = record.getResourceBundle();
            if (bundle != null) {
                try {
                    message = bundle.getString(message);
                } catch (MissingResourceException e) {
                }
            }
            Object[] params = record.getParameters();
            // avoid formatting when there are no or 0 parameters. see also
            // http://jira.qos.ch/browse/SLF4J-203
            if (params != null && params.length > 0) {
                try {
                    message = MessageFormat.format(message, params);
                } catch (IllegalArgumentException e) {
                    // default to the same behavior as in java.util.logging.Formatter.formatMessage(LogRecord)
                    // see also http://jira.qos.ch/browse/SLF4J-337
                    return message;
                }
            }
        } else {
            message = "";
        }

        return message;
    }
}


text:
SHELL=/bin/bash

pre-install:
	@$(SHELL) ./scripts/check-node-canvas.sh

all:
	@$(SHELL) ./scripts/install.sh

clean:
	@rm -rf node_modules/*

check: test

test:
	@echo "***tests***"
	@$(SHELL) ./run_tests.sh ${RUNTESTFLAGS} \
		test/unit/*.js \
		test/unit/renderers/*.js \
		test/unit/controllers/*.js \
		test/integration/renderers/*.js \
		test/acceptance/*.js

test-acceptance:
	@echo "***acceptance tests***"
	@$(SHELL) ./run_tests.sh ${RUNTESTFLAGS} \
		test/acceptance/*.js

test-integration:
	@echo "***integration tests***"
	@$(SHELL) ./run_tests.sh ${RUNTESTFLAGS} \
		test/integration/renderers/*.js

test-unit:
	@echo "***unit tests***"
	@$(SHELL) ./run_tests.sh ${RUNTESTFLAGS} \
		test/unit/*.js \
		test/unit/renderers/*.js \
		test/unit/controllers/*.js

jshint:
	@echo "***jshint***"
	@./node_modules/.bin/jshint lib/ test/

test-all: jshint test

coverage:
	@RUNTESTFLAGS=--with-coverage make test

.PHONY: pre-install test jshint coverage


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="copyright" content="(C) Copyright 2005"/>
<meta name="DC.rights.owner" content="(C) Copyright 2005"/>
<meta name="DC.Type" content="reference"/>
<meta name="DC.Title" content="cxxStructTypedefInherited"/>
<meta name="abstract" content="Links to a typedef inherited by a struct."/>
<meta name="description" content="Links to a typedef inherited by a struct."/>
<meta name="DC.Relation" scheme="URI" content="../cxxStruct/cxxStruct_module.html"/>
<meta name="DC.Format" content="XHTML"/>
<meta name="DC.Identifier" content="cxxStructTypedefInherited"/>
<meta name="DC.Language" content="en-us"/>
<link rel="stylesheet" type="text/css" href="../commonltr.css"/>
<title>cxxStructTypedefInherited</title>
<link rel="stylesheet" type="text/css" href="../nokiacxxref.css"/>

cxxStructTypedefInherited

Links to a typedef inherited by a struct.

Description

The
<cxxStructTypedefInherited> element is a child of the <cxxStructInheritsDetail>
element. It provides the name of a typedef inherited by a struct and
a link to the typedef.

Example

<cxxStructInherits>
    <cxxStructInheritsDetail>
        <cxxStructTypedefInherited href="astruct.xml#atypedef">AStruct::ATypedef</cxxStructTypedefInherited>
    </cxxStructInheritsDetail>
</cxxStructInherits>

Contained by

cxxStructInheritsDetail

Contains

Content Model

No content.

Inheritance

 topic/xref reference/xref apiRef/apiRelation apiClassifier/apiRelation cxxStruct/cxxStructTypedefInherited

Parent topic: cxxStruct module


text:
name: analyzepsbt
btcversion: 22.0.0
btcgroup: rawtransactions
permalink: en/doc/22.0.0/rpc/rawtransactions/analyzepsbt/
---

analyzepsbt "psbt"

Analyzes and provides information about the current status of a PSBT and its inputs

Arguments:
1. psbt    (string, required) A base64 string of a PSBT

Result:
{                                   (json object)
  "inputs" : [                      (json array)
    {                               (json object)
      "has_utxo" : true|false,      (boolean) Whether a UTXO is provided
      "is_final" : true|false,      (boolean) Whether the input is finalized
      "missing" : {                 (json object, optional) Things that are missing that are required to complete this input
        "pubkeys" : [               (json array, optional)
          "hex",                    (string) Public key ID, hash160 of the public key, of a public key whose BIP 32 derivation path is missing
          ...
        ],
        "signatures" : [            (json array, optional)
          "hex",                    (string) Public key ID, hash160 of the public key, of a public key whose signature is missing
          ...
        ],
        "redeemscript" : "hex",     (string, optional) Hash160 of the redeemScript that is missing
        "witnessscript" : "hex"     (string, optional) SHA256 of the witnessScript that is missing
      },
      "next" : "str"                (string, optional) Role of the next person that this input needs to go to
    },
    ...
  ],
  "estimated_vsize" : n,            (numeric, optional) Estimated vsize of the final signed transaction
  "estimated_feerate" : n,          (numeric, optional) Estimated feerate of the final signed transaction in BTC/kvB. Shown only if all UTXO slots in the PSBT have been filled
  "fee" : n,                        (numeric, optional) The transaction fee paid. Shown only if all UTXO slots in the PSBT have been filled
  "next" : "str",                   (string) Role of the next person that this psbt needs to go to
  "error" : "str"                   (string, optional) Error message (if there is one)
}

Examples:
> bitcoin-cli analyzepsbt "psbt"


text:
import unittest
import unittest.mock as mock
import numpy as np
import bson
import database.tests.test_entity
import core.image_source
import core.system
import util.dict_utils as du
import batch_analysis.task
import batch_analysis.tasks.run_system_task as task

class TestRunSystemTask(database.tests.test_entity.EntityContract, unittest.TestCase):

    def get_class(self):
        return task.RunSystemTask

    def make_instance(self, *args, **kwargs):
        kwargs = du.defaults(kwargs, {
            'system_id': bson.ObjectId(),
            'image_source_id': bson.ObjectId(),
            'repeat': np.random.randint(0, 1000),
            'state': batch_analysis.task.JobState.RUNNING,
            'num_cpus': np.random.randint(0, 1000),
            'num_gpus': np.random.randint(0, 1000),
            'memory_requirements': '{}MB'.format(np.random.randint(0, 50000)),
            'expected_duration': '{0}:{1}:{2}'.format(np.random.randint(1000), np.random.randint(60),
                                                      np.random.randint(60)),
            'node_id': 'node-{}'.format(np.random.randint(10000)),
            'job_id': np.random.randint(1000)
        })
        return task.RunSystemTask(*args, **kwargs)

    def assert_models_equal(self, task1, task2):
        """
        Helper to assert that two tasks are equal
        We're going to violate encapsulation for a bit
        :param task1:
        :param task2:
        :return:
        """
        if (not isinstance(task1, task.RunSystemTask) or
                not isinstance(task2, task.RunSystemTask)):
            self.fail('object was not an RunSystemTask')
        self.assertEqual(task1.identifier, task2.identifier)
        self.assertEqual(task1.system, task2.system)
        self.assertEqual(task1.image_source, task2.image_source)
        self.assertEqual(task1._repeat, task2._repeat)
        self.assertEqual(task1._state, task2._state)
        self.assertEqual(task1.node_id, task2.node_id)
        self.assertEqual(task1.job_id, task2.job_id)
        self.assertEqual(task1.result, task2.result)
        self.assertEqual(task1.num_cpus, task2.num_cpus)
        self.assertEqual(task1.num_gpus, task2.num_gpus)
        self.assertEqual(task1.memory_requirements, task2.memory_requirements)
        self.assertEqual(task1.expected_duration, task2.expected_duration)

class TestTrialRunner(unittest.TestCase):

    def setUp(self):
        self._trial_result = mock.Mock()

        self._system = mock.create_autospec(core.system.VisionSystem)
        self._system.is_image_source_appropriate.return_value = True
        self._system.finish_trial.return_value = self._trial_result

        self._image_source = mock.create_autospec(core.image_source.ImageSource)
        self._image_source.get_stereo_baseline.return_value = None
        self._image_source.get_camera_intrinsics.return_value = mock.Mock()
        self._image_source._image_count = 0
        self._image_source._image = mock.Mock()

        def get_next_image(self_=self._image_source):
            self_._image_count += 1
            return self_._image, self_._image_count

        def is_complete(self_=self._image_source):
            return self_._image_count >= 10

        self._image_source.get_next_image.side_effect = get_next_image
        self._image_source.is_complete.side_effect = is_complete

    def test_run_system_checks_is_appropriate(self):
        self._system.is_image_source_appropriate.return_value = False
        task.run_system_with_source(self._system, self._image_source)
        self.assertIn(mock.call(self._image_source), self._system.is_image_source_appropriate.call_args_list)

    def test_run_system_calls_trial_functions_in_order(self):
        task.run_system_with_source(self._system, self._image_source)
        mock_calls = self._system.mock_calls
        # is_appropriate; set_camera_intrinsics; begin; 10 process image calls; end
        self.assertEqual(14, len(mock_calls))
        self.assertEqual('set_camera_intrinsics', mock_calls[1][0])
        self.assertEqual('start_trial', mock_calls[2][0])
        for i in range(10):
            self.assertEqual('process_image', mock_calls[3 + i][0])
        self.assertEqual('finish_trial', mock_calls[13][0])

    def test_run_system_calls_iteration_functions_in_order(self):
        task.run_system_with_source(self._system, self._image_source)
        mock_calls = self._image_source.mock_calls
        # get_camera_intrinsics; get_stereo_baseline; begin; 10 pairs of  is complete and get image; final is complete
        self.assertEqual(25, len(mock_calls))
        self.assertEqual('get_camera_intrinsics', mock_calls[0][0])
        self.assertEqual('get_stereo_baseline', mock_calls[1][0])
        self.assertEqual('__enter__', mock_calls[2][0])
        for i in range(10):
            self.assertEqual('is_complete', mock_calls[3 + 2 * i][0])
            self.assertEqual('get_next_image', mock_calls[4 + 2 * i][0])
        self.assertEqual('is_complete', mock_calls[23][0])
        self.assertEqual('__exit__', mock_calls[24][0])

    def test_run_system_returns_trial_result(self):
        result = task.run_system_with_source(self._system, self._image_source)
        self.assertEqual(self._trial_result, result)


text:
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
#endregion

namespace Textile
{
    public partial class TextileFormatter
    {
        private readonly Regex VelocityArguments =
            new Regex("nostyle(?<arg>.*?)/nostyle", RegexOptions.IgnoreCase | RegexOptions.Singleline);

        private string argMatchReplace(Match match)
        {
            return match.Result("${arg}");
        }

        #region Formatting Methods

        /// <summary>
        /// Formats the given text.
        /// </summary>
        /// <param name="input">The text to format.</param>
        public void Format(string input)
        {
            m_output.Begin();

            // Clean the text...
            string str = PrepareInputForFormatting(input);
            // ...and format each line.
            foreach (string line in str.Split('\n'))
            {
                string tmp = line;

                // Let's see if the current state(s) is(are) finished...
                while (CurrentState != null && CurrentState.ShouldExit(tmp))
                    PopState();

                if (!Regex.IsMatch(tmp, @"^\s*$"))
                {
                    // Figure out the new state for this text line, if possible.
                    if (CurrentState == null || CurrentState.ShouldParseForNewFormatterState(tmp))
                    {
                        tmp = HandleFormattingState(tmp);
                    }
                    // else, the current state doesn't want to be superceded by
                    // a new one. We'll leave him be.

                    // Modify the line with our block modifiers.
                    if (CurrentState == null || CurrentState.ShouldFormatBlocks(tmp))
                    {
                        foreach (BlockModifier blockModifier in s_blockModifiers)
                        {
                            //TODO: if not disabled...
                            tmp = blockModifier.ModifyLine(tmp);
                        }

                        for (int i = s_blockModifiers.Count - 1; i >= 0; i--)
                        {
                            BlockModifier blockModifier = s_blockModifiers[i];
                            tmp = blockModifier.Conclude(tmp);
                        }
                    }

                    tmp = VelocityArguments.Replace(tmp, argMatchReplace);

                    // Format the current line.
                    CurrentState.FormatLine(tmp);
                }
            }
            // We're done. There might be a few states still on
            // the stack (for example if the text ends with a nested
            // list), so we must pop them all so that they have
            // their "Exit" method called correctly.
            while (m_stackOfStates.Count > 0)
                PopState();

            m_output.End();
        }

        #endregion

        #region Preparation Methods

        /// <summary>
        /// Cleans up a text before formatting.
        /// </summary>
        /// <param name="input">The text to clean up.</param>
        /// <returns>The clean text.</returns>
        /// This method cleans stuff like line endings, so that
        /// we don't have to bother with it while formatting.
        private string PrepareInputForFormatting(string input)
        {
            input = CleanWhiteSpace(input);
            return input;
        }

        private string CleanWhiteSpace(string text)
        {
            text = text.Replace("\r\n", "\n");
            text = text.Replace("\t", "");
            text = Regex.Replace(text, @"\n{3,}", "\n\n");
            text = Regex.Replace(text, @"\n *\n", "\n\n");
            text = Regex.Replace(text, "\"$", "\" ");
            return text;
        }

        #endregion
    }
}


text:
from PROJECTMODULE.database import classes, helpers
from PROJECTMODULE.database.helpers import get_session

__all__ = ['classes', 'helpers', 'get_session']


text:
// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	v1alpha1 "github.com/rancher/vm/pkg/apis/ranchervm/v1alpha1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
)

// FakeSettings implements SettingInterface
type FakeSettings struct {
	Fake *FakeVirtualmachineV1alpha1
}

var settingsResource = schema.GroupVersionResource{Group: "virtualmachine.rancher.com", Version: "v1alpha1", Resource: "settings"}

var settingsKind = schema.GroupVersionKind{Group: "virtualmachine.rancher.com", Version: "v1alpha1", Kind: "Setting"}

// Get takes name of the setting, and returns the corresponding setting object, and an error if there is any.
func (c *FakeSettings) Get(name string, options v1.GetOptions) (result *v1alpha1.Setting, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootGetAction(settingsResource, name), &v1alpha1.Setting{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.Setting), err
}

// List takes label and field selectors, and returns the list of Settings that match those selectors.
func (c *FakeSettings) List(opts v1.ListOptions) (result *v1alpha1.SettingList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootListAction(settingsResource, settingsKind, opts), &v1alpha1.SettingList{})
	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &v1alpha1.SettingList{ListMeta: obj.(*v1alpha1.SettingList).ListMeta}
	for _, item := range obj.(*v1alpha1.SettingList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested settings.
func (c *FakeSettings) Watch(opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewRootWatchAction(settingsResource, opts))
}

// Create takes the representation of a setting and creates it.  Returns the server's representation of the setting, and an error, if there is any.
func (c *FakeSettings) Create(setting *v1alpha1.Setting) (result *v1alpha1.Setting, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(settingsResource, setting), &v1alpha1.Setting{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.Setting), err
}

// Update takes the representation of a setting and updates it. Returns the server's representation of the setting, and an error, if there is any.
func (c *FakeSettings) Update(setting *v1alpha1.Setting) (result *v1alpha1.Setting, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(settingsResource, setting), &v1alpha1.Setting{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.Setting), err
}

// Delete takes name of the setting and deletes it. Returns an error if one occurs.
func (c *FakeSettings) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteAction(settingsResource, name), &v1alpha1.Setting{})
	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeSettings) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	action := testing.NewRootDeleteCollectionAction(settingsResource, listOptions)

	_, err := c.Fake.Invokes(action, &v1alpha1.SettingList{})
	return err
}

// Patch applies the patch and returns the patched setting.
func (c *FakeSettings) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Setting, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(settingsResource, name, data, subresources...), &v1alpha1.Setting{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.Setting), err
}


text:
require "rails/generators/base"

module Kuva
  module Generators
    class InstallGenerator < Rails::Generators::Base
      source_root File.expand_path("../templates", __FILE__)

      desc "Creates a Kuva initializer in your application"

      def copy_initializer
        copy_file "kuva.rb", "config/initializers/kuva.rb"
      end

      def copy_locale
        copy_file "../../../../config/locales/frontend.yml", "config/locales/kuva.en.yml"
      end

      def create_assets
        generate "kuva:assets"
      end

      def mount_engine
        if original_routes.include? "mount Kuva::Engine"
          say_status "skip", "mounting of Kuva into config/routes.rb", :yellow
        else
          route 'mount Kuva::Engine => "/kuva"'
        end
      end

      private

      def original_routes
        File.read "config/routes.rb"
      end

    end
  end
end


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * Created on Jun 3, 2005
 *
 */
package ghidra.app.decompiler;

/**
 * An exception from (or that has passed through) the decompiler process
 *
 *
 */
public class DecompileException extends Exception {
	private static final long serialVersionUID = 1L;

	public DecompileException(String type,String msg) {
		super(type + ": "+msg);
	}

	@Override
	public String toString() {
	    return "DecompileException: " + getMessage();
	}
}


text:
import * as sinon from 'sinon';

const chai = require('chai');
chai.use(require('sinon-chai'));

export const expect = chai.expect;

export const stubWithArgs = (...args) => {
    const stub = sinon.stub();
    for (let i = 0; i + 1 < args.length; i += 2) {
        stub.withArgs.apply(stub, args[i]).returns(args[i + 1]);
    }
    return stub;
};

export const stubReturns = (...args) =>
    args.reduce((stub, arg, index) => {
        stub.onCall(index).returns(arg);
        return stub;
    }, sinon.stub());


text:
<?php

// no direct access
defined('_JEXEC') or die('Restricted access');

// include assets css
$this->app->document->addStylesheet('elements:socialbookmarks/assets/css/socialbookmarks.css');

?>

	<?php foreach ($bookmarks as $name => $data) : ?>
		<?php $title = ($name == "email") ? JText::_('Recommend this Page') : JText::_('Add this Page to') . ' ' . ucfirst($name); ?>
		<a class="<?php echo $name ?>" onclick="<?php echo $data['click']; ?>" href="<?php echo $data['link']; ?>" title="<?php echo $title; ?>">
	<?php endforeach; ?>


text:
*from [adarsh on StackOverflow](http://stackoverflow.com/questions/27158573/how-to-delete-record-by-id-in-flask-sqlalchemy)*

To delete an item from a SQLAlchemy database, just call the `delete` method on an item from a query, then `commit` it.

```python
User.query.filter_by(id=123).delete()
db.session.commit()
```

Also, before implementing this functionality, consider adding a 'disabled', 'inactive', or 'expired' column to the schema instead of actually deleting the item.


text:
package org.apache.eagle.query.parser;

public enum LogicalOperator {
    AND,
    OR,
    NOT
}


text:
package org.test.launcher;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class TestDC {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		createPassword("user2");
		createPassword("manager2");
	}

	private static void createPassword(String text) {
		PasswordEncoder encoder = new BCryptPasswordEncoder();
		System.out.println("Password: " + encoder.encode(text));
		System.out.println("-------------");
	}

}


text:
require 'naught'

require 'attribute'

require 'subst_attr/substitute'
require 'subst_attr/attribute'
require 'subst_attr/macro'
require 'subst_attr/activate'


text:
cask "advancedrestclient" do
  version "16.0.0"
  sha256 "837087a5358bc106c31b562d2b24565571805aa4f99fe742ee7e1baf978354c4"

  url "https://github.com/advanced-rest-client/arc-electron/releases/download/v#{version}/arc-macos.dmg"
  name "Advanced REST Client"
  desc "API testing tool"
  homepage "https://github.com/advanced-rest-client/arc-electron"

  livecheck do
    url :url
    regex(/^v?(\d+(?:\.\d+)+)$/i)
  end

  app "AdvancedRestClient.app"

  zap trash: [
    "~/Library/Application Support/advanced-rest-client",
    "~/Library/Logs/AdvancedRestClient",
  ]
end


text:
package com.graphhopper.jsprit.core.problem.solution;

/**
 * Interface for all solutionCostCalculators which should be the objective-functions of the problem.
 *

 *
It evaluates VehicleRoutingProblemSolution and returns its costs.
 *
 * @author schroeder
 */
public interface SolutionCostCalculator {

    /**
     * Returns costs of solution.
     *
     * @param solution
     * @return costs
     */
    public double getCosts(VehicleRoutingProblemSolution solution);

}


text:
if (!global.Promise) return;

var test = require('tap').test;

var unwrappedPromise = global.Promise;

require('../index.js');

test('then', function(t) {
  var listener = addListner();

  var promise = new Promise(function(accept, reject) {
    listener.currentName = 'accept';
    accept(10);
  });

  promise.then(function(val) {
    listener.currentName = 'nextTick in first then';
    process.nextTick(function() {
      t.strictEqual(val, 10);
    });
    listener.currentName = 'first then continuation';
  });

  listener.currentName = 'setImmediate in root';
  setImmediate(function() {
    promise.then(function(val) {
      t.strictEqual(val, 10);
      t.strictEqual(this, global);
      listener.currentName = 'setTimeout in 2nd then';
      setTimeout(function() {
        t.deepEqual(listener.root, expected);
        t.end();
      });
      listener.currentName = '2nd then continuation';
    });
  });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'accept',
        children: [
          {
            name: 'nextTick in first then',
            children: [],
            before: 1,
            after: 1,
            error: 0
          },
          {
            name: 'first then continuation',
            children: [],
            before: 0,
            after: 0,
            error: 0
          },
          {
            name: 'setTimeout in 2nd then',
            children: [],
            before: 1,
            after: 0,
            error: 0
          },
          {
            name: '2nd then continuation',
            children: [],
            before: 0,
            after: 0,
            error: 0
          }
        ],
        before: 2,
        after: 2,
        error: 0
      },
      {
        name: 'setImmediate in root',
        children: [],
        before: 1,
        after: 1,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

test('chain', function chainTest(t) {
  var listener = addListner();

  var promise = new Promise(function(accept, reject) {
    listener.currentName = 'accept';
    accept(10);
  });

  promise.chain(function(val) {
    listener.currentName = 'nextTick in first chain';
    process.nextTick(function() {
      t.strictEqual(val, 10);
    });
    listener.currentName = 'first chain continuation';
  });

  listener.currentName = 'setImmediate in root';
  setImmediate(function() {
    promise.chain(function(val) {
      t.strictEqual(val, 10);
      t.strictEqual(this, global);
      listener.currentName = 'setTimeout in 2nd chain';
      setTimeout(function() {
        t.deepEqual(listener.root, expected);
        t.end();
      });
      listener.currentName = '2nd chain continuation';
    });
  });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'accept',
        children: [
          {
            name: 'nextTick in first chain',
            children: [],
            before: 1,
            after: 1,
            error: 0
          },
          {
            name: 'first chain continuation',
            children: [],
            before: 0,
            after: 0,
            error: 0
          },
          {
            name: 'setTimeout in 2nd chain',
            children: [],
            before: 1,
            after: 0,
            error: 0
          },
          {
            name: '2nd chain continuation',
            children: [],
            before: 0,
            after: 0,
            error: 0
          }
        ],
        before: 2,
        after: 2,
        error: 0
      },
      {
        name: 'setImmediate in root',
        children: [],
        before: 1,
        after: 1,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

test('catch', function(t) {
  var listener = addListner();

  var promise = new Promise(function(accept, reject) {
    listener.currentName = 'reject';
    reject(15);
  });

  listener.currentName = 'catch';
  promise.catch(function(val) {
    listener.currentName = 'nextTick in catch';
    process.nextTick(function() {
      t.strictEqual(val, 15);
    });
    listener.currentName = 'catch continuation';
  });

  listener.currentName = 'setImmediate in root';
  setImmediate(function() {
    promise.then(
      function fullfilled() {
        throw new Error('should not be called on reject');
      },
      function rejected(val) {
        t.strictEqual(val, 15);
        t.strictEqual(this, global);
        listener.currentName = 'setTimeout in then';
        setTimeout(function() {
          // some version of iojs use nextTick for some parts of its async
          if (listener.root.children.length === 3) {
            expected.children.splice(-1, 0, {
              name: 'catch',
              children: [],
              before: 1,
              after: 1,
              error: 0
            })
          }
          t.deepEqual(listener.root, expected);
          t.end();
        });
        listener.currentName = 'then continuation';
      }
    )
  });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'reject',
        children: [
          {
            name: 'nextTick in catch',
            children: [],
            before: 1,
            after: 1,
            error: 0
          },
          {
            name: 'catch continuation',
            children: [],
            before: 0,
            after: 0,
            error: 0
          },
          {
            name: 'setTimeout in then',
            children: [],
            before: 1,
            after: 0,
            error: 0
          },
          {
            name: 'then continuation',
            children: [],
            before: 0,
            after: 0,
            error: 0
          }
        ],
        before: 2,
        after: 2,
        error: 0
      },
      {
        name: 'setImmediate in root',
        children: [],
        before: 1,
        after: 1,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  };
});

test('future chains', function futureChainTest(t) {
  var listener = addListner();

  listener.currentName = 'resolve';
  var promise = Promise.resolve();

  promise
    .then(function() { listener.currentName = '1st then'; })
    .then(function() { listener.currentName = '2nd then'; })
    .then(function() { listener.currentName = '3rd then'; });

  promise
    .chain(function() { listener.currentName = '1st chain'; })
    .chain(function() { listener.currentName = '2nd chain'; })
    .chain(function() { listener.currentName = '3rd chain'; });

  listener.currentName = 'setTimeout';
  setTimeout(function() {
    t.deepEqual(listener.root, expected);
    t.end();
  });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'resolve',
        children: [
          {
            name: '1st then',
            children: [
              {
                name: '2nd then',
                children: [
                  {
                    name: '3rd then',
                    children: [],
                    before: 0,
                    after: 0,
                    error: 0
                  }
                ],
                before: 1,
                after: 1,
                error: 0
              }
            ],
            before: 1,
            after: 1,
            error: 0
          },
          {
            name: '1st chain',
            children: [
              {
                name: '2nd chain',
                children: [
                  {
                    name: '3rd chain',
                    children: [],
                    before: 0,
                    after: 0,
                    error: 0
                  }
                ],
                before: 1,
                after: 1,
                error: 0
              }
            ],
            before: 1,
            after: 1,
            error: 0
          }
        ],
        before: 2,
        after: 2,
        error: 0
      },
      {
        name: 'setTimeout',
        children: [],
        before: 1,
        after: 0,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

test('Promise.resolve', function resolveTest(t) {
  var listener = addListner();

  listener.currentName = 'resolve';
  var p = Promise.resolve(123);

  p.then(function then(value) {
    listener.currentName = 'nextTick';
    process.nextTick(function next() {
      t.equal(value, 123);
      t.deepEqual(listener.root, {
        name: 'root',
        children: [{
            name: 'resolve',
          children: [{
            name: 'nextTick',
            children: [],
            before: 1,
            after: 0,
            error: 0
          }],
          before: 1,
          after: 1,
          error: 0
        }],
        before: 0,
        after: 0,
        error: 0
      });
      t.end();
    });
    process.removeAsyncListener(listener.listener);
  });
});

test('Promise.accept', function acceptTest(t) {
  var listener = addListner();

  listener.currentName = 'accept';
  var p = Promise.accept(123);

  p.then(function then(value) {
    listener.currentName = 'nextTick';
    process.nextTick(function next() {
      t.equal(value, 123);
      t.deepEqual(listener.root, {
        name: 'root',
        children: [{
          name: 'accept',
          children: [
            {
              name: 'nextTick',
              children: [],
              before: 1,
              after: 0,
              error: 0
            },
            {
              name: 'then continuation',
              children: [],
              before: 0,
              after: 0,
              error: 0
            }
          ],
          before: 1,
          after: 1,
          error: 0
        }],
        before: 0,
        after: 0,
        error: 0
      });
      t.end();
    });

    listener.currentName = 'then continuation';
  });

  process.removeAsyncListener(listener.listener);
});

test('Promise.reject', function rejectTest(t) {
  var listener = addListner();

  listener.currentName = 'reject';
  var p = Promise.reject(123);

  listener.currentName = 'catch';
  p.catch(function then(value) {
    listener.currentName = 'nextTick';
    process.nextTick(function next() {
      t.equal(value, 123);

      // some version of iojs use nextTick for some parts of its async
      if (listener.root.children.length === 2) {
        expected.children.push({
          name: 'catch',
          children: [],
          before: 1,
          after: 1,
          error: 0
        })
      }

      t.deepEqual(listener.root, expected);
      t.end();
    });

    listener.currentName = 'catch continuation';
  });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [{
      name: 'reject',
      children: [
        {
          name: 'nextTick',
          children: [],
          before: 1,
          after: 0,
          error: 0
        },
        {
          name: 'catch continuation',
          children: [],
          before: 0,
          after: 0,
          error: 0
        }
      ],
      before: 1,
      after: 1,
      error: 0
    }],
    before: 0,
    after: 0,
    error: 0
  }
});

test('Promise.all', function allTest(t) {
  var listener = addListner();

  listener.currentName = 'resolve 1';
  var a = Promise.resolve(123);
  listener.currentName = 'resolve 2';
  var b = Promise.resolve(456);
  listener.currentName = 'all';
  var p = Promise.all([a, b]);

  p.then(function then(value) {
    listener.currentName = 'nextTick';
    process.nextTick(function next() {
      process.removeAsyncListener(listener.listener);
      t.deepEqual(value, [123, 456]);
      t.deepEqual(listener.root, {
        name: 'root',
        children: [{
          name: 'resolve 1',
          children: [{
            // Internal continuation of a used for making the race future.
            name: 'all',
            children: [],
            before: 0,
            after: 0,
            error: 0
          }],
          before: 1,
          after: 1,
          error: 0
        }, {
          name: 'resolve 2',
          children: [
            {
              name: 'all',
              children: [
                {
                  name: 'nextTick',
                  children: [],
                  before: 1,
                  after: 0,
                  error: 0
                },
                {
                  name: 'then continuation',
                  children: [],
                  before: 0,
                  after: 0,
                  error: 0
                }
              ],
              before: 1,
              after: 1,
              error: 0
            },
            {
              // Internal continuation of b used for making the race future.
              name: 'all',
              children: [],
              before: 0,
              after: 0,
              error: 0
            }
          ],
          before: 1,
          after: 1,
          error: 0
        }],
        before: 0,
        after: 0,
        error: 0
      });
      t.end();
    });

    listener.currentName = 'then continuation';
  });
});

test('Promise.all reject', function allTest(t) {
  var listener = addListner();

  listener.currentName = 'resolve';
  var a = Promise.resolve(123);
  listener.currentName = 'reject';
  var b = Promise.reject(456);
  listener.currentName = 'all';
  var p = Promise.all([a, b]);

  p.catch(function then(value) {
    listener.currentName = 'nextTick';
    process.nextTick(function next() {
      // some version of iojs use nextTick for some parts of its async
      if (listener.root.children.length === 3) {
        expected.children.push({
          name: 'all',
          children: [],
          before: 1,
          after: 1,
          error: 0
        })
      }

      process.removeAsyncListener(listener.listener);
      t.equal(value, 456);
      t.deepEqual(listener.root, expected);
      t.end();
    });

    listener.currentName = 'catch continuation';
  });

  var expected = {
    name: 'root',
    children: [{
      name: 'resolve',
      children: [{
        // Internal continuation of a used for making the race future.
        name: 'all',
        children: [],
        before: 0,
        after: 0,
        error: 0
      }],
      before: 1,
      after: 1,
      error: 0
    }, {
      name: 'reject',
      children: [
        {
          name: 'all',
          children: [
            {
              name: 'nextTick',
              children: [],
              before: 1,
              after: 0,
              error: 0
            },
            {
              name: 'catch continuation',
              children: [],
              before: 0,
              after: 0,
              error: 0
            }
          ],
          before: 1,
          after: 1,
          error: 0
        },
        {
          // Internal continuation of b used for making the race future.
          name: 'all',
          children: [],
          before: 0,
          after: 0,
          error: 0
        }
      ],
      before: 1,
      after: 1,
      error: 0
    }],
    before: 0,
    after: 0,
    error: 0
  }
});

test('Promise.race', function raceTest(t) {
  var listener = addListner();

  listener.currentName = 'resolve 1';
  var a = Promise.resolve(123);
  listener.currentName = 'resolve 2';
  var b = Promise.resolve(456);
  listener.currentName = 'race';
  var p = Promise.race([a, b]);

  p.then(function then(value) {
    listener.currentName = 'nextTick';
    process.nextTick(function next() {
      process.removeAsyncListener(listener.listener);
      t.equal(value, 123);
      t.deepEqual(listener.root, {
        name: 'root',
        children: [{
          name: 'resolve 1',
          children: [
            {
              name: 'race',
              children: [
                {
                  name: 'nextTick',
                  children: [],
                  before: 1,
                  after: 0,
                  error: 0
                },
                {
                  name: 'then continuation',
                  children: [],
                  before: 0,
                  after: 0,
                  error: 0
                }
              ],
              before: 1,
              after: 1,
              error: 0
            },
            {
              // Internal continuation of a used for making the race future.
              name: 'race',
              children: [],
              before: 0,
              after: 0,
              error: 0
            }
          ],
          before: 1,
          after: 1,
          error: 0
        }, {
          name: 'resolve 2',
          children: [{
            // Internal continuation of b used for making the race future.
            name: 'race',
            children: [],
            before: 0,
            after: 0,
            error: 0
          }],
          before: 1,
          after: 1,
          error: 0
        }],
        before: 0,
        after: 0,
        error: 0
      });
      t.end();
    });

    listener.currentName = 'then continuation';
  });
});

test('Promise.race - reject', function raceTest(t) {
  var listener = addListner();

  listener.currentName = 'reject';
  var a = Promise.reject(123);
  listener.currentName = 'resolve';
  var b = Promise.resolve(456);
  listener.currentName = 'race';
  var p = Promise.race([a, b]);

  p.catch(function then(value) {
    listener.currentName = 'nextTick';
    process.nextTick(function next() {
      process.removeAsyncListener(listener.listener);
      t.equal(value, 123);

      // some version of iojs use nextTick for some parts of its async
      if (listener.root.children.length === 3) {
        expected.children.push({
          name: 'race',
          children: [],
          before: 1,
          after: 1,
          error: 0
        })
      }

      t.deepEqual(listener.root, expected);
      t.end();
    });

    listener.currentName = 'catch continuation';
  });

  var expected = {
    name: 'root',
    children: [{
      name: 'reject',
      children: [
        {
          name: 'race',
          children: [
            {
              name: 'nextTick',
              children: [],
              before: 1,
              after: 0,
              error: 0
            },
            {
              name: 'catch continuation',
              children: [],
              before: 0,
              after: 0,
              error: 0
            }
          ],
          before: 1,
          after: 1,
          error: 0
        },
        {
          // Internal continuation of a used for making the race future.
          name: 'race',
          children: [],
          before: 0,
          after: 0,
          error: 0
        }
      ],
      before: 1,
      after: 1,
      error: 0
    }, {
      name: 'resolve',
      children: [{
        // Internal continuation of b used for making the race future.
        name: 'race',
        children: [],
        before: 0,
        after: 0,
        error: 0
      }],
      before: 1,
      after: 1,
      error: 0
    }],
    before: 0,
    after: 0,
    error: 0
  }
});

test('Promise.defer', function diferTest(t) {
  var listener = addListner();

  listener.currentName = 'defer';
  var p = Promise.defer();
  listener.currentName = 'resolve';
  p.resolve(123);
  listener.currentName = 'reject';
  p.reject(456);

  p.promise.then(function then(value) {
    listener.currentName = 'nextTick';
    process.nextTick(function next() {
      process.removeAsyncListener(listener.listener);
      t.equal(value, 123);
      t.deepEqual(listener.root, {
        name: 'root',
        children: [{
          name: 'resolve',
          children: [
            {
              name: 'nextTick',
              children: [],
              before: 1,
              after: 0,
              error: 0
            },
            {
              name: 'then continuation',
              children: [],
              before: 0,
              after: 0,
              error: 0
            }
          ],
          before: 1,
          after: 1,
          error: 0
        }],
        before: 0,
        after: 0,
        error: 0
      });
      t.end();
    });

    listener.currentName = 'then continuation';
  });
});

test('instanceof', function diferTest(t) {
  var p = Promise.accept();

  t.ok(p instanceof Promise, 'instanceof should work on wrapped Promise');
  t.ok(p instanceof unwrappedPromise, 'instanceof should work on unwrapped Promise');
  t.end()
});

test('then chain with promise', function(t) {
  var listener = addListner();

  listener.currentName = 'accept';
  var promise = Promise.accept(10);

  promise
    .then(function(val) {
      return new Promise(function wait(accept) {
        listener.currentName = 'nextTick in nested promise';
        process.nextTick(function() {
          listener.currentName = 'accept from nextTick';
          accept(val);
        });
      });
    })
    .then(function validate(val) {
      t.strictEqual(val, 10);
      t.strictEqual(this, global);

      listener.currentName = 'setTimeout in 2nd then';
      setTimeout(function() {
        t.deepEqual(listener.root, expected);
        t.end();
      });

      listener.currentName = '2nd then continuation';
    });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'accept',
        children: [
          {
            name: 'nextTick in nested promise',
            children: [
              {
                name: 'accept from nextTick',
                children: [
                  {
                    name: 'setTimeout in 2nd then',
                    children: [],
                    before: 1,
                    after: 0,
                    error: 0
                  },
                  {
                    name: '2nd then continuation',
                    children: [],
                    before: 0,
                    after: 0,
                    error: 0
                  }
                ],
                before: 1,
                after: 1,
                error: 0
              }
            ],
            before: 1,
            after: 1,
            error: 0
          }
        ],
        before: 1,
        after: 1,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

test('multi chain with promise', function(t) {
  var listener = addListner();

  listener.currentName = 'accept';
  var promise = Promise.accept(10);

  promise
    .chain(function(val) {
      return new Promise(function wait(accept) {
        listener.currentName = 'nextTick in nested promise';
        process.nextTick(function() {
          listener.currentName = 'accept from nextTick';
          accept(val);
        });
      });
    })
    .chain(function validate(val) {
      t.strictEqual(val, 10);
      t.strictEqual(this, global);

      listener.currentName = 'setTimeout in 2nd chain';
      setTimeout(function() {
        t.deepEqual(listener.root, expected);
        t.end();
      });

      listener.currentName = '2nd then continuation';
    });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'accept',
        children: [
          {
            name: 'nextTick in nested promise',
            children: [
              {
                name: 'accept from nextTick',
                children: [
                  {
                    name: 'setTimeout in 2nd chain',
                    children: [],
                    before: 1,
                    after: 0,
                    error: 0
                  },
                  {
                    name: '2nd then continuation',
                    children: [],
                    before: 0,
                    after: 0,
                    error: 0
                  }
                ],
                before: 1,
                after: 1,
                error: 0
              }
            ],
            before: 1,
            after: 1,
            error: 0
          }
        ],
        before: 1,
        after: 1,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

test('then chain with rejected promise', function(t) {
  var listener = addListner();

  listener.currentName = 'reject';
  var promise = Promise.reject(10);

  promise
    .then(fail, function(val) {
      return new Promise(function wait(accept, reject) {
        listener.currentName = 'nextTick in nested promise';
        process.nextTick(function() {
          listener.currentName = 'reject from nextTick';
          reject(val);
        });
      });
    })
    .then(fail, function validate(val) {
      t.strictEqual(val, 10);
      t.strictEqual(this, global);

      listener.currentName = 'setTimeout in 2nd then';
      setTimeout(function() {
        // some version of iojs use nextTick for some parts of its async
        if (listener.root.children.length === 2) {
          expected.children.splice(1, 0, {
            name: 'reject',
            children: [],
            before: 1,
            after: 1,
            error: 0
          })
        }

        t.deepEqual(listener.root, expected);
        t.end();
      });

      listener.currentName = '2nd then continuation';
    });

  function fail() {
    t.fail('should not be called');
    t.end();
  }

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'reject',
        children: [
          {
            name: 'nextTick in nested promise',
            children: [
              {
                name: 'reject from nextTick',
                children: [
                  {
                    name: 'setTimeout in 2nd then',
                    children: [],
                    before: 1,
                    after: 0,
                    error: 0
                  },
                  {
                    name: '2nd then continuation',
                    children: [],
                    before: 0,
                    after: 0,
                    error: 0
                  }
                ],
                before: 1,
                after: 1,
                error: 0
              }
            ],
            before: 1,
            after: 1,
            error: 0
          }
        ],
        before: 1,
        after: 1,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

test('multi chain with rejected promise', function(t) {
  var listener = addListner();

  listener.currentName = 'reject';
  var promise = Promise.reject(10);

  promise
    .chain(fail, function(val) {
      return new Promise(function wait(accept, reject) {
        listener.currentName = 'nextTick in nested promise';
        process.nextTick(function() {
          listener.currentName = 'reject from nextTick';
          reject(val);
        });
      });
    })
    .chain(fail, function validate(val) {
      t.strictEqual(val, 10);
      t.strictEqual(this, global);

      listener.currentName = 'setTimeout in 2nd chain';
      setTimeout(function() {
        // some version of iojs use nextTick for some parts of its async
        if (listener.root.children.length === 2) {
          expected.children.splice(1, 0, {
            name: 'reject',
            children: [],
            before: 1,
            after: 1,
            error: 0
          })
        }

        t.deepEqual(listener.root, expected);
        t.end();
      });

      listener.currentName = '2nd chain continuation';
    });

  function fail() {
    t.fail('should not be called');
    t.end();
  }

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'reject',
        children: [
          {
            name: 'nextTick in nested promise',
            children: [
              {
                name: 'reject from nextTick',
                children: [
                  {
                    name: 'setTimeout in 2nd chain',
                    children: [],
                    before: 1,
                    after: 0,
                    error: 0
                  },
                  {
                    name: '2nd chain continuation',
                    children: [],
                    before: 0,
                    after: 0,
                    error: 0
                  }
                ],
                before: 1,
                after: 1,
                error: 0
              }
            ],
            before: 1,
            after: 1,
            error: 0
          }
        ],
        before: 1,
        after: 1,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

test('multi catch with promise', function(t) {
  var listener = addListner();

  listener.currentName = 'reject';
  var promise = Promise.reject(10);

  promise
    .catch(function(val) {
      return new Promise(function wait(accept, reject) {
        listener.currentName = 'nextTick in nested promise';
        process.nextTick(function() {
          listener.currentName = 'reject from nextTick';
          reject(val);
        });
      });
    })
    .catch(function validate(val) {
      t.strictEqual(val, 10);
      t.strictEqual(this, global);

      listener.currentName = 'setTimeout in 2nd catch';
      setTimeout(function() {
        // some version of iojs use nextTick for some parts of its async
        if (listener.root.children.length === 2) {
          expected.children.splice(1, 0, {
            name: 'reject',
            children: [],
            before: 1,
            after: 1,
            error: 0
          })
        }

        t.deepEqual(listener.root, expected);
        t.end();
      });

      listener.currentName = '2nd catch continuation';
    });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'reject',
        children: [
          {
            name: 'nextTick in nested promise',
            children: [
              {
                name: 'reject from nextTick',
                children: [
                  {
                    name: 'setTimeout in 2nd catch',
                    children: [],
                    before: 1,
                    after: 0,
                    error: 0
                  },
                  {
                    name: '2nd catch continuation',
                    children: [],
                    before: 0,
                    after: 0,
                    error: 0
                  }
                ],
                before: 1,
                after: 1,
                error: 0
              }
            ],
            before: 1,
            after: 1,
            error: 0
          }
        ],
        before: 1,
        after: 1,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

test('throw in executor', function(t) {
  var listener = addListner();

  var promise = new Promise(function unsafe() {
    listener.currentName = 'throw';
    throw 10;
  });

  promise.catch(function(val) {
    t.equal(val, 10, 'should match thrown value')
    if (listener.root.children.length === 2) {
      expected.children.splice(1, 0, {
        name: 'throw',
        children: [],
        before: 0,
        after: 0,
        error: 0
      })
    }

    t.deepEqual(listener.root, expected);
    t.end();
  });

  process.removeAsyncListener(listener.listener);

  var expected = {
    name: 'root',
    children: [
      {
        name: 'throw',
        children: [
        ],
        before: 1,
        after: 0,
        error: 0
      }
    ],
    before: 0,
    after: 0,
    error: 0
  }
});

function addListner() {
  var listener = process.addAsyncListener({
    create: create,
    before: before,
    after: after,
    error: error
  });

  var state = {
    listener: listener,
    currentName: 'root'
  };

  state.root = create();
  state.current = state.root;

  return state;

  function create () {
    var node = {
      name: state.currentName,
      children: [],
      before: 0,
      after: 0,
      error: 0
    };

    if(state.current) state.current.children.push(node);
    return node;
  }

  function before(ctx, node) {
    state.current = node;
    state.current.before++;
  }

  function after(ctx, node) {
    node.after++;
    state.current = null;
  }

  function error(ctx, node) {
    node.error++;
    state.current = null;
    return false;
  }
}