text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Blog - João Martins Filho</title>

  <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet'
    type='text/css'>
  <link
    href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800'
    rel='stylesheet' type='text/css'>

  <link href="css/clean-blog.min.css" rel="stylesheet">

      Início
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse"
        data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false"
        aria-label="Toggle navigation">
        Menu

      </button>

            Sobre

            Contato

O que é QAOps?

Sua importancia para a Qualidade de Software

"Será possível ter uma cultura onde as pessoas têm coragem de falar a verdade
            quando erram para ajudar os times a resolver mais rápido os problemas em produção e evitar a recorrência?
            Como aumentar a frequência de deploys sem impactar a qualidade e minimizar a guerra entre os departamentos
            com a verdadeira colaboração e empatia?"

Começo meu primeiro artigo usando essas duas perguntas feitas no livro Jornada DevOps, essa pergunta até os
            dias atuais causa um grande impacto nas empresas, onde há a dificuldade e consenso entre os times de
            desenvolvimento e de operações (infraestrutura). Neste conflito originou-se a palavra DevOps que é a
            contração de dois termos em inglês que identifica as equipes envolvidas nas atividades de construção e
            implantação de um software:

Development: equipe responsável pela identificação dos requisitos com o cliente, a análise, o
              projeto,
              codificação e os testes.

Operations: equipe responsável pela implantação em produção, pelo monitoramento e pela solução de
              incidentes e problemas.

A criação desse conceito é originário de 2009 pela apresentação de John Allspaw e Paul Hammond na
            conferência Velocity da O'Reilly. Nesta apresentação John e Paul apresentaram "Mais de
                10 implantações por
                dia: Cooperação entre Dev e Ops no Flickr", onde a parte principal desta apresentação é
            Cooperação entre Dev
                e Ops, criando assim UMA CULTURA de trabalho mútuo entre dev e ops, na qual o maior objetivo
            dessa união é a
            entrega do software funcionando em produção de forma, ágil, segura e estável.

            Assim, com a aplicação bem-sucedida do DevOps, desencadeou o surgimento de práticas semelhantes, como
            DataOps, ArchOps, DevSecOps e QAOps, todas elas complementam a metodologia DevOps, com o objetivo de
            otimizar o ciclo de vida do desenvolvimento de software, mas afinal, QAOps o que significa?

          Ilustração de onde o QAOps desempenha o papel dentro de uma estrutura de
            times em uma empresa.

O QAOps combina responsabilidades de teste e garantia de qualidade, e tudo isso acompanha o desenvolvimento
            de software. Anteriormente, as responsabilidades pela qualidade de software não eram claramente atribuídas e
            supunha-se que os "testadores deveriam lidar com os problemas", fazendo com que ocorresse fraca capacidade
            de trabalho e resultados ineficientes. A cooperação entre os departamentos, a clara estratégia de qualidade
            de uma empresa e seu desenvolvimento na prática de QAOps formam as políticas básicas das empresas de rápido
            crescimento. As práticas básicas de QAOps incluem:

Teste Automatizado

Principal pilar da estrutura de QAOps. Teste automatizados significa executar testes com a ajuda de
            tecnologias e ferramentas e com um esforço humano mínimo. O QAOps deve estudar o produto em detalhes e
            entender as especificações antes de criar a estrutura de automação. Dependendo do produto e do estágio real
            de desenvolvimento, o QAOps pode decidir quais testes podem ser automatizados com sucesso para ajudar a
            economizar tempo e testar as funcionalidades de uma maneira mais eficaz.

Os tipos mais óbvios de teste que devem ser automatizados são os casos de teste de regressão. Esses tipos
            de teste consomem o tempo dos testadores, onde seria interessante utilizar esses testadores para criar casos
            de teste de automação. Da mesma forma, as funcionalidades que mais são executadas no produto, bem como as de
            suma importância para o funcionamento do produto devem ser automatizadas, pela razão que a medida que o
            produto cresce em funcionalidade e recursos, você não deseja que suas funções mais usadas falhem e criem uma
            experiência ruim para o usuário.

Vamos considerar uma história, João é um testador de software, encarregado de garantir a qualidade e a
            compatibilidade do navegador com o aplicativo da web. Para isso João deve para cada ticket em estágio de
            teste, deve testar nos navegadores mais famosos, sistemas operacionais mais famosos, bem como para
            cada ticket ele deve realizar um cadastro que é de suma importância para o funcionamento do produto que
            contém 20 campos de entrada de informações.

No começo, João pode achar até interessante realizar manualmente, contudo, com o passar do tempo vai se
            tornar uma tarefa desgastante e maçante, nesta parte João aceita uma frase bem popular no desenvolvimento de
            software "Computadores são desenvolvidos para fazer trabalhos repetitivos. Quando você faz trabalhos
              repetitivos, os computadores se juntam para rir de você...".
            Desta forma, João automatizando esses testes, terá tempo para realizar levantamento de informações para
            melhorar a qualidade do produto, bem como garantirá que erros de desenvolvimento não acontecerá no futuro em
            telas que estão cobertas por testes automatizados.

Teste Paralelo

            Como parte da estrutura QAOps, os testes devem ser executados rapidamente (em paralelo com o pipeline de
            entrega). O processo de teste automatizado garante uma aceleração no processo de teste, contudo, com o
            aumento da cobertura dos testes pode se criar gargalos de desempenho fazendo com que segure a entrega do
            código para o cliente.

            Ainda com o exemplo de João, com o tempo João conseguiu automatizar várias telas do produto web, contudo
            percebeu
            que a execução do teste para o navegador B é feito após o navegador A, sendo que os testes não há
            dependência entre
            eles. Assim João precisar fazer com que os testes se tornam paralelos onde os testes para o navegador A e os
            testes para navegador B, bem como os testes em rotinas interdependentes executem simutaneamente em paralelo,
            garantindo assim maior velocidade nos testes e rapida entrega ao cliente.

Integrando Dev & Ops ao controle de qualidade.

            A prática final para alcançar uma estrutura de QAOps é tornar as atividades de QA parte do pipeline de CI /
            CD. Uma das maneiras mais fáceis de integrar as operações de Desenvolvimento e qualidade é
            fazer com que os desenvolvedores escrevam casos de teste e para os engenheiros de operações de TI
            identificar
            possíveis problemas de UI / UX no aplicativo da Web por meio da assistência da equipe de qualidade. Isso
            oferece a oportunidade perfeita para os desenvolvedores e a qualidade colaborarem. Essa colaboração entre as
            diferentes partes
            interessadas apenas torna todo o processo de desenvolvimento e teste mais eficiente.

De volta a João, ele decidiu compartilhar sua perspectiva com seu gerente e partes interessadas. Ele
            percebeu que, quanto mais cedo os casos de teste são escritos, mais rápido se torna o lançamento no mercado.
            Ele sugeriu a implementação de testes shift-left para incorporar a estrutura de QAOps em sua empresa.
            Desde
            que o número de anomalias detectadas após a migração do pipeline de CI / CD foi notavelmente reduzido.

Ciclo Básico.

Em uma abordagem básico de desenvolvimento de DevOps e QAOps consistem em:

Um ambiente de integração contínua (com CI / CD) deve ser configurado para que os desenvolvedores e
              testadores executem os testes no código.

As equipes de desenvolvimento DEVEM realizar testes contínuos testando todas as novas funcionalidades
              criadas no aplicativo. Eles devem testar o aplicativo quanto à sua funcionalidade, desempenho, facilidade
              de uso da interface. Eles devem criar casos de teste agressivos para garantir todos os cenários de casos
              extremos para a funcionalidade criada. É o desenvolvedor que é a melhor pessoa para conhecer toda a
              funcionalidade em detalhes desde que a construiu.

Paralelamente, as equipes de qualidade devem começar a testar a nova funcionalidade para manter o
              andamento do pipeline de desenvolvimento, bem como realizar testes mais rígidos com foco no usuário e
              automatizar testes voltados ao usuário, como caso de testes end-to-end.

Após a conclusão do teste pela equipe de qualidade e a finalização, a equipe de operações de TI deve
              executar uma implantação do aplicativo Web e fornecer a finalização. Somente após a aprovação, o processo
              de liberação deve começar.

Da mesma forma, após as atividades de lançamento, a equipe de Operações de TI deve ficar de olho no
              aplicativo da web para garantir que tudo esteja funcionando conforme o esperado. Eles devem monitorar
              todos os aspectos do aplicativo para garantir a eficiência.

          Ao integrar o processo de teste contínuo ao processo de desenvolvimento de software, as empresas podem
          alcançar um ciclo de entrega bem-sucedido do produto.

Melhores Práticas

Com base na perspectiva da cultura QAOps, há um conjunto de práticas recomendadas para serem seguidas,
            como:

O processo de teste contínuo deve ser integrado ao ciclo de vida de desenvolvimento de software. Isso
              ajuda as empresas a reduzir os riscos e garantir uma liberação mais rápida do produto e tempo de
              lançamento no mercado.

Todas as equipes da organização (Dev, operações de TI, qualidade) devem fazer parte de todo o ciclo de
              lançamento. Eles devem garantir a colaboração e a comunicação eficaz durante todo o curso do lançamento.

O CI / CD deve ser feito regularmente, preferencialmente diariamente. O trabalho de todos deve ser
              mesclado no pipeline de liberação. Isso ajuda a identificar os defeitos nos estágios iniciais e
              corrigi-los antes que seja tarde demais.

As equipes de qualidade devem fazer parte do planejamento de liberação e do processo de coleta de
              requisitos. Será mais eficaz se as equipes de qualidade trabalharem junto com as equipes de
              desenvolvimento para fornecer contribuições vitais durante o desenvolvimento.

As métricas de cada equipe devem ser definidas e medidas em intervalos definidos durante o processo de
              liberação.

