text:
<!DOCTYPE html>

Hello, world!
Hello, world!

Hello, world!
Hello, world!

Hello, world!
Hello, world!

Hello, world!
Hello, world!

redpajama_set_name: RedPajamaGithub


text:
define(["ko", "jquery", "apiMappings"], function(ko, $, ApiMappings){
    function AuthenticationService(){
        var self = this;

        self._ = {
            initialized: false,
            started: false,
            disposed: false,
            timer: null,
            apiMappings : ApiMappings,

            checkIfInitialized: function(){
                if(!self._.initialized){
                    throw new Error("Must initialize Authentication Service before using it.");
                }
            },

            checkIfStarted: function(){
                if(!self._.started){
                    throw new Error("Must start Authentication Service before using it.");
                }
            },

            checkIfDisposed: function(){
                if(self._disposed){
                    throw new Error("Authentication Service has already been disposed.");
                }
            }
        };

        self.token = ko.observable(null);
        self.admin = ko.observable(false);

        self.init = function(){
            self._.checkIfDisposed();

            if(!self._.initialized){

                self.loadLocalStorage();

                self._.initialized = true;
            }
        };

        self.start = function(){
            self._.checkIfInitialized();
            self._.checkIfDisposed();

            self._.timer = setInterval(self.validateToken, 60000);

            if(!self._.started){
                self._.started = true;
            }
        };

        self.stop = function(){
            self._.checkIfDisposed();
            self._.checkIfStarted();
            if(self._.started){
                self.started = false

                    clearInterval(self._.timer);
            }
        };

        self.dispose = function(){
            if(!self._.disposed){
                self.stop()

                self._.disposed = true;
            }
        };

        self.loadLocalStorage = function(){
            if(localStorage.hasOwnProperty("access_token")){
                if(localStorage.hasOwnProperty("expiration_date")){
                    if((new Date(localStorage["expiration_date"])).valueOf() > (new Date()).getTime()){
                        self.token(localStorage["access_token"]); self.admin(Boolean(localStorage["admin"]));
                    }
                    else{
                        localStorage.clear();
                    }
                }
            }
        }

        self.validateToken = function(){
            if(self.token() !== null && self.token() !== "" && self.token() !== undefined){
                $.ajax({
                    url: self._.apiMappings.baseUrl + "/authenticate/verify",
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify({"token": self.token()}),
                    success: function(response){
                        if(!Boolean(response.result)){
                            self.logout();
                        }
                        else{
                            /* Verify the user is an admin */
                            if(self.admin()){
                                $.ajax({
                                    url: self._.apiMappings.baseUrl + "/authenticate/verify/admin",
                                    type: "POST",
                                    dataType: "json",
                                    contentType: "application/json",
                                    data: JSON.stringify({"token": self.token()}),
                                    success: function(response){
                                        self.admin(Boolean(response.result))
                                    }
                                });
                            }
                        }
                    }
                });

            }
        };

        self.login = function(username, password, successCallback, errorCallback){
            $.ajax({
                url: self._.apiMappings.baseUrl + "/authenticate",
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    "username": username,
                    "password": password
                }),
                success: function(result){
                    if("Error" in result){
                        errorCallback(result.Error);
                    }
                    else{
                        localStorage["access_token"] = result.access_token;
                        self.token(result.access_token);
                        localStorage["expiration_date"] = result.expiration_date;
                        localStorage["admin"] = result.admin;
                        localStorage["user_key"] = result.user_key;
                        self.admin(Boolean(result.admin));
                    }
                    successCallback();
                }
            });
        }

        self.logout = function(){
            localStorage.clear();
            self.token(null);
            self.admin(false);
        }
    }

    return {
        get: function(){
            return new AuthenticationService();
        },
        type: function(){
            return AuthenticationService;
        }
    };
});


text:
<?php

namespace Nours\RestAdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Class DeleteType
 *
 * @author David Coudrier <david.coudrier@gmail.com>
 */
class BulkDeleteType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('submit', SubmitType::class);
    }

    public function getBlockPrefix()
    {
        return 'bulk_delete';
    }
}


text:
# Copyright 2011 - Present RealDimensions Software, LLC & original authors/contributors from https://github.com/chocolatey/chocolatey
#
# 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.

function Get-OSArchitectureWidth {
<#
.SYNOPSIS
Get the operating system architecture address width.

.DESCRIPTION
This will return the system architecture address width (probably 32 or
64 bit). If you pass a comparison, it will return true or false instead
of {`32`|`64`}.

.NOTES
When your installation script has to know what architecture it is run
on, this simple function comes in handy.

Available as `Get-OSArchitectureWidth` in 0.9.10+. If you need
compatibility with pre 0.9.10, please use the alias `Get-ProcessorBits`.

.INPUTS
None

.OUTPUTS
None

.PARAMETER Compare
This optional parameter causes the function to return $true or $false,
depending on wether or not the bit width matches.
#>
param(
  $compare
)
  Write-Debug "Running 'Get-OSArchitectureWidth'"

  $bits = 64
  if (([System.IntPtr]::Size -eq 4) -and (Test-Path env:\PROCESSOR_ARCHITEW6432)) {
    $bits = 64
  } elseif ([System.IntPtr]::Size -eq 4) {
    $bits = 32
  }

  # Return bool|int
  if ("$compare" -ne '' -and $compare -eq $bits) {
    return $true
  } elseif ("$compare" -ne '') {
    return $false
  } else {
    return $bits
  }
}

Set-Alias Get-ProcessorBits Get-OSArchitectureWidth
Set-Alias Get-OSBitness Get-OSArchitectureWidth


text:
* Criar contratos que descrevem os dados em produção
* Contratos matem a descrição dos dados atualizados
* Contratos facilitam a criação de modelos
* Contrato devem ser testados e automatizados
* Bancos temporais ajudam a recuperar estado em um timeset
* Spark
* Kafka

## [Microservices e workflows distribuídos: tornando dados acessíveis na 99](http://qconsp.com/system/files/presentation-slides/qconsp_-_airflow_-_gustavo_amigo.pdf)

