text:
"""circuit training agent definition and utility functions."""

from typing import Optional, Text, Tuple

from absl import logging
from circuit_training.model import model
import gin
import tensorflow as tf
from tf_agents.agents.ppo import ppo_agent
from tf_agents.agents.ppo import ppo_utils
from tf_agents.networks import network
from tf_agents.trajectories import time_step as ts
from tf_agents.typing import types
from tf_agents.utils import common
from tf_agents.utils import eager_utils
from tf_agents.utils import nest_utils
from tf_agents.utils import object_identity
from tf_agents.utils import value_ops

def _normalize_advantages(advantages, axes=(0), variance_epsilon=1e-8):
  adv_mean, adv_var = tf.nn.moments(x=advantages, axes=axes, keepdims=True)
  normalized_advantages = ((advantages - adv_mean) /
                           (tf.sqrt(adv_var) + variance_epsilon))
  return normalized_advantages

@gin.configurable
class CircuitPPOAgent(ppo_agent.PPOAgent):
  """A PPO Agent for circuit training aligned with Menger.

  Major differencs between this and ppo_agent.PPOAgent:
  - Loss aggregation uses reduce_mean instead of common.aggregate_losses which
    handles aggregation across multiple accelerator cores.
  - Value bootstrapping uses the second to last observation, instead of the
    last one. This is likely temporarily for aligning with Menger.
  - The additional time dimension ([B, 1, ...] was squeezed at the beginning,
    which eventually leads to different behavior when generating the action
    distribution. b/202055908 tracks the work on fully understanding and
    documenting this.
  - Normalization is done manually as opposed to `tf.nn.batch_normalization`
    which leads to different results in TPU setups.
  """

  def __init__(self,
               time_step_spec: ts.TimeStep,
               action_spec: types.NestedTensorSpec,
               optimizer: Optional[types.Optimizer] = None,
               actor_net: Optional[network.Network] = None,
               value_net: Optional[network.Network] = None,
               importance_ratio_clipping: types.Float = 0.2,
               discount_factor: types.Float = 1.0,
               entropy_regularization: types.Float = 0.01,
               value_pred_loss_coef: types.Float = 0.5,
               gradient_clipping: Optional[types.Float] = 1.0,
               value_clipping: Optional[types.Float] = None,
               check_numerics: bool = False,
               debug_summaries: bool = False,
               summarize_grads_and_vars: bool = False,
               train_step_counter: Optional[tf.Variable] = None,
               aggregate_losses_across_replicas: bool = True,
               report_loss_scaling_factor: float = 1.,
               name: Optional[Text] = 'PPOClipAgent'):
    """Creates a PPO Agent implementing the clipped probability ratios.

    Args:
      time_step_spec: A `TimeStep` spec of the expected time_steps.
      action_spec: A nest of BoundedTensorSpec representing the actions.
      optimizer: Optimizer to use for the agent.
      actor_net: A function actor_net(observations, action_spec) that returns
        tensor of action distribution params for each observation. Takes nested
        observation and returns nested action.
      value_net: A function value_net(time_steps) that returns value tensor from
        neural net predictions for each observation. Takes nested observation
        and returns batch of value_preds.
      importance_ratio_clipping: Epsilon in clipped, surrogate PPO objective.
        For more detail, see explanation at the top of the doc.
      discount_factor: Discount factor for return computation.
      entropy_regularization: Coefficient for entropy regularization loss term.
      value_pred_loss_coef: Multiplier for value prediction loss to balance with
        policy gradient loss.
      gradient_clipping: Norm length to clip gradients.  Default: no clipping.
      value_clipping: Difference between new and old value predictions are
        clipped to this threshold. Value clipping could be helpful when training
        very deep networks. Default: no clipping.
      check_numerics: If true, adds tf.debugging.check_numerics to help find NaN
        / Inf values. For debugging only.
      debug_summaries: A bool to gather debug summaries.
      summarize_grads_and_vars: If true, gradient summaries will be written.
      train_step_counter: An optional counter to increment every time the train
        op is run.  Defaults to the global_step.
      aggregate_losses_across_replicas: only applicable to setups using multiple
        relicas. Default to aggregating across multiple cores using common.
        aggregate_losses. If set to `False`, use `reduce_mean` directly, which
        is faster but may impact learning results.
      report_loss_scaling_factor: the multiplier for scaling the loss in the
        report.
      name: The name of this agent. All variables in this module will fall under
        that name. Defaults to the class name.

    Raises:
      ValueError: If the actor_net is not a DistributionNetwork.
    """
    self._report_loss_scaling_factor = report_loss_scaling_factor
    self._use_tpu = bool(tf.config.list_logical_devices('TPU'))

    super(CircuitPPOAgent, self).__init__(
        time_step_spec,
        action_spec,
        optimizer,
        actor_net,
        value_net,
        importance_ratio_clipping=importance_ratio_clipping,
        discount_factor=discount_factor,
        entropy_regularization=entropy_regularization,
        value_pred_loss_coef=value_pred_loss_coef,
        gradient_clipping=gradient_clipping,
        value_clipping=value_clipping,
        check_numerics=check_numerics,
        debug_summaries=debug_summaries,
        summarize_grads_and_vars=summarize_grads_and_vars,
        train_step_counter=train_step_counter,
        aggregate_losses_across_replicas=aggregate_losses_across_replicas,
        # Epochs are set through the tf.Data pipeline outside of the agent.
        num_epochs=1,
        # Value and advantages are computed as part of the data pipeline, this
        # is set to False for all setups using minibatching and PPOLearner.
        compute_value_and_advantage_in_train=False,
        normalize_rewards=False,
        normalize_observations=False,
        update_normalizers_in_train=False,
        name=name,
    )

  def compute_return_and_advantage(
      self, next_time_steps: ts.TimeStep,
      value_preds: types.Tensor) -> Tuple[types.Tensor, types.Tensor]:
    """Compute the Monte Carlo return and advantage.

    Args:
      next_time_steps: batched tensor of TimeStep tuples after action is taken.
      value_preds: Batched value prediction tensor. Should have one more entry
        in time index than time_steps, with the final value corresponding to the
        value prediction of the final state.

    Returns:
      tuple of (return, advantage), both are batched tensors.
    """
    discounts = next_time_steps.discount * tf.constant(
        self._discount_factor, dtype=tf.float32)

    rewards = next_time_steps.reward
    # TODO(b/202226773): Move debugging to helper function for clarity.
    if self._debug_summaries:
      # Summarize rewards before they get normalized below.
      # TODO(b/171573175): remove the condition once histograms are
      # supported on TPUs.
      if not self._use_tpu:
        tf.compat.v2.summary.histogram(
            name='rewards', data=rewards, step=self.train_step_counter)
      tf.compat.v2.summary.scalar(
          name='rewards_mean',
          data=tf.reduce_mean(rewards),
          step=self.train_step_counter)

    # Normalize rewards if self._reward_normalizer is defined.
    if self._reward_normalizer:
      rewards = self._reward_normalizer.normalize(
          rewards, center_mean=False, clip_value=self._reward_norm_clipping)
      if self._debug_summaries:
        # TODO(b/171573175): remove the condition once histograms are
        # supported on TPUs.
        if not self._use_tpu:
          tf.compat.v2.summary.histogram(
              name='rewards_normalized',
              data=rewards,
              step=self.train_step_counter)
        tf.compat.v2.summary.scalar(
            name='rewards_normalized_mean',
            data=tf.reduce_mean(rewards),
            step=self.train_step_counter)

    # Make discount 0.0 at end of each episode to restart cumulative sum
    #   end of each episode.
    episode_mask = common.get_episode_mask(next_time_steps)
    discounts *= episode_mask

    # Compute Monte Carlo returns. Data from incomplete trajectories, not
    #   containing the end of an episode will also be used, with a bootstrapped
    #   estimation from the last value.
    # Note that when a trajectory driver is used, then the final step is
    #   terminal, the bootstrapped estimation will not be used, as it will be
    #   multiplied by zero (the discount on the last step).
    # TODO(b/202055908): Use -1 instead to bootstrap from the last step, once
    # we verify that it has no negative impact on learning.
    final_value_bootstrapped = value_preds[:, -2]
    returns = value_ops.discounted_return(
        rewards,
        discounts,
        time_major=False,
        final_value=final_value_bootstrapped)
    # TODO(b/171573175): remove the condition once histograms are
    # supported on TPUs.
    if self._debug_summaries and not self._use_tpu:
      tf.compat.v2.summary.histogram(
          name='returns', data=returns, step=self.train_step_counter)

    # Compute advantages.
    advantages = self.compute_advantages(rewards, returns, discounts,
                                         value_preds)

    # TODO(b/171573175): remove the condition once historgrams are
    # supported on TPUs.
    if self._debug_summaries and not self._use_tpu:
      tf.compat.v2.summary.histogram(
          name='advantages', data=advantages, step=self.train_step_counter)

    # Return TD-Lambda returns if both use_td_lambda_return and use_gae.
    if self._use_td_lambda_return:
      if not self._use_gae:
        logging.warning('use_td_lambda_return was True, but use_gae was '
                        'False. Using Monte Carlo return.')
      else:
        returns = tf.add(
            advantages, value_preds[:, :-1], name='td_lambda_returns')

    return returns, advantages

  def _train(self, experience, weights):
    experience = self._as_trajectory(experience)

    if self._compute_value_and_advantage_in_train:
      processed_experience = self._preprocess(experience)
    else:
      processed_experience = experience

    def squeeze_time_dim(t):
      return tf.squeeze(t, axis=[1])

    processed_experience = tf.nest.map_structure(squeeze_time_dim,
                                                 processed_experience)

    valid_mask = ppo_utils.make_trajectory_mask(processed_experience)

    masked_weights = valid_mask
    if weights is not None:
      masked_weights *= weights

    # Reconstruct per-timestep policy distribution from stored distribution
    #   parameters.
    old_action_distribution_parameters = (
        processed_experience.policy_info['dist_params'])

    old_actions_distribution = (
        ppo_utils.distribution_from_spec(
            self._action_distribution_spec,
            old_action_distribution_parameters,
            legacy_distribution_network=isinstance(
                self._actor_net, network.DistributionNetwork)))

    # Compute log probability of actions taken during data collection, using the
    #   collect policy distribution.
    old_act_log_probs = common.log_probability(old_actions_distribution,
                                               processed_experience.action,
                                               self._action_spec)

    # TODO(b/171573175): remove the condition once histograms are
    # supported on TPUs.
    if self._debug_summaries and not self._use_tpu:
      actions_list = tf.nest.flatten(processed_experience.action)
      show_action_index = len(actions_list) != 1
      for i, single_action in enumerate(actions_list):
        action_name = ('actions_{}'.format(i)
                       if show_action_index else 'actions')
        tf.compat.v2.summary.histogram(
            name=action_name, data=single_action, step=self.train_step_counter)

    time_steps = ts.TimeStep(
        step_type=processed_experience.step_type,
        reward=processed_experience.reward,
        discount=processed_experience.discount,
        observation=processed_experience.observation)

    actions = processed_experience.action
    returns = processed_experience.policy_info['return']
    advantages = processed_experience.policy_info['advantage']

    normalized_advantages = _normalize_advantages(
        advantages, variance_epsilon=1e-8)

    # TODO(b/171573175): remove the condition once histograms are
    # supported on TPUs.
    if self._debug_summaries and not self._use_tpu:
      tf.compat.v2.summary.histogram(
          name='advantages_normalized',
          data=normalized_advantages,
          step=self.train_step_counter)
    old_value_predictions = processed_experience.policy_info['value_prediction']

    batch_size = nest_utils.get_outer_shape(time_steps, self._time_step_spec)[0]

    loss_info = None  # TODO(b/123627451): Remove.
    variables_to_train = list(
        object_identity.ObjectIdentitySet(self._actor_net.trainable_weights +
                                          self._value_net.trainable_weights))
    # Sort to ensure tensors on different processes end up in same order.
    variables_to_train = sorted(variables_to_train, key=lambda x: x.name)

    with tf.GradientTape(watch_accessed_variables=False) as tape:
      tape.watch(variables_to_train)
      loss_info = self.get_loss(
          time_steps,
          actions,
          old_act_log_probs,
          returns,
          normalized_advantages,
          old_action_distribution_parameters,
          masked_weights,
          self.train_step_counter,
          self._debug_summaries,
          old_value_predictions=old_value_predictions,
          training=True)

    grads = tape.gradient(loss_info.loss, variables_to_train)
    if self._gradient_clipping > 0:
      grads, _ = tf.clip_by_global_norm(grads, self._gradient_clipping)

    self._grad_norm = tf.linalg.global_norm(grads)

    # Tuple is used for py3, where zip is a generator producing values once.
    grads_and_vars = tuple(zip(grads, variables_to_train))

    # If summarize_gradients, create functions for summarizing both
    # gradients and variables.
    if self._summarize_grads_and_vars and self._debug_summaries:
      eager_utils.add_gradients_summaries(grads_and_vars,
                                          self.train_step_counter)
      eager_utils.add_variables_summaries(grads_and_vars,
                                          self.train_step_counter)

    self._optimizer.apply_gradients(grads_and_vars)
    self.train_step_counter.assign_add(1)

    # TODO(b/161365079): Move this logic to PPOKLPenaltyAgent.
    if self._initial_adaptive_kl_beta > 0:
      # After update epochs, update adaptive kl beta, then update observation
      #   normalizer and reward normalizer.
      policy_state = self._collect_policy.get_initial_state(batch_size)
      # Compute the mean kl from previous action distribution.
      kl_divergence = self._kl_divergence(
          time_steps, old_action_distribution_parameters,
          self._collect_policy.distribution(time_steps, policy_state).action)
      kl_divergence *= masked_weights
      self.update_adaptive_kl_beta(kl_divergence)

    if self.update_normalizers_in_train:
      self.update_observation_normalizer(time_steps.observation)
      self.update_reward_normalizer(processed_experience.reward)

    loss_info = tf.nest.map_structure(tf.identity, loss_info)

    with tf.name_scope('Losses/'):
      tf.compat.v2.summary.scalar(
          name='policy_gradient_loss',
          data=loss_info.extra.policy_gradient_loss *
          self._report_loss_scaling_factor,
          step=self.train_step_counter)
      tf.compat.v2.summary.scalar(
          name='value_estimation_loss',
          data=loss_info.extra.value_estimation_loss *
          self._report_loss_scaling_factor,
          step=self.train_step_counter)
      tf.compat.v2.summary.scalar(
          name='l2_regularization_loss',
          data=loss_info.extra.l2_regularization_loss *
          self._report_loss_scaling_factor,
          step=self.train_step_counter)
      tf.compat.v2.summary.scalar(
          name='entropy_regularization_loss',
          data=loss_info.extra.entropy_regularization_loss *
          self._report_loss_scaling_factor,
          step=self.train_step_counter)
      tf.compat.v2.summary.scalar(
          name='kl_penalty_loss',
          data=loss_info.extra.kl_penalty_loss *
          self._report_loss_scaling_factor,
          step=self.train_step_counter)
      tf.compat.v2.summary.scalar(
          name='clip_fraction',
          data=loss_info.extra.clip_fraction,
          step=self.train_step_counter)
      tf.compat.v2.summary.scalar(
          name='grad_norm', data=self._grad_norm, step=self.train_step_counter)

      total_abs_loss = (
          tf.abs(loss_info.extra.policy_gradient_loss) +
          tf.abs(loss_info.extra.value_estimation_loss) +
          tf.abs(loss_info.extra.entropy_regularization_loss) +
          tf.abs(loss_info.extra.l2_regularization_loss) +
          tf.abs(loss_info.extra.kl_penalty_loss))

      tf.compat.v2.summary.scalar(
          name='total_abs_loss',
          data=total_abs_loss * self._report_loss_scaling_factor,
          step=self.train_step_counter)

      tf.compat.v2.summary.scalar(
          name='total_loss',
          data=loss_info.loss * self._report_loss_scaling_factor,
          step=self.train_step_counter)

    with tf.name_scope('LearningRate/'):
      tf.compat.v2.summary.scalar(
          name='learning_rate',
          data=self._optimizer.learning_rate,
          step=self.train_step_counter)

    # TODO(b/171573175): remove the condition once histograms are
    # supported on TPUs.
    if self._summarize_grads_and_vars and not self._use_tpu:
      with tf.name_scope('Variables/'):
        all_vars = (
            self._actor_net.trainable_weights +
            self._value_net.trainable_weights)
        for var in all_vars:
          tf.compat.v2.summary.histogram(
              name=var.name.replace(':', '_'),
              data=var,
              step=self.train_step_counter)

    return loss_info