A equipe de qualidade devem usar ferramentas e scripts de automação para automatizar o máximo possível
              de testes. O teste de regressão profunda deve ser realizado nos recursos existentes quando uma nova
              funcionalidade é desenvolvida para garantir que os recursos existentes não sejam quebrados.

Os desenvolvedores devem começar a pensar como testadores, e os testadores devem fazer o vice-versa,
              (ie) corrigir o código. Isso faz com que todos na organização assumam a responsabilidade pela qualidade
              geral do produto.

Como o QAOps podem auxiliar em uma empresa?

O QAOps pode parecer um termo semelhante ao DevOps, contudo sua diferença é feita entre o conjunto de
            operações necessárias para ser colocada em prática. Para se criar uma cultura DevOps deve haver uma mudança
            cultural enorme, sendo que o QAOps realiza uma estruturação entre os desenvolvedores e testadores a fim de
            trabalharem mutuamente para obter resultados mais rápidos e testar novas partes do aplicativo antes do
            lançamento.

            Porém, para haver essa cultura de trabalho mútuo, deve haver a comunicação dos principais valores que
            estão em jogo para a melhor performance do produto, bem como o entendimento das partes que ambas as equipes
            são de suma importância para o produto.

            Refletindo suas vantagens e desvantagens da abordagem QAOps, deve-se
            notar que não existe uma verdade absoluta e que não existe abordagens que irão resolver todos os problemas
            do desenvolvimento de software. Um fato irrefutável é que a abordagem QAOps chama atenção para a questão da
            colaboração eficaz entre técnicas e a qualidade, fazendo com que garantem juntos a qualidade do código.

Espero que gostem, até a próxima :)

Referências

Manual
                De DevOps: Como obter agilidade, confiabilidade e segurança em organizações tecnológicas

                Jornada Devops: Unindo Cultura Ágil, Lean E Tecnologia Para Entrega De Software Com Qualidade

                O projeto fênix: Um Romance Sobre TI, DevOps e Sobre Ajudar o seu Negócio a Vencer

 The
                Cucumber for Java Book: Behaviour-Driven Development for Testers and Developers (English Edition)


text:
package proguard.optimize.info;

import proguard.classfile.ClassPool;
import proguard.classfile.visitor.ClassPoolVisitor;

/**
 * This ClassPoolVisitor repeatedly delegates to a given class pool visitor, as
 * long as it keeps setting a given flag.
 *
 * @author Eric Lafortune
 */
