text:
package com.amazonaws.services.lambda.runtime.events.models.dynamodb;

import java.io.Serializable;

/**
 *

 * A description of a unique event within a stream.
 *

 *
 * @see AWS API
 *      Documentation
 */
public class Record implements Serializable, Cloneable {

    /**
     *

     * A globally unique identifier for the event that was recorded in this stream record.
     *

     */
    private String eventID;
    /**
     *

     * The type of data modification that was performed on the DynamoDB table:
     *

     *

     *

     *

     * INSERT - a new item was added to the table.
     *

     *

     *

     *

     * MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     * REMOVE - the item was deleted from the table
     *

     *

     *

     */
    private String eventName;
    /**
     *

     * The version number of the stream record format. This number is updated whenever the structure of
     * Record is modified.
     *

     *

     * Client applications must not assume that eventVersion will remain at a particular value, as this
     * number is subject to change at any time. In general, eventVersion will only increase as the
     * low-level DynamoDB Streams API evolves.
     *

     */
    private String eventVersion;
    /**
     *

     * The AWS service from which the stream record originated. For DynamoDB Streams, this is aws:dynamodb.
     *

     */
    private String eventSource;
    /**
     *

     * The region in which the GetRecords request was received.
     *

     */
    private String awsRegion;
    /**
     *

     * The main body of the stream record, containing all of the DynamoDB-specific fields.
     *

     */
    private StreamRecord dynamodb;
    /**
     *

     * Items that are deleted by the Time to Live process after expiration have the following fields:
     *

     *

     *

     *

     * Records[].userIdentity.type
     *

     *

     * "Service"
     *

     *

     *

     *

     * Records[].userIdentity.principalId
     *

     *

     * "dynamodb.amazonaws.com"
     *

     *

     *

     */
    private Identity userIdentity;

    /**
     *

     * A globally unique identifier for the event that was recorded in this stream record.
     *

     *
     * @param eventID
     *        A globally unique identifier for the event that was recorded in this stream record.
     */
    public void setEventID(String eventID) {
        this.eventID = eventID;
    }

    /**
     *

     * A globally unique identifier for the event that was recorded in this stream record.
     *

     *
     * @return A globally unique identifier for the event that was recorded in this stream record.
     */
    public String getEventID() {
        return this.eventID;
    }

    /**
     *

     * A globally unique identifier for the event that was recorded in this stream record.
     *

     *
     * @param eventID
     *        A globally unique identifier for the event that was recorded in this stream record.
     * @return Returns a reference to this object so that method calls can be chained together.
     */
    public Record withEventID(String eventID) {
        setEventID(eventID);
        return this;
    }

    /**
     *

     * The type of data modification that was performed on the DynamoDB table:
     *

     *

     *

     *

     * INSERT - a new item was added to the table.
     *

     *

     *

     *

     * MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     * REMOVE - the item was deleted from the table
     *

     *

     *

     *
     * @param eventName
     *        The type of data modification that was performed on the DynamoDB table:

     *

     *

     *

     *        INSERT - a new item was added to the table.
     *

     *

     *

     *

     *        MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     *        REMOVE - the item was deleted from the table
     *

     *

     * @see OperationType
     */
    public void setEventName(String eventName) {
        this.eventName = eventName;
    }

    /**
     *

     * The type of data modification that was performed on the DynamoDB table:
     *

     *

     *

     *

     * INSERT - a new item was added to the table.
     *

     *

     *

     *

     * MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     * REMOVE - the item was deleted from the table
     *

     *

     *

     *
     * @return The type of data modification that was performed on the DynamoDB table:

     *

     *

     *

     *         INSERT - a new item was added to the table.
     *

     *

     *

     *

     *         MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     *         REMOVE - the item was deleted from the table
     *

     *

     * @see OperationType
     */
    public String getEventName() {
        return this.eventName;
    }

    /**
     *

     * The type of data modification that was performed on the DynamoDB table:
     *

     *

     *

     *

     * INSERT - a new item was added to the table.
     *

     *

     *

     *

     * MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     * REMOVE - the item was deleted from the table
     *

     *

     *

     *
     * @param eventName
     *        The type of data modification that was performed on the DynamoDB table:

     *

     *

     *

     *        INSERT - a new item was added to the table.
     *

     *

     *

     *

     *        MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     *        REMOVE - the item was deleted from the table
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see OperationType
     */
    public Record withEventName(String eventName) {
        setEventName(eventName);
        return this;
    }

    /**
     *

     * The type of data modification that was performed on the DynamoDB table:
     *

     *

     *

     *

     * INSERT - a new item was added to the table.
     *

     *

     *

     *

     * MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     * REMOVE - the item was deleted from the table
     *

     *

     *

     *
     * @param eventName
     *        The type of data modification that was performed on the DynamoDB table:

     *

     *

     *

     *        INSERT - a new item was added to the table.
     *

     *

     *

     *

     *        MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     *        REMOVE - the item was deleted from the table
     *

     *

     * @see OperationType
     */
    public void setEventName(OperationType eventName) {
        this.eventName = eventName.toString();
    }

    /**
     *

     * The type of data modification that was performed on the DynamoDB table:
     *

     *

     *

     *

     * INSERT - a new item was added to the table.
     *

     *

     *

     *

     * MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     * REMOVE - the item was deleted from the table
     *

     *

     *

     *
     * @param eventName
     *        The type of data modification that was performed on the DynamoDB table:

     *

     *

     *

     *        INSERT - a new item was added to the table.
     *

     *

     *

     *

     *        MODIFY - one or more of an existing item's attributes were modified.
     *

     *

     *

     *

     *        REMOVE - the item was deleted from the table
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see OperationType
     */
    public Record withEventName(OperationType eventName) {
        setEventName(eventName);
        return this;
    }

    /**
     *

     * The version number of the stream record format. This number is updated whenever the structure of
     * Record is modified.
     *

     *

     * Client applications must not assume that eventVersion will remain at a particular value, as this
     * number is subject to change at any time. In general, eventVersion will only increase as the
     * low-level DynamoDB Streams API evolves.
     *

     *
     * @param eventVersion
     *        The version number of the stream record format. This number is updated whenever the structure of
     *        Record is modified.

     *

     *        Client applications must not assume that eventVersion will remain at a particular value, as
     *        this number is subject to change at any time. In general, eventVersion will only increase as
     *        the low-level DynamoDB Streams API evolves.
     */
    public void setEventVersion(String eventVersion) {
        this.eventVersion = eventVersion;
    }

    /**
     *

     * The version number of the stream record format. This number is updated whenever the structure of
     * Record is modified.
     *

     *

     * Client applications must not assume that eventVersion will remain at a particular value, as this
     * number is subject to change at any time. In general, eventVersion will only increase as the
     * low-level DynamoDB Streams API evolves.
     *

     *
     * @return The version number of the stream record format. This number is updated whenever the structure of
     *         Record is modified.

     *

     *         Client applications must not assume that eventVersion will remain at a particular value, as
     *         this number is subject to change at any time. In general, eventVersion will only increase as
     *         the low-level DynamoDB Streams API evolves.
     */
    public String getEventVersion() {
        return this.eventVersion;
    }

    /**
     *

     * The version number of the stream record format. This number is updated whenever the structure of
     * Record is modified.
     *

     *

     * Client applications must not assume that eventVersion will remain at a particular value, as this
     * number is subject to change at any time. In general, eventVersion will only increase as the
     * low-level DynamoDB Streams API evolves.
     *

     *
     * @param eventVersion
     *        The version number of the stream record format. This number is updated whenever the structure of
     *        Record is modified.

     *

     *        Client applications must not assume that eventVersion will remain at a particular value, as
     *        this number is subject to change at any time. In general, eventVersion will only increase as
     *        the low-level DynamoDB Streams API evolves.
     * @return Returns a reference to this object so that method calls can be chained together.
     */
    public Record withEventVersion(String eventVersion) {
        setEventVersion(eventVersion);
        return this;
    }

    /**
     *

     * The AWS service from which the stream record originated. For DynamoDB Streams, this is aws:dynamodb.
     *

     *
     * @param eventSource
     *        The AWS service from which the stream record originated. For DynamoDB Streams, this is
     *        aws:dynamodb.
     */
    public void setEventSource(String eventSource) {
        this.eventSource = eventSource;
    }

    /**
     *

     * The AWS service from which the stream record originated. For DynamoDB Streams, this is aws:dynamodb.
     *

     *
     * @return The AWS service from which the stream record originated. For DynamoDB Streams, this is
     *         aws:dynamodb.
     */
    public String getEventSource() {
        return this.eventSource;
    }

    /**
     *

     * The AWS service from which the stream record originated. For DynamoDB Streams, this is aws:dynamodb.
     *

     *
     * @param eventSource
     *        The AWS service from which the stream record originated. For DynamoDB Streams, this is
     *        aws:dynamodb.
     * @return Returns a reference to this object so that method calls can be chained together.
     */
    public Record withEventSource(String eventSource) {
        setEventSource(eventSource);
        return this;
    }

    /**
     *

     * The region in which the GetRecords request was received.
     *

     *
     * @param awsRegion
     *        The region in which the GetRecords request was received.
     */
    public void setAwsRegion(String awsRegion) {
        this.awsRegion = awsRegion;
    }

    /**
     *

     * The region in which the GetRecords request was received.
     *

     *
     * @return The region in which the GetRecords request was received.
     */
    public String getAwsRegion() {
        return this.awsRegion;
    }

    /**
     *

     * The region in which the GetRecords request was received.
     *

     *
     * @param awsRegion
     *        The region in which the GetRecords request was received.
     * @return Returns a reference to this object so that method calls can be chained together.
     */
    public Record withAwsRegion(String awsRegion) {
        setAwsRegion(awsRegion);
        return this;
    }

    /**
     *

     * The main body of the stream record, containing all of the DynamoDB-specific fields.
     *

     *
     * @param dynamodb
     *        The main body of the stream record, containing all of the DynamoDB-specific fields.
     */
    public void setDynamodb(StreamRecord dynamodb) {
        this.dynamodb = dynamodb;
    }

