text:
package com.wavefront.agent;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.RateLimiter;
import com.google.common.util.concurrent.RecyclableRateLimiter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import com.fasterxml.jackson.databind.JsonNode;
import com.squareup.tape.FileException;
import com.squareup.tape.FileObjectQueue;
import com.wavefront.agent.api.ForceQueueEnabledAgentAPI;
import com.wavefront.api.AgentAPI;
import com.wavefront.api.agent.AgentConfiguration;
import com.wavefront.api.agent.ShellOutputDTO;
import com.wavefront.ingester.StringLineIngester;
import com.wavefront.metrics.ExpectedAgentMetric;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.core.Meter;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;

import net.jpountz.lz4.LZ4BlockInputStream;
import net.jpountz.lz4.LZ4BlockOutputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;

import javax.annotation.Nullable;
import javax.ws.rs.core.Response;

import static com.google.common.collect.ImmutableList.of;

/**
 * A wrapper for any AgentAPI that queues up any result posting if the backend is not available.
 * Current data will always be submitted right away (thus prioritizing live data) while background
 * threads will submit backlogged data.
 *
 * @author Clement Pang (clement@wavefront.com)
 */
public class QueuedAgentService implements ForceQueueEnabledAgentAPI {

  private static final int MAX_SPLIT_BATCH_SIZE = 50000; // same value as default pushFlushMaxPoints
  private static final double MAX_RETRY_BACKOFF_BASE_SECONDS = 60.0;
  private static final Logger logger = Logger.getLogger(QueuedAgentService.class.getCanonicalName());

