text:
namespace media {

namespace {

// Pattern decryption uses 16-byte blocks.
constexpr size_t kBlockSize = 16;

// Keys and IVs have to be 128 bits.
const std::array<uint8_t, 16> kKey = {0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
                                      0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                                      0x10, 0x11, 0x12, 0x13};

const std::array<uint8_t, 16> kIv = {0x20, 0x21, 0x22, 0x23, 0x24, 0x25,
                                     0x26, 0x27, 0x00, 0x00, 0x00, 0x00,
                                     0x00, 0x00, 0x00, 0x00};

const std::array<uint8_t, kBlockSize> kOneBlock = {'a', 'b', 'c', 'd', 'e', 'f',
                                                   'g', 'h', 'i', 'j', 'k', 'l',
                                                   'm', 'n', 'o', 'p'};

const std::array<uint8_t, 6> kPartialBlock = {'a', 'b', 'c', 'd', 'e', 'f'};
static_assert(base::size(kPartialBlock) != kBlockSize, "kPartialBlock wrong");

std::string MakeString(const std::vector<uint8_t>& chars) {
  return std::string(chars.begin(), chars.end());
}

// Combine multiple std::vector<uint8_t> into one.
std::vector<uint8_t> Combine(const std::vector<std::vector<uint8_t>>& inputs) {
  std::vector<uint8_t> result;
  for (const auto& input : inputs)
    result.insert(result.end(), input.begin(), input.end());

  return result;
}

// Extract the |n|th block of |input|. The first block is number 1.
std::vector<uint8_t> GetBlock(size_t n, const std::vector<uint8_t>& input) {
  DCHECK_LE(n, input.size() / kBlockSize);
  auto it = input.begin() + ((n - 1) * kBlockSize);
  return std::vector<uint8_t>(it, it + kBlockSize);
}

// Returns a std::vector<uint8_t> containing |count| copies of |input|.
std::vector<uint8_t> Repeat(const std::vector<uint8_t>& input, size_t count) {
  std::vector<uint8_t> result;
  for (size_t i = 0; i < count; ++i)
    result.insert(result.end(), input.begin(), input.end());
  return result;
}

}  // namespace

class CbcsDecryptorTest : public testing::Test {
 public:
  CbcsDecryptorTest()
      : key_(crypto::SymmetricKey::Import(
            crypto::SymmetricKey::AES,
            std::string(std::begin(kKey), std::end(kKey)))),
        iv_(std::begin(kIv), std::end(kIv)),
        one_block_(std::begin(kOneBlock), std::end(kOneBlock)),
        partial_block_(std::begin(kPartialBlock), std::end(kPartialBlock)) {}

  // Excrypt |original| using AES-CBC encryption with |key| and |iv|.
  std::vector<uint8_t> Encrypt(const std::vector<uint8_t>& original,
                               const crypto::SymmetricKey& key,
                               const std::string& iv) {
    // This code uses crypto::Encryptor to encrypt |original| rather than
    // calling EVP_EncryptInit_ex() / EVP_EncryptUpdate() / etc. This is done
    // for simplicity, as the crypto:: code wraps all the calls up nicely.
    // However, for AES-CBC encryption, the crypto:: code does add padding to
    // the output, which is simply stripped off.
    crypto::Encryptor encryptor;
    EXPECT_TRUE(encryptor.Init(&key, crypto::Encryptor::CBC, iv));

    std::string ciphertext;
    EXPECT_TRUE(encryptor.Encrypt(MakeString(original), &ciphertext));

    // CBC encyption adds a block of padding at the end, so discard it.
    DCHECK_GT(ciphertext.size(), original.size());
    ciphertext.resize(original.size());

    return std::vector<uint8_t>(ciphertext.begin(), ciphertext.end());
  }

  // Returns a 'cbcs' DecoderBuffer using the data and other parameters.
  scoped_refptr<DecoderBuffer> CreateEncryptedBuffer(
      const std::vector<uint8_t>& data,
      const std::string& iv,
      const std::vector<SubsampleEntry>& subsample_entries,
      base::Optional<EncryptionPattern> encryption_pattern) {
    EXPECT_FALSE(data.empty());
    EXPECT_FALSE(iv.empty());

    auto encrypted_buffer = DecoderBuffer::CopyFrom(data.data(), data.size());

    // Key_ID is never used.
    encrypted_buffer->set_decrypt_config(DecryptConfig::CreateCbcsConfig(
        "key_id", iv, subsample_entries, encryption_pattern));
    return encrypted_buffer;
  }

  // Calls DecryptCbcsBuffer() to decrypt |encrypted| using |key|,
  // and then returns the data in the decrypted buffer.
  std::vector<uint8_t> DecryptWithKey(scoped_refptr<DecoderBuffer> encrypted,
                                      const crypto::SymmetricKey& key) {
    auto decrypted = DecryptCbcsBuffer(*encrypted, key);

    std::vector<uint8_t> decrypted_data;
    if (decrypted.get()) {
      EXPECT_TRUE(decrypted->data_size());
      decrypted_data.assign(decrypted->data(),
                            decrypted->data() + decrypted->data_size());
    }

    return decrypted_data;
  }

  // Constants for testing.
  std::unique_ptr<crypto::SymmetricKey> key_;
  const std::string iv_;
  const std::vector<uint8_t> one_block_;
  const std::vector<uint8_t> partial_block_;
};

TEST_F(CbcsDecryptorTest, OneBlock) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);
  DCHECK_EQ(kBlockSize, encrypted_block.size());

  // Only 1 subsample, all encrypted data.
  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size()}};

  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(1, 9));
  EXPECT_EQ(one_block_, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, AdditionalData) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);
  DCHECK_EQ(kBlockSize, encrypted_block.size());

  // Only 1 subsample, all encrypted data.
  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size()}};

  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(1, 9));
  encrypted_buffer->set_timestamp(base::TimeDelta::FromDays(2));
  encrypted_buffer->set_duration(base::TimeDelta::FromMinutes(5));
  encrypted_buffer->set_is_key_frame(true);
  encrypted_buffer->CopySideDataFrom(encrypted_block.data(),
                                     encrypted_block.size());

  auto decrypted_buffer = DecryptCbcsBuffer(*encrypted_buffer, *key_);
  EXPECT_EQ(encrypted_buffer->timestamp(), decrypted_buffer->timestamp());
  EXPECT_EQ(encrypted_buffer->duration(), decrypted_buffer->duration());
  EXPECT_EQ(encrypted_buffer->end_of_stream(),
            decrypted_buffer->end_of_stream());
  EXPECT_EQ(encrypted_buffer->is_key_frame(), decrypted_buffer->is_key_frame());
  EXPECT_EQ(encrypted_buffer->side_data_size(),
            decrypted_buffer->side_data_size());
  EXPECT_TRUE(std::equal(
      encrypted_buffer->side_data(),
      encrypted_buffer->side_data() + encrypted_buffer->side_data_size(),
      decrypted_buffer->side_data(),
      decrypted_buffer->side_data() + encrypted_buffer->side_data_size()));
}

TEST_F(CbcsDecryptorTest, DifferentPattern) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);
  DCHECK_EQ(kBlockSize, encrypted_block.size());

  // Only 1 subsample, all encrypted data.
  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size()}};

  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(1, 0));
  EXPECT_EQ(one_block_, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, EmptyPattern) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);
  DCHECK_EQ(kBlockSize, encrypted_block.size());

  // Only 1 subsample, all encrypted data.
  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size()}};

  // Pattern 0:0 treats the buffer as all encrypted.
  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(0, 0));
  EXPECT_EQ(one_block_, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, PatternTooLarge) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);
  DCHECK_EQ(kBlockSize, encrypted_block.size());

  // Only 1 subsample, all encrypted data.
  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size()}};

  // Pattern 100:0 is too large, so decryption will fail.
  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(100, 0));
  EXPECT_EQ(std::vector<uint8_t>(), DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, NoSubsamples) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);
  DCHECK_EQ(kBlockSize, encrypted_block.size());

  std::vector<SubsampleEntry> subsamples = {};

  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(1, 9));
  EXPECT_EQ(one_block_, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, BadSubsamples) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);

  // Subsample size > data size.
  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size() + 1}};

  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(1, 0));
  EXPECT_EQ(std::vector<uint8_t>(), DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, InvalidIv) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);

  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size()}};

  // Use an invalid IV for decryption. Call should succeed, but return
  // something other than the original data.
  std::string invalid_iv(iv_.size(), 'a');
  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, invalid_iv, subsamples, EncryptionPattern(1, 0));
  EXPECT_NE(one_block_, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, InvalidKey) {
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);

  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size()}};

  // Use a different key for decryption. Call should succeed, but return
  // something other than the original data.
  std::unique_ptr<crypto::SymmetricKey> bad_key = crypto::SymmetricKey::Import(
      crypto::SymmetricKey::AES, std::string(base::size(kKey), 'b'));
  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(1, 0));
  EXPECT_NE(one_block_, DecryptWithKey(encrypted_buffer, *bad_key));
}