    /**
     *

     * The main body of the stream record, containing all of the DynamoDB-specific fields.
     *

     *
     * @return The main body of the stream record, containing all of the DynamoDB-specific fields.
     */
    public StreamRecord getDynamodb() {
        return this.dynamodb;
    }

    /**
     *

     * The main body of the stream record, containing all of the DynamoDB-specific fields.
     *

     *
     * @param dynamodb
     *        The main body of the stream record, containing all of the DynamoDB-specific fields.
     * @return Returns a reference to this object so that method calls can be chained together.
     */
    public Record withDynamodb(StreamRecord dynamodb) {
        setDynamodb(dynamodb);
        return this;
    }

    /**
     *

     * Items that are deleted by the Time to Live process after expiration have the following fields:
     *

     *

     *

     *

     * Records[].userIdentity.type
     *

     *

     * "Service"
     *

     *

     *

     *

     * Records[].userIdentity.principalId
     *

     *

     * "dynamodb.amazonaws.com"
     *

     *

     *

     *
     * @param userIdentity
     *        Items that are deleted by the Time to Live process after expiration have the following fields:

     *

     *

     *

     *        Records[].userIdentity.type
     *

     *

     *        "Service"
     *

     *

     *

     *

     *        Records[].userIdentity.principalId
     *

     *

     *        "dynamodb.amazonaws.com"
     *

     *

     */
    public void setUserIdentity(Identity userIdentity) {
        this.userIdentity = userIdentity;
    }

    /**
     *

     * Items that are deleted by the Time to Live process after expiration have the following fields:
     *

     *

     *

     *

     * Records[].userIdentity.type
     *

     *

     * "Service"
     *

     *

     *

     *

     * Records[].userIdentity.principalId
     *

     *

     * "dynamodb.amazonaws.com"
     *

     *

     *

     *
     * @return Items that are deleted by the Time to Live process after expiration have the following fields:

     *

     *

     *

     *         Records[].userIdentity.type
     *

     *

     *         "Service"
     *

     *

     *

     *

     *         Records[].userIdentity.principalId
     *

     *

     *         "dynamodb.amazonaws.com"
     *

     *

     */
    public Identity getUserIdentity() {
        return this.userIdentity;
    }

