text:
* [Overview][8]
* [Example][9]
* [Parameter Reference][6]
  * [Main config][7]
  * [AWS][0]
  * [GCP][1]
  * [Azure][2]

## Overview

Heptio Ark defines its own Config object (a custom resource) for specifying Ark backup and cloud provider settings. When the Ark server is first deployed, it waits until you create a Config--specifically one named `default`--in the `heptio-ark` namespace.

> *NOTE*: There is an underlying assumption that you're running the Ark server as a Kubernetes deployment. If the `default` Config is modified, the server shuts down gracefully. Once the kubelet restarts the Ark server pod, the server then uses the updated Config values.

## Example

A sample YAML `Config` looks like the following:
```
apiVersion: ark.heptio.com/v1
kind: Config
metadata:
  namespace: heptio-ark
  name: default
persistentVolumeProvider:
  name: aws
  config:
    region: us-west-2
backupStorageProvider:
  name: aws
  bucket: ark
  config:
    region: us-west-2
backupSyncPeriod: 60m
gcSyncPeriod: 60m
scheduleSyncPeriod: 1m
restoreOnlyMode: false
```

## Parameter Reference

The configurable parameters are as follows:

### Main config parameters

| Key | Type | Default | Meaning |
| --- | --- | --- | --- |
| `persistentVolumeProvider` | CloudProviderConfig | None (Optional) | The specification for whichever cloud provider the cluster is using for persistent volumes (to be snapshotted), if any.

If not specified, Backups and Restores requesting PV snapshots & restores, respectively, are considered invalid.

 *NOTE*: For Azure, your Kubernetes cluster needs to be version 1.7.2+ in order to support PV snapshotting of its managed disks. |
| `persistentVolumeProvider/name` | String

(Ark natively supports `aws`, `gcp`, and `azure`. Other providers may be available via external plugins.) | None (Optional) | The name of the cloud provider the cluster is using for persistent volumes, if any. |
| `persistentVolumeProvider/config` | map[string]string

(See the corresponding [AWS][0], [GCP][1], and [Azure][2]-specific configs or your provider's documentation.) | None (Optional) | Configuration keys/values to be passed to the cloud provider for persistent volumes.  |
| `backupStorageProvider` | CloudProviderConfig | Required Field | The specification for whichever cloud provider will be used to actually store the backups. |
| `backupStorageProvider/name` | String

(Ark natively supports `aws`, `gcp`, and `azure`. Other providers may be available via external plugins.) | Required Field | The name of the cloud provider that will be used to actually store the backups. |
| `backupStorageProvider/bucket` | String | Required Field | The storage bucket where backups are to be uploaded. |
| `backupStorageProvider/config` | map[string]string

(See the corresponding [AWS][0], [GCP][1], and [Azure][2]-specific configs or your provider's documentation.) | None (Optional) | Configuration keys/values to be passed to the cloud provider for backup storage. |
| `backupSyncPeriod` | metav1.Duration | 60m0s | How frequently Ark queries the object storage to make sure that the appropriate Backup resources have been created for existing backup files. |
| `gcSyncPeriod` | metav1.Duration | 60m0s | How frequently Ark queries the object storage to delete backup files that have passed their TTL. |
| `scheduleSyncPeriod` | metav1.Duration | 1m0s | How frequently Ark checks its Schedule resource objects to see if a backup needs to be initiated. |
| `resourcePriorities` | []string | `[namespaces, persistentvolumes, persistentvolumeclaims, secrets, configmaps]` | An ordered list that describes the order in which Kubernetes resource objects should be restored (also specified with the `<RESOURCE>.<GROUP>` format.

If a resource is not in this list, it is restored after all other prioritized resources. |
| `restoreOnlyMode` | bool | `false` | When RestoreOnly mode is on, functionality for backups, schedules, and expired backup deletion is *turned off*. Restores are made from existing backup files in object storage. |

### AWS

**(Or other S3-compatible storage)**

#### backupStorageProvider/config

| Key | Type | Default | Meaning |
| --- | --- | --- | --- |
| `region` | string | Required Field | *Example*: "us-east-1"

See [AWS documentation][3] for the full list. |
| `s3ForcePathStyle` | bool | `false` | Set this to `true` if you are using a local storage service like Minio. |
| `s3Url` | string | Required field for non-AWS-hosted storage| *Example*: http://minio:9000

You can specify the AWS S3 URL here for explicitness, but Ark can already generate it from `region`, and `bucket`. This field is primarily for local storage services like Minio.|
| `kmsKeyId` | string | Empty | *Example*: "502b409c-4da1-419f-a16e-eif453b3i49f" or "alias/`<KMS-Key-Alias-Name>`"

Specify an [AWS KMS key][10] id or alias to enable encryption of the backups stored in S3. Only works with AWS S3 and may require explicitly granting key usage rights.|

#### persistentVolumeProvider/config (AWS Only)

| Key | Type | Default | Meaning |
| --- | --- | --- | --- |
| `region` | string | Required Field | *Example*: "us-east-1"

See [AWS documentation][3] for the full list. |

### GCP

#### backupStorageProvider/config

No parameters required.

#### persistentVolumeProvider/config

| Key | Type | Default | Meaning |
| --- | --- | --- | --- |
| `project` | string | Required Field | *Example*: "project-example-3jsn23"

 See the [Project ID documentation][4] for details. |

### Azure

#### backupStorageProvider/config

No parameters required.

#### persistentVolumeProvider/config

| Key | Type | Default | Meaning |
| --- | --- | --- | --- |
| `location` | string | Required Field | *Example*: "Canada East"

See [the list of available locations][5] (note that this particular page refers to them as "Regions"). |
| `apiTimeout` | metav1.Duration | 2m0s | How long to wait for an Azure API request to complete before timeout. |

[0]: #aws
[1]: #gcp
[2]: #azure
[3]: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions
[4]: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects
[5]: https://azure.microsoft.com/en-us/regions/
[6]: #parameter-reference
[7]: #main-config-parameters
[8]: #overview
[9]: #example
[10]: http://docs.aws.amazon.com/kms/latest/developerguide/overview.html


text:
#include "Tests.h"
#include <UnitTest++.h>
#include <MTScheduler.h>

SUITE(StackSizeTests)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct StandartStackSizeTask
{
	MT_DECLARE_TASK(StandartStackSizeTask, MT::StackRequirements::STANDARD, MT::TaskPriority::NORMAL, MT::Color::Blue);

	void Do(MT::FiberContext&)
	{
		//byte stackData[28000];

		// Looks like OSX ASAN took too many stack space
		byte stackData[20000];
		for (uint32 i = 0; i < MT_ARRAY_SIZE(stackData); i++)
		{
			stackData[i] = 0x0D;
		}
	}
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct ExtendedStackSizeTask
{
	MT_DECLARE_TASK(ExtendedStackSizeTask, MT::StackRequirements::EXTENDED, MT::TaskPriority::NORMAL, MT::Color::Red);

	void Do(MT::FiberContext&)
	{
		byte stackData[262144];
		for (uint32 i = 0; i < MT_ARRAY_SIZE(stackData); i++)
		{
			stackData[i] = 0x0D;
		}
	}

};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunStandartTasks)
{
	MT::TaskScheduler scheduler;

	StandartStackSizeTask tasks[100];
	scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks));
	CHECK(scheduler.WaitAll(1000));
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunExtendedTasks)
{
	MT::TaskScheduler scheduler;

	ExtendedStackSizeTask tasks[100];
	scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks));
	CHECK(scheduler.WaitAll(1000));
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunMixedTasks)
{
	MT::TaskScheduler scheduler;

	MT::TaskPool<ExtendedStackSizeTask, 64> extendedTaskPool;
	MT::TaskPool<StandartStackSizeTask, 64> standardTaskPool;

	MT::TaskHandle taskHandles[100];
	for (size_t i = 0; i < MT_ARRAY_SIZE(taskHandles); ++i)
	{
		MT::TaskHandle handle;

		if (i & 1)
		{
			handle = extendedTaskPool.Alloc(ExtendedStackSizeTask());
		} else
		{
			handle = standardTaskPool.Alloc(StandartStackSizeTask());
		}
		taskHandles[i] = handle;
	}

	scheduler.RunAsync(MT::TaskGroup::Default(), &taskHandles[0], MT_ARRAY_SIZE(taskHandles));
	CHECK(scheduler.WaitAll(1000));
}

}

redpajama_set_name: RedPajamaGithub


text: Balanced\Marketplace::mine()->card_holds


text:
<?php
namespace watoki\stores\exceptions;

class NotFoundException extends \Exception {

    /** @var string */
    private $key;

    /**
     * @param string $key
     */
    public function __construct($key) {
        parent::__construct("Could not find [$key]");
        $this->key = $key;
    }
}


text:
    <title>angular-jsonrpc-client cancel request example</title>

Server: {{ url }}

Method name: <input type="text" ng-model="methodCall">
            <button ng-click="performCall()">Call now</button>
            <button ng-click="cancel()">Cancel now</button>

{{ message }}

JSON-RPC result:

{{ result }}

JSON-RPC error:

{{ error }}

It looks like the local JSON-RPC server is not running. If this is indeed the case, please start it.


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

namespace Squidex.Web;

public interface IApiCostsFeature
{
    double Costs { get; }
}


text:
using BigO.DAL.DaoImpl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BigO.Web.Controllers
{
    public class WeightGraphQuartController : Controller
    {
        // GET: WeightGrapQuart
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Report()
        {
            return View();
        }
    }
}


text:
package net.lightstone.net.codec;

import java.io.IOException;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;

import net.lightstone.msg.HealthMessage;

public final class HealthCodec extends MessageCodec<HealthMessage> {

	public HealthCodec() {
		super(HealthMessage.class, 0x08);
	}

	@Override
	public HealthMessage decode(ChannelBuffer buffer) throws IOException {
		int health = buffer.readUnsignedByte();
		return new HealthMessage(health);
	}

	@Override
	public ChannelBuffer encode(HealthMessage message) throws IOException {
		ChannelBuffer buffer = ChannelBuffers.buffer(1);
		buffer.writeByte(message.getHealth());
		return buffer;
	}

}


text:
<?php

namespace Symfony\Bridge\PhpUnit\TextUI;

use PHPUnit\TextUI\Command as BaseCommand;

if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version::id(), '6.0.0', '<')) {
    class_alias('Symfony\Bridge\PhpUnit\Legacy\Command', 'Symfony\Bridge\PhpUnit\TextUI\Command');

    return;
}

/**
 * {@inheritdoc}
 *
 * @internal
 */
class Command extends BaseCommand
{
    /**
     * {@inheritdoc}
     */
    protected function createRunner()
    {
        return new TestRunner($this->arguments['loader']);
    }
}