TEST_F(CbcsDecryptorTest, PartialBlock) {
  // Only 1 subsample, all "encrypted" data. However, as it's not a full block,
  // it will be treated as unencrypted.
  std::vector<SubsampleEntry> subsamples = {{0, partial_block_.size()}};

  auto encrypted_buffer = CreateEncryptedBuffer(partial_block_, iv_, subsamples,
                                                EncryptionPattern(1, 0));
  EXPECT_EQ(partial_block_, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, SingleBlockWithExtraData) {
  // Create some data that is longer than a single block. The full block will
  // be encrypted, but the extra data at the end will be considered unencrypted.
  auto encrypted_block =
      Combine({Encrypt(one_block_, *key_, iv_), partial_block_});
  auto expected_result = Combine({one_block_, partial_block_});

  // Only 1 subsample, all "encrypted" data.
  std::vector<SubsampleEntry> subsamples = {{0, encrypted_block.size()}};

  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(1, 0));
  EXPECT_EQ(expected_result, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, SkipBlock) {
  // Only 1 subsample, but all unencrypted data.
  std::vector<SubsampleEntry> subsamples = {{one_block_.size(), 0}};

  auto encrypted_buffer = CreateEncryptedBuffer(one_block_, iv_, subsamples,
                                                EncryptionPattern(1, 0));
  EXPECT_EQ(one_block_, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, MultipleBlocks) {
  // Encrypt 2 copies of |one_block_| together using kKey and kIv.
  auto encrypted_block = Encrypt(Repeat(one_block_, 2), *key_, iv_);
  DCHECK_EQ(2 * kBlockSize, encrypted_block.size());

  // 1 subsample, 4 blocks in (1,1) pattern.
  // Encrypted blocks come from |encrypted_block|.
  // data:       | enc1 | clear | enc2 | clear |
  // subsamples: |         subsample#1         |
  //             |eeeeeeeeeeeeeeeeeeeeeeeeeeeee|
  auto input_data = Combine({GetBlock(1, encrypted_block), one_block_,
                             GetBlock(2, encrypted_block), one_block_});
  auto expected_result = Repeat(one_block_, 4);
  std::vector<SubsampleEntry> subsamples = {{0, 4 * kBlockSize}};

  auto encrypted_buffer = CreateEncryptedBuffer(input_data, iv_, subsamples,
                                                EncryptionPattern(1, 1));
  EXPECT_EQ(expected_result, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, PartialPattern) {
  // Encrypt 4 copies of |one_block_| together using kKey and kIv.
  auto encrypted_block = Encrypt(Repeat(one_block_, 4), *key_, iv_);
  DCHECK_EQ(4 * kBlockSize, encrypted_block.size());

  // 1 subsample, 4 blocks in (8,2) pattern. Even though there is not a full
  // pattern (10 blocks), all 4 blocks should be decrypted.
  auto expected_result = Repeat(one_block_, 4);
  std::vector<SubsampleEntry> subsamples = {{0, 4 * kBlockSize}};

  auto encrypted_buffer = CreateEncryptedBuffer(
      encrypted_block, iv_, subsamples, EncryptionPattern(8, 2));
  EXPECT_EQ(expected_result, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, SkipBlocks) {
  // Encrypt 5 blocks together using kKey and kIv.
  auto encrypted_block = Encrypt(Repeat(one_block_, 5), *key_, iv_);
  DCHECK_EQ(5 * kBlockSize, encrypted_block.size());

  // 1 subsample, 1 unencrypted block followed by 7 blocks in (2,1) pattern.
  // Encrypted blocks come from |encrypted_block|.
  // data:       | clear | enc1 | enc2 | clear | enc3 | enc4 | clear | enc5 |
  // subsamples: |                  subsample#1                             |
  //             |uuuuuuu eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee|
  auto input_data = Combine(
      {one_block_, GetBlock(1, encrypted_block), GetBlock(2, encrypted_block),
       one_block_, GetBlock(3, encrypted_block), GetBlock(4, encrypted_block),
       one_block_, GetBlock(5, encrypted_block)});
  auto expected_result = Repeat(one_block_, 8);
  std::vector<SubsampleEntry> subsamples = {{kBlockSize, 7 * kBlockSize}};

  auto encrypted_buffer = CreateEncryptedBuffer(input_data, iv_, subsamples,
                                                EncryptionPattern(2, 1));
  EXPECT_EQ(expected_result, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, MultipleSubsamples) {
  // Encrypt |one_block_| using kKey and kIv.
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);
  DCHECK_EQ(kBlockSize, encrypted_block.size());

  // 3 subsamples, each 1 block of |encrypted_block|.
  // data:       |  encrypted  |  encrypted  |  encrypted  |
  // subsamples: | subsample#1 | subsample#2 | subsample#3 |
  //             |eeeeeeeeeeeee|eeeeeeeeeeeee|eeeeeeeeeeeee|
  auto input_data = Repeat(encrypted_block, 3);
  auto expected_result = Repeat(one_block_, 3);
  std::vector<SubsampleEntry> subsamples = {
      {0, kBlockSize}, {0, kBlockSize}, {0, kBlockSize}};

  auto encrypted_buffer = CreateEncryptedBuffer(input_data, iv_, subsamples,
                                                EncryptionPattern(1, 0));
  EXPECT_EQ(expected_result, DecryptWithKey(encrypted_buffer, *key_));
}

TEST_F(CbcsDecryptorTest, MultipleSubsamplesWithClearBytes) {
  // Encrypt |one_block_| using kKey and kIv.
  auto encrypted_block = Encrypt(one_block_, *key_, iv_);
  DCHECK_EQ(kBlockSize, encrypted_block.size());

  // Combine into alternating clear/encrypted blocks in 3 subsamples. Split
  // the second and third clear blocks into part of encrypted data of the
  // previous block (which as a partial block will be considered unencrypted).
  // data:       | clear | encrypted | clear | encrypted | clear | encrypted |
  // subsamples: |    subsample#1     |    subsample#2        | subsample#3  |
  //             |uuuuuuu eeeeeeeeeeee|uuuuuu eeeeeeeeeeeeeeee|uu eeeeeeeeeee|
  auto input_data = Combine({one_block_, encrypted_block, one_block_,
                             encrypted_block, one_block_, encrypted_block});
  auto expected_result = Repeat(one_block_, 6);
  std::vector<SubsampleEntry> subsamples = {{kBlockSize, kBlockSize + 1},
                                            {kBlockSize - 1, kBlockSize + 10},
                                            {kBlockSize - 10, kBlockSize}};

  auto encrypted_buffer = CreateEncryptedBuffer(input_data, iv_, subsamples,
                                                EncryptionPattern(1, 0));
  EXPECT_EQ(expected_result, DecryptWithKey(encrypted_buffer, *key_));
}

}  // namespace media


text:
#ifndef M3BP_TEST_UTIL_PROCESSOR_OUTPUT_RECEIVER_HPP
#define M3BP_TEST_UTIL_PROCESSOR_OUTPUT_RECEIVER_HPP

#include <gtest/gtest.h>
#include <vector>
#include <algorithm>
#include "m3bp/processor_base.hpp"
#include "m3bp/task.hpp"
#include "util/generator_util.hpp"
#include "util/processors/input_deserializer.hpp"
#include "util/processors/output_builder.hpp"
#include "util/processors/test_processor_base.hpp"

namespace util {
namespace processors {

template <typename T>
class TestOutputReceiver : public TestProcessorBase {

private:
	std::shared_ptr<std::vector<T>> m_received;

public:
	explicit TestOutputReceiver(
		std::shared_ptr<std::vector<T>> destination)
		: TestProcessorBase(
			{
				m3bp::InputPort("input0")
					.movement(m3bp::Movement::ONE_TO_ONE)
			},
			{ })
		, m_received(std::move(destination))
	{
		max_concurrency(1);
	}

	virtual void run(m3bp::Task &task) override {
		TestProcessorBase::run(task);

		auto reader = task.input(0);
		const auto received = deserialize_value_only_buffer<T>(reader);
		for(const auto &x : received){
			m_received->push_back(x);
		}
	}

};

template <typename KeyType, typename ValueType>
class TestGroupedOutputReceiver : public TestProcessorBase {

public:
	using GroupType = std::pair<KeyType, std::vector<ValueType>>;

private:
	std::shared_ptr<std::vector<GroupType>> m_received;

public:
	explicit TestGroupedOutputReceiver(
		std::shared_ptr<std::vector<GroupType>> destination)
		: TestProcessorBase(
			{
				m3bp::InputPort("input0")
					.movement(m3bp::Movement::SCATTER_GATHER)
			},
			{ })
		, m_received(std::move(destination))
	{
		max_concurrency(1);
	}

	virtual void run(m3bp::Task &task) override {
		TestProcessorBase::run(task);

		auto reader = task.input(0);
		auto received =
			deserialize_grouped_buffer<KeyType, ValueType>(reader);
		for(auto &x : received){
			m_received->push_back(std::move(x));
		}
	}

};

}
}

#endif

redpajama_set_name: RedPajamaGithub


text:
![logo](https://github.com/getsentry/rb/blob/master/docs/_static/rb.png?raw=true)

rb - the redis blaster.

The fastest way to talk to many redis nodes.  Can do routing as well as
blindly blasting commands to many nodes.  How does it work?

For full documentation see [rb.rtfd.org](http://rb.rtfd.org/)

## Quickstart

Set up a cluster:

```python
from rb import Cluster

cluster = Cluster({
    0: {'port': 6379},
    1: {'port': 6380},
    2: {'port': 6381},
    3: {'port': 6382},
}, host_defaults={
    'host': '127.0.0.1',
})
```

Automatic routing:

```python
results = []
with cluster.map() as client:
    for key in range(100):
        client.get(key).then(lambda x: results.append(int(x or 0)))

print 'Sum: %s' % sum(results)
```

Fanout:

```python
with cluster.fanout(hosts=[0, 1, 2, 3]) as client:
    infos = client.info()
```

Fanout to all:

```python
with cluster.fanout(hosts='all') as client:
    client.flushdb()
```


text:
using UnityEngine;
using System.Linq;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Destructible2D
{
	public class D2dPopupAttribute : PropertyAttribute
	{
		public GUIContent[] Names;

		public int[] Values;

		public D2dPopupAttribute(params int[] newValues)
		{
			Names = newValues.Select(v => new GUIContent(v.ToString())).ToArray();

			Values = newValues.Select(v => v).ToArray();
		}
	}

#if UNITY_EDITOR
	[CustomPropertyDrawer(typeof(D2dPopupAttribute))]
	public class D2dPopupDrawer : PropertyDrawer
	{
		public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
		{
			if (D2dHelper.BaseRectSet == true)
			{
				position.x     = D2dHelper.BaseRect.x;
				position.width = D2dHelper.BaseRect.width;
			}

			var Attribute = (D2dPopupAttribute)attribute;

			EditorGUI.IntPopup(position, property, Attribute.Names, Attribute.Values, label);
		}
	}
#endif
}


text:
package internal

var KubeConfigTemplate = []byte(`apiVersion: v1
kind: Config
clusters:
- name: local
  cluster:
    server: {{ .Server }}
    certificate-authority-data: {{ .CACert }}
users:
- name: kubelet
  user:
    client-certificate-data: {{ .KubeletCert}}
    client-key-data: {{ .KubeletKey }}
contexts:
- context:
    cluster: local
    user: kubelet
`)

var KubeSystemSARoleBindingTemplate = []byte(`apiVersion: rbac.authorization.k8s.io/v1alpha1
kind: ClusterRoleBinding
metadata:
  name: system:default-sa
subjects:
  - kind: ServiceAccount
    name: default
    namespace: kube-system
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
`)

var KubeletTemplate = []byte(`apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: kubelet
  namespace: kube-system
  labels:
    tier: node
    k8s-app: kubelet
spec:
  template:
    metadata:
      labels:
        tier: node
        k8s-app: kubelet
    spec:
      containers:
      - name: kubelet
        image: {{ .Images.Hyperkube }}
        command:
        - ./hyperkube
        - kubelet
        - --allow-privileged
        - --cluster-dns={{ .DNSServiceIP }}
        - --cluster-domain=cluster.local
        - --cni-conf-dir=/etc/kubernetes/cni/net.d
        - --cni-bin-dir=/opt/cni/bin
        - --containerized
        - --hostname-override=$(NODE_NAME)
        - --kubeconfig=/etc/kubernetes/kubeconfig
        - --lock-file=/var/run/lock/kubelet.lock
        - --network-plugin=cni
        - --pod-manifest-path=/etc/kubernetes/manifests
        - --require-kubeconfig
        env:
          - name: NODE_NAME
            valueFrom:
              fieldRef:
                fieldPath: spec.nodeName
        securityContext:
          privileged: true
        volumeMounts:
        - name: dev
          mountPath: /dev
        - name: run
          mountPath: /run
        - name: sys
          mountPath: /sys
          readOnly: true
        - name: etc-kubernetes
          mountPath: /etc/kubernetes
          readOnly: true
        - name: etc-ssl-certs
          mountPath: /etc/ssl/certs
          readOnly: true
        - name: var-lib-docker
          mountPath: /var/lib/docker
        - name: var-lib-kubelet
          mountPath: /var/lib/kubelet
        - name: var-lib-rkt
          mountPath: /var/lib/rkt
        - name: rootfs
          mountPath: /rootfs
      hostNetwork: true
      hostPID: true
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      volumes:
      - name: dev
        hostPath:
          path: /dev
      - name: run
        hostPath:
          path: /run
      - name: sys
        hostPath:
          path: /sys
      - name: etc-kubernetes
        hostPath:
          path: /etc/kubernetes
      - name: etc-ssl-certs
        hostPath:
          path: /usr/share/ca-certificates
      - name: var-lib-docker
        hostPath:
          path: /var/lib/docker
      - name: var-lib-kubelet
        hostPath:
          path: /var/lib/kubelet
      - name: var-lib-rkt
        hostPath:
          path: /var/lib/rkt
      - name: rootfs
        hostPath:
          path: /
  updateStrategy:
    rollingUpdate:
      maxUnavailable: 1
    type: RollingUpdate
`)

var APIServerTemplate = []byte(`apiVersion: "extensions/v1beta1"
kind: DaemonSet
metadata:
  name: kube-apiserver
  namespace: kube-system
  labels:
    tier: control-plane
    k8s-app: kube-apiserver
spec:
  template:
    metadata:
      labels:
        tier: control-plane
        k8s-app: kube-apiserver
      annotations:
        checkpointer.alpha.coreos.com/checkpoint: "true"
        scheduler.alpha.kubernetes.io/critical-pod: ''
    spec:
      containers:
      - name: kube-apiserver
        image: {{ .Images.Hyperkube }}
        command:
        - /usr/bin/flock
        - /var/lock/api-server.lock
        - /hyperkube
        - apiserver
        - --admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota
        - --advertise-address=$(POD_IP)
        - --allow-privileged=true
        - --anonymous-auth=false
        - --authorization-mode=RBAC
        - --bind-address=0.0.0.0
        - --client-ca-file=/etc/kubernetes/secrets/ca.crt
        - --cloud-provider={{ .CloudProvider }}
{{- if .EtcdUseTLS }}
        - --etcd-cafile=/etc/kubernetes/secrets/etcd-client-ca.crt
        - --etcd-certfile=/etc/kubernetes/secrets/etcd-client.crt
        - --etcd-keyfile=/etc/kubernetes/secrets/etcd-client.key
{{- end }}
        - --etcd-quorum-read=true
        - --etcd-servers={{ range $i, $e := .EtcdServers }}{{ if $i }},{{end}}{{ $e }}{{end}}
        - --insecure-port=0
        - --kubelet-client-certificate=/etc/kubernetes/secrets/apiserver.crt
        - --kubelet-client-key=/etc/kubernetes/secrets/apiserver.key
        - --secure-port={{ (index .APIServers 0).Port }}
        - --service-account-key-file=/etc/kubernetes/secrets/service-account.pub
        - --service-cluster-ip-range={{ .ServiceCIDR }}
        - --storage-backend=etcd3
        - --tls-ca-file=/etc/kubernetes/secrets/ca.crt
        - --tls-cert-file=/etc/kubernetes/secrets/apiserver.crt
        - --tls-private-key-file=/etc/kubernetes/secrets/apiserver.key
        env:
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        volumeMounts:
        - mountPath: /etc/ssl/certs
          name: ssl-certs-host
          readOnly: true
        - mountPath: /etc/kubernetes/secrets
          name: secrets
          readOnly: true
        - mountPath: /var/lock
          name: var-lock
          readOnly: false
      hostNetwork: true
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: CriticalAddonsOnly
        operator: Exists
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      volumes:
      - name: ssl-certs-host
        hostPath:
          path: /usr/share/ca-certificates
      - name: secrets
        secret:
          secretName: kube-apiserver
      - name: var-lock
        hostPath:
          path: /var/lock
  updateStrategy:
    rollingUpdate:
      maxUnavailable: 1
    type: RollingUpdate
`)

var BootstrapAPIServerTemplate = []byte(`apiVersion: v1
kind: Pod
metadata:
  name: bootstrap-kube-apiserver
  namespace: kube-system
spec:
  containers:
  - name: kube-apiserver
    image: {{ .Images.Hyperkube }}
    command:
    - /usr/bin/flock
    - /var/lock/api-server.lock
    - /hyperkube
    - apiserver
    - --admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota
    - --advertise-address=$(POD_IP)
    - --allow-privileged=true
    - --authorization-mode=RBAC
    - --bind-address=0.0.0.0
    - --client-ca-file=/etc/kubernetes/secrets/ca.crt
{{- if .EtcdUseTLS }}
    - --etcd-cafile=/etc/kubernetes/secrets/etcd-client-ca.crt
    - --etcd-certfile=/etc/kubernetes/secrets/etcd-client.crt
    - --etcd-keyfile=/etc/kubernetes/secrets/etcd-client.key
{{- end }}
    - --etcd-quorum-read=true
    - --etcd-servers={{ range $i, $e := .EtcdServers }}{{ if $i }},{{end}}{{ $e }}{{end}}{{ if .SelfHostedEtcd }},https://127.0.0.1:12379{{end}}
    - --insecure-port=0
    - --kubelet-client-certificate=/etc/kubernetes/secrets/apiserver.crt
    - --kubelet-client-key=/etc/kubernetes/secrets/apiserver.key
    - --secure-port={{ (index .APIServers 0).Port }}
    - --service-account-key-file=/etc/kubernetes/secrets/service-account.pub
    - --service-cluster-ip-range={{ .ServiceCIDR }}
    - --cloud-provider={{ .CloudProvider }}
    - --storage-backend=etcd3
    - --tls-ca-file=/etc/kubernetes/secrets/ca.crt
    - --tls-cert-file=/etc/kubernetes/secrets/apiserver.crt
    - --tls-private-key-file=/etc/kubernetes/secrets/apiserver.key
    env:
    - name: POD_IP
      valueFrom:
        fieldRef:
          fieldPath: status.podIP
    volumeMounts:
    - mountPath: /etc/ssl/certs
      name: ssl-certs-host
      readOnly: true
    - mountPath: /etc/kubernetes/secrets
      name: secrets
      readOnly: true
    - mountPath: /var/lock
      name: var-lock
      readOnly: false
  hostNetwork: true
  volumes:
  - name: secrets
    hostPath:
      path: /etc/kubernetes/{{ .BootstrapSecretsSubdir }}
  - name: ssl-certs-host
    hostPath:
      path: /usr/share/ca-certificates
  - name: var-lock
    hostPath:
      path: /var/lock
`)

var KencTemplate = []byte(`apiVersion: "extensions/v1beta1"
kind: DaemonSet
metadata:
  name: kube-etcd-network-checkpointer
  namespace: kube-system
  labels:
    tier: control-plane
    k8s-app: kube-etcd-network-checkpointer
spec:
  template:
    metadata:
      labels:
        tier: control-plane
        k8s-app: kube-etcd-network-checkpointer
      annotations:
        checkpointer.alpha.coreos.com/checkpoint: "true"
    spec:
      containers:
      - image: {{ .Images.Kenc }}
        name: kube-etcd-network-checkpointer
        securityContext:
          privileged: true
        volumeMounts:
        - mountPath: /etc/kubernetes/selfhosted-etcd
          name: checkpoint-dir
          readOnly: false
        - mountPath: /var/etcd
          name: etcd-dir
          readOnly: false
        - mountPath: /var/lock
          name: var-lock
          readOnly: false
        command:
        - /usr/bin/flock
        - /var/lock/kenc.lock
        - -c
        - "kenc -r -m iptables && kenc -m iptables"
      hostNetwork: true
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      volumes:
      - name: checkpoint-dir
        hostPath:
          path: /etc/kubernetes/checkpoint-iptables
      - name: etcd-dir
        hostPath:
          path: /var/etcd
      - name: var-lock
        hostPath:
          path: /var/lock
  updateStrategy:
    rollingUpdate:
      maxUnavailable: 1
    type: RollingUpdate
`)

var CheckpointerTemplate = []byte(`apiVersion: "extensions/v1beta1"
kind: DaemonSet
metadata:
  name: pod-checkpointer
  namespace: kube-system
  labels:
    tier: control-plane
    k8s-app: pod-checkpointer
spec:
  template:
    metadata:
      labels:
        tier: control-plane
        k8s-app: pod-checkpointer
      annotations:
        checkpointer.alpha.coreos.com/checkpoint: "true"
    spec:
      containers:
      - name: pod-checkpointer
        image: {{ .Images.PodCheckpointer }}
        command:
        - /checkpoint
        - --v=4
        - --lock-file=/var/run/lock/pod-checkpointer.lock
        env:
        - name: NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        imagePullPolicy: Always
        volumeMounts:
        - mountPath: /etc/kubernetes
          name: etc-kubernetes
        - mountPath: /var/run
          name: var-run
      hostNetwork: true
      nodeSelector:
        node-role.kubernetes.io/master: ""
      restartPolicy: Always
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      volumes:
      - name: etc-kubernetes
        hostPath:
          path: /etc/kubernetes
      - name: var-run
        hostPath:
          path: /var/run
  updateStrategy:
    rollingUpdate:
      maxUnavailable: 1
    type: RollingUpdate
`)

var ControllerManagerTemplate = []byte(`apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: kube-controller-manager
  namespace: kube-system
  labels:
    tier: control-plane
    k8s-app: kube-controller-manager
spec:
  replicas: 2
  template:
    metadata:
      labels:
        tier: control-plane
        k8s-app: kube-controller-manager
      annotations:
        scheduler.alpha.kubernetes.io/critical-pod: ''
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: tier
                  operator: In
                  values:
                  - control-plane
                - key: k8s-app
                  operator: In
                  values:
                  - kube-controller-manager
              topologyKey: kubernetes.io/hostname
      containers:
      - name: kube-controller-manager
        image: {{ .Images.Hyperkube }}
        command:
        - ./hyperkube
        - controller-manager
        - --allocate-node-cidrs=true
        - --cloud-provider={{ .CloudProvider }}
        - --cluster-cidr={{ .PodCIDR }}
        - --configure-cloud-routes=false
        - --leader-elect=true
        - --root-ca-file=/etc/kubernetes/secrets/ca.crt
        - --service-account-private-key-file=/etc/kubernetes/secrets/service-account.key
        livenessProbe:
          httpGet:
            path: /healthz
            port: 10252  # Note: Using default port. Update if --port option is set differently.
          initialDelaySeconds: 15
          timeoutSeconds: 15
        volumeMounts:
        - name: secrets
          mountPath: /etc/kubernetes/secrets
          readOnly: true
        - name: ssl-host
          mountPath: /etc/ssl/certs
          readOnly: true
      nodeSelector:
        node-role.kubernetes.io/master: ""
      securityContext:
        runAsNonRoot: true
        runAsUser: 65534
      tolerations:
      - key: CriticalAddonsOnly
        operator: Exists
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      volumes:
      - name: secrets
        secret:
          secretName: kube-controller-manager
      - name: ssl-host
        hostPath:
          path: /usr/share/ca-certificates
      dnsPolicy: Default # Don't use cluster DNS.
`)

var BootstrapControllerManagerTemplate = []byte(`apiVersion: v1
kind: Pod
metadata:
  name: bootstrap-kube-controller-manager
  namespace: kube-system
spec:
  containers:
  - name: kube-controller-manager
    image: {{ .Images.Hyperkube }}
    command:
    - ./hyperkube
    - controller-manager
    - --allocate-node-cidrs=true
    - --cluster-cidr={{ .PodCIDR }}
    - --cloud-provider={{ .CloudProvider }}
    - --configure-cloud-routes=false
    - --kubeconfig=/etc/kubernetes/kubeconfig
    - --leader-elect=true
    - --root-ca-file=/etc/kubernetes/{{ .BootstrapSecretsSubdir }}/ca.crt
    - --service-account-private-key-file=/etc/kubernetes/{{ .BootstrapSecretsSubdir }}/service-account.key
    volumeMounts:
    - name: kubernetes
      mountPath: /etc/kubernetes
      readOnly: true
    - name: ssl-host
      mountPath: /etc/ssl/certs
      readOnly: true
  hostNetwork: true
  volumes:
  - name: kubernetes
    hostPath:
      path: /etc/kubernetes
  - name: ssl-host
    hostPath:
      path: /usr/share/ca-certificates
`)

var ControllerManagerDisruptionTemplate = []byte(`apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  name: kube-controller-manager
  namespace: kube-system
spec:
  minAvailable: 1
  selector:
    matchLabels:
      tier: control-plane
      k8s-app: kube-controller-manager
`)

var SchedulerTemplate = []byte(`apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: kube-scheduler
  namespace: kube-system
  labels:
    tier: control-plane
    k8s-app: kube-scheduler
spec:
  replicas: 2
  template:
    metadata:
      labels:
        tier: control-plane
        k8s-app: kube-scheduler
      annotations:
        scheduler.alpha.kubernetes.io/critical-pod: ''
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: tier
                  operator: In
                  values:
                  - control-plane
                - key: k8s-app
                  operator: In
                  values:
                  - kube-scheduler
              topologyKey: kubernetes.io/hostname
      containers:
      - name: kube-scheduler
        image: {{ .Images.Hyperkube }}
        command:
        - ./hyperkube
        - scheduler
        - --leader-elect=true
        livenessProbe:
          httpGet:
            path: /healthz
            port: 10251  # Note: Using default port. Update if --port option is set differently.
          initialDelaySeconds: 15
          timeoutSeconds: 15
      nodeSelector:
        node-role.kubernetes.io/master: ""
      securityContext:
        runAsNonRoot: true
        runAsUser: 65534
      tolerations:
      - key: CriticalAddonsOnly
        operator: Exists
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
`)

var BootstrapSchedulerTemplate = []byte(`apiVersion: v1
kind: Pod
metadata:
  name: bootstrap-kube-scheduler
  namespace: kube-system
spec:
  containers:
  - name: kube-scheduler
    image: {{ .Images.Hyperkube }}
    command:
    - ./hyperkube
    - scheduler
    - --kubeconfig=/etc/kubernetes/kubeconfig
    - --leader-elect=true
    volumeMounts:
    - name: kubernetes
      mountPath: /etc/kubernetes
      readOnly: true
  hostNetwork: true
  volumes:
  - name: kubernetes
    hostPath:
      path: /etc/kubernetes
`)

var SchedulerDisruptionTemplate = []byte(`apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  name: kube-scheduler
  namespace: kube-system
spec:
  minAvailable: 1
  selector:
    matchLabels:
      tier: control-plane
      k8s-app: kube-scheduler
`)

var ProxyTemplate = []byte(`apiVersion: "extensions/v1beta1"
kind: DaemonSet
metadata:
  name: kube-proxy
  namespace: kube-system
  labels:
    tier: node
    k8s-app: kube-proxy
spec:
  template:
    metadata:
      labels:
        tier: node
        k8s-app: kube-proxy
      annotations:
        scheduler.alpha.kubernetes.io/critical-pod: ''
    spec:
      containers:
      - name: kube-proxy
        image: {{ .Images.Hyperkube }}
        command:
        - ./hyperkube
        - proxy
        - --cluster-cidr={{ .PodCIDR }}
        - --hostname-override=$(NODE_NAME)
        - --kubeconfig=/etc/kubernetes/kubeconfig
        - --proxy-mode=iptables
        env:
          - name: NODE_NAME
            valueFrom:
              fieldRef:
                fieldPath: spec.nodeName
        securityContext:
          privileged: true
        volumeMounts:
        - mountPath: /etc/ssl/certs
          name: ssl-certs-host
          readOnly: true
        - name: etc-kubernetes
          mountPath: /etc/kubernetes
          readOnly: true
      hostNetwork: true
      tolerations:
      - key: CriticalAddonsOnly
        operator: Exists
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      volumes:
      - hostPath:
          path: /usr/share/ca-certificates
        name: ssl-certs-host
      - name: etc-kubernetes
        hostPath:
          path: /etc/kubernetes
  updateStrategy:
    rollingUpdate:
      maxUnavailable: 1
    type: RollingUpdate
`)

var DNSDeploymentTemplate = []byte(`apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: kube-dns
  namespace: kube-system
  labels:
    k8s-app: kube-dns
    kubernetes.io/cluster-service: "true"
    addonmanager.kubernetes.io/mode: Reconcile
spec:
  # replicas: not specified here:
  # 1. In order to make Addon Manager do not reconcile this replicas parameter.
  # 2. Default is 1.
  # 3. Will be tuned in real time if DNS horizontal auto-scaling is turned on.
  strategy:
    rollingUpdate:
      maxSurge: 10%
      maxUnavailable: 0
  selector:
    matchLabels:
      k8s-app: kube-dns
  template:
    metadata:
      labels:
        k8s-app: kube-dns
      annotations:
        scheduler.alpha.kubernetes.io/critical-pod: ''
    spec:
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: "CriticalAddonsOnly"
        operator: "Exists"
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      volumes:
      - name: kube-dns-config
        configMap:
          name: kube-dns
          optional: true
      containers:
      - name: kubedns
        image: {{ .Images.KubeDNS }}
        resources:
          # TODO: Set memory limits when we've profiled the container for large
          # clusters, then set request = limit to keep this container in
          # guaranteed class. Currently, this container falls into the
          # "burstable" category so the kubelet doesn't backoff from restarting it.
          limits:
            memory: 170Mi
          requests:
            cpu: 100m
            memory: 70Mi
        livenessProbe:
          httpGet:
            path: /healthcheck/kubedns
            port: 10054
            scheme: HTTP
          initialDelaySeconds: 60
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 5
        readinessProbe:
          httpGet:
            path: /readiness
            port: 8081
            scheme: HTTP
          # we poll on pod startup for the Kubernetes master service and
          # only setup the /readiness HTTP server once that's available.
          initialDelaySeconds: 3
          timeoutSeconds: 5
        args:
        - --domain=cluster.local.
        - --dns-port=10053
        - --config-dir=/kube-dns-config
        - --v=2
        env:
        - name: PROMETHEUS_PORT
          value: "10055"
        ports:
        - containerPort: 10053
          name: dns-local
          protocol: UDP
        - containerPort: 10053
          name: dns-tcp-local
          protocol: TCP
        - containerPort: 10055
          name: metrics
          protocol: TCP
        volumeMounts:
        - name: kube-dns-config
          mountPath: /kube-dns-config
      - name: dnsmasq
        image: {{ .Images.KubeDNSMasq }}
        livenessProbe:
          httpGet:
            path: /healthcheck/dnsmasq
            port: 10054
            scheme: HTTP
          initialDelaySeconds: 60
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 5
        args:
        - -v=2
        - -logtostderr
        - -configDir=/etc/k8s/dns/dnsmasq-nanny
        - -restartDnsmasq=true
        - --
        - -k
        - --cache-size=1000
        - --log-facility=-
        - --server=/cluster.local/127.0.0.1#10053
        - --server=/in-addr.arpa/127.0.0.1#10053
        - --server=/ip6.arpa/127.0.0.1#10053
        ports:
        - containerPort: 53
          name: dns
          protocol: UDP
        - containerPort: 53
          name: dns-tcp
          protocol: TCP
        # see: https://github.com/kubernetes/kubernetes/issues/29055 for details
        resources:
          requests:
            cpu: 150m
            memory: 20Mi
        volumeMounts:
        - name: kube-dns-config
          mountPath: /etc/k8s/dns/dnsmasq-nanny
      - name: sidecar
        image: {{ .Images.KubeDNSSidecar }}
        livenessProbe:
          httpGet:
            path: /metrics
            port: 10054
            scheme: HTTP
          initialDelaySeconds: 60
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 5
        args:
        - --v=2
        - --logtostderr
        - --probe=kubedns,127.0.0.1:10053,kubernetes.default.svc.cluster.local,5,A
        - --probe=dnsmasq,127.0.0.1:53,kubernetes.default.svc.cluster.local,5,A
        ports:
        - containerPort: 10054
          name: metrics
          protocol: TCP
        resources:
          requests:
            memory: 20Mi
            cpu: 10m
      dnsPolicy: Default  # Don't use cluster DNS.
`)

var DNSSvcTemplate = []byte(`apiVersion: v1
kind: Service
metadata:
  name: kube-dns
  namespace: kube-system
  labels:
    k8s-app: kube-dns
    kubernetes.io/cluster-service: "true"
    kubernetes.io/name: "KubeDNS"
spec:
  selector:
    k8s-app: kube-dns
  clusterIP: {{ .DNSServiceIP }}
  ports:
  - name: dns
    port: 53
    protocol: UDP
  - name: dns-tcp
    port: 53
    protocol: TCP
`)

var EtcdOperatorTemplate = []byte(`apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: etcd-operator
  namespace: kube-system
  labels:
    k8s-app: etcd-operator
spec:
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  replicas: 1
  template:
    metadata:
      labels:
        k8s-app: etcd-operator
    spec:
      containers:
      - name: etcd-operator
        image: {{ .Images.EtcdOperator }}
        env:
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
      nodeSelector:
        node-role.kubernetes.io/master: ""
      securityContext:
        runAsNonRoot: true
        runAsUser: 65534
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
`)

var EtcdSvcTemplate = []byte(`apiVersion: v1
kind: Service
metadata:
  name: {{ .EtcdServiceName }}
  namespace: kube-system
  # This alpha annotation will retain the endpoints even if the etcd pod isn't ready.
  # This feature is always enabled in endpoint controller in k8s even it is alpha.
  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
spec:
  selector:
    app: etcd
    etcd_cluster: kube-etcd
  clusterIP: {{ .EtcdServiceIP }}
  ports:
  - name: client
    port: 2379
    protocol: TCP
`)

var BootstrapEtcdTemplate = []byte(`apiVersion: v1
kind: Pod
metadata:
  name: bootstrap-etcd
  namespace: kube-system
  labels:
    k8s-app: boot-etcd
spec:
  containers:
  - name: etcd
    image: {{ .Images.Etcd }}
    command:
    - /usr/local/bin/etcd
    - --name=boot-etcd
    - --listen-client-urls=https://0.0.0.0:12379
    - --listen-peer-urls=https://0.0.0.0:12380
    - --advertise-client-urls=https://{{ .BootEtcdServiceIP }}:12379
    - --initial-advertise-peer-urls=https://{{ .BootEtcdServiceIP }}:12380
    - --initial-cluster=boot-etcd=https://{{ .BootEtcdServiceIP }}:12380
    - --initial-cluster-token=bootkube
    - --initial-cluster-state=new
    - --data-dir=/var/etcd/data
    - --peer-client-cert-auth=true
    - --peer-trusted-ca-file=/etc/kubernetes/secrets/etcd/peer-ca.crt
    - --peer-cert-file=/etc/kubernetes/secrets/etcd/peer.crt
    - --peer-key-file=/etc/kubernetes/secrets/etcd/peer.key
    - --client-cert-auth=true
    - --trusted-ca-file=/etc/kubernetes/secrets/etcd/server-ca.crt
    - --cert-file=/etc/kubernetes/secrets/etcd/server.crt
    - --key-file=/etc/kubernetes/secrets/etcd/server.key
    volumeMounts:
    - mountPath: /etc/kubernetes/secrets
      name: secrets
      readOnly: true
  volumes:
  - name: secrets
    hostPath:
      path: /etc/kubernetes/{{ .BootstrapSecretsSubdir }}
  hostNetwork: true
  restartPolicy: Never
  dnsPolicy: ClusterFirstWithHostNet
`)

var BootstrapEtcdSvcTemplate = []byte(`{
  "apiVersion": "v1",
  "kind": "Service",
  "metadata": {
    "name": "bootstrap-etcd-service",
    "namespace": "kube-system"
  },
  "spec": {
    "selector": {
      "k8s-app": "boot-etcd"
    },
    "clusterIP": "{{ .BootEtcdServiceIP }}",
    "ports": [
      {
        "name": "client",
        "port": 12379,
        "protocol": "TCP"
      },
      {
        "name": "peers",
        "port": 12380,
        "protocol": "TCP"
      }
    ]
  }
}`)

var EtcdTPRTemplate = []byte(`{
  "apiVersion": "etcd.coreos.com/v1beta1",
  "kind": "Cluster",
  "metadata": {
    "name": "kube-etcd",
    "namespace": "kube-system"
  },
  "spec": {
    "size": 1,
    "version": "v3.1.8",
    "pod": {
      "nodeSelector": {
        "node-role.kubernetes.io/master": ""
      },
      "tolerations": [
        {
          "key": "node-role.kubernetes.io/master",
          "operator": "Exists",
          "effect": "NoSchedule"
        }
      ]
    },
    "selfHosted": {
      "bootMemberClientEndpoint": "https://{{ .BootEtcdServiceIP }}:12379"
    },
    "TLS": {
      "static": {
        "member": {
          "peerSecret": "etcd-peer-tls",
          "serverSecret": "etcd-server-tls"
        },
        "operatorSecret": "etcd-client-tls"
      }
    }
  }
}`)

var KubeFlannelCfgTemplate = []byte(`apiVersion: v1
kind: ConfigMap
metadata:
  name: kube-flannel-cfg
  namespace: kube-system
  labels:
    tier: node
    k8s-app: flannel
data:
  cni-conf.json: |
    {
      "name": "cbr0",
      "type": "flannel",
      "delegate": {
        "isDefaultGateway": true
      }
    }
  net-conf.json: |
    {
      "Network": "{{ .PodCIDR }}",
      "Backend": {
        "Type": "vxlan"
      }
    }
`)

var KubeFlannelTemplate = []byte(`apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: kube-flannel
  namespace: kube-system
  labels:
    tier: node
    k8s-app: flannel
spec:
  template:
    metadata:
      labels:
        tier: node
        k8s-app: flannel
    spec:
      containers:
      - name: kube-flannel
        image: {{ .Images.Flannel }}
        command: [ "/opt/bin/flanneld", "--ip-masq", "--kube-subnet-mgr", "--iface=$(POD_IP)"]
        securityContext:
          privileged: true
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        volumeMounts:
        - name: run
          mountPath: /run
        - name: cni
          mountPath: /etc/cni/net.d
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/
      - name: install-cni
        image: {{ .Images.FlannelCNI }}
        command: ["/install-cni.sh"]
        env:
        - name: CNI_NETWORK_CONFIG
          valueFrom:
            configMapKeyRef:
              name: kube-flannel-cfg
              key: cni-conf.json
        volumeMounts:
        - name: cni
          mountPath: /host/etc/cni/net.d
        - name: host-cni-bin
          mountPath: /host/opt/cni/bin/
      hostNetwork: true
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      volumes:
        - name: run
          hostPath:
            path: /run
        - name: cni
          hostPath:
            path: /etc/kubernetes/cni/net.d
        - name: flannel-cfg
          configMap:
            name: kube-flannel-cfg
        - name: host-cni-bin
          hostPath:
            path: /opt/cni/bin
  updateStrategy:
    rollingUpdate:
      maxUnavailable: 1
    type: RollingUpdate
`)

var KubeCalicoCfgTemplate = []byte(`apiVersion: v1
kind: ConfigMap
metadata:
  name: kube-calico-cfg
  namespace: kube-system
data:
  # The CNI network configuration to install on each node.
  cni_network_config: |-
    {
        "name": "k8s-pod-network",
        "cniVersion": "0.3.0",
        "type": "calico",
        "log_level": "debug",
        "datastore_type": "kubernetes",
        "nodename": "__KUBERNETES_NODE_NAME__",
        "ipam": {
            "type": "host-local",
            "subnet": "usePodCidr"
        },
        "policy": {
            "type": "k8s",
            "k8s_auth_token": "__SERVICEACCOUNT_TOKEN__"
        },
        "kubernetes": {
            "k8s_api_root": "https://__KUBERNETES_SERVICE_HOST__:__KUBERNETES_SERVICE_PORT__",
            "kubeconfig": "__KUBECONFIG_FILEPATH__"
        }
    }
`)

var KubeCalicoTemplate = []byte(`apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: kube-calico
  namespace: kube-system
  labels:
    k8s-app: kube-calico
spec:
  selector:
    matchLabels:
      k8s-app: kube-calico
  template:
    metadata:
      labels:
        k8s-app: kube-calico
      annotations:
        scheduler.alpha.kubernetes.io/critical-pod: ''
    spec:
      hostNetwork: true
      serviceAccountName: kube-calico
      tolerations:
        - key: node-role.kubernetes.io/master
          effect: NoSchedule
        - key: "CriticalAddonsOnly"
          operator: "Exists"
      containers:
        - name: kube-calico
          image: {{ .Images.Calico }}
          env:
            - name: DATASTORE_TYPE
              value: "kubernetes"
            - name: FELIX_LOGSEVERITYSCREEN
              value: "info"
            - name: CALICO_NETWORKING_BACKEND
              value: "none"
            - name: CALICO_DISABLE_FILE_LOGGING
              value: "true"
            - name: FELIX_DEFAULTENDPOINTTOHOSTACTION
              value: "ACCEPT"
            - name: FELIX_IPV6SUPPORT
              value: "false"
            - name: WAIT_FOR_DATASTORE
              value: "true"
            - name: CALICO_IPV4POOL_CIDR
              value: "{{ .PodCIDR }}"
            - name: CALICO_IPV4POOL_IPIP
              value: "always"
            - name: NODENAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: IP
              value: ""
          securityContext:
            privileged: true
          resources:
            requests:
              cpu: 250m
          volumeMounts:
            - mountPath: /var/run/calico
              name: var-run-calico
              readOnly: false
        - name: install-cni
          image: {{ .Images.CalicoCNI }}
          command: ["/install-cni.sh"]
          env:
            - name: CNI_NETWORK_CONFIG
              valueFrom:
                configMapKeyRef:
                  name: kube-calico-cfg
                  key: cni_network_config
            - name: CNI_NET_DIR
              value: "/etc/kubernetes/cni/net.d"
            - name: KUBERNETES_NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: SKIP_CNI_BINARIES
              value: bridge,cnitool,dhcp,flannel,host-local,ipvlan,loopback,macvlan,noop,portmap,ptp,tuning
          volumeMounts:
            - mountPath: /host/opt/cni/bin
              name: cni-bin-dir
            - mountPath: /host/etc/cni/net.d
              name: cni-net-dir
      volumes:
        - name: var-run-calico
          hostPath:
            path: /var/run/calico
        - name: cni-bin-dir
          hostPath:
            path: /opt/cni/bin
        - name: cni-net-dir
          hostPath:
            path: /etc/kubernetes/cni/net.d
  updateStrategy:
    rollingUpdate:
      maxUnavailable: 1
    type: RollingUpdate
`)

var KubeCalicoServiceAccountTemplate = []byte(`apiVersion: v1
kind: ServiceAccount
metadata:
  name: kube-calico
  namespace: kube-system
`)

var KubeCalicoRoleTemplate = []byte(`apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: kube-calico
  namespace: kube-system
rules:
  - apiGroups: [""]
    resources:
      - namespaces
    verbs:
      - get
      - list
      - watch
  - apiGroups: [""]
    resources:
      - pods/status
    verbs:
      - update
  - apiGroups: [""]
    resources:
      - pods
    verbs:
      - get
      - list
      - watch
  - apiGroups: [""]
    resources:
      - nodes
    verbs:
      - get
      - list
      - update
      - watch
  - apiGroups: ["extensions"]
    resources:
      - thirdpartyresources
    verbs:
      - create
      - get
      - list
      - watch
  - apiGroups: ["extensions"]
    resources:
      - networkpolicies
    verbs:
      - get
      - list
      - watch
  - apiGroups: ["projectcalico.org"]
    resources:
      - globalconfigs
    verbs:
      - create
      - get
      - list
      - update
      - watch
  - apiGroups: ["projectcalico.org"]
    resources:
      - ippools
    verbs:
      - create
      - delete
      - get
      - list
      - update
      - watch
  - apiGroups: ["alpha.projectcalico.org"]
    resources:
      - systemnetworkpolicies
    verbs:
      - get
      - list
      - watch
`)

var KubeCalicoRoleBindingTemplate = []byte(`apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: kube-calico
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: kube-calico
subjects:
- kind: ServiceAccount
  name: kube-calico
  namespace: kube-system
`)

// vim: set expandtab:tabstop=2


text:
<?php

namespace Richpolis\CategoriasGaleriaBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Richpolis\CategoriasGaleriaBundle\Entity\Categorias;

/**
 * CategoriasRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CategoriasRepository extends EntityRepository
{
    public function getMaxPosicion($tipo=0){
        $em=$this->getEntityManager();
        if($tipo==0){
            $query=$em->createQuery('
                SELECT MAX(p.posicion) as value
                FROM CategoriasGaleriaBundle:Categorias p
                ORDER BY p.posicion DESC
            ');
        }else{
            $query=$em->createQuery('
                SELECT MAX(p.posicion) as value
                FROM CategoriasGaleriaBundle:Categorias p
                WHERE p.tipoCategoria=:tipo
                ORDER BY p.posicion DESC
            ')->setParameter('tipo', $tipo);
        }
        $max=$query->getResult();
        return $max[0]['value'];
    }

    public function getCategoriaActualPorTipoCategoria($tipoCategoria){
        $em=$this->getEntityManager();
        $query=$em->createQuery('
                    SELECT p,g FROM CategoriasGaleriaBundle:Categorias p
                    LEFT JOIN p.galerias g
                    WHERE p.tipoCategoria = :tipo
                    AND g.isActive=:activeGaleria
                    AND p.isActive = :active
                    ORDER BY g.posicion ASC
                ')->setParameters(array('tipo'=> $tipoCategoria,'active'=>true,'activeGaleria'=>true));
        $categorias=$query->getResult();
        if(isset($categorias[0])){
            return $categorias[0];
        }else{
            $query=$em->createQuery('
                    SELECT p FROM CategoriasGaleriaBundle:Categorias p
                    WHERE p.tipoCategoria = :tipo
                    AND p.isActive = :active
                ')->setParameters(array('tipo'=> $tipoCategoria,'active'=>true));
            $categorias=$query->getResult();
            return $categorias[0];
        }
    }

    public function getCategoriaConGaleriaPorId($categoria_id,$active=true){
        $em=$this->getEntityManager();
        $query=$em->createQuery('
               SELECT p,g
               FROM CategoriasGaleriaBundle:Categorias p
               JOIN p.galerias g
               WHERE p.id = :categoria
               AND g.isActive = :active
               ORDER BY g.posicion ASC
        ')->setParameters(array('categoria'=> $categoria_id,'active'=>$active));

        $categorias=$query->getResult();
        if(isset($categorias[0])){
            return $categorias[0];
        }else{
            return null;
        }
    }
    public function getQueryCategoriasPorTipoCategoria($tipoCategoria,$categoria_actual=0,$active=true){
        $em=$this->getEntityManager();
        $query=$em->createQuery('
                    SELECT p FROM CategoriasGaleriaBundle:Categorias p
                    WHERE p.tipoCategoria = :tipo
                    AND p.id <> :actual
                    AND p.isActive = :active
                    ORDER BY p.posicion DESC
                ')->setParameters(array(
                    'tipo'=> $tipoCategoria,
                    "actual"=>$categoria_actual,
                    'active'=>$active
                ));
        return $query;
    }

    public function getCategoriasPorTipoCategoria($tipoCategoria,$categoria_actual=0,$active=true){
        $query=$this->getQueryCategoriasPorTipoCategoria($tipoCategoria,$categoria_actual,$active);
        return $query->getResult();
    }

    public function getQueryCategoriasPorTipoYActivas($tipoCategoria,$todas=false){
        $query= $this->getEntityManager()->createQueryBuilder();
                $query->select('c,g')
                    ->from('Richpolis\CategoriasGaleriaBundle\Entity\Categorias', 'c')
                    ->leftJoin('c.galerias', 'g')
                    ->where('c.tipoCategoria=:tipo')
                    ->setParameter('tipo', $tipoCategoria)
                    ->orderBy('c.posicion', 'DESC')
                    ->addOrderBy('g.posicion', 'ASC');
        if(!$todas){
            $query->andWhere('c.isActive=:active')
                  ->setParameter('active', true);
        }
        return $query->getQuery();
    }

    public function getCategoriasPorTipoYActivas($tipo,$todas=false){
        $query=$this->getQueryCategoriasPorTipoYActivas($tipo, $todas);
        return $query->getResult();
    }

    public function getQueryCategoriasGaleriaActivas($tipoCategoria,$todas=false,$inicial=0,$cuantos=0){
         $query=$this->createQueryBuilder('c')
                    ->where('c.tipoCategoria=:tipo')
                    ->setParameter('tipo', $tipoCategoria)
                    ->orderBy('c.posicion', 'DESC');
        if(!$todas){
            $query->andWhere('c.isActive=:active')
                  ->setParameter('active', true);
        }
        return $query->getQuery();
    }

    public function getCategoriasGaleriaActivas($tipo,$todas=false){
        $query=$this->getQueryCategoriasGaleriaActivas($tipo, $todas);
        return $query->getResult();
    }

    public function getCategoriasActuales(){
        $em=$this->getEntityManager();
        $query=$em->createQuery('
                    SELECT DISTINCT c,g
                    FROM CategoriasGaleriaBundle:Categorias c
                    LEFT JOIN c.galerias g
                    WHERE c.isActive=:active
                    AND g.isActive=:activeGaleria
                    ORDER BY c.tipoCategoria,c.posicion DESC, g.posicion DESC
                ')->setParameters(array('active'=>true,'activeGaleria'=>true));
        return $query->getResult();
    }

    public function getCategoriasValidas($registros){
        $categorias=array();
        $categorias['tipo'.Categorias::$GALERIA]=null;
        $categorias['tipo'.Categorias::$RECOMENDACIONES]=null;
        $lugar=0;

        foreach($registros as $registro){
            $lugar=$registro->getTipoCategoria();
            $categorias['tipo'.$lugar]=$registro;
        }

        return $categorias;
    }

    public function getRegistroUpOrDown(Categorias $categoria,$up=true){
        // $up = true, $up = false is down
        if($up){
            //up
            $query=$this->createQueryBuilder('p')
                    ->where('p.posicion<:posicion')
                    ->setParameter('posicion', $categoria->getPosicion())
                    ->andWhere('p.tipoCategoria=:tipo')
                    ->setParameter('tipo',$categoria->getTipoCategoria())
                    ->orderBy('p.posicion', 'DESC');
        }else{
            //down
            $query=$this->createQueryBuilder('p')
                    ->where('p.posicion>:posicion')
                    ->setParameter('posicion', $categoria->getPosicion())
                    ->andWhere('p.tipoCategoria=:tipo')
                    ->setParameter('tipo',$categoria->getTipoCategoria())
                    ->orderBy('p.posicion', 'ASC');
        }

        return $query->getQuery()->setMaxResults(1)->getOneOrNullResult();
    }

}


text:
#include "URISyntaxException.h"

using namespace decaf;
using namespace decaf::net;
using namespace decaf::lang;

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::URISyntaxException() : decaf::lang::Exception(), reason(), input(), index(-1) {
}

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::~URISyntaxException() throw () {
}

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::URISyntaxException(const Exception& ex) : Exception(), reason(), input(), index(-1) {
    *(Exception*) this = ex;
}

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::URISyntaxException(const URISyntaxException& ex) :
    Exception(), reason(ex.getReason()), input(ex.getInput()), index(ex.getIndex()) {

    *(Exception*) this = ex;
}

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::URISyntaxException(const char* file, const int lineNumber, const std::exception* cause, const char* msg, ...) :
    lang::Exception(cause), reason(), input(), index(-1) {

    va_list vargs;
    va_start(vargs, msg);
    buildMessage(msg, vargs);

    // Set the first mark for this exception.
    setMark(file, lineNumber);
}

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::URISyntaxException(const std::exception* cause) :
    lang::Exception(cause), reason(), input(), index(-1) {
}

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::URISyntaxException(const char* file, const int lineNumber, const char* msg DECAF_UNUSED) :
    Exception(), reason("<Unknown Reason>"), input("<No Address Given>"), index(-1) {

    const char * message = "Input: %s, Reason it failed: %s";
    this->setMessage(message, input.c_str(), reason.c_str());

    // Set the first mark for this exception.
    setMark(file, lineNumber);
}

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::URISyntaxException(const char* file, const int lineNumber, const std::string& input, const std::string& reason) :
    Exception(), reason(reason), input(input), index(-1) {

    const char * message = "Input: %s, Reason it failed: %s";
    this->setMessage(message, input.c_str(), reason.c_str());

    // Set the first mark for this exception.
    setMark(file, lineNumber);
}

////////////////////////////////////////////////////////////////////////////////
URISyntaxException::URISyntaxException(const char* file, const int lineNumber, const std::string& input, const std::string& reason, int index) :
    Exception(), reason(reason), input(input), index(index) {

    const char * message = "Input: %s, Index %d resulted in this error: %s";
    this->setMessage(message, input.c_str(), index, reason.c_str());

    // Set the first mark for this exception.
    setMark(file, lineNumber);
}


text:
<?php

namespace Anthem\Auth\Model;

use Anthem\Auth\Model\om\BaseUser;

class User extends BaseUser
{
  public function isEmailValid()
  {
    return preg_match('/^[^@\s]+@[^\s.]+\.[^\s]+$/', $this->getEmail());
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:descendantFocusability="beforeDescendants"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <com.flurgle.camerakit.CameraView xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/camera"
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:layout_gravity="center_horizontal"
                android:adjustViewBounds="true"
                app:ckCropOutput="false"
                app:ckFacing="back"
                app:ckFlash="off"
                app:ckFocus="tapWithMarker"
                app:ckJpegQuality="100"
                app:ckMethod="standard" />

        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="16dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="3">

                <ImageButton
                    android:id="@+id/capturePhoto"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:layout_weight="1"
                    android:backgroundTint="@color/colorPrimary"
                    android:src="@drawable/ic_photo"
                    android:tint="@android:color/white" />

                <ImageButton
                    android:id="@+id/captureVideo"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:layout_weight="1"
                    android:backgroundTint="@color/colorPrimary"
                    android:src="@drawable/ic_video"
                    android:tint="@android:color/white"
                    android:visibility="gone" />

                <ImageButton
                    android:id="@+id/toggleFlash"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:layout_weight="1"
                    android:backgroundTint="@color/colorPrimary"
                    android:src="@drawable/ic_flash"
                    android:tint="@android:color/white" />

                <ImageButton
                    android:id="@+id/toggleCamera"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:layout_weight="1"
                    android:backgroundTint="@color/colorPrimary"
                    android:src="@drawable/ic_switch"
                    android:tint="@android:color/white" />

            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginTop="10dp"
                android:background="#cccccc" />

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp">

                <View
                    android:layout_width="2.5dp"
                    android:layout_height="match_parent"
                    android:background="@color/colorPrimary" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="3dp"
                        android:text="CAPTURE METHOD"
                        android:textColor="@android:color/black"
                        android:textSize="14sp"
                        android:textStyle="bold" />

                    <RadioGroup
                        android:id="@+id/captureModeRadioGroup"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="4dp"
                        android:checkedButton="@+id/modeCaptureStandard"
                        android:orientation="horizontal">

                        <RadioButton
                            android:id="@+id/modeCaptureStandard"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Standard" />

                        <RadioButton
                            android:id="@+id/modeCaptureStill"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:text="Still" />

                    </RadioGroup>

                </LinearLayout>

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp">

                <View
                    android:layout_width="2.5dp"
                    android:layout_height="match_parent"
                    android:background="@color/colorPrimary" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="3dp"
                        android:text="CROP OUTPUT"
                        android:textColor="@android:color/black"
                        android:textSize="14sp"
                        android:textStyle="bold" />

                    <RadioGroup
                        android:id="@+id/cropModeRadioGroup"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="4dp"
                        android:checkedButton="@+id/modeCropFullSize"
                        android:orientation="horizontal">

                        <RadioButton
                            android:id="@+id/modeCropFullSize"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Off" />

                        <RadioButton
                            android:id="@+id/modeCropVisible"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:text="On" />

                    </RadioGroup>

                </LinearLayout>

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp">

                <View
                    android:layout_width="2.5dp"
                    android:layout_height="match_parent"
                    android:background="@color/colorPrimary" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:descendantFocusability="beforeDescendants"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="3dp"
                        android:text="WIDTH"
                        android:textColor="@android:color/black"
                        android:textSize="14sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/screenWidth"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="3dp"
                        android:text="screen: 1080px"
                        android:textColor="@android:color/black"
                        android:textSize="11sp" />

                    <FrameLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <com.sherchen.wanjiedemo.camera.AutoUnfocusEditText
                            android:id="@+id/width"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginRight="120dp"
                            android:hint="pixels"
                            android:inputType="number" />

                        <Button
                            android:id="@+id/widthUpdate"
                            android:layout_width="90dp"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical|right"
                            android:layout_marginRight="15dp"
                            android:backgroundTint="@color/colorPrimary"
                            android:gravity="center"
                            android:text="UPDATE"
                            android:textColor="@android:color/white"
                            android:textSize="14sp"
                            android:textStyle="bold" />

                    </FrameLayout>

                    <RadioGroup
                        android:id="@+id/widthModeRadioGroup"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="3dp"
                        android:checkedButton="@+id/widthCustom"
                        android:orientation="horizontal">

                        <RadioButton
                            android:id="@+id/widthCustom"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Custom" />

                        <RadioButton
                            android:id="@+id/widthWrapContent"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:text="wrap_content" />

                        <RadioButton
                            android:id="@+id/widthMatchParent"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:text="match_parent" />

                    </RadioGroup>

                </LinearLayout>

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp">

                <View
                    android:layout_width="2.5dp"
                    android:layout_height="match_parent"
                    android:background="@color/colorPrimary" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:descendantFocusability="beforeDescendants"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="3dp"
                        android:text="HEIGHT"
                        android:textColor="@android:color/black"
                        android:textSize="14sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/screenHeight"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="3dp"
                        android:text="screen: 1920px"
                        android:textColor="@android:color/black"
                        android:textSize="11sp" />

                    <FrameLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">

                        <com.sherchen.wanjiedemo.camera.AutoUnfocusEditText
                            android:id="@+id/height"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginRight="120dp"
                            android:hint="pixels"
                            android:inputType="number" />

                        <Button
                            android:id="@+id/heightUpdate"
                            android:layout_width="90dp"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical|right"
                            android:layout_marginRight="15dp"
                            android:backgroundTint="@color/colorPrimary"
                            android:gravity="center"
                            android:text="UPDATE"
                            android:textColor="@android:color/white"
                            android:textSize="14sp"
                            android:textStyle="bold" />

                    </FrameLayout>

                    <RadioGroup
                        android:id="@+id/heightModeRadioGroup"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="3dp"
                        android:checkedButton="@+id/heightCustom"
                        android:orientation="horizontal">

                        <RadioButton
                            android:id="@+id/heightCustom"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Custom" />

                        <RadioButton
                            android:id="@+id/heightWrapContent"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:text="wrap_content" />

                        <RadioButton
                            android:id="@+id/heightMatchParent"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:text="match_parent" />

                    </RadioGroup>

                </LinearLayout>

            </FrameLayout>

        </LinearLayout>

    </LinearLayout>

</ScrollView>


text:
package com.blazebit.persistence.view.testsuite.update.correlated.mutable.model;

import com.blazebit.persistence.testsuite.entity.Document;
import com.blazebit.persistence.testsuite.entity.Person;
import com.blazebit.persistence.view.EntityView;
import com.blazebit.persistence.view.EntityViewManager;
import com.blazebit.persistence.view.IdMapping;
import com.blazebit.persistence.view.MappingCorrelatedSimple;
import com.blazebit.persistence.view.UpdatableEntityView;

import java.util.List;

/**
 *
 * @author Christian Beikov
 * @since 1.3.0
 */
@UpdatableEntityView
@EntityView(Document.class)
public abstract class UpdatableDocumentWithCollectionsView {

    @IdMapping
    public abstract Long getId();

    public abstract Long getVersion();

    public abstract String getName();

    public abstract void setName(String name);

    @MappingCorrelatedSimple(correlated = Person.class, correlationBasis = "id", correlationExpression = "partnerDocument.id IN correlationKey")
    public abstract List<UpdatablePersonView> getPartners();

    public abstract void setPartners(List<UpdatablePersonView> partners);

    public void addPerson(UpdatablePersonView person) {
        getPartners().add(person);
        person.setPartnerDocument(evm().getReference(DocumentIdView.class, getId()));
    }

    abstract EntityViewManager evm();

}


text:
Core functionalities:
- Extraction: extracts component to new file and embeds it in the current file. Props are automatically passed to the new component.

(Folder default src/components/NAME/index.js) >> package.json @components
- to change the default folder, edit configuration "extractcomponent.path"

- Embedding: wraps selected component in a component of choice (e.g. View, ScrollView )

- Extract stylesheet inline

- Extract method render

![](https://github.com/zucska/extract-component/blob/master/extract-component.gif?raw=true)


text:
describe("Anagram", function() {

    var calculator = undefined;
    beforeEach(function() {
        calculator = new AnagramCalculator();
    });

    it("should be an empty list initially", function() {
        expect(calculator.getAnagrams().length).toEqual(0);
    });

    it("should be empty when two different words are added", function() {
        calculator.addWord("was");
        calculator.addWord("were");
        expect(calculator.getAnagrams().length).toEqual(0);
    });

    it("should be sized 1 when two items match", function() {
        calculator.addWord("was");
        calculator.addWord("saw");
        expect(calculator.getAnagrams().length).toEqual(1);
    });

    it("should be exactly the two items", function() {
        calculator.addWord("was");
        calculator.addWord("saw");
        calculator.addWord("draper");
        expect(calculator.getAnagrams()).toEqual([["was","saw"]]);
    });

    it("should accumulate two sets", function() {
        var words = ["tea","eat","peal","leap"];
        $.each(words,function(index,word) {
           calculator.addWord(word);
        });
        expect(calculator.getAnagrams()).toEqual([["tea","eat"],["peal","leap"]]);
    });

});


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Dashboard for /var/www/html/Album/vendor/zendframework/zendframework/library/Zend/Db</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/var/www/html/Album /

vendor /

zendframework /

zendframework /

library /

Zend /

Db

(Dashboard)

Class Coverage Distribution

Class Complexity

Top Project Risks

AbstractTableGateway (3306)

AbstractResultSet (1230)

TableGateway (110)

ResultSet (27)

Least Tested Methods

AbstractTableGateway::insert (0%)

AbstractTableGateway::insertWith (0%)

AbstractTableGateway::executeInsert (0%)

AbstractTableGateway::update (0%)

AbstractTableGateway::executeSelect (0%)

AbstractTableGateway::selectWith (0%)

AbstractTableGateway::getResultSetPrototype (0%)

AbstractTableGateway::getSql (0%)

AbstractTableGateway::select (0%)

AbstractTableGateway::updateWith (0%)

     Generated by PHP_CodeCoverage 1.2.13 using PHP 5.6.0-1+deb.sury.org~trusty+1 and PHPUnit 3.7.28 at Tue Oct 7 22:36:47 AMT 2014.


text:
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <arith_uint256.h>
#include <compressor.h>
#include <consensus/merkle.h>
#include <core_io.h>
#include <crypto/common.h>
#include <crypto/siphash.h>
#include <key_io.h>
#include <memusage.h>
#include <netbase.h>
#include <policy/settings.h>
#include <pow.h>
#include <pubkey.h>
#include <rpc/util.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <serialize.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <uint256.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/time.h>

#include <cassert>
#include <limits>
#include <vector>

void initialize()
{
    SelectParams(CBaseChainParams::REGTEST);
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    if (buffer.size() < sizeof(uint256) + sizeof(uint160)) {
        return;
    }
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const uint256 u256(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint256)));
    const uint160 u160(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint160)));
    const uint64_t u64 = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
    const int64_t i64 = fuzzed_data_provider.ConsumeIntegral<int64_t>();
    const uint32_t u32 = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
    const int32_t i32 = fuzzed_data_provider.ConsumeIntegral<int32_t>();
    const uint16_t u16 = fuzzed_data_provider.ConsumeIntegral<uint16_t>();
    const int16_t i16 = fuzzed_data_provider.ConsumeIntegral<int16_t>();
    const uint8_t u8 = fuzzed_data_provider.ConsumeIntegral<uint8_t>();
    const int8_t i8 = fuzzed_data_provider.ConsumeIntegral<int8_t>();
    // We cannot assume a specific value of std::is_signed<char>::value:
    // ConsumeIntegral<char>() instead of casting from {u,}int8_t.
    const char ch = fuzzed_data_provider.ConsumeIntegral<char>();

    const Consensus::Params& consensus_params = Params().GetConsensus();
    (void)CheckProofOfWork(u256, u32, consensus_params);
    (void)CompressAmount(u64);
    static const uint256 u256_min(uint256S("0000000000000000000000000000000000000000000000000000000000000000"));
    static const uint256 u256_max(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
    const std::vector<uint256> v256{u256, u256_min, u256_max};
    (void)ComputeMerkleRoot(v256);
    (void)CountBits(u64);
    (void)DecompressAmount(u64);
    (void)FormatISO8601Date(i64);
    (void)FormatISO8601DateTime(i64);
    (void)GetSizeOfCompactSize(u64);
    (void)GetSpecialScriptSize(u32);
    // (void)GetVirtualTransactionSize(i64, i64); // function defined only for a subset of int64_t inputs
    // (void)GetVirtualTransactionSize(i64, i64, u32); // function defined only for a subset of int64_t/uint32_t inputs
    (void)HexDigit(ch);
    (void)i64tostr(i64);
    (void)IsDigit(ch);
    (void)IsSpace(ch);
    (void)IsSwitchChar(ch);
    (void)itostr(i32);
    (void)memusage::DynamicUsage(ch);
    (void)memusage::DynamicUsage(i16);
    (void)memusage::DynamicUsage(i32);
    (void)memusage::DynamicUsage(i64);
    (void)memusage::DynamicUsage(i8);
    (void)memusage::DynamicUsage(u16);
    (void)memusage::DynamicUsage(u32);
    (void)memusage::DynamicUsage(u64);
    (void)memusage::DynamicUsage(u8);
    const unsigned char uch = static_cast<unsigned char>(u8);
    (void)memusage::DynamicUsage(uch);
    (void)MillisToTimeval(i64);
    const double d = ser_uint64_to_double(u64);
    assert(ser_double_to_uint64(d) == u64);
    const float f = ser_uint32_to_float(u32);
    assert(ser_float_to_uint32(f) == u32);
    (void)SighashToStr(uch);
    (void)SipHashUint256(u64, u64, u256);
    (void)SipHashUint256Extra(u64, u64, u256, u32);
    (void)ToLower(ch);

    const arith_uint256 au256 = UintToArith256(u256);
    assert(ArithToUint256(au256) == u256);
    assert(uint256S(au256.GetHex()) == u256);
    (void)au256.bits();
    (void)au256.GetCompact(/* fNegative= */ false);
    (void)au256.GetCompact(/* fNegative= */ true);
    (void)au256.getdouble();
    (void)au256.GetHex();
    (void)au256.GetLow64();
    (void)au256.size();
    (void)au256.ToString();

    const CKeyID key_id{u160};
    const CScriptID script_id{u160};
    // CTxDestination = CNoDestination ∪ PKHash ∪ ScriptHash ∪ WitnessV0ScriptHash ∪ WitnessV0KeyHash ∪ WitnessUnknown
    const PKHash pk_hash{u160};
    const ScriptHash script_hash{u160};
    const WitnessV0KeyHash witness_v0_key_hash{u160};
    const WitnessV0ScriptHash witness_v0_script_hash{u256};
    const std::vector<CTxDestination> destinations{pk_hash, script_hash, witness_v0_key_hash, witness_v0_script_hash};
    const SigningProvider store;
    for (const CTxDestination& destination : destinations) {
        (void)DescribeAddress(destination);
        (void)EncodeDestination(destination);
        (void)GetKeyForDestination(store, destination);
        (void)GetScriptForDestination(destination);
        (void)IsValidDestination(destination);
    }
}