    /**
     *

     * Items that are deleted by the Time to Live process after expiration have the following fields:
     *

     *

     *

     *

     * Records[].userIdentity.type
     *

     *

     * "Service"
     *

     *

     *

     *

     * Records[].userIdentity.principalId
     *

     *

     * "dynamodb.amazonaws.com"
     *

     *

     *

     *
     * @param userIdentity
     *        Items that are deleted by the Time to Live process after expiration have the following fields:

     *

     *

     *

     *        Records[].userIdentity.type
     *

     *

     *        "Service"
     *

     *

     *

     *

     *        Records[].userIdentity.principalId
     *

     *

     *        "dynamodb.amazonaws.com"
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */
    public Record withUserIdentity(Identity userIdentity) {
        setUserIdentity(userIdentity);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getEventID() != null)
            sb.append("EventID: ").append(getEventID()).append(",");
        if (getEventName() != null)
            sb.append("EventName: ").append(getEventName()).append(",");
        if (getEventVersion() != null)
            sb.append("EventVersion: ").append(getEventVersion()).append(",");
        if (getEventSource() != null)
            sb.append("EventSource: ").append(getEventSource()).append(",");
        if (getAwsRegion() != null)
            sb.append("AwsRegion: ").append(getAwsRegion()).append(",");
        if (getDynamodb() != null)
            sb.append("Dynamodb: ").append(getDynamodb()).append(",");
        if (getUserIdentity() != null)
            sb.append("UserIdentity: ").append(getUserIdentity());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof Record == false)
            return false;
        Record other = (Record) obj;
        if (other.getEventID() == null ^ this.getEventID() == null)
            return false;
        if (other.getEventID() != null && other.getEventID().equals(this.getEventID()) == false)
            return false;
        if (other.getEventName() == null ^ this.getEventName() == null)
            return false;
        if (other.getEventName() != null && other.getEventName().equals(this.getEventName()) == false)
            return false;
        if (other.getEventVersion() == null ^ this.getEventVersion() == null)
            return false;
        if (other.getEventVersion() != null && other.getEventVersion().equals(this.getEventVersion()) == false)
            return false;
        if (other.getEventSource() == null ^ this.getEventSource() == null)
            return false;
        if (other.getEventSource() != null && other.getEventSource().equals(this.getEventSource()) == false)
            return false;
        if (other.getAwsRegion() == null ^ this.getAwsRegion() == null)
            return false;
        if (other.getAwsRegion() != null && other.getAwsRegion().equals(this.getAwsRegion()) == false)
            return false;
        if (other.getDynamodb() == null ^ this.getDynamodb() == null)
            return false;
        if (other.getDynamodb() != null && other.getDynamodb().equals(this.getDynamodb()) == false)
            return false;
        if (other.getUserIdentity() == null ^ this.getUserIdentity() == null)
            return false;
        if (other.getUserIdentity() != null && other.getUserIdentity().equals(this.getUserIdentity()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getEventID() == null) ? 0 : getEventID().hashCode());
        hashCode = prime * hashCode + ((getEventName() == null) ? 0 : getEventName().hashCode());
        hashCode = prime * hashCode + ((getEventVersion() == null) ? 0 : getEventVersion().hashCode());
        hashCode = prime * hashCode + ((getEventSource() == null) ? 0 : getEventSource().hashCode());
        hashCode = prime * hashCode + ((getAwsRegion() == null) ? 0 : getAwsRegion().hashCode());
        hashCode = prime * hashCode + ((getDynamodb() == null) ? 0 : getDynamodb().hashCode());
        hashCode = prime * hashCode + ((getUserIdentity() == null) ? 0 : getUserIdentity().hashCode());
        return hashCode;
    }

    @Override
    public Record clone() {
        try {
            return (Record) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
module Tracing
  module Template
    class Base

      # default template init
      def initialize(options = {})
        # no default init
      end

      # handle tracing after method call
      def handle_after_call(context)
        template = end_template(context)
        output(template, context)
      end

      # handle tracing before method call
      def handle_before_call(context)
        template = before_template(context)
        if context[:block]
          template << before_block_template
        end
        output(template, context)
      end

      def method_stack
        @method_stack ||= []
      end

      # override to increase # of spaces for each indenation level!
      def space_count
        1
      end

      # calculate indentation level, based on method stack level (# of nested method calls)
      def indentation
        s = ""
        lv = method_stack.empty? ? 0 : method_stack.size-1
        lv.times { s << (" " * space_count) }
        s
      end

      def output(template, context)
        # get spaces to indent each line
        spaces = indentation

        # modify template, inserting indentation
        lines = template.split("\n")
        lines.map!{|line| spaces + line + "\n"}
        template = lines.join

        # send modified template to output handler with context
        output_handler(template, context)
      end

      # default output action: put string to STDOUT
      # override this to customize trace handling
      def output_handler(template, context)
        # create new erb template
        erb_template = ERB.new template

        # evaluate erb template for output using context
        str_res = erb_template.result(binding)
        # send final output to action handlers for further processing...
        # action_handlers(str_res, context)
      end
    end # class
  end # template
end # tracing

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hive.ql.parse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx;

/**
 * This class implements the context information that is used for typechecking
 * phase in query compilation.
 */
public class TypeCheckCtx implements NodeProcessorCtx {
  protected static final Log LOG = LogFactory.getLog(TypeCheckCtx.class);

  /**
   * The row resolver of the previous operator. This field is used to generate
   * expression descriptors from the expression ASTs.
   */
  private RowResolver inputRR;

  /**
   * Receives translations which will need to be applied during unparse.
   */
  private UnparseTranslator unparseTranslator;

  /**
   * Potential typecheck error reason.
   */
  private String error;

  /**
   * The node that generated the potential typecheck error
   */
  private ASTNode errorSrcNode;

  /**
   * Whether to allow stateful UDF invocations.
   */
  private boolean allowStatefulFunctions;

  private boolean allowDistinctFunctions;

  private final boolean allowGBExprElimination;

  private final boolean allowAllColRef;

  private final boolean allowFunctionStar;

  private final boolean allowWindowing;

  // "[]" : LSQUARE/INDEX Expression
  private final boolean allowIndexExpr;

  private final boolean allowSubQueryExpr;

  /**
   * Constructor.
   *
   * @param inputRR
   *          The input row resolver of the previous operator.
   */
  public TypeCheckCtx(RowResolver inputRR) {
    this(inputRR, false, true, true, true, true, true, true, true);
  }

  public TypeCheckCtx(RowResolver inputRR, boolean allowStatefulFunctions,
      boolean allowDistinctFunctions, boolean allowGBExprElimination, boolean allowAllColRef,
      boolean allowFunctionStar, boolean allowWindowing,
      boolean allowIndexExpr, boolean allowSubQueryExpr) {
    setInputRR(inputRR);
    error = null;
    this.allowStatefulFunctions = allowStatefulFunctions;
    this.allowDistinctFunctions = allowDistinctFunctions;
    this.allowGBExprElimination = allowGBExprElimination;
    this.allowAllColRef = allowAllColRef;
    this.allowFunctionStar = allowFunctionStar;
    this.allowWindowing = allowWindowing;
    this.allowIndexExpr = allowIndexExpr;
    this.allowSubQueryExpr = allowSubQueryExpr;
  }

  /**
   * @param inputRR
   *          the inputRR to set
   */
  public void setInputRR(RowResolver inputRR) {
    this.inputRR = inputRR;
  }

  /**
   * @return the inputRR
   */
  public RowResolver getInputRR() {
    return inputRR;
  }

  /**
   * @param unparseTranslator
   *          the unparseTranslator to set
   */
  public void setUnparseTranslator(UnparseTranslator unparseTranslator) {
    this.unparseTranslator = unparseTranslator;
  }

  /**
   * @return the unparseTranslator
   */
  public UnparseTranslator getUnparseTranslator() {
    return unparseTranslator;
  }

  /**
   * @param allowStatefulFunctions
   *          whether to allow stateful UDF invocations
   */
  public void setAllowStatefulFunctions(boolean allowStatefulFunctions) {
    this.allowStatefulFunctions = allowStatefulFunctions;
  }

  /**
   * @return whether to allow stateful UDF invocations
   */
  public boolean getAllowStatefulFunctions() {
    return allowStatefulFunctions;
  }

  /**
   * @param error
   *          the error to set
   *
   */
  public void setError(String error, ASTNode errorSrcNode) {
    if (LOG.isDebugEnabled()) {
      // Log the callstack from which the error has been set.
      LOG.debug("Setting error: [" + error + "] from "
          + ((errorSrcNode == null) ? "null" : errorSrcNode.toStringTree()), new Exception());
    }
    this.error = error;
    this.errorSrcNode = errorSrcNode;
  }

  /**
   * @return the error
   */
  public String getError() {
    return error;
  }

  public ASTNode getErrorSrcNode() {
    return errorSrcNode;
  }

  public void setAllowDistinctFunctions(boolean allowDistinctFunctions) {
    this.allowDistinctFunctions = allowDistinctFunctions;
  }

  public boolean getAllowDistinctFunctions() {
    return allowDistinctFunctions;
  }

  public boolean getAllowGBExprElimination() {
    return allowGBExprElimination;
  }

  public boolean getallowAllColRef() {
    return allowAllColRef;
  }

  public boolean getallowFunctionStar() {
    return allowFunctionStar;
  }

  public boolean getallowWindowing() {
    return allowWindowing;
  }

  public boolean getallowIndexExpr() {
    return allowIndexExpr;
  }

  public boolean getallowSubQueryExpr() {
    return allowSubQueryExpr;
  }
}


text:
// Package envelope transforms values for storage at rest using a Envelope provider
package envelope

import (
	"context"
	"fmt"
	"net"
	"net/url"
	"strings"
	"time"

	"github.com/golang/glog"

	"google.golang.org/grpc"

	kmsapi "k8s.io/apiserver/pkg/storage/value/encrypt/envelope/v1beta1"
)

const (
	// Now only supported unix domain socket.
	unixProtocol = "unix"

	// Current version for the protocol interface definition.
	kmsapiVersion = "v1beta1"

	// The timeout that communicate with KMS server.
	timeout = 30 * time.Second
)

// The gRPC implementation for envelope.Service.
type gRPCService struct {
	// gRPC client instance
	kmsClient  kmsapi.KeyManagementServiceClient
	connection *grpc.ClientConn
}

// NewGRPCService returns an envelope.Service which use gRPC to communicate the remote KMS provider.
func NewGRPCService(endpoint string) (Service, error) {
	glog.V(4).Infof("Configure KMS provider with endpoint: %s", endpoint)

	addr, err := parseEndpoint(endpoint)
	if err != nil {
		return nil, err
	}

	connection, err := grpc.Dial(addr, grpc.WithInsecure(), grpc.WithTimeout(timeout), grpc.WithDialer(unixDial))
	if err != nil {
		return nil, fmt.Errorf("connect remote KMS provider %q failed, error: %v", addr, err)
	}

	kmsClient := kmsapi.NewKeyManagementServiceClient(connection)

	err = checkAPIVersion(kmsClient)
	if err != nil {
		connection.Close()
		return nil, fmt.Errorf("failed check version for %q, error: %v", addr, err)
	}

	return &gRPCService{kmsClient: kmsClient, connection: connection}, nil
}

// This dialer explicitly ask gRPC to use unix socket as network.
func unixDial(addr string, timeout time.Duration) (net.Conn, error) {
	return net.DialTimeout(unixProtocol, addr, timeout)
}

// Parse the endpoint to extract schema, host or path.
func parseEndpoint(endpoint string) (string, error) {
	if len(endpoint) == 0 {
		return "", fmt.Errorf("remote KMS provider can't use empty string as endpoint")
	}

	u, err := url.Parse(endpoint)
	if err != nil {
		return "", fmt.Errorf("invalid endpoint %q for remote KMS provider, error: %v", endpoint, err)
	}

	if u.Scheme != unixProtocol {
		return "", fmt.Errorf("unsupported scheme %q for remote KMS provider", u.Scheme)
	}

	// Linux abstract namespace socket - no physical file required
	// Warning: Linux Abstract sockets have not concept of ACL (unlike traditional file based sockets).
	// However, Linux Abstract sockets are subject to Linux networking namespace, so will only be accessible to
	// containers within the same pod (unless host networking is used).
	if strings.HasPrefix(u.Path, "/@") {
		return strings.TrimPrefix(u.Path, "/"), nil
	}

	return u.Path, nil
}

// Check the KMS provider API version.
// Only matching kmsapiVersion is supported now.
func checkAPIVersion(kmsClient kmsapi.KeyManagementServiceClient) error {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	request := &kmsapi.VersionRequest{Version: kmsapiVersion}
	response, err := kmsClient.Version(ctx, request)
	if err != nil {
		return fmt.Errorf("failed get version from remote KMS provider: %v", err)
	}
	if response.Version != kmsapiVersion {
		return fmt.Errorf("KMS provider api version %s is not supported, only %s is supported now",
			response.Version, kmsapiVersion)
	}

	glog.V(4).Infof("KMS provider %s initialized, version: %s", response.RuntimeName, response.RuntimeVersion)
	return nil
}

// Decrypt a given data string to obtain the original byte data.
func (g *gRPCService) Decrypt(cipher []byte) ([]byte, error) {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	request := &kmsapi.DecryptRequest{Cipher: cipher, Version: kmsapiVersion}
	response, err := g.kmsClient.Decrypt(ctx, request)
	if err != nil {
		return nil, err
	}
	return response.Plain, nil
}

// Encrypt bytes to a string ciphertext.
func (g *gRPCService) Encrypt(plain []byte) ([]byte, error) {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	request := &kmsapi.EncryptRequest{Plain: plain, Version: kmsapiVersion}
	response, err := g.kmsClient.Encrypt(ctx, request)
	if err != nil {
		return nil, err
	}
	return response.Cipher, nil
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>Commit And Rollback Notification Callbacks</title>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

Small. Fast. Reliable.
Choose any three.

    About
    Sitemap
    Documentation
    Download
    License
    News
    Developers
    Support

SQLite C Interface

Commit And Rollback Notification Callbacks

void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);

The sqlite3_commit_hook() interface registers a callback
function to be invoked whenever a transaction is committed.
Any callback set by a previous call to sqlite3_commit_hook()
for the same database connection is overridden.
The sqlite3_rollback_hook() interface registers a callback
function to be invoked whenever a transaction is committed.
Any callback set by a previous call to sqlite3_commit_hook()
for the same database connection is overridden.
The pArg argument is passed through to the callback.
If the callback on a commit hook function returns non-zero,
then the commit is converted into a rollback.

If another function was previously registered, its
pArg value is returned.  Otherwise NULL is returned.

The callback implementation must not do anything that will modify
the database connection that invoked the callback.  Any actions
to modify the database connection must be deferred until after the
completion of the sqlite3_step() call that triggered the commit
or rollback hook in the first place.
Note that sqlite3_prepare_v2() and sqlite3_step() both modify their
database connections for the meaning of "modify" in this paragraph.

Registering a NULL function disables the callback.

For the purposes of this API, a transaction is said to have been
rolled back if an explicit "ROLLBACK" statement is executed, or
an error or constraint causes an implicit rollback to occur.
The rollback callback is not invoked if a transaction is
automatically rolled back because the database connection is closed.
The rollback callback is not invoked if a transaction is
rolled back because a commit callback returned non-zero.
(TODO:  Check on this )

Requirements:
H12951 H12952 H12953 H12954 H12955
H12961 H12962 H12963 H12964

See also lists of
  Objects,
  Constants, and
  Functions.

This page last modified 2009/02/18 18:03:35 UTC


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace SoftwarePatterns.Core.State
{
	public class WorkItem : ICommands
	{
		private static WorkItemContainer _container;
		private Status _state;
		private List<Type> _stateCommandTypes;
		private ICommands _stateCommands;

		public WorkItem()
		{
		}

		public string Description { get; set; }

		public int Id { get; set; }
		public string Name { get; set; }

		public Status State
		{
			get { return _state; }
			set
			{
				_state = value;
				SetStateCommands();
			}
		}

		private void LoadPossibleTypes()
		{
			_stateCommandTypes = Assembly
				.GetExecutingAssembly()
				.GetTypes()
				.Where(type => !type.IsAbstract
					&& type.Name != typeof(WorkItem).Name.ToString(CultureInfo.InvariantCulture)
					&&  type.GetInterface(typeof (ICommands).ToString()) != null)
				.ToList();
		}

		private void SetStateCommands()
		{
			if (_stateCommandTypes == null)
				LoadPossibleTypes();

			if (_stateCommandTypes != null)
			{
				var command = _stateCommandTypes
					.Where(type => type.Name.ToLowerInvariant().Contains(_state.ToString().ToLowerInvariant()))
					.Select(type => (ICommands) Activator.CreateInstance(type, this))
					.FirstOrDefault();

				if (command == null) throw new ArgumentException("Can't find state command for the given state");

				_stateCommands = command;
			}
		}

		public bool Delete()
		{
			var canDelete = _stateCommands.Delete();
			if (canDelete)
				_container.Remove(this);
			return canDelete;
		}

		public void Edit(string name, string description)
		{
			_stateCommands.Edit(name, description);
		}

		public void Print()
		{
			_stateCommands.Print();
		}

		public void SetState(Status newState)
		{
			_stateCommands.SetState(newState);
		}

		public static WorkItem Create()
		{
			var wi = new WorkItem {Id = -1, State = Status.Proposed};
			_container.Add(wi);
			return wi;
		}

		public static WorkItem FindById(int id)
		{
			return _container.WorkItems.FirstOrDefault(item => item.Id == id);
		}

		public static void Init(WorkItemContainer container)
		{
			_container = container;
		}
	}
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\User;

use Auth;

class UserController extends Controller
{
    public function create()
    {
    	return view('user.create');
    }

    public function show($id)
    {
    	$user = User::findOrFail($id);
    	return view('user.show', compact('user'));
    }

    public function store(Request $request)
    {
    	$this->validate($request, [
    		'name' => 'required|max:24',
    		'email' => 'required|email|unique:users|max:255',
    		'password' => 'confirmed'
    	]);

    	$user = User::create([
    		'name' => $request->name,
    		'email' => $request->email,
    		'password' => $request->password,
    	]);
        // 自动登录
    	Auth::login($user);
    	session()->flash('success', '注册成功,新的旅程即将开始...');
    	return redirect()->route('users.show', [$user]);
    }
}


text:
/*
    Based on the Public Domain MaxRectanglesBinPack.cpp source by Jukka Jylänki
    https://github.com/juj/RectangleBinPack/

    Originally Ported to C# by Sven Magnus
    Updated to .Net 4.5 by Stefan Gordon
*/

using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;

public class MaxRectanglesBinPack
{

    public int binWidth = 0;
    public int binHeight = 0;
    public bool allowRotations;

    public List<Rectangle> usedRectangles = new List<Rectangle>();
    public List<Rectangle> freeRectangles = new List<Rectangle>();

    public enum FreeRectangleChoiceHeuristic
    {
        RectangleBestShortSideFit, // -BSSF: Positions the Rectangleangle against the short side of a free Rectangleangle into which it fits the best.
        RectangleBestLongSideFit, // -BLSF: Positions the Rectangleangle against the long side of a free Rectangleangle into which it fits the best.
        RectangleBestAreaFit, // -BAF: Positions the Rectangleangle into the smallest free Rectangle into which it fits.
        RectangleBottomLeftRule,	// -BL: Does the Tetris placement.
        RectangleContactPointRule // -CP: Choosest the placement where the Rectangleangle touches other Rectangles as much as possible.
    };

    public MaxRectanglesBinPack(int width, int height, bool rotations = true)
    {
        Init(width, height, rotations);
    }

    public void Init(int width, int height, bool rotations = true)
    {
        binWidth = width;
        binHeight = height;
        allowRotations = rotations;

        Rectangle n = new Rectangle();
        n.X = 0;
        n.Y = 0;
        n.Width = width;
        n.Height = height;

        usedRectangles.Clear();

        freeRectangles.Clear();
        freeRectangles.Add(n);
    }

    public Rectangle Insert(int width, int height, FreeRectangleChoiceHeuristic method, CancellationToken cancellationToken)
    {
        Rectangle newNode = new Rectangle();
        int score1 = 0;	// Unused in this function. We don't need to know the score after finding the position.
        int score2 = 0;
        switch (method)
        {
            case FreeRectangleChoiceHeuristic.RectangleBestShortSideFit: newNode = FindPositionForNewNodeBestShortSideFit(width, height, ref score1, ref score2); break;
            case FreeRectangleChoiceHeuristic.RectangleBottomLeftRule: newNode = FindPositionForNewNodeBottomLeft(width, height, ref score1, ref score2); break;
            case FreeRectangleChoiceHeuristic.RectangleContactPointRule: newNode = FindPositionForNewNodeContactPoint(width, height, ref score1); break;
            case FreeRectangleChoiceHeuristic.RectangleBestLongSideFit: newNode = FindPositionForNewNodeBestLongSideFit(width, height, ref score2, ref score1); break;
            case FreeRectangleChoiceHeuristic.RectangleBestAreaFit: newNode = FindPositionForNewNodeBestAreaFit(width, height, ref score1, ref score2); break;
        }

        if (newNode.Height == 0)
            return newNode;

        int numRectangleanglesToProcess = freeRectangles.Count;
        for (int i = 0; i < numRectangleanglesToProcess; ++i)
        {
            if (SplitFreeNode(freeRectangles[i], ref newNode))
            {
                freeRectangles.RemoveAt(i);
                --i;
                --numRectangleanglesToProcess;
            }
        }

        PruneFreeList(cancellationToken);

        usedRectangles.Add(newNode);
        return newNode;
    }

    void PlaceRectangle(Rectangle node)
    {
        int numRectangleanglesToProcess = freeRectangles.Count;
        for (int i = 0; i < numRectangleanglesToProcess; ++i)
        {
            if (SplitFreeNode(freeRectangles[i], ref node))
            {
                freeRectangles.RemoveAt(i);
                --i;
                --numRectangleanglesToProcess;
            }
        }

        PruneFreeList(new CancellationToken());

        usedRectangles.Add(node);
    }

    Rectangle ScoreRectangle(int width, int height, FreeRectangleChoiceHeuristic method, ref int score1, ref int score2)
    {
        Rectangle newNode = new Rectangle();
        score1 = int.MaxValue;
        score2 = int.MaxValue;
        switch (method)
        {
            case FreeRectangleChoiceHeuristic.RectangleBestShortSideFit: newNode = FindPositionForNewNodeBestShortSideFit(width, height, ref score1, ref score2); break;
            case FreeRectangleChoiceHeuristic.RectangleBottomLeftRule: newNode = FindPositionForNewNodeBottomLeft(width, height, ref score1, ref score2); break;
            case FreeRectangleChoiceHeuristic.RectangleContactPointRule:
                newNode = FindPositionForNewNodeContactPoint(width, height, ref score1);
                score1 = -score1; // Reverse since we are minimizing, but for contact point score bigger is better.
                break;
            case FreeRectangleChoiceHeuristic.RectangleBestLongSideFit: newNode = FindPositionForNewNodeBestLongSideFit(width, height, ref score2, ref score1); break;
            case FreeRectangleChoiceHeuristic.RectangleBestAreaFit: newNode = FindPositionForNewNodeBestAreaFit(width, height, ref score1, ref score2); break;
        }

        // Cannot fit the current Rectangleangle.
        if (newNode.Height == 0)
        {
            score1 = int.MaxValue;
            score2 = int.MaxValue;
        }

        return newNode;
    }

    /// Computes the ratio of used surface area.
    public float Occupancy()
    {
        ulong usedSurfaceArea = 0;
        for (int i = 0; i < usedRectangles.Count; ++i)
            usedSurfaceArea += (uint)usedRectangles[i].Width * (uint)usedRectangles[i].Height;

        return (float)usedSurfaceArea / (binWidth * binHeight);
    }

    Rectangle FindPositionForNewNodeBottomLeft(int width, int height, ref int bestY, ref int bestX)
    {
        Rectangle bestNode = new Rectangle();
        //memset(bestNode, 0, sizeof(Rectangle));

        bestY = int.MaxValue;

        for (int i = 0; i < freeRectangles.Count; ++i)
        {
            // Try to place the Rectangleangle in upright (non-flipped) orientation.
            if (freeRectangles[i].Width >= width && freeRectangles[i].Height >= height)
            {
                int topSideY = (int)freeRectangles[i].Y + height;
                if (topSideY < bestY || (topSideY == bestY && freeRectangles[i].X < bestX))
                {
                    bestNode.X = freeRectangles[i].X;
                    bestNode.Y = freeRectangles[i].Y;
                    bestNode.Width = width;
                    bestNode.Height = height;
                    bestY = topSideY;
                    bestX = (int)freeRectangles[i].X;
                }
            }
            if (allowRotations && freeRectangles[i].Width >= height && freeRectangles[i].Height >= width)
            {
                int topSideY = (int)freeRectangles[i].Y + width;
                if (topSideY < bestY || (topSideY == bestY && freeRectangles[i].X < bestX))
                {
                    bestNode.X = freeRectangles[i].X;
                    bestNode.Y = freeRectangles[i].Y;
                    bestNode.Width = height;
                    bestNode.Height = width;
                    bestY = topSideY;
                    bestX = (int)freeRectangles[i].X;
                }
            }
        }
        return bestNode;
    }

    Rectangle FindPositionForNewNodeBestShortSideFit(int width, int height, ref int bestShortSideFit, ref int bestLongSideFit)
    {
        Rectangle bestNode = new Rectangle();
        //memset(&bestNode, 0, sizeof(Rectangle));

        bestShortSideFit = int.MaxValue;

        for (int i = 0; i < freeRectangles.Count; ++i)
        {
            // Try to place the Rectangleangle in upright (non-flipped) orientation.
            if (freeRectangles[i].Width >= width && freeRectangles[i].Height >= height)
            {
                int leftoverHoriz = System.Math.Abs((int)freeRectangles[i].Width - width);
                int leftoverVert = System.Math.Abs((int)freeRectangles[i].Height - height);
                int shortSideFit = System.Math.Min(leftoverHoriz, leftoverVert);
                int longSideFit = System.Math.Max(leftoverHoriz, leftoverVert);

                if (shortSideFit < bestShortSideFit || (shortSideFit == bestShortSideFit && longSideFit < bestLongSideFit))
                {
                    bestNode.X = freeRectangles[i].X;
                    bestNode.Y = freeRectangles[i].Y;
                    bestNode.Width = width;
                    bestNode.Height = height;
                    bestShortSideFit = shortSideFit;
                    bestLongSideFit = longSideFit;
                }
            }

            if (allowRotations && freeRectangles[i].Width >= height && freeRectangles[i].Height >= width)
            {
                int flippedLeftoverHoriz = System.Math.Abs((int)freeRectangles[i].Width - height);
                int flippedLeftoverVert = System.Math.Abs((int)freeRectangles[i].Height - width);
                int flippedShortSideFit = System.Math.Min(flippedLeftoverHoriz, flippedLeftoverVert);
                int flippedLongSideFit = System.Math.Max(flippedLeftoverHoriz, flippedLeftoverVert);

                if (flippedShortSideFit < bestShortSideFit || (flippedShortSideFit == bestShortSideFit && flippedLongSideFit < bestLongSideFit))
                {
                    bestNode.X = freeRectangles[i].X;
                    bestNode.Y = freeRectangles[i].Y;
                    bestNode.Width = height;
                    bestNode.Height = width;
                    bestShortSideFit = flippedShortSideFit;
                    bestLongSideFit = flippedLongSideFit;
                }
            }
        }
        return bestNode;
    }

    Rectangle FindPositionForNewNodeBestLongSideFit(int width, int height, ref int bestShortSideFit, ref int bestLongSideFit)
    {
        Rectangle bestNode = new Rectangle();
        //memset(&bestNode, 0, sizeof(Rectangle));

        bestLongSideFit = int.MaxValue;

        for (int i = 0; i < freeRectangles.Count; ++i)
        {
            // Try to place the Rectangleangle in upright (non-flipped) orientation.
            if (freeRectangles[i].Width >= width && freeRectangles[i].Height >= height)
            {
                int leftoverHoriz = System.Math.Abs((int)freeRectangles[i].Width - width);
                int leftoverVert = System.Math.Abs((int)freeRectangles[i].Height - height);
                int shortSideFit = System.Math.Min(leftoverHoriz, leftoverVert);
                int longSideFit = System.Math.Max(leftoverHoriz, leftoverVert);

                if (longSideFit < bestLongSideFit || (longSideFit == bestLongSideFit && shortSideFit < bestShortSideFit))
                {
                    bestNode.X = freeRectangles[i].X;
                    bestNode.Y = freeRectangles[i].Y;
                    bestNode.Width = width;
                    bestNode.Height = height;
                    bestShortSideFit = shortSideFit;
                    bestLongSideFit = longSideFit;
                }
            }

            if (allowRotations && freeRectangles[i].Width >= height && freeRectangles[i].Height >= width)
            {
                int leftoverHoriz = System.Math.Abs((int)freeRectangles[i].Width - height);
                int leftoverVert = System.Math.Abs((int)freeRectangles[i].Height - width);
                int shortSideFit = System.Math.Min(leftoverHoriz, leftoverVert);
                int longSideFit = System.Math.Max(leftoverHoriz, leftoverVert);

                if (longSideFit < bestLongSideFit || (longSideFit == bestLongSideFit && shortSideFit < bestShortSideFit))
                {
                    bestNode.X = freeRectangles[i].X;
                    bestNode.Y = freeRectangles[i].Y;
                    bestNode.Width = height;
                    bestNode.Height = width;
                    bestShortSideFit = shortSideFit;
                    bestLongSideFit = longSideFit;
                }
            }
        }
        return bestNode;
    }

    Rectangle FindPositionForNewNodeBestAreaFit(int width, int height, ref int bestAreaFit, ref int bestShortSideFit)
    {
        Rectangle bestNode = new Rectangle();
        //memset(&bestNode, 0, sizeof(Rectangle));

        bestAreaFit = int.MaxValue;

        for (int i = 0; i < freeRectangles.Count; ++i)
        {
            int areaFit = (int)freeRectangles[i].Width * (int)freeRectangles[i].Height - width * height;

            // Try to place the Rectangleangle in upright (non-flipped) orientation.
            if (freeRectangles[i].Width >= width && freeRectangles[i].Height >= height)
            {
                int leftoverHoriz = System.Math.Abs((int)freeRectangles[i].Width - width);
                int leftoverVert = System.Math.Abs((int)freeRectangles[i].Height - height);
                int shortSideFit = System.Math.Min(leftoverHoriz, leftoverVert);

                if (areaFit < bestAreaFit || (areaFit == bestAreaFit && shortSideFit < bestShortSideFit))
                {
                    bestNode.X = freeRectangles[i].X;
                    bestNode.Y = freeRectangles[i].Y;
                    bestNode.Width = width;
                    bestNode.Height = height;
                    bestShortSideFit = shortSideFit;
                    bestAreaFit = areaFit;
                }
            }

            if (allowRotations && freeRectangles[i].Width >= height && freeRectangles[i].Height >= width)
            {
                int leftoverHoriz = System.Math.Abs((int)freeRectangles[i].Width - height);
                int leftoverVert = System.Math.Abs((int)freeRectangles[i].Height - width);
                int shortSideFit = System.Math.Min(leftoverHoriz, leftoverVert);

                if (areaFit < bestAreaFit || (areaFit == bestAreaFit && shortSideFit < bestShortSideFit))
                {
                    bestNode.X = freeRectangles[i].X;
                    bestNode.Y = freeRectangles[i].Y;
                    bestNode.Width = height;
                    bestNode.Height = width;
                    bestShortSideFit = shortSideFit;
                    bestAreaFit = areaFit;
                }
            }
        }
        return bestNode;
    }

    /// Returns 0 if the two intervals i1 and i2 are disjoint, or the length of their overlap otherwise.
    int CommonIntervalLength(int i1start, int i1end, int i2start, int i2end)
    {
        if (i1end < i2start || i2end < i1start)
            return 0;
        return System.Math.Min(i1end, i2end) - System.Math.Max(i1start, i2start);
    }

    int ContactPointScoreNode(int x, int y, int width, int height)
    {
        int score = 0;

        if (x == 0 || x + width == binWidth)
            score += height;
        if (y == 0 || y + height == binHeight)
            score += width;

        for (int i = 0; i < usedRectangles.Count; ++i)
        {
            if (usedRectangles[i].X == x + width || usedRectangles[i].X + usedRectangles[i].Width == x)
                score += CommonIntervalLength((int)usedRectangles[i].Y, (int)usedRectangles[i].Y + (int)usedRectangles[i].Height, y, y + height);
            if (usedRectangles[i].Y == y + height || usedRectangles[i].Y + usedRectangles[i].Height == y)
                score += CommonIntervalLength((int)usedRectangles[i].X, (int)usedRectangles[i].X + (int)usedRectangles[i].Width, x, x + width);
        }
        return score;
    }

    Rectangle FindPositionForNewNodeContactPoint(int width, int height, ref int bestContactScore)
    {
        Rectangle bestNode = new Rectangle();
        //memset(&bestNode, 0, sizeof(Rectangle));

        bestContactScore = -1;

        for (int i = 0; i < freeRectangles.Count; ++i)
        {
            // Try to place the Rectangleangle in upright (non-flipped) orientation.
            if (freeRectangles[i].Width >= width && freeRectangles[i].Height >= height)
            {
                int score = ContactPointScoreNode((int)freeRectangles[i].X, (int)freeRectangles[i].Y, width, height);
                if (score > bestContactScore)
                {
                    bestNode.X = (int)freeRectangles[i].X;
                    bestNode.Y = (int)freeRectangles[i].Y;
                    bestNode.Width = width;
                    bestNode.Height = height;
                    bestContactScore = score;
                }
            }
            if (allowRotations && freeRectangles[i].Width >= height && freeRectangles[i].Height >= width)
            {
                int score = ContactPointScoreNode((int)freeRectangles[i].X, (int)freeRectangles[i].Y, height, width);
                if (score > bestContactScore)
                {
                    bestNode.X = (int)freeRectangles[i].X;
                    bestNode.Y = (int)freeRectangles[i].Y;
                    bestNode.Width = height;
                    bestNode.Height = width;
                    bestContactScore = score;
                }
            }
        }
        return bestNode;
    }

    bool SplitFreeNode(Rectangle freeNode, ref Rectangle usedNode)
    {
        // Test with SAT if the Rectangleangles even intersect.
        if (usedNode.X >= freeNode.X + freeNode.Width || usedNode.X + usedNode.Width <= freeNode.X ||
            usedNode.Y >= freeNode.Y + freeNode.Height || usedNode.Y + usedNode.Height <= freeNode.Y)
            return false;

        if (usedNode.X < freeNode.X + freeNode.Width && usedNode.X + usedNode.Width > freeNode.X)
        {
            // New node at the top side of the used node.
            if (usedNode.Y > freeNode.Y && usedNode.Y < freeNode.Y + freeNode.Height)
            {
                Rectangle newNode = freeNode;
                newNode.Height = usedNode.Y - newNode.Y;
                freeRectangles.Add(newNode);
            }

            // New node at the bottom side of the used node.
            if (usedNode.Y + usedNode.Height < freeNode.Y + freeNode.Height)
            {
                Rectangle newNode = freeNode;
                newNode.Y = usedNode.Y + usedNode.Height;
                newNode.Height = freeNode.Y + freeNode.Height - (usedNode.Y + usedNode.Height);
                freeRectangles.Add(newNode);
            }
        }

        if (usedNode.Y < freeNode.Y + freeNode.Height && usedNode.Y + usedNode.Height > freeNode.Y)
        {
            // New node at the left side of the used node.
            if (usedNode.X > freeNode.X && usedNode.X < freeNode.X + freeNode.Width)
            {
                Rectangle newNode = freeNode;
                newNode.Width = usedNode.X - newNode.X;
                freeRectangles.Add(newNode);
            }

            // New node at the right side of the used node.
            if (usedNode.X + usedNode.Width < freeNode.X + freeNode.Width)
            {
                Rectangle newNode = freeNode;
                newNode.X = usedNode.X + usedNode.Width;
                newNode.Width = freeNode.X + freeNode.Width - (usedNode.X + usedNode.Width);
                freeRectangles.Add(newNode);
            }
        }

        return true;
    }

    void PruneFreeList(CancellationToken cancellationToken)
    {
        SortedSet<int> rectanglesToRemove = new SortedSet<int>();

        Parallel.For(0,freeRectangles.Count, new ParallelOptions() { CancellationToken = cancellationToken }, i =>
        {
            for (int j = i + 1; j < freeRectangles.Count; ++j)
            {
                if (rectanglesToRemove.Contains(j) || rectanglesToRemove.Contains(i))
                {
                    break;
                }

                if (freeRectangles[j].Contains(freeRectangles[i]))
                {
                    lock (rectanglesToRemove)
                    {
                        rectanglesToRemove.Add(i);
                    }
                    break;
                }

                if (freeRectangles[i].Contains(freeRectangles[j]))
                {
                    lock (rectanglesToRemove)
                    {
                        rectanglesToRemove.Add(j);
                    }
                }
            }
        });

        foreach (var rectangleToRemove in rectanglesToRemove.Reverse())
        {
            freeRectangles.RemoveAt(rectangleToRemove);
        }
    }
}


text:
layout: post
title: "Execute lambdas inside mock with Moq"
date: 2014-06-30 +1100
comments: true
categories: ['moq', 'mock', 'unit test', 'tdd']
---

So a colleague asked me if it was possible using Moq to mock a dependency, yet call the lambda function
that is passed to it.

It is, here's how;

Take the following class, you could imagine that the dependency is some sort of business process that will crunch the data returned from the lambda. This is a contrived example and you could do the same thing without the lambda. The main take away is to show how to mock a dependency and still have the lambda from the calling class consumed.

```
public class MyClass
{
  private readonly IDependency dependency;

  public MyClass(IDependency dependency) {
    this.dependency = dependency;
  }

  public IEnumerable<MyOtherClass> GetOtherClasses() {
    return dependency.RunSomeProcess(LoadData);
  }

  private IEnumerable<MyOtherClass> LoadData() {
    return new List<MyOtherClass> {
      new MyOtherClass()
    };
  }
}

```

Now the Moq setup

```
var mockDependency = new Mock<IDependency>()
  .Setup(m => m.RunSomeProcess(It.IsAny<Func<IEnumerable<MyOtherClass>>>))
  .Returns((IEnumerable<MyOtherClass> callback) => callback());
```

That's it! Now the ``LoadData`` method will get called when the mock signature is matched.


text:
#ifndef P2P_BASE_CONNECTION_H_
#define P2P_BASE_CONNECTION_H_

#include <memory>
#include <string>
#include <vector>

#include "absl/types/optional.h"
#include "api/candidate.h"
#include "api/transport/stun.h"
#include "logging/rtc_event_log/ice_logger.h"
#include "p2p/base/candidate_pair_interface.h"
#include "p2p/base/connection_info.h"
#include "p2p/base/p2p_transport_channel_ice_field_trials.h"
#include "p2p/base/stun_request.h"
#include "p2p/base/transport_description.h"
#include "rtc_base/async_packet_socket.h"
#include "rtc_base/message_handler.h"
#include "rtc_base/network.h"
#include "rtc_base/numerics/event_based_exponential_moving_average.h"
#include "rtc_base/rate_tracker.h"

namespace cricket {

// Version number for GOOG_PING, this is added to have the option of
// adding other flavors in the future.
constexpr int kGoogPingVersion = 1;

// Connection and Port has circular dependencies.
// So we use forward declaration rather than include.
class Port;

// Forward declaration so that a ConnectionRequest can contain a Connection.
class Connection;

struct CandidatePair final : public CandidatePairInterface {
  ~CandidatePair() override = default;

  const Candidate& local_candidate() const override { return local; }
  const Candidate& remote_candidate() const override { return remote; }

  Candidate local;
  Candidate remote;
};

// A ConnectionRequest is a simple STUN ping used to determine writability.
class ConnectionRequest : public StunRequest {
 public:
  explicit ConnectionRequest(Connection* connection);
  void Prepare(StunMessage* request) override;
  void OnResponse(StunMessage* response) override;
  void OnErrorResponse(StunMessage* response) override;
  void OnTimeout() override;
  void OnSent() override;
  int resend_delay() override;

 private:
  Connection* connection_;
};

// Represents a communication link between a port on the local client and a
// port on the remote client.
class Connection : public CandidatePairInterface,
                   public rtc::MessageHandler,
                   public sigslot::has_slots<> {
 public:
  struct SentPing {
    SentPing(const std::string id, int64_t sent_time, uint32_t nomination)
        : id(id), sent_time(sent_time), nomination(nomination) {}

    std::string id;
    int64_t sent_time;
    uint32_t nomination;
  };

  ~Connection() override;

  // A unique ID assigned when the connection is created.
  uint32_t id() const { return id_; }

  // Implementation of virtual methods in CandidatePairInterface.
  // Returns the description of the local port
  const Candidate& local_candidate() const override;
  // Returns the description of the remote port to which we communicate.
  const Candidate& remote_candidate() const override;

  // Return local network for this connection.
  virtual const rtc::Network* network() const;
  // Return generation for this connection.
  virtual int generation() const;

  // Returns the pair priority.
  virtual uint64_t priority() const;

  enum WriteState {
    STATE_WRITABLE = 0,          // we have received ping responses recently
    STATE_WRITE_UNRELIABLE = 1,  // we have had a few ping failures
    STATE_WRITE_INIT = 2,        // we have yet to receive a ping response
    STATE_WRITE_TIMEOUT = 3,     // we have had a large number of ping failures
  };

  WriteState write_state() const { return write_state_; }
  bool writable() const { return write_state_ == STATE_WRITABLE; }
  bool receiving() const { return receiving_; }

  // Determines whether the connection has finished connecting.  This can only
  // be false for TCP connections.
  bool connected() const { return connected_; }
  bool weak() const { return !(writable() && receiving() && connected()); }
  bool active() const { return write_state_ != STATE_WRITE_TIMEOUT; }

  // A connection is dead if it can be safely deleted.
  bool dead(int64_t now) const;

  // Estimate of the round-trip time over this connection.
  int rtt() const { return rtt_; }

  int unwritable_timeout() const;
  void set_unwritable_timeout(const absl::optional<int>& value_ms) {
    unwritable_timeout_ = value_ms;
  }
  int unwritable_min_checks() const;
  void set_unwritable_min_checks(const absl::optional<int>& value) {
    unwritable_min_checks_ = value;
  }
  int inactive_timeout() const;
  void set_inactive_timeout(const absl::optional<int>& value) {
    inactive_timeout_ = value;
  }

  // Gets the |ConnectionInfo| stats, where |best_connection| has not been
  // populated (default value false).
  ConnectionInfo stats();

  sigslot::signal1<Connection*> SignalStateChange;

  // Sent when the connection has decided that it is no longer of value.  It
  // will delete itself immediately after this call.
  sigslot::signal1<Connection*> SignalDestroyed;

  // The connection can send and receive packets asynchronously.  This matches
  // the interface of AsyncPacketSocket, which may use UDP or TCP under the
  // covers.
  virtual int Send(const void* data,
                   size_t size,
                   const rtc::PacketOptions& options) = 0;

  // Error if Send() returns < 0
  virtual int GetError() = 0;

  sigslot::signal4<Connection*, const char*, size_t, int64_t> SignalReadPacket;

  sigslot::signal1<Connection*> SignalReadyToSend;

  // Called when a packet is received on this connection.
  void OnReadPacket(const char* data, size_t size, int64_t packet_time_us);

  // Called when the socket is currently able to send.
  void OnReadyToSend();

  // Called when a connection is determined to be no longer useful to us.  We
  // still keep it around in case the other side wants to use it.  But we can
  // safely stop pinging on it and we can allow it to time out if the other
  // side stops using it as well.
  bool pruned() const { return pruned_; }
  void Prune();

  bool use_candidate_attr() const { return use_candidate_attr_; }
  void set_use_candidate_attr(bool enable);

  void set_nomination(uint32_t value) { nomination_ = value; }

  uint32_t remote_nomination() const { return remote_nomination_; }
  // One or several pairs may be nominated based on if Regular or Aggressive
  // Nomination is used. https://tools.ietf.org/html/rfc5245#section-8
  // |nominated| is defined both for the controlling or controlled agent based
  // on if a nomination has been pinged or acknowledged. The controlled agent
  // gets its |remote_nomination_| set when pinged by the controlling agent with
  // a nomination value. The controlling agent gets its |acked_nomination_| set
  // when receiving a response to a nominating ping.
  bool nominated() const { return acked_nomination_ || remote_nomination_; }
  void set_remote_ice_mode(IceMode mode) { remote_ice_mode_ = mode; }

  int receiving_timeout() const;
  void set_receiving_timeout(absl::optional<int> receiving_timeout_ms) {
    receiving_timeout_ = receiving_timeout_ms;
  }

  // Makes the connection go away.
  void Destroy();

  // Makes the connection go away, in a failed state.
  void FailAndDestroy();

  // Prunes the connection and sets its state to STATE_FAILED,
  // It will not be used or send pings although it can still receive packets.
  void FailAndPrune();

  // Checks that the state of this connection is up-to-date.  The argument is
  // the current time, which is compared against various timeouts.
  void UpdateState(int64_t now);

  // Called when this connection should try checking writability again.
  int64_t last_ping_sent() const { return last_ping_sent_; }
  void Ping(int64_t now);
  void ReceivedPingResponse(
      int rtt,
      const std::string& request_id,
      const absl::optional<uint32_t>& nomination = absl::nullopt);
  int64_t last_ping_response_received() const {
    return last_ping_response_received_;
  }
  const absl::optional<std::string>& last_ping_id_received() const {
    return last_ping_id_received_;
  }
  // Used to check if any STUN ping response has been received.
  int rtt_samples() const { return rtt_samples_; }

  // Called whenever a valid ping is received on this connection.  This is
  // public because the connection intercepts the first ping for us.
  int64_t last_ping_received() const { return last_ping_received_; }
  void ReceivedPing(
      const absl::optional<std::string>& request_id = absl::nullopt);
  // Handles the binding request; sends a response if this is a valid request.
  void HandleStunBindingOrGoogPingRequest(IceMessage* msg);
  // Handles the piggyback acknowledgement of the lastest connectivity check
  // that the remote peer has received, if it is indicated in the incoming
  // connectivity check from the peer.
  void HandlePiggybackCheckAcknowledgementIfAny(StunMessage* msg);
  int64_t last_data_received() const { return last_data_received_; }

  // Debugging description of this connection
  std::string ToDebugId() const;
  std::string ToString() const;
  std::string ToSensitiveString() const;
  // Structured description of this candidate pair.
  const webrtc::IceCandidatePairDescription& ToLogDescription();
  void set_ice_event_log(webrtc::IceEventLog* ice_event_log) {
    ice_event_log_ = ice_event_log;
  }
  // Prints pings_since_last_response_ into a string.
  void PrintPingsSinceLastResponse(std::string* pings, size_t max);

  bool reported() const { return reported_; }
  void set_reported(bool reported) { reported_ = reported; }
  // The following two methods are only used for logging in ToString above, and
  // this flag is set true by P2PTransportChannel for its selected candidate
  // pair.
  bool selected() const { return selected_; }
  void set_selected(bool selected) { selected_ = selected; }

  // This signal will be fired if this connection is nominated by the
  // controlling side.
  sigslot::signal1<Connection*> SignalNominated;

  // Invoked when Connection receives STUN error response with 487 code.
  void HandleRoleConflictFromPeer();

  IceCandidatePairState state() const { return state_; }

  int num_pings_sent() const { return num_pings_sent_; }

  IceMode remote_ice_mode() const { return remote_ice_mode_; }

  uint32_t ComputeNetworkCost() const;

  // Update the ICE password and/or generation of the remote candidate if the
  // ufrag in |params| matches the candidate's ufrag, and the
  // candidate's password and/or ufrag has not been set.
  void MaybeSetRemoteIceParametersAndGeneration(const IceParameters& params,
                                                int generation);

  // If |remote_candidate_| is peer reflexive and is equivalent to
  // |new_candidate| except the type, update |remote_candidate_| to
  // |new_candidate|.
  void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);

  // Returns the last received time of any data, stun request, or stun
  // response in milliseconds
  int64_t last_received() const;
  // Returns the last time when the connection changed its receiving state.
  int64_t receiving_unchanged_since() const {
    return receiving_unchanged_since_;
  }

  bool stable(int64_t now) const;

  // Check if we sent |val| pings without receving a response.
  bool TooManyOutstandingPings(const absl::optional<int>& val) const;

  void SetIceFieldTrials(const IceFieldTrials* field_trials);
  const rtc::EventBasedExponentialMovingAverage& GetRttEstimate() const {
    return rtt_estimate_;
  }

  // Reset the connection to a state of a newly connected.
  // - STATE_WRITE_INIT
  // - receving = false
  // - throw away all pending request
  // - reset RttEstimate
  //
  // Keep the following unchanged:
  // - connected
  // - remote_candidate
  // - statistics
  //
  // Does not trigger SignalStateChange
  void ForgetLearnedState();

  void SendStunBindingResponse(const StunMessage* request);
  void SendGoogPingResponse(const StunMessage* request);
  void SendResponseMessage(const StunMessage& response);

  // An accessor for unit tests.
  Port* PortForTest() { return port_; }
  const Port* PortForTest() const { return port_; }

  // Public for unit tests.
  uint32_t acked_nomination() const { return acked_nomination_; }

  // Public for unit tests.
  void set_remote_nomination(uint32_t remote_nomination) {
    remote_nomination_ = remote_nomination;
  }

 protected:
  enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };

  // Constructs a new connection to the given remote port.
  Connection(Port* port, size_t index, const Candidate& candidate);

  // Called back when StunRequestManager has a stun packet to send
  void OnSendStunPacket(const void* data, size_t size, StunRequest* req);

  // Callbacks from ConnectionRequest
  virtual void OnConnectionRequestResponse(ConnectionRequest* req,
                                           StunMessage* response);
  void OnConnectionRequestErrorResponse(ConnectionRequest* req,
                                        StunMessage* response);
  void OnConnectionRequestTimeout(ConnectionRequest* req);
  void OnConnectionRequestSent(ConnectionRequest* req);

  bool rtt_converged() const;

  // If the response is not received within 2 * RTT, the response is assumed to
  // be missing.
  bool missing_responses(int64_t now) const;

  // Changes the state and signals if necessary.
  void set_write_state(WriteState value);
  void UpdateReceiving(int64_t now);
  void set_state(IceCandidatePairState state);
  void set_connected(bool value);

  uint32_t nomination() const { return nomination_; }

  void OnMessage(rtc::Message* pmsg) override;

  // The local port where this connection sends and receives packets.
  Port* port() { return port_; }
  const Port* port() const { return port_; }

  uint32_t id_;
  Port* port_;
  size_t local_candidate_index_;
  Candidate remote_candidate_;

  ConnectionInfo stats_;
  rtc::RateTracker recv_rate_tracker_;
  rtc::RateTracker send_rate_tracker_;

 private:
  // Update the local candidate based on the mapped address attribute.
  // If the local candidate changed, fires SignalStateChange.
  void MaybeUpdateLocalCandidate(ConnectionRequest* request,
                                 StunMessage* response);

  void LogCandidatePairConfig(webrtc::IceCandidatePairConfigType type);
  void LogCandidatePairEvent(webrtc::IceCandidatePairEventType type,
                             uint32_t transaction_id);

  // Check if this IceMessage is identical
  // to last message ack:ed STUN_BINDING_REQUEST.
  bool ShouldSendGoogPing(const StunMessage* message);

  WriteState write_state_;
  bool receiving_;
  bool connected_;
  bool pruned_;
  bool selected_ = false;
  // By default |use_candidate_attr_| flag will be true,
  // as we will be using aggressive nomination.
  // But when peer is ice-lite, this flag "must" be initialized to false and
  // turn on when connection becomes "best connection".
  bool use_candidate_attr_;
  // Used by the controlling side to indicate that this connection will be
  // selected for transmission if the peer supports ICE-renomination when this
  // value is positive. A larger-value indicates that a connection is nominated
  // later and should be selected by the controlled side with higher precedence.
  // A zero-value indicates not nominating this connection.
  uint32_t nomination_ = 0;
  // The last nomination that has been acknowledged.
  uint32_t acked_nomination_ = 0;
  // Used by the controlled side to remember the nomination value received from
  // the controlling side. When the peer does not support ICE re-nomination, its
  // value will be 1 if the connection has been nominated.
  uint32_t remote_nomination_ = 0;

  IceMode remote_ice_mode_;
  StunRequestManager requests_;
  int rtt_;
  int rtt_samples_ = 0;
  // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime
  uint64_t total_round_trip_time_ms_ = 0;
  // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime
  absl::optional<uint32_t> current_round_trip_time_ms_;
  int64_t last_ping_sent_;      // last time we sent a ping to the other side
  int64_t last_ping_received_;  // last time we received a ping from the other
                                // side
  int64_t last_data_received_;
  int64_t last_ping_response_received_;
  int64_t receiving_unchanged_since_ = 0;
  std::vector<SentPing> pings_since_last_response_;
  // Transaction ID of the last connectivity check received. Null if having not
  // received a ping yet.
  absl::optional<std::string> last_ping_id_received_;

  absl::optional<int> unwritable_timeout_;
  absl::optional<int> unwritable_min_checks_;
  absl::optional<int> inactive_timeout_;

  bool reported_;
  IceCandidatePairState state_;
  // Time duration to switch from receiving to not receiving.
  absl::optional<int> receiving_timeout_;
  int64_t time_created_ms_;
  int num_pings_sent_ = 0;

  absl::optional<webrtc::IceCandidatePairDescription> log_description_;
  webrtc::IceEventLog* ice_event_log_ = nullptr;

  // GOOG_PING_REQUEST is sent in place of STUN_BINDING_REQUEST
  // if configured via field trial, the remote peer supports it (signaled
  // in STUN_BINDING) and if the last STUN BINDING is identical to the one
  // that is about to be sent.
  absl::optional<bool> remote_support_goog_ping_;
  std::unique_ptr<StunMessage> cached_stun_binding_;

  const IceFieldTrials* field_trials_;
  rtc::EventBasedExponentialMovingAverage rtt_estimate_;

  friend class Port;
  friend class ConnectionRequest;
  friend class P2PTransportChannel;
};

// ProxyConnection defers all the interesting work to the port.
class ProxyConnection : public Connection {
 public:
  ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);

  int Send(const void* data,
           size_t size,
           const rtc::PacketOptions& options) override;
  int GetError() override;

 private:
  int error_ = 0;
};

}  // namespace cricket