  private final Gson resubmissionTaskMarshaller;
  private final AgentAPI wrapped;
  private final List<ResubmissionTaskQueue> taskQueues;
  private static int splitBatchSize = MAX_SPLIT_BATCH_SIZE;
  private static double retryBackoffBaseSeconds = 2.0;
  private boolean lastKnownQueueSizeIsPositive = true;
  private final ExecutorService executorService;
  private MetricsRegistry metricsRegistry = new MetricsRegistry();
  private Meter resultPostingMeter = metricsRegistry.newMeter(QueuedAgentService.class, "post-result", "results",
      TimeUnit.MINUTES);
  private Counter permitsGranted = Metrics.newCounter(new MetricName("limiter", "", "permits-granted"));
  private Counter permitsDenied = Metrics.newCounter(new MetricName("limiter", "", "permits-denied"));
  private Counter permitsRetried = Metrics.newCounter(new MetricName("limiter", "", "permits-retried"));
  /**
   * Biases result sizes to the last 5 minutes heavily. This histogram does not see all result
   * sizes. The executor only ever processes one posting at any given time and drops the rest.
   * {@link #resultPostingMeter} records the actual rate (i.e. sees all posting calls).
   */
  private Histogram resultPostingSizes = metricsRegistry.newHistogram(QueuedAgentService.class, "result-size", true);
  /**
   * A single threaded bounded work queue to update result posting sizes.
   */
  private ExecutorService resultPostingSizerExecutorService = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS,
      new ArrayBlockingQueue<Runnable>(1));

  /**
   * Only size postings once every 5 seconds.
   */
  private final RateLimiter resultSizingRateLimier = RateLimiter.create(0.2);
  /**
   * @return bytes per minute for requests submissions. Null if no data is available yet.
   */
  @Nullable
  public Long getBytesPerMinute() {
    if (resultPostingMeter.fifteenMinuteRate() == 0 || resultPostingSizes.mean() == 0 || resultPostingSizes.count() <
        50) {
      return null;
    }
    return (long) (resultPostingSizes.mean() * resultPostingMeter.fifteenMinuteRate());
  }

  @Deprecated
  public QueuedAgentService(AgentAPI service, String bufferFile, final int retryThreads,
                            final ScheduledExecutorService executorService, boolean purge,
                            final UUID agentId, final boolean splitPushWhenRateLimited,
                            final String logLevel) throws IOException {
    this(service, bufferFile, retryThreads, executorService, purge,
        agentId, splitPushWhenRateLimited, (RecyclableRateLimiter) null);
  }

  public QueuedAgentService(AgentAPI service, String bufferFile, final int retryThreads,
                            final ScheduledExecutorService executorService, boolean purge,
                            final UUID agentId, final boolean splitPushWhenRateLimited,
                            final RecyclableRateLimiter pushRateLimiter)
      throws IOException {
    if (retryThreads <= 0) {
      logger.severe("You have no retry threads set up. Any points that get rejected will be lost.\n Change this by " +
          "setting retryThreads to a value > 0");
    }
    if (pushRateLimiter != null) {
      logger.info("Pushing to Wavefront with average PPS: " + String.valueOf(pushRateLimiter.getRate()));
    } else {
      logger.info("Pushing to Wavefront without user defined rate limit.");
    }
    resubmissionTaskMarshaller = new GsonBuilder().
        registerTypeHierarchyAdapter(ResubmissionTask.class, new ResubmissionTaskDeserializer()).create();
    this.wrapped = service;
    this.taskQueues = Lists.newArrayListWithExpectedSize(retryThreads);
    this.executorService = executorService;
    for (int i = 0; i < retryThreads; i++) {
      final int threadId = i;
      File buffer = new File(bufferFile + "." + i);
      if (purge) {
        if (buffer.delete()) {
          logger.warning("Retry buffer has been purged: " + buffer.getAbsolutePath());
        }
      }
      final ResubmissionTaskQueue taskQueue = new ResubmissionTaskQueue(
          new FileObjectQueue<>(buffer, new FileObjectQueue.Converter<ResubmissionTask>() {
            @Override
            public ResubmissionTask from(byte[] bytes) throws IOException {
              try {
                if (bytes.length > 2 && bytes[0] == (byte) 0x1f && bytes[1] == (byte) 0x8b) {
                  // gzip signature detected (backwards compatibility mode)
                  Reader reader = new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(bytes)));
                  return resubmissionTaskMarshaller.fromJson(reader, ResubmissionTask.class);
                }
                ObjectInputStream ois = new ObjectInputStream(new LZ4BlockInputStream(new ByteArrayInputStream(bytes)));
                return (ResubmissionTask) ois.readObject();
              } catch (Throwable t) {
                logger.warning("Failed to read a single retry submission from buffer, ignoring: " + t);
                return null;
              }
            }

            @Override
            public void toStream(ResubmissionTask o, OutputStream bytes) throws IOException {
              LZ4BlockOutputStream lz4BlockOutputStream = new LZ4BlockOutputStream(bytes);
              ObjectOutputStream oos = new ObjectOutputStream(lz4BlockOutputStream);
              oos.writeObject(o);
              oos.close();
              lz4BlockOutputStream.close();
            }
          }),
          task -> {
            task.service = wrapped;
            task.currentAgentId = agentId;
          }
      );

      Runnable taskRunnable = new Runnable() {
        private int backoffExponent = 1;

        @Override
        public void run() {
          int successes = 0;
          int failures = 0;
          boolean rateLimiting = false;
          try {
            logger.fine("[RETRY THREAD " + threadId + "] TASK STARTING");
            while (taskQueue.size() > 0 && taskQueue.size() > failures) {
              taskQueue.getLockObject().lock();
              try {
                ResubmissionTask task = taskQueue.peek();
                int taskSize = task == null ? 0 : task.size();
                if (pushRateLimiter != null && pushRateLimiter.getAvailablePermits() < pushRateLimiter.getRate()) {
                  // if there's less than 1 second worth of accumulated credits, don't process the backlog queue
                  rateLimiting = true;
                  permitsDenied.inc(taskSize);
                  break;
                }

                if (pushRateLimiter != null && taskSize > 0) {
                  pushRateLimiter.acquire(taskSize);
                  permitsGranted.inc(taskSize);
                }

                boolean removeTask = true;
                try {
                  if (task != null) {
                    task.execute(null);
                    successes++;
                  }
                } catch (Exception ex) {
                  if (pushRateLimiter != null) {
                    pushRateLimiter.recyclePermits(taskSize);
                    permitsRetried.inc(taskSize);
                  }
                  failures++;
                  //noinspection ThrowableResultOfMethodCallIgnored
                  if (Throwables.getRootCause(ex) instanceof QueuedPushTooLargeException) {
                    // this should split this task, remove it from the queue, and not try more tasks
                    logger.warning("[RETRY THREAD " + threadId + "] Wavefront server rejected push (413 response). " +
                        "Split data and attempt later: " + ex);
                    List<? extends ResubmissionTask> splitTasks = task.splitTask();
                    for (ResubmissionTask smallerTask : splitTasks) {
                      taskQueue.add(smallerTask);
                    }
                    break;
                  } else //noinspection ThrowableResultOfMethodCallIgnored
                    if (Throwables.getRootCause(ex) instanceof RejectedExecutionException) {
                      // this should either split and remove the original task or keep it at front
                      // it also should not try any more tasks
                      logger.warning("[RETRY THREAD " + threadId + "] Wavefront server rejected the submission. Will " +
                          "attempt later: " + ex);
                      if (splitPushWhenRateLimited) {
                        List<? extends ResubmissionTask> splitTasks = task.splitTask();
                        for (ResubmissionTask smallerTask : splitTasks) {
                          taskQueue.add(smallerTask);
                        }
                      } else {
                        removeTask = false;
                      }
                      break;
                    } else {
                      logger.log(Level.WARNING, "[RETRY THREAD " + threadId + "] cannot submit data to Wavefront servers. Will " +
                          "re-attempt later", ex);
                    }
                  // this can potentially cause a duplicate task to be injected (but since submission is mostly
                  // idempotent it's not really a big deal)
                  task.service = null;
                  task.currentAgentId = null;
                  taskQueue.add(task);
                  if (failures > 10) {
                    logger.warning("[RETRY THREAD " + threadId + "] saw too many submission errors. Will " +
                        "re-attempt later");
                    break;
                  }
                } finally {
                  if (removeTask) taskQueue.remove();
                }
              } finally {
                taskQueue.getLockObject().unlock();
              }
            }
          } catch (Throwable ex) {
            logger.log(Level.WARNING, "[RETRY THREAD " + threadId + "] unexpected exception", ex);
          } finally {
            if (rateLimiting) {
              logger.fine("[RETRY THREAD " + threadId + "] Successful Batches: " + successes +
                  ", Failed Batches: " + failures);
              logger.fine("[RETRY THREAD " + threadId + "] Rate limit reached, will re-attempt later");
              // if proxy rate limit exceeded, try again in 250..500ms (to introduce some degree of fairness)
              executorService.schedule(this, 250 + (int) (Math.random() * 250), TimeUnit.MILLISECONDS);
            } else {
              if (successes == 0 && failures != 0) {
                backoffExponent = Math.min(4, backoffExponent + 1); // caps at 2*base^4
              } else {
                backoffExponent = 1;
              }
              long next = (long) ((Math.random() + 1.0) *
                  Math.pow(retryBackoffBaseSeconds, backoffExponent));
              logger.fine("[RETRY THREAD " + threadId + "] Successful Batches: " + successes +
                  ", Failed Batches: " + failures);
              logger.fine("[RETRY THREAD " + threadId + "] RESCHEDULING in " + next);
              executorService.schedule(this, next, TimeUnit.SECONDS);
            }
          }
        }
      };

      executorService.schedule(taskRunnable, (long) (Math.random() * retryThreads), TimeUnit.SECONDS);
      taskQueues.add(taskQueue);
    }

    if (retryThreads > 0) {
      executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
          List<Integer> queueSizes = Lists.newArrayList(Lists.transform(taskQueues,
              new Function<ResubmissionTaskQueue, Integer>() {
                @Override
                public Integer apply(ResubmissionTaskQueue input) {
                  return input.size();
                }
              }
          ));
          if (Iterables.tryFind(queueSizes, new Predicate<Integer>() {
            @Override
            public boolean apply(Integer input) {
              return input > 0;
            }
          }).isPresent()) {
            lastKnownQueueSizeIsPositive = true;
            logger.info("current retry queue sizes: [" + Joiner.on("/").join(queueSizes) + "]");
          } else if (lastKnownQueueSizeIsPositive) {
            lastKnownQueueSizeIsPositive = false;
            logger.info("retry queue has been cleared");
          }
        }
      }, 0, 5, TimeUnit.SECONDS);
    }

    Metrics.newGauge(ExpectedAgentMetric.BUFFER_BYTES_PER_MINUTE.metricName, new Gauge<Long>() {
      @Override
      public Long value() {
        return getBytesPerMinute();
      }
    });

    Metrics.newGauge(ExpectedAgentMetric.CURRENT_QUEUE_SIZE.metricName, new Gauge<Long>() {
      @Override
      public Long value() {
        return getQueuedTasksCount();
      }
    });
  }

  public void shutdown() {
    executorService.shutdown();
  }

  public static void setRetryBackoffBaseSeconds(double newSecs) {
    retryBackoffBaseSeconds = Math.min(newSecs, MAX_RETRY_BACKOFF_BASE_SECONDS);
    retryBackoffBaseSeconds = Math.max(retryBackoffBaseSeconds, 1.0);
  }

  public static void setSplitBatchSize(int newSize) {
    splitBatchSize = Math.min(newSize, MAX_SPLIT_BATCH_SIZE);
    splitBatchSize = Math.max(splitBatchSize, 1);
  }

  public long getQueuedTasksCount() {
    long toReturn = 0;
    for (ResubmissionTaskQueue taskQueue : taskQueues) {
      toReturn += taskQueue.size();
    }
    return toReturn;
  }

  private ResubmissionTaskQueue getSmallestQueue() {
    int size = Integer.MAX_VALUE;
    ResubmissionTaskQueue toReturn = null;
    for (ResubmissionTaskQueue queue : taskQueues) {
      if (queue.size() == 0) {
        return queue;
      } else if (queue.size() < size) {
        toReturn = queue;
        size = queue.size();
      }
    }
    return toReturn;
  }

  private Runnable getPostingSizerTask(final ResubmissionTask task) {
    return () -> {
      try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        LZ4BlockOutputStream lz4OutputStream = new LZ4BlockOutputStream(outputStream);
        ObjectOutputStream oos = new ObjectOutputStream(lz4OutputStream);
        oos.writeObject(task);
        oos.close();
        lz4OutputStream.finish();
        lz4OutputStream.close();
        resultPostingSizes.update(outputStream.size());
      } catch (Throwable t) {
        // ignored. this is a stats task.
      }
    };
  }

  private void scheduleTaskForSizing(ResubmissionTask task) {
    try {
      if (resultSizingRateLimier.tryAcquire()) {
        resultPostingSizerExecutorService.submit(getPostingSizerTask(task));
      }
    } catch (RejectedExecutionException ex) {
      // ignored.
    } catch (RuntimeException ex) {
      logger.warning("cannot size a submission task for stats tracking: " + ex);
    }
  }

  @Override
  public AgentConfiguration getConfig(UUID agentId, String hostname, Long currentMillis,
                                      Long bytesLeftForbuffer, Long bytesPerMinuteForBuffer, Long currentQueueSize,
                                      String token, String version) {
    return wrapped.getConfig(agentId, hostname, currentMillis, bytesLeftForbuffer, bytesPerMinuteForBuffer,
        currentQueueSize, token, version);
  }

  @Override
  public AgentConfiguration checkin(UUID agentId, String hostname, String token, String version, Long currentMillis,
                                    Boolean localAgent, JsonNode agentMetrics, Boolean pushAgent, Boolean ephemeral) {
    return wrapped.checkin(agentId, hostname, token, version, currentMillis, localAgent, agentMetrics, pushAgent, ephemeral);
  }

  @Override
  public Response postWorkUnitResult(final UUID agentId, final UUID workUnitId, final UUID targetId,
                                     final ShellOutputDTO shellOutputDTO) {
    return this.postWorkUnitResult(agentId, workUnitId, targetId, shellOutputDTO, false);
  }

  @Override
  public Response postWorkUnitResult(UUID agentId, UUID workUnitId, UUID targetId, ShellOutputDTO shellOutputDTO,
                                     boolean forceToQueue) {
    PostWorkUnitResultTask task = new PostWorkUnitResultTask(agentId, workUnitId, targetId, shellOutputDTO);

    if (forceToQueue) {
      addTaskToSmallestQueue(task);
      return Response.status(Response.Status.NOT_ACCEPTABLE).build();
    } else {

      try {
        resultPostingMeter.mark();
        parsePostingResponse(wrapped.postWorkUnitResult(agentId, workUnitId, targetId, shellOutputDTO));
        scheduleTaskForSizing(task);
      } catch (RuntimeException ex) {
        logger.warning("Cannot post work unit result to Wavefront servers. Will enqueue and retry later: " + ex);
        handleTaskRetry(ex, task);
        return Response.status(Response.Status.NOT_ACCEPTABLE).build();
      }
      return Response.ok().build();
    }
  }

  @Override
  public Response postPushData(final UUID agentId, final UUID workUnitId, final Long currentMillis,
                               final String format, final String pushData) {
    return this.postPushData(agentId, workUnitId, currentMillis, format, pushData, false);
  }

  @Override
  public Response postPushData(UUID agentId, UUID workUnitId, Long currentMillis, String format, String pushData,
                               boolean forceToQueue) {
    PostPushDataResultTask task = new PostPushDataResultTask(agentId, workUnitId, currentMillis, format, pushData);

    if (forceToQueue) {
      // bypass the charade of posting to the wrapped agentAPI. Just go straight to the retry queue
      addTaskToSmallestQueue(task);
      return Response.status(Response.Status.NOT_ACCEPTABLE).build();
    } else {
      try {
        resultPostingMeter.mark();
        parsePostingResponse(wrapped.postPushData(agentId, workUnitId, currentMillis, format, pushData));
        scheduleTaskForSizing(task);
      } catch (RuntimeException ex) {
        List<PostPushDataResultTask> splitTasks = handleTaskRetry(ex, task);
        for (PostPushDataResultTask splitTask : splitTasks) {
          // we need to ensure that we use the latest agent id.
          postPushData(agentId, splitTask.getWorkUnitId(), splitTask.getCurrentMillis(),
              splitTask.getFormat(), splitTask.getPushData());
        }
        return Response.status(Response.Status.NOT_ACCEPTABLE).build();
      }
      return Response.ok().build();
    }
  }

  /**
   * @return list of tasks to immediately retry
   */
  private <T extends ResubmissionTask<T>> List<T> handleTaskRetry(RuntimeException failureException, T taskToRetry) {
    if (failureException instanceof QueuedPushTooLargeException) {
      List<T> resubmissionTasks = taskToRetry.splitTask();
      // there are split tasks, so go ahead and return them
      // otherwise, nothing got split, so this should just get queued up
      if (resubmissionTasks.size() > 1) {
        return resubmissionTasks;
      }
    }
    logger.warning("Cannot post push data result to Wavefront servers. " +
        "Will enqueue and retry later: " + failureException);
    addTaskToSmallestQueue(taskToRetry);
    return Collections.emptyList();
  }

  private void addTaskToSmallestQueue(ResubmissionTask taskToRetry) {
    ResubmissionTaskQueue queue = getSmallestQueue();
    if (queue != null) {
      queue.getLockObject().lock();
      try {
        queue.add(taskToRetry);
      } catch (FileException e) {
        logger.log(Level.SEVERE, "CRITICAL (Losing points!): WF-1: Submission queue is full.", e);
      } finally {
        queue.getLockObject().unlock();
      }
    } else {
      logger.severe("CRITICAL (Losing points!): WF-2: No retry queues found.");
    }
  }

  private static void parsePostingResponse(Response response) {
    try {
      if (response.getStatus() != Response.Status.OK.getStatusCode()) {
        if (response.getStatus() == Response.Status.NOT_ACCEPTABLE.getStatusCode()) {
          throw new RejectedExecutionException("Response not accepted by server: " + response.getStatus());
        } else if (response.getStatus() == Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode()) {
          throw new QueuedPushTooLargeException("Request too large: " + response.getStatus());
        } else if (response.getStatus() == 407 || response.getStatus() == 408) {
          boolean isWavefrontResponse = false;
          // check if the HTTP 407/408 response was actually received from Wavefront - if it's a JSON object
          // containing "code" key, with value equal to the HTTP response code, it's most likely from us.
          try {
            Map<String, Object> resp = new HashMap<>();
            resp = (Map<String, Object>) new Gson().fromJson(response.readEntity(String.class), resp.getClass());
            if (resp.containsKey("code") && resp.get("code") instanceof Number &&
                ((Number) resp.get("code")).intValue() == response.getStatus()) {
              isWavefrontResponse = true;
            }
          } catch (Exception ex) {
            // ignore
          }
          if (isWavefrontResponse) {
            throw new RejectedExecutionException("Response not accepted by server: " + response.getStatus() +
                " unclaimed agent - please verify that your token is valid and has Agent Management permission!");
          } else {
            throw new RuntimeException("HTTP " + response.getStatus() + ": Please verify your " +
                "network/HTTP proxy settings!");
          }
        } else {
          throw new RuntimeException("Server error: " + response.getStatus());
        }
      }
    } finally {
      response.close();
    }
  }

  @Override
  public void agentError(UUID agentId, String details) {
    wrapped.agentError(agentId, details);
  }

  @Override
  public void agentConfigProcessed(UUID agentId) {
    wrapped.agentConfigProcessed(agentId);
  }

  @Override
  public void hostConnectionFailed(UUID agentId, UUID hostId, String details) {
    wrapped.hostConnectionFailed(agentId, hostId, details);
  }

  @Override
  public void hostConnectionEstablished(UUID agentId, UUID hostId) {
    wrapped.hostConnectionEstablished(agentId, hostId);
  }

  @Override
  public void hostAuthenticated(UUID agentId, UUID hostId) {
    wrapped.hostAuthenticated(agentId, hostId);
  }

  public static class PostWorkUnitResultTask extends ResubmissionTask {

    @VisibleForTesting
    final UUID agentId;
    @VisibleForTesting
    final UUID workUnitId;
    @VisibleForTesting
    final UUID hostId;
    @VisibleForTesting
    final ShellOutputDTO shellOutputDTO;

    public PostWorkUnitResultTask(UUID agentId, UUID workUnitId, UUID hostId, ShellOutputDTO shellOutputDTO) {
      this.agentId = agentId;
      this.workUnitId = workUnitId;
      this.hostId = hostId;
      this.shellOutputDTO = shellOutputDTO;
    }

    @Override
    public void execute(Object callback) {
      parsePostingResponse(service.postWorkUnitResult(currentAgentId, workUnitId, hostId, shellOutputDTO));
    }

    @Override
    public List<PostWorkUnitResultTask> splitTask() {
      // doesn't make sense to split this, so just return a new task
      return of(new PostWorkUnitResultTask(agentId, workUnitId, hostId, shellOutputDTO));
    }

    @Override
    public int size() {
      return 1;
    }
  }

  public static class PostPushDataResultTask extends ResubmissionTask<PostPushDataResultTask> {

    private final UUID agentId;
    private final UUID workUnitId;
    private final Long currentMillis;
    private final String format;
    private final String pushData;

    public PostPushDataResultTask(UUID agentId, UUID workUnitId, Long currentMillis, String format, String pushData) {
      this.agentId = agentId;
      this.workUnitId = workUnitId;
      this.currentMillis = currentMillis;
      this.format = format;
      this.pushData = pushData;
    }

    @Override
    public void execute(Object callback) {
      Response response;
      try {
        response = service.postPushData(currentAgentId, workUnitId, currentMillis, format, pushData);
      } catch (Exception ex) {
        throw new RuntimeException("Server error: " + Throwables.getRootCause(ex));
      }
      parsePostingResponse(response);
    }

    @Override
    public List<PostPushDataResultTask> splitTask() {
      // pull the pushdata back apart to split and put back together
      List<PostPushDataResultTask> splitTasks = Lists.newArrayList();

      List<Integer> dataIndex = StringLineIngester.indexPushData(pushData);

      int numDatum = dataIndex.size() / 2;
      if (numDatum > 1) {
        // in this case, at least split the strings in 2 batches.  batch size must be less
        // than splitBatchSize
        int stride = Math.min(splitBatchSize, (int) Math.ceil((float) numDatum / 2.0));
        int endingIndex = 0;
        for (int startingIndex = 0; endingIndex < numDatum - 1; startingIndex += stride) {
          endingIndex = Math.min(numDatum, startingIndex + stride) - 1;
          splitTasks.add(new PostPushDataResultTask(agentId, workUnitId, currentMillis, format,
              pushData.substring(dataIndex.get(startingIndex * 2), dataIndex.get(endingIndex * 2 + 1))));
        }
      } else {
        // 1 or 0
        splitTasks.add(new PostPushDataResultTask(agentId, workUnitId, currentMillis, format, pushData));
      }

      return splitTasks;
    }

    @Override
    public int size() {
      return StringLineIngester.pushDataSize(pushData);
    }

    @VisibleForTesting
    public UUID getAgentId() {
      return agentId;
    }

    @VisibleForTesting
    public UUID getWorkUnitId() {
      return workUnitId;
    }

    @VisibleForTesting
    public Long getCurrentMillis() {
      return currentMillis;
    }

    @VisibleForTesting
    public String getFormat() {
      return format;
    }

    @VisibleForTesting
    public String getPushData() {
      return pushData;
    }
  }
}