public class RepeatedClassPoolVisitor
implements   ClassPoolVisitor
{
    //*
    private static final boolean DEBUG = false;
    /*/
    private static       boolean DEBUG = System.getProperty("rcpv") != null;
    //*/

    private final MutableBoolean   repeatTrigger;
    private final ClassPoolVisitor classPoolVisitor;

    /**
     * Creates a new RepeatedClassPoolVisitor.
     * @param repeatTrigger    the mutable boolean flag that the class pool
     *                         visitor can set to indicate that the class pool
     *                         should be visited again.
     * @param classPoolVisitor the class pool visitor to apply.
     */
    public RepeatedClassPoolVisitor(MutableBoolean   repeatTrigger,
                                    ClassPoolVisitor classPoolVisitor)
    {
        this.repeatTrigger    = repeatTrigger;
        this.classPoolVisitor = classPoolVisitor;
    }

    // Implementations for ClassPoolVisitor.

    public void visitClassPool(ClassPool classPool)
    {
        // Visit all classes at least once, until the class visitors stop
        // setting the repeat trigger.
        do
        {
            if (DEBUG)
            {
                System.out.println("RepeatedClassPoolVisitor: new iteration");
            }

            repeatTrigger.reset();

            // Visit over all classes once.
            classPoolVisitor.visitClassPool(classPool);
        }
        while (repeatTrigger.isSet());

        if (DEBUG)
        {
            System.out.println("RepeatedClassPoolVisitor: done iterating");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var Biome = require('./biome');
var blocks = require('node-minecraft-data').blocks;

module.exports = Block;

function Block(type, biomeId, metadata) {
  this.type = type;
  this.metadata = metadata;
  this.light = 0;
  this.skyLight = 0;
  this.biome = new Biome(biomeId);
  this.position = null;

  var blockEnum = blocks[type];
  if(blockEnum) {
    this.name = blockEnum.name;
    this.hardness = blockEnum.hardness;
    this.displayName = blockEnum.displayName;
    if("variations" in blockEnum)
      for(var i in blockEnum["variations"]) {
        if(blockEnum["variations"][i].metadata === metadata)
          this.displayName = blockEnum["variations"][i].displayName;
      }
    this.boundingBox = blockEnum.boundingBox;
    this.diggable = blockEnum.diggable;
    this.material = blockEnum.material;
    this.harvestTools = blockEnum.harvestTools;
    this.drops = blockEnum.drops;
  } else {
    this.name = "";
    this.displayName = "";
    this.hardness = 0;
    this.boundingBox = "empty";
    this.diggable = false;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ShortcutRunner.HotkeyRegistration;

namespace ShortcutRunner.ShortcutParsing
{
    public interface IShortcutParser
    {
        ShortcutDescription Create(string shortcut);
    }

    public class ShortcutParser : IShortcutParser
    {
        public readonly IKeyParser KeyParser;

        public ShortcutParser(IKeyParser keyParser)
        {
            KeyParser = keyParser;
        }

        public ShortcutDescription Create(string shortcut)
        {
            if (shortcut == null)
            {
                throw new ArgumentNullException("shortcut");
            }

            try
            {
                return CreateShortcut(shortcut);
            }
            catch (ShortcutParsingException e)
            {
                e.Shortcut = shortcut;
                throw;
            }
        }

        private ShortcutDescription CreateShortcut(string shortcut)
        {
            var tokens = SplitToTokens(shortcut);

            return new ShortcutDescription(
                GetModifierKeys(tokens),
                GetKey(tokens));
        }

        private IKeyToken[] SplitToTokens(string shortcut)
        {
            return shortcut.Split('+')
                .Select(s => s.Trim())
                .Select(KeyParser.Parse)
                .ToArray();
        }

        private ModifierKeys GetModifierKeys(IEnumerable<IKeyToken> tokens)
        {
            return tokens
                .OfType<ModifierKeyToken>()
                .Select(p => p.ModifierKeys)
                .Aggregate(ModifierKeys.None, (a, b) => a | b);
        }

        private Keys GetKey(IEnumerable<IKeyToken> tokens)
        {
            var keyTokens = tokens
                .OfType<KeyToken>()
                .ToArray();

            if (keyTokens.Length > 1)
            {
                throw new MultipleNonModifierKeysException();
            }

            if (keyTokens.Length == 0)
            {
                throw new NoNonModifierKeysException();
            }

            return keyTokens
                .Single()
                .Key;
        }
    }
}


text:
class TeachersController < ApplicationController

  def new
    @teacher = Teacher.new
  end

  def create
    @teacher = Teacher.new(teacher_params)

    if @teacher.save
      redirect_to @teacher
    else
      render 'new'
    end
  end

  def show
    @teacher = Teacher.find(params[:id])
  end

  def index
    @teachers = Teacher.all
  end

  def edit
    @teacher = Teacher.find(params[:id])
  end

  def update
    @teacher = Teacher.find(params[:id])

    if @teacher.update(teacher_params)
      redirect_to @teacher
    else
      render 'edit'
    end
  end

  def destroy
    @teacher = Teacher.find(params[:id])
    @teacher.destroy

    redirect_to teachers_path
  end

  private
    def teacher_params
      params.require(:teacher).permit(:title, :text)
    end

end


text:
define(['lib/news_special/bootstrap', 'model/model', 'lib/vendors/tweenlite.min'], function (news, model, tweenlite) {

    'use strict';

    var Chapter5SvgMapsMediator = function () {

        /********************************************************
            * VARIABLES
        ********************************************************/
        this.chapterHolder = news.$('.chapter5Holder');
        this.wholeMapEl = this.chapterHolder.find('.chapter5wholeAfricaMap');

        this.malawiTooltipEl = this.wholeMapEl.find('#chapter5MalawiTooltip');
        this.angolaTooltipEl = this.wholeMapEl.find('#chapter5AngolaTooltip');
        this.sierraTooltipEl = this.wholeMapEl.find('#chapter5SierraTooltip');
        this.chadTooltipEl = this.wholeMapEl.find('#chapter5ChadTooltip');

        this.malawiEl = this.wholeMapEl.find('#chapter5MalawiEl');
        this.angolaEl = this.wholeMapEl.find('#chapter5AngolaEl');
        this.sierraEl = this.wholeMapEl.find('#chapter5SierraEl');
        this.chadEl = this.wholeMapEl.find('#chapter5ChadEl');

        this.deselectedCountryColor = 'rgb(178, 217, 217)';//'#B2D9D9';
        this.selectedCountryColor = 'rgb(0, 127, 127)'; //'#007F7F'

        this.malawiTweenObj = {prop:0};
        this.angolaTweenObj = {prop:0};
        this.sierraTweenObj = {prop:0};
        this.chadTweenObj = {prop:0};

        this.fallbackA = news.$('#chapter5FallbackImgA');
        this.fallbackB = news.$('#chapter5FallbackImgB');
        this.fallbackC = news.$('#chapter5FallbackImgC');
        this.fallbackD = news.$('#chapter5FallbackImgD');

        this.grnstck = window.GreenSockGlobals;
        this.iCanHazSvg = model.iCanHazSvg();

        /********************************************************
            * INIT STUFF
        ********************************************************/
        this.init();
    };

    Chapter5SvgMapsMediator.prototype = {

        init: function () {
            //hide all the tooltips!
            this.malawiTooltipEl.css({'opacity': 0, '-webkit-opacity': 0});
            this.angolaTooltipEl.css({'opacity': 0, '-webkit-opacity': 0});
            this.sierraTooltipEl.css({'opacity': 0, '-webkit-opacity': 0});
            this.chadTooltipEl.css({'opacity': 0, '-webkit-opacity': 0});

            this.malawiEl.attr("class", "chapter5MapElAnim");
            this.angolaEl.attr("class", "chapter5MapElAnim");
            this.sierraEl.attr("class", "chapter5MapElAnim");
            this.chadEl.attr("class", "chapter5MapElAnim");

            this.malawiEl.css('fill', this.deselectedCountryColor);
            this.angolaEl.css('fill', this.deselectedCountryColor);
            this.sierraEl.css('fill', this.deselectedCountryColor);
            this.chadEl.css('fill', this.deselectedCountryColor);

            this.fallbackB.css({'opacity':0, '-webkit-opacity':0});
            this.fallbackC.css({'opacity':0, '-webkit-opacity':0});
            this.fallbackD.css({'opacity':0, '-webkit-opacity':0});
        },

        showMap: function () {
            this.chapterHolder.css({
                'opacity': 0,
                '-webkit-opacity': 0
            });
            this.chapterHolder.removeClass('hideEl');

            var tweenObj = {prop:0}, targetEl = this.chapterHolder;
            this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:1, onUpdate:function () {
                targetEl.css({
                    'opacity': tweenObj.prop,
                    '-webkit-opacity': tweenObj.prop
                });
            }});
        },

        removeMap: function () {
            var targetEl = this.chapterHolder, currentOpacityNum = Number(targetEl.css('opacity')), tweenObj = {prop:currentOpacityNum}, tweenDuration = 1.5 * currentOpacityNum;
            this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:0, onUpdate:function () {
                targetEl.css({
                    'opacity': tweenObj.prop,
                    '-webkit-opacity': tweenObj.prop
                });
            }, onComplete:function () {
                targetEl.addClass('hideEl');
            }});
        },

        showMalawiVal: function () {

            var targetEl, tweenObj;
            if (this.iCanHazSvg) {
                this.malawiEl.css('fill', this.selectedCountryColor);

                var currentOpacityVal = Number(this.malawiTooltipEl.css('opacity'));
                this.malawiTweenObj.prop = currentOpacityVal;

                targetEl = this.malawiTooltipEl;
                var tweenDuration = 1.5 * (1 - currentOpacityVal);
                tweenObj = this.malawiTweenObj;

                targetEl.css({
                    'opacity': currentOpacityVal,
                    '-webkit-opacity': currentOpacityVal
                });
                this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:1, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop
                    });
                }});
            }
            else {
                targetEl = this.fallbackA;
                tweenObj = {prop:0};
                this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:1, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop,
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (tweenObj.prop * 100) + ')'
                    });
                }});
            }

        },

        hideMalawiVal: function () {

            var targetEl, tweenObj;

            if (this.iCanHazSvg) {
                this.malawiEl.css('fill', this.deselectedCountryColor);

                var currentOpacityVal = Number(this.malawiTooltipEl.css('opacity'));
                this.malawiTweenObj.prop = currentOpacityVal;

                targetEl = this.malawiTooltipEl;
                var tweenDuration = 1.5 * currentOpacityVal;
                tweenObj = this.malawiTweenObj;

                targetEl.css({
                    'opacity': currentOpacityVal,
                    '-webkit-opacity': currentOpacityVal
                });
                this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:0, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop
                    });
                }});
            }
            else {
                targetEl = this.fallbackA;
                tweenObj = {prop:1};
                this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:0, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop,
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (tweenObj.prop * 100) + ')'
                    });
                }});
            }
        },

        showAngolaVal: function () {
            var targetEl, tweenObj;

            if (this.iCanHazSvg) {
                this.angolaEl.css('fill', this.selectedCountryColor);

                var currentOpacityVal = Number(this.angolaTooltipEl.css('opacity'));
                this.malawiTweenObj.prop = currentOpacityVal;

                targetEl = this.angolaTooltipEl;
                var tweenDuration = 1.5 * (1 - currentOpacityVal);
                tweenObj = this.angolaTweenObj;

                targetEl.css({
                    'opacity': currentOpacityVal,
                    '-webkit-opacity': currentOpacityVal,
                    '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (currentOpacityVal * 100) + ')'
                });
                this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:1, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop
                    });
                }});
            }
            else {
                targetEl = this.fallbackB;
                tweenObj = {prop:0};
                this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:1, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop,
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (tweenObj.prop * 100) + ')'
                    });
                }});
            }
        },

        hideAngolaVal: function () {
            var targetEl, tweenObj;

            if (this.iCanHazSvg) {
                this.angolaEl.css('fill', this.deselectedCountryColor);

                var currentOpacityVal = Number(this.angolaTooltipEl.css('opacity'));
                this.malawiTweenObj.prop = currentOpacityVal;

                targetEl = this.angolaTooltipEl;
                var tweenDuration = 1.5 * currentOpacityVal;
                tweenObj = this.angolaTweenObj;

                targetEl.css({
                    'opacity': currentOpacityVal,
                    '-webkit-opacity': currentOpacityVal
                });
                this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:0, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop
                    });
                }});
            }
            else {
                targetEl = this.fallbackB;
                tweenObj = {prop:1};
                this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:0, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop,
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (tweenObj.prop * 100) + ')'
                    });
                }});
            }
        },

        showSierraVal: function () {
            var targetEl, tweenObj;

            if (this.iCanHazSvg) {
                this.sierraEl.css('fill', this.selectedCountryColor);

                var currentOpacityVal = Number(this.sierraTooltipEl.css('opacity'));
                this.malawiTweenObj.prop = currentOpacityVal;

                targetEl = this.sierraTooltipEl;
                var tweenDuration = 1.5 * (1 - currentOpacityVal);
                tweenObj = this.sierraTweenObj;

                targetEl.css({
                    'opacity': currentOpacityVal,
                    '-webkit-opacity': currentOpacityVal
                });
                this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:1, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop
                    });
                }});
            }
            else {
                targetEl = this.fallbackC;
                tweenObj = {prop:0};
                this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:1, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop,
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (tweenObj.prop * 100) + ')'
                    });
                }});
            }
        },

        hideSierraVal: function () {
            var targetEl, tweenObj;

            if (this.iCanHazSvg) {
                this.sierraEl.css('fill', this.deselectedCountryColor);

                var currentOpacityVal = Number(this.sierraTooltipEl.css('opacity'));
                this.malawiTweenObj.prop = currentOpacityVal;

                targetEl = this.sierraTooltipEl;
                var tweenDuration = 1.5 * currentOpacityVal;
                tweenObj = this.sierraTweenObj;

                targetEl.css({
                    'opacity': currentOpacityVal,
                    '-webkit-opacity': currentOpacityVal
                });
                this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:0, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop
                    });
                }});
            }
            else {
                targetEl = this.fallbackC;
                tweenObj = {prop:1};
                this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:0, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop,
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (tweenObj.prop * 100) + ')'
                    });
                }});
            }
        },

        showChadVal: function () {
            var targetEl, tweenObj;

            if (this.iCanHazSvg) {
                this.chadEl.css('fill', this.selectedCountryColor);

                var currentOpacityVal = Number(this.chadTooltipEl.css('opacity'));
                this.malawiTweenObj.prop = currentOpacityVal;

                targetEl = this.chadTooltipEl;
                var tweenDuration = 1.5 * (1 - currentOpacityVal);
                tweenObj = this.chadTweenObj;

                targetEl.css({
                    'opacity': currentOpacityVal,
                    '-webkit-opacity': currentOpacityVal
                });
                this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:1, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop
                    });
                }});
            }
            else {
                targetEl = this.fallbackD;
                tweenObj = {prop:0};
                this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:1, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop,
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (tweenObj.prop * 100) + ')'
                    });
                }});
            }
        },

        hideChadVal: function () {
            var targetEl, tweenObj;

            if (this.iCanHazSvg) {
                this.chadEl.css('fill', this.deselectedCountryColor);

                var currentOpacityVal = Number(this.chadTooltipEl.css('opacity'));
                this.malawiTweenObj.prop = currentOpacityVal;

                targetEl = this.chadTooltipEl;
                var tweenDuration = 1.5 * currentOpacityVal;
                tweenObj = this.chadTweenObj;

                targetEl.css({
                    'opacity': currentOpacityVal,
                    '-webkit-opacity': currentOpacityVal
                });
                this.grnstck.tweenlite.to(tweenObj, tweenDuration, {prop:0, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop
                    });
                }});
            }
            else {
                targetEl = this.fallbackD;
                tweenObj = {prop:1};
                this.grnstck.tweenlite.to(tweenObj, 1.5, {prop:0, onUpdate:function () {
                    targetEl.css({
                        'opacity': tweenObj.prop,
                        '-webkit-opacity': tweenObj.prop,
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (tweenObj.prop * 100) + ')'
                    });
                }});
            }
        }

    };

    return Chapter5SvgMapsMediator;

});


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  var BaseDialog = require('utils/dialogs/dialog');
  var TemplateHTML = require('hbs!./reserve/html');
  var Sunstone = require('sunstone');
  var Locale = require('utils/locale');
  var Tips = require('utils/tips');
  var WizardFields = require('utils/wizard-fields');
  var VNetsTable = require('tabs/vnets-tab/datatable');
  var ARsTable = require('./reserve/ar-datatable');

  /*
    CONSTANTS
   */

  var DIALOG_ID = require('./reserve/dialogId');

  /*
    CONSTRUCTOR
   */

  function Dialog() {
    var that = this;

    this.dialogId = DIALOG_ID;

    BaseDialog.call(this);
  }

  Dialog.DIALOG_ID = DIALOG_ID;
  Dialog.prototype = Object.create(BaseDialog.prototype);
  Dialog.prototype.constructor = Dialog;
  Dialog.prototype.html = _html;
  Dialog.prototype.onShow = _onShow;
  Dialog.prototype.setup = _setup;
  Dialog.prototype.setParams = _setParams;

  return Dialog;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    var that = this;

    var opts = {
      info: false,
      select: true,
      selectOptions: {
        filter_fn: function(vnet){
          return (vnet['PARENT_NETWORK_ID'] == that.vnetId);
        }
      }
    };

    this.vnetsTable = new VNetsTable("reserve", opts);

    var arOpts = {
      info: false,
      select: true,
      vnetId: this.vnetId
    };

    this.arsTable = new ARsTable("ar_reserve", arOpts);

    return TemplateHTML({
      'vnetsTableHTML': this.vnetsTable.dataTableHTML,
      'arsTableHTML': this.arsTable.dataTableHTML
    });
  }

  function _setup(context) {
    var that = this;

    $('input[name="reserve_target"]',context).change(function(){
      $('div#reserve_new_body', context).hide();
      $('div#reserve_add_body', context).hide();

      $('input', $('div#reserve_new_body', context)).prop('wizard_field_disabled', true);
      $('input', $('div#reserve_add_body', context)).prop('wizard_field_disabled', true);

      switch($(this).val()){
        case "NEW":
          $('div#reserve_new_body', context).show();
          $('input', $('div#reserve_new_body', context)).prop('wizard_field_disabled', false);
          break;
        case "ADD":
          $('div#reserve_add_body', context).show();
          $('input', $('div#reserve_add_body', context)).prop('wizard_field_disabled', false);
          break;
      }
    });

    $('input#reserve_new', context).prop('checked', true);
    $('input#reserve_new', context).change();

    that.vnetsTable.idInput().attr("wizard_field", "vnet");
    that.arsTable.idInput().attr("wizard_field", "ar_id");

    this.vnetsTable.initialize();
    this.arsTable.initialize();

    Tips.setup(context);

    $('#reserve_form',context).submit(function(){
      var data = WizardFields.retrieve(context);

      Sunstone.runAction('Network.reserve', that.vnetId, data);

      return false;
    });
  }

  function _onShow(context) {
    this.vnetsTable.refreshResourceTableSelect();
    this.arsTable.refreshResourceTableSelect();
  }

  /**
   * [_setParams description]
   * @param {object} params
   *        - params.vnetId : Virtual Network id
   */
  function _setParams(params) {
    this.vnetId = params.vnetId;

    $('#vnet_id', this.dialogElement).text(params.vnetId);
  }
});