#endif  // P2P_BASE_CONNECTION_H_


text:
from os.path import abspath, basename, dirname, join
from sys import path

from django.utils.translation import ugettext_lazy as _

# Absolute filesystem path to the Django project directory:
BASE_DIR = dirname(dirname(abspath(__file__)))
# # Absolute filesystem path to the top-level project folder:
SITE_ROOT = dirname(BASE_DIR)

SITE_NAME = basename(BASE_DIR)
# # Add our project to our pythonpath, this way we don't need to type our project
# # name in our dotted import paths:
path.append(BASE_DIR)

SITE_URL = "http://localhost:8000"

DEBUG = False
TEMPLATE_DEBUG = DEBUG

TESTING = True #no attached to debug. Can be used to avoid stuff in local/staging development

#See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins & #managers
ADMINS = (
    ('Django Reinhardt', 'admin@email.com'),
)
MANAGERS = ADMINS

ROOT_URLCONF = 'urls'
WSGI_APPLICATION = 'wsgi.application'

DJANGO_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

# Apps specific for this project go here.
LOCAL_APPS = (
    'core',
    'web',
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS

INSTALLED_APPS += (
    'django_nose',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.request',
)

TEMPLATE_CONTEXT_PROCESSORS += (
    'core.context_processors.analytics',
    'core.context_processors.i18n_extended',
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
TEMPLATE_DIRS = (
    join(BASE_DIR, 'templates'),
)

# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGES = (
    ('en', _('English')),
    ('es', _('Spanish')),
)

LOCALE_PATHS = (
    join(BASE_DIR, 'locale'),
)

USE_I18N = True
USE_L10N = True
USE_TZ = True

TIME_ZONE = 'Europe/Madrid'

# https://docs.djangoproject.com/en/1.7/howto/static-files/
MEDIA_ROOT = join(BASE_DIR, 'media')

# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'

# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = join(SITE_ROOT, 'static')

# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS

STATICFILES_DIRS = (
    join(BASE_DIR,  'static'),
)

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}