text:
package imports

import (
	. "reflect"
	"net/http/cookiejar"
)

// reflection: allow interpreted code to import "net/http/cookiejar"
func init() {
	Packages["net/http/cookiejar"] = Package{
	Binds: map[string]Value{
		"New":	ValueOf(cookiejar.New),
	}, Types: map[string]Type{
		"Jar":	TypeOf((*cookiejar.Jar)(nil)).Elem(),
		"Options":	TypeOf((*cookiejar.Options)(nil)).Elem(),
		"PublicSuffixList":	TypeOf((*cookiejar.PublicSuffixList)(nil)).Elem(),
	}, Proxies: map[string]Type{
		"PublicSuffixList":	TypeOf((*P_net_http_cookiejar_PublicSuffixList)(nil)).Elem(),
	},
	}
}

// --------------- proxy for net/http/cookiejar.PublicSuffixList ---------------
type P_net_http_cookiejar_PublicSuffixList struct {
	Object	interface{}
	PublicSuffix_	func(_proxy_obj_ interface{}, domain string) string
	String_	func(interface{}) string
}
func (P *P_net_http_cookiejar_PublicSuffixList) PublicSuffix(domain string) string {
	return P.PublicSuffix_(P.Object, domain)
}
func (P *P_net_http_cookiejar_PublicSuffixList) String() string {
	return P.String_(P.Object)
}