def create_circuit_ppo_grl_agent(train_step: tf.Variable,
                                 action_tensor_spec: types.NestedTensorSpec,
                                 time_step_tensor_spec: types.TimeStep,
                                 grl_actor_net: model.GrlPolicyModel,
                                 grl_value_net: model.GrlValueModel,
                                 strategy: tf.distribute.Strategy,
                                 optimizer: Optional[types.Optimizer] = None,
                                 **kwargs) -> CircuitPPOAgent:
  """Creates a PPO agent using the GRL networks."""

  aggregate_losses_across_replicas = True
  if aggregate_losses_across_replicas:
    report_loss_scaling_factor = strategy.num_replicas_in_sync
  else:
    report_loss_scaling_factor = 1.0

  return CircuitPPOAgent(
      time_step_tensor_spec,
      action_tensor_spec,
      optimizer=optimizer,
      actor_net=grl_actor_net,
      value_net=grl_value_net,
      train_step_counter=train_step,
      aggregate_losses_across_replicas=aggregate_losses_across_replicas,
      report_loss_scaling_factor=report_loss_scaling_factor,
      **kwargs)

def create_circuit_ppo_agent(train_step: tf.Variable,
                             action_tensor_spec: types.NestedTensorSpec,
                             time_step_tensor_spec: types.TimeStep,
                             actor_net: network.Network,
                             value_net: network.Network,
                             strategy: tf.distribute.Strategy,
                             optimizer: Optional[types.Optimizer] = None,
                             **kwargs) -> CircuitPPOAgent:
  """Creates a PPO agent using the simpler fully connected RL networks."""

  aggregate_losses_across_replicas = True
  if aggregate_losses_across_replicas:
    report_loss_scaling_factor = strategy.num_replicas_in_sync
  else:
    report_loss_scaling_factor = 1.0

  return CircuitPPOAgent(
      time_step_tensor_spec,
      action_tensor_spec,
      optimizer=optimizer,
      actor_net=actor_net,
      value_net=value_net,
      train_step_counter=train_step,
      aggregate_losses_across_replicas=aggregate_losses_across_replicas,
      report_loss_scaling_factor=report_loss_scaling_factor,
      **kwargs)


text:
package com.google.ads.googleads.v12.services;

import com.google.ads.googleads.v12.services.CustomerManagerLinkServiceGrpc.CustomerManagerLinkServiceImplBase;
import com.google.api.core.BetaApi;
import com.google.protobuf.AbstractMessage;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.annotation.Generated;

@BetaApi
@Generated("by gapic-generator-java")
public class MockCustomerManagerLinkServiceImpl extends CustomerManagerLinkServiceImplBase {
  private List<AbstractMessage> requests;
  private Queue<Object> responses;

  public MockCustomerManagerLinkServiceImpl() {
    requests = new ArrayList<>();
    responses = new LinkedList<>();
  }

  public List<AbstractMessage> getRequests() {
    return requests;
  }

  public void addResponse(AbstractMessage response) {
    responses.add(response);
  }

  public void setResponses(List<AbstractMessage> responses) {
    this.responses = new LinkedList<Object>(responses);
  }

  public void addException(Exception exception) {
    responses.add(exception);
  }

  public void reset() {
    requests = new ArrayList<>();
    responses = new LinkedList<>();
  }