* Utilizar o airflow para agregar informacoes e fluxos
* Airflow executa tasks para agregar informações
* Estas informacoes ficam disponiveis os demais setores da empresa (Contabilidade)
* Integração dessas informacoes com slack bot - facil interface com o consumidor das informações
* [Metabase](http://www.metabase.com/) para facilitar a buscar de dados

## [Evolução cultural de desenvolvedores a equipes: criando times de alto desempenho no Elo7](http://qconsp.com/system/files/presentation-slides/david.robert.qcon_2017_-_evolucao_cultural_-_desenvolvendo_times_de_alta_performance.pdf)

* Times especialistas - precisa de mais colaboração entre equipes
* Ambiente colaborativo.. não tem entrega individual.. todos envolvidos na feature tem responsabilidades..
* Integração do negócio com o dev.. (mostrar quando a empresa vendeu por semana)
* O dev também é responsável pelo produto - produção diária.. caiu? Porque? Mostrar a produção mensal para motivar
* pareamento de monitores
* autonomia .. confiança nas pessoas

## [Autorização de transações no Nubank: Consumindo serviços anos 80 com tecnologias atuais](http://qconsp.com/system/files/presentation-slides/lucas_e_luiz.qcon-authorizer-nubank.pdf)

* [Datomic](http://www.datomic.com/)
* [Finagle](https://github.com/twitter/finagle)
* Atom banco de dados em memoria

## [Autorização de transações no Nubank: Consumindo serviços anos 80 com tecnologias atuais](http://qconsp.com/system/files/presentation-slides/diego.paris_.o_lider_agil.pptx.pptx)

* todos são responsáveis.. o que vc fez para mudar a equipe?
* atacar a raiz do problema
* círculo de segurança - piramede de Maslow
* não ter medo de gerar feature - bugs
* pensar no coletivo
* valorização confiança cooperação
* líder por exemplo
* saber oq motiva o time e as pessoas?
* moving motivators cards
* coaching - nao dar a resposta do problema.. fazer perguntas pra fazer entender o problema
* mentoring - acompanhar a carreira
* cooperação - visão do futuro.. envolver as pessoas nas missões dá empresa
* confiança - feedback

## [Actors Unleashed: Reactive Systems, DDD, and the Ubiquitous Language](http://qconsp.com/system/files/presentation-slides/usingactormodeldddreactive_vaughnvernon.pdf)

* não fazer otimizações prematuras
* pensar em threads como mensagens. Message drive
* erlarg , elixir
* actor modelos
* reactive é resiliente
* iot - embrace latency
* fazer mais com menos - procurar linguagens não tradicionais.. para ter mais performance.. fazer de modo diferente
* Lock Free.. não compartilhe estado
* transações adicionam complexidade
* actor models facilitam transações.. eventos são atomicos
* DDD linguagens ubliquoas
* Akka
* saber trabalhar com a incerteza

## The Realist's Guide to Language Design

* Não tem linguagem perfeita
* Deve evitar cometer erros
* Dem ambiguidade.. mesma entrada mesmo valor sempre
* Sintaxe intuitiva.. não pensar muito como faz um IF..
* Footprint razoável
* Abstração demais é ruim.. array..Lista vector..map.. collection
* Eficiência
* [lazy Evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation)
- Tooling
- Boa comunidade
- [Idris Lang] (https://www.idris-lang.org/)

## [Criptografia aplicada: de algoritmos a bibliotecas](http://qconsp.com/system/files/presentation-slides/bruno.applied-cryptography-qconsp2017.pdf)

* Autenticidade
* Confiabilidade
* Integridade
* Hash não garante integridade.. jah tem colisão
* ECB é ruim para criptografia
* GCM
* RSA
* Key agrement

## [Microservices reativos e a experiência do iFood](http://qconsp.com/system/files/presentation-slides/tiago.dolphine.qcon_sp_2017_-_reactive_microservices.pdf)

* manifesto reativo
* não blocar as operações.. o DB avisa quando acabou a operação e ediciona informações as mensagens
* stream reativo
* reactor java
* Spring

## [Resiliência com microservices: cache distribuído, feedback e tuning na Globo.com](http://qconsp.com/system/files/presentation-slides/resiliencia_em_microservices.pdf)

* [cachet status pages](https://github.com/CachetHQ/Cachet)
* Backstage apis com tenants
* Buffer em memória fazendo flush de tempos em tempos - votação BBB
* Load balance

## [Failing Gracefully with the Actor Model](http://qconsp.com/system/files/presentation-slides/roger.failingactors.pptx)

* Não devolver o error direto para o usuário.. remanejar o erro pra quem pode corrigi-lo - erros supervisionados
* Circuit break
* fanout and quickest replay
* active passive consume
* modular redundancy
* throttling to lead with load
* bounded mailboxes
* work pulling - blackpressure
* orbit framework - virtual actor

## From laptop to the world: multi-region container deployment with Kubernetes

* Definir o ambiente de produção desde o começo do projeto.. pensar em como será pelo menos
* Env de desenvolvimento deve ser mais próximo possível de prod.. para evitar configurações diferentes
* Containers
* /static
* delete pod do k8s cria outro pod até q fique igual ao número do scale
* Type loadbalancer
* Dederativo service.. vários clusters de kubernetes
* [Saturnism](https://github.com/saturnism)

## [Processamento de Linguagem Natural com Deep Learning](http://qconsp.com/system/files/presentation-slides/juliano.viana_.kunumi_processamento-linguagem-natural-deep-learning-v3.pdf)

* word2vec
* vdb
* recurrent network
* long short term memory
* detectar se a frase eh autêntica
* música neural sabotagem
* sequence prediction
* seq2seq
* chatbot .. converter perguntas em consultas SQL
* cutting Edge models

## [Billions and Billions](http://qconsp.com/system/files/presentation-slides/jim.qcon_fighting_fraud_with_graphs.pptx)

## [How Apache Beam will change Big Data](http://qconsp.com/system/files/presentation-slides/jesse.beam_intro.pdf)

* Tenta encapsular várias tecnologias.. Kafka.. hadoop
* Uma unica API
* Unifica diferentes API - Kafka se comunica com spark stream

## [IoT e Smart Energy: monitoramento de instalações elétricas através do auto-registro de dispositivos](http://qconsp.com/system/files/presentation-slides/caio.cesar_.uiot-smart-energy.pdf)

- Rede de dispositivos para ajudar a tomada de decisão
- Auto registro do dispositivo
- Tratar comportamento do dispositivo - validar o comportamento
- Couch DB
- Manutenção preventiva consumo de energia


text:
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using OpenTK;

namespace osu.Game.Rulesets.Objects.Types
{
    /// <summary>
    /// A HitObject that has a starting position.
    /// </summary>
    public interface IHasPosition : IHasXPosition, IHasYPosition
    {
        /// <summary>
        /// The starting position of the HitObject.
        /// </summary>
        Vector2 Position { get; }
    }
}


text:
package de.zib.gndms.infra.system;

import org.jetbrains.annotations.NotNull;

/**
 * A simple box that holds a GNDMSystem instance
 *
 * @author  try ste fan pla nti kow zib
 * @version $Id$
 *
 *          User: stepn Date: 25.07.2008 Time: 13:01:27
 */
@SuppressWarnings({"ClassReferencesSubclass"})
public interface SystemHolder {
	@NotNull
	GNDMSystem getSystem() throws IllegalStateException;

	void setSystem(@NotNull GNDMSystem system) throws IllegalStateException;
}


text:
package org.drools.repository.events;

import org.drools.repository.AssetItem;

/**
 * To be called after an asset is checked in.
 */
public interface CheckinEvent {
    public void afterCheckin(AssetItem item);
}


text:
package com.github.jlmd.animatedcircleloadingview.component;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import com.github.jlmd.animatedcircleloadingview.animator.AnimationState;

/**
 * @author jlmd
 */
public class RightCircleView extends ComponentViewAnimation {

  private int rightMargin;
  private int bottomMargin;
  private Paint paint;

  public RightCircleView(Context context, int parentWidth, int mainColor, int secondaryColor) {
    super(context, parentWidth, mainColor, secondaryColor);
    init();
  }

  private void init() {
    rightMargin = (150 * parentWidth / 700);
    bottomMargin = (50 * parentWidth / 700);
    initPaint();
  }

  private void initPaint() {
    paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(secondaryColor);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawCircle(canvas);
  }

  public void drawCircle(Canvas canvas) {
    canvas.drawCircle(getWidth() - rightMargin, parentCenter - bottomMargin, circleRadius, paint);
  }

  public void startSecondaryCircleAnimation() {
    int bottomMovementAddition = (260 * parentWidth) / 700;
    TranslateAnimation translateAnimation =
        new TranslateAnimation(getX(), getX(), getY(), getY() + bottomMovementAddition);
    translateAnimation.setStartOffset(200);
    translateAnimation.setDuration(1000);

    AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
    alphaAnimation.setStartOffset(1300);
    alphaAnimation.setDuration(200);

    AnimationSet animationSet = new AnimationSet(true);
    animationSet.addAnimation(translateAnimation);
    animationSet.addAnimation(alphaAnimation);
    animationSet.setFillAfter(true);
    animationSet.setAnimationListener(new Animation.AnimationListener() {
      @Override
      public void onAnimationStart(Animation animation) {
        // Empty
      }

      @Override
      public void onAnimationEnd(Animation animation) {
        setState(AnimationState.SECONDARY_CIRCLE_FINISHED);
      }

      @Override
      public void onAnimationRepeat(Animation animation) {
        // Empty
      }
    });

    startAnimation(animationSet);
  }
}


text:
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace Microsoft.VisualBasic.Logging
{
  public class Log
  {
    public Log(string name)
    {
      Contract.Requires(name != null);
    }

    //public void WriteEntry(string message);
    //public void WriteEntry(string message, TraceEventType severity);
    //public void WriteEntry(string message, TraceEventType severity, int id);
    //public void WriteException(Exception ex);
    //public void WriteException(Exception ex, TraceEventType severity, string additionalInfo);
    //public void WriteException(Exception ex, TraceEventType severity, string additionalInfo, int id);

    // Properties
    public FileLogTraceListener DefaultFileLogWriter
    {
      get
      {
        Contract.Ensures(Contract.Result<FileLogTraceListener>() != null);
        return default(FileLogTraceListener);
      }
    }

    public TraceSource TraceSource
    {
      get
      {
        Contract.Ensures(Contract.Result<TraceSource>() != null);
        return default(TraceSource);
      }
    }

  }
}
#endif


text:
PerfMonitor::PerfMonitor(unsigned int indicationId, unsigned int requestId) :
        PerfMonitorIndicationWrapper(indicationId) {
    performanceRequest = new PerfMonitorRequestProxy(requestId);
    sem_init(&respSem, 0, 0);
}

void PerfMonitor::printPerformance(std::string filename) {
    std::ifstream file(filename);
    std::string line;
    std::string name;
    uint32_t index;

    while (std::getline(file, line)) {
        size_t commaIndex = line.find(',');
        if (commaIndex != std::string::npos) {
            if (line.substr(0,2) == "0x") {
                std::istringstream s(line.substr(2, commaIndex));
                s >> std::hex >> index;
            } else {
                std::istringstream s(line.substr(0, commaIndex));
                s >> index;
            }
            name = line.substr(commaIndex+1);
            std::cout << name << " = " << readMonitor(index) << std::endl;
        }
    }
}

void PerfMonitor::setEnable(const int x) {
    performanceRequest->setEnable(x);
}

uint64_t PerfMonitor::readMonitor(const uint32_t index) {
    performanceRequest->req((uint64_t) index);
    // set semaphore
    sem_wait(&respSem);
    uint64_t resp = prevResp;
    return resp;
}

void PerfMonitor::resp(const uint64_t x) {
    prevResp = x;
    sem_post(&respSem);
}


text:
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from test import run_only
from mock import Mock
from mock import patch

from diamond.collector import Collector
from files import FilesCollector

###############################################################################

class TestFilesCollector(CollectorTestCase):
    def setUp(self):
        config = get_collector_config('FilesCollector', {
        })
        self.collector = FilesCollector(config, None)

    def test_import(self):
        self.assertTrue(FilesCollector)

###############################################################################
if __name__ == "__main__":
    unittest.main()


text:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="#40000000">
   <item android:drawable="@drawable/drawer_entry_background"></item>
</ripple>


text:
package org.kuali.kra.bo;

import org.kuali.rice.core.api.util.type.KualiDecimal;

import java.sql.Date;

public class OrganizationIndirectcost extends KraPersistableBusinessObjectBase {

    private Integer idcNumber;

    private String organizationId;

    private KualiDecimal applicableIndirectcostRate;

    private Date endDate;

    private String idcComment;

    private Integer idcRateTypeCode;

    private Date requestedDate;

    private Date startDate;

    private Organization organization;

    public OrganizationIndirectcost() {
        super();
    }

    public Integer getIdcNumber() {
        return idcNumber;
    }

    public void setIdcNumber(Integer idcNumber) {
        this.idcNumber = idcNumber;
    }

    public String getOrganizationId() {
        return organizationId;
    }

    public void setOrganizationId(String organizationId) {
        this.organizationId = organizationId;
    }

    public KualiDecimal getApplicableIndirectcostRate() {
        return applicableIndirectcostRate;
    }

    public void setApplicableIndirectcostRate(KualiDecimal applicableIndirectcostRate) {
        this.applicableIndirectcostRate = applicableIndirectcostRate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public String getIdcComment() {
        return idcComment;
    }

    public void setIdcComment(String idcComment) {
        this.idcComment = idcComment;
    }

    public Integer getIdcRateTypeCode() {
        return idcRateTypeCode;
    }

    public void setIdcRateTypeCode(Integer idcRateTypeCode) {
        this.idcRateTypeCode = idcRateTypeCode;
    }

    public Date getRequestedDate() {
        return requestedDate;
    }

    public void setRequestedDate(Date requestedDate) {
        this.requestedDate = requestedDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Organization getOrganization() {
        return organization;
    }

    public void setOrganization(Organization organization) {
        this.organization = organization;
    }
}


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class ClusterDasVmConfigSpec extends ArrayUpdateSpec {
  public ClusterDasVmConfigInfo info;

  public ClusterDasVmConfigInfo getInfo() {
    return this.info;
  }

  public void setInfo(ClusterDasVmConfigInfo info) {
    this.info=info;
  }
}


text:
define(
    ['ufojs/errors', 'ufojs/tools/pens/AbstractPen'],
    function(errors, AbstractPen)
{
    doh.register("ufojs.pens.AbstractPen", [
    function Test_AbstractPen_Errors(){
        var pen = new AbstractPen;
        doh.assertError(
            errors.NotImplemented,
            pen, 'moveTo'
        );
        doh.assertError(
            errors.NotImplemented,
            pen, 'lineTo'
        );
        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo'
        );

        //these methods just do nothing:
        //pen.closePath
        //pen.endPath

        doh.assertError(
            errors.NotImplemented,
            pen, 'addComponent'
        );
    }
    ]);
});


text:
var _ = require("lodash");
var minimist = require("minimist");
var Promise = require("bluebird").Promise;

var argument = require("./argument");
var autocomplete = require("./autocomplete");
var autocompleteScript = require("./autocompleteScript");
var command = require("./command");
var option = require("./option");
var parsers = require("./parsers");
var utils = require("./utils");

var cli = module.exports = {};

cli.cli = function(options, cb) {
  options.topLevel = true;
  options.version = typeof options.version !== 'undefined' ? options.version : null;
  options.helpCommand = typeof options.helpCommand !== 'undefined' ? options.helpCommand : true;
  options.options = [ option.helpOption, option.versionOption ].concat(options.options || []);

  if(options.helpCommand) {
    options.commands = [ command.helpCommand ].concat(options.commands || []);
  }

  return command.command(
    options.name || utils.getProcessName(process.argv),
    options,
    cb
  );
};

cli.displayVersion = function(cli) {
  console.log(cli.version !== null ? cli.version : 'N/A');
};

cli.displayUsage = function(cliApp, givenArgs) {
  var context = _.reduce(givenArgs, function(acc, arg) {
    var isDone = acc[0];
    var cmd = _.last(acc[1]);

    var matchingSubcommand = _.find(cmd.commands, function(cmd) {
      return cmd.name === arg;
    });

    if(!isDone && matchingSubcommand) {
      return [false, acc[1].concat(matchingSubcommand)];
    } else {
      return [true, acc[1]];
    }
  }, [false, [cliApp]])[1];

  console.log(command.help(context).trim());
};

cli.displayErrors = function(errors, cliApp, givenArgs) {
  var argsErrors = _.map(errors.args, function(error) {
    if(error.argument) {
      return error.argument.name + ': ' + error.error;
    } else {
      return error.error;
    }
  });
  var optionsErrors = _.map(errors.options, function(error) {
    if(error.option) {
      return error.option.name + ': ' + error.error;
    } else {
      return error.error;
    }
  });

  if(!_.isEmpty(argsErrors)) console.log(argsErrors.join('\n'));
  if(!_.isEmpty(optionsErrors)) console.log(optionsErrors.join('\n'));

  if(!_.isEmpty(argsErrors) || !_.isEmpty(optionsErrors)) console.log();

  cli.displayUsage(cliApp, givenArgs);
};

cli.execute = function(cliApp, args, options) {
  var result = command.parse(cliApp, [], args, options);

  if(parsers.isError(result)) {
    cli.displayErrors(result.error, cliApp, args);
  } else {
    if(!_.last(result.context).action) {
      cli.displayUsage(cliApp, args);
    } else {
      _.last(result.context).action(result.success);
    }
  }
};

cli.autocomplete = function(cliApp, words, index, flagNames, optionNames) {
  if(typeof words !== 'object') words = [words];
  if(index >= words.length) words.push('');
  var opts = {
     string: optionNames.concat(["_"]),
    boolean: flagNames
  }
  var argv = minimist(words, opts);
  var current = words[index] || '';
  var consumedArgs = autocomplete.currentArg(words, index, argv._).consumedArgs;
  var results;

  if(argv._[1] === 'help' && cliApp.helpCommand) {
    results = Promise.resolve(autocomplete.autocompleteHelpCommand(cliApp, _.drop(consumedArgs, 2)));
  } else {
    results = command.autocomplete(
      cliApp,
      _.drop(consumedArgs, 1),
      argv,
      words,
      index,
      []);
  }

  results.then(function(rs) {
    return autocomplete.compgen(rs, current);
  }).then(console.log);
};

cli.cleanArgv = function(argv) {
  // check the command is launched via the node interpreter (+ ensure windows compat)
  if (argv[0].match(/node/)) {
    return _.drop(argv, 2);
  } else {
    return _.drop(argv, 1);
  }
};

cli.parse = function(cliApp, argv) {
  argv = (typeof argv === "undefined") ? process.argv : argv;

  var flagNames = command.getFlagNames(cliApp);
  var optionNames = command.getOptionNames(cliApp);

  var opts = {
    string: optionNames.concat(["autocomplete-words", "_"]), // All other options should be treated as strings (and not coerced)
    boolean: flagNames // Declare flags as not expecting values
  };

  var cliValues = minimist(argv, opts);
  var optionsWithFlagDefaults = _.omit(cliValues, "_");

  // Minimist adds all the names declared as flags even though they are not
  // present (with value false). These interfere with the parsing later, so we
  // remove them here.
  var options = _.fromPairs(_.filter(_.toPairs(optionsWithFlagDefaults), function(kv) {
    return kv[1] || !_.includes(flagNames, kv[0]);
  }));
  var args = cli.cleanArgv(cliValues._);

  if(option.parse(option.helpOption, options).success === true) {
    cli.displayUsage(cliApp, args);
  } else if(!cliApp.noHelpCommand && args[0] === 'help') {
    cli.displayUsage(cliApp, _.drop(args, 1));
  } else if(option.parse(option.versionOption, options).success === true) {
    cli.displayVersion(cliApp);
  } else if(options["bash-autocomplete-script"]) {
    console.log(autocompleteScript.bashScript(options["bash-autocomplete-script"]));
  } else if(options["zsh-autocomplete-script"]) {
    console.log(autocompleteScript.bashScript(options["zsh-autocomplete-script"], true));
  } else if(options["autocomplete-words"] && options["autocomplete-index"]) {
    cli.autocomplete(cliApp, options["autocomplete-words"], options["autocomplete-index"], flagNames, optionNames);
  } else {
    cli.execute(cliApp, args, options);
  }
};


text:
FactoryGirl.define do
  factory :time_table do
    course nil
start_date "2016-02-08"
comments "MyText"
  end

end


text:
namespace swift {
class ModuleDecl;
class SourceFile;
class DeclContext;

namespace index {

void indexDeclContext(DeclContext *DC, IndexDataConsumer &consumer);
void indexSourceFile(SourceFile *SF, StringRef hash,
                     IndexDataConsumer &consumer);
void indexModule(ModuleDecl *module, StringRef hash,
                 IndexDataConsumer &consumer);

} // end namespace index
} // end namespace swift

#endif // SWIFT_INDEX_INDEX_H


text:
package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Rat extends StdMOB
{
	@Override
	public String ID()
	{
		return "Rat";
	}

	public Rat()
	{
		super();
		username="a rat";
		setDescription("A small furry rodent with a long, leathery tail.");
		setDisplayText("A rat is here nibbling on something.");
		CMLib.factions().setAlignment(this,Faction.Align.NEUTRAL);
		setMoney(0);
		setWimpHitPoint(2);

		basePhyStats().setDamage(1);

		baseCharStats().setMyRace(CMClass.getRace("Rat"));
		baseCharStats().getMyRace().startRacing(this,false);

		basePhyStats().setAbility(0);
		basePhyStats().setLevel(1);
		basePhyStats().setArmor(90);

		baseState.setHitPoints(CMLib.dice().roll(basePhyStats().level(),20,basePhyStats().level()));

		recoverMaxState();
		resetToMaxState();
		recoverPhyStats();
		recoverCharStats();
	}

}


text:
import axios from 'axios';
import {localApi, awsApi} from '../config.json';
//get user
export const GET_USER = 'GET_USER';
export const GET_USER_SUCCESS = 'GET_USER_SUCCESS';
export const GET_USER_ERROR = 'GET_USER_ERROR';
//Login
export const POST_LOGIN = "POST_LOGIN";
export const POST_LOGIN_SUCCESS = "POST_LOGIN_SUCCESS";
export const POST_LOGIN_ERROR = "POST_LOGIN_ERROR";

//Actions creators para o login. Ver documentação react-redux

const getUser = () => {
  return {
    type: GET_USER
  }
}

const getUserSuccess = (response) => {
  return {
    type: GET_USER_SUCCESS,
    //key = value então apenas uma vez
    response
  }
}

const getUserError = (error) => {
  return {
    type: GET_USER_ERROR,
    error
  }
}

export const getUserRequest = (id) => {
  const instance = axios.create({
    headers: {
      "Content-Type" : "application/json"
    }
  });

  const request = instance.get(`${awsApi.url}/clientes/procurar?_id=${id}`);

  return dispatch => {
    dispatch(getUser());

    return request.then( (response) => {
      console.log("GET USER S", response);
      dispatch(getUserSuccess(response));
    }).catch( (err) => {
      console.log("GET USER ERR", err);
      dispatch(getUserError(err));
    });
  }
}

const postLogin = () => {
  return {
    type: POST_LOGIN
  }
}

const postLoginSuccess = (response) => {
  return {
    type: POST_LOGIN_SUCCESS,
    response
  }
}

const postLoginError = (error) => {
  return {
    type: POST_LOGIN_ERROR,
    error
  }
}

export const postLoginRequest = (payload) => {
  const instance = axios.create({
    headers: {
      "Content-Type" : "application/json"
    }
  });

  const request = instance.post(`${awsApi.url}/clientes/login`, payload);

  return dispatch => {
    dispatch(postLogin());

    return request.then( (response) => {
      console.log("POST LOGIN SUCCESS", response);
      dispatch(postLoginSuccess(response));
    }).catch( (error) => {
      console.log("POST LOGIN ERR", error);
      dispatch(postLoginError(error));
    });
  }
}


text:
package com.sergiopino.ars.dao.notes;

import org.springframework.stereotype.Repository;

import com.sergiopino.ars.dao.JpaDao;
import com.sergiopino.ars.entity.Note;

@Repository("notesDao")
public class JpaNotesDao extends JpaDao<Note, Long> implements NotesDao
{

	public JpaNotesDao()
	{
		super(Note.class);
	}

}


text:
using System;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using FluentMigrator.Tests.Helpers;
using NUnit.Framework;
using NUnit.Should;

namespace FluentMigrator.Tests.Unit.Expressions
{
    [TestFixture]
    public class DeleteSequenceExpressionTests
    {
        [Test]
        public void ErrorIsReturnedWhenSequenceNameIsEmptyString()
        {
            var expression = new DeleteSequenceExpression { SequenceName = String.Empty };

            var errors = ValidationHelper.CollectErrors(expression);
            errors.ShouldContain(ErrorMessages.SequenceNameCannotBeNullOrEmpty);
        }

        [Test]
        public void ErrorIsNotReturnedWhenSequenceNameIsSet()
        {
            var expression = new DeleteSequenceExpression { SequenceName = "sequence1" };

            var errors = ValidationHelper.CollectErrors(expression);
            Assert.That(errors.Count, Is.EqualTo(0));
        }

        [Test]
        public void WhenDefaultSchemaConventionIsAppliedAndSchemaIsNotSetThenSchemaShouldBeNull()
        {
            var expression = new DeleteSequenceExpression { SequenceName = "sequence1" };

            expression.ApplyConventions(new MigrationConventions());

            Assert.That(expression.SchemaName, Is.Null);
        }

        [Test]
        public void WhenDefaultSchemaConventionIsAppliedAndSchemaIsSetThenSchemaShouldNotBeChanged()
        {
            var expression = new DeleteSequenceExpression { SchemaName = "testschema", SequenceName = "sequence1" };

            expression.ApplyConventions(new MigrationConventions());

            Assert.That(expression.SchemaName, Is.EqualTo("testschema"));
        }

        [Test]
        public void WhenDefaultSchemaConventionIsChangedAndSchemaIsNotSetThenSetSchema()
        {
            var expression = new DeleteSequenceExpression { SequenceName = "sequence1" };
            var migrationConventions = new MigrationConventions { GetDefaultSchema = () => "testdefault" };

            expression.ApplyConventions(migrationConventions);

            Assert.That(expression.SchemaName, Is.EqualTo("testdefault"));
        }
    }
}


text:
PokeStack

A curated directory of Pokemon GO resources


text:
/*
 * SHA-224 and SHA-256 hash function.
 * Will use Openssl if the openssl version is great enough.
 * otherwise, we use C code, in ssh2.c, and some #defines
 * to make that code 'appear' like OpenSSL  It was done this
 * way, just in case there are versions of OSSL that have some
 * of this code, older than what we 'know' about. If we do not
 * use differnt names, (and #defines to map), we run the risk
 * of having multiple defined functions/data.
 *
 * NOTE, if FORCE_GENERIC_SHA2 is defined before this header is
 * included, then the generic data_types/functions are used.
 *
 */

#ifndef _JOHN_SHA2_h
#define _JOHN_SHA2_h

#include <string.h>
#include "arch.h"
#include "aligned.h"
#include <openssl/opensslv.h>
#include "openssl_local_overrides.h"

#if (AC_BUILT && HAVE_SHA256 && !FORCE_GENERIC_SHA2) ||	  \
    (!AC_BUILT && OPENSSL_VERSION_NUMBER >= 0x00908000 && !FORCE_GENERIC_SHA2)

#if HAVE_COMMONCRYPTO || (!AC_BUILT &&	  \
	!defined(MMX_COEF) && defined(__APPLE__) && defined(__MACH__) && \
	 defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \
	 __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070)
/* Mitigate CommonCrypto name clashes */
#include "md4.h"
#include "md5.h"
#define COMMON_DIGEST_FOR_OPENSSL 1
#define SHA2_LIB "CommonCrypto"
#include <CommonCrypto/CommonDigest.h>
#define JTR_INC_COMMON_CRYPTO_SHA2
#else
#define SHA2_LIB "OpenSSL"
#include <openssl/sha.h>
#endif

#undef GENERIC_SHA2

#else	// OPENSSL_VERSION_NUMBER ! >= 0x00908000

#include "jtr_sha2.h"

#define SHA2_LIB "generic"
#define GENERIC_SHA2

#endif

#endif /* _JOHN_SHA2_h */


text:
/*-----------------------------------------------------------
This is a very simple TGA lib. It will only load and save
uncompressed images in greyscale, RGB or RGBA mode.

If you want a more complete lib I suggest you take
a look at Paul Groves' TGA loader. Paul's home page is at

	http://paulyg.virtualave.net

Just a little bit about the TGA file format.

Header - 12 fields

id						unsigned char
colour map type			unsigned char
image type				unsigned char

	1	-	colour map image
	2	-	RGB(A) uncompressed
	3	-	greyscale uncompressed
	9	-	greyscale RLE (compressed)
	10	-	RGB(A) RLE (compressed)

colour map first entry	short int
colour map length		short int
map entry size			short int

horizontal origin		short int
vertical origin			short int
width					short int
height					short int
pixel depth				unsigned char

	8	-	greyscale
	24	-	RGB
	32	-	RGBA

image descriptor		unsigned char

From all these fields, we only care about the image type,
to check if the image is uncompressed and not color indexed,
the width and height, and the pixel depth.

You may use this library for whatever you want. This library is
provide as is, meaning that I won't take any responsability for
any damages that you may incur for its usage.

Antonio Ramires Fernandes ajbrf@yahoo.com
-------------------------------------------------------------*/

#define	TGA_ERROR_FILE_OPEN				-5
#define TGA_ERROR_READING_FILE			-4
#define TGA_ERROR_INDEXED_COLOR			-3
#define TGA_ERROR_MEMORY				-2
#define TGA_ERROR_COMPRESSED_FILE		-1
#define TGA_OK							 0

typedef struct {
	int status;
	unsigned char type, pixelDepth;
	short int width, height;
	unsigned char *imageData;
}tgaInfo;

tgaInfo* tgaLoad(char *filename);

int tgaSave(char			*filename,
			 short int		width,
			 short int		height,
			 unsigned char	pixelDepth,
			 unsigned char	*imageData);

int tgaSaveSeries(char			*filename,
			 short int		width,
			 short int		height,
			 unsigned char	pixelDepth,
			 unsigned char	*imageData);

void tgaRGBtoGreyscale(tgaInfo *info);

int tgaGrabScreenSeries(char *filename, int x,int y, int w, int h);

void tgaDestroy(tgaInfo *info);


text:
from media_tree.models import FileNode
from media_tree.utils.filenode import get_file_link
from django import template

register = template.Library()

def get_kwargs_for_file_link(opts):
	kwargs = {
		'use_metadata': False,
		'include_size': False,
		'include_extension': False,
		'include_icon': False
	}
	if isinstance(opts, basestring):
		for key in opts.split(' '):
			kwargs[key] = True
	elif isinstance(opts, dict):
		kwargs.update(opts)
	return kwargs

def file_links(items, opts=None):
	"""
	Turns a (optionally nested) list of FileNode objects into a list of
	strings, linking to the associated files.
	"""
	result = []
	kwargs = get_kwargs_for_file_link(opts)
	for item in items:
		if isinstance(item, FileNode):
			result.append(get_file_link(item, **kwargs))
		else:
			result.append(file_links(item, kwargs))
	return result

register.filter(file_links)

def file_link(node, opts=None):
	"""
	Turns a FileNode object into a string, linking to the associated file.
	"""
	kwargs = get_kwargs_for_file_link(opts)
	return get_file_link(node, **kwargs)

register.filter(file_link)


text:
<?php

namespace Riverline\WorkerBundle\Provider;

use Riverline\WorkerBundle\Exception\NotImplementedFeatureException;

/**
 * Interface ProviderInterface
 * @package Riverline\WorkerBundle\Provider
 */
interface ProviderInterface
{
    /**
     * Get the amount of workload in the queue
     * @abstract
     *
     * @param string $queueName The queue name
     *
     * @return int
     * @throws NotImplementedFeatureException
     */
    public function count($queueName);

    /**
     * Create a new queue.
     * @abstract
     *
     * @param string $queueName    The queue name
     * @param array  $queueOptions The queue options
     *
     * @return \Riverline\WorkerBundle\Queue\Queue
     * @throws NotImplementedFeatureException
     */
    public function createQueue($queueName, array $queueOptions = []);

    /**
     * Delete a queue.
     * @abstract
     *
     * @param string $queueName The queue name
     *
     * @return boolean
     * @throws NotImplementedFeatureException
     */
    public function deleteQueue($queueName);

    /**
     * Get a workload from the queue
     * @abstract
     *
     * @param string   $queueName The queue name
     * @param int|null $timeout   The wait timeout for a workload
     *
     * @return mixed|null
     */
    public function get($queueName, $timeout = null);

    /**
     * Return queue options.
     *
     * @param string $queueName
     *
     * @return array
     * @throws NotImplementedFeatureException
     */
    public function getQueueOptions($queueName);

    /**
     * List all the queues.
     * @abstract
     *
     * @param string $queueNamePrefix
     *
     * @return array
     * @throws NotImplementedFeatureException
     */
    public function listQueues($queueNamePrefix = null);

    /**
     * Put multpile workload in the queue
     * @abstract
     *
     * @param string $queueName The queue name
     * @param array  $workloads Array of workloads
     */
    public function multiPut($queueName, array $workloads);

    /**
     * Put a workload in the queue
     * @abstract
     *
     * @param string $queueName The queue name
     * @param mixed  $workload  The workload
     */
    public function put($queueName, $workload);

    /**
     * Indicates if a queue exists.
     * @abstract
     *
     * @param string $queueName The queue name
     *
     * @return boolean
     * @throws NotImplementedFeatureException
     */
    public function queueExists($queueName);

    /**
     * Update a queue.
     * @abstract
     *
     * @param string $queueName    The queue name
     * @param array  $queueOptions The queue options
     *
     * @return boolean
     * @throws NotImplementedFeatureException
     */
    public function updateQueue($queueName, array $queueOptions = []);
}


text:
@echo off
REM Windows batch file to get results on the basis of success files from AWS Mechanical Turk
REM Author: Sreejith Menon
REM Date: 21th May 2016

set /p directory="Enter source drive : "
%directory%:

set /p mTurkPath="Enter AWS CLT bin directory path : "
cd %mTurkPath%

set /p jobPath="Enter jobs directory path : "

call getResults -successfile %jobPath%\photo_album_31.input.success -outputfile  %jobPath%\photo_album_31.results
call getResults -successfile %jobPath%\photo_album_32.input.success -outputfile  %jobPath%\photo_album_32.results
call getResults -successfile %jobPath%\photo_album_33.input.success -outputfile  %jobPath%\photo_album_33.results
call getResults -successfile %jobPath%\photo_album_34.input.success -outputfile  %jobPath%\photo_album_34.results
call getResults -successfile %jobPath%\photo_album_35.input.success -outputfile  %jobPath%\photo_album_35.results
call getResults -successfile %jobPath%\photo_album_36.input.success -outputfile  %jobPath%\photo_album_36.results
call getResults -successfile %jobPath%\photo_album_37.input.success -outputfile  %jobPath%\photo_album_37.results
call getResults -successfile %jobPath%\photo_album_38.input.success -outputfile  %jobPath%\photo_album_38.results
call getResults -successfile %jobPath%\photo_album_39.input.success -outputfile  %jobPath%\photo_album_39.results
call getResults -successfile %jobPath%\photo_album_40.input.success -outputfile  %jobPath%\photo_album_40.results

PAUSE


text:
/**
 * Created by rrusk on 2015/02/20.
 * Modified by rrusk on 2015/05/04.
 */
// Title: What percentage of patients, calculated as active, has an invalid date of birth?
// Description: DQ-DEM-03
// Note 1: Checks for patients that are more than 150 years old or younger than yesterday.
// Note 2: Encounters include entries in case management notes and prescription events
// Note 3: A potentially useful check to add would be that the patient was born before the first recorded encounter.

function map(patient) {

    var drugList = patient.medications();
    var encounterList = patient.encounters();

    var refdateStr = setStoppDQRefDateStr(); // hQuery library function call
    var refdate = new Date(refdateStr);      // refdateStr is 'yyyy,mm,dd' with mm from 1-12
    refdate.setHours(23, 59);                // set to end of refdate then subtract one day
    var start = addDate(refdate, -2, 0, -1); // 24 month study window; generally most
    var end = addDate(refdate, 0, 0, -1);    // recent records are from previous day
    var currentRec = currentRecord(end);

    var age = patient.age(end);

    // Shifts date by year, month, and date specified
    function addDate(date, y, m, d) {
        var n = new Date(date);
        n.setFullYear(date.getFullYear() + (y || 0));
        n.setMonth(date.getMonth() + (m || 0));
        n.setDate(date.getDate() + (d || 0));
        return n;
    }

    // Test that record is current (as of day before study reference date at 0:00AM)
    function currentRecord(date) {
        var daybefore = new Date(date);
        daybefore.setHours(0, 0);
        return patient['json']['effective_time'] > daybefore / 1000;
    }

    // Checks for encounter between start and end dates
    function hadEncounter(startDate, endDate) {
        for (var i = 0; i < encounterList.length; i++) {
            if (encounterList[i].startDate() >= startDate &&
                encounterList[i].startDate() <= endDate) {
                return true;
            }
        }
        return false;
    }

    // Checks for prescription encounter between start and end dates
    function hadRxEncounter(startDate, endDate) {
        for (var i = 0; i < drugList.length; i++) {
            if (typeof drugList[i].orderInformation() !== 'undefined' &&
                typeof drugList[i].orderInformation().length != 0) {
                for (var j = 0; j < drugList[i].orderInformation().length; j++) {
                    var drugPrescribed = drugList[i].orderInformation()[j].orderDateTime();
                    drugPrescribed.setHours(24,1);  // kludge to get start date to match rx_date in EMR
                    if (drugPrescribed >= startDate && drugPrescribed <= endDate) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /* // Checks for encounter before birthdate
     function hasInvalidEncounterDate(birthdate) {
     for (var i = 0; i < encounterList.length; i++) {
     if (encounterList[i].startDate() < birthdate) {
     emit("e_d_no: " + patient["json"]["emr_demographics_primary_key"] + " edate: " + encounterList[i].startDate() + " birthdate: "+birthdate,1);
     return true;
     }
     }
     for (var i = 0; i < drugList.length; i++) {
     if (typeof drugList[i].orderInformation() !== 'undefined' &&
     typeof drugList[i].orderInformation().length != 0) {
     for (var j = 0; j < drugList[i].orderInformation().length; j++) {
     var drugPrescribedDate = drugList[i].orderInformation()[j].orderDateTime();
     if (drugPrescribedDate < birthdate) {
     emit("rx_d_no: " + patient["json"]["emr_demographics_primary_key"],1);
     return true;
     }
     }
     }
     }
     return false;
     }*/

    // Checks if patient is out of age range
    function incorrectAge() {
        return (age === null || typeof age == 'undefined' || Number.isNaN(age) || age < 0 || age > 150);// || hasInvalidEncounterDate(patient.birthtime()));
    }

    refdateStr = refdateStr.replace(/,/g, '');
    emit('denominator_' + refdateStr, 0);
    emit('numerator_' + refdateStr, 0);
    if (currentRec && (hadEncounter(start, end) || hadRxEncounter(start, end))) {
        emit('denominator_' + refdateStr, 1);
        if (incorrectAge()) {
            emit('numerator_' + refdateStr, 1);
        }
    }
}


text:
<?php

namespace Vegas\Security\Acl\Adapter\Exception;

use Vegas\Security\Acl\Adapter\Exception as AclAdapterException;

/**
 *
 * @package Vegas\Security\Acl\Adapter\Exception
 */
class ResourceNotExistsException extends AclAdapterException
{
    protected $message = "Resource does not exist";

    /**
     * @param string $resourceName
     */
    public function __construct($resourceName = '')
    {
        $this->message = sprintf("Resource '%s' does not exist", $resourceName);
    }
}


text:
package com.barentine.totalconnect.ws;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ArrayOfSecuritySubAction complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ArrayOfSecuritySubAction">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="SecuritySubAction" type="{https://services.alarmnet.com/TC2/}SecuritySubAction" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfSecuritySubAction", propOrder = {
    "securitySubAction"
})
public class ArrayOfSecuritySubAction {

    @XmlElement(name = "SecuritySubAction", nillable = true)
    protected List<SecuritySubAction> securitySubAction;

    /**
     * Gets the value of the securitySubAction property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the securitySubAction property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getSecuritySubAction().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link SecuritySubAction }
     *
     *
     */
    public List<SecuritySubAction> getSecuritySubAction() {
        if (securitySubAction == null) {
            securitySubAction = new ArrayList<SecuritySubAction>();
        }
        return this.securitySubAction;
    }

}


text:
from fabric.api import *
from fabric.contrib.files import *

@task
def install():
    sudo('yum -y --enablerepo=remi install mysql-server')

@task
def config():
    upload_template(
        'fabfile/common/templates/my.cnf',
        '/etc/my.cnf',
        context = {
            'buffer_pool_size': env.MYSQL_BUFFER_POOL_SIZE
        },
        use_sudo = True,
        use_jinja = True,
        mode = 0644
    )
    sudo('chown root.root /etc/my.cnf')

@task
def chkconfig():
    sudo('chkconfig mysqld on')

@task
def restart():
    sudo('service mysqld restart')

@task
def adduser():
    run('mysql -u root -e "grant all on *.* to \'%s\'@\'localhost\' identified by \'%s\';"' % (env.MYSQL_USER_NAME, env.MYSQL_USER_PASSWORD))
    run('mysql -u root -e "revoke super on *.* from \'%s\'@\'localhost\';"' % env.MYSQL_USER_NAME)
    run('mysql -u root -e "grant all on *.* to \'%s\'@\'%%\' identified by \'%s\';"' % (env.MYSQL_USER_NAME, env.MYSQL_USER_PASSWORD))
    run('mysql -u root -e "revoke super on *.* from \'%s\'@\'%%\';"' % env.MYSQL_USER_NAME)

@task
def create_database():
    run('mysql -u root -e "create database %s character set utf8mb4 collate utf8mb4_general_ci;"' % env.MYSQL_DATABASE_NAME)


text:
package org.apache.sling.engine.impl.adapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper;

/**
 * The SlingServletRequestAdapter class is a
 * ComponentRequestWrapper which does not delegate to a wrapped
 * ComponentRequest but to a wrapped
 * HttpServletRequest. This is required if any user of the
 * RequestDispatcher.include method uses a
 * HttpServletRequestWrapper instead of a
 * ComponentRequestWrapper.
 */
public class SlingServletRequestAdapter extends SlingHttpServletRequestWrapper {

    private final HttpServletRequest request;

    public SlingServletRequestAdapter(SlingHttpServletRequest delegatee,
            HttpServletRequest request) {
        super(delegatee);
        this.request = request;
    }

    @Override
    public String getLocalAddr() {
        return request.getLocalAddr();
    }

    @Override
    public String getLocalName() {
        return request.getLocalName();
    }

    @Override
    public int getLocalPort() {
        return request.getLocalPort();
    }

    @Override
    public int getRemotePort() {
        return request.getRemotePort();
    }

    @Override
    public String getAuthType() {
        return request.getAuthType();
    }

    @Override
    public String getContextPath() {
        return request.getContextPath();
    }

    @Override
    public Cookie[] getCookies() {
        return request.getCookies();
    }

    @Override
    public long getDateHeader(String name) {
        return request.getDateHeader(name);
    }

    @Override
    public String getHeader(String name) {
        return request.getHeader(name);
    }

    @Override
    public Enumeration<?> getHeaderNames() {
        return request.getHeaderNames();
    }

    @Override
    public Enumeration<?> getHeaders(String name) {
        return request.getHeaders(name);
    }

    @Override
    public int getIntHeader(String name) {
        return request.getIntHeader(name);
    }

    @Override
    public String getMethod() {
        return request.getMethod();
    }

    @Override
    public String getPathInfo() {
        return request.getPathInfo();
    }

    @Override
    public String getPathTranslated() {
        return request.getPathTranslated();
    }

    @Override
    public String getQueryString() {
        return request.getQueryString();
    }

    @Override
    public String getRemoteUser() {
        return request.getRemoteUser();
    }

    @Override
    public String getRequestURI() {
        return request.getRequestURI();
    }

    @Override
    public StringBuffer getRequestURL() {
        return request.getRequestURL();
    }

    @Override
    public String getRequestedSessionId() {
        return request.getRequestedSessionId();
    }

    @Override
    public String getServletPath() {
        return request.getServletPath();
    }

    @Override
    public HttpSession getSession() {
        return request.getSession();
    }

    @Override
    public HttpSession getSession(boolean create) {
        return request.getSession(create);
    }

    @Override
    public Principal getUserPrincipal() {
        return request.getUserPrincipal();
    }

    @Override
    public boolean isRequestedSessionIdFromCookie() {
        return request.isRequestedSessionIdFromCookie();
    }

    @Override
    public boolean isRequestedSessionIdFromURL() {
        return request.isRequestedSessionIdFromURL();
    }

    @Override
    @Deprecated
    public boolean isRequestedSessionIdFromUrl() {
        return request.isRequestedSessionIdFromUrl();
    }

    @Override
    public boolean isRequestedSessionIdValid() {
        return request.isRequestedSessionIdValid();
    }

    @Override
    public boolean isUserInRole(String role) {
        return request.isUserInRole(role);
    }

    @Override
    public Object getAttribute(String name) {
        return request.getAttribute(name);
    }

    @Override
    public Enumeration<?> getAttributeNames() {
        return request.getAttributeNames();
    }

    @Override
    public String getCharacterEncoding() {
        return request.getCharacterEncoding();
    }

    @Override
    public int getContentLength() {
        return request.getContentLength();
    }

    @Override
    public String getContentType() {
        return request.getContentType();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return request.getInputStream();
    }

    @Override
    public Locale getLocale() {
        return request.getLocale();
    }

    @Override
    public Enumeration<?> getLocales() {
        return request.getLocales();
    }

    @Override
    public String getParameter(String name) {
        return request.getParameter(name);
    }

    @Override
    public Map<?, ?> getParameterMap() {
        return request.getParameterMap();
    }

    @Override
    public Enumeration<?> getParameterNames() {
        return request.getParameterNames();
    }

    @Override
    public String[] getParameterValues(String name) {
        return request.getParameterValues(name);
    }

    @Override
    public String getProtocol() {
        return request.getProtocol();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return request.getReader();
    }

    @Override
    @Deprecated
    public String getRealPath(String path) {
        return request.getRealPath(path);
    }

    @Override
    public String getRemoteAddr() {
        return request.getRemoteAddr();
    }

    @Override
    public String getRemoteHost() {
        return request.getRemoteHost();
    }

    @Override
    public ServletRequest getRequest() {
        return request;
    }

    @Override
    public RequestDispatcher getRequestDispatcher(String path) {
        return request.getRequestDispatcher(path);
    }

    @Override
    public String getScheme() {
        return request.getScheme();
    }

    @Override
    public String getServerName() {
        return request.getServerName();
    }

    @Override
    public int getServerPort() {
        return request.getServerPort();
    }

    @Override
    public boolean isSecure() {
        return request.isSecure();
    }

    @Override
    public void removeAttribute(String name) {
        request.removeAttribute(name);
    }

    @Override
    public void setAttribute(String name, Object o) {
        request.setAttribute(name, o);
    }

    @Override
    public void setCharacterEncoding(String enc)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding(enc);
    }
}


text:
package com.microsoft.services.graph;

import com.microsoft.services.orc.core.ODataBaseEntity;

/**
 * The type Item Reference.
* @deprecated This SDK is deprecated. Please review the README for further information (https://github.com/OfficeDev/Microsoft-Graph-SDK-Android).
 */
@Deprecated
public class ItemReference extends ODataBaseEntity {

    public ItemReference(){
        setODataType("#microsoft.graph.itemReference");
    }

    private String driveId;

    /**
    * Gets the drive Id.
    *
    * @return the String
    */
    public String getDriveId() {
        return this.driveId;
    }

    /**
    * Sets the drive Id.
    *
    * @param value the String
    */
    public void setDriveId(String value) {
        this.driveId = value;
        valueChanged("driveId", value);

    }

    private String id;

    /**
    * Gets the id.
    *
    * @return the String
    */
    public String getId() {
        return this.id;
    }

    /**
    * Sets the id.
    *
    * @param value the String
    */
    public void setId(String value) {
        this.id = value;
        valueChanged("id", value);

    }

    private String path;

    /**
    * Gets the path.
    *
    * @return the String
    */
    public String getPath() {
        return this.path;
    }

    /**
    * Sets the path.
    *
    * @param value the String
    */
    public void setPath(String value) {
        this.path = value;
        valueChanged("path", value);

    }
}


text:
namespace OpenProtocolInterpreter
{
    /// <summary>
    /// Result types. Used in <see cref="Tightening.Mid0061"/> and <see cref="Tightening.Mid0065"/>.
    /// </summary>
    public enum ResultType
    {
        TIGHTENING = 1,
        LOOSENING = 2,
        BATCH_INCREMENT = 3,
        BATCH_DECREMENT = 4,
        BYPASS_PARAMETER_SET_RESULT = 5,
        ABORT_JOB_RESULT = 6,
        SYNC_TIGHTENING = 7,
        REFERENCE_SETUP = 8
    }
}


text:
FROM python:2.7.13
MAINTAINER jizhilong <zhilongji@gmail.com>

ADD dresponse/requirements.txt /usr/local/src/dresponse/requirements.txt

RUN pip install -r /usr/local/src/dresponse/requirements.txt

CMD ["uwsgi", "--http-socket", "/var/run/dresponse/dresponse.sock", "-w", "dresponse.wsgi"]

ADD dresponse /usr/local/src/dresponse
ADD dwait/bin.tar /usr/lib/dwait
RUN pip install /usr/local/src/dresponse &&\
    mkdir -p /var/lib/dresponse/
ENTRYPOINT ["/usr/local/src/dresponse/bin/entrypoint"]


text:
"""
This module provides helpers for C++11+ projects using pybind11.

LICENSE:

Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>, All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

# IMPORTANT: If you change this file in the pybind11 repo, also review
# setup_helpers.pyi for matching changes.
#
# If you copy this file in, you don't
# need the .pyi file; it's just an interface file for static type checkers.

import contextlib
import os
import platform
import shlex
import shutil
import sys
import sysconfig
import tempfile
import threading
import warnings
from functools import lru_cache
from pathlib import Path
from typing import (
    Any,
    Callable,
    Dict,
    Iterable,
    Iterator,
    List,
    Optional,
    Tuple,
    TypeVar,
    Union,
)

try:
    from setuptools import Extension as _Extension
    from setuptools.command.build_ext import build_ext as _build_ext
except ImportError:
    from distutils.command.build_ext import build_ext as _build_ext
    from distutils.extension import Extension as _Extension

import distutils.ccompiler
import distutils.errors

WIN = sys.platform.startswith("win32") and "mingw" not in sysconfig.get_platform()
MACOS = sys.platform.startswith("darwin")
STD_TMPL = "/std:c++{}" if WIN else "-std=c++{}"

# It is recommended to use PEP 518 builds if using this module. However, this
# file explicitly supports being copied into a user's project directory
# standalone, and pulling pybind11 with the deprecated setup_requires feature.
# If you copy the file, remember to add it to your MANIFEST.in, and add the current
# directory into your path if it sits beside your setup.py.

class Pybind11Extension(_Extension):  # type: ignore[misc]
    """
    Build a C++11+ Extension module with pybind11. This automatically adds the
    recommended flags when you init the extension and assumes C++ sources - you
    can further modify the options yourself.

    The customizations are:

    * ``/EHsc`` and ``/bigobj`` on Windows
    * ``stdlib=libc++`` on macOS
    * ``visibility=hidden`` and ``-g0`` on Unix

    Finally, you can set ``cxx_std`` via constructor or afterwards to enable
    flags for C++ std, and a few extra helper flags related to the C++ standard
    level. It is _highly_ recommended you either set this, or use the provided
    ``build_ext``, which will search for the highest supported extension for
    you if the ``cxx_std`` property is not set. Do not set the ``cxx_std``
    property more than once, as flags are added when you set it. Set the
    property to None to disable the addition of C++ standard flags.

    If you want to add pybind11 headers manually, for example for an exact
    git checkout, then set ``include_pybind11=False``.
    """

    # flags are prepended, so that they can be further overridden, e.g. by
    # ``extra_compile_args=["-g"]``.

    def _add_cflags(self, flags: List[str]) -> None:
        self.extra_compile_args[:0] = flags

    def _add_ldflags(self, flags: List[str]) -> None:
        self.extra_link_args[:0] = flags

    def __init__(self, *args: Any, **kwargs: Any) -> None:

        self._cxx_level = 0
        cxx_std = kwargs.pop("cxx_std", 0)

        if "language" not in kwargs:
            kwargs["language"] = "c++"

        include_pybind11 = kwargs.pop("include_pybind11", True)

        super().__init__(*args, **kwargs)

        # Include the installed package pybind11 headers
        if include_pybind11:
            # If using setup_requires, this fails the first time - that's okay
            try:
                import pybind11

                pyinc = pybind11.get_include()

                if pyinc not in self.include_dirs:
                    self.include_dirs.append(pyinc)
            except ModuleNotFoundError:
                pass

        self.cxx_std = cxx_std

        cflags = []
        ldflags = []
        if WIN:
            cflags += ["/EHsc", "/bigobj"]
        else:
            cflags += ["-fvisibility=hidden"]
            env_cflags = os.environ.get("CFLAGS", "")
            env_cppflags = os.environ.get("CPPFLAGS", "")
            c_cpp_flags = shlex.split(env_cflags) + shlex.split(env_cppflags)
            if not any(opt.startswith("-g") for opt in c_cpp_flags):
                cflags += ["-g0"]
            if MACOS:
                cflags += ["-stdlib=libc++"]
                ldflags += ["-stdlib=libc++"]
        self._add_cflags(cflags)
        self._add_ldflags(ldflags)

    @property
    def cxx_std(self) -> int:
        """
        The CXX standard level. If set, will add the required flags. If left at
        0, it will trigger an automatic search when pybind11's build_ext is
        used. If None, will have no effect.  Besides just the flags, this may
        add a macos-min 10.9 or 10.14 flag if MACOSX_DEPLOYMENT_TARGET is
        unset.
        """
        return self._cxx_level

    @cxx_std.setter
    def cxx_std(self, level: int) -> None:

        if self._cxx_level:
            warnings.warn("You cannot safely change the cxx_level after setting it!")

        # MSVC 2015 Update 3 and later only have 14 (and later 17) modes, so
        # force a valid flag here.
        if WIN and level == 11:
            level = 14

        self._cxx_level = level

        if not level:
            return

        cflags = [STD_TMPL.format(level)]
        ldflags = []

        if MACOS and "MACOSX_DEPLOYMENT_TARGET" not in os.environ:
            # C++17 requires a higher min version of macOS. An earlier version
            # (10.12 or 10.13) can be set manually via environment variable if
            # you are careful in your feature usage, but 10.14 is the safest
            # setting for general use. However, never set higher than the
            # current macOS version!
            current_macos = tuple(int(x) for x in platform.mac_ver()[0].split(".")[:2])
            desired_macos = (10, 9) if level < 17 else (10, 14)
            macos_string = ".".join(str(x) for x in min(current_macos, desired_macos))
            macosx_min = f"-mmacosx-version-min={macos_string}"
            cflags += [macosx_min]
            ldflags += [macosx_min]

        self._add_cflags(cflags)
        self._add_ldflags(ldflags)

# Just in case someone clever tries to multithread
tmp_chdir_lock = threading.Lock()

@contextlib.contextmanager
def tmp_chdir() -> Iterator[str]:
    "Prepare and enter a temporary directory, cleanup when done"

    # Threadsafe
    with tmp_chdir_lock:
        olddir = os.getcwd()
        try:
            tmpdir = tempfile.mkdtemp()
            os.chdir(tmpdir)
            yield tmpdir
        finally:
            os.chdir(olddir)
            shutil.rmtree(tmpdir)

# cf http://bugs.python.org/issue26689
def has_flag(compiler: Any, flag: str) -> bool:
    """
    Return the flag if a flag name is supported on the
    specified compiler, otherwise None (can be used as a boolean).
    If multiple flags are passed, return the first that matches.
    """

    with tmp_chdir():
        fname = Path("flagcheck.cpp")
        # Don't trigger -Wunused-parameter.
        fname.write_text("int main (int, char **) { return 0; }", encoding="utf-8")

        try:
            compiler.compile([str(fname)], extra_postargs=[flag])
        except distutils.errors.CompileError:
            return False
        return True

# Every call will cache the result
cpp_flag_cache = None

@lru_cache()
def auto_cpp_level(compiler: Any) -> Union[str, int]:
    """
    Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows.
    """

    if WIN:
        return "latest"

    levels = [17, 14, 11]

    for level in levels:
        if has_flag(compiler, STD_TMPL.format(level)):
            return level

    msg = "Unsupported compiler -- at least C++11 support is needed!"
    raise RuntimeError(msg)

class build_ext(_build_ext):  # type: ignore[misc] # noqa: N801
    """
    Customized build_ext that allows an auto-search for the highest supported
    C++ level for Pybind11Extension. This is only needed for the auto-search
    for now, and is completely optional otherwise.
    """

    def build_extensions(self) -> None:
        """
        Build extensions, injecting C++ std for Pybind11Extension if needed.
        """

        for ext in self.extensions:
            if hasattr(ext, "_cxx_level") and ext._cxx_level == 0:
                ext.cxx_std = auto_cpp_level(self.compiler)

        super().build_extensions()

def intree_extensions(
    paths: Iterable[str], package_dir: Optional[Dict[str, str]] = None
) -> List[Pybind11Extension]:
    """
    Generate Pybind11Extensions from source files directly located in a Python
    source tree.

    ``package_dir`` behaves as in ``setuptools.setup``.  If unset, the Python
    package root parent is determined as the first parent directory that does
    not contain an ``__init__.py`` file.
    """
    exts = []

    if package_dir is None:
        for path in paths:
            parent, _ = os.path.split(path)
            while os.path.exists(os.path.join(parent, "__init__.py")):
                parent, _ = os.path.split(parent)
            relname, _ = os.path.splitext(os.path.relpath(path, parent))
            qualified_name = relname.replace(os.path.sep, ".")
            exts.append(Pybind11Extension(qualified_name, [path]))
        return exts

    for path in paths:
        for prefix, parent in package_dir.items():
            if path.startswith(parent):
                relname, _ = os.path.splitext(os.path.relpath(path, parent))
                qualified_name = relname.replace(os.path.sep, ".")
                if prefix:
                    qualified_name = prefix + "." + qualified_name
                exts.append(Pybind11Extension(qualified_name, [path]))
                break
        else:
            msg = (
                f"path {path} is not a child of any of the directories listed "
                f"in 'package_dir' ({package_dir})"
            )
            raise ValueError(msg)

    return exts

def naive_recompile(obj: str, src: str) -> bool:
    """
    This will recompile only if the source file changes. It does not check
    header files, so a more advanced function or Ccache is better if you have
    editable header files in your package.
    """
    return os.stat(obj).st_mtime < os.stat(src).st_mtime

def no_recompile(obg: str, src: str) -> bool:  # pylint: disable=unused-argument
    """
    This is the safest but slowest choice (and is the default) - will always
    recompile sources.
    """
    return True

S = TypeVar("S", bound="ParallelCompile")

CCompilerMethod = Callable[
    [
        distutils.ccompiler.CCompiler,
        List[str],
        Optional[str],
        Optional[Union[Tuple[str], Tuple[str, Optional[str]]]],
        Optional[List[str]],
        bool,
        Optional[List[str]],
        Optional[List[str]],
        Optional[List[str]],
    ],
    List[str],
]

# Optional parallel compile utility
# inspired by: http://stackoverflow.com/questions/11013851/speeding-up-build-process-with-distutils
# and: https://github.com/tbenthompson/cppimport/blob/stable/cppimport/build_module.py
# and NumPy's parallel distutils module:
#              https://github.com/numpy/numpy/blob/master/numpy/distutils/ccompiler.py
class ParallelCompile:
    """
    Make a parallel compile function. Inspired by
    numpy.distutils.ccompiler.CCompiler.compile and cppimport.

    This takes several arguments that allow you to customize the compile
    function created:

    envvar:
        Set an environment variable to control the compilation threads, like
        NPY_NUM_BUILD_JOBS
    default:
        0 will automatically multithread, or 1 will only multithread if the
        envvar is set.
    max:
        The limit for automatic multithreading if non-zero
    needs_recompile:
        A function of (obj, src) that returns True when recompile is needed.  No
        effect in isolated mode; use ccache instead, see
        https://github.com/matplotlib/matplotlib/issues/1507/

    To use::

        ParallelCompile("NPY_NUM_BUILD_JOBS").install()

    or::

        with ParallelCompile("NPY_NUM_BUILD_JOBS"):
            setup(...)

    By default, this assumes all files need to be recompiled. A smarter
    function can be provided via needs_recompile.  If the output has not yet
    been generated, the compile will always run, and this function is not
    called.
    """

    __slots__ = ("envvar", "default", "max", "_old", "needs_recompile")

    def __init__(
        self,
        envvar: Optional[str] = None,
        default: int = 0,
        max: int = 0,  # pylint: disable=redefined-builtin
        needs_recompile: Callable[[str, str], bool] = no_recompile,
    ) -> None:
        self.envvar = envvar
        self.default = default
        self.max = max
        self.needs_recompile = needs_recompile
        self._old: List[CCompilerMethod] = []

    def function(self) -> CCompilerMethod:
        """
        Builds a function object usable as distutils.ccompiler.CCompiler.compile.
        """

        def compile_function(
            compiler: distutils.ccompiler.CCompiler,
            sources: List[str],
            output_dir: Optional[str] = None,
            macros: Optional[Union[Tuple[str], Tuple[str, Optional[str]]]] = None,
            include_dirs: Optional[List[str]] = None,
            debug: bool = False,
            extra_preargs: Optional[List[str]] = None,
            extra_postargs: Optional[List[str]] = None,
            depends: Optional[List[str]] = None,
        ) -> Any:

            # These lines are directly from distutils.ccompiler.CCompiler
            macros, objects, extra_postargs, pp_opts, build = compiler._setup_compile(  # type: ignore[attr-defined]
                output_dir, macros, include_dirs, sources, depends, extra_postargs
            )
            cc_args = compiler._get_cc_args(pp_opts, debug, extra_preargs)  # type: ignore[attr-defined]

            # The number of threads; start with default.
            threads = self.default

            # Determine the number of compilation threads, unless set by an environment variable.
            if self.envvar is not None:
                threads = int(os.environ.get(self.envvar, self.default))

            def _single_compile(obj: Any) -> None:
                try:
                    src, ext = build[obj]
                except KeyError:
                    return

                if not os.path.exists(obj) or self.needs_recompile(obj, src):
                    compiler._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)  # type: ignore[attr-defined]

            try:
                # Importing .synchronize checks for platforms that have some multiprocessing
                # capabilities but lack semaphores, such as AWS Lambda and Android Termux.
                import multiprocessing.synchronize
                from multiprocessing.pool import ThreadPool
            except ImportError:
                threads = 1

            if threads == 0:
                try:
                    threads = multiprocessing.cpu_count()
                    threads = self.max if self.max and self.max < threads else threads
                except NotImplementedError:
                    threads = 1

            if threads > 1:
                with ThreadPool(threads) as pool:
                    for _ in pool.imap_unordered(_single_compile, objects):
                        pass
            else:
                for ob in objects:
                    _single_compile(ob)

            return objects

        return compile_function

    def install(self: S) -> S:
        """
        Installs the compile function into distutils.ccompiler.CCompiler.compile.
        """
        distutils.ccompiler.CCompiler.compile = self.function()  # type: ignore[assignment]
        return self

    def __enter__(self: S) -> S:
        self._old.append(distutils.ccompiler.CCompiler.compile)
        return self.install()

    def __exit__(self, *args: Any) -> None:
        distutils.ccompiler.CCompiler.compile = self._old.pop()  # type: ignore[assignment]


text:
package queryservice

import (
	"fmt"

	"github.com/youtube/vitess/go/sqltypes"
	"github.com/youtube/vitess/go/vt/tabletserver/proto"
	"golang.org/x/net/context"

	querypb "github.com/youtube/vitess/go/vt/proto/query"
)

// QueryService is the interface implemented by the tablet's query service.
type QueryService interface {
	// establish a session to survive restart
	GetSessionId(sessionParams *proto.SessionParams, sessionInfo *proto.SessionInfo) error

	// Transaction management
	Begin(ctx context.Context, target *querypb.Target, session *proto.Session, txInfo *proto.TransactionInfo) error
	Commit(ctx context.Context, target *querypb.Target, session *proto.Session) error
	Rollback(ctx context.Context, target *querypb.Target, session *proto.Session) error

	// Query execution
	Execute(ctx context.Context, target *querypb.Target, query *proto.Query, reply *sqltypes.Result) error
	StreamExecute(ctx context.Context, target *querypb.Target, query *proto.Query, sendReply func(*sqltypes.Result) error) error
	ExecuteBatch(ctx context.Context, target *querypb.Target, queryList *proto.QueryList, reply *proto.QueryResultList) error

	// Map reduce helper
	SplitQuery(ctx context.Context, target *querypb.Target, req *proto.SplitQueryRequest, reply *proto.SplitQueryResult) error

	// StreamHealthRegister registers a listener for StreamHealth
	StreamHealthRegister(chan<- *querypb.StreamHealthResponse) (int, error)

	// StreamHealthUnregister unregisters a listener for StreamHealth
	StreamHealthUnregister(int) error

	// Helper for RPC panic handling: call this in a defer statement
	// at the beginning of each RPC handling method.
	HandlePanic(*error)
}

// ErrorQueryService is an implementation of QueryService that returns a
// configurable error for some of its methods.
type ErrorQueryService struct {
	GetSessionIdError error
}

// GetSessionId is part of QueryService interface
func (e *ErrorQueryService) GetSessionId(sessionParams *proto.SessionParams, sessionInfo *proto.SessionInfo) error {
	return e.GetSessionIdError
}

// Begin is part of QueryService interface
func (e *ErrorQueryService) Begin(ctx context.Context, target *querypb.Target, session *proto.Session, txInfo *proto.TransactionInfo) error {
	return fmt.Errorf("ErrorQueryService does not implement any method")
}

// Commit is part of QueryService interface
func (e *ErrorQueryService) Commit(ctx context.Context, target *querypb.Target, session *proto.Session) error {
	return fmt.Errorf("ErrorQueryService does not implement any method")
}

// Rollback is part of QueryService interface
func (e *ErrorQueryService) Rollback(ctx context.Context, target *querypb.Target, session *proto.Session) error {
	return fmt.Errorf("ErrorQueryService does not implement any method")
}

// Execute is part of QueryService interface
func (e *ErrorQueryService) Execute(ctx context.Context, target *querypb.Target, query *proto.Query, reply *sqltypes.Result) error {
	return fmt.Errorf("ErrorQueryService does not implement any method")
}

// StreamExecute is part of QueryService interface
func (e *ErrorQueryService) StreamExecute(ctx context.Context, target *querypb.Target, query *proto.Query, sendReply func(*sqltypes.Result) error) error {
	return fmt.Errorf("ErrorQueryService does not implement any method")
}

// ExecuteBatch is part of QueryService interface
func (e *ErrorQueryService) ExecuteBatch(ctx context.Context, target *querypb.Target, queryList *proto.QueryList, reply *proto.QueryResultList) error {
	return fmt.Errorf("ErrorQueryService does not implement any method")
}

// SplitQuery is part of QueryService interface
func (e *ErrorQueryService) SplitQuery(ctx context.Context, target *querypb.Target, req *proto.SplitQueryRequest, reply *proto.SplitQueryResult) error {
	return fmt.Errorf("ErrorQueryService does not implement any method")
}

// StreamHealthRegister is part of QueryService interface
func (e *ErrorQueryService) StreamHealthRegister(chan<- *querypb.StreamHealthResponse) (int, error) {
	return 0, fmt.Errorf("ErrorQueryService does not implement any method")
}

// StreamHealthUnregister is part of QueryService interface
func (e *ErrorQueryService) StreamHealthUnregister(int) error {
	return fmt.Errorf("ErrorQueryService does not implement any method")
}

// HandlePanic is part of QueryService interface
func (e *ErrorQueryService) HandlePanic(*error) {
}

// make sure ErrorQueryService implements QueryService
var _ QueryService = &ErrorQueryService{}


text:
package org.cloudfoundry.client.v3.builds;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.immutables.value.Value;

/**
 * The request payload for the Get Build operation
 */
@Value.Immutable
abstract class _GetBuildRequest {

    /**
     * The build id
     */
    @JsonIgnore
    abstract String getBuildId();

}


text:
sudo apt-get update
sudo apt-get -y install python-pip

sudo pip install boto
sudo pip install docopt

#${var.region} ${aws_vpc.main.id} ${var.base_iam_role_name} ${var.vpc_name} ${aws_security_group.infra_spinnaker.id} ${aws_security_group.vpc_sg.id} ${aws_security_group.mgmt_sg.id}

cd /tmp/terraform/
prefix=$8
key=`echo $prefix-key`
echo $key
sed -i "s/my-aws-account-keypair/$key/" pipeline_create.json
#/tmp/terraform/create_application_and_pipeline.py -a testappname -p testappnamepipeline -g sg-a6ebd8c2 -i vpc-cde4d4a8 -v sg-daebd8be -m sg-0ae8db6e -n vpc_DIFFNAME -r us-west-2 -o base_iam_role_testing_diff_name_profile

chmod a+x create_application_and_pipeline.py

/tmp/terraform/create_application_and_pipeline.py -a testappname -p testappnamepipeline -r $1 -i $2 -o $3 -n $4 -g $5 -v $6 -m $7


text:
(function() {
  'use strict';

  angular
    .module('app')
    .config(config);

  config.$inject = ['$compileProvider'];

  function config($compileProvider) {
    // Disable debug
    $compileProvider.debugInfoEnabled(false);
  }
})();


text:
DIR=`dirname $0`
cd "${DIR}" || exit 1
echo "Running previously failed tasks..."
./noop_tests.sh -j 'auto' -d -x -R $@


text:
package solace.script;
import solace.cmd.AbstractCommand;
import solace.cmd.Command;
import solace.game.Player;
import java.util.function.BiPredicate;

/**
 * Data model for scripted gameplay commands. Game play commands
 * handle basic actions such as getting items, movement, etc.
 * @author Ryan Sandor Richards
 */
public class ScriptedPlayCommand extends AbstractScriptedCommand {
  /**
   * Creates a new play command with the given names and run lamdba.
   * @param name Name of the command.
   * @param displayName The display name for the command.
   * @param runLambda Run lambda for the command.
   */
  public ScriptedPlayCommand(
    String name,
    String displayName,
    String[] aliases,
    BiPredicate<Player, String[]> runLambda
  ) {
    super(name, displayName, aliases, runLambda);
    setPriority(100);
  }

  /**
   * Creates an instance of the play command for use by the game engine.
   * @return The play command instance.
   */
  public Command getInstance() {
    AbstractCommand command = new AbstractCommand(
      getName(),
      getDisplayName(),
      getAliases()
    ) {
      public void run(Player p, String[] params) {
        getRunLambda().test(p, params);
      }
    };
    command.setPriority(getPriority());
    return command;
  }
}


text:
DROP TABLE IF EXISTS tblCustomReports;

CREATE table tblCustomReports (
    intCustomReportsID  INT NOT NULL AUTO_INCREMENT,
    strName		VARCHAR(30),
    strSQL		TEXT,
    intTypeID      	INT NOT NULL,
    strConfig		TEXT,
    strTemplateFile	VARCHAR(30),
    intMinLevel        	INT NOT NULL,
    intMaxLevel        	INT NOT NULL,
	PRIMARY KEY (intCustomReportsID),
	KEY index_strName (strName)
);


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2014 Evolveum
  ~
  ~ 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.
  -->
<user oid="c0c010c0-d34d-b33f-f00d-1111111111aa"
		xmlns='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
		xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
		xmlns:t='http://prism.evolveum.com/xml/ns/public/types-3'
		xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
		xmlns:xsd='http://www.w3.org/2001/XMLSchema'
		xmlns:piracy='http://midpoint.evolveum.com/xml/ns/samples/piracy'>
    <name>murray</name>
    <fullName>Murray</fullName>
    <givenName>Murray</givenName>
    <familyName>The Skull</familyName>

    <activation>
    	<administrativeStatus>enabled</administrativeStatus>
    </activation>
</user>


text:
package result

import (
	"context"

	configpb "github.com/GoogleCloudPlatform/testgrid/pb/config"
	statepb "github.com/GoogleCloudPlatform/testgrid/pb/state"
	statuspb "github.com/GoogleCloudPlatform/testgrid/pb/test_status"
)

const (
	// IgnoreRunning maps RUNNING to NO_RESULT
	IgnoreRunning = true
	// ShowRunning maps RUNNING to UNKNOWN
	ShowRunning = false
)

var (
	statusSeverity = map[statuspb.TestStatus]int{
		statuspb.TestStatus_NO_RESULT:         0,
		statuspb.TestStatus_BUILD_PASSED:      1,
		statuspb.TestStatus_PASS:              2,
		statuspb.TestStatus_PASS_WITH_SKIPS:   3,
		statuspb.TestStatus_PASS_WITH_ERRORS:  4,
		statuspb.TestStatus_RUNNING:           5,
		statuspb.TestStatus_CATEGORIZED_ABORT: 6,
		statuspb.TestStatus_UNKNOWN:           7,
		statuspb.TestStatus_CANCEL:            8,
		statuspb.TestStatus_BLOCKED:           9,
		statuspb.TestStatus_FLAKY:             10,
		statuspb.TestStatus_TOOL_FAIL:         11,
		statuspb.TestStatus_TIMED_OUT:         12,
		statuspb.TestStatus_CATEGORIZED_FAIL:  13,
		statuspb.TestStatus_BUILD_FAIL:        14,
		statuspb.TestStatus_FAIL:              15,
	}
)

// LTE returns if rowResult is less than or equal to compareTo.
func LTE(rowResult, compareTo statuspb.TestStatus) bool {
	return statusSeverity[rowResult] <= statusSeverity[compareTo]
}

// GTE returns if rowResult is greater than or equal to compareTo.
func GTE(rowResult, compareTo statuspb.TestStatus) bool {
	return statusSeverity[rowResult] >= statusSeverity[compareTo]
}

// Passing returns true if the test status is any passing status,
// including PASS_WITH_SKIPS, BUILD_PASSED, and more.
func Passing(rowResult statuspb.TestStatus) bool {
	return GTE(rowResult, statuspb.TestStatus_BUILD_PASSED) && LTE(rowResult, statuspb.TestStatus_PASS_WITH_ERRORS)
}

// Failing returns true if the test status is any failing status,
// including CATEGORIZED_FAILURE, BUILD_FAIL, and more.
func Failing(rowResult statuspb.TestStatus) bool {
	return GTE(rowResult, statuspb.TestStatus_TOOL_FAIL) && LTE(rowResult, statuspb.TestStatus_FAIL)
}

// Ignored returns true if the test status is any ignored status,
// configured via Config > DashboardTab > DashboardTabStatusCustomizationOptions > IgnoredTestStatuses
func Ignored(rowResult statuspb.TestStatus, opts *configpb.DashboardTabStatusCustomizationOptions) bool {
	for _, ignoredStatus := range opts.GetIgnoredTestStatuses() {
		if (ignoredStatus == configpb.DashboardTabStatusCustomizationOptions_CATEGORIZED_ABORT && rowResult == statuspb.TestStatus_CATEGORIZED_ABORT) ||
			(ignoredStatus == configpb.DashboardTabStatusCustomizationOptions_UNKNOWN && rowResult == statuspb.TestStatus_UNKNOWN) ||
			(ignoredStatus == configpb.DashboardTabStatusCustomizationOptions_CANCEL && rowResult == statuspb.TestStatus_CANCEL) ||
			(ignoredStatus == configpb.DashboardTabStatusCustomizationOptions_BLOCKED && rowResult == statuspb.TestStatus_BLOCKED) {
			return true
		}
	}
	return false
}

// Coalesce reduces the result to PASS, NO_RESULT, FAIL, FLAKY or UNKNOWN.
func Coalesce(result statuspb.TestStatus, ignoreRunning bool) statuspb.TestStatus {
	// TODO(fejta): other result types, not used by k8s testgrid
	if result == statuspb.TestStatus_NO_RESULT || result == statuspb.TestStatus_RUNNING && ignoreRunning {
		return statuspb.TestStatus_NO_RESULT
	}
	if result == statuspb.TestStatus_FLAKY {
		return result
	}
	if Failing(result) {
		return statuspb.TestStatus_FAIL
	}
	if Passing(result) {
		return statuspb.TestStatus_PASS
	}
	return statuspb.TestStatus_UNKNOWN
}

func iterSlow(ctx context.Context, results []int32) <-chan statuspb.TestStatus {
	out := make(chan statuspb.TestStatus)
	go func() {
		defer close(out)
		for i := 0; i+1 < len(results); i += 2 {
			select { // Non-blocking check to see if we're done
			case <-ctx.Done():
				return
			default:
			}
			result := statuspb.TestStatus(results[i])
			count := results[i+1]
			for count > 0 {
				select { // Non-blocking check to see if we're done
				case <-ctx.Done():
					return
				default:
				}
				select {
				case <-ctx.Done():
					return
				case out <- result:
					count--
				}
			}
		}
	}()
	return out
}

// Iter returns a function that returns the result for each column, decoding the run-length-encoding.
func Iter(results []int32) IterFunc {
	return iterFast(results)
}

func iterFast(results []int32) IterFunc {
	var i int
	n := len(results)
	var more int32
	var status statuspb.TestStatus
	return func() (statuspb.TestStatus, bool) {
		for {
			if more > 0 {
				more--
				return status, true
			}
			if i+1 >= n {
				return statuspb.TestStatus_NO_RESULT, false
			}
			status = statuspb.TestStatus(results[i])
			more = results[i+1]
			i += 2
		}
	}
}

// IterFunc returns a result for each column (and then !ok).
//
// This decodes the run-length-encoding for a row's results.
type IterFunc func() (result statuspb.TestStatus, ok bool)

// Map returns a per-column result output channel for each row.
func Map(rows []*statepb.Row) map[string]IterFunc {
	iters := map[string]IterFunc{}
	for _, r := range rows {
		iters[r.Name] = Iter(r.Results)
	}
	return iters
}


text:
define([
    "dijit/registry",
    "utils/NavListController",
    "utils/Hasher",
	"dojo/dom",
	"dojo/query",
	"dojo/dom-class",
	"dojo/dom-style",
], function (registry, NavListController, Hasher, dom, query, domClass, domStyle) {
    'use strict';

	var initialized = false;

	return {

		init: function (template) {

			if (initialized) {
				registry.byId("stackContainer").selectChild("dataView");
				return;
			}

			initialized = true;
			registry.byId("stackContainer").selectChild("dataView");
			registry.byId("dataView").set('content', template);

            var context = "data";
            NavListController.loadNavControl(context);
            NavListController.loadNavView(context);

            var divs = document.getElementsByTagName('input');
            for(var i=0; i < divs.length; i += 1) {
                divs[i].onclick = function(){
                    if(this.checked){
                        Hasher.setHash("s", this.id);
                    } else {
                        Hasher.removeKey("s");
                    }
                    //need to close all other checked boxes
                    //so only one can be open at a time.
                    for(var j=0; j<divs.length; j++){
                        if(divs[j] !== this){
                            divs[j].checked = false;
                        }
                    }
                };
            }

			this.initializeCountryDropdowns();
		},

		initializeCountryDropdowns: function () {

			var dropdowns = document.getElementsByClassName('source_download_container');
			var options = document.getElementsByClassName('source_dropdown_body');

			if(dropdowns.length > 0){
				[].map.call(dropdowns, function(dropdown) {
					dropdown.onchange = function(){
						[].map.call(options, function(option){
							if(option.value !== "none"){
								option.className = 'source_dropdown_body';
							}
						});
						var selectedValue = dropdown.options[dropdown.selectedIndex].value;
						if(selectedValue !== "none"){
							var countryInfo = document.getElementById(selectedValue)
							countryInfo.className = countryInfo.className + " active";
						}
					}
				});
			}
		}

	};

});