redpajama_set_name: RedPajamaGithub


text:
class SkColorFilter;
class SkImageFilter;
class SkMatrix44;
class SkPicture;
struct SkRect;
class SkRRect;

namespace cc {
class FilterOperations;
}

namespace blink {

// An ordered list of items representing content to be rendered (stored in
// 'drawing' items) and operations to be performed when rendering this content
// (stored in 'clip', 'transform', 'filter', etc...). For more details see:
// http://dev.chromium.org/blink/slimming-paint.
class WebDisplayItemList {
public:
    virtual ~WebDisplayItemList() { }

    virtual void appendDrawingItem(const WebRect& visualRect, sk_sp<const SkPicture>) { }

    virtual void appendClipItem(const WebRect& clipRect, const WebVector<SkRRect>& roundedClipRects) { }
    virtual void appendEndClipItem() { }
    virtual void appendClipPathItem(const SkPath&, SkRegion::Op, bool antialias) { }
    virtual void appendEndClipPathItem() { }
    virtual void appendFloatClipItem(const WebFloatRect& clipRect) { }
    virtual void appendEndFloatClipItem() { }
    virtual void appendTransformItem(const SkMatrix44&) { }
    virtual void appendEndTransformItem() { }
    virtual void appendCompositingItem(float opacity,
        SkXfermode::Mode, SkRect* bounds, SkColorFilter*) { }
    virtual void appendEndCompositingItem() { }

    // TODO(loyso): This should use CompositorFilterOperation. crbug.com/584551
    virtual void appendFilterItem(const cc::FilterOperations&, const WebFloatRect& bounds) { }
    virtual void appendEndFilterItem() { }

    // Scroll containers are identified by an opaque pointer.
    using ScrollContainerId = const void*;
    virtual void appendScrollItem(const WebSize& scrollOffset, ScrollContainerId) { }
    virtual void appendEndScrollItem() { }

    virtual void setIsSuitableForGpuRasterization(bool isSuitable) { }
};

} // namespace blink

#endif // WebDisplayItemList_h


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <sponsors>
      <item>
        <party>D</party>
        <firstName>EDWARD</firstName>
        <bioguideId>M000133</bioguideId>
        <lastName>MARKEY</lastName>
        <byRequestType />
        <fullName>Sen. Markey, Edward J. [D-MA]</fullName>
        <middleName>J.</middleName>
        <state>MA</state>
        <identifiers>
          <gpoId>7972</gpoId>
          <lisID>735</lisID>
          <bioguideId>M000133</bioguideId>
        </identifiers>
      </item>
    </sponsors>
    <summaries>
      <billSummaries />
    </summaries>
    <amendments />
    <title>Safer Prescribing of Controlled Substances Act</title>
    <originChamber>Senate</originChamber>
    <cboCostEstimates />
    <titles>
      <item>
        <parentTitleType />
        <titleType>Short Titles as Introduced</titleType>
        <title>Safer Prescribing of Controlled Substances Act</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>Official Title as Introduced</titleType>
        <title>A bill to require certain practitioners authorized to prescribe controlled substances to complete continuing education.</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>Display Title</titleType>
        <title>Safer Prescribing of Controlled Substances Act</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <title>Safer Prescribing of Controlled Substances Act</title>
        <chamberCode />
        <chamberName />
      </item>
    </titles>
    <latestAction>
      <text>Read twice and referred to the Committee on Health, Education, Labor, and Pensions.</text>
      <actionDate>2017-07-13</actionDate>
      <links />
    </latestAction>
    <billType>S</billType>
    <congress>115</congress>
    <billNumber>1554</billNumber>
    <committeeReports />
    <introducedDate>2017-07-13</introducedDate>
    <updateDate>2017-09-11T03:01:49Z</updateDate>
    <version>1.0.0</version>
    <notes />
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Drug therapy</name>
          </item>
          <item>
            <name>Drug trafficking and controlled substances</name>
          </item>
          <item>
            <name>Drug, alcohol, tobacco use</name>
          </item>
          <item>
            <name>Government information and archives</name>
          </item>
          <item>
            <name>Health information and medical records</name>
          </item>
          <item>
            <name>Health personnel</name>
          </item>
          <item>
            <name>Medical education</name>
          </item>
          <item>
            <name>Medical research</name>
          </item>
          <item>
            <name>Medical tests and diagnostic methods</name>
          </item>
          <item>
            <name>Prescription drugs</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Crime and Law Enforcement</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <recordedVotes />
    <laws />
    <policyArea>
      <name>Crime and Law Enforcement</name>
    </policyArea>
    <actions>
      <item>
        <actionDate>2017-07-13</actionDate>
        <committee>
          <name>Health, Education, Labor, and Pensions Committee</name>
          <systemCode>sshr00</systemCode>
        </committee>
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Read twice and referred to the Committee on Health, Education, Labor, and Pensions.</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <links />
        <text>Introduced in Senate</text>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <committee />
        <actionDate>2017-07-13</actionDate>
        <type>IntroReferral</type>
        <actionCode>10000</actionCode>
      </item>
      <actionTypeCounts>
        <referredToCommittee>1</referredToCommittee>
        <introducedInSenate>1</introducedInSenate>
      </actionTypeCounts>
      <actionByCounts>
        <senate>2</senate>
      </actionByCounts>
    </actions>
    <committees>
      <billCommittees>
        <item>
          <name>Health, Education, Labor, and Pensions Committee</name>
          <chamber>Senate</chamber>
          <subcommittees />
          <systemCode>sshr00</systemCode>
          <activities>
            <item>
              <date>2017-07-13T18:27:11Z</date>
              <name>Referred to</name>
            </item>
          </activities>
          <type>Standing</type>
        </item>
      </billCommittees>
    </committees>
    <createDate>2017-07-14T00:41:33Z</createDate>
    <relatedBills />
    <calendarNumbers />
    <cosponsors>
      <item>
        <state>CT</state>
        <fullName>Sen. Blumenthal, Richard [D-CT]</fullName>
        <firstName>Richard</firstName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>B001277</bioguideId>
        <lastName>Blumenthal</lastName>
        <middleName />
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <sponsorshipDate>2017-07-13</sponsorshipDate>
        <identifiers>
          <gpoId>8332</gpoId>
          <lisID>2076</lisID>
          <bioguideId>B001277</bioguideId>
        </identifiers>
      </item>
      <item>
        <state>CA</state>
        <fullName>Sen. Feinstein, Dianne [D-CA]</fullName>
        <firstName>DIANNE</firstName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>F000062</bioguideId>
        <lastName>FEINSTEIN</lastName>
        <middleName />
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <sponsorshipDate>2017-07-13</sponsorshipDate>
        <identifiers>
          <bioguideId>F000062</bioguideId>
          <gpoId>8338</gpoId>
          <lisID>1332</lisID>
        </identifiers>
      </item>
      <item>
        <state>WV</state>
        <fullName>Sen. Manchin, Joe, III [D-WV]</fullName>
        <firstName>Joe</firstName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>M001183</bioguideId>
        <lastName>Manchin</lastName>
        <middleName />
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <sponsorshipDate>2017-07-13</sponsorshipDate>
        <identifiers>
          <bioguideId>M001183</bioguideId>
          <lisID>1983</lisID>
          <gpoId>8256</gpoId>
        </identifiers>
      </item>
      <item>
        <state>MA</state>
        <fullName>Sen. Warren, Elizabeth [D-MA]</fullName>
        <firstName>Elizabeth</firstName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>W000817</bioguideId>
        <lastName>Warren</lastName>
        <middleName>A.</middleName>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <sponsorshipDate>2017-07-13</sponsorshipDate>
        <identifiers>
          <gpoId />
          <lisID>2182</lisID>
          <bioguideId>W000817</bioguideId>
        </identifiers>
      </item>
    </cosponsors>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