text:
package com.rk.aspectCache.common;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;

/**
 * Use this to annotate a method that you want to cache. Since annotations on methods are not inherited, you must annotate the method in
 * the parent class and in the subclasses which override it. <br>
 * The elements' default values need not stay the same across all the overriding versions, therefore you can enforce different caching behaviors
 * for the same method by calling it from subtypes of the original version.
 *
 * @author Raul Bertone (raul.bertone@emptyingthebuffer.com)
 */

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Cached {
	KeyStrategy keyType() default KeyStrategy.ARGS_IDENTITY;
	FieldMonitoringStrategy fieldMonitoringStrategy() default FieldMonitoringStrategy.ALL;
	boolean stable() default false; // if true delays propagation of invalidations to parent cache entries until a new value is calculated and only if newValue != oldValue
	boolean automaticRecalculation() default false; // cannot use mutable keys. Cannot be stable (or rather can but means nothing)
	boolean waitForFresh() default false; // during a cache look-up, if a calculation of a fresh value is already underway, whether to wait for the new one or start another calculation
}


text:
package com.orientechnologies.orient.test.server;

import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;
import com.orientechnologies.orient.server.OServer;
import java.io.File;
import org.testng.annotations.Test;

public class OServerTest {

  /** Test for https://github.com/orientechnologies/orientdb/issues/1667 */
  @Test
  public void testRestart() throws Exception {
    // set ORIENTDB_HOME
    final String buildDirectory = System.getProperty("buildDirectory", ".");
    System.setProperty(
        "ORIENTDB_HOME", buildDirectory + File.separator + OServerTest.class.getSimpleName());

    OLogManager.instance().info(this, "ORIENTDB_HOME: " + System.getProperty("ORIENTDB_HOME"));

    // loop for start & stop server
    for (int i = 0; i < 5; i++) {
      OLogManager.instance().info(this, "Iteration " + i);
      OServer server = new OServer(false).activate();
      // create database if does not exist
      OObjectDatabaseTx database =
          new OObjectDatabaseTx("plocal:" + System.getProperty("ORIENTDB_HOME") + "/test-db");
      if (!database.exists()) database.create();
      database.open("admin", "admin");
      database.countClass("ouser");
      database.close();
      server.shutdown();
    }
  }
}