text:
package main

// TODO: xbrli:unit
// TODO: namespace us-gaap:
// TODO: namespace dei:
// TODO: cistom namespaces e.g.: appl:
// TODO: <link:schemaRef xlink:href="aapl-20180929.xsd" xlink:type="simple" />

type Document struct {
  Contexts []Context `xml:"context"`
  Units    []Unit    `xml:"xbrli unit"`
}

type Context struct {
  Id      string     `xml:"id,attr"`
  // Value   string     `xml:",chardata"`
  Entity  Entity     `xml:"entity"`
  Period  Period     `xml:"period"`
}

type Entity struct {
  Identifier string  `xml:"identifier,omitempty"`
  Segment    Segment `xml:"segment"`
}

type Segment struct {
  Members   []Member `xml:"explicitMember"`
}

type Member struct {
  Dimension  string  `xml:"dimension,attr"`
  Value      string  `xml:",chardata"`
}

type Period struct {
  Instant    string `xml:"instant,omitempty"`
  StartDate  string `xml:"startDate,omitempty"`
  EndDate    string `xml:"endDate,omitempty"`
}

type Unit struct {
  Id         string `xml:"id,attr"`
}


text:
<?php
namespace NewRelicTest\Listener;

use NewRelic\Client;
use NewRelic\Listener\RequestListener;
use NewRelic\ModuleOptions;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;

class RequestListenerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ModuleOptions
     */
    protected $moduleOptions;

    /**
     * @var Client
     */
    protected $client;

    /**
     * @var RequestListener
     */
    protected $listener;

    /**
     * @var MvcEvent
     */
    protected $event;

    public function setUp()
    {
        $this->listener = new RequestListener();

        $this->moduleOptions = new ModuleOptions();
        $this->listener->setModuleOptions($this->moduleOptions);

        $this->client = $this->getMockBuilder(Client::class)
            ->disableOriginalConstructor()
            ->getMock();
        $this->listener->setClient($this->client);

        $this->event = new MvcEvent();
    }

    public function testOnRequestWithoutRouteMatch()
    {
        $this->client
            ->expects($this->never())
            ->method('nameTransaction');

        $this->listener->onRequest($this->event);
    }

    public function testOnRequestWithRouteMatch()
    {
        $this->client
            ->expects($this->once())
            ->method('nameTransaction');

        $routeMatch = new RouteMatch([]);
        $this->event->setRouteMatch($routeMatch);

        $this->listener->onRequest($this->event);
    }

    public function testAppNameNotSetWhenMissingInConfig()
    {
        $this->moduleOptions->setApplicationName('');

        $this->client
            ->expects($this->never())
            ->method('setAppName');

        $routeMatch = new RouteMatch([]);
        $this->event->setRouteMatch($routeMatch);

        $this->listener->onRequest($this->event);
    }
}


text:
package com.twitter.finagle.memcached.replication

import _root_.java.lang.{Boolean => JBoolean, Long => JLong}

import scala.util.Random

import com.twitter.conversions.time._
import com.twitter.finagle.builder.{Cluster, ClientBuilder, ClientConfig}
import com.twitter.finagle.Group
import com.twitter.finagle.memcached._
import com.twitter.finagle.memcached.protocol.Value
import com.twitter.finagle.stats.{StatsReceiver, NullStatsReceiver}
import com.twitter.io.Buf
import com.twitter.util._

sealed trait ReplicationStatus[T]

/**
 * Indicating a consistent state across all replicas, which comes with the agreed consistent result;
 */
case class ConsistentReplication[T](result: T) extends ReplicationStatus[T]

/**
 * Indicating an inconsistent state across all replicas, which comes with a sequence of result
 * from all replicas; each replica's result can be either Return[T] or Throw[T]
 */
case class InconsistentReplication[T](resultSeq: Seq[Try[T]]) extends ReplicationStatus[T]

/**
 * indicating a failed state from all replicas, which comes with a sequence of failures from
 * all replicas;
 */
case class FailedReplication[T](failureSeq: Seq[Throw[T]]) extends ReplicationStatus[T]

/**
 * Wrapping underlying replicas cas unique values for replication purpose.
 */
trait ReplicaCasUnique
case class RCasUnique(uniques: Seq[Buf]) extends ReplicaCasUnique
case class SCasUnique(casUnique: Buf) extends ReplicaCasUnique

/**
 * Replication client helper
 */
object ReplicationClient {
  def newBaseReplicationClient(
    pools: Seq[Cluster[CacheNode]],
    clientBuilder: Option[ClientBuilder[_, _, _, _, ClientConfig.Yes]] = None,
    hashName: Option[String] = None,
    failureAccrualParams: (Int, () => Duration) = (5, () => 30.seconds)
  ) = {
    val underlyingClients = pools map { pool =>
      Await.result(pool.ready)
      KetamaClientBuilder(Group.fromCluster(pool), hashName, clientBuilder, failureAccrualParams).build()
    }
    val repStatsReceiver =
      clientBuilder map { _.statsReceiver.scope("cache_replication") } getOrElse(NullStatsReceiver)
    new BaseReplicationClient(underlyingClients, repStatsReceiver)
  }

  def newSimpleReplicationClient(
    pools: Seq[Cluster[CacheNode]],
    clientBuilder: Option[ClientBuilder[_, _, _, _, ClientConfig.Yes]] = None,
    hashName: Option[String] = None,
    failureAccrualParams: (Int, () => Duration) = (5, () => 30.seconds)
  ) = {
    new SimpleReplicationClient(newBaseReplicationClient(pools, clientBuilder, hashName, failureAccrualParams))
  }
}

/**
 * Base replication client. This client manages a list of base memcached clients representing
 * cache replicas. All replication API returns ReplicationStatus object indicating the underlying
 * replicas consistency state.
 * @param clients list of memcached clients with each one representing to a single cache pool
 * @param statsReceiver
 */
class BaseReplicationClient(clients: Seq[Client], statsReceiver: StatsReceiver = NullStatsReceiver) {
  private[this] val inconsistentContentCounter = statsReceiver.counter("inconsistent_content_count")
  private[this] val failedCounter = statsReceiver.counter("failed_replication_count")

  assert(!clients.isEmpty)

  /**
   * Return GetResult object that aggregates all hits, misses and failures.
   * This method will send the requested keys to each underlying replicas in a fixed order or
   * random order, and will stop passing along a key if a replica has returned 'hit'.
   *
   * TODO: introducing BackupRequestFilter to shorten the waiting period for secondary requests
   */
  private[memcached] def getResult(keys: Iterable[String], useRandomOrder: Boolean): Future[GetResult] = {
    val clientsInOrder = if (useRandomOrder) Random.shuffle(clients) else clients

    def loopGet(clients: Seq[Client], currentRes: GetResult): Future[GetResult] = clients match {
      case _ if currentRes.misses.isEmpty &&
          currentRes.failures.isEmpty => Future.value(currentRes)
      case Seq() => Future.value(currentRes)
      case Seq(c, tail@_*) =>
        val missing = currentRes.misses ++ currentRes.failures.keySet
        c.getResult(missing) flatMap { case res =>
          val newRes = GetResult.merged(Seq(GetResult(currentRes.hits), res))
          loopGet(tail, newRes)
        }
    }

    loopGet(clientsInOrder, GetResult(Map.empty, keys.toSet))
  }