import * as React from 'react';
import { SxProps } from '@material-ui/system';
import { OverridableStringUnion } from '@material-ui/types';
import { InternalStandardProps as StandardProps, Theme } from '..';
import { RatingClasses } from './ratingClasses';

export interface IconContainerProps extends React.HTMLAttributes<HTMLSpanElement> {
  value: number;
}

export interface RatingPropsSizeOverrides {}

export interface RatingProps
  extends StandardProps<React.HTMLAttributes<HTMLSpanElement>, 'children' | 'onChange'> {
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<RatingClasses>;
  /**
   * The default value. Use when the component is not controlled.
   * @default null
   */
  defaultValue?: number;
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled?: boolean;
  /**
   * The icon to display when empty.
   * @default <StarBorder fontSize="inherit" />
   */
  emptyIcon?: React.ReactNode;
  /**
   * The label read when the rating input is empty.
   * @default 'Empty'
   */
  emptyLabelText?: React.ReactNode;
  /**
   * Accepts a function which returns a string value that provides a user-friendly name for the current value of the rating.
   * This is important for screen reader users.
   *
   * For localization purposes, you can use the provided [translations](/guides/localization/).
   * @param {number} value The rating label's value to format.
   * @returns {string}
   * @default function defaultLabelText(value) {
   *   return `${value} Star${value !== 1 ? 's' : ''}`;
   * }
   */
  getLabelText?: (value: number) => string;
  /**
   * If `true`, only the selected icon will be highlighted.
   * @default false
   */
  highlightSelectedOnly?: boolean;
  /**
   * The icon to display.
   * @default <Star fontSize="inherit" />
   */
  icon?: React.ReactNode;
  /**
   * The component containing the icon.
   * @default function IconContainer(props) {
   *   const { value, ...other } = props;
   *   return <span {...other} />;
   * }
   */
  IconContainerComponent?: React.ElementType<IconContainerProps>;
  /**
   * Maximum rating.
   * @default 5
   */
  max?: number;
  /**
   * The name attribute of the radio `input` elements.
   * This input `name` should be unique within the page.
   * Being unique within a form is insufficient since the `name` is used to generated IDs.
   */
  name?: string;
  /**
   * Callback fired when the value changes.
   * @param {object} event The event source of the callback.
   * @param {number} value The new value.
   */
  onChange?: (event: React.SyntheticEvent, value: number | null) => void;
  /**
   * Callback function that is fired when the hover state changes.
   * @param {object} event The event source of the callback.
   * @param {number} value The new value.
   */
  onChangeActive?: (event: React.SyntheticEvent, value: number) => void;
  /**
   * The minimum increment value change allowed.
   * @default 1
   */
  precision?: number;
  /**
   * Removes all hover effects and pointer events.
   * @default false
   */
  readOnly?: boolean;
  /**
   * The size of the component.
   * @default 'medium'
   */
  size?: OverridableStringUnion<'small' | 'medium' | 'large', RatingPropsSizeOverrides>;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme>;
  /**
   * The rating value.
   */
  value?: number | null;
}

/**
 *
 * Demos:
 *
 * - [Rating](https://material-ui.com/components/rating/)
 *
 * API:
 *
 * - [Rating API](https://material-ui.com/api/rating/)
 */
export default function Rating(props: RatingProps): JSX.Element;


text:
/*  tm_set.h
 *
 *  'pv' versions of functions are meant to be called only when the set
 *  has been privatized.
 */

#ifndef TM_SET_H
#define TM_SET_H

template<typename T>
class tm_set {
  public:
    virtual void tx_insert(const T item) = 0;
    virtual void tx_remove(const T item) = 0;
    virtual bool tx_lookup(const T item) = 0;

    virtual void pv_insert(const T item) = 0;
    virtual void pv_remove(const T item) = 0;
    virtual bool pv_lookup(const T item) = 0;

    virtual void pv_apply_to_all(void (*f)(T item)) = 0;

    virtual ~tm_set() { }
};

#endif


text:
package com.ecas.web.admin.validator;

import com.ecas.domain.User;
import com.ecas.service.ServiceRegistry;
import com.ecas.web.admin.bean.BaseBean;
import com.sun.faces.component.visit.FullVisitContext;
import org.primefaces.util.MessageFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.component.visit.VisitResult;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 * Keep common API for validator
 */
public abstract class BaseValidator {
    @Autowired
    private ServiceRegistry serviceRegistry;

    protected String getStringMessage(String messageId, Object... objs) {
        return MessageFactory.getFormattedText(FacesContext.getCurrentInstance().getApplication().getDefaultLocale(), FacesContext
                .getCurrentInstance().getApplication().getResourceBundle(FacesContext.getCurrentInstance(), "msg").getString(messageId), objs);
    }

    public User getCurrentUser() {
        Object obj = getSession().getAttribute(BaseBean.USER_CONTEXT_SESSION_KEY);
        if (obj != null) {
            return (User) obj;
        }
        return null;
    }

    protected UIComponent findCompnent(final String id) {

        FacesContext context = FacesContext.getCurrentInstance();
        UIViewRoot root = context.getViewRoot();
        final UIComponent[] found = new UIComponent[1];

        root.visitTree(new FullVisitContext(context), new VisitCallback() {
            @Override
            public VisitResult visit(VisitContext context, UIComponent component) {
                if (component.getId().equals(id)) {
                    found[0] = component;
                    return VisitResult.COMPLETE;
                }
                return VisitResult.ACCEPT;
            }
        });
        return found[0];
    }

    protected HttpSession getSession() {
        return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    }

    public ServiceRegistry getServiceRegistry() {
        return serviceRegistry;
    }

    public void setServiceRegistry(ServiceRegistry serviceRegistry) {
        this.serviceRegistry = serviceRegistry;
    }
}


text:
using DragonSpark.Application;
using System.Windows.Input;

namespace DragonSpark.Testing.Framework.Application
{
	public class Application : ApplicationBase<AutoData>, IApplication
	{
		public Application() {}
		public Application( params ICommand[] commands ) : base( commands ) {}
	}
}


text:
<?php

/**
 * sfUploadManagerAddToBlackListTask
 * Add an IP to blacklist.
 *
 * @package    symfony
 * @subpackage sfUploadManagerPlugin
 * @author     François Béliveau  <francois.beliveau@my-labz.com>
 */