text:
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.10.25019.0

; Generated by VC++ for Common Language Runtime
.file "C:\Users\k_sdk\AppData\Local\Temp\.NETFramework,Version=v4.0.AssemblyAttributes.cpp"


text:
package <%= appPackage %>.tasks;

import android.content.Context;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
import android.databinding.ObservableList;
import android.graphics.drawable.Drawable;

import <%= appPackage %>.BR;
import <%= appPackage %>.R;
import <%= appPackage %>.addedittask.AddEditTaskActivity;
import <%= appPackage %>.data.Task;
import <%= appPackage %>.data.source.TasksDataSource;
import <%= appPackage %>.data.source.TasksRepository;
import <%= appPackage %>.taskdetail.TaskDetailActivity;
import <%= appPackage %>.util.EspressoIdlingResource;

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

/**
 * Exposes the data to be used in the task list screen.
 * <p>
 * {@link BaseObservable} implements a listener registration mechanism which is notified when a
 * property changes. This is done by assigning a {@link Bindable} annotation to the property's
 * getter method.
 */
public class TasksViewModel extends BaseObservable {

    // These observable fields will update Views automatically
    public final ObservableList<Task> items = new ObservableArrayList<>();

    public final ObservableBoolean dataLoading = new ObservableBoolean(false);