  @Override
  public void mutateCustomerManagerLink(
      MutateCustomerManagerLinkRequest request,
      StreamObserver<MutateCustomerManagerLinkResponse> responseObserver) {
    Object response = responses.poll();
    if (response instanceof MutateCustomerManagerLinkResponse) {
      requests.add(request);
      responseObserver.onNext(((MutateCustomerManagerLinkResponse) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method MutateCustomerManagerLink, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  MutateCustomerManagerLinkResponse.class.getName(),
                  Exception.class.getName())));
    }
  }

  @Override
  public void moveManagerLink(
      MoveManagerLinkRequest request, StreamObserver<MoveManagerLinkResponse> responseObserver) {
    Object response = responses.poll();
    if (response instanceof MoveManagerLinkResponse) {
      requests.add(request);
      responseObserver.onNext(((MoveManagerLinkResponse) response));
      responseObserver.onCompleted();
    } else if (response instanceof Exception) {
      responseObserver.onError(((Exception) response));
    } else {
      responseObserver.onError(
          new IllegalArgumentException(
              String.format(
                  "Unrecognized response type %s for method MoveManagerLink, expected %s or %s",
                  response == null ? "null" : response.getClass().getName(),
                  MoveManagerLinkResponse.class.getName(),
                  Exception.class.getName())));
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
APP_NAME = power
SOC ?= quark_d2000
TARGET ?= x86
BASE_DIR := ../../..
APP_DIR := .

ifeq ($(SOC),quark_se)
$(error Supported SOC value is 'quark_d2000')
endif

### Make includes
include $(BASE_DIR)/examples/app.mk


text:
<?php

namespace RobTeifi\Differencer\Visitors;

class LineBuffer
{
    /** @var  Line[] */
    private $lines;

    public function __construct()
    {
        $this->lines = [];
    }

    /**
     * @param boolean $matched
     * @param string  $main
     * @param string $marker
     */
    public function add($matched, $main, $marker = '>>>')
    {
        if (strpos($main, "\n")) {
            $first = true ;
            foreach (explode("\n", $main) as $partial) {
                if ($first) {
                    $first = false ;
                    $this->add($matched, $partial, $marker);
                } else {
                    $this->add($matched, $partial, '   ');
                }
            }
            return ;
        }
        $line = new Line($matched, $main, $marker);
        $this->lines[] = $line;
    }

    /**
     * @param LineBuffer $buffer
     * @param int $indent
     * @param string $firstPrefix
     */
    public function addBuffer(LineBuffer $buffer, $indent = 0, $firstPrefix = '')
    {
        $first = true ;
        foreach ($buffer->getLines() as $line) {
            $newline = null ;
            if ($first) {
                $first = false ;
                $newline = new Line($line->hasMatched(), $firstPrefix . $line->getText(), $line->getMarker());
                $newline->setExtraIndent(max(0, $indent - strlen($firstPrefix)));
            } else {
                $newline = $line ;
                $newline->setExtraIndent($indent);
            }
            $this->lines[] = $newline ;
        }
    }

    /**
     * @return Line[]
     */
    public function getLines()
    {
        return $this->lines;
    }

    public function __toString()
    {
        return array_reduce(
            $this->getLines(),
            function ($out, Line $line) {
                return $out . ($line->hasMatched() ? '    ' : ($line->getMarker() . ' ')) . $line->getText() . "\n";
            },
            ''
        );
    }
}


text:
There exists a problem for which you must get exactly 4 gallons of liquid, using only a 3 gallon jug and a 5 gallon jug. You must fill, empty, and/or transfer liquid from either of the jugs to acquire exactly 4 gallons.

The solution to this particular problem is the following:

- Fill the 5 gallon jug

- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 2 gallons in the 5 gallon jug and 3 gallons in the 3 gallon jug

- Empty the 3 gallon jug

- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 0 gallons in the 5 gallon jug and 2 gallons in the 3 gallon jug

- Fill the 5 gallon jug

- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 4 gallons in the 5 gallon jug and 3 gallons in the 3 gallon jug

- Empty the 3 gallon jug (optional)

The challenge will be to output a set of instructions to achieve an arbitrary final volume given 2 arbitrary sized gallon jugs. Jugs should be sized in a whole number (integer) amount of gallons. The program must also determine if the desired volume is impossible with this method (i.e. 2 - 4 gallon jugs to make 3 gallons). The program should be deterministic, meaning that running with the same inputs always produces the same solution (preventing a random pouring algorithm). The program should also consider outputting the most optimal set of instructions, but is not necessary.


text:
using System.Collections.Generic;
using System.Linq;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;

namespace NodeCanvas.Tasks.Actions{

	[Category("Physics")]
	[Description("Get hit info for ALL objects in the linecast, in Lists")]
	public class GetLinecastInfo2DAll : ActionTask<Transform> {

		[RequiredField]
		public BBParameter<GameObject> target;
		public LayerMask mask = -1;
		[BlackboardOnly]
		public BBParameter<List<GameObject>> saveHitGameObjectsAs;
		[BlackboardOnly]
		public BBParameter<List<float>> saveDistancesAs;
		[BlackboardOnly]
		public BBParameter<List<Vector3>> savePointsAs;
		[BlackboardOnly]
		public BBParameter<List<Vector3>> saveNormalsAs;

		private RaycastHit2D[] hits;

		protected override void OnExecute(){

            hits = Physics2D.LinecastAll(agent.position, target.value.transform.position, mask);

            if (hits.Length > 0) {
                saveHitGameObjectsAs.value = hits.Select(h => h.collider.gameObject).ToList();
                saveDistancesAs.value = hits.Select(h => h.fraction).ToList();
                savePointsAs.value = hits.Select(h => h.point).Cast<Vector3>().ToList();
                saveNormalsAs.value = hits.Select(h => h.normal).Cast<Vector3>().ToList();
                EndAction(true);
                return;
            }

            EndAction(false);
		}

		public override void OnDrawGizmosSelected(){
			if (agent && target.value)
				Gizmos.DrawLine(agent.position, target.value.transform.position);
		}
	}
}


text:
/* SPLASH SCREEN */
.welcome{
	right:0;
	bottom:0;
	position:absolute;
	width:100%;
	height:100%;
	background: white url("../static/loading.gif") no-repeat center;
	z-index:1995;
	overflow-y: hidden;
	overflow-x: hidden;
}


text:
#region << 版 本 注 释 >>

#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data;

namespace Dos.ORM.SqlServer
{

    /// <summary>
    /// SqlServer
    /// </summary>
    public class SqlServerProvider : DbProvider
    {
        public SqlServerProvider(string connectionString)
            : this(connectionString, SqlClientFactory.Instance)
        {
        }

        public SqlServerProvider(string connectionString, DbProviderFactory dbFactory)
            : base(connectionString, dbFactory, '[', ']', '@')
        {
        }

        public override string RowAutoID
        {
            get { return "select scope_identity()"; }
        }

        public override bool SupportBatch
        {
            get { return true; }
        }

        /// <summary>
        /// Builds the name of the parameter.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public override string BuildParameterName(string name)
        {
            string nameStr = name.Trim(leftToken, rightToken);
            if (nameStr[0] != paramPrefixToken)
            {
                return nameStr.Insert(0, new string(paramPrefixToken, 1));
            }
            //剔除参数中的"." 2016-04-08 added
            return nameStr.Replace(".", "_");
        }

        public override void PrepareCommand(DbCommand cmd)
        {
            base.PrepareCommand(cmd);

            foreach (DbParameter p in cmd.Parameters)
            {
                if (p.Direction == ParameterDirection.Output || p.Direction == ParameterDirection.ReturnValue)
                {
                    continue;
                }

                object value = p.Value;
                if (value == DBNull.Value)
                {
                    continue;
                }
                Type type = value.GetType();
                SqlParameter sqlParam = (SqlParameter)p;

                if (type == typeof(Guid))
                {
                    sqlParam.SqlDbType = SqlDbType.UniqueIdentifier;
                    continue;
                }

                switch (p.DbType)
                {
                    case DbType.Binary:
                        if (((byte[])value).Length > 8000)
                        {
                            sqlParam.SqlDbType = SqlDbType.Image;
                        }
                        break;
                    case DbType.Time:
                        sqlParam.SqlDbType = SqlDbType.DateTime;
                        break;
                    case DbType.DateTime:
                        sqlParam.SqlDbType = SqlDbType.DateTime;
                        break;
                    case DbType.AnsiString:
                        if (value.ToString().Length > 8000)
                        {
                            sqlParam.SqlDbType = SqlDbType.Text;
                        }
                        break;
                    case DbType.String:
                        if (value.ToString().Length > 4000)
                        {
                            sqlParam.SqlDbType = SqlDbType.NText;
                        }
                        break;
                    case DbType.Object:
                        sqlParam.SqlDbType = SqlDbType.NText;
                        p.Value = SerializationManager.Serialize(value);
                        break;
                }

                if (sqlParam.SqlDbType == SqlDbType.DateTime && type == typeof(TimeSpan))
                {
                    sqlParam.Value = new DateTime(1900, 1, 1).Add((TimeSpan)value);
                    continue;
                }
            }

            ////replace TONUMBER to cast
            //int pos = cmd.CommandText.IndexOf("TO_NUMBER(");
            //if (pos > 0)
            //{
            //    int bracketCount = 1;
            //    string columnName = null;
            //    int i = pos + "TO_NUMBER(".Length;
            //    for (; i < cmd.CommandText.Length; ++i)
            //    {
            //        if (cmd.CommandText[i] == ')')
            //            --bracketCount;
            //        else if (cmd.CommandText[i] == '(')
            //            ++bracketCount;

            //        if (bracketCount == 0)
            //            break;
            //    }
            //    columnName = cmd.CommandText.Substring(pos + "TO_NUMBER(".Length, i - pos - "TO_NUMBER(".Length);
            //    string newSql = cmd.CommandText.Substring(0, pos) + string.Format("cast(cast({0} as money) as float)", columnName);
            //    if (i < cmd.CommandText.Length - 1)
            //        newSql += cmd.CommandText.Substring(i + 1);
            //    cmd.CommandText = newSql;
            //}

        }
    }
}


text:
#include "config.h"

#include "RenderFlowThread.h"

#include "FlowThreadController.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "Node.h"
#include "PaintInfo.h"
#include "RenderBoxRegionInfo.h"
#include "RenderLayer.h"
#include "RenderRegion.h"
#include "RenderView.h"
#include "TransformState.h"
#include "WebKitNamedFlow.h"

namespace WebCore {

RenderFlowThread::RenderFlowThread(Node* node)
    : RenderBlock(node)
    , m_regionsInvalidated(false)
    , m_regionsHaveUniformLogicalWidth(true)
    , m_regionsHaveUniformLogicalHeight(true)
    , m_overset(true)
    , m_hasRegionsWithStyling(false)
    , m_dispatchRegionLayoutUpdateEvent(false)
    , m_pageLogicalHeightChanged(false)
{
    ASSERT(node->document()->cssRegionsEnabled());
    setIsAnonymous(false);
    setInRenderFlowThread();
}

PassRefPtr<RenderStyle> RenderFlowThread::createFlowThreadStyle(RenderStyle* parentStyle)
{
    RefPtr<RenderStyle> newStyle(RenderStyle::create());
    newStyle->inheritFrom(parentStyle);
    newStyle->setDisplay(BLOCK);
    newStyle->setPosition(AbsolutePosition);
    newStyle->setZIndex(0);
    newStyle->setLeft(Length(0, Fixed));
    newStyle->setTop(Length(0, Fixed));
    newStyle->setWidth(Length(100, Percent));
    newStyle->setHeight(Length(100, Percent));
    newStyle->font().update(0);

    return newStyle.release();
}

void RenderFlowThread::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
    RenderBlock::styleDidChange(diff, oldStyle);

    if (oldStyle && oldStyle->writingMode() != style()->writingMode())
        m_regionsInvalidated = true;
}

void RenderFlowThread::removeFlowChildInfo(RenderObject* child)
{
    if (child->isBox())
        removeRenderBoxRegionInfo(toRenderBox(child));
    clearRenderObjectCustomStyle(child);
}

void RenderFlowThread::addRegionToThread(RenderRegion* renderRegion)
{
    ASSERT(renderRegion);
    m_regionList.add(renderRegion);
    renderRegion->setIsValid(true);
    invalidateRegions();
    checkRegionsWithStyling();
}

void RenderFlowThread::removeRegionFromThread(RenderRegion* renderRegion)
{
    ASSERT(renderRegion);
    m_regionRangeMap.clear();
    m_regionList.remove(renderRegion);
    invalidateRegions();
    checkRegionsWithStyling();
}

class CurrentRenderFlowThreadDisabler {
    WTF_MAKE_NONCOPYABLE(CurrentRenderFlowThreadDisabler);
public:
    CurrentRenderFlowThreadDisabler(RenderView* view)
        : m_view(view)
        , m_renderFlowThread(0)
    {
        m_renderFlowThread = m_view->flowThreadController()->currentRenderFlowThread();
        if (m_renderFlowThread)
            view->flowThreadController()->setCurrentRenderFlowThread(0);
    }
    ~CurrentRenderFlowThreadDisabler()
    {
        if (m_renderFlowThread)
            m_view->flowThreadController()->setCurrentRenderFlowThread(m_renderFlowThread);
    }
private:
    RenderView* m_view;
    RenderFlowThread* m_renderFlowThread;
};

void RenderFlowThread::layout()
{
    m_pageLogicalHeightChanged = m_regionsInvalidated && everHadLayout();
    if (m_regionsInvalidated) {
        m_regionsInvalidated = false;
        m_regionsHaveUniformLogicalWidth = true;
        m_regionsHaveUniformLogicalHeight = true;
        m_regionRangeMap.clear();
        LayoutUnit previousRegionLogicalWidth = 0;
        LayoutUnit previousRegionLogicalHeight = 0;
        bool firstRegionVisited = false;
        if (hasRegions()) {
            for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
                RenderRegion* region = *iter;
                ASSERT(!region->needsLayout());

                region->deleteAllRenderBoxRegionInfo();

                LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
                LayoutUnit regionLogicalHeight = region->pageLogicalHeight();

                if (!firstRegionVisited)
                    firstRegionVisited = true;
                else {
                    if (m_regionsHaveUniformLogicalWidth && previousRegionLogicalWidth != regionLogicalWidth)
                        m_regionsHaveUniformLogicalWidth = false;
                    if (m_regionsHaveUniformLogicalHeight && previousRegionLogicalHeight != regionLogicalHeight)
                        m_regionsHaveUniformLogicalHeight = false;
                }

                previousRegionLogicalWidth = regionLogicalWidth;
            }

            updateLogicalWidth(); // Called to get the maximum logical width for the region.
            updateRegionsFlowThreadPortionRect();
        }
    }

    CurrentRenderFlowThreadMaintainer currentFlowThreadSetter(this);
    RenderBlock::layout();

    m_pageLogicalHeightChanged = false;

    if (lastRegion())
        lastRegion()->expandToEncompassFlowThreadContentsIfNeeded();

    if (shouldDispatchRegionLayoutUpdateEvent())
        dispatchRegionLayoutUpdateEvent();
}

void RenderFlowThread::updateLogicalWidth()
{
    LayoutUnit logicalWidth = 0;
    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        ASSERT(!region->needsLayout());
        logicalWidth = max(region->pageLogicalWidth(), logicalWidth);
    }
    setLogicalWidth(logicalWidth);

    // If the regions have non-uniform logical widths, then insert inset information for the RenderFlowThread.
    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
        if (regionLogicalWidth != logicalWidth) {
            LayoutUnit logicalLeft = style()->direction() == LTR ? ZERO_LAYOUT_UNIT : logicalWidth - regionLogicalWidth;
            region->setRenderBoxRegionInfo(this, logicalLeft, regionLogicalWidth, false);
        }
    }
}