  /**
   * Get one value for the input keys from the underlying replicas.
   * For each input key, this operation searches all replicas in an order until it finds the
   * first hit result, or return the last replica's result.
   */
  def getOne(key: String, useRandomOrder: Boolean = false): Future[Option[Buf]] =
    getOne(Seq(key), useRandomOrder) map { _.values.headOption }

  def getOne(keys: Iterable[String], useRandomOrder: Boolean): Future[Map[String, Buf]] =
    getResult(keys, useRandomOrder) flatMap { result =>
      if (result.failures.nonEmpty)
        Future.exception(result.failures.values.head)
      else
        Future.value(result.values)
    }

  /**
   * Get replication status for the input keys from the underlying replicas.
   * For each input key, this operation returns the aggregated replication status after requesting
   * all replicas.
   */
  def getAll(key: String): Future[ReplicationStatus[Option[Buf]]] =
    getAll(Seq(key)) map { _.values.head }

  def getAll(keys: Iterable[String]): Future[Map[String, ReplicationStatus[Option[Buf]]]] = {
    val keySet = keys.toSet
    Future.collect(clients map { _.getResult(keySet) }) map {
      results: Seq[GetResult] =>
        keySet.map { k =>
          val replicasResult = results map {
            case r if (r.hits.contains(k)) => Return(Some(r.hits.get(k).get.value))
            case r if (r.misses.contains(k)) => Return(None)
            case r if (r.failures.contains(k)) => Throw(r.failures.get(k).get)
          }
          k -> toReplicationStatus(replicasResult)
        }.toMap
    }
  }

  /**
   * Get replication status for the input keys and their checksum. The aggregated results returned
   * can be either of these three cases:
   * - ConsistentReplication, indicating consistent value across all replicas, which comes with
   * an aggregated cas unique to be used for CAS;
   *
   * - InconsistentReplication, indicating inconsistent values across all replicas, which comes
   * with each replica's own cas unique id;
   *
   * - FailedReplication, indicating failures from all replicas;
   */
  def getsAll(key: String): Future[ReplicationStatus[Option[(Buf, ReplicaCasUnique)]]] =
    getsAll(Seq(key)) map { _.values.head }

  def getsAll(keys: Iterable[String]): Future[Map[String, ReplicationStatus[Option[(Buf, ReplicaCasUnique)]]]] = {
    val keySet = keys.toSet
    Future.collect(clients map { _.getsResult(keySet) }) map {
      results: Seq[GetsResult] =>
        keySet.map { k =>
          val replicasResult = results map {
            case r if (r.hits.contains(k)) => Return(Some(r.hits.get(k).get.value))
            case r if (r.misses.contains(k)) => Return(None)
            case r if (r.failures.contains(k)) => Throw(r.failures.get(k).get)
          }

          k -> attachCas(toReplicationStatus(replicasResult), results, k)
        }.toMap
    }
  }

  // attach replication cas unique to the result for clients to do following CAS;
  // if all replicas are consistent, a RCasUnique is attached,
  // otherwise individual SCasUnique is attached
  private[this] def attachCas(
    valueStatus: ReplicationStatus[Option[Buf]],
    underlyingResults: Seq[GetsResult],
    key: String
  ): ReplicationStatus[Option[(Buf, ReplicaCasUnique)]] =
    valueStatus match {
      case ConsistentReplication(Some(v)) =>
        val allReplicasCas = underlyingResults map {_.hits.get(key).get.casUnique.get}
        ConsistentReplication(Some((v, RCasUnique(allReplicasCas))))
      case ConsistentReplication(None) => ConsistentReplication(None)
      case InconsistentReplication(rs) =>
        val transformed = rs.zip(underlyingResults) map {
          case (Return(Some(v)), r: GetsResult) =>
            val singleReplicaCas = r.hits.get(key).get.casUnique.get
            Return(Some((v, SCasUnique(singleReplicaCas))))
          case (Return(None), _) => Return(None)
          case (Throw(e), _) => Throw(e)
        }
        InconsistentReplication(transformed)
      case FailedReplication(fs) =>
        FailedReplication(fs map { t => Throw(t.e)})
    }

  /**
   * Stores a key in all replicas and returns the aggregated replication status.
   */
  def set(key: String, value: Buf): Future[ReplicationStatus[Unit]] =
    set(key, 0, Time.epoch, value)

  def set(key: String, flags: Int, expiry: Time, value: Buf): Future[ReplicationStatus[Unit]] =
    collectAndResolve[Unit](_.set(key, flags, expiry, value))

  /**
   * Attempts to perform a CAS operation on all replicas, and returns the aggregated replication status.
   */
  def checkAndSet(key: String, value: Buf, casUniques: Seq[Buf]): Future[ReplicationStatus[CasResult]] =
    checkAndSet(key, 0, Time.epoch, value, casUniques)

  def checkAndSet(key: String, flags: Int, expiry: Time, value: Buf, casUniques: Seq[Buf]): Future[ReplicationStatus[CasResult]] = {
    assert(clients.size == casUniques.size)

    // cannot use collectAndResolve helper here as this is the only case where there's no common op
    Future.collect((clients zip casUniques) map {
      case (c, u) =>
        c.checkAndSet(key, flags, expiry, value, u).transform(Future.value)
    }) map { toReplicationStatus }
  }

  /**
   * Remove a key and returns the aggregated replication status.
   */
  def delete(key: String): Future[ReplicationStatus[JBoolean]] =
    collectAndResolve[JBoolean](_.delete(key))

  /**
   * Store a key in all replicas but only if it doesn't already exist on the server, and returns
   * the aggregated replication status.
   */
  def add(key: String, value: Buf): Future[ReplicationStatus[JBoolean]] =
    add(key, 0, Time.epoch, value)

  def add(key: String, flags: Int, expiry: Time, value: Buf): Future[ReplicationStatus[JBoolean]] =
    collectAndResolve[JBoolean](_.add(key, flags, expiry, value))

  /**
   * Replace existing key in all replicas, and returns the aggregated replication status.
   */
  def replace(key: String, value: Buf): Future[ReplicationStatus[JBoolean]] =
    replace(key, 0, Time.epoch, value)

  def replace(key: String, flags: Int, expiry: Time, value: Buf): Future[ReplicationStatus[JBoolean]] =
    collectAndResolve[JBoolean](_.replace(key, flags, expiry, value))

  /**
   * Increment a key and returns the aggregated replication status.
   */
  def incr(key: String): Future[ReplicationStatus[Option[JLong]]] = incr(key, 1L)

  def incr(key: String, delta: Long): Future[ReplicationStatus[Option[JLong]]] =
    collectAndResolve[Option[JLong]](_.incr(key, delta))

  /**
   * Decrement a key and returns the aggregated replication status.
   */
  def decr(key: String): Future[ReplicationStatus[Option[JLong]]] = decr(key, 1L)

  def decr(key: String, delta: Long): Future[ReplicationStatus[Option[JLong]]] =
    collectAndResolve[Option[JLong]](_.decr(key, delta))

  /**
   * Unsupported operation yet
   */
  def append(key: String, value: Buf): Future[ReplicationStatus[JBoolean]] =
    append(key, 0, Time.epoch, value)
  def append(key: String, flags: Int, expiry: Time, value: Buf): Future[ReplicationStatus[JBoolean]] =
    throw new UnsupportedOperationException("append is not supported for cache replication client.")

  /**
   * Unsupported operation yet
   */
  def prepend(key: String, value: Buf): Future[ReplicationStatus[JBoolean]] =
    prepend(key, 0, Time.epoch, value)
  def prepend(key: String, flags: Int, expiry: Time, value: Buf): Future[ReplicationStatus[JBoolean]] =
    throw new UnsupportedOperationException("prepend is not supported for cache replication client.")

  /**
   * Unsupported operation yet
   */
  def stats(args: Option[String]): Future[Seq[String]] =
    throw new UnsupportedOperationException("stats is not supported for cache replication client.")

  def release() {
    clients foreach { _.release() }
  }

  /**
   * Translating the results sequence from all replicas into aggregated results, which can be
   * either of these three sub-types of ReplicationStatus:
   *
   * - ConsistentReplication, indicating a consistent state across all replicas, which comes with
   * the agreed consistent result;
   *
   * - InconsistentReplication, indicating an inconsistent state across all replicas, which comes
   * with a sequence of result from all replicas;
   *
   * - FailedReplication, indicating a failed state from all replicas, which comes with a sequence
   * of failures from all replicas;
   */
  private[this] def toReplicationStatus[T](results: Seq[Try[T]]): ReplicationStatus[T] = {
    results match {
      case _ if (results.forall(_.isReturn)) && (results.distinct.size == 1) =>
        ConsistentReplication(results.head.get())
      case _ if (results.exists(_.isReturn)) =>
        inconsistentContentCounter.incr()
        InconsistentReplication(results)
      case _ =>
        failedCounter.incr()
        FailedReplication(results collect {case t@Throw(_) => t})
    }
  }

  /**
   * Private helper to collect all underlying clients result for a given operation
   * and resolve them to the ReplicationStatus to tell the consistency
   */
  private[this] def collectAndResolve[T](op: Client => Future[T]) =
    Future.collect(clients map {
      op(_).transform(Future.value)
    }) map { toReplicationStatus }
}

/**
 * Simple replication client wrapper that's compatible with base memcached client.
 * This simple replication client handles inconsistent state across underlying replicas in a
 * naive way:
 * - operation would succeed only if it succeeds on all replicas
 * - inconsistent data across replicas will be treated as key missing
 * - any replica's failure will make the operation throw
 */
case class SimpleReplicationFailure(msg: String) extends Throwable(msg)

class SimpleReplicationClient(underlying: BaseReplicationClient) extends Client {
  def this(clients: Seq[Client], statsReceiver: StatsReceiver = NullStatsReceiver) =
    this(new BaseReplicationClient(clients, statsReceiver))