    public final ObservableField<String> currentFilteringLabel = new ObservableField<>();

    public final ObservableField<String> noTasksLabel = new ObservableField<>();

    public final ObservableField<Drawable> noTaskIconRes = new ObservableField<>();

    public final ObservableBoolean tasksAddViewVisible = new ObservableBoolean();

    final ObservableField<String> snackbarText = new ObservableField<>();

    private TasksFilterType mCurrentFiltering = TasksFilterType.ALL_TASKS;

    private final TasksRepository mTasksRepository;

    private final ObservableBoolean mIsDataLoadingError = new ObservableBoolean(false);

    private Context mContext; // To avoid leaks, this must be an Application Context.

    private TasksNavigator mNavigator;

    public TasksViewModel(
            TasksRepository repository,
            Context context) {
        mContext = context.getApplicationContext(); // Force use of Application Context.
        mTasksRepository = repository;

        // Set initial state
        setFiltering(TasksFilterType.ALL_TASKS);
    }

    void setNavigator(TasksNavigator navigator) {
        mNavigator = navigator;
    }

    void onActivityDestroyed() {
        // Clear references to avoid potential memory leaks.
        mNavigator = null;
    }

    public void start() {
        loadTasks(false);
    }

    @Bindable
    public boolean isEmpty() {
        return items.isEmpty();
    }