void RenderFlowThread::computeLogicalHeight(LayoutUnit, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
{
    computedValues.m_position = logicalTop;
    computedValues.m_extent = 0;

    for (RenderRegionList::const_iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        ASSERT(!region->needsLayout());

        if (region->needsOverrideLogicalContentHeightComputation()) {
            // If we have an auto logical height region for which we did not compute a height yet,
            // then we cannot compute and update the height of this flow.
            return;
        }

        computedValues.m_extent += region->logicalHeightOfAllFlowThreadContent();
    }
}

void RenderFlowThread::paintFlowThreadPortionInRegion(PaintInfo& paintInfo, RenderRegion* region, LayoutRect flowThreadPortionRect, LayoutRect flowThreadPortionOverflowRect, const LayoutPoint& paintOffset) const
{
    GraphicsContext* context = paintInfo.context;
    if (!context)
        return;

    // Adjust the clipping rect for the region.
    // paintOffset contains the offset where the painting should occur
    // adjusted with the region padding and border.
    LayoutRect regionClippingRect(paintOffset + (flowThreadPortionOverflowRect.location() - flowThreadPortionRect.location()), flowThreadPortionOverflowRect.size());

    PaintInfo info(paintInfo);
    info.rect.intersect(pixelSnappedIntRect(regionClippingRect));

    if (!info.rect.isEmpty()) {
        context->save();

        context->clip(regionClippingRect);

        // RenderFlowThread should start painting its content in a position that is offset
        // from the region rect's current position. The amount of offset is equal to the location of
        // the flow thread portion in the flow thread's local coordinates.
        IntPoint renderFlowThreadOffset;
        if (style()->isFlippedBlocksWritingMode()) {
            LayoutRect flippedFlowThreadPortionRect(flowThreadPortionRect);
            flipForWritingMode(flippedFlowThreadPortionRect);
            renderFlowThreadOffset = roundedIntPoint(paintOffset - flippedFlowThreadPortionRect.location());
        } else
            renderFlowThreadOffset = roundedIntPoint(paintOffset - flowThreadPortionRect.location());

        context->translate(renderFlowThreadOffset.x(), renderFlowThreadOffset.y());
        info.rect.moveBy(-renderFlowThreadOffset);

        layer()->paint(context, info.rect, 0, 0, region, RenderLayer::PaintLayerTemporaryClipRects);

        context->restore();
    }
}

bool RenderFlowThread::hitTestFlowThreadPortionInRegion(RenderRegion* region, LayoutRect flowThreadPortionRect, LayoutRect flowThreadPortionOverflowRect, const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) const
{
    LayoutRect regionClippingRect(accumulatedOffset + (flowThreadPortionOverflowRect.location() - flowThreadPortionRect.location()), flowThreadPortionOverflowRect.size());
    if (!regionClippingRect.contains(locationInContainer.point()))
        return false;

    LayoutSize renderFlowThreadOffset;
    if (style()->isFlippedBlocksWritingMode()) {
        LayoutRect flippedFlowThreadPortionRect(flowThreadPortionRect);
        flipForWritingMode(flippedFlowThreadPortionRect);
        renderFlowThreadOffset = accumulatedOffset - flippedFlowThreadPortionRect.location();
    } else
        renderFlowThreadOffset = accumulatedOffset - flowThreadPortionRect.location();

    // Always ignore clipping, since the RenderFlowThread has nothing to do with the bounds of the FrameView.
    HitTestRequest newRequest(request.type() | HitTestRequest::IgnoreClipping);

    // Make a new temporary HitTestLocation in the new region.
    HitTestLocation newHitTestLocation(locationInContainer, -renderFlowThreadOffset, region);

    bool isPointInsideFlowThread = layer()->hitTest(newRequest, newHitTestLocation, result);

    // FIXME: Should we set result.m_localPoint back to the RenderRegion's coordinate space or leave it in the RenderFlowThread's coordinate
    // space? Right now it's staying in the RenderFlowThread's coordinate space, which may end up being ok. We will know more when we get around to
    // patching positionForPoint.
    return isPointInsideFlowThread;
}

bool RenderFlowThread::shouldRepaint(const LayoutRect& r) const
{
    if (view()->printing() || r.isEmpty())
        return false;

    return true;
}

void RenderFlowThread::repaintRectangleInRegions(const LayoutRect& repaintRect, bool immediate)
{
    if (!shouldRepaint(repaintRect) || !hasValidRegionInfo())
        return;

    LayoutStateDisabler layoutStateDisabler(view()); // We can't use layout state to repaint, since the regions are somewhere else.

    // We can't use currentFlowThread as it is possible to have interleaved flow threads and the wrong one could be used.
    // Let each region figure out the proper enclosing flow thread.
    CurrentRenderFlowThreadDisabler disabler(view());

    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;

        region->repaintFlowThreadContent(repaintRect, immediate);
    }
}

RenderRegion* RenderFlowThread::regionAtBlockOffset(LayoutUnit offset, bool extendLastRegion) const
{
    ASSERT(!m_regionsInvalidated);

    // If no region matches the position and extendLastRegion is true, it will return
    // the last valid region. It is similar to auto extending the size of the last region.
    RenderRegion* lastValidRegion = 0;

    LayoutUnit accumulatedLogicalHeight = ZERO_LAYOUT_UNIT;

    // FIXME: The regions are always in order, optimize this search.
    for (RenderRegionList::const_iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;

        if (offset <= 0)
            return region;

        if (extendLastRegion || region->isRenderRegionSet())
            lastValidRegion = region;

        // If we did not compute the region's height, we should consider this region
        // tall enough to accomodate all content.
        if (region->needsOverrideLogicalContentHeightComputation())
            return region;

        if (region->hasOverrideHeight() && view()->normalLayoutPhase()) {
            accumulatedLogicalHeight += region->overrideLogicalContentHeight();
            if (offset < accumulatedLogicalHeight)
                return region;
            continue;
        }

        LayoutRect regionRect = region->flowThreadPortionRect();
        accumulatedLogicalHeight += isHorizontalWritingMode() ? regionRect.height() : regionRect.width();
        if (offset < accumulatedLogicalHeight)
            return region;
    }

    return lastValidRegion;
}

LayoutUnit RenderFlowThread::pageLogicalTopForOffset(LayoutUnit offset) const
{
    RenderRegion* region = regionAtBlockOffset(offset);
    return region ? region->pageLogicalTopForOffset(offset) : ZERO_LAYOUT_UNIT;
}

LayoutUnit RenderFlowThread::pageLogicalWidthForOffset(LayoutUnit offset) const
{
    RenderRegion* region = regionAtBlockOffset(offset, true);
    return region ? region->pageLogicalWidth() : contentLogicalWidth();
}

LayoutUnit RenderFlowThread::pageLogicalHeightForOffset(LayoutUnit offset) const
{
    RenderRegion* region = regionAtBlockOffset(offset);
    if (!region)
        return ZERO_LAYOUT_UNIT;
    if (region->needsOverrideLogicalContentHeightComputation())
        return MAX_LAYOUT_UNIT / 2;
    return region->pageLogicalHeight();
}