  private[this] val underlyingClient = underlying

  /**
   * Returns the first result found within all replicas, or miss/failure depends on the last replica
   */
  def getResult(keys: Iterable[String]): Future[GetResult] =
    underlyingClient.getResult(keys, useRandomOrder = false)

  /**
   * Only returns the consistent result from all replicas; if the data is inconsistent, this client simply
   * returns nothing just like key missing; if any failure occurs, this method returns failure
   * as there's a great chance the check-and-set won't succeed.
   */
  def getsResult(keys: Iterable[String]): Future[GetsResult] =
    underlyingClient.getsAll(keys) map {
      resultsMap =>
        val getsResultSeq = resultsMap map {
          case (key, ConsistentReplication(Some((value, RCasUnique(uniques))))) =>
            val newCas = uniques map { case Buf.Utf8(s) => s } mkString("|")
            val newValue = Value(Buf.Utf8(key), value, Some(Buf.Utf8(newCas)))
            GetsResult(GetResult(hits = Map(key -> newValue)))
          case (key, ConsistentReplication(None)) =>
            GetsResult(GetResult(misses = Set(key)))
          case (key, InconsistentReplication(resultsSeq)) if resultsSeq.forall(_.isReturn) =>
            GetsResult(GetResult(misses = Set(key)))
          case (key, _) =>
            GetsResult(GetResult(failures = Map(key -> SimpleReplicationFailure("One or more underlying replica failed gets"))))
        }
        GetResult.merged(getsResultSeq.toSeq)
    }

  /**
   * Store a key in all replicas, succeed only if all replicas succeed.
   */
  def set(key: String, flags: Int, expiry: Time, value: Buf) =
    resolve[Unit]("set", _.set(key, flags, expiry, value), ())

  /**
   * Check and set a key, succeed only if all replicas succeed.
   */
  def checkAndSet(key: String, flags: Int, expiry: Time, value: Buf, casUnique: Buf): Future[CasResult] =
  {
    val Buf.Utf8(casUniqueStr) = casUnique
    val casUniqueBufs = casUniqueStr.split('|') map { Buf.Utf8(_) }
    resolve[CasResult]("checkAndSet", _.checkAndSet(key, flags, expiry, value, casUniqueBufs), CasResult.Stored)
  }

  /**
   * Delete a key from all replicas, succeed only if all replicas succeed.
   */
  def delete(key: String) =
    resolve[JBoolean]("delete", _.delete(key), false)

  /**
   * Add a new key to all replicas, succeed only if all replicas succeed.
   */
  def add(key: String, flags: Int, expiry: Time, value: Buf) =
    resolve[JBoolean]("add", _.add(key, flags, expiry, value), false)

  /**
   * Replace an existing key in all replicas, succeed only if all replicas succeed.
   */
  def replace(key: String, flags: Int, expiry: Time, value: Buf) =
    resolve[JBoolean]("replace", _.replace(key, flags, expiry, value), false)

  /**
   * Increase an existing key in all replicas, succeed only if all replicas succeed.
   */
  def incr(key: String, delta: Long): Future[Option[JLong]] =
    resolve[Option[JLong]]("incr", _.incr(key, delta), None)

  /**
   * Decrease an existing key in all replicas, succeed only if all replicas succeed.
   */
  def decr(key: String, delta: Long): Future[Option[JLong]] =
    resolve[Option[JLong]]("decr", _.decr(key, delta), None)

  /**
   * Private helper to resolve a replication operation result from BaseReplicationClient to
   * a single value type, with using given default value in case of data inconsistency.
   */
  private[this] def resolve[T](name: String, op: BaseReplicationClient => Future[ReplicationStatus[T]], default: T): Future[T] =
    op(underlyingClient) flatMap {
      case ConsistentReplication(r) => Future.value(r)
      case InconsistentReplication(resultsSeq) if resultsSeq.forall(_.isReturn) => Future.value(default)
      case _ => Future.exception(SimpleReplicationFailure("One or more underlying replica failed op: " + name))
    }

  def append(key: String, flags: Int, expiry: Time, value: Buf): Future[JBoolean] =
    throw new UnsupportedOperationException("append is not supported for replication cache client yet.")

  def prepend(key: String, flags: Int, expiry: Time, value: Buf): Future[JBoolean] =
    throw new UnsupportedOperationException("prepend is not supported for replication cache client yet.")

  def stats(args: Option[String]): Future[Seq[String]] =
    throw new UnsupportedOperationException("No logical way to perform stats without a key")

  def release() {
    underlyingClient.release()
  }
}


text:
import { forwardRef } from "react";

import { FontIcon, FontIconProps } from "@react-md/icon";

export const AccessAlarmFontIcon = forwardRef<HTMLElement, FontIconProps>(
  function AccessAlarmFontIcon(props, ref) {
    return (
      <FontIcon {...props} ref={ref}>
        access_alarm
      </FontIcon>
    );
  }
);


text:
@interface VGStringRegexCondition : VGStringCondition

@property (nonatomic, strong) NSString *regex;

+ (instancetype)conditionWithRegex:(NSString *)regex description:(NSString *)description;

@end


text:
'use strict'

import createReducer from '../utils/create-reducer'

import {PLAYER} from '../constant'

const initialState = {
  isLoaded: false,
  recent: [],
  data: []
}

const actionHandler = {
  [PLAYER.LIST]: (state, action) => {
    return {
      isLoaded: true,
      data: action.data
    }
  },

  [PLAYER.RECENT]: (state, action) => {
    return {
      recent: action.data
    }
  }
}

export default createReducer(initialState, actionHandler)


text:
class DeactivatableItem < ActiveRecord::Base
  acts_as_deactivatable
end


text:
/**
 *  LibBoostAsio.cpp
 *
 *  Test program to check AMQP functionality based on Boost's asio io_service.
 *
 *  @author Gavin Smith <gavin.smith@coralbay.tv>
 *
 *  Compile with g++ -std=c++14 libboostasio.cpp -o boost_test -lpthread -lboost_system -lamqpcpp
 */

/**
 *  Dependencies
 */
#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/deadline_timer.hpp>

#include <amqpcpp.h>
#include <amqpcpp/libboostasio.h>

/**
 *  Main program
 *  @return int
 */