text:
package org.apache.flink.streaming.runtime.tasks;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.io.network.partition.consumer.StreamTestSingleInputGate;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.operators.testutils.MockInputSplitProvider;
import org.apache.flink.runtime.state.LocalRecoveryConfig;
import org.apache.flink.runtime.state.TestLocalRecoveryConfig;
import org.apache.flink.runtime.state.TestTaskStateManager;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.graph.StreamConfig;
import org.apache.flink.streaming.api.graph.StreamConfig.InputConfig;
import org.apache.flink.streaming.api.graph.StreamConfig.NetworkInputConfig;
import org.apache.flink.streaming.api.graph.StreamConfig.SourceInputConfig;
import org.apache.flink.streaming.api.graph.StreamEdge;
import org.apache.flink.streaming.api.graph.StreamNode;
import org.apache.flink.streaming.api.operators.SimpleOperatorFactory;
import org.apache.flink.streaming.api.operators.SourceOperatorFactory;
import org.apache.flink.streaming.api.operators.StreamOperator;
import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
import org.apache.flink.streaming.runtime.partitioner.BroadcastPartitioner;
import org.apache.flink.streaming.runtime.partitioner.ForwardPartitioner;
import org.apache.flink.streaming.runtime.streamrecord.StreamElementSerializer;
import org.apache.flink.util.function.FunctionWithException;

import javax.annotation.Nullable;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.function.Consumer;

import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;

/**
 * Builder class for {@link StreamTaskMailboxTestHarness}.
 */
public class StreamTaskMailboxTestHarnessBuilder<OUT> {
	protected final FunctionWithException<Environment, ? extends StreamTask<OUT, ?>, Exception> taskFactory;
	protected final TypeSerializer<OUT> outputSerializer;
	protected final ExecutionConfig executionConfig = new ExecutionConfig();

	protected long memorySize = 1024 * 1024;
	protected int bufferSize = 1024;
	protected Configuration jobConfig = new Configuration();
	protected Configuration taskConfig = new Configuration();
	protected StreamConfig streamConfig = new StreamConfig(taskConfig);
	protected LocalRecoveryConfig localRecoveryConfig = TestLocalRecoveryConfig.disabled();
	@Nullable
	protected StreamTestSingleInputGate[] inputGates;
	protected TaskMetricGroup taskMetricGroup = UnregisteredMetricGroups.createUnregisteredTaskMetricGroup();
	protected Map<Long, TaskStateSnapshot> taskStateSnapshots;

	protected final ArrayList<InputConfig> inputs = new ArrayList<>();
	protected final ArrayList<Integer> inputChannelsPerGate = new ArrayList<>();

	private boolean setupCalled = false;

	public StreamTaskMailboxTestHarnessBuilder(
			FunctionWithException<Environment, ? extends StreamTask<OUT, ?>, Exception> taskFactory,
			TypeInformation<OUT> outputType) {
		this.taskFactory = checkNotNull(taskFactory);
		outputSerializer = outputType.createSerializer(executionConfig);
		streamConfig.setTimeCharacteristic(TimeCharacteristic.EventTime);
	}

	public <T> StreamTaskMailboxTestHarnessBuilder<OUT> modifyExecutionConfig(Consumer<ExecutionConfig> action) {
		action.accept(executionConfig);
		return this;
	}