class sfUploadManagerAddToBlackListTask extends sfBaseTask
{
  /**
   * Configures the task
   *
   * @access protected
   */
  protected function configure()
  {
    $this->namespace            = 'upload-manager';
    $this->name                 = 'add-to-blacklist';
    $this->briefDescription     = '"sfUploadManagerPlugin" add an IP to blacklist';
    $this->detailedDescription  = <<<EOF
"sfUploadManagerPlugin" add an IP to blacklist

Examples:
  [./symfony upload-manager:add-to-blacklist frontend xxx.xxx.x.xx --env=cli]
EOF;

    $this->addArguments(array(
      new sfCommandArgument('application', sfCommandOption::PARAMETER_REQUIRED, "The application's name"),
      new sfCommandArgument('ip', sfCommandOption::PARAMETER_REQUIRED, "The IP"),
    ));

    $this->addOptions(array(
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_OPTIONAL, 'The environment', 'cli'),
    ));
  }

  /**
   * Executes the task
   *
   * @param array $arguments The CLI arguments array
   * @param array $options   The CLI options array
   *
   * @access protected
   */
  protected function execute($arguments = array(), $options = array())
  {
    $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'], $options['env'], true);
    sfContext::createInstance($configuration);

    $uploadManagerSecurity = sfUploadManagerHelper::findUploadManagerSecurityOrCreate($arguments['ip']);
    $uploadManagerSecurity->setBlacklisted(true);
    $uploadManagerSecurity->save();

    $this->logSection('result', 'added to blacklist');
  }
}


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * PHP Version 4
 *
 * Copyright (c) 2002-2005, Sebastian Bergmann <sb@sebastian-bergmann.de>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *   * Neither the name of Sebastian Bergmann nor the names of his
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @category   Testing
 * @package    PHPUnit
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    CVS: $Id: TestFailure.php,v 1.13 2005/11/10 09:47:14 sebastian Exp $
 * @link       http://pear.php.net/package/PHPUnit
 * @since      File available since Release 1.0.0
 */

/**
 * A TestFailure collects a failed test together with the caught exception.
 *
 * @category   Testing
 * @package    PHPUnit
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: 1.3.2
 * @link       http://pear.php.net/package/PHPUnit
 * @since      Class available since Release 1.0.0
 */
class PHPUnit_TestFailure {
    /**
     * @var    object
     * @access private
     */
    var $_failedTest;

    /**
     * @var    string
     * @access private
     */
    var $_thrownException;

    /**
     * Constructs a TestFailure with the given test and exception.
     *
     * @param  object
     * @param  string
     * @access public
     */
    function PHPUnit_TestFailure(&$failedTest, &$thrownException) {
        $this->_failedTest      = &$failedTest;
        $this->_thrownException = &$thrownException;
    }

    /**
     * Gets the failed test.
     *
     * @return object
     * @access public
     */
    function &failedTest() {
        return $this->_failedTest;
    }

    /**
     * Gets the thrown exception.
     *
     * @return object
     * @access public
     */
    function &thrownException() {
        return $this->_thrownException;
    }