LayoutUnit RenderFlowThread::pageRemainingLogicalHeightForOffset(LayoutUnit offset, PageBoundaryRule pageBoundaryRule) const
{
    RenderRegion* region = regionAtBlockOffset(offset);
    if (!region)
        return ZERO_LAYOUT_UNIT;
    if (region->needsOverrideLogicalContentHeightComputation())
        return MAX_LAYOUT_UNIT / 2;

    LayoutUnit pageLogicalTop = region->pageLogicalTopForOffset(offset);
    LayoutUnit pageLogicalHeight = region->pageLogicalHeight();
    LayoutUnit pageLogicalBottom = pageLogicalTop + pageLogicalHeight;
    LayoutUnit remainingHeight = pageLogicalBottom - offset;
    if (pageBoundaryRule == IncludePageBoundary) {
        // If IncludePageBoundary is set, the line exactly on the top edge of a
        // region will act as being part of the previous region.
        remainingHeight = intMod(remainingHeight, pageLogicalHeight);
    }
    return remainingHeight;
}

RenderRegion* RenderFlowThread::mapFromFlowToRegion(TransformState& transformState) const
{
    if (!hasValidRegionInfo())
        return 0;

    LayoutRect boxRect = transformState.mappedQuad().enclosingBoundingBox();
    flipForWritingMode(boxRect);

    // FIXME: We need to refactor RenderObject::absoluteQuads to be able to split the quads across regions,
    // for now we just take the center of the mapped enclosing box and map it to a region.
    // Note: Using the center in order to avoid rounding errors.

    LayoutPoint center = boxRect.center();
    RenderRegion* renderRegion = regionAtBlockOffset(isHorizontalWritingMode() ? center.y() : center.x(), true);
    if (!renderRegion)
        return 0;

    LayoutRect flippedRegionRect(renderRegion->flowThreadPortionRect());
    flipForWritingMode(flippedRegionRect);

    transformState.move(renderRegion->contentBoxRect().location() - flippedRegionRect.location());

    return renderRegion;
}

void RenderFlowThread::removeRenderBoxRegionInfo(RenderBox* box)
{
    if (!hasRegions())
        return;

    RenderRegion* startRegion;
    RenderRegion* endRegion;
    getRegionRangeForBox(box, startRegion, endRegion);

    for (RenderRegionList::iterator iter = m_regionList.find(startRegion); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        region->removeRenderBoxRegionInfo(box);
        if (region == endRegion)
            break;
    }

#ifndef NDEBUG
    // We have to make sure we did not leave any RenderBoxRegionInfo attached.
    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        ASSERT(!region->renderBoxRegionInfo(box));
    }
#endif

    m_regionRangeMap.remove(box);
}

bool RenderFlowThread::logicalWidthChangedInRegions(const RenderBlock* block, LayoutUnit offsetFromLogicalTopOfFirstPage)
{
    if (!hasRegions() || block == this) // Not necessary, since if any region changes, we do a full pagination relayout anyway.
        return false;

    RenderRegion* startRegion;
    RenderRegion* endRegion;
    getRegionRangeForBox(block, startRegion, endRegion);

    for (RenderRegionList::iterator iter = m_regionList.find(startRegion); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        ASSERT(!region->needsLayout());

        OwnPtr<RenderBoxRegionInfo> oldInfo = region->takeRenderBoxRegionInfo(block);
        if (!oldInfo)
            continue;

        LayoutUnit oldLogicalWidth = oldInfo->logicalWidth();
        RenderBoxRegionInfo* newInfo = block->renderBoxRegionInfo(region, offsetFromLogicalTopOfFirstPage);
        if (!newInfo || newInfo->logicalWidth() != oldLogicalWidth)
            return true;

        if (region == endRegion)
            break;
    }

    return false;
}

LayoutUnit RenderFlowThread::contentLogicalWidthOfFirstRegion() const
{
    RenderRegion* firstValidRegionInFlow = firstRegion();
    if (!firstValidRegionInFlow)
        return ZERO_LAYOUT_UNIT;
    return isHorizontalWritingMode() ? firstValidRegionInFlow->contentWidth() : firstValidRegionInFlow->contentHeight();
}

LayoutUnit RenderFlowThread::contentLogicalHeightOfFirstRegion() const
{
    RenderRegion* firstValidRegionInFlow = firstRegion();
    if (!firstValidRegionInFlow)
        return ZERO_LAYOUT_UNIT;
    return isHorizontalWritingMode() ? firstValidRegionInFlow->contentHeight() : firstValidRegionInFlow->contentWidth();
}

LayoutUnit RenderFlowThread::contentLogicalLeftOfFirstRegion() const
{
    RenderRegion* firstValidRegionInFlow = firstRegion();
    if (!firstValidRegionInFlow)
        return ZERO_LAYOUT_UNIT;
    return isHorizontalWritingMode() ? firstValidRegionInFlow->flowThreadPortionRect().x() : firstValidRegionInFlow->flowThreadPortionRect().y();
}

RenderRegion* RenderFlowThread::firstRegion() const
{
    if (!hasValidRegionInfo())
        return 0;
    return m_regionList.first();
}

RenderRegion* RenderFlowThread::lastRegion() const
{
    if (!hasValidRegionInfo())
        return 0;
    return m_regionList.last();
}

void RenderFlowThread::clearRenderObjectCustomStyle(const RenderObject* object,
    const RenderRegion* oldStartRegion, const RenderRegion* oldEndRegion,
    const RenderRegion* newStartRegion, const RenderRegion* newEndRegion)
{
    // Clear the styles for the object in the regions.
    // The styles are not cleared for the regions that are contained in both ranges.
    bool insideOldRegionRange = false;
    bool insideNewRegionRange = false;
    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;

        if (oldStartRegion == region)
            insideOldRegionRange = true;
        if (newStartRegion == region)
            insideNewRegionRange = true;

        if (!(insideOldRegionRange && insideNewRegionRange))
            region->clearObjectStyleInRegion(object);

        if (oldEndRegion == region)
            insideOldRegionRange = false;
        if (newEndRegion == region)
            insideNewRegionRange = false;
    }
}

void RenderFlowThread::setRegionRangeForBox(const RenderBox* box, LayoutUnit offsetFromLogicalTopOfFirstPage)
{
    if (!hasRegions())
        return;

    // FIXME: Not right for differing writing-modes.
    RenderRegion* startRegion = regionAtBlockOffset(offsetFromLogicalTopOfFirstPage, true);
    RenderRegion* endRegion = regionAtBlockOffset(offsetFromLogicalTopOfFirstPage + box->logicalHeight(), true);
    RenderRegionRangeMap::iterator it = m_regionRangeMap.find(box);
    if (it == m_regionRangeMap.end()) {
        m_regionRangeMap.set(box, RenderRegionRange(startRegion, endRegion));
        clearRenderObjectCustomStyle(box);
        return;
    }

    // If nothing changed, just bail.
    RenderRegionRange& range = it->value;
    if (range.startRegion() == startRegion && range.endRegion() == endRegion)
        return;

    // Delete any info that we find before our new startRegion and after our new endRegion.
    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        if (region == startRegion) {
            iter = m_regionList.find(endRegion);
            continue;
        }

        region->removeRenderBoxRegionInfo(box);

        if (region == range.endRegion())
            break;
    }

    clearRenderObjectCustomStyle(box, range.startRegion(), range.endRegion(), startRegion, endRegion);
    range.setRange(startRegion, endRegion);
}

void RenderFlowThread::getRegionRangeForBox(const RenderBox* box, RenderRegion*& startRegion, RenderRegion*& endRegion) const
{
    startRegion = 0;
    endRegion = 0;
    RenderRegionRangeMap::const_iterator it = m_regionRangeMap.find(box);
    if (it == m_regionRangeMap.end())
        return;

    const RenderRegionRange& range = it->value;
    startRegion = range.startRegion();
    endRegion = range.endRegion();
    ASSERT(m_regionList.contains(startRegion) && m_regionList.contains(endRegion));
}

void RenderFlowThread::computeOverflowStateForRegions(LayoutUnit oldClientAfterEdge)
{
    LayoutUnit height = oldClientAfterEdge;

    // Simulate a region break at height. If it points inside an auto logical height region,
    // then it determines the region override logical content height.
    addForcedRegionBreak(height);

    // FIXME: the visual overflow of middle region (if it is the last one to contain any content in a render flow thread)
    // might not be taken into account because the render flow thread height is greater that that regions height + its visual overflow
    // because of how computeLogicalHeight is implemented for RenderFlowThread (as a sum of all regions height).
    // This means that the middle region will be marked as fit (even if it has visual overflow flowing into the next region)
    if (hasRenderOverflow()
        && ( (isHorizontalWritingMode() && visualOverflowRect().maxY() > clientBoxRect().maxY())
            || (!isHorizontalWritingMode() && visualOverflowRect().maxX() > clientBoxRect().maxX())))
        height = isHorizontalWritingMode() ? visualOverflowRect().maxY() : visualOverflowRect().maxX();

    RenderRegion* lastReg = lastRegion();
    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        LayoutUnit flowMin = height - (isHorizontalWritingMode() ? region->flowThreadPortionRect().y() : region->flowThreadPortionRect().x());
        LayoutUnit flowMax = height - (isHorizontalWritingMode() ? region->flowThreadPortionRect().maxY() : region->flowThreadPortionRect().maxX());
        RenderRegion::RegionState previousState = region->regionState();
        RenderRegion::RegionState state = RenderRegion::RegionFit;
        if (flowMin <= 0)
            state = RenderRegion::RegionEmpty;
        if (flowMax > 0 && region == lastReg)
            state = RenderRegion::RegionOverset;
        region->setRegionState(state);
        // determine whether the NamedFlow object should dispatch a regionLayoutUpdate event
        // FIXME: currently it cannot determine whether a region whose regionOverset state remained either "fit" or "overset" has actually
        // changed, so it just assumes that the NamedFlow should dispatch the event
        if (previousState != state
            || state == RenderRegion::RegionFit
            || state == RenderRegion::RegionOverset)
            setDispatchRegionLayoutUpdateEvent(true);
    }

    // With the regions overflow state computed we can also set the overset flag for the named flow.
    // If there are no valid regions in the chain, overset is true.
    m_overset = lastReg ? lastReg->regionState() == RenderRegion::RegionOverset : true;
}

bool RenderFlowThread::regionInRange(const RenderRegion* targetRegion, const RenderRegion* startRegion, const RenderRegion* endRegion) const
{
    ASSERT(targetRegion);

    for (RenderRegionList::const_iterator it = m_regionList.find(const_cast<RenderRegion*>(startRegion)); it != m_regionList.end(); ++it) {
        const RenderRegion* currRegion = *it;
        if (targetRegion == currRegion)
            return true;
        if (currRegion == endRegion)
            break;
    }

    return false;
}

// Check if the content is flown into at least a region with region styling rules.
void RenderFlowThread::checkRegionsWithStyling()
{
    bool hasRegionsWithStyling = false;
    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        if (region->hasCustomRegionStyle()) {
            hasRegionsWithStyling = true;
            break;
        }
    }
    m_hasRegionsWithStyling = hasRegionsWithStyling;
}