	public <T> StreamTaskMailboxTestHarnessBuilder<OUT> modifyStreamConfig(Consumer<StreamConfig> action) {
		action.accept(streamConfig);
		return this;
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> addInput(TypeInformation<?> inputType) {
		return addInput(inputType, 1);
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> addInput(TypeInformation<?> inputType, int inputChannels) {
		return addInput(inputType, inputChannels, null);
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> addInput(
			TypeInformation<?> inputType,
			int inputChannels,
			@Nullable KeySelector<?, ?> keySelector) {
		streamConfig.setStatePartitioner(inputs.size(), keySelector);
		inputs.add(new NetworkInputConfig(inputType.createSerializer(executionConfig), inputChannelsPerGate.size()));
		inputChannelsPerGate.add(inputChannels);
		return this;
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> addSourceInput(SourceOperatorFactory<?> sourceOperatorFactory) {
		inputs.add(new SourceInputConfigPlaceHolder(sourceOperatorFactory));
		return this;
	}

	public StreamTaskMailboxTestHarness<OUT> build() throws Exception {

		TestTaskStateManager taskStateManager = new TestTaskStateManager(localRecoveryConfig);
		if (taskStateSnapshots != null) {
			taskStateManager.setReportedCheckpointId(taskStateSnapshots.keySet().iterator().next());
			taskStateManager.setJobManagerTaskStateSnapshotsByCheckpointId(taskStateSnapshots);
		}

		StreamMockEnvironment streamMockEnvironment = new StreamMockEnvironment(
			jobConfig,
			taskConfig,
			executionConfig,
			memorySize,
			new MockInputSplitProvider(),
			bufferSize,
			taskStateManager);

		streamMockEnvironment.setCheckpointResponder(taskStateManager.getCheckpointResponder());
		initializeInputs(streamMockEnvironment);

		checkState(inputGates != null, "InputGates hasn't been initialised");

		StreamElementSerializer<OUT> outputStreamRecordSerializer = new StreamElementSerializer<>(outputSerializer);

		Queue<Object> outputList = new ArrayDeque<>();
		streamMockEnvironment.addOutput(outputList, outputStreamRecordSerializer);
		streamMockEnvironment.setTaskMetricGroup(taskMetricGroup);

		StreamTask<OUT, ?> task = taskFactory.apply(streamMockEnvironment);
		task.beforeInvoke();

		return new StreamTaskMailboxTestHarness<>(
			task,
			outputList,
			inputGates,
			streamMockEnvironment);
	}

	protected void initializeInputs(StreamMockEnvironment streamMockEnvironment) {
		inputGates = new StreamTestSingleInputGate[inputChannelsPerGate.size()];
		List<StreamEdge> inPhysicalEdges = new LinkedList<>();

		StreamNode mainNode = new StreamNode(StreamConfigChainer.MAIN_NODE_ID, null, null, (StreamOperator<?>) null, null, null);
		for (int i = 0; i < inputs.size(); i++) {
			if ((inputs.get(i) instanceof NetworkInputConfig)) {
				NetworkInputConfig networkInput = (NetworkInputConfig) inputs.get(i);
				initializeNetworkInput(networkInput, mainNode, streamMockEnvironment, inPhysicalEdges);
			}
			else if ((inputs.get(i) instanceof StreamTaskMailboxTestHarnessBuilder.SourceInputConfigPlaceHolder)) {
				SourceInputConfigPlaceHolder sourceInput = (SourceInputConfigPlaceHolder) inputs.get(i);
				inputs.set(i, initializeSourceInput(i, sourceInput, mainNode));
			}
			else {
				throw new UnsupportedOperationException("Unknown input type " + inputs.get(i));
			}
		}

		streamConfig.setInPhysicalEdges(inPhysicalEdges);
		streamConfig.setNumberOfNetworkInputs(inputGates.length);
		streamConfig.setInputs(inputs.toArray(new InputConfig[inputs.size()]));
	}

	private void initializeNetworkInput(
			NetworkInputConfig networkInput,
			StreamNode targetVertexDummy,
			StreamMockEnvironment streamMockEnvironment,
			List<StreamEdge> inPhysicalEdges) {
		int gateIndex = networkInput.getInputGateIndex();

		TypeSerializer<?> inputSerializer = networkInput.getTypeSerializer();
		inputGates[gateIndex] = new StreamTestSingleInputGate<>(
			inputChannelsPerGate.get(gateIndex),
			gateIndex,
			inputSerializer,
			bufferSize);

		StreamNode sourceVertexDummy = new StreamNode(0, null, null, (StreamOperator<?>) null, null, SourceStreamTask.class);
		StreamEdge streamEdge = new StreamEdge(
			sourceVertexDummy,
			targetVertexDummy,
			gateIndex + 1,
			new BroadcastPartitioner<>(),
			null);

		inPhysicalEdges.add(streamEdge);
		streamMockEnvironment.addInputGate(inputGates[gateIndex].getInputGate());
	}

	private SourceInputConfig initializeSourceInput(
			int inputId,
			SourceInputConfigPlaceHolder sourceInput,
			StreamNode mainNode) {
		Map<Integer, StreamConfig> transitiveChainedTaskConfigs = streamConfig.getTransitiveChainedTaskConfigs(getClass().getClassLoader());
		Integer maxNodeId = transitiveChainedTaskConfigs.isEmpty() ? StreamConfigChainer.MAIN_NODE_ID : Collections.max(transitiveChainedTaskConfigs.keySet());

		List<StreamEdge> outEdgesInOrder = new LinkedList<>();

		StreamEdge sourceToMainEdge = new StreamEdge(
			new StreamNode(maxNodeId + inputId + 1337, null, null, (StreamOperator<?>) null, null, null),
			mainNode,
			0,
			new ForwardPartitioner<>(),
			null);
		outEdgesInOrder.add(sourceToMainEdge);

		StreamConfig sourceConfig = new StreamConfig(new Configuration());
		sourceConfig.setTimeCharacteristic(streamConfig.getTimeCharacteristic());
		sourceConfig.setOutEdgesInOrder(outEdgesInOrder);
		sourceConfig.setChainedOutputs(outEdgesInOrder);
		sourceConfig.setTypeSerializerOut(outputSerializer);
		sourceConfig.setOperatorID(new OperatorID());
		sourceConfig.setStreamOperatorFactory(sourceInput.getSourceOperatorFactory());

		transitiveChainedTaskConfigs.put(sourceToMainEdge.getSourceId(), sourceConfig);
		streamConfig.setTransitiveChainedTaskConfigs(transitiveChainedTaskConfigs);
		return new SourceInputConfig(sourceToMainEdge);
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> setupOutputForSingletonOperatorChain(StreamOperator<?> operator) {
		return setupOutputForSingletonOperatorChain(SimpleOperatorFactory.of(operator), new OperatorID());
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> setupOutputForSingletonOperatorChain(
			StreamOperator<?> operator,
			OperatorID operatorID) {
		return setupOutputForSingletonOperatorChain(SimpleOperatorFactory.of(operator), operatorID);
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> setupOutputForSingletonOperatorChain(StreamOperatorFactory<?> factory) {
		return setupOutputForSingletonOperatorChain(factory, new OperatorID());
	}

	/**
	 * Users of the test harness can call this utility method to setup the stream config
	 * if there will only be a single operator to be tested. The method will setup the
	 * outgoing network connection for the operator.
	 *
	 * <p>For more advanced test cases such as testing chains of multiple operators with the harness,
	 * please manually configure the stream config.
	 */
	public StreamTaskMailboxTestHarnessBuilder<OUT> setupOutputForSingletonOperatorChain(
			StreamOperatorFactory<?> factory,
			OperatorID operatorID) {
		checkState(!setupCalled, "This harness was already setup.");
		return setupOperatorChain(operatorID, factory).finishForSingletonOperatorChain(outputSerializer);
	}

	public StreamConfigChainer<StreamTaskMailboxTestHarnessBuilder<OUT>> setupOperatorChain(StreamOperator<?> headOperator) {
		return setupOperatorChain(new OperatorID(), headOperator);
	}

	public StreamConfigChainer<StreamTaskMailboxTestHarnessBuilder<OUT>> setupOperatorChain(OperatorID headOperatorId, StreamOperator<?> headOperator) {
		return setupOperatorChain(headOperatorId, SimpleOperatorFactory.of(headOperator));
	}

	public StreamConfigChainer<StreamTaskMailboxTestHarnessBuilder<OUT>> setupOperatorChain(StreamOperatorFactory<?> headOperatorFactory) {
		return setupOperatorChain(new OperatorID(), headOperatorFactory);
	}

	public StreamConfigChainer<StreamTaskMailboxTestHarnessBuilder<OUT>> setupOperatorChain(OperatorID headOperatorId, StreamOperatorFactory<?> headOperatorFactory) {
		checkState(!setupCalled, "This harness was already setup.");
		setupCalled = true;
		streamConfig.setStreamOperatorFactory(headOperatorFactory);
		return new StreamConfigChainer<>(headOperatorId, streamConfig, this);
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> setTaskMetricGroup(TaskMetricGroup taskMetricGroup) {
		this.taskMetricGroup = taskMetricGroup;
		return this;
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> setKeyType(TypeInformation<?> keyType) {
		streamConfig.setStateKeySerializer(keyType.createSerializer(executionConfig));
		return this;
	}

	public StreamTaskMailboxTestHarnessBuilder<OUT> setTaskStateSnapshot(long checkpointId, TaskStateSnapshot snapshot) {
		taskStateSnapshots = Collections.singletonMap(checkpointId, snapshot);
		return this;
	}

	/**
	 * A place holder representation of a {@link SourceInputConfig}. When building the test harness
	 * it is replaced with {@link SourceInputConfig}.
	 */
	public static class SourceInputConfigPlaceHolder implements InputConfig {
		private SourceOperatorFactory<?> sourceOperatorFactory;

		public SourceInputConfigPlaceHolder(SourceOperatorFactory<?> sourceOperatorFactory) {
			this.sourceOperatorFactory = sourceOperatorFactory;
		}

		public SourceOperatorFactory<?> getSourceOperatorFactory() {
			return sourceOperatorFactory;
		}
	}
}


text:
use option::{Option, None};
use kinds::Send;
use string::String;

/// Base functionality for all errors in Rust.
pub trait Error: Send {
    /// A short description of the error; usually a static string.
    fn description(&self) -> &str;

    /// A detailed description of the error, usually including dynamic information.
    fn detail(&self) -> Option<String> { None }

    /// The lower-level cause of this error, if any.
    fn cause(&self) -> Option<&Error> { None }
}

/// A trait for types that can be converted from a given error type `E`.
pub trait FromError<E> {
    /// Perform the conversion.
    fn from_error(err: E) -> Self;
}

// Any type is convertable from itself
impl<E> FromError<E> for E {
    fn from_error(err: E) -> E {
        err
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Adebola
 * Date: 29/08/2014
 * Time: 12:57
 */

namespace Samcrosoft\Accesstory\Core\Session;
use Samcrosoft\Accesstory\Config\Reader;

/**
 * Class SessionManager
 * @package Samcrosoft\Accesstory\Core\Session
 */
class SessionManager {

    /**
     * @var null|float
     */
    private $fStartTimeStore = null;
    /**
     * @var null
     */
    private $fEndTime   = null;

    /**
     * @var null
     */
    private $fMemoryUsage = null;

    /**
     * @var array
     */
    public $aCollectedData = [];

    /**
     * @return float|null
     */
    public function getStartTime()
    {
        return $this->fStartTimeStore;
    }

    /**
     */
    public function setStartTime()
    {
        // set the time to the start of laravel
        $this->fStartTimeStore = Reader::includeLaravelBootTime() ? LARAVEL_START : microtime(true);
    }

    /**
     *
     */
    public function setEndTime(){
        $this->fEndTime = microtime(true);
    }

    /**
     * @return null
     */
    public function getEndTime(){
        if(is_null($this->fEndTime))
            $this->setEndTime();

        return $this->fEndTime;
    }

    /**
     * This will return the time take
     */
    public function getTimeTaken(){
        return round($this->getEndTime() - $this->getStartTime(), 6);
    }

    /**
     * This will set the memory usage for the current request[session]
     */
    public function setMemoryUsage(){
        $this->fMemoryUsage = memory_get_usage(TRUE);
    }

    /**
     * @return string
     */
    public function getMemoryUsage(){
        if(empty($this->fEndTime)) $this->setMemoryUsage();

        return $this->fMemoryUsage;
    }

    /**
     * @param array $aData
     */
    public function saveCollectedData($aData = []){
        $this->aCollectedData = $aData;
    }

    /**
     * @return array
     */
    public function getCollectedData(){
        return $this->aCollectedData;
    }

}


text:
The `cni-bridge-fp` is a CNI plugin which delegates interface-creating function
to [CNI bridge plugin][1] and allows user to inject failpoint before delegation.

Since the CNI plugin is invoked by binary call from CRI and it is short-lived,
the failpoint need to be configured by a JSON file, which can be persisted.
There is an example about failpoint description.

```json
{
	"cmdAdd":   "1*error(you-shall-not-pass!)->1*panic(again)",
	"cmdDel":   "1*error(try-again)",
	"cmdCheck": "10*off"
}
```

* `cmdAdd` (string, optional): The failpoint for `ADD` command.
* `cmdDel` (string, optional): The failpoint for `DEL` command.
* `cmdCheck` (string, optional): The failpoint for `CHECK` command.

Since the `cmdXXX` can be multiple failpoints, each CNI binary call will update
the current state to make sure the order of execution is expected.

And the failpoint injection is enabled by pod's annotation. Currently, the key
of customized CNI capabilities in containerd can only be `io.kubernetes.cri.pod-annotations`
and containerd will pass pod's annotations to CNI under the that object. The
user can use the `failpoint.cni.containerd.io/confpath` annotation to enable
failpoint for the pod.

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  annotations:
    failpoint.cni.containerd.io/confpath: "/tmp/pod-failpoints.json"
spec:
  containers:
  - name: nginx
    image: nginx:1.14.2
    ports:
    - containerPort: 80
```

### Example

Let's use the following json as failpoint description.

```bash
$ cat <<EOF | tee /tmp/cni-failpoint.json
{
	"cmdAdd":   "1*error(try-again)",
	"cmdDel":   "2*error(oops)",
	"cmdCheck": "1*off->1*panic(sorry)"
}
EOF
```

And use `ip netns` to create persisted net namespace named by `failpoint`.

```bash
$ sudo ip netns add failpoint
```

And then setup the following bash script for demo.

```bash
$ cat <<EOFDEMO | tee /tmp/cni-failpoint-demo-helper.sh
#!/usr/bin/env bash

export CNI_CONTAINERID=failpoint-testing
export CNI_NETNS=/run/netns/failpoint
export CNI_IFNAME=fpeni0
export CNI_PATH=/opt/cni/bin/

cat <<EOF | /opt/cni/bin/cni-bridge-fp
{
  "cniVersion": "0.3.0",
  "name": "containerd-net-fp",
  "type": "cni-bridge-fp",
  "bridge": "fp-cni0",
  "isGateway": true,
  "ipMasq": true,
  "promiscMode": true,
  "ipam": {
    "type": "host-local",
    "ranges": [
      [{
        "subnet": "10.88.0.0/16"
      }],
      [{
        "subnet": "2001:4860:4860::/64"
      }]
    ],
    "routes": [
      { "dst": "0.0.0.0/0" },
      { "dst": "::/0" }
    ]
  },
  "runtimeConfig": {
    "io.kubernetes.cri.pod-annotations": {
      "failpoint.cni.containerd.io/confpath": "/tmp/cni-failpoint.json"
    }
  }
}
EOF

EOFDEMO
```

Let's try to setup CNI and we should get a error `try-again`.

```bash
$ sudo CNI_COMMAND=ADD bash /tmp/cni-failpoint-demo-helper.sh
{
    "code": 999,
    "msg": "try-again"
}

# there is no failpoint for ADD command.
$ cat /tmp/cni-failpoint.json | jq .
{
  "cmdAdd": "0*error(try-again)",
  "cmdDel": "2*error(oops)",
  "cmdCheck": "1*off->1*panic(sorry)"
}
```

We should setup CNI successfully after retry. When we teardown the interface,
there should be two failpoints.

```bash
$ sudo CNI_COMMAND=ADD bash /tmp/cni-failpoint-demo-helper.sh
...

$ sudo CNI_COMMAND=DEL bash /tmp/cni-failpoint-demo-helper.sh
{
    "code": 999,
    "msg": "oops"
}

$ sudo CNI_COMMAND=DEL bash /tmp/cni-failpoint-demo-helper.sh
{
    "code": 999,
    "msg": "oops"
}

$ cat /tmp/cni-failpoint.json | jq .
{
  "cmdAdd": "0*error(try-again)",
  "cmdDel": "0*error(oops)",
  "cmdCheck": "1*off->1*panic(sorry)"
}
```

[1]: <https://www.cni.dev/plugins/current/main/bridge/>


text:
id: V-38522
status: implemented
tag: misc
---

Rules are added for auditing changes to system time made via ``settimeofday``.


text:
using SolidWorks.Interop.sldworks;

namespace AngelSix.SolidDna
{
    /// <summary>
    /// Represents a SolidWorks Reference Curve feature
    /// </summary>
    public class FeatureReferenceCurve : SolidDnaObject<IReferenceCurve>
    {
        #region Constructor

        /// <summary>
        /// Default constructor
        /// </summary>
        public FeatureReferenceCurve(IReferenceCurve model) : base(model)
        {

        }

        #endregion
    }
}


text:
<?php

namespace Fungio\GoogleMapBundle\Tests\Fixtures\Model\Events;

use Fungio\GoogleMap\Events\Event as BaseEvent;

/**
 * Event for testing.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class Event extends BaseEvent
{
}


text:
---
layout: post100
title:  Task Execution
categories: XAP100
parent: scala.html
weight: 500
---

A wrapper around the `XAP` API provides some sugaring on top of the `GigaSpace#execute` methods.

# Usage

Import `org.openspaces.scala.core.ScalaGigaSpacesImplicits.ScalaEnhancedGigaSpaceWrapper` into scope to use the methods demonstrated below.
Some examples:

{% highlight scala %}
/** Import GigaSpace implicits into scope */
import org.openspaces.scala.core.ScalaGigaSpacesImplicits._

...

gigaSpace write Data(id = 1, routing = 2, data = "some data")
gigaSpace write Data(id = 2, routing = 3, data = "some other data")

val asyncFuture1 = gigaSpace.execute { gigaSpace: GigaSpace =>
  gigaSpace.readById(classOf[Data], 1l)
}

println("Execute1 result: " + asyncFuture1.get())

val asyncFuture2 = gigaSpace.execute(
  { gigaSpace: GigaSpace => gigaSpace.read(Data()).data } /* map */,
  { results: Seq[AsyncResult[String]] => results.map { _.getResult() } mkString } /* reduce */
)

println("Map reduce result: " + asyncFuture2.get())
{% endhighlight %}


text:
package org.apache.sling.launchpad.base.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.felix.framework.Logger;
import org.apache.felix.framework.util.FelixConstants;
import org.apache.sling.launchpad.api.LaunchpadContentProvider;
import org.apache.sling.launchpad.base.shared.Notifiable;
import org.apache.sling.launchpad.base.shared.SharedConstants;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.launch.Framework;
import org.osgi.service.url.URLConstants;
import org.osgi.service.url.URLStreamHandlerService;

/**
 * The Sling serves as the starting point for Sling.
 *

 *
The {@link #Sling(Notifiable, Logger, LaunchpadContentProvider, Map)} method launches Apache
 * Felix as the OSGi framework implementation we use.
 *

 *

 * Launch Configuration
 *

 * The Apache Felix framework requires configuration parameters to
 * be specified for startup. This servlet builds the list of parameters from
 * three locations:
 *

 *
The sling.properties file is read from the servlet class
 * path. This properties file contains default settings.

 *
Extensions of this servlet may provide additional properties to be loaded
 * overwriting the {@link #loadPropertiesOverride(Map)} method.
 *
Finally, web application init parameters are added to the properties and
 * may overwrite existing properties of the same name(s).
 *

 *

 * After loading all properties, variable substitution takes place on the
 * property values. A variable is indicated as ${<prop-name>}
 * where <prop-name> is the name of a system or configuration
 * property (configuration properties override system properties). Variables may
 * be nested and are resolved from inner-most to outer-most. For example, the
 * property value ${outer-${inner}} is resolved by first resolving
 * ${inner} and then resolving the property whose name is the
 * catenation of outer- and the result of resolving
 * ${inner}.
 *

 */
public class Sling {

    /**
     * The name of the configuration property defining the Sling home directory
     * as an URL (value is "sling.home.url").
     *

     * The value of this property is assigned the value of
     * new File(${sling.home}).toURI().toString() before
     * resolving the property variables.
     *
     * @see SharedConstants#SLING_HOME
     */
    public static final String SLING_HOME_URL = "sling.home.url";

    /**
     * The name of the configuration property defining the JCR home directory
     * (value is "sling.repository.home").
     *

     * The value of this property could be set as a system property, init-param in
     * web.xml or property in sling.properties.
     *

     * Default value to #SLING_HOME/repository_name
     */
    public static final String JCR_REPO_HOME = "sling.repository.home";

    /**
     * The name of the configuration property defining the URL of an existing
     * repository config file (repository.xml).
     *

     * The value of this property could be set as a system property, init-param in
     * web.xml or property in sling.properties.
     *

     * Default value to #SLING_HOME/repository_name/repository.xml
     */
    public static final String JCR_REPO_CONFIG_FILE_URL = "sling.repository.config.file.url";

    /**
     * The name of the configuration property defining a properties file
     * defining a list of bundles, which are installed into the framework when
     * it has been launched (value is "org.apache.osgi.bundles").
     *

     * This configuration property is generally set in the web application
     * configuration and may be referenced in all property files (default, user
     * supplied and web application parameters) used to build the framework
     * configuration.
     */
    public static final String OSGI_FRAMEWORK_BUNDLES = "org.apache.osgi.bundles";

    /**
     * The property to be set to ignore the system properties when building the
     * Felix framework properties (value is "sling.ignoreSystemProperties"). If
     * this is property is set to true (case does not matter),
     * the system properties will not be used by
     * {@link #loadConfigProperties(Map)}.
     */
    public static final String SLING_IGNORE_SYSTEM_PROPERTIES = "sling.ignoreSystemProperties";

    /**
     * The name of the default launcher properties file to setup the environment
     * for the Felix framework (value is "sling.properties").
     *

     * Extensions of this class may overwrite some or all properties in this
     * file through Web Application parameters or other properties files.
     */
    public static final String CONFIG_PROPERTIES = "sling.properties";

    public static final String PROP_SYSTEM_PACKAGES = "org.apache.sling.launcher.system.packages";

    public static final String PROP_EXTRA_CAPS = "org.apache.sling.launcher.system.capabilities.extra";

    /**
     * Timeout to wait for the initialized framework to actually stop for it to
     * be reinitialized. This is set to a second, which should be ample time to
     * do this. If this time passes without the framework being stopped, an
     * error is issued.
     */
    private static final long REINIT_TIMEOUT = 1000L;

    /**
     * The simple logger to log messages during startup and shutdown to
     */
    protected final Logger logger;

    private LaunchpadContentProvider resourceProvider;

    /**
     * The Felix instance loaded on {@link #init()} and stopped
     * on {@link #destroy()}.
     */
    private Framework framework;

    /**
     * Initializes this servlet by loading the framework configuration
     * properties, starting the OSGi framework (Apache Felix) and exposing the
     * system bundle context and the Felix instance as servlet
     * context attributes.
     *
     * @throws BundleException if the framework cannot be initialized.
     */
    public Sling(final Notifiable notifiable,
            final Logger logger,
            final LaunchpadContentProvider resourceProvider,
            final Map<String, String> propOverwrite)
    throws BundleException {

        this.logger = logger;
        this.resourceProvider = resourceProvider;

        final long startedAt = System.currentTimeMillis();
        this.logger.log(Logger.LOG_INFO, "Starting Apache Sling");

        // read the default parameters
        final Map<String, String> props = this.loadConfigProperties(propOverwrite);

        // check for bootstrap command file
        copyBootstrapCommandFile(props);

        // check for auto-start bundles
        this.setInstallBundles(props);

        // create the framework and start it
        try {

            // initiate startup handler
            final StartupManager startupManager = new StartupManager(props, logger);

            Framework tmpFramework = createFramework(notifiable, logger, props);
            init(tmpFramework);

            final boolean restart = new BootstrapInstaller(tmpFramework.getBundleContext(), logger,
                    resourceProvider, startupManager.getMode()).install();
            startupManager.markInstalled();

            if (restart) {
                restart(tmpFramework);
                tmpFramework = createFramework(notifiable, logger, props);
                init(tmpFramework);
            }

            new DefaultStartupHandler(tmpFramework.getBundleContext(), logger, startupManager, startedAt);

            // finally start
            tmpFramework.start();

            // only assign field if start succeeds
            this.framework = tmpFramework;
        } catch (final BundleException be) {
            throw be;
        } catch (final Exception e) {
            // thrown by SlingFelix constructor
            throw new BundleException("Uncaught Instantiation Issue: " + e, e);
        }

        // log sucess message
        this.logger.log(Logger.LOG_INFO, "Apache Sling started");
    }

    /**
     * Destroys this servlet by shutting down the OSGi framework and hence the
     * delegatee servlet if one is set at all.
     */
    public final void destroy() {
        if (framework != null) {
            // get a private copy of the reference and remove the class ref
            Framework myFramework;
            synchronized (this) {
                myFramework = framework;
                framework = null;
            }

            // shutdown the Felix container
            if (myFramework != null) {
                logger.log(Logger.LOG_INFO, "Shutting down Apache Sling");
                try {

                    myFramework.stop();
                    myFramework.waitForStop(0);

                } catch (BundleException be) {

                    // may be thrown by stop, log but continue
                    logger.log(Logger.LOG_ERROR,
                        "Failure initiating Framework Shutdown", be);

                } catch (InterruptedException ie) {

                    // may be thrown by waitForStop, log but continue
                    logger.log(
                        Logger.LOG_ERROR,
                        "Interrupted while waiting for the Framework Termination",
                        ie);

                }

                logger.log(Logger.LOG_INFO, "Apache Sling stopped");
            }
        }
    }

    // ---------- BundleActivator ----------------------------------------------

    /**
     * Called when the OSGi framework is being started. This implementation
     * registers as a service listener for the
     * javax.servlet.Servlet class and calls the
     * {@link #doStartBundle()} method for implementations to execute more
     * startup tasks. Additionally the context URL protocol
     * handler is registered.
     *
     * @param bundleContext The BundleContext of the system
     *            bundle of the OSGi framework.
     * @throws BundleException May be thrown if the {@link #doStartBundle()} throws.
     */
    private final void startup(BundleContext bundleContext) {

        // register the context URL handler
        Hashtable<String, Object> props = new Hashtable<String, Object>();
        props.put(URLConstants.URL_HANDLER_PROTOCOL, new String[] { "context" });
        ContextProtocolHandler contextHandler = new ContextProtocolHandler(
            this.resourceProvider);
        bundleContext.registerService(URLStreamHandlerService.class.getName(),
            contextHandler, props);

        // register the platform MBeanServer
        MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
        Hashtable<String, Object> mbeanProps = new Hashtable<String, Object>();
        try {
            ObjectName beanName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
            AttributeList attrs = platformMBeanServer.getAttributes(beanName,
                new String[] { "MBeanServerId", "SpecificationName",
                    "SpecificationVersion", "SpecificationVendor",
                    "ImplementationName", "ImplementationVersion",
                    "ImplementationVendor" });
            for (Object object : attrs) {
                Attribute attr = (Attribute) object;
                if (attr.getValue() != null) {
                    mbeanProps.put(attr.getName(), attr.getValue().toString());
                }
            }
        } catch (Exception je) {
            logger.log(
                Logger.LOG_INFO,
                "start: Cannot set service properties of Platform MBeanServer service, registering without",
                je);
        }
        bundleContext.registerService(MBeanServer.class.getName(),
            platformMBeanServer, mbeanProps);
        bundleContext.registerService(LaunchpadContentProvider.class.getName(), resourceProvider, null);
    }

    // ---------- Creating the framework instance

    @SuppressWarnings("unchecked")
    private Framework createFramework(final Notifiable notifiable,
            final Logger logger, @SuppressWarnings("rawtypes") Map props)
            throws Exception {
        props.put(FelixConstants.LOG_LOGGER_PROP, logger);
        return new SlingFelix(notifiable, props);
    }

    private void init(final Framework framework) throws BundleException {
        // initialize the framework
        framework.init();

        // do first startup setup
        this.startup(framework.getBundleContext());
    }

    private void restart(final Framework framework) throws BundleException {
        if ((framework.getState() & (Bundle.STARTING|Bundle.ACTIVE|Bundle.STOPPING)) != 0) {
            if ( framework instanceof SlingFelix ) {
                ((SlingFelix)framework).restart();
            } else {
                framework.stop();
            }
            try {
                framework.waitForStop(REINIT_TIMEOUT);
            } catch (InterruptedException ie) {
                throw new BundleException(
                    "Interrupted while waiting for the framework stop before reinitialization");
            }
        }
    }

    // ---------- Configuration Loading

    /**
     * Loads the configuration properties in the configuration property file
     * associated with the framework installation; these properties are
     * accessible to the framework and to bundles and are intended for
     * configuration purposes. By default, the configuration property file is
     * located in the <tt>conf/</tt> directory of the Felix installation
     * directory and is called "<tt>config.properties</tt>". The
     * installation directory of Felix is assumed to be the parent directory of
     * the <tt>framework.jar</tt> file as found on the system class path property.
     * The precise file from which to load configuration properties can be set
     * by initializing the "<tt>framework.config.properties</tt>" system
     * property to an arbitrary URL.
     *
     * @return A <tt>Properties</tt> instance or <tt>null</tt> if there was
     *         an error.
     */
    private Map<String, String> loadConfigProperties(
            final Map<String, String> propOverwrite) throws BundleException {
        // The config properties file is either specified by a system
        // property or it is in the same directory as the Felix JAR file.
        // Try to load it from one of these places.
        final Map<String, String> staticProps = new HashMap<String, String>();

        // Read the embedded (default) properties file.
        this.load(staticProps, CONFIG_PROPERTIES);

        // resolve inclusions (and remove property)
        this.loadIncludes(staticProps, null);

        // overwrite default properties with initial overwrites
        if (propOverwrite != null) {
            staticProps.putAll(propOverwrite);
        }

        // check whether sling.home is overwritten by system property
        String slingHome = staticProps.get(SharedConstants.SLING_HOME);
        if (slingHome == null || slingHome.length() == 0) {
            throw new BundleException("sling.home property is missing, cannot start");
        }

        // resolve variables and ensure sling.home is an absolute path
        slingHome = substVars(slingHome, SharedConstants.SLING_HOME, null, staticProps);
        File slingHomeFile = new File(slingHome).getAbsoluteFile();
        slingHome = slingHomeFile.getAbsolutePath();

        // overlay with ${sling.home}/sling.properties
        this.logger.log(Logger.LOG_INFO, "Starting Apache Sling in " + slingHome);
        File propFile = getSlingProperties(slingHome, staticProps);
        this.load(staticProps, propFile);

        // migrate old properties to new properties
        migrateProp(staticProps, "framework.cache.profiledir", Constants.FRAMEWORK_STORAGE);
        migrateProp(staticProps, "sling.osgi-core-packages", "osgi-core-packages");
        migrateProp(staticProps, "sling.osgi-compendium-services", "osgi-compendium-services");

        // migrate initial start level property: Felix used to have
        // framework.startlevel.framework, later moved to org.osgi.framework.startlevel
        // and finally now uses org.osgi.framework.startlevel.beginning as
        // speced in the latest R 4.2 draft (2009/03/10). We first check the
        // intermediate Felix property, then the initial property, thus allowing
        // the older (and more probable value) to win
        migrateProp(staticProps, "org.osgi.framework.startlevel", Constants.FRAMEWORK_BEGINNING_STARTLEVEL);
        migrateProp(staticProps, "framework.startlevel.framework", Constants.FRAMEWORK_BEGINNING_STARTLEVEL);

        // create a copy of the properties to perform variable substitution
        final Map<String, String> runtimeProps = new HashMap<String, String>();
        runtimeProps.putAll(staticProps);

        // check system properties for any overrides (except sling.home !)
        String ignoreSystemProperties = runtimeProps.get(SLING_IGNORE_SYSTEM_PROPERTIES);
        if (!"true".equalsIgnoreCase(ignoreSystemProperties)) {
            for (String name : runtimeProps.keySet()) {
                String sysProp = System.getProperty(name);
                if (sysProp != null) {
                    runtimeProps.put(name, sysProp);
                }
            }
        }

        // resolve inclusions again
        this.loadIncludes(runtimeProps, slingHome);

        // overwrite properties, this is not persisted as such
        this.loadPropertiesOverride(runtimeProps);

        // resolve boot delegation and system packages
        this.resolve(runtimeProps, "org.osgi.framework.bootdelegation",
            "sling.bootdelegation.");
        this.resolve(runtimeProps, "org.osgi.framework.system.packages",
            "sling.system.packages.");

        // reset back the sling home property
        // might have been overwritten by system properties, included
        // files or the sling.properties file
        staticProps.put(SharedConstants.SLING_HOME, slingHome);
        runtimeProps.put(SharedConstants.SLING_HOME, slingHome);
        runtimeProps.put(SLING_HOME_URL, slingHomeFile.toURI().toString());

        // add property file locations
        runtimeProps.put(SharedConstants.SLING_PROPERTIES, propFile.getAbsolutePath());
        runtimeProps.put(SharedConstants.SLING_PROPERTIES_URL, propFile.toURI().toString());

        // Perform variable substitution for system properties.
        for (Entry<String, String> entry : runtimeProps.entrySet()) {
            entry.setValue(substVars(entry.getValue(), entry.getKey(), null,
                runtimeProps));
        }

        // look for context:/ URLs to substitute
        for (Entry<String, String> entry : runtimeProps.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue();
            if (value != null && value.startsWith("context:/")) {
                String path = value.substring("context:/".length() - 1);

                InputStream src = this.resourceProvider.getResourceAsStream(path);
                if (src != null) {
                    File target = new File(slingHome, path);
                    OutputStream dest = null;
                    try {
                        // only copy file if not existing
                        if (!target.exists()) {
                            target.getParentFile().mkdirs();
                            dest = new FileOutputStream(target);
                            byte[] buf = new byte[2048];
                            int rd;
                            while ((rd = src.read(buf)) >= 0) {
                                dest.write(buf, 0, rd);
                            }
                        }

                        // after copying replace property and add url property
                        entry.setValue(target.getAbsolutePath());

                        // also set the new property on the unsubstituted props
                        staticProps.put(name, "${sling.home}" + path);

                    } catch (IOException ioe) {
                        this.logger.log(Logger.LOG_ERROR, "Cannot copy file "
                            + value + " to " + target, ioe);
                    } finally {
                        if (dest != null) {
                            try {
                                dest.close();
                            } catch (IOException ignore) {
                            }
                        }
                        try {
                            src.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            }
        }

        // write the unsubstituted properties back to the overlay file
        OutputStream os = null;
        try {
            // ensure parent folder(s)
            propFile.getParentFile().mkdirs();

            os = new FileOutputStream(propFile);

            // copy the values into a temporary properties structure to store
            Properties tmp = new Properties();
            tmp.putAll(staticProps);

            // remove properties where overlay makes no sense
            tmp.remove(SharedConstants.SLING_HOME);
            tmp.remove(SharedConstants.SLING_LAUNCHPAD);
            tmp.remove(SharedConstants.SLING_PROPERTIES);

            tmp.store(os, "Overlay properties for configuration");
        } catch (Exception ex) {
            this.logger.log(Logger.LOG_ERROR,
                "Error loading overlay properties from " + propFile, ex);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex2) {
                    // Nothing we can do.
                }
            }
        }

        return runtimeProps;
    }

    /**
     * Scans the properties for any properties starting with the given
     * prefix (e.g. sling.bootdelegation.).
     *

     *
Each such property is checked, whether it actually starts with
     * prefixclass.. If so, the rest of the property
     * name is assumed to be a fully qualified class name which is check,
     * whether it is visible. If so, the value of the property is appended to
     * the value of the osgiProp. If the class cannot be loaded,
     * the property is ignored.
     *
Otherwise, if the property does not contain a fully qualified class
     * name, the value of the property is simply appended to the
     * osgiProp.
     *

     *
     * @param props The Properties to be scanned.
     * @param osgiProp The name of the property in props to which
     *            any matching property values are appended.
     * @param prefix The prefix of properties to handle.
     */
    private void resolve(Map<String, String> props, String osgiProp,
            String prefix) {
        final String propVal = props.get(osgiProp);
        StringBuffer prop = new StringBuffer(propVal == null ? "" : propVal);
        boolean mod = false;
        for (Entry<String, String> pEntry : props.entrySet()) {
            String key = pEntry.getKey();
            if (key.startsWith(prefix)) {
                if (key.indexOf("class.") == prefix.length()) {
                    // prefix is followed by checker class name
                    String className = key.substring(prefix.length()
                        + "class.".length());
                    try {
                        this.getClass().getClassLoader().loadClass(className);
                    } catch (Throwable t) {
                        // don't really care, but class checking failed, so we
                        // do not add
                        this.logger.log(Logger.LOG_DEBUG, "Class " + className
                            + " not found. Ignoring '" + pEntry.getValue()
                            + "' for property " + osgiProp);
                        continue;
                    }
                }

                // get here if class is known or no checker class
                this.logger.log(Logger.LOG_DEBUG, "Adding '"
                    + pEntry.getValue() + "' to property " + osgiProp);
                if (prop.length() > 0) {
                    prop.append(',');
                }
                prop.append(pEntry.getValue());
                mod = true;
            }
        }

        // replace the property with the modified property
        if (mod) {
            this.logger.log(Logger.LOG_DEBUG, "Setting property " + osgiProp
                + " to " + prop.toString());
            props.put(osgiProp, prop.toString());
        }
    }

    /**
     * Converts an old Felix framework property into a new (standard or modified
     * Felix framework) property. If a property named oldName does
     * not exist in the props map, the map is not modified. If such
     * a property exists it is removed and add to the map with the
     * newName key. If both properties oldName and
     * newName exist, the property newName is replaced
     * with the value of the property oldName.
     *
     * @param props The map of properties containing the property to rename
     * @param oldName The old key of the property value
     * @param newName The new key of the property value
     */
    private void migrateProp(Map<String, String> props, String oldName,
            String newName) {
        String propValue = props.remove(oldName);
        if (propValue != null) {
            String previousNewValue = props.put(newName, propValue);
            if (previousNewValue != null) {
                logger.log(Logger.LOG_WARNING, "Old value (" + previousNewValue
                    + ") of property " + newName + " by value: " + propValue);
            } else {
                logger.log(Logger.LOG_INFO, "Property " + oldName + " ("
                    + propValue + ") renamed to " + newName);
            }
        } else {
            logger.log(Logger.LOG_DEBUG, "Property " + oldName
                + " does not exist, nothing to do");
        }
    }

    private void setInstallBundles(Map<String, String> props) {
        String prefix = "sling.install.";
        Set<String> levels = new TreeSet<String>();
        for (String key : props.keySet()) {
            if (key.startsWith(prefix)) {
                levels.add(key.substring(prefix.length()));
            }
        }

        StringBuffer buf = new StringBuffer();
        for (String level : levels) {
            if (buf.length() > 0) {
                buf.append(',');
            }
            buf.append(level);
        }

        props.put(prefix + "bundles", buf.toString());
    }

    // ---------- Extension support --------------------------------------------

    /**
     * Loads additional properties into the properties object.
     *

     * This implementation does nothing and may be overwritten by extensions
     * requiring additional properties to be set.
     *

     * This method is called when the servlet is initialized to prepare the
     * configuration for Felix. Implementations may add
     * properties from implementation specific sources. Properties added here
     * overwrite properties loaded from the default properties file and may be
     * overwritten by parameters set in the web application.
     *

     * The properties object has not undergone variable
     * substition and properties added by this method may also contain values
     * refererring to other properties.
     *

     * The properties added in this method will not be persisted in the
     * sling.properties file in the sling.home
     * directory.
     *
     * @param properties The Properties object to which custom
     *            properties may be added.
     */
    protected void loadPropertiesOverride(@SuppressWarnings("unused") Map<String, String> properties) {
    }

    /**
     * Returns the BundleContext of the system bundle of the OSGi
     * framework launched by this servlet. This method only returns a non-null
     * object after the system bundle of the framework has been started and
     * before it is being stopped.
     */
    public final BundleContext getBundleContext() {
        return this.framework.getBundleContext();
    }

    // ---------- Property file support ----------------------------------------

    /**
     * Returns the abstract path name to the sling.properties file.
     */
    private File getSlingProperties(final String slingHome,
            final Map<String, String> properties) {
        final String prop = properties.get(SharedConstants.SLING_PROPERTIES);
        if (prop == null) {
            return new File(slingHome, CONFIG_PROPERTIES);
        }

        final File propFile = new File(prop);
        return propFile.isAbsolute() ? propFile : new File(slingHome, prop);
    }

    /**
     * Looks for sling.include and sling.include.*
     * properties in the props and loads properties form the
     * respective locations.
     *

     * Each sling.include (or sling.include.*)
     * property may contain a comma-separated list of resource and/or file names
     * to be loaded from. The includes are loaded in alphabetical order of the
     * property names.
     *

     * Each reasource path is first tried to be loaded through the
     * {@link #resourceProvider}. If that fails, the resource path is tested as
     * a file. If relative slingHome is used as the parent if not
     * null, otherwise the current working directory is used as
     * the parent.
     *

     * Any non-existing resource is silently ignored.
     *

     * When the method returns, the sling.include and
     * sling.include.* properties are not contained in the
     * props any more.
     *
     * @param props The Properties containing the
     *            sling.include and sling.include.*
     *            properties. This is also the destination for the new
     *            properties loaded.
     * @param slingHome The parent directory used to resolve relative path names
     *            if loading from a file. This may be null in
     *            which case the current working directory is used as the
     *            parent.
     */
    private void loadIncludes(Map<String, String> props, String slingHome) {
        // Build the sort map of include properties first
        // and remove include elements from the properties
        SortedMap<String, String> includes = new TreeMap<String, String>();
        for (Iterator<Entry<String, String>> pi = props.entrySet().iterator(); pi.hasNext();) {
            Entry<String, String> entry = pi.next();
            if (entry.getKey().startsWith("sling.include.")
                || entry.getKey().equals("sling.include")) {
                includes.put(entry.getKey(), entry.getValue());
                pi.remove();
            }
        }

        for (Iterator<Entry<String, String>> ii = includes.entrySet().iterator(); ii.hasNext();) {
            Map.Entry<String, String> entry = ii.next();
            String key = entry.getKey();
            String include = entry.getValue();

            // ensure variable resolution on this property
            include = substVars(include, key, null, props);

            StringTokenizer tokener = new StringTokenizer(include, ",");
            while (tokener.hasMoreTokens()) {
                String file = tokener.nextToken().trim();
                InputStream is = this.resourceProvider.getResourceAsStream(file);
                try {
                    if (is == null && slingHome != null) {
                        File resFile = new File(file);
                        if (!resFile.isAbsolute()) {
                            resFile = new File(slingHome, file);
                        }
                        if (resFile.canRead()) {
                            is = new FileInputStream(resFile);
                            file = resFile.getAbsolutePath(); // for logging
                        }
                    }

                    if (is != null) {
                        this.load(props, is);
                    }
                } catch (IOException ioe) {
                    this.logger.log(Logger.LOG_ERROR,
                        "Error loading config properties from " + file, ioe);
                } finally {
                    if ( is != null ) {
                        try {
                            is.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            }
        }
    }

    /**
     * Load properties from the given resource file, which is accessed through
     * the {@link #resourceProvider}. If the resource does not exist, nothing
     * is loaded.
     *
     * @param props The Properties into which the loaded
     *            properties are loaded
     * @param resource The resource from which to load the resources
     */
    private void load(Map<String, String> props, String resource) {
        InputStream is = this.resourceProvider.getResourceAsStream(resource);
        if (is != null) {
            try {
                this.load(props, is);
            } catch (IOException ioe) {
                this.logger.log(Logger.LOG_ERROR,
                    "Error loading config properties from " + resource, ioe);
            } finally {
                try {
                    is.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    /**
     * Load properties from the given file. If the resource cannot be read from
     * (e.g. because it does not exist), nothing is loaded.
     *
     * @param props The Properties into which the loaded
     *            properties are loaded
     * @param file The File to load the properties from
     */
    private void load(Map<String, String> props, File file) {
        if (file != null && file.canRead()) {
            try {
                this.load(props, new FileInputStream(file));
            } catch (IOException ioe) {
                this.logger.log(Logger.LOG_ERROR,
                    "Error loading config properties from "
                        + file.getAbsolutePath(), ioe);
            }
        }
    }

    private void load(Map<String, String> props, InputStream ins)
            throws IOException {
        try {
            Properties tmp = new Properties();
            tmp.load(ins);

            for (Map.Entry<Object, Object> entry : tmp.entrySet()) {
                final String value = (String)entry.getValue();
                props.put((String) entry.getKey(), (value == null ? null : value.trim()));
            }
        } finally {
            try {
                ins.close();
            } catch (IOException ioe2) {
                // ignore
            }
        }
    }

    // ---------- Property file variable substition support --------------------

    /**
     * The starting delimiter of variable names (value is "${").
     */
    private static final String DELIM_START = "${";

    /**
     * The ending delimiter of variable names (value is "}").
     */
    private static final String DELIM_STOP = "}";

    /**
     * This method performs property variable substitution on the specified
     * value. If the specified value contains the syntax
     * <tt>${<prop-name>}</tt>, where <tt><prop-name></tt>
     * refers to either a configuration property or a system property, then the
     * corresponding property value is substituted for the variable placeholder.
     * Multiple variable placeholders may exist in the specified value as well
     * as nested variable placeholders, which are substituted from inner most to
     * outer most. Configuration properties override system properties.
     *
     * NOTE - this is a verbatim copy of the same-named method
     * in o.a.s.launchpad.webapp.SlingServlet. Please keep them in sync.
     *
     * @param val The string on which to perform property substitution.
     * @param currentKey The key of the property being evaluated used to detect
     *            cycles.
     * @param cycleMap Map of variable references used to detect nested cycles.
     * @param configProps Set of configuration properties.
     * @return The value of the specified string after system property
     *         substitution.
     * @throws IllegalArgumentException If there was a syntax error in the
     *             property placeholder syntax or a recursive variable
     *             reference.
     */
    private static String substVars(String val, String currentKey,
            Map<String, String> cycleMap, Map<String, String> configProps)
            throws IllegalArgumentException {
        // If there is currently no cycle map, then create
        // one for detecting cycles for this invocation.
        if (cycleMap == null) {
            cycleMap = new HashMap<String, String>();
        }

        // Put the current key in the cycle map.
        cycleMap.put(currentKey, currentKey);

        // Assume we have a value that is something like:
        // "leading ${foo.${bar}} middle ${baz} trailing"

        // Find the first ending '}' variable delimiter, which
        // will correspond to the first deepest nested variable
        // placeholder.
        int stopDelim = val.indexOf(DELIM_STOP);

        // Find the matching starting "${" variable delimiter
        // by looping until we find a start delimiter that is
        // greater than the stop delimiter we have found.
        int startDelim = val.indexOf(DELIM_START);
        while (stopDelim >= 0) {
            int idx = val.indexOf(DELIM_START, startDelim
                + DELIM_START.length());
            if ((idx < 0) || (idx > stopDelim)) {
                break;
            } else if (idx < stopDelim) {
                startDelim = idx;
            }
        }

        // If we do not have a start or stop delimiter, then just
        // return the existing value.
        if ((startDelim < 0) && (stopDelim < 0)) {
            return val;
        }
        // At this point, we found a stop delimiter without a start,
        // so throw an exception.
        else if (((startDelim < 0) || (startDelim > stopDelim))
            && (stopDelim >= 0)) {
            throw new IllegalArgumentException(
                "stop delimiter with no start delimiter: " + val);
        }

        // At this point, we have found a variable placeholder so
        // we must perform a variable substitution on it.
        // Using the start and stop delimiter indices, extract
        // the first, deepest nested variable placeholder.
        String variable = val.substring(startDelim + DELIM_START.length(),
            stopDelim);

        // Verify that this is not a recursive variable reference.
        if (cycleMap.get(variable) != null) {
            throw new IllegalArgumentException("recursive variable reference: "
                + variable);
        }

        // Get the value of the deepest nested variable placeholder.
        // Try to configuration properties first.
        String substValue = (configProps != null)
                ? configProps.get(variable)
                : null;
        if (substValue == null) {
            // Ignore unknown property values.
            substValue = System.getProperty(variable, "");
        }

        // Remove the found variable from the cycle map, since
        // it may appear more than once in the value and we don't
        // want such situations to appear as a recursive reference.
        cycleMap.remove(variable);

        // Append the leading characters, the substituted value of
        // the variable, and the trailing characters to get the new
        // value.
        val = val.substring(0, startDelim) + substValue
            + val.substring(stopDelim + DELIM_STOP.length(), val.length());

        // Now perform substitution again, since there could still
        // be substitutions to make.
        val = substVars(val, currentKey, cycleMap, configProps);

        // Return the value.
        return val;
    }

    private void copyBootstrapCommandFile(final Map<String, String> props) {
        // check last modification date
        final URL url = this.resourceProvider.getResource(BootstrapInstaller.BOOTSTRAP_CMD_FILENAME);
        if ( url != null ) {
            this.logger.log(Logger.LOG_DEBUG, "Checking last modification date of bootstrap command file.");
            InputStream is = null;
            OutputStream os = null;
            try {
                final long lastModified = url.openConnection().getLastModified();
                final File launchpadHome = new File(props.get(SharedConstants.SLING_LAUNCHPAD));
                final File cmdFile = new File(launchpadHome, BootstrapInstaller.BOOTSTRAP_CMD_FILENAME);
                boolean copyFile = true;
                if ( cmdFile.exists() && cmdFile.lastModified() >= lastModified ) {
                    copyFile = false;
                }
                if ( copyFile ) {
                    this.logger.log(Logger.LOG_INFO, "Copying bootstrap command file.");
                    is = this.resourceProvider.getResourceAsStream(BootstrapInstaller.BOOTSTRAP_CMD_FILENAME);
                    os = new FileOutputStream(cmdFile);
                    final byte[] buffer = new byte[2048];
                    int l;
                    while ( (l = is.read(buffer, 0, buffer.length)) != -1 ) {
                        os.write(buffer, 0, l);
                    }
                }

            } catch (final IOException ioe) {
                this.logger.log(Logger.LOG_INFO, "Ignoring exception during processing of bootstrap command file.", ioe);
            } finally {
                if ( is != null ) {
                    try { is.close(); } catch (final IOException ignore) {}
                }
                if ( os != null ) {
                    try { os.close(); } catch (final IOException ignore) {}
                }
            }
        } else {
            this.logger.log(Logger.LOG_DEBUG, "Bootstrap command file not found.");
        }

    }
}


text:
import bottle
import funkcije

bottle.debug(True)

@bottle.route('/')
@bottle.view('homepage')
def homepage():
    return "zivjo!"

bottle.run(host='localhost', port=8080)


text:
module MVC {
    "use strict";

    export interface IAppConfig {
        DefaultAction: string;
        UniqueIdentifier: string;
        AppNamespace: Object;
        RootPath: string;
    }

    export class AppConfigBase extends CoreObject implements IAppConfig {
        private uniqueIdentifier: string;
        public constructor() {
            super();

            this.uniqueIdentifier = Date.now().toString();
        }

        public get DefaultAction(): string {
            return "Index";
        }

        public get UniqueIdentifier(): string {
            return this.uniqueIdentifier;
        }

        public get AppNamespace(): Object {
            return {};
        }

        public get RootPath(): string {
            return "/";
        }
    }
}


text:
#include "webrtc/base/helpers.h"

#include <limits>
#include <memory>

#if defined(FEATURE_ENABLE_SSL)
#include "webrtc/base/sslconfig.h"
#if defined(SSL_USE_OPENSSL)
#include <openssl/rand.h>
#else
#if defined(WEBRTC_WIN)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <ntsecapi.h>
#endif  // WEBRTC_WIN
#endif  // else
#endif  // FEATURE_ENABLED_SSL

#include "webrtc/base/base64.h"
#include "webrtc/base/basictypes.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/timeutils.h"

// Protect against max macro inclusion.
#undef max

namespace rtc {

// Base class for RNG implementations.
class RandomGenerator {
 public:
  virtual ~RandomGenerator() {}
  virtual bool Init(const void* seed, size_t len) = 0;
  virtual bool Generate(void* buf, size_t len) = 0;
};

#if defined(SSL_USE_OPENSSL)
// The OpenSSL RNG.
class SecureRandomGenerator : public RandomGenerator {
 public:
  SecureRandomGenerator() {}
  ~SecureRandomGenerator() override {}
  bool Init(const void* seed, size_t len) override { return true; }
  bool Generate(void* buf, size_t len) override {
    return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
  }
};

#elif defined(SSL_USE_NSS_RNG)
// The NSS RNG.
class SecureRandomGenerator : public RandomGenerator {
 public:
  SecureRandomGenerator() {}
  ~SecureRandomGenerator() override {}
  bool Init(const void* seed, size_t len) override { return true; }
  bool Generate(void* buf, size_t len) override {
    return (PK11_GenerateRandom(reinterpret_cast<unsigned char*>(buf),
                                static_cast<int>(len)) == SECSuccess);
  }
};

#else
#if defined(WEBRTC_WIN)
class SecureRandomGenerator : public RandomGenerator {
 public:
  SecureRandomGenerator() : advapi32_(NULL), rtl_gen_random_(NULL) {}
  ~SecureRandomGenerator() {
    FreeLibrary(advapi32_);
  }

  virtual bool Init(const void* seed, size_t seed_len) {
    // We don't do any additional seeding on Win32, we just use the CryptoAPI
    // RNG (which is exposed as a hidden function off of ADVAPI32 so that we
    // don't need to drag in all of CryptoAPI)
    if (rtl_gen_random_) {
      return true;
    }

    advapi32_ = LoadLibrary(L"advapi32.dll");
    if (!advapi32_) {
      return false;
    }

    rtl_gen_random_ = reinterpret_cast<RtlGenRandomProc>(
        GetProcAddress(advapi32_, "SystemFunction036"));
    if (!rtl_gen_random_) {
      FreeLibrary(advapi32_);
      return false;
    }

    return true;
  }
  virtual bool Generate(void* buf, size_t len) {
    if (!rtl_gen_random_ && !Init(NULL, 0)) {
      return false;
    }
    return (rtl_gen_random_(buf, static_cast<int>(len)) != FALSE);
  }

 private:
  typedef BOOL (WINAPI *RtlGenRandomProc)(PVOID, ULONG);
  HINSTANCE advapi32_;
  RtlGenRandomProc rtl_gen_random_;
};

#elif !defined(FEATURE_ENABLE_SSL)

// No SSL implementation -- use rand()
class SecureRandomGenerator : public RandomGenerator {
 public:
  virtual bool Init(const void* seed, size_t len) {
    if (len >= 4) {
      srand(*reinterpret_cast<const int*>(seed));
    } else {
      srand(*reinterpret_cast<const char*>(seed));
    }
    return true;
  }
  virtual bool Generate(void* buf, size_t len) {
    char* bytes = reinterpret_cast<char*>(buf);
    for (size_t i = 0; i < len; ++i) {
      bytes[i] = static_cast<char>(rand());
    }
    return true;
  }
};

#else

#error No SSL implementation has been selected!

#endif  // WEBRTC_WIN
#endif

// A test random generator, for predictable output.
class TestRandomGenerator : public RandomGenerator {
 public:
  TestRandomGenerator() : seed_(7) {
  }
  ~TestRandomGenerator() override {
  }
  bool Init(const void* seed, size_t len) override { return true; }
  bool Generate(void* buf, size_t len) override {
    for (size_t i = 0; i < len; ++i) {
      static_cast<uint8_t*>(buf)[i] = static_cast<uint8_t>(GetRandom());
    }
    return true;
  }

 private:
  int GetRandom() {
    return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
  }
  int seed_;
};

namespace {

// TODO: Use Base64::Base64Table instead.
static const char kBase64[64] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

static const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
                              '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

static const char kUuidDigit17[4] = {'8', '9', 'a', 'b'};

// This round about way of creating a global RNG is to safe-guard against
// indeterminant static initialization order.
std::unique_ptr<RandomGenerator>& GetGlobalRng() {
  RTC_DEFINE_STATIC_LOCAL(std::unique_ptr<RandomGenerator>, global_rng,
                          (new SecureRandomGenerator()));
  return global_rng;
}

RandomGenerator& Rng() {
  return *GetGlobalRng();
}

}  // namespace

void SetRandomTestMode(bool test) {
  if (!test) {
    GetGlobalRng().reset(new SecureRandomGenerator());
  } else {
    GetGlobalRng().reset(new TestRandomGenerator());
  }
}

bool InitRandom(int seed) {
  return InitRandom(reinterpret_cast<const char*>(&seed), sizeof(seed));
}

bool InitRandom(const char* seed, size_t len) {
  if (!Rng().Init(seed, len)) {
    LOG(LS_ERROR) << "Failed to init random generator!";
    return false;
  }
  return true;
}

std::string CreateRandomString(size_t len) {
  std::string str;
  CreateRandomString(len, &str);
  return str;
}

bool CreateRandomString(size_t len,
                        const char* table, int table_size,
                        std::string* str) {
  str->clear();
  std::unique_ptr<uint8_t[]> bytes(new uint8_t[len]);
  if (!Rng().Generate(bytes.get(), len)) {
    LOG(LS_ERROR) << "Failed to generate random string!";
    return false;
  }
  str->reserve(len);
  for (size_t i = 0; i < len; ++i) {
    str->push_back(table[bytes[i] % table_size]);
  }
  return true;
}

bool CreateRandomString(size_t len, std::string* str) {
  return CreateRandomString(len, kBase64, 64, str);
}

bool CreateRandomString(size_t len, const std::string& table,
                        std::string* str) {
  return CreateRandomString(len, table.c_str(),
                            static_cast<int>(table.size()), str);
}

// Version 4 UUID is of the form:
// xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
// Where 'x' is a hex digit, and 'y' is 8, 9, a or b.
std::string CreateRandomUuid() {
  std::string str;
  std::unique_ptr<uint8_t[]> bytes(new uint8_t[31]);
  if (!Rng().Generate(bytes.get(), 31)) {
    LOG(LS_ERROR) << "Failed to generate random string!";
    return str;
  }
  str.reserve(36);
  for (size_t i = 0; i < 8; ++i) {
    str.push_back(kHex[bytes[i] % 16]);
  }
  str.push_back('-');
  for (size_t i = 8; i < 12; ++i) {
    str.push_back(kHex[bytes[i] % 16]);
  }
  str.push_back('-');
  str.push_back('4');
  for (size_t i = 12; i < 15; ++i) {
    str.push_back(kHex[bytes[i] % 16]);
  }
  str.push_back('-');
  str.push_back(kUuidDigit17[bytes[15] % 4]);
  for (size_t i = 16; i < 19; ++i) {
    str.push_back(kHex[bytes[i] % 16]);
  }
  str.push_back('-');
  for (size_t i = 19; i < 31; ++i) {
    str.push_back(kHex[bytes[i] % 16]);
  }
  return str;
}

uint32_t CreateRandomId() {
  uint32_t id;
  if (!Rng().Generate(&id, sizeof(id))) {
    LOG(LS_ERROR) << "Failed to generate random id!";
  }
  return id;
}

uint64_t CreateRandomId64() {
  return static_cast<uint64_t>(CreateRandomId()) << 32 | CreateRandomId();
}

uint32_t CreateRandomNonZeroId() {
  uint32_t id;
  do {
    id = CreateRandomId();
  } while (id == 0);
  return id;
}

double CreateRandomDouble() {
  return CreateRandomId() / (std::numeric_limits<uint32_t>::max() +
                             std::numeric_limits<double>::epsilon());
}

}  // namespace rtc


text:
    <button type="button" class="close" ng-click="cancel()" aria-label="Close">×</button>

CreateEdit Source oh the places you will go!

    <form name="createForm" class="form-horizontal" role="form" novalidate>

                Label

                <input name="label" ng-model="source.label" placeholder="Label" class="form-control" required/>

You must enter an source label

                Description

                <textarea name="comments" ng-model="source.description" placeholder="Something elegant" class="form-control" required></textarea>

You must enter description

                Plugin

                <select class="form-control" ng-model="source.plugin" ng-options="plugin.title for plugin in plugins" required></select>

            <ng-form name="subForm" class="form-horizontal" role="form" novalidate>

                        {{ item.name | titleCase }}

                        <input name="sub" ng-if="item.type == 'int'" type="number" ng-pattern="/^[0-9]{12,12}$/" class="form-control" ng-model="item.value"/>
                        <select name="sub" ng-if="item.type == 'select'" class="form-control" ng-options="i for i in item.available" ng-model="item.value"></select>
                        <input name="sub" ng-if="item.type == 'bool'" class="form-control" type="checkbox" ng-model="item.value">
                        <input name="sub" ng-if="item.type == 'str'" type="text" class="form-control" ng-model="item.value"/>

{{ item.helpMessage }}

            </ng-form>

    </form>

    <button ng-click="save(source)" type="submit" ng-disabled="createForm.$invalid" class="btn btn-primary">Save</button>
    <button ng-click="cancel()" class="btn btn-danger">Cancel</button>


text:
import {SpecDirectory} from '../spec-directory';

// The Sass compiler is expected to succeed.
interface SuccessResult {
  isSuccess: true;
  output: string;
  warning?: string;
}

// The Sass compiler is expected to fail.
interface ErrorResult {
  isSuccess: false;
  error: string;
}

/** The result of compiling a test case. */
export type SassResult = SuccessResult | ErrorResult;

/**
 * The expected result of compiling a test case. This also includes the
 * possibility of a test case that doesn't set any expectations for its output.
 */
export type ExpectedSassResult = SassResult | {isSuccess: null};

type FailureType =
  // | "todo_warning_nonexistent"
  // | "conflicting_files"
  | 'missing_output'
  | 'unexpected_error'
  | 'unexpected_success'
  | 'output_difference'
  | 'error_difference'
  | 'warning_difference'
  | 'unnecessary_todo';

// TODO split these up into separate types (e.g. `FailureResult | ErrorResult`).
// Spliting up the properties into a union type will be cumbersome when
// results are used as part of a test case across multiple methods (e.g. in `Interactor`).
// When calling `TestResult.result()` across multiple methods with `TestResult` as a signature,
// we need to check each time that we the right type of result before using any sub-properties.
/**
 * The result of a test execution, along with metadata for failures and errors
 */
export interface TestResult {
  type: 'pass' | 'fail' | 'todo' | 'skip' | 'error';
  // If `fail`, the type of failure, message, and possible diff
  failureType?: FailureType;
  message?: string;
  diff?: string;
  // If `error`, the thrown error
  error?: Error;
}

function makeFailureFactory(failureType: FailureType, message: string) {
  return function (diff?: string): TestResult {
    return {
      type: 'fail',
      failureType,
      message,
      diff,
    };
  };
}

export const failures = {
  UnexpectedError: makeFailureFactory(
    'unexpected_error',
    'Test case should succeed but it did not'
  ),
  UnexpectedSuccess: makeFailureFactory(
    'unexpected_success',
    'Expected test to fail but it did not'
  ),
  OutputDifference: makeFailureFactory(
    'output_difference',
    'Expected did not match output'
  ),
  WarningDifference: makeFailureFactory(
    'warning_difference',
    'Expected did not match warning'
  ),
  ErrorDifference: makeFailureFactory(
    'error_difference',
    'Expected did not match error'
  ),
  UnnecessaryTodo: makeFailureFactory(
    'unnecessary_todo',
    'Expected test marked TODO to fail but it passed'
  ),
  MissingOutput: makeFailureFactory(
    'missing_output',
    'Test case is missing an output file'
  ),
};

export function getExpectedFiles(impl?: string): string[] {
  return impl
    ? [`output-${impl}.css`, `warning-${impl}`, `error-${impl}`]
    : ['output.css', 'warning', 'error'];
}

// Overwrite the set of results to be equal to the provided result
export async function overwriteResults(
  dir: SpecDirectory,
  actual: SassResult,
  impl?: string
): Promise<void> {
  const [outputFile, warningFile, errorFile] = getExpectedFiles(impl);
  if (actual.isSuccess) {
    await Promise.all([
      dir.writeFile(outputFile, actual.output),
      actual.warning
        ? dir.writeFile(warningFile, actual.warning)
        : dir.removeFile(warningFile),
      dir.removeFile(errorFile),
    ]);
  } else {
    await Promise.all([
      dir.writeFile(errorFile, actual.error),
      dir.removeFile(outputFile),
      dir.removeFile(warningFile),
    ]);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="backgroudColor">#222222</color>
    <color name="anonFieldColor">#2a2a2a</color>
    <color name="redFieldColor">#d55336</color>
    <color name="blueFieldColor">#35b8d5</color>
    <color name="white">#FFFFFF</color>
</resources>


text:
describe("Dashboard Pipeline Trigger With Options Modal Body", () => {
  const m                           = require("mithril");
  const Stream                      = require("mithril/stream");
  const Modal                       = require('views/shared/new_modal');
  const TriggerWithOptionsModalBody = require("views/dashboard/trigger_with_options/modal_body");
  const SparkRoutes                 = require('helpers/spark_routes');
  require('jasmine-ajax');

  const TriggerWithOptionsVM   = require('views/dashboard/models/trigger_with_options_vm');
  const TriggerWithOptionsInfo = require("models/dashboard/trigger_with_options_info");

  let $root, root;
  beforeEach(() => {
    [$root, root] = window.createDomElementForTest();
  });
  afterEach(window.destroyDomElementForTest);

  let triggerWithOptionsInfo, vm;
  const pipelineName = 'up42';
  beforeEach(mount);

  afterEach(unmount);

  it("should render pipeline trigger with options information", () => {
    expect($root.find('.pipeline-trigger-with-options')).toBeInDOM();
  });

  it("shoould render tab headings", () => {
    const headings = $root.find('.pipeline_options-heading li');

    expect(headings.length).toBe(3);
    expect(headings.get(0)).toContainText('Materials');
    expect(headings.get(1)).toContainText('Environment variables');
    expect(headings.get(2)).toContainText('Secure Environment variables');
  });

  it("should render materials section", () => {
    expect($root.find('.material-for-trigger')).toBeInDOM();
  });

  it("should render environment variables section", () => {
    expect($root.find('.environment-variables.plain')).toBeInDOM();
  });

  it("should render secure environment variables section", () => {
    expect($root.find('.environment-variables.secure')).toBeInDOM();
  });

  it("should show select materials tab by default", () => {
    expect($root.find('.pipeline_options-heading li').get(0)).toHaveClass('active');

    const materialsContent = $root.find('.pipeline_options-body .h-tab_content:first');
    const envContent       = $root.find('.pipeline_options-body .h-tab_content:nth-child(2)');
    const secureEnvContent = $root.find('.pipeline_options-body .h-tab_content:nth-child(3)');

    expect(materialsContent).not.toHaveClass('hidden');
    expect(envContent).toHaveClass('hidden');
    expect(secureEnvContent).toHaveClass('hidden');
  });

  it("should show appropriate content based on tab selected", () => {
    const materialsContent = $root.find('.pipeline_options-body .h-tab_content:first');
    const envContent       = $root.find('.pipeline_options-body .h-tab_content:nth-child(2)');
    const secureEnvContent = $root.find('.pipeline_options-body .h-tab_content:nth-child(3)');

    expect($root.find('.pipeline_options-heading li').get(0)).toHaveClass('active');

    expect(materialsContent).not.toHaveClass('hidden');
    expect(envContent).toHaveClass('hidden');
    expect(secureEnvContent).toHaveClass('hidden');

    $root.find('.pipeline_options-heading li').get(1).click();

    expect($root.find('.pipeline_options-heading li').get(1)).toHaveClass('active');

    expect(materialsContent).toHaveClass('hidden');
    expect(envContent).not.toHaveClass('hidden');
    expect(secureEnvContent).toHaveClass('hidden');
  });

  it('should not render the environment variables tab and content if no environment variables are present', () => {
    triggerWithOptionsInfo(TriggerWithOptionsInfo.fromJSON({variables: [], materials: json.materials}));
    vm.initialize(triggerWithOptionsInfo());
    m.redraw();
    const headings = $root.find('.pipeline_options-heading li');

    expect(headings.length).toBe(1);
    expect(headings.get(0)).toContainText('Materials');
  });

  function mount() {
    jasmine.Ajax.install();
    stubMaterialSearch(json.materials[0].fingerprint);

    triggerWithOptionsInfo = Stream(TriggerWithOptionsInfo.fromJSON(json));
    vm                     = new TriggerWithOptionsVM();
    vm.initialize(triggerWithOptionsInfo());

    const searchVM = {
      [json.materials[0].name]: {
        performSearch:         jasmine.createSpy('performSearch'),
        searchText:            jasmine.createSpy('searchText'),
        searchInProgress:      jasmine.createSpy('searchInProgress'),
        materialSearchResults: jasmine.createSpy('materialSearchResult'),
        selectRevision:        jasmine.createSpy('selectRevision'),
        isRevisionSelected:      jasmine.createSpy('isRevisionSelected')
      }
    };

    m.mount(root, {
      view() {
        return m(TriggerWithOptionsModalBody, {
          triggerWithOptionsInfo,
          vm: Stream(vm),
          searchVM
        });
      }
    });
    m.redraw(true);
  }

  function unmount() {
    jasmine.Ajax.uninstall();
    Modal.destroyAll();
    m.mount(root, null);
    m.redraw();
  }

  const json = {
    "variables": [
      {
        "name":   "version",
        "secure": false,
        "value":  "asdf"
      },
      {
        "name":   "foobar",
        "secure": true
      }
    ],
    "materials": [
      {
        "type":        "Git",
        "name":        "https://github.com/ganeshspatil/gocd",
        "fingerprint": "3dcc10e7943de637211a4742342fe456ffbe832577bb377173007499434fd819",
        "revision":    {
          "date":              "2018-02-08T04:32:11Z",
          "user":              "Ganesh S Patil <ganeshpl@thoughtworks.com>",
          "comment":           "Refactor Pipeline Widget (#4311)\n\n* Extract out PipelineHeaderWidget and PipelineOperationsWidget into seperate msx files",
          "last_run_revision": "a2d23c5505ac571d9512bdf08d6287e47dcb52d5"
        }
      }
    ]
  };

  function stubMaterialSearch(fingerprint) {
    const url = SparkRoutes.pipelineMaterialSearchPath(pipelineName, fingerprint, "");

    jasmine.Ajax.stubRequest(url, undefined, 'GET').andReturn({
      status:          200,
      responseText:    JSON.stringify([]),
      responseHeaders: {'Content-Type': 'application/json'}
    });
  }
});