int main()
{

    // access to the boost asio handler
    // note: we suggest use of 2 threads - normally one is fin (we are simply demonstrating thread safety).
    boost::asio::io_service service(4);

    // handler for libev
    AMQP::LibBoostAsioHandler handler(service);

    // make a connection
    AMQP::TcpConnection connection(&handler, AMQP::Address("amqp://guest:guest@localhost/"));

    // we need a channel too
    AMQP::TcpChannel channel(&connection);

    // create a temporary queue
    channel.declareQueue(AMQP::exclusive).onSuccess([&connection](const std::string &name, uint32_t messagecount, uint32_t consumercount) {

        // report the name of the temporary queue
        std::cout << "declared queue " << name << std::endl;

        // now we can close the connection
        connection.close();
    });

    // run the handler
    // a t the moment, one will need SIGINT to stop.  In time, should add signal handling through boost API.
    return service.run();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using RestSharp;
using SolrScheduler.Interfaces.Log;
using SolrScheduler.Interfaces.Solr;
using SolrScheduler.Interfaces.Utility;
using SolrScheduler.Objects.Utility;

namespace SolrScheduler.Objects.Solr {
    public class SolrOperationRunner : ISolrOperationRunner {

        #region Private Variables

        private readonly IDirectoryInfoWrapper _directoryInfoWrapper;

        /// <summary>
        /// The rest client
        /// </summary>
        private readonly IRestClient _restClient;

        /// <summary>
        /// The solr log
        /// </summary>
        private readonly ISolrLog _log;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the solr operations.
        /// </summary>
        /// <value>The solr operations.</value>
        public IList<ISolrOperation> SolrOperations { get; } = new List<ISolrOperation>();

        /// <summary>
        /// Occurs when [on job action].
        /// </summary>
        public event Action<string> OnJobAction;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="SolrOperationRunner" /> class.
        /// </summary>
        /// <param name="directoryInfoWrapper">The directory information wrapper.</param>
        /// <param name="restClient">The rest client.</param>
        /// <param name="log">The log.</param>
        public SolrOperationRunner(IDirectoryInfoWrapper directoryInfoWrapper = null, IRestClient restClient = null, ISolrLog log = null) {
            _directoryInfoWrapper = directoryInfoWrapper ?? new DirectoryInfoWrapper();
            _restClient = restClient;
            _log = log;

            LoadDeserializedOperationObjects(_restClient, _log);
        }

        #endregion

        /// <summary>
        /// Starts the operationModel.
        /// </summary>
        /// <param name="operationName">The operationModel identifier.</param>
        public void StartOperation(string operationName) {
            ISolrOperation operation = SolrOperations.FirstOrDefault(x => x.OperationModel.Name == operationName);
            operation?.Start();
            OnJobAction?.Invoke(null);
        }

        /// <summary>
        /// Starts all operations.
        /// </summary>
        public void StartAllOperations() {
            foreach (ISolrOperation operation in SolrOperations.Where(x => !x.IsRunning))
                operation.Start();
            OnJobAction?.Invoke(null);
        }

        /// <summary>
        /// Stops the operation.
        /// </summary>
        /// <param name="operationName">Name of the operation.</param>
        public void StopOperation(string operationName) {
            ISolrOperation operation = SolrOperations.FirstOrDefault(x => x.OperationModel.Name == operationName);
            operation?.Stop();
            OnJobAction?.Invoke(null);
        }

        /// <summary>
        /// Stops all operations.
        /// </summary>
        public void StopAllOperations() {
            foreach (ISolrOperation operation in SolrOperations)
                operation.Stop();
            OnJobAction?.Invoke(null);
        }

        /// <summary>
        /// Reloads this instance.
        /// </summary>
        public void ReloadAllOperations() {
            StopAllOperations();
            SolrOperations.Clear();
            LoadDeserializedOperationObjects(_restClient, _log);
            StartAllOperations();
        }

        #region Private Methods

        /// <summary>
        /// Loads the deserialized operationModel objects from the flat files.
        /// </summary>
        private void LoadDeserializedOperationObjects(IRestClient restClient = null, ISolrLog log = null) {
            IEnumerable<string> jobFiles = _directoryInfoWrapper.GetFileContentsFromDirectory();

            foreach (string jobFileText in jobFiles) {
                ISolrOperationModel operationModel = JsonConvert.DeserializeObject<SolrOperationModel>(jobFileText);
                IRestClient operationRestClient = restClient ?? GetSolrRestClient(operationModel);

                SolrOperations.Add(new SolrOperation(operationModel, operationRestClient, log));
            }
        }

        /// <summary>
        /// Gets the solr rest client.
        /// </summary>
        /// <param name="solrOperationModel">The solr operationModel.</param>
        /// <returns>RestSharp.IRestClient.</returns>
        private IRestClient GetSolrRestClient(ISolrOperationModel solrOperationModel) {
            return new RestClient($"http://{solrOperationModel.Server}/{solrOperationModel.Core}/");
        }

        #endregion
    }
}


text:
void EnsureExtensionsClientInitialized() {
  static bool initialized = false;

  static base::NoDestructor<extensions::ChromeExtensionsClient>
      extensions_client;

  if (!initialized) {
    initialized = true;
    extensions_client->AddAPIProvider(
        std::make_unique<chrome_apps::ChromeAppsAPIProvider>());
    extensions::ExtensionsClient::Set(extensions_client.get());
  }

  // ExtensionsClient::Set() will early-out if the client was already set, so
  // this allows us to check that this was the only site setting it.
  DCHECK_EQ(extensions_client.get(), extensions::ExtensionsClient::Get())
      << "ExtensionsClient should only be initialized through "
      << "EnsureExtensionsClientInitialized() when using "
      << "ChromeExtensionsClient.";
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>2002</year><year>2013</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>cprof - The Call Count Profiler</title>
    <prepared>Raimo Niskanen</prepared>
    <responsible>nobody</responsible>
    <docno></docno>
    <approved>nobody</approved>
    <checked>no</checked>
    <date>2002-09-11</date>
    <rev>PA1</rev>
    <file>cprof_chapter.xml</file>

<c>cprof</c> is a profiling tool that can be used to get a picture of
    how often different functions in the system are called.

<c>cprof</c> uses breakpoints similar to local call trace,
    but containing counters, to collect profiling
    data. Therfore there is no need for special compilation of any
    module to be profiled.

<c>cprof</c> presents all profiled modules in decreasing total
    call count order, and for each module presents all profiled
    functions also in decreasing call count order. A call count limit
    can be specified to filter out all functions below the limit.

Profiling is done in the following steps:

  <taglist>
    <tag><c>cprof:start/0..3</c></tag>
    <item>Starts profiling with zeroed call counters for specified
     functions by setting call count breakpoints on them. </item>
    <tag><c>Mod:Fun()</c></tag>
    <item>Runs the code to be profiled.</item>
    <tag><c>cprof:pause/0..3</c></tag>
    <item>Pauses the call counters for specified functions. This minimises
     the impact of code running in the background or in the shell
     that disturbs the profiling. Call counters are automatically
     paused when they  "hit the ceiling" of the host machine word
     size. For a 32 bit host the maximum counter value is
     2147483647.</item>
    <tag><c>cprof:analyse/0..2</c></tag>
    <item>Collects call counters and computes the result.</item>
    <tag><c>cprof:restart/0..3</c></tag>
    <item>Restarts the call counters from zero for specified
     functions. Can be used to collect a new set of counters without
     having to stop and start call count profiling.</item>
    <tag><c>cprof:stop/0..3</c></tag>
    <item>Stops profiling by removing call count breakpoints from
     specified functions.</item>
  </taglist>

Functions can be specified as either all in the system, all in one
    module, all arities of one function, one function, or all
    functions in all modules not yet loaded. As for now, BIFs cannot
    be call count traced.

The analysis result can either be for all modules, or for one
    module. In either case a call count limit can be given to filter
    out the functions with a call count below the limit. The all
    modules analysis does not contain the module <c>cprof</c>
    itself, it can only be analysed by specifying it as a single
    module to analyse.

Call count tracing is very lightweight compared to other forms of
    tracing since no trace message has to be generated. Some
    measurements indicates performance degradations in the vicinity of
    10 percent.

The following sections show some examples of profiling with
    <c>cprof</c>. See also
    <seealso marker="cprof">cprof(3)</seealso>.

    <title>Example: Background work</title>

From the Erlang shell:

1> <input>cprof:start(), cprof:pause(). % Stop counters just after start</input>
3476
2> <input>cprof:analyse().</input>
{30,
 [{erl_eval,11,
            [{{erl_eval,expr,3},3},
             {{erl_eval,'-merge_bindings/2-fun-0-',2},2},
             {{erl_eval,expand_module_name,2},1},
             {{erl_eval,merge_bindings,2},1},
             {{erl_eval,binding,2},1},
             {{erl_eval,expr_list,5},1},
             {{erl_eval,expr_list,3},1},
             {{erl_eval,exprs,4},1}]},
  {orddict,8,
           [{{orddict,find,2},6},
            {{orddict,dict_to_list,1},1},
            {{orddict,to_list,1},1}]},
  {packages,7,[{{packages,is_segmented_1,1},6},
               {{packages,is_segmented,1},1}]},
  {lists,4,[{{lists,foldl,3},3},{{lists,reverse,1},1}]}]}
3> <input>cprof:analyse(cprof).</input>
{cprof,3,[{{cprof,tr,2},2},{{cprof,pause,0},1}]}
4> <input>cprof:stop().</input>
3476

The example showed the background work that the shell performs
      just to interpret the first command line. Most work is done by
      <c>erl_eval</c> and <c>orddict</c>.

What is captured in this example is the part of the work the
      shell does while interpreting the command line that occurs
      between the actual calls to <c>cprof:start()</c> and
      <c>cprof:analyse()</c>.

    <title>Example: One module</title>

From the Erlang shell:

1> <input>cprof:start(),R=calendar:day_of_the_week(1896,4,27),cprof:pause(),R.</input>
1
2> <input>cprof:analyse(calendar).</input>
{calendar,9,
          [{{calendar,df,2},1},
           {{calendar,dm,1},1},
           {{calendar,dy,1},1},
           {{calendar,last_day_of_the_month1,2},1},
           {{calendar,last_day_of_the_month,2},1},
           {{calendar,is_leap_year1,1},1},
           {{calendar,is_leap_year,1},1},
           {{calendar,day_of_the_week,3},1},
           {{calendar,date_to_gregorian_days,3},1}]}
3> <input>cprof:stop().</input>
3271

The example tells us that "Aktiebolaget LM Ericsson & Co"
      was registered on a Monday (since the return value
      of the first command is 1), and that the <c>calendar</c> module
      needed 9 function calls to calculate that.

Using <c>cprof:analyse()</c> in this example also shows
      approximately the same background work as in the first example.

    <title>Example: In the code</title>

Write a module:

-module(sort).

-export([do/1]).

do(N) ->
    cprof:stop(),
    cprof:start(),
    do(N, []).

do(0, L) ->
    R = lists:sort(L),
    cprof:pause(),
    R;
do(N, L) ->
    do(N-1, [random:uniform(256)-1 | L]).

From the Erlang shell:

1> <input>c(sort).</input>
{ok,sort}
2> <input>l(random).</input>
{module,random}
3> <input>sort:do(1000).</input>
[0,0,1,1,1,1,1,1,2,2,2,3,3,3,3,3,4,4,4,5,5,5,5,6,6,6,6,6,6|...]
4> <input>cprof:analyse().</input>
{9050,
 [{lists_sort,6047,
              [{{lists_sort,merge3_2,6},923},
               {{lists_sort,merge3_1,6},879},
               {{lists_sort,split_2,5},661},
               {{lists_sort,rmerge3_1,6},580},
               {{lists_sort,rmerge3_2,6},543},
               {{lists_sort,merge3_12_3,6},531},
               {{lists_sort,merge3_21_3,6},383},
               {{lists_sort,split_2_1,6},338},
               {{lists_sort,rmerge3_21_3,6},299},
               {{lists_sort,rmerge3_12_3,6},205},
               {{lists_sort,rmerge2_2,4},180},
               {{lists_sort,rmerge2_1,4},171},
               {{lists_sort,merge2_1,4},127},
               {{lists_sort,merge2_2,4},121},
               {{lists_sort,mergel,2},79},
               {{lists_sort,rmergel,2},27}]},
  {random,2001,
          [{{random,uniform,1},1000},
           {{random,uniform,0},1000},
           {{random,seed0,0},1}]},
  {sort,1001,[{{sort,do,2},1001}]},
  {lists,1,[{{lists,sort,1},1}]}]}
5> <input>cprof:stop().</input>
5369

The example shows some details of how <c>lists:sort/1</c>
      works. It used 6047 function calls in the module
      <c>lists_sort</c> to complete the work.

This time, since the shell was not involved, no other work was
      done in the system during the profiling. If you retry the same
      example with a freshly started Erlang emulator, but omit the
      command <c>l(random)</c>, the analysis will show a lot more
      function calls done by <c>code_server</c> and others to
      automatically load the module <c>random</c>.

</chapter>


text:
package main

import (
	"errors"
	"fmt"
	"log"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	"os/user"
	"path"
)

func initK8s(configPath string) (*kubernetes.Clientset, error) {
	var k8s *kubernetes.Clientset

	// if no kubeconfig is specified, try loading from the user's home dir
	if configPath == "" {
		usr, _ := user.Current()
		dir := usr.HomeDir
		configPath = path.Join(dir, ".kube", "config")
	}

	// try loading the kubeconfig first, then fall back to the in-cluster config
	config, err := clientcmd.BuildConfigFromFlags("", configPath)
	if err != nil {
		var inClusterErr error
		config, inClusterErr = rest.InClusterConfig()
		// uses the current context in kubeconfig
		if err != nil {
			return nil, errors.New(fmt.Sprint("could not get kubernetes config: [", err, ", ", inClusterErr, "]"))
		}
		log.Println("loaded k8s in-cluster config")
	} else {
		log.Println("loaded k8s config from: ", configPath)
	}

	// creates the clientset
	k8s, err = kubernetes.NewForConfig(config)
	return k8s, err
}


text:
//
// IMessageSummary.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

using System;
using System.Collections.Generic;

using MimeKit;

namespace MailKit {
	/// <summary>
	/// A summary of a message.
	/// </summary>
	/// <remarks>
	/// A <see cref="IMessageSummary"/> is returned by
	/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>, MessageSummaryItems, System.Threading.CancellationToken)"/>.
	/// The properties of the <see cref="IMessageSummary"/> that will be available
	/// depend on the <see cref="MessageSummaryItems"/> passed to the aformentioned method.
	/// </remarks>
	public interface IMessageSummary
	{
		/// <summary>
		/// Get a bitmask of fields that have been populated.
		/// </summary>
		/// <remarks>
		/// Gets a bitmask of fields that have been populated.
		/// </remarks>
		/// <value>The fields that have been populated.</value>
		MessageSummaryItems Fields { get; }

		/// <summary>
		/// Gets the body structure of the message, if available.
		/// </summary>
		/// <remarks>
		/// <para>The body will be one of <see cref="BodyPartText"/>,
		/// <see cref="BodyPartMessage"/>, <see cref="BodyPartBasic"/>,
		/// or <see cref="BodyPartMultipart"/>.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.Body"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The body structure of the message.</value>
		BodyPart Body { get; }

		/// <summary>
		/// Gets the text body part of the message if it exists.
		/// </summary>
		/// <remarks>
		/// <para>Gets the text/plain body part of the message.</para>
		/// <para>In order for this to work properly, it is necessary to include
		/// <see cref="MessageSummaryItems.BodyStructure"/> when fetching
		/// summary information from a <see cref="IMailFolder"/>.</para>
		/// </remarks>
		/// <value>The text body if it exists; otherwise, <c>null</c>.</value>
		BodyPartText TextBody { get; }

		/// <summary>
		/// Gets the html body part of the message if it exists.
		/// </summary>
		/// <remarks>
		/// <para>Gets the text/html body part of the message.</para>
		/// <para>In order for this to work properly, it is necessary to include
		/// <see cref="MessageSummaryItems.BodyStructure"/> when fetching
		/// summary information from a <see cref="IMailFolder"/>.</para>
		/// </remarks>
		/// <value>The html body if it exists; otherwise, <c>null</c>.</value>
		BodyPartText HtmlBody { get; }

		/// <summary>
		/// Gets the body parts of the message.
		/// </summary>
		/// <remarks>
		/// <para>Traverses over the <see cref="Body"/>, enumerating all of the
		/// <see cref="BodyPartBasic"/> objects.</para>
		/// <para>In order for this to work, it is necessary to include
		/// <see cref="MessageSummaryItems.BodyStructure"/> or
		/// <see cref="MessageSummaryItems.Body"/> when fetching
		/// summary information from a <see cref="IMailFolder"/>.</para>
		/// </remarks>
		/// <value>The body parts.</value>
		IEnumerable<BodyPartBasic> BodyParts { get; }

		/// <summary>
		/// Gets the attachments.
		/// </summary>
		/// <remarks>
		/// <para>Traverses over the <see cref="Body"/>, enumerating all of the
		/// <see cref="BodyPartBasic"/> objects that have a Content-Disposition
		/// header set to <c>"attachment"</c>.</para>
		/// <para>In order for this to work properly, it is necessary to include
		/// <see cref="MessageSummaryItems.BodyStructure"/> when fetching
		/// summary information from a <see cref="IMailFolder"/>.</para>
		/// </remarks>
		/// <value>The attachments.</value>
		IEnumerable<BodyPartBasic> Attachments { get; }

		/// <summary>
		/// Gets the envelope of the message, if available.
		/// </summary>
		/// <remarks>
		/// <para>The envelope of a message contains information such as the
		/// date the message was sent, the subject of the message,
		/// the sender of the message, who the message was sent to,
		/// which message(s) the message may be in reply to,
		/// and the message id.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.Envelope"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The envelope of the message.</value>
		Envelope Envelope { get; }

		/// <summary>
		/// Gets the normalized subject.
		/// </summary>
		/// <remarks>
		/// <para>A normalized Subject header value where prefixes such as "Re:", "Re[#]:", etc have been pruned.</para>
		/// <para>This property is typically used for threading messages by subject.</para>
		/// </remarks>
		/// <value>The normalized subject.</value>
		string NormalizedSubject { get; }

		/// <summary>
		/// Gets the Date header value.
		/// </summary>
		/// <remarks>
		/// Gets the Date header value. If the Date header is not present, the arrival date is used.
		/// If neither are known, <see cref="System.DateTimeOffset.MinValue"/> is returned.
		/// </remarks>
		/// <value>The date.</value>
		DateTimeOffset Date { get; }

		/// <summary>
		/// Gets whether or not the message is a reply.
		/// </summary>
		/// <remarks>
		/// This value should be based on whether the message subject contained any "Re:" or "Fwd:" prefixes.
		/// </remarks>
		/// <value><c>true</c> if the message is a reply; otherwise, <c>false</c>.</value>
		bool IsReply { get; }

		/// <summary>
		/// Gets the message flags, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the message flags, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.Flags"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The message flags.</value>
		MessageFlags? Flags { get; }

		/// <summary>
		/// Gets the user-defined message flags, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the user-defined message flags, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.Flags"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The user-defined message flags.</value>
		HashSet<string> UserFlags { get; }

		/// <summary>
		/// Gets the list of headers, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the list of headers, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Collections.Generic.HashSet<MimeKit.HeaderId>,System.Threading.CancellationToken)"/>.
		/// method is used.</para>
		/// </remarks>
		/// <value>The list of headers.</value>
		HeaderList Headers { get; }

		/// <summary>
		/// Gets the internal date of the message (i.e. the "received" date), if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the internal date of the message (i.e. the "received" date), if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.InternalDate"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The internal date of the message.</value>
		DateTimeOffset? InternalDate { get; }

		/// <summary>
		/// Gets the size of the message, in bytes, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the size of the message, in bytes, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.MessageSize"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The size of the message.</value>
		uint? Size { get; }

		/// <summary>
		/// Gets the mod-sequence value for the message, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the mod-sequence value for the message, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.ModSeq"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The mod-sequence value.</value>
		ulong? ModSeq { get; }

		/// <summary>
		/// Gets the message-ids that the message references, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the message-ids that the message references, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.References"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The references.</value>
		MessageIdList References { get; }

		/// <summary>
		/// Gets the unique identifier of the message, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the unique identifier of the message, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.UniqueId"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The uid of the message.</value>
		UniqueId UniqueId { get; }

		/// <summary>
		/// Gets the index of the message.
		/// </summary>
		/// <remarks>
		/// Gets the index of the message.
		/// </remarks>
		/// <value>The index of the message.</value>
		int Index { get; }

		#region GMail extension properties

		/// <summary>
		/// Gets the GMail message identifier, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the GMail message identifier, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.GMailMessageId"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The GMail message identifier.</value>
		ulong? GMailMessageId { get; }

		/// <summary>
		/// Gets the GMail thread identifier, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the GMail thread identifier, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.GMailThreadId"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The GMail thread identifier.</value>
		ulong? GMailThreadId { get; }

		/// <summary>
		/// Gets the list of GMail labels, if available.
		/// </summary>
		/// <remarks>
		/// <para>Gets the list of GMail labels, if available.</para>
		/// <para>This property will only be set if the
		/// <see cref="MessageSummaryItems.GMailLabels"/> flag is passed to
		/// <see cref="IMailFolder.Fetch(System.Collections.Generic.IList<UniqueId>,MessageSummaryItems,System.Threading.CancellationToken)"/>.</para>
		/// </remarks>
		/// <value>The GMail labels.</value>
		IList<string> GMailLabels { get; }

		#endregion
	}
}


text:
package net.mgsx.game.examples.convoy.ui;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;

import net.mgsx.game.examples.convoy.components.Planet;

public class PlanetUI extends Table
{

	private Entity planetEntity;
	private TextButton btAddGaz;

	public PlanetUI(Skin skin) {
		super(skin);
	}

	public void setPlanet(Entity planetEntity)
	{
		this.planetEntity = planetEntity;

		clear();

		// buy gaz station ...
		if(planetEntity != null){

			final Planet planet = Planet.components.get(planetEntity);

			// add bt add gaz
			TextButton bt = btAddGaz = new TextButton("add gaz", getSkin());
			add(bt).row();
			bt.addListener(new ChangeListener() {
				@Override
				public void changed(ChangeEvent event, Actor actor) {
					planet.gazAvailability++;
				}
			});

		}

	}

	@Override
	public void act(float delta) {

		// TODO generic UI : buttons enabled under condition (interface Condition)

		// update all dynamic fields and gui control
		if(planetEntity != null){
			final Planet planet = Planet.components.get(planetEntity);
			boolean canGaz = planet.gazAvailability < 3;
			btAddGaz.setDisabled(!canGaz);
			btAddGaz.getColor().a = canGaz ? 1 : .5f;
		}
		super.act(delta);
	}

}