bool RenderFlowThread::objectInFlowRegion(const RenderObject* object, const RenderRegion* region) const
{
    ASSERT(object);
    ASSERT(region);

    if (!object->inRenderFlowThread())
        return false;
    if (object->enclosingRenderFlowThread() != this)
        return false;
    if (!m_regionList.contains(const_cast<RenderRegion*>(region)))
        return false;

    RenderBox* enclosingBox = object->enclosingBox();
    RenderRegion* enclosingBoxStartRegion = 0;
    RenderRegion* enclosingBoxEndRegion = 0;
    getRegionRangeForBox(enclosingBox, enclosingBoxStartRegion, enclosingBoxEndRegion);
    if (!regionInRange(region, enclosingBoxStartRegion, enclosingBoxEndRegion))
        return false;

    if (object->isBox())
        return true;

    LayoutRect objectABBRect = object->absoluteBoundingBoxRect(true);
    if (!objectABBRect.width())
        objectABBRect.setWidth(1);
    if (!objectABBRect.height())
        objectABBRect.setHeight(1);
    if (objectABBRect.intersects(region->absoluteBoundingBoxRect(true)))
        return true;

    if (region == lastRegion()) {
        // If the object does not intersect any of the enclosing box regions
        // then the object is in last region.
        for (RenderRegionList::const_iterator it = m_regionList.find(enclosingBoxStartRegion); it != m_regionList.end(); ++it) {
            const RenderRegion* currRegion = *it;
            if (currRegion == region)
                break;
            if (objectABBRect.intersects(currRegion->absoluteBoundingBoxRect(true)))
                return false;
        }
        return true;
    }

    return false;
}

#ifndef NDEBUG
unsigned RenderFlowThread::autoLogicalHeightRegionsCount() const
{
    unsigned autoLogicalHeightRegions = 0;
    for (RenderRegionList::const_iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        const RenderRegion* region = *iter;
        if (region->hasAutoLogicalHeight())
            autoLogicalHeightRegions++;
    }

    return autoLogicalHeightRegions;
}
#endif

void RenderFlowThread::resetRegionsOverrideLogicalContentHeight()
{
    ASSERT(view()->layoutState());
    ASSERT(view()->normalLayoutPhase());

    // We need to reset the override logical content height for regions with auto logical height
    // only if the flow thread content needs layout.
    if (!selfNeedsLayout())
        return;

    // FIXME: optimize this to iterate the region chain only if the flow thread has auto logical height
    // region.

    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        if (!region->hasAutoLogicalHeight())
            continue;

        region->clearOverrideLogicalContentHeight();
        // FIXME: We need to find a way to avoid marking all the regions ancestors for layout
        // as we are already inside layout.
        region->setNeedsLayout(true);
    }
}

void RenderFlowThread::markAutoLogicalHeightRegionsForLayout()
{
    ASSERT(view()->layoutState());
    ASSERT(view()->constrainedFlowThreadsLayoutPhase());

    // FIXME: optimize this to iterate the region chain only if the flow thread has auto logical height
    // region.

    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;
        if (!region->hasAutoLogicalHeight())
            continue;

        // FIXME: We need to find a way to avoid marking all the regions ancestors for layout
        // as we are already inside layout.
        region->setNeedsLayout(true);
    }

    m_regionsInvalidated = true;
    setNeedsLayout(true);
}

void RenderFlowThread::updateRegionsFlowThreadPortionRect()
{
    LayoutUnit logicalHeight = 0;
    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
        RenderRegion* region = *iter;

        LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
        LayoutUnit regionLogicalHeight = region->logicalHeightOfAllFlowThreadContent();

        LayoutRect regionRect(style()->direction() == LTR ? ZERO_LAYOUT_UNIT : logicalWidth() - regionLogicalWidth, logicalHeight, regionLogicalWidth, regionLogicalHeight);

        // FIXME: when a flow thread has more than one auto logical height region,
        // we have to take into account the override logical content height value,
        // if computed for an auto logical height region, and use it to set the height
        // for the region rect. This way, the regions in the chain following the auto
        // logical height region, will be able to fragment the right part of their
        // associated flow thread content (and compute their overrideComputedLogicalHeight properly).

        region->setFlowThreadPortionRect(isHorizontalWritingMode() ? regionRect : regionRect.transposedRect());
        logicalHeight += regionLogicalHeight;
    }
}

// FIXME: Extend it to account for region break
void RenderFlowThread::addForcedRegionBreak(LayoutUnit offsetBreakInFlowThread)
{
    // We take breaks into account for height computation for auto logical height regions
    // only in the layout phase in which we lay out the flows threads unconstrained
    // and we use the content breaks to determine the overrideContentLogicalHeight for
    // auto logical height regions.
    if (view()->constrainedFlowThreadsLayoutPhase())
        return;

    // Simulate a region break at height. If it points inside an auto logical height region,
    // then it determines the region override logical content height.
    RenderRegion* region = regionAtBlockOffset(offsetBreakInFlowThread);
    if (!region)
        return;

    if (!region->needsOverrideLogicalContentHeightComputation())
        return;

    LayoutUnit currentRegionOffsetInFlowThread = isHorizontalWritingMode() ? region->flowThreadPortionRect().y() : region->flowThreadPortionRect().x();
    LayoutUnit offsetBreakInCurrentRegion = offsetBreakInFlowThread - currentRegionOffsetInFlowThread;
    LayoutUnit regionOverrideLogicalContentHeight = region->computeReplacedLogicalHeightRespectingMinMaxHeight(offsetBreakInCurrentRegion);
    region->setOverrideLogicalContentHeight(regionOverrideLogicalContentHeight);

    // FIXME: Extend it to take into account that we may have more than one auto-height region in flow.
    // For now, clear the override logical content height for remaining auto logical height regions in the flow.
    // A follow-up patch will properly distribute the remaining height into the following regions.
    RenderRegionList::iterator regionIter = m_regionList.find(region);
    ASSERT(regionIter != m_regionList.end());

    // Skip the current region.
    ++regionIter;

    for (; regionIter != m_regionList.end(); ++regionIter) {
        RenderRegion* currRegion = *regionIter;
        if (!currRegion->hasAutoLogicalHeight())
            continue;
        currRegion->clearOverrideLogicalContentHeight();
    }

    updateRegionsFlowThreadPortionRect();
}

CurrentRenderFlowThreadMaintainer::CurrentRenderFlowThreadMaintainer(RenderFlowThread* renderFlowThread)
    : m_renderFlowThread(renderFlowThread)
{
    if (!m_renderFlowThread)
        return;
    RenderView* view = m_renderFlowThread->view();
    ASSERT(!view->flowThreadController()->currentRenderFlowThread());
    view->flowThreadController()->setCurrentRenderFlowThread(m_renderFlowThread);
}

CurrentRenderFlowThreadMaintainer::~CurrentRenderFlowThreadMaintainer()
{
    if (!m_renderFlowThread)
        return;
    RenderView* view = m_renderFlowThread->view();
    ASSERT(view->flowThreadController()->currentRenderFlowThread() == m_renderFlowThread);
    view->flowThreadController()->setCurrentRenderFlowThread(0);
}

} // namespace WebCore


text:
log_level                :debug
log_location             STDOUT
# Webui is an admin.
# env.rb gets the client name from Chef::Config[:web_ui_client_name] but we
# cannot use that since it won't be loaded in knife's memory.
systmpdir = File.expand_path(File.join(Dir.tmpdir, "chef_integration"))
node_name                'chef-webui'
client_key               File.join(systmpdir, "webui.pem")
validation_client_name   'chef-validator'
validation_key           File.join(systmpdir, "validation.pem")
chef_server_url          'http://localhost:4000'
cache_type               'BasicFile'


text:
using namespace lldb;
using namespace lldb_private;

LLDB_PLUGIN_DEFINE(MemoryHistoryASan)

MemoryHistorySP MemoryHistoryASan::CreateInstance(const ProcessSP &process_sp) {
  if (!process_sp.get())
    return nullptr;

  Target &target = process_sp->GetTarget();

  const ModuleList &target_modules = target.GetImages();
  std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
  const size_t num_modules = target_modules.GetSize();
  for (size_t i = 0; i < num_modules; ++i) {
    Module *module_pointer = target_modules.GetModulePointerAtIndexUnlocked(i);

    const Symbol *symbol = module_pointer->FindFirstSymbolWithNameAndType(
        ConstString("__asan_get_alloc_stack"), lldb::eSymbolTypeAny);

    if (symbol != nullptr)
      return MemoryHistorySP(new MemoryHistoryASan(process_sp));
  }

  return MemoryHistorySP();
}

void MemoryHistoryASan::Initialize() {
  PluginManager::RegisterPlugin(
      GetPluginNameStatic(), "ASan memory history provider.", CreateInstance);
}

void MemoryHistoryASan::Terminate() {
  PluginManager::UnregisterPlugin(CreateInstance);
}

ConstString MemoryHistoryASan::GetPluginNameStatic() {
  static ConstString g_name("asan");
  return g_name;
}

MemoryHistoryASan::MemoryHistoryASan(const ProcessSP &process_sp) {
  if (process_sp)
    m_process_wp = process_sp;
}

const char *memory_history_asan_command_prefix = R"(
    extern "C"
    {
        size_t __asan_get_alloc_stack(void *addr, void **trace, size_t size, int *thread_id);
        size_t __asan_get_free_stack(void *addr, void **trace, size_t size, int *thread_id);
    }

    struct data {
        void *alloc_trace[256];
        size_t alloc_count;
        int alloc_tid;

        void *free_trace[256];
        size_t free_count;
        int free_tid;
    };
)";

const char *memory_history_asan_command_format =
    R"(
    data t;

    t.alloc_count = __asan_get_alloc_stack((void *)0x%)" PRIx64
    R"(, t.alloc_trace, 256, &t.alloc_tid);
    t.free_count = __asan_get_free_stack((void *)0x%)" PRIx64
    R"(, t.free_trace, 256, &t.free_tid);

    t;
)";