    public void loadTasks(boolean forceUpdate) {
        loadTasks(forceUpdate, true);
    }

    /**
     * Sets the current task filtering type.
     *
     * @param requestType Can be {@link TasksFilterType#ALL_TASKS},
     *                    {@link TasksFilterType#COMPLETED_TASKS}, or
     *                    {@link TasksFilterType#ACTIVE_TASKS}
     */
    public void setFiltering(TasksFilterType requestType) {
        mCurrentFiltering = requestType;

        // Depending on the filter type, set the filtering label, icon drawables, etc.
        switch (requestType) {
            case ALL_TASKS:
                currentFilteringLabel.set(mContext.getString(R.string.label_all));
                noTasksLabel.set(mContext.getResources().getString(R.string.no_tasks_all));
                noTaskIconRes.set(mContext.getResources().getDrawable(
                        R.drawable.ic_assignment_turned_in_24dp));
                tasksAddViewVisible.set(true);
                break;
            case ACTIVE_TASKS:
                currentFilteringLabel.set(mContext.getString(R.string.label_active));
                noTasksLabel.set(mContext.getResources().getString(R.string.no_tasks_active));
                noTaskIconRes.set(mContext.getResources().getDrawable(
                        R.drawable.ic_check_circle_24dp));
                tasksAddViewVisible.set(false);
                break;
            case COMPLETED_TASKS:
                currentFilteringLabel.set(mContext.getString(R.string.label_completed));
                noTasksLabel.set(mContext.getResources().getString(R.string.no_tasks_completed));
                noTaskIconRes.set(mContext.getResources().getDrawable(
                        R.drawable.ic_verified_user_24dp));
                tasksAddViewVisible.set(false);
                break;
        }
    }

    public void clearCompletedTasks() {
        mTasksRepository.clearCompletedTasks();
        snackbarText.set(mContext.getString(R.string.completed_tasks_cleared));
        loadTasks(false, false);
    }

    public String getSnackbarText() {
        return snackbarText.get();
    }

    /**
     * Called by the Data Binding library and the FAB's click listener.
     */
    public void addNewTask() {
        if (mNavigator != null) {
            mNavigator.addNewTask();
        }
    }

    void handleActivityResult(int requestCode, int resultCode) {
        if (AddEditTaskActivity.REQUEST_CODE == requestCode) {
            switch (resultCode) {
                case TaskDetailActivity.EDIT_RESULT_OK:
                    snackbarText.set(
                            mContext.getString(R.string.successfully_saved_task_message));
                    break;
                case AddEditTaskActivity.ADD_EDIT_RESULT_OK:
                    snackbarText.set(
                            mContext.getString(R.string.successfully_added_task_message));
                    break;
                case TaskDetailActivity.DELETE_RESULT_OK:
                    snackbarText.set(
                            mContext.getString(R.string.successfully_deleted_task_message));
                    break;
            }
        }
    }

    /**
     * @param forceUpdate   Pass in true to refresh the data in the {@link TasksDataSource}
     * @param showLoadingUI Pass in true to display a loading icon in the UI
     */
    private void loadTasks(boolean forceUpdate, final boolean showLoadingUI) {
        if (showLoadingUI) {
            dataLoading.set(true);
        }
        if (forceUpdate) {

            mTasksRepository.refreshTasks();
        }

        // The network request might be handled in a different thread so make sure Espresso knows
        // that the app is busy until the response is handled.
        EspressoIdlingResource.increment(); // App is busy until further notice

        mTasksRepository.getTasks(new TasksDataSource.LoadTasksCallback() {
            @Override
            public void onTasksLoaded(List<Task> tasks) {
                List<Task> tasksToShow = new ArrayList<Task>();

                // This callback may be called twice, once for the cache and once for loading
                // the data from the server API, so we check before decrementing, otherwise
                // it throws "Counter has been corrupted!" exception.
                if (!EspressoIdlingResource.getIdlingResource().isIdleNow()) {
                    EspressoIdlingResource.decrement(); // Set app as idle.
                }

                // We filter the tasks based on the requestType
                for (Task task : tasks) {
                    switch (mCurrentFiltering) {
                        case ALL_TASKS:
                            tasksToShow.add(task);
                            break;
                        case ACTIVE_TASKS:
                            if (task.isActive()) {
                                tasksToShow.add(task);
                            }
                            break;
                        case COMPLETED_TASKS:
                            if (task.isCompleted()) {
                                tasksToShow.add(task);
                            }
                            break;
                        default:
                            tasksToShow.add(task);
                            break;
                    }
                }
                if (showLoadingUI) {
                    dataLoading.set(false);
                }
                mIsDataLoadingError.set(false);

                items.clear();
                items.addAll(tasksToShow);
                notifyPropertyChanged(BR.empty); // It's a @Bindable so update manually
            }

            @Override
            public void onDataNotAvailable() {
                mIsDataLoadingError.set(true);
            }
        });
    }

}