    /**
     * Returns a short description of the failure.
     *
     * @return string
     * @access public
     */
    function toString() {
        return sprintf(
          "TestCase %s->%s() failed: %s\n",

          get_class($this->_failedTest),
          $this->_failedTest->getName(),
          $this->_thrownException
        );
    }
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */
?>


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

// It is recommended to store a reference to the host view controller here (this will also be
// our window's root view controller)
@property (strong, nonatomic) ICHostViewController *hostViewController;

@end


text:
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Nag Boranna (nagaraja_boranna@hp.com)
//
// Modified By:  Amit K Arora, IBM (amita@in.ibm.com)
//               Vijay Eli, IBM (vijayeli@in.ibm.com), bug#3608.
//
//%/////////////////////////////////////////////////////////////////////////////

#include <cctype>
#include <fstream>
#include <Pegasus/Common/FileSystem.h>
#include <Pegasus/Common/HashTable.h>
#include <Pegasus/Common/Tracer.h>

#include "ConfigExceptions.h"
#include "ConfigFile.h"
#if  defined(PEGASUS_OS_OS400)
#include "OS400ConvertChar.h"
#endif

PEGASUS_USING_STD;

PEGASUS_NAMESPACE_BEGIN

////////////////////////////////////////////////////////////////////////////////
//
//  ConfigFile Class
//
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// ConfigTable
////////////////////////////////////////////////////////////////////////////////

typedef HashTable<String, String, EqualFunc<String>, HashFunc<String> > Table;

struct ConfigTable
{
    Table table;
};

/*
    Config file header information
*/
static const char* ConfigHeader [] = {
    "########################################################################",
    "##                                                                    ##",
    "##                  CIM Server configuration file                     ##",
    "##                                                                    ##",
    "########################################################################",
    " ",
    "########################################################################",
    "#                                                                      #",
    "# This is the configuration file for the CIMOM. The configuration      #",
    "# properties in this file are loaded in to CIMOM at startup.           #",
    "# CIMOM updates this file with the changes in the configurations.      #",
    "#                                                                      #",
    "# It is recommended that user do not edit this file, instead use       #",
    "# CIMConfigCommand to make any changes to the CIMOM configurations.    #",
    "#                                                                      #",
    "########################################################################",
    " "
};

static const int HEADER_SIZE = sizeof(ConfigHeader) / sizeof(ConfigHeader[0]);

/**
    Constructor.
*/
ConfigFile::ConfigFile (const String& fileName)
{
    _configFile = fileName;

    _configBackupFile = fileName + ".bak";

}

/**
    Destructor.
*/
ConfigFile::~ConfigFile ()
{

}

/**
    Get the name of the configuration file.
*/
String ConfigFile::getFileName () const
{
    return ( _configFile );
}

/**
    Load the properties from the config file.
*/
void ConfigFile::load (ConfigTable* confTable)
{
    String line;

    //
    // Delete the backup configuration file
    //
    if (FileSystem::exists(_configBackupFile))
    {
        FileSystem::removeFile(_configBackupFile);
    }

    //
    // Open the config file
    //
#if defined(PEGASUS_OS_OS400)
    ifstream ifs(_configFile.getCString(), PEGASUS_STD(_CCSID_T(1208)));
#else
    ifstream ifs(_configFile.getCString());
#endif
    if (!ifs)
    {
        return;
    }

    //
    // Read each line of the file
    //
    for (Uint32 lineNumber = 1; GetLine(ifs, line); lineNumber++)
    {
        // Get the property name and value

        //
        // Skip leading whitespace
        //
        const Char16* p = line.getChar16Data();

        while (*p && isspace(*p))
        {
            p++;
        }

        if (!*p)
        {
            continue;
        }

        //
        // Skip comment lines
        //
        if (*p == '#')
        {
            continue;
        }

        //
        // Get the property name
        //
        String name = String::EMPTY;

        if (!(isalpha(*p) || *p == '_'))
        {
            ifs.close();
            throw ConfigFileSyntaxError(_configFile, lineNumber);
        }

        name.append(*p++);

        while (isalnum(*p) || *p == '_')
        {
            name.append(*p++);
        }

        //
        // Skip whitespace after property name
        //
        while (*p && isspace(*p))
        {
            p++;
        }

        //
        // Expect an equal sign
        //
        if (*p != '=')
        {
            ifs.close();
            throw ConfigFileSyntaxError(_configFile, lineNumber);
        }

        p++;

        //
        // Skip whitespace after equal sign
        //
        while (*p && isspace(*p))
        {
            p++;
        }

        //
        // Get the value
        //
        String value = String::EMPTY;

        while (*p)
        {
            value.append(*p++);
        }

        //
        // Store the property name and value in the table
        //
        if (!confTable->table.insert(name, value))
        {
            //
            // Duplicate property, ignore the new property value.
            // FUTURE: Log this message in a log file.
            //
            PEG_TRACE_STRING(TRC_CONFIG, Tracer::LEVEL3,
                "Duplicate property '" + name + "', value '" + value + "' is ignored.");
        }
    }

    ifs.close();
}

/**
    Save the properties to the config file.
*/
void ConfigFile::save (ConfigTable* confTable)
{
    //
    // Delete the backup configuration file
    //
    if (FileSystem::exists(_configBackupFile))
    {
        FileSystem::removeFile(_configBackupFile);
    }

    //
    // Rename the configuration file as a backup file
    //
    if (FileSystem::exists(_configFile))
    {
        if (!FileSystem::renameFile(_configFile, _configBackupFile))
        {
            throw CannotRenameFile(_configFile);
        }
    }

    //
    // Open the config file for writing
    //
#if defined(PEGASUS_OS_OS400)
    ofstream ofs(_configFile.getCString(), PEGASUS_STD(_CCSID_T(1208)));
#else
    ofstream ofs(_configFile.getCString());
#endif
    ofs.clear();

#if !defined(PEGASUS_OS_TYPE_WINDOWS)
    //
    // Set permissions on the config file to 0644
    //
    if ( !FileSystem::changeFilePermissions(_configFile,
        (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) )    // set 0644
    {
        throw CannotOpenFile(_configFile);
    }
#endif

    //
    // Write config file header information
    //
    for (int index = 0; index < HEADER_SIZE; index++)
    {
        ofs << ConfigHeader[index] << endl;
    }

    ofs << endl;

    //
    // Save config properties and values to the file
    //
    for (Table::Iterator i = confTable->table.start(); i; i++)
    {
        ofs << i.key() << "=" << i.value() << endl;
    }

    ofs.close();
}

/**
    Replace the properties in the config file with the properties from
    the given file.
*/
void ConfigFile::replace (const String& fileName)
{
    String line;

    //
    // Open the given config file for reading
    //
#if defined(PEGASUS_OS_OS400)
    ifstream ifs(fileName.getCString(), PEGASUS_STD(_CCSID_T(1208)));
#else
    ifstream ifs(fileName.getCString());
#endif

    //
    // Delete the backup configuration file
    //
    if (FileSystem::exists(_configBackupFile))
    {
        FileSystem::removeFile(_configBackupFile);
    }

    //
    // Rename the existing config file as a backup file
    //
    if (FileSystem::exists(_configFile))
    {
        if (!FileSystem::renameFile(_configFile, _configBackupFile))
        {
            ifs.close();
            throw CannotRenameFile(_configFile);
        }
    }

    //
    // Open the existing config file for writing
    //
#if defined(PEGASUS_OS_OS400)
    ofstream ofs(_configFile.getCString(), PEGASUS_STD(_CCSID_T(1208)));
#else
    ofstream ofs(_configFile.getCString());
#endif
    ofs.clear();

#if !defined(PEGASUS_OS_TYPE_WINDOWS)
    //
    // Set permissions on the config file to 0644
    //
    if ( !FileSystem::changeFilePermissions(_configFile,
        (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) )    // set 0644
    {
        throw CannotOpenFile(_configFile);
    }
#endif

    //
    // Read each line of the new file and write to the config file.
    //
    for (Uint32 lineNumber = 1; GetLine(ifs, line); lineNumber++)
    {
        ofs << line << endl;
    }

    //
    // Close the file handles
    //
    ifs.close();
    ofs.close();
}

PEGASUS_NAMESPACE_END


text:
import * as React from 'react'

import { SemanticShorthandItem } from '../../generic'
import { StrictPortalProps } from '../../addons/Portal'
import ModalActions, { ModalActionsProps } from './ModalActions'
import ModalContent, { ModalContentProps } from './ModalContent'
import ModalDescription from './ModalDescription'
import ModalDimmer, { ModalDimmerProps } from './ModalDimmer'
import ModalHeader, { ModalHeaderProps } from './ModalHeader'

export interface ModalProps extends StrictModalProps {
  [key: string]: any
}

export interface StrictModalProps extends StrictPortalProps {
  /** An element type to render as (string or function). */
  as?: any

  /** Shorthand for Modal.Actions. Typically an array of button shorthand. */
  actions?: SemanticShorthandItem<ModalActionsProps>

  /** A Modal can reduce its complexity */
  basic?: boolean

  /** A modal can be vertically centered in the viewport. */
  centered?: boolean

  /** Primary content. */
  children?: React.ReactNode

  /** Additional classes. */
  className?: string

  /** Icon. */
  closeIcon?: any

  /** Whether or not the Modal should close when the dimmer is clicked. */
  closeOnDimmerClick?: boolean

  /** Whether or not the Modal should close when the document is clicked. */
  closeOnDocumentClick?: boolean

  /** A Modal can be passed content via shorthand. */
  content?: SemanticShorthandItem<ModalContentProps>

  /** Initial value of open. */
  defaultOpen?: boolean

  /** A modal can appear in a dimmer. */
  dimmer?: true | 'blurring' | 'inverted' | SemanticShorthandItem<ModalDimmerProps>

  /** Event pool namespace that is used to handle component events */
  eventPool?: string

  /** A Modal can be passed header via shorthand. */
  header?: SemanticShorthandItem<ModalHeaderProps>

  /** The node where the modal should mount. Defaults to document.body. */
  mountNode?: any

  /**
   * Action onClick handler when using shorthand `actions`.
   *
   * @param {SyntheticEvent} event - React's original SyntheticEvent.
   * @param {object} data - All props.
   */
  onActionClick?: (event: React.MouseEvent<HTMLElement>, data: ModalProps) => void

  /**
   * Called when a close event happens.
   *
   * @param {SyntheticEvent} event - React's original SyntheticEvent.
   * @param {object} data - All props.
   */
  onClose?: (event: React.MouseEvent<HTMLElement>, data: ModalProps) => void

  /**
   * Called when the portal is mounted on the DOM.
   *
   * @param {null}
   * @param {object} data - All props.
   */
  onMount?: (nothing: null, data: ModalProps) => void

  /**
   * Called when an open event happens.
   *
   * @param {SyntheticEvent} event - React's original SyntheticEvent.
   * @param {object} data - All props.
   */
  onOpen?: (event: React.MouseEvent<HTMLElement>, data: ModalProps) => void

  /**
   * Called when the portal is unmounted from the DOM.
   *
   * @param {null}
   * @param {object} data - All props.
   */
  onUnmount?: (nothing: null, data: ModalProps) => void

  /** Controls whether or not the Modal is displayed. */
  open?: boolean

  /** A modal can vary in size. */
  size?: 'mini' | 'tiny' | 'small' | 'large' | 'fullscreen'

  /** Custom styles. */
  style?: React.CSSProperties

  /** Element to be rendered in-place where the portal is defined. */
  trigger?: React.ReactNode
}

interface ModalComponent extends React.ComponentClass<ModalProps> {
  Actions: typeof ModalActions
  Content: typeof ModalContent
  Description: typeof ModalDescription
  Dimmer: typeof ModalDimmer
  Header: typeof ModalHeader
}

declare const Modal: ModalComponent

export default Modal


text:
namespace chromeos {

static CrosSettings*  g_cros_settings = NULL;

// static
void CrosSettings::Initialize() {
  CHECK(!g_cros_settings);
  g_cros_settings = new CrosSettings();
}

// static
bool CrosSettings::IsInitialized() {
  return g_cros_settings;
}

// static
void CrosSettings::Shutdown() {
  DCHECK(g_cros_settings);
  delete g_cros_settings;
  g_cros_settings = NULL;
}

// static
CrosSettings* CrosSettings::Get() {
  CHECK(g_cros_settings);
  return g_cros_settings;
}

bool CrosSettings::IsCrosSettings(const std::string& path) {
  return StartsWithASCII(path, kCrosSettingsPrefix, true);
}

void CrosSettings::Set(const std::string& path, const base::Value& in_value) {
  DCHECK(CalledOnValidThread());
  CrosSettingsProvider* provider;
  provider = GetProvider(path);
  if (provider)
    provider->Set(path, in_value);
}

const base::Value* CrosSettings::GetPref(const std::string& path) const {
  DCHECK(CalledOnValidThread());
  CrosSettingsProvider* provider = GetProvider(path);
  if (provider)
    return provider->Get(path);
  NOTREACHED() << path << " preference was not found in the signed settings.";
  return NULL;
}

CrosSettingsProvider::TrustedStatus CrosSettings::PrepareTrustedValues(
    const base::Closure& callback) const {
  DCHECK(CalledOnValidThread());
  for (size_t i = 0; i < providers_.size(); ++i) {
    CrosSettingsProvider::TrustedStatus status =
        providers_[i]->PrepareTrustedValues(callback);
    if (status != CrosSettingsProvider::TRUSTED)
      return status;
  }
  return CrosSettingsProvider::TRUSTED;
}

void CrosSettings::SetBoolean(const std::string& path, bool in_value) {
  DCHECK(CalledOnValidThread());
  base::FundamentalValue value(in_value);
  Set(path, value);
}

void CrosSettings::SetInteger(const std::string& path, int in_value) {
  DCHECK(CalledOnValidThread());
  base::FundamentalValue value(in_value);
  Set(path, value);
}

void CrosSettings::SetDouble(const std::string& path, double in_value) {
  DCHECK(CalledOnValidThread());
  base::FundamentalValue value(in_value);
  Set(path, value);
}

void CrosSettings::SetString(const std::string& path,
                             const std::string& in_value) {
  DCHECK(CalledOnValidThread());
  base::StringValue value(in_value);
  Set(path, value);
}

void CrosSettings::AppendToList(const std::string& path,
                                const base::Value* value) {
  DCHECK(CalledOnValidThread());
  const base::Value* old_value = GetPref(path);
  scoped_ptr<base::Value> new_value(
      old_value ? old_value->DeepCopy() : new base::ListValue());
  static_cast<base::ListValue*>(new_value.get())->Append(value->DeepCopy());
  Set(path, *new_value);
}

void CrosSettings::RemoveFromList(const std::string& path,
                                  const base::Value* value) {
  DCHECK(CalledOnValidThread());
  const base::Value* old_value = GetPref(path);
  scoped_ptr<base::Value> new_value(
      old_value ? old_value->DeepCopy() : new base::ListValue());
  static_cast<base::ListValue*>(new_value.get())->Remove(*value, NULL);
  Set(path, *new_value);
}

bool CrosSettings::GetBoolean(const std::string& path,
                              bool* bool_value) const {
  DCHECK(CalledOnValidThread());
  const base::Value* value = GetPref(path);
  if (value)
    return value->GetAsBoolean(bool_value);
  return false;
}

bool CrosSettings::GetInteger(const std::string& path,
                              int* out_value) const {
  DCHECK(CalledOnValidThread());
  const base::Value* value = GetPref(path);
  if (value)
    return value->GetAsInteger(out_value);
  return false;
}

bool CrosSettings::GetDouble(const std::string& path,
                             double* out_value) const {
  DCHECK(CalledOnValidThread());
  const base::Value* value = GetPref(path);
  if (value)
    return value->GetAsDouble(out_value);
  return false;
}

bool CrosSettings::GetString(const std::string& path,
                             std::string* out_value) const {
  DCHECK(CalledOnValidThread());
  const base::Value* value = GetPref(path);
  if (value)
    return value->GetAsString(out_value);
  return false;
}

bool CrosSettings::GetList(const std::string& path,
                           const base::ListValue** out_value) const {
  DCHECK(CalledOnValidThread());
  const base::Value* value = GetPref(path);
  if (value)
    return value->GetAsList(out_value);
  return false;
}

bool CrosSettings::FindEmailInList(const std::string& path,
                                   const std::string& email) const {
  DCHECK(CalledOnValidThread());
  std::string canonicalized_email(
      gaia::CanonicalizeEmail(gaia::SanitizeEmail(email)));
  std::string wildcard_email;
  std::string::size_type at_pos = canonicalized_email.find('@');
  if (at_pos != std::string::npos) {
    wildcard_email =
        std::string("*").append(canonicalized_email.substr(at_pos));
  }

  const base::ListValue* list;
  if (!GetList(path, &list))
    return false;
  for (base::ListValue::const_iterator entry(list->begin());
       entry != list->end();
       ++entry) {
    std::string entry_string;
    if (!(*entry)->GetAsString(&entry_string)) {
      NOTREACHED();
      continue;
    }
    std::string canonicalized_entry(
        gaia::CanonicalizeEmail(gaia::SanitizeEmail(entry_string)));

    if (canonicalized_entry == canonicalized_email ||
        canonicalized_entry == wildcard_email) {
      return true;
    }
  }
  return false;
}

bool CrosSettings::AddSettingsProvider(CrosSettingsProvider* provider) {
  DCHECK(CalledOnValidThread());
  providers_.push_back(provider);

  // Allow the provider to notify this object when settings have changed.
  // Providers instantiated inside this class will have the same callback
  // passed to their constructor, but doing it here allows for providers
  // to be instantiated outside this class.
  CrosSettingsProvider::NotifyObserversCallback notify_cb(
      base::Bind(&CrosSettings::FireObservers, base::Unretained(this)));
  provider->SetNotifyObserversCallback(notify_cb);
  return true;
}

bool CrosSettings::RemoveSettingsProvider(CrosSettingsProvider* provider) {
  DCHECK(CalledOnValidThread());
  std::vector<CrosSettingsProvider*>::iterator it =
      std::find(providers_.begin(), providers_.end(), provider);
  if (it != providers_.end()) {
    providers_.erase(it);
    return true;
  }
  return false;
}

void CrosSettings::AddSettingsObserver(const char* path,
                                       content::NotificationObserver* obs) {
  DCHECK(path);
  DCHECK(obs);
  DCHECK(CalledOnValidThread());

  if (!GetProvider(std::string(path))) {
    NOTREACHED() << "Trying to add an observer for an unregistered setting: "
                 << path;
    return;
  }

  // Get the settings observer list associated with the path.
  NotificationObserverList* observer_list = NULL;
  SettingsObserverMap::iterator observer_iterator =
      settings_observers_.find(path);
  if (observer_iterator == settings_observers_.end()) {
    observer_list = new NotificationObserverList;
    settings_observers_[path] = observer_list;
  } else {
    observer_list = observer_iterator->second;
  }

  // Verify that this observer doesn't already exist.
  NotificationObserverList::Iterator it(*observer_list);
  content::NotificationObserver* existing_obs;
  while ((existing_obs = it.GetNext()) != NULL) {
    if (existing_obs == obs)
      return;
  }

  // Ok, safe to add the pref observer.
  observer_list->AddObserver(obs);
}

void CrosSettings::RemoveSettingsObserver(const char* path,
                                          content::NotificationObserver* obs) {
  DCHECK(CalledOnValidThread());

  SettingsObserverMap::iterator observer_iterator =
      settings_observers_.find(path);
  if (observer_iterator == settings_observers_.end())
    return;

  NotificationObserverList* observer_list = observer_iterator->second;
  observer_list->RemoveObserver(obs);
}

CrosSettingsProvider* CrosSettings::GetProvider(
    const std::string& path) const {
  for (size_t i = 0; i < providers_.size(); ++i) {
    if (providers_[i]->HandlesSetting(path))
      return providers_[i];
  }
  return NULL;
}

CrosSettings::CrosSettings() {
  CrosSettingsProvider::NotifyObserversCallback notify_cb(
      base::Bind(&CrosSettings::FireObservers,
                 // This is safe since |this| is never deleted.
                 base::Unretained(this)));
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kStubCrosSettings)) {
    AddSettingsProvider(new StubCrosSettingsProvider(notify_cb));
  } else {
    AddSettingsProvider(
        new DeviceSettingsProvider(notify_cb, DeviceSettingsService::Get()));
  }
  // System settings are not mocked currently.
  AddSettingsProvider(new SystemSettingsProvider(notify_cb));
  // Kiosk app settings are not mocked.
  AddSettingsProvider(new KioskAppLocalSettings(notify_cb));
}

CrosSettings::~CrosSettings() {
  STLDeleteElements(&providers_);
  STLDeleteValues(&settings_observers_);
}

void CrosSettings::FireObservers(const std::string& path) {
  DCHECK(CalledOnValidThread());
  SettingsObserverMap::iterator observer_iterator =
      settings_observers_.find(path);
  if (observer_iterator == settings_observers_.end())
    return;

  NotificationObserverList::Iterator it(*(observer_iterator->second));
  content::NotificationObserver* observer;
  while ((observer = it.GetNext()) != NULL) {
    observer->Observe(chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED,
                      content::Source<CrosSettings>(this),
                      content::Details<const std::string>(&path));
  }
}

ScopedTestCrosSettings::ScopedTestCrosSettings() {
  CrosSettings::Initialize();
}

ScopedTestCrosSettings::~ScopedTestCrosSettings() {
  CrosSettings::Shutdown();
}

}  // namespace chromeos