static void CreateHistoryThreadFromValueObject(ProcessSP process_sp,
                                               ValueObjectSP return_value_sp,
                                               const char *type,
                                               const char *thread_name,
                                               HistoryThreads &result) {
  std::string count_path = "." + std::string(type) + "_count";
  std::string tid_path = "." + std::string(type) + "_tid";
  std::string trace_path = "." + std::string(type) + "_trace";

  ValueObjectSP count_sp =
      return_value_sp->GetValueForExpressionPath(count_path.c_str());
  ValueObjectSP tid_sp =
      return_value_sp->GetValueForExpressionPath(tid_path.c_str());

  if (!count_sp || !tid_sp)
    return;

  int count = count_sp->GetValueAsUnsigned(0);
  tid_t tid = tid_sp->GetValueAsUnsigned(0) + 1;

  if (count <= 0)
    return;

  ValueObjectSP trace_sp =
      return_value_sp->GetValueForExpressionPath(trace_path.c_str());

  if (!trace_sp)
    return;

  std::vector<lldb::addr_t> pcs;
  for (int i = 0; i < count; i++) {
    addr_t pc = trace_sp->GetChildAtIndex(i, true)->GetValueAsUnsigned(0);
    if (pc == 0 || pc == 1 || pc == LLDB_INVALID_ADDRESS)
      continue;
    pcs.push_back(pc);
  }

  // The ASAN runtime already massages the return addresses into call
  // addresses, we don't want LLDB's unwinder to try to locate the previous
  // instruction again as this might lead to us reporting a different line.
  bool pcs_are_call_addresses = true;
  HistoryThread *history_thread =
      new HistoryThread(*process_sp, tid, pcs, pcs_are_call_addresses);
  ThreadSP new_thread_sp(history_thread);
  std::ostringstream thread_name_with_number;
  thread_name_with_number << thread_name << " Thread " << tid;
  history_thread->SetThreadName(thread_name_with_number.str().c_str());
  // Save this in the Process' ExtendedThreadList so a strong pointer retains
  // the object
  process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
  result.push_back(new_thread_sp);
}

HistoryThreads MemoryHistoryASan::GetHistoryThreads(lldb::addr_t address) {
  HistoryThreads result;

  ProcessSP process_sp = m_process_wp.lock();
  if (!process_sp)
    return result;

  ThreadSP thread_sp =
      process_sp->GetThreadList().GetExpressionExecutionThread();
  if (!thread_sp)
    return result;

  StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
  if (!frame_sp)
    return result;

  ExecutionContext exe_ctx(frame_sp);
  ValueObjectSP return_value_sp;
  StreamString expr;
  Status eval_error;
  expr.Printf(memory_history_asan_command_format, address, address);

  EvaluateExpressionOptions options;
  options.SetUnwindOnError(true);
  options.SetTryAllThreads(true);
  options.SetStopOthers(true);
  options.SetIgnoreBreakpoints(true);
  options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
  options.SetPrefix(memory_history_asan_command_prefix);
  options.SetAutoApplyFixIts(false);
  options.SetLanguage(eLanguageTypeObjC_plus_plus);

  ExpressionResults expr_result = UserExpression::Evaluate(
      exe_ctx, options, expr.GetString(), "", return_value_sp, eval_error);
  if (expr_result != eExpressionCompleted) {
    process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(
        "Warning: Cannot evaluate AddressSanitizer expression:\n%s\n",
        eval_error.AsCString());
    return result;
  }

  if (!return_value_sp)
    return result;

  CreateHistoryThreadFromValueObject(process_sp, return_value_sp, "free",
                                     "Memory deallocated by", result);
  CreateHistoryThreadFromValueObject(process_sp, return_value_sp, "alloc",
                                     "Memory allocated by", result);

  return result;
}


text:
module SolidusPaypalBraintree
  module GatewayHelpers
    def new_gateway(opts = {})
      SolidusPaypalBraintree::Gateway.new({
        name: "Braintree",
        preferences: {
          environment: 'sandbox',
          public_key: ENV.fetch('BRAINTREE_PUBLIC_KEY', 'dummy_public_key'),
          private_key: ENV.fetch('BRAINTREE_PRIVATE_KEY', 'dummy_private_key'),
          merchant_id: ENV.fetch('BRAINTREE_MERCHANT_ID', 'dummy_merchant_id'),
          merchant_currency_map: {
            'EUR' => 'stembolt_EUR'
          },
          paypal_payee_email_map: {
            'EUR' => ENV.fetch('BRAINTREE_PAYPAL_PAYEE_EMAIL', 'paypal+europe@example.com')
          }
        }
      }.merge(opts))
    end

    def create_gateway(opts = {})
      new_gateway(opts).tap(&:save!)
    end
  end
end

RSpec.configure do |config|
  config.include SolidusPaypalBraintree::GatewayHelpers
end


text:
package dockerauth

import (
	"testing"
	"fmt"

	"github.com/fsouza/go-dockerclient"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func TestMultiAuthProvider_AuthConfiguration_FirstMatch(t *testing.T) {
	mockProvider1 := new(mockAuthProvider)
	mockProvider1.On("AuthConfiguration", "foobar").Return(&docker.AuthConfiguration{Username: "foo"}, nil)
	mockProvider2 := new(mockAuthProvider)
	provider := NewMultiAuthProvider(mockProvider1, mockProvider2)

	authConf, err := provider.AuthConfiguration("foobar")
	assert.NoError(t, err)
	assert.Equal(t, "foo", authConf.Username)
	mockProvider1.AssertCalled(t, "AuthConfiguration", "foobar")
	mockProvider1.AssertNumberOfCalls(t, "AuthConfiguration", 1)
	mockProvider2.AssertNumberOfCalls(t, "AuthConfiguration", 0)
}

func TestMultiAuthProvider_AuthConfiguration_SecondMatch(t *testing.T) {
	mockProvider1 := new(mockAuthProvider)
	mockProvider1.On("AuthConfiguration", "foobar").Return(nil, nil)
	mockProvider2 := new(mockAuthProvider)
	mockProvider2.On("AuthConfiguration", "foobar").Return(&docker.AuthConfiguration{Username: "foo"}, nil)
	provider := NewMultiAuthProvider(mockProvider1, mockProvider2)

	authConf, err := provider.AuthConfiguration("foobar")
	assert.NoError(t, err)
	assert.Equal(t, "foo", authConf.Username)
	mockProvider1.AssertCalled(t, "AuthConfiguration", "foobar")
	mockProvider1.AssertNumberOfCalls(t, "AuthConfiguration", 1)
	mockProvider2.AssertCalled(t, "AuthConfiguration", "foobar")
	mockProvider2.AssertNumberOfCalls(t, "AuthConfiguration", 1)
}

func TestMultiAuthProvider_AuthConfiguration_FirstErr(t *testing.T) {
	mockProvider1 := new(mockAuthProvider)
	mockProvider1.On("AuthConfiguration", "foobar").Return(nil, fmt.Errorf("Some error"))
	mockProvider2 := new(mockAuthProvider)
	mockProvider2.On("AuthConfiguration", "foobar").Return(nil, nil)
	provider := NewMultiAuthProvider(mockProvider1, mockProvider2)

	_, err := provider.AuthConfiguration("foobar")
	assert.EqualError(t, err, "Some error")
	mockProvider1.AssertCalled(t, "AuthConfiguration", "foobar")
	mockProvider1.AssertNumberOfCalls(t, "AuthConfiguration", 1)
	mockProvider2.AssertNumberOfCalls(t, "AuthConfiguration", 0)
}

func TestMultiAuthProvider_AuthConfiguration_NoMatch(t *testing.T) {
	mockProvider1 := new(mockAuthProvider)
	mockProvider1.On("AuthConfiguration", "foobar").Return(nil, nil)
	mockProvider2 := new(mockAuthProvider)
	mockProvider2.On("AuthConfiguration", "foobar").Return(nil, nil)
	provider := NewMultiAuthProvider(mockProvider1, mockProvider2)

	authConf, err := provider.AuthConfiguration("foobar")
	assert.NoError(t, err)
	assert.Nil(t, authConf)
	mockProvider1.AssertCalled(t, "AuthConfiguration", "foobar")
	mockProvider1.AssertNumberOfCalls(t, "AuthConfiguration", 1)
	mockProvider2.AssertCalled(t, "AuthConfiguration", "foobar")
	mockProvider2.AssertNumberOfCalls(t, "AuthConfiguration", 1)
}

func TestMultiAuthProvider_AddProvider(t *testing.T) {
	p := NewMultiAuthProvider()
	assert.Equal(t, 0, len(p.providers))

	mockProvider1 := new(mockAuthProvider)
	p.AddProvider(mockProvider1)
	assert.Equal(t, p.providers, []AuthProvider{mockProvider1})

	mockProvider2 := new(mockAuthProvider)
	p.AddProvider(mockProvider2)
	assert.Equal(t, p.providers, []AuthProvider{mockProvider1, mockProvider2})
}

type mockAuthProvider struct {
	mock.Mock
}

func (m *mockAuthProvider) AuthConfiguration(registry string) (*docker.AuthConfiguration, error) {
	ret := m.Called(registry)
	authConf := ret.Get(0)
	if authConf != nil {
		return ret.Get(0).(*docker.AuthConfiguration), ret.Error(1)
	} else {
		return nil, ret.Error(1)
	}
}


text:
"""
sentry.logging.handlers
~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2016 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

import logging

from django.utils.timezone import now
from simplejson import JSONEncoder
from structlog import get_logger
from structlog.processors import _json_fallback_handler

_default_encoder = JSONEncoder(
    separators=(',', ':'),
    ignore_nan=True,
    skipkeys=False,
    ensure_ascii=True,
    check_circular=True,
    allow_nan=True,
    indent=None,
    encoding='utf-8',
    default=_json_fallback_handler,
).encode

# These are values that come default from logging.LogRecord.
# They are defined here: https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L237-L310
throwaways = frozenset((
    'threadName', 'thread', 'created', 'process', 'processName', 'args',
    'module', 'filename', 'levelno', 'exc_text', 'msg', 'pathname', 'lineno',
    'funcName', 'relativeCreated', 'levelname', 'msecs',
))

class JSONRenderer(object):
    def __call__(self, logger, name, event_dict):
        return _default_encoder(event_dict)

class HumanRenderer(object):
    def __call__(self, logger, name, event_dict):
        level = event_dict.pop('level')
        real_level = (level.upper()
            if isinstance(level, basestring)
            else logging.getLevelName(level)
        )
        base = '%s [%s] %s: %s' % (
            now().strftime('%H:%M:%S'),
            real_level,
            event_dict.pop('name', 'root'),
            event_dict.pop('event', ''),
        )
        join = ' '.join(k + '=' + repr(v)
               for k, v in event_dict.iteritems())
        return '%s%s' % (base, (' (%s)' % join if join else ''))

class StructLogHandler(logging.StreamHandler):
    def emit(self, record, logger=get_logger()):
        # If anyone wants to use the 'extra' kwarg to provide context within
        # structlog, we have to strip all of the default attributes from
        # a record because the RootLogger will take the 'extra' dictionary
        # and just turn them into attributes.
        kwargs = {
            k: v
            for k, v in vars(record).iteritems()
            if k not in throwaways
            and v is not None
        }
        kwargs.update({
            'level': record.levelno,
            'event': record.msg,
        })

        if record.args:
            # record.args inside of LogRecord.__init__ gets unrolled
            # if it's the shape `({},)`, a single item dictionary.
            # so we need to check for this, and re-wrap it because
            # down the line of structlog, it's expected to be this
            # original shape.
            if isinstance(record.args, (tuple, list)):
                kwargs['positional_args'] = record.args
            else:
                kwargs['positional_args'] = (record.args,)

        logger.log(**kwargs)


text:
<?php
/**
 * This file was automatically generated by automattic/jetpack-autoloader.
 *
 * @package automattic/jetpack-autoloader
 */

namespace Automattic\Jetpack\Autoloader\jp95016e8b7af5cfd6a3cbf90d4433a769;

 // phpcs:ignore

/**
 * This class selects the package version for the autoloader.
 */
class Autoloader_Handler {

	// The name of the autoloader function registered by v1.* autoloaders.
	const V1_AUTOLOADER_NAME = 'Automattic\Jetpack\Autoloader\autoloader';

	/*
	 * The autoloader function for v2.* autoloaders is named __NAMESPACE__ . \autoloader.
	 * The namespace is defined in AutoloadGenerator as
	 * 'Automattic\Jetpack\Autoloader\jp' plus a unique suffix.
	 */
	const V2_AUTOLOADER_BASE = 'Automattic\Jetpack\Autoloader\jp';

	/**
	 * The current plugin path.
	 *
	 * @var string
	 */
	private $current_plugin_path;

	/**
	 * The paths for all of the active plugins.
	 *
	 * @var array
	 */
	private $active_plugin_paths;

	/**
	 * The Autoloader_Locator object.
	 *
	 * @var Autoloader_Locator
	 */
	private $autoloader_locator;

	/**
	 * The Version_Selector object.
	 *
	 * @var Version_Selector
	 */
	private $version_selector;

	/**
	 * The constructor.
	 *
	 * @param string             $current_plugin_path The current plugin path.
	 * @param array              $active_plugin_paths The active plugin paths.
	 * @param Autoloader_Locator $autoloader_locator The Autoloader_Locator object.
	 * @param Version_Selector   $version_selector The Version_Selector object.
	 */
	public function __construct( $current_plugin_path, $active_plugin_paths, $autoloader_locator, $version_selector ) {
		$this->current_plugin_path = $current_plugin_path;
		$this->active_plugin_paths = $active_plugin_paths;
		$this->autoloader_locator  = $autoloader_locator;
		$this->version_selector    = $version_selector;
	}

	/**
	 * Finds the latest installed autoloader.
	 *
	 * @return bool True if this autoloader is the latest, false otherwise.
	 */
	public function is_latest_autoloader() {
		global $jetpack_autoloader_latest_version;

		if ( isset( $jetpack_autoloader_latest_version ) ) {
			return $jetpack_autoloader_latest_version === $this->autoloader_locator->get_autoloader_version( $this->current_plugin_path );
		}

		$latest_plugin = $this->autoloader_locator->find_latest_autoloader( $this->active_plugin_paths, $jetpack_autoloader_latest_version );
		if ( ! isset( $latest_plugin ) ) {
			return true;
		}

		if ( $latest_plugin !== $this->current_plugin_path ) {
			require $this->autoloader_locator->get_autoloader_path( $latest_plugin );
			return false;
		}

		return true;
	}

	/**
	 * Checks whether the autoloader should be reset. The autoloader should be reset:
	 *
	 *  - When a plugin is activated via a method other than a request, for example using WP-CLI.
	 *  - When the active plugins list changes between autoloader checks, for example when filtered by a plugin.
	 *
	 * We perform this reset because the manifest files for the plugin will have been initially unknown when
	 * selecting versions for classes and files.
	 *
	 * If the current plugin is not already known, this method will add it to the
	 * $jetpack_autoloader_activating_plugins_paths global.
	 * The $jetpack_autoloader_cached_plugin_paths global will store a cache of the
	 * active plugin paths when last changed.
	 *
	 * @return boolean True if the autoloader must be reset, else false.
	 */
	public function should_autoloader_reset() {
		global $jetpack_autoloader_activating_plugins_paths;
		global $jetpack_autoloader_cached_plugin_paths;

		$plugin_unknown = ! in_array( $this->current_plugin_path, $this->active_plugin_paths, true );
		if ( $plugin_unknown ) {
			if ( ! isset( $jetpack_autoloader_activating_plugins_paths ) ) {
				$jetpack_autoloader_activating_plugins_paths = array();
			}

			// If the current plugin isn't known, add it to the activating plugins list.
			$jetpack_autoloader_activating_plugins_paths[] = $this->current_plugin_path;
			$this->active_plugin_paths[]                   = $this->current_plugin_path;
		}

		$cache_invalidated = $jetpack_autoloader_cached_plugin_paths !== $this->active_plugin_paths;
		if ( $cache_invalidated ) {
			$jetpack_autoloader_cached_plugin_paths = $this->active_plugin_paths;
		}

		return $plugin_unknown || $cache_invalidated;
	}

	/**
	 * Builds the Version_Autoloader class that is used for autoloading.
	 *
	 * @return Version_Loader
	 */
	public function build_autoloader() {
		$manifest_handler = new Manifest_Handler( $this->active_plugin_paths, $this->version_selector );

		global $jetpack_packages_psr4;
		$jetpack_packages_psr4 = array();
		$manifest_handler->register_plugin_manifests( 'vendor/composer/jetpack_autoload_psr4.php', $jetpack_packages_psr4 );

		global $jetpack_packages_classmap;
		$jetpack_packages_classmap = array();
		$manifest_handler->register_plugin_manifests( 'vendor/composer/jetpack_autoload_classmap.php', $jetpack_packages_classmap );

		global $jetpack_packages_filemap;
		$jetpack_packages_filemap = array();
		$manifest_handler->register_plugin_manifests( 'vendor/composer/jetpack_autoload_filemap.php', $jetpack_packages_filemap );

		// Store the generated autoloader data in the loader so we can use it.
		return new Version_Loader(
			$this->version_selector,
			$jetpack_packages_classmap,
			$jetpack_packages_psr4,
			$jetpack_packages_filemap
		);
	}

	/**
	 * Updates the spl autoloader chain:
	 *  - Registers this namespace's autoloader function.
	 *  - If a v1 autoloader function is registered, moves it to the end of the chain.
	 *  - Removes any other v2 autoloader functions that have already been registered. This
	 *    can occur when the autoloader is being reset by an activating plugin.
	 */
	public function update_autoloader_chain() {
		spl_autoload_register( __NAMESPACE__ . '\autoloader' );

		$autoload_chain = spl_autoload_functions();

		foreach ( $autoload_chain as $autoloader ) {
			if ( ! is_string( $autoloader ) ) {
				/*
				 * The Jetpack Autoloader functions are registered as strings, so
				 * just continue if $autoloader isn't a string.
				 */
				continue;
			}

			if ( self::V1_AUTOLOADER_NAME === $autoloader ) {
				// Move the v1.* autoloader function to the end of the spl autoloader chain.
				spl_autoload_unregister( $autoloader );
				spl_autoload_register( $autoloader );

			} elseif (
				self::V2_AUTOLOADER_BASE === substr( $autoloader, 0, strlen( self::V2_AUTOLOADER_BASE ) )
				&& __NAMESPACE__ !== substr( $autoloader, 0, strlen( __NAMESPACE__ ) )
			) {
				// Unregister any other v2.* autoloader functions if they're in the chain.
				spl_autoload_unregister( $autoloader );
			}
		}
	}
}


text:
1.7.2 / 2014-07-27
==================

  * deps: depd@0.4.4
    - Work-around v8 generating empty stack traces

1.7.1 / 2014-07-26
==================

  * deps: depd@0.4.3
    - Fix exception when global `Error.stackTraceLimit` is too low

1.7.0 / 2014-07-22
==================

  * Improve session-ending error handling
    - Errors are passed to `next(err)` instead of `console.error`
  * deps: debug@1.0.4
  * deps: depd@0.4.2
    - Add `TRACE_DEPRECATION` environment variable
    - Remove non-standard grey color from color output
    - Support `--no-deprecation` argument
    - Support `--trace-deprecation` argument

1.6.5 / 2014-07-11
==================

  * Do not require `req.originalUrl`
  * deps: debug@1.0.3
    - Add support for multiple wildcards in namespaces

1.6.4 / 2014-07-07
==================

  * Fix blank responses for stores with synchronous operations

1.6.3 / 2014-07-04
==================

  * Fix resave deprecation message

1.6.2 / 2014-07-04
==================

  * Fix confusing option deprecation messages

1.6.1 / 2014-06-28
==================

  * Fix saveUninitialized deprecation message

1.6.0 / 2014-06-28
==================

  * Add deprecation message to undefined `resave` option
  * Add deprecation message to undefined `saveUninitialized` option
  * Fix `res.end` patch to return correct value
  * Fix `res.end` patch to handle multiple `res.end` calls
  * Reject cookies with missing signatures

1.5.2 / 2014-06-26
==================

  * deps: cookie-signature@1.0.4
    - fix for timing attacks

1.5.1 / 2014-06-21
==================

  * Move hard-to-track-down `req.secret` deprecation message

1.5.0 / 2014-06-19
==================

  * Debug name is now "express-session"
  * Deprecate integration with `cookie-parser` middleware
  * Deprecate looking for secret in `req.secret`
  * Directly read cookies; `cookie-parser` no longer required
  * Directly set cookies; `res.cookie` no longer required
  * Generate session IDs with `uid-safe`, faster and even less collisions

1.4.0 / 2014-06-17
==================

  * Add `genid` option to generate custom session IDs
  * Add `saveUninitialized` option to control saving uninitialized sessions
  * Add `unset` option to control unsetting `req.session`
  * Generate session IDs with `rand-token` by default; reduce collisions
  * deps: buffer-crc32@0.2.3

1.3.1 / 2014-06-14
==================

  * Add description in package for npmjs.org listing

1.3.0 / 2014-06-14
==================

  * Integrate with express "trust proxy" by default
  * deps: debug@1.0.2

1.2.1 / 2014-05-27
==================

  * Fix `resave` such that `resave: true` works

1.2.0 / 2014-05-19
==================

  * Add `resave` option to control saving unmodified sessions

1.1.0 / 2014-05-12
==================

  * Add `name` option; replacement for `key` option
  * Use `setImmediate` in MemoryStore for node.js >= 0.10

1.0.4 / 2014-04-27
==================

  * deps: debug@0.8.1

1.0.3 / 2014-04-19
==================

  *  Use `res.cookie()` instead of `res.setHeader()`
  * deps: cookie@0.1.2

1.0.2 / 2014-02-23
==================

  * Add missing dependency to `package.json`

1.0.1 / 2014-02-15
==================

  * Add missing dependencies to `package.json`

1.0.0 / 2014-02-15
==================

  * Genesis from `connect`