text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
define(["require", "exports", '../Subscriber'], function (require, exports, Subscriber_1) {
    /**
     * buffers a number of values from the source observable by `bufferSize` then emits the buffer and clears it, and starts a
     * new buffer each `startBufferEvery` values. If `startBufferEvery` is not provided or is `null`, then new buffers are
     * started immediately at the start of the source and when each buffer closes and is emitted.
     * @param {number} bufferSize the maximum size of the buffer emitted.
     * @param {number} [startBufferEvery] optional interval at which to start a new buffer. (e.g. if `startBufferEvery` is `2`,asdf then a
     *   new buffer will be started on every other value from the source.) A new buffer is started at the beginning of the source by default.
     * @returns {Observable<T[]>} an observable of arrays of buffered values.
     */
    function bufferCount(bufferSize, startBufferEvery) {
        if (startBufferEvery === void 0) { startBufferEvery = null; }
        return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
    }
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = bufferCount;
    var BufferCountOperator = (function () {
        function BufferCountOperator(bufferSize, startBufferEvery) {
            this.bufferSize = bufferSize;
            this.startBufferEvery = startBufferEvery;
        }
        BufferCountOperator.prototype.call = function (subscriber) {
            return new BufferCountSubscriber(subscriber, this.bufferSize, this.startBufferEvery);
        };
        return BufferCountOperator;
    })();
    var BufferCountSubscriber = (function (_super) {
        __extends(BufferCountSubscriber, _super);
        function BufferCountSubscriber(destination, bufferSize, startBufferEvery) {
            _super.call(this, destination);
            this.bufferSize = bufferSize;
            this.startBufferEvery = startBufferEvery;
            this.buffers = [[]];
            this.count = 0;
        }
        BufferCountSubscriber.prototype._next = function (value) {
            var count = (this.count += 1);
            var destination = this.destination;
            var bufferSize = this.bufferSize;
            var startBufferEvery = (this.startBufferEvery == null) ? bufferSize : this.startBufferEvery;
            var buffers = this.buffers;
            var len = buffers.length;
            var remove = -1;
            if (count % startBufferEvery === 0) {
                buffers.push([]);
            }
            for (var i = 0; i < len; i++) {
                var buffer = buffers[i];
                buffer.push(value);
                if (buffer.length === bufferSize) {
                    remove = i;
                    this.destination.next(buffer);
                }
            }
            if (remove !== -1) {
                buffers.splice(remove, 1);
            }
        };
        BufferCountSubscriber.prototype._error = function (err) {
            this.destination.error(err);
        };
        BufferCountSubscriber.prototype._complete = function () {
            var destination = this.destination;
            var buffers = this.buffers;
            while (buffers.length > 0) {
                var buffer = buffers.shift();
                if (buffer.length > 0) {
                    destination.next(buffer);
                }
            }
            destination.complete();
        };
        return BufferCountSubscriber;
    })(Subscriber_1.default);
});
//# sourceMappingURL=bufferCount.js.map


text:
<?xml version="1.0" encoding="utf-8" ?>
<INTERACTIONS>
<INTERACTION>
<SOURCE>
<CLINICAL_SOURCE>ANSM</CLINICAL_SOURCE>
<SOURCE_FILE>4-ACETOHYDROXAMIC-ACID.html
</SOURCE_FILE>
</SOURCE>
<DRUG1>
<DRUG name="ACETOHYDROXAMIC ACID" rxcui="16728">
<ATC code="G04BX03" />
</DRUG>
</DRUG1>
<DRUG2>
<DRUG name="IRON" rxcui="90176">
<ATC code="B03A" />
</DRUG>
</DRUG2>
<DESCRIPTION>Decrease of the digestive absorption of these two medications due to chelation of the iron</DESCRIPTION>
<SEVERITY>Take into account</SEVERITY>
</INTERACTION>
</INTERACTIONS>

redpajama_set_name: RedPajamaGithub


text:
<?php
declare(strict_types=1);

namespace Crossjoin\Browscap\PropertyFilter;

/**
 * Class PropertyAbstract
 *
 * @package Crossjoin\Browscap\PropertyFilter
 * @author Christoph Ziegenberg <ziegenberg@crossjoin.com>
 * @link https://github.com/crossjoin/browscap
 */
abstract class PropertyAbstract implements PropertyFilterInterface
{
    /**
     * @var array
     */
    protected $properties = [];

    /**
     * Allowed constructor.
     *
     * @param array $properties
     */
    public function __construct(array $properties = [])
    {
        $this->setProperties($properties);
    }

    /**
     * @return array
     */
    public function getProperties() : array
    {
        return $this->properties;
    }

    /**
     * @param array $properties
     *
     * @return PropertyAbstract
     */
    public function setProperties(array $properties) : self
    {
        $this->properties = [];

        foreach ($properties as $property) {
            $this->addProperty($property);
        }

        return $this;
    }

    /**
     * @param string $property
     *
     * @return PropertyAbstract
     */
    public function addProperty(string $property) : self
    {
        $property = strtolower($property);
        if (!in_array($property, $this->properties, true)) {
            $this->properties[] = $property;
        }

        return $this;
    }
}


text:
import React from "react"
import { observer } from "mobx-react"
import { action, observable, runInAction } from "mobx"

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome/index.js"
import { faCheckCircle } from "@fortawesome/free-solid-svg-icons/faCheckCircle"

import { AdminLayout } from "./AdminLayout.js"
import { AdminAppContext, AdminAppContextType } from "./AdminAppContext.js"
import { Deploy, DeployStatus } from "@ourworldindata/utils"
import { Timeago } from "./Forms.js"

const statusLabel: Record<DeployStatus, string> = {
    [DeployStatus.queued]: "Next up",
    [DeployStatus.pending]: "Deploying",
}

@observer
export class DeployStatusPage extends React.Component {
    static contextType = AdminAppContext
    context!: AdminAppContextType

    @observable deploys: Deploy[] = []
    @observable canManuallyDeploy = true

    render() {
        return (
            <AdminLayout title="Deploys">

Deploy status

                        <button
                            className="btn btn-secondary"
                            type="button"
                            disabled={!this.canManuallyDeploy}
                            onClick={async () => {
                                this.canManuallyDeploy = false
                                await this.triggerDeploy()
                                await this.getData()
                            }}
                        >
                            Manually enqueue a deploy
                        </button>

                    {this.deploys.length > 0 ? (

                                    Status
                                    Note
                                    Author
                                    Time

                                {this.deploys.map((deploy) =>
                                    deploy.changes.map((change, i) => (
                                        <tr key={`${deploy.status}-${i}`}>
                                            <td
                                                className={`cell-status cell-status--${deploy.status}`}
                                            >
                                                {statusLabel[deploy.status]}

                                                {change.message}

                                                {change.authorName}

                                                <Timeago
                                                    time={change.timeISOString}
                                                />

                                    ))
                                )}

                    ) : (

                                    <FontAwesomeIcon icon={faCheckCircle} />
                                {" "}
                                All changes are successfully deployed.

                    )}

                        Past deploys can be found in the{" "}

                            owid-static GitHub repository

                        .

            </AdminLayout>
        )
    }

    @action.bound async triggerDeploy() {
        const { admin } = this.context
        await admin.rawRequest("/api/deploy", undefined, "PUT")
    }

    async getData() {
        const { admin } = this.context
        if (admin.currentRequests.length > 0) return

        const json = (await admin.getJSON("/api/deploys.json")) as {
            deploys: Deploy[]
        }
        runInAction(() => {
            this.deploys = json.deploys
        })
    }

    componentDidMount() {
        this.getData()
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="vendor/styles/bootstrap.min.css">
    <link rel="stylesheet" href="styles/main.css">
    <link rel="stylesheet" href="styles/_results.css">
    <link rel="stylesheet" href="styles/_results_right.css">

            Recruit App

    <new-candidate-modal></new-candidate-modal>


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE TupleSections     #-}

module Phaedrus.Evidence
    ( readEvidence
    , tagEvidence
    , makeTrainingSet
    , getEvidenceFile
    ) where

import           Control.Applicative
import           Control.Error
import           Control.Monad
import qualified Data.ByteString.Lazy      as BS
import           Data.Csv
import qualified Data.HashSet              as S
import qualified Data.List                 as L
import qualified Data.Text                 as T
import qualified Data.Vector               as V
import           Filesystem
import           Filesystem.Path.CurrentOS hiding (decode)
import           Prelude                   hiding (FilePath, readFile)

import           Phaedrus.Types
import           Phaedrus.Utils

readEvidence :: FilePath -> IO (Either String EvidenceSet)
readEvidence fp =   fmap (S.fromList . V.toList)
                .   decode NoHeader
                .   BS.fromStrict
                <$> readFile fp

tagEvidence :: EvidenceSet -> [TextLoc] -> [TextLoc]
tagEvidence eset = map (flipEvidence eset)

textLocEvidence :: TextLoc -> EvidencePoint
textLocEvidence TextLoc{..} = Evidence (toBeta _tlTitle) _tlSection

isEvidence :: EvidenceSet -> TextLoc -> Bool
isEvidence eset = (`S.member` eset) . textLocEvidence

flipEvidence :: EvidenceSet -> TextLoc -> TextLoc
flipEvidence eset tl = tl { _tlEvidence = isEvidence eset tl }

instance FromRecord EvidencePoint where
    parseRecord v
        | V.length v == 2 =   Evidence
                          <$> fmap (toBeta . T.strip) (v .! 0)
                          <*> fmap T.strip (v .! 1)
        | otherwise       = mzero

makeTrainingSet :: Int -> Double -> (a -> Bool) -> [a] -> IO ([a], [a])
makeTrainingSet size ratio p xs = do
    ts <- take targetTsize <$> shuffle ts'
    let targetSize = min size $ backr ratio ts
        fsize      = targetSize - length ts
    (ts,) . take fsize <$> shuffle fs'
    where (ts', fs')  = L.partition p xs
          targetTsize = rationl ratio xs

          rationl :: Double -> [a] -> Int
          rationl r = truncate . (* r) . fromIntegral . length
          backr :: Double -> [a] -> Int
          backr r = truncate . (/ r) . fromIntegral . length

getEvidenceFile :: Maybe FilePath -> Phaedrus (Maybe EvidenceSet)
getEvidenceFile Nothing = putStrLn' "No evidence file. Skipping." >> return Nothing
getEvidenceFile (Just ef) = fmap Just . Phaedrus . EitherT $ readEvidence ef


text:
+++
author = "André Lucas"
categories = ["Desenvolvimento Web"]
date = "2018-01-31T11:56:57-03:00"
disqus = false
hugo_image = "images/uploads/2017/05/02/roadmap_webdevelopment_2017.jpg"
tags = ["roadmap", "programação", "currículo", "desenvolvimento de websites", "2018"]
title = "Como se tornar um desenvolvedor web em 2018"
url = "/como-se-tornar-um-desenvolvedor-web-em-2018/"
youtube = ""

+++
Como se tornar um desenvolvedor web em 2018 é uma pergunta cada vez mais complicada de responder. De um lado temos a universidade e os cursos da ciência da computação, de outro os autodidatas que se aventuram online para aprender esse ofício.

Nesse artigo trago tanto minha experiência quanto recursos de outras pesquisas para ajudar a responder essa questão. Me inspirei muito no artigo de Kamran Ahmed e também do vídeo do Leancode.academy. Também trouxe algumas de minhas experiências dos últimos 6 anos na área para tentar deixar mais claro o caminho que alguém hoje tem que passar para ser um desenvolvedor web.

Muitas pessoas quando veem gráficos iguais aos que vou adicionar abaixo ficam meio confusas ou mesmo achando que é algo excessivo. Contudo, gostaria que olhasse como um currículo para um curso de desenvolvimento de websites. Explico na primeira parte aqui sobre o por quê das universidades não serem uma boa alternativa e da necessidade de guias como esse para orientar autodidatas.

## Por que a universidade não é uma opção

Eu me formei em Relações Internacionais e logo em seguida entrei para a faculdade de Ciência da Computação. Apesar de adorar os conteúdos e ter notas excelentes eu não durei mai de 8 meses nesse novo curso e vou explicar um pouco as razões por trás disso.

### Nenhum curso consegue acompanhar

Todo curso de uma universidade precisa de muito planejamento, organização de professores e dependência de questões legais para que seus currículos sejam estruturados. Se por um lado isso é bom para garantir uma formação respaldada por instituições reguladoras, é impraticável para uma área como a do desenvolvimento web.

Vamos pensar o seguinte. Um curso normalmente tem 4 anos. Quando você entra para a faculdade já sabe quais serão as disciplinas possíveis de serem cursadas e tem uma ideia do que irá aprender. Contudo, um website que criei há 4 anos atrás com as tecnologias mais avançadas e atuais daquela época hoje está completamente atrasado e de difícil manutenção.

A velocidade com que a área de desenvolvimento web cresce e se modifica hoje é imensa e se alguém entrasse numa universidade hoje - mesmo com um currículo 100% atualizado -, entraria em um mercado com déficit de conhecimento nas tecnologias mais atuais.

### Conceitos amplos

Todo curso universitário é mais abrangente do que o ofício em si. Isso é algo muito bom pois faz os alunos aprenderem mais sobre o mundo, áreas adjacentes e também metodologias de pesquisa.

Ao mesmo tempo, em geral falta um aprofundamento naquilo que define o sucesso de um programador -> "capacidade de se virar".

Por mais que ter tudo mastigado por um professor seja bom para o aprendizado, um bom desenvolvedor web terá que saber pesquisar por soluções e novos aprendizados sozinho. Essa habilidade não é muito incentivada em uma boa parte das universidades. Naturalmente estou falando aqui do meu ponto de vista, minhas experiências e minhas pesquisas com outras pessoas.

**Se a sua experiência for diferente, não deixe de comentar aqui no artigo e contar**.

### Não existe curso universitário de desenvolvimento web

Até onde eu saiba e consegui pesquisar não existe uma faculdade de desenvolvimento de webistes. Os cursos da ciência da computação são voltados para o desenvolvimento de softwares e, na maior parte dos casos, foca em linguagens como Java para ensinarem seus alunos a lógica da programação.

Não há problema nenhum nisso. Inclusive é possível usar Java em aplicações web. Mas essa é só a ponta do iceberg e é uma ponta que não está apontando para o futuro da web.

Existem disciplinas voltadas para a web, mas no final das contas aprendemo somente o básico de HTML, CSS e JavaScript.

O ambiente de desenvolvimento de websites é muito diferente do de softwares tradicionais e mesmo que a lógica da programação seja a mesma, é ainda um caminho um tanto quanto longo para sair de um para o outro.

Eu acho que o papel da universidade é muito importante, mas para quem quer se tornar um desenvolvedor web talvez o caminho autodidata seja mais apropriado.

## O caminho autodidata

Então se a universidade não serve, ser autodidata vai ser mais fácil? Não necessariamente, mas talvez mais rápido.

Indo direto ao ponto, se você buscar aprender sozinho como ser um desenvolvedor web estará mais focado no que realmente importa e poderá se desenvolver no ofício com mais agilidade.

Deixo claro que estou focando apenas nas habilidades necessárias para ser um bom programador de websites e não um bom profissional. Ser um bom profissional envolve muitas outras habilidades adjacentes como trabalhar em grupo, saber lidar com relações interpessoais, dedicação, se importar com o trabalho, etc. Algumas dessas habilidades podem ser desenvolvidas nas universidades, mas no final das contas são elementos que cada um de nós precisa buscar, ser humilde e se abrir para eles.

### A vantagem do caminho autodidata

Ser autodidata não é uma condição nata do ser humano. É uma habilidade que, mesmo que alguns tenham mais facilidade, pode ser aprendida e aperfeiçoada por qualquer um.

Como toda habilidade, ela exige muita dedicação e treino. Mas o retorno é incrivelmente vantajoso. Quando você é autodidata - principalmente nessa geração que estamos com o acesso à praticamente qualquer informação online - pode aprender inúmeros ofícios sem precisar de investimentos grandes.

Ao invés de pagar mil reais em uma mensalidade de um curso presencial, você pode pagar 100 ou mesmo não pagar nada e ter acesso aos conhecimentos. Muitas universidades já gravam seus cursos e disponibilizam online gratuitamente e existem outras empresas especializadas que possuem seus próprios cursos.

Aliando essa capacidade de aprender sozinho com um caminho claro do que deve estudar, temos um desenvolvimento focado, objetivo e rápido do (no nosso caso) desenvolvimento web.

### O desafio do caminho autodidata

Pensando no meu próprio caminho de aprendizado autodidata, os dois maiores desafios são:

1. Persistência/disciplina
2. Saber o que aprender

A parte da disciplina eu posso ajudar com alguns desses artigos aqui no blog:

* 8 Dicas para ser mais produtivo
* Como estruturar seu negócio como Freelancer
* Você não é sua produtividade. Diminua a velocidade

Porém, disciplina e persistência é uma luta diária contra a procrastinação. A internet é um mar de possibilidades para distrair a cabeça, então aprender algumas técnicas de foco e bloqueio de distrações pode ajudar muito aqui.

Já com relação ao que aprender é que esse artigo irá ser mais útil. Quando eu comecei a fazer websites eu não tinha ideia de por onde começar. Fui até o YouTube para ver alguns cursos, li artigos, [fiz cursos online no Lynda, Udemy e outros](https://www.igluonline.com/infoprodutos-e-cursos-online/) e até participei de fóruns para fazer perguntas.

Mesmo assim a cada novo conteúdo que eu assistia ou lia vinham 10 novos impedimentos. Quando digo impedimento me refiro a algum tipo de conceito, conhecimento ou habilidade que eu ainda não tinha e precisava me aprofundar mais.

Por exemplo, quando criei meu primeiro "Hello World" eu resolvi subir para um servidor que adquiri, mas rapidamente me deparei com o conceito de DNS e fiquei totalmente perdido. Deixei meu código de lado e fui estudar sobre como direcionar o domínio que tinha comprado para meu servidor e somente então conseguir visualizar meu programa no navegador.

É nesse ponto em específico que abaixo juntei várias fontes na criação de um diagrama de caminhos que podemos seguir para tornarmos desenvolvedores web. Passo por conceitos que precisamos aprende numa ordem que faz mais sentido do que simplesmente igual eu fiz: "na raça".

## Como se tornar um desenvolvedor web em 2018

Vamos então aos caminhos! Dividi aqui em 4 seções e cada uma também tem suas divisões. Podemos então dividir o aprendizado do desenvolvimento web nas seguintes categorias:

1. Básico para qualquer caminho
2. Front-end
3. Back-end
4. DevOps

### Legenda

Nas imagens abaixo as cores significam o seguinte:

* Azul: Os caminhos principais
* Vermelho: Os conhecimentos e conceitos recomendados
* Rosa: As opções dentro dos conceitos
* Amarelo: Os conhecimentos e conceitos facultativos
* Estrela: Minha recomendação pessoal

**O diagrama completo pode ser acessado por esse link.**

### 1- Básico para qualquer caminho

Independentemente de qual área você quer se especializar, existem alguns conceitos e conhecimentos que todos precisamos saber.

![](images/uploads/2018/02/28/como_ser_desenvolvedor_basico.jpg)

### 2- Front-end

O caminho do Front-end é para quem quer mexer com o layout e a parte visual do site. Profissionais front-end lidam com a criação de estruturas em HTML, CSS e JavaScript.

Tradicionalmente esse era um papel bem mais operacional e manual do que lógico e intelectual, mas atualmente a história mudou e quem trabalha com a parte da frente também está responsável pela lógica e funcionalidades dos sites e aplicações web.

#### Front-end básico

#### Front-end intermediário

Front-end avançado

### 3- Back-end

O caminho do Back-end é para aqueles que gostam de criar funcionalidades, lógica de programação, banco de dados e a estrutura dos sites e aplicativos. Quem lida com essa área normalmente precisa de um aprofundamento maior nos conceitos e funcionalidades de das linguagens escolhidas para se programar.

Aqui temos uma variedade maior de opções pois podemos escolher entre diversos tipos de linguagens para programar. No cado do Front-end os navegadores apenas entendem HTML, CSS e JavaScript, mas no servidor - onde o código do back-end roda - uma infinidade de linguagens podem não só existir mas co-existir.

Back-end básico

Primeiro temos os conceitos e conhecimentos mais básicos.

Em seguida a escolha da linguagem de programação. Nessa primeira imagem temos as linguagens compiladas e funcionais.

Agora dentro das linguagens de script. Também conhecidas como de alto nível. Na primeira imagem Node.js e Ruby.

E para finalizar Python e PHP.

Back-end intermediário

Back-end avançado

### 4- DevOps

O nome DevOps vem de desenvolvimento e operações. Quem quer entrar nesse ramo é interessante chegar até o nível intermediário do Back-end pois muitos dos conhecimentos são comuns e irão ajudar muito no processo.

DevOps é uma área mais complexa e voltada para a configuração dos servidores e ambientes de desenvolvimento para receber e escalar aplicações online. Se você consegue abrir um site como o Facebook em alta velocidade, uma boa parcela da responsabilidade é de quem fez a configuração dos clusters de máquinas para receber tantos usuários de uma só vez.

Os conhecimentos aqui são muito técnicos e é preciso que os fundamentos estejam muito claros.

DevOps básico

![](images/uploads/2017/05/02/devops_basico.jpg)

DevOps intermediário

Aqui eu já não possuo muitas opiniões ou conhecimento, então aproveitei de recursos externos para construir esse diagrama.

![](images/uploads/2017/05/02/devops_intermediario.jpg)

DevOps avançado

A partir daqui não tenho conhecimento nem para construir o diagrama. Essa área fica um tanto quanto "cabeluda" nos níveis mais próximos da máquina para que as otimizações de sistemas sejam adequadas.

## Conclusão

Acho que vale a pena reforças que esses diagramas servem como aqueles currículos ou planos de disciplinas nas universidades. São muitos conceitos e muitas matérias, mas é como se fossem o curso inteiro.

Alguns itens são bem simples, outros necessitam de muitas horas, dias e até meses para serem compreendidos completamente. Além disso, **é importante dizer que nem tudo precisa ser entendido perfeitamente**. Exatamente por isso que dividi entre básico, intermediário e avançado.

Como básico já é possível criar websites e aplicações, mas quanto mais aprofundar, melhor e mais eficiente o código será. No básico você vai fazer uma funcionalidade com, por exemplo, 100 linhas de código. No avançado pode ser que consiga o mesmo resultado com 10.

Espero que tenha gostado e que sirva de inspiração e guia para seu aprendizado.

Divirta-se!


text:
package org.apache.camel.component.thrift;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;

import org.apache.camel.CamelContext;
import org.apache.camel.component.thrift.client.AsyncClientMethodCallback;
import org.apache.camel.support.ObjectHelper;
import org.apache.camel.util.ReflectionHelper;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.async.TAsyncClientManager;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TZlibTransport;

/**
 * ThriftUtils helpers are working with dynamic methods via Camel and Java
 * reflection utilities
 */
public final class ThriftUtils {

    private ThriftUtils() {
    }

    public static String extractServiceName(String service) {
        return service.substring(service.lastIndexOf(".") + 1);
    }

    public static String extractServicePackage(String service) {
        return service.substring(0, service.lastIndexOf("."));
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static Object constructClientInstance(String packageName, String serviceName, TTransport transport, ThriftExchangeProtocol exchangeProtocol,
                                                 final ThriftNegotiationType negotiationType, final ThriftCompressionType compressionType, final CamelContext context) {
        Object clientInstance = null;
        Class[] constructorParamTypes = {TProtocol.class};
        Object[] constructorParamValues = {constructSyncProtocol(transport, exchangeProtocol, negotiationType, compressionType)};

        String clientClassName = packageName + "." + serviceName + "$" + ThriftConstants.THRIFT_SYNC_CLIENT_CLASS_NAME;
        try {
            Class clientClass = context.getClassResolver().resolveMandatoryClass(clientClassName);
            Constructor clientConstructor = clientClass.getConstructor(constructorParamTypes);
            clientInstance = clientConstructor.newInstance(constructorParamValues);

        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Thrift client class not found: " + clientClassName);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Thrift client class constructor not found: " + clientClassName);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | SecurityException e) {
            throw new IllegalArgumentException(e);
        }
        return clientInstance;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static Object constructAsyncClientInstance(String packageName, String serviceName, TNonblockingTransport transport, ThriftExchangeProtocol exchangeProtocol, final CamelContext context) {
        Object asynClientInstance = null;
        Class[] getterParamTypes = {TNonblockingTransport.class};
        Class[] constructorParamTypes = {TAsyncClientManager.class, TProtocolFactory.class};

        String clientClassName = packageName + "." + serviceName + "$" + ThriftConstants.THRIFT_ASYNC_CLIENT_CLASS_NAME + "$" + ThriftConstants.THRIFT_ASYNC_CLIENT_FACTORY_NAME;
        try {
            Class clientClass = context.getClassResolver().resolveMandatoryClass(clientClassName);
            Constructor factoryConstructor = clientClass.getConstructor(constructorParamTypes);
            Object factoryInstance = factoryConstructor.newInstance(new TAsyncClientManager(), constructAsyncProtocol(exchangeProtocol));
            Method asyncClientGetter = ReflectionHelper.findMethod(clientClass, ThriftConstants.THRIFT_ASYNC_CLIENT_GETTER_NAME, getterParamTypes);
            if (asyncClientGetter == null) {
                throw new IllegalArgumentException("Thrift async client getter not found: " + clientClassName + "." + ThriftConstants.THRIFT_ASYNC_CLIENT_GETTER_NAME);
            }
            asynClientInstance = ObjectHelper.invokeMethod(asyncClientGetter, factoryInstance, transport);

        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Thrift sync client class not found: " + clientClassName);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Thrift sync client factory class not found: " + clientClassName);
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | IOException | SecurityException e) {
            throw new IllegalArgumentException(e);
        }
        return asynClientInstance;
    }

    @SuppressWarnings({"rawtypes"})
    public static Object invokeSyncMethod(Object syncClient, String invokeMethod, Object request) {
        Object[] params = convertObjects2Primitives(request, null);
        Class[] paramsTypes = (Class[])params[0];
        Object[] paramsValues = (Object[])params[1];

        Method method = ReflectionHelper.findMethod(syncClient.getClass(), invokeMethod, paramsTypes);
        if (method == null) {
            throw new IllegalArgumentException("Thrift service client method not found: " + syncClient.getClass().getName() + "." + invokeMethod + printParamsTypes(paramsTypes));
        }
        Object result = ObjectHelper.invokeMethod(method, syncClient, paramsValues);
        return result;
    }

    @SuppressWarnings({"rawtypes"})
    public static void invokeAsyncMethod(Object asyncClient, String invokeMethod, Object request, AsyncClientMethodCallback methodCallback) {
        Object[] params = convertObjects2Primitives(request, methodCallback);
        Class[] paramsTypes = (Class[])params[0];
        Object[] paramsValues = (Object[])params[1];

        Method method = ReflectionHelper.findMethod(asyncClient.getClass(), invokeMethod, paramsTypes);
        if (method == null) {
            throw new IllegalArgumentException("Thrift service client method not found: " + asyncClient.getClass().getName() + "." + invokeMethod + printParamsTypes(paramsTypes));
        }
        ObjectHelper.invokeMethod(method, asyncClient, paramsValues);
    }

    @SuppressWarnings("rawtypes")
    public static Class getServerInterface(String packageName, String serviceName, boolean isSyncInterface, final CamelContext context) {
        String serverInterfaceName = null;
        Class serverInterface = null;

        try {
            if (isSyncInterface) {
                serverInterfaceName = packageName + "." + serviceName + "$" + ThriftConstants.THRIFT_SERVER_SYNC_INTERFACE_NAME;
            } else {
                serverInterfaceName = packageName + "." + serviceName + "$" + ThriftConstants.THRIFT_SERVER_ASYNC_INTERFACE_NAME;
            }
            serverInterface = context.getClassResolver().resolveMandatoryClass(serverInterfaceName);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Unable to find server interface implementation for: " + serverInterfaceName);
        }
        return serverInterface;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static Object constructServerProcessor(String packageName, String serviceName, Object serverImplementation, boolean isSyncProcessor, final CamelContext context) {
        String processorClassName = null;
        Class serverInterface = null;
        Object processorInstance = null;

        try {
            if (isSyncProcessor) {
                processorClassName = packageName + "." + serviceName + "$" + ThriftConstants.THRIFT_SERVER_SYNC_PROCESSOR_CLASS;
                serverInterface = getServerInterface(packageName, serviceName, isSyncProcessor, context);
            } else {
                processorClassName = packageName + "." + serviceName + "$" + ThriftConstants.THRIFT_SERVER_ASYNC_PROCESSOR_CLASS;
                serverInterface = getServerInterface(packageName, serviceName, isSyncProcessor, context);
            }
            Class processorClass = context.getClassResolver().resolveMandatoryClass(processorClassName);
            Constructor procesorConstructor = processorClass.getConstructor(new Class[] {serverInterface});
            processorInstance = procesorConstructor.newInstance(serverImplementation);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Unable to find server processor for: " + processorClassName);
        } catch (NoSuchMethodException | SecurityException e) {
            throw new IllegalArgumentException("Processor class instance not found for: " + processorClassName);
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new IllegalArgumentException(e);
        }
        return processorInstance;
    }

    private static TProtocol constructSyncProtocol(TTransport transport, ThriftExchangeProtocol exchangeProtocol,
                                                   final ThriftNegotiationType negotiationType, final ThriftCompressionType compressionType) {
        if (negotiationType == ThriftNegotiationType.SSL) {
            // If negotiation passed over SSL/TLS the only binary transport is supported
            return new TBinaryProtocol(transport);
        } else if (compressionType == ThriftCompressionType.ZLIB) {
            return new TBinaryProtocol(new TZlibTransport(transport));
        } else {
            switch (exchangeProtocol) {
            case BINARY:
                return new TBinaryProtocol(new TFramedTransport(transport));
            case JSON:
                return new TJSONProtocol(new TFramedTransport(transport));
            case SJSON:
                return new TSimpleJSONProtocol(new TFramedTransport(transport));
            case COMPACT:
                return new TCompactProtocol(new TFramedTransport(transport));
            default:
                throw new IllegalArgumentException("Exchange protocol " + exchangeProtocol + " not implemented");
            }
        }
    }

    private static TProtocolFactory constructAsyncProtocol(ThriftExchangeProtocol exchangeProtocol) {
        switch (exchangeProtocol) {
        case BINARY:
            return new TBinaryProtocol.Factory();
        case JSON:
            return new TJSONProtocol.Factory();
        case SJSON:
            return new TSimpleJSONProtocol.Factory();
        case COMPACT:
            return new TCompactProtocol.Factory();
        default:
            throw new IllegalArgumentException("Exchange protocol " + exchangeProtocol + " not implemented");
        }
    }

    /**
     * The function find onComplete method inside interface implementation and
     * get fist parameter (but not Object.class) as return type
     */
    @SuppressWarnings("rawtypes")
    public static Class findMethodReturnType(Class clazz, String name) {
        for (Method method : clazz.getMethods()) {
            if (name.equals(method.getName()) && !method.getParameterTypes()[0].equals(Object.class)) {
                return method.getParameterTypes()[0];
            }
        }
        return null;
    }

    @SuppressWarnings("rawtypes")
    private static String printParamsTypes(Class[] paramsTypes) {
        StringJoiner joiner = new StringJoiner(",");
        for (Class paramType : paramsTypes) {
            joiner.add(paramType == null ? "null" : paramType.getName());
        }
        return "(" + joiner.toString() + ")";
    }

    /**
     * The function transforms objects types stored as list or simple object
     * inside the Body to the primitives objects to find appropriate method
     */
    @SuppressWarnings({"rawtypes"})
    private static Object[] convertObjects2Primitives(Object request, AsyncClientMethodCallback methodCallback) {
        Class[] paramsTypes = null;
        Object[] paramsValues = null;
        int paramListSize = 1;
        if (request instanceof List) {
            List paramList = (List)request;
            paramListSize = paramList.size() + (methodCallback == null ? 0 : 1);
            paramsTypes = new Class[paramListSize];
            paramsValues = new Object[paramListSize];
            int idx = 0;

            for (Object param : paramList) {
                if (param instanceof Short) {
                    paramsTypes[idx] = short.class;
                } else if (param instanceof Long) {
                    paramsTypes[idx] = long.class;
                } else if (param instanceof Integer) {
                    paramsTypes[idx] = int.class;
                } else if (param instanceof Double) {
                    paramsTypes[idx] = double.class;
                } else if (param instanceof Byte) {
                    paramsTypes[idx] = byte.class;
                } else if (param instanceof Boolean) {
                    paramsTypes[idx] = boolean.class;
                } else if (param instanceof List) {
                    paramsTypes[idx] = List.class;
                } else if (param instanceof Set) {
                    paramsTypes[idx] = Set.class;
                } else if (param instanceof Map) {
                    paramsTypes[idx] = Map.class;
                } else if (param instanceof ByteBuffer) {
                    paramsTypes[idx] = ByteBuffer.class;
                } else {
                    paramsTypes[idx] = param.getClass();
                }
                paramsValues[idx] = param;
                idx++;
            }
        } else if (request != null) {
            paramListSize = methodCallback == null ? 1 : 2;
            paramsTypes = new Class[paramListSize];
            paramsValues = new Object[paramListSize];
            paramsTypes[0] = request.getClass();
            paramsValues[0] = request;
        } else {
            paramListSize = methodCallback == null ? 0 : 1;
            paramsTypes = new Class[paramListSize];
            paramsValues = new Object[paramListSize];
        }
        if (methodCallback != null) {
            paramsTypes[paramListSize - 1] = AsyncMethodCallback.class;
            paramsValues[paramListSize - 1] = methodCallback;
        }
        return new Object[] {paramsTypes, paramsValues};
    }
}


text:
from aminiaio import app
from aminiaio import login
from flask import redirect, request, flash
from flask.ext.login import current_user, login_user

@app.route('/newaccount', methods=['POST'])
def newaccount():
	if current_user.is_authenticated():
		abort(404)

	username = request.form.get('username', '')
	password = request.form.get('password', '')
	invalidCredentials = False

	if not login.usernameValid(username):
		invalidCredentials = True
		flash('Invalid username. ' + login.usernameDescription(), 'alert-danger')

	if not login.passwordValid(password):
		invalidCredentials = True
		flash('Invalid password. ' + login.passwordDescription(), 'alert-danger')

	if not invalidCredentials:
		user = login.create(username, password)
		if user is None:
			flash('Username is already in use.  Please log in or choose a different username.', 'alert-warning')
		else:
			login_user(user)
			flash('Account created successfully.  Welcome %s!' % user.name(), 'alert-success')

	return redirect('/')


text:
require "formula"

# Note that x.even are stable releases, x.odd are devel releases
class Node < Formula
  homepage "http://nodejs.org/"
  url "http://nodejs.org/dist/v0.10.29/node-v0.10.29.tar.gz"
  sha1 "0d5dc62090404f7c903f29779295758935529242"

  bottle do
    sha1 "e90cc43c18f9ff8191d6602e042aa14b33da37a1" => :mavericks
    sha1 "42014487797e67983672e933ed14488ee24d7b1f" => :mountain_lion
    sha1 "128fa1edbefb09ac634af404e1822996423232f0" => :lion
  end

  devel do
    url "http://nodejs.org/dist/v0.11.13/node-v0.11.13.tar.gz"
    sha1 "da4a9adb73978710566f643241b2c05fb8a97574"
  end

  head "https://github.com/joyent/node.git"

  option "enable-debug", "Build with debugger hooks"
  option "without-npm", "npm will not be installed"
  option "without-completion", "npm bash completion will not be installed"

  depends_on :python => :build

  fails_with :llvm do
    build 2326
  end

  resource "npm" do
    url "http://registry.npmjs.org/npm/-/npm-1.4.9.tgz"
    sha1 "29094f675dad69fc5ea24960a81c7abbfca5ce01"
  end

  def install
    args = %W{--prefix=#{prefix} --without-npm}
    args << "--debug" if build.include? "enable-debug"

    system "./configure", *args
    system "make", "install"

    resource("npm").stage libexec/"npm" if build.with? "npm"
  end

  def post_install
    return if build.without? "npm"

    node_modules = HOMEBREW_PREFIX/"lib/node_modules"
    node_modules.mkpath
    cp_r libexec/"npm", node_modules

    npm_root = node_modules/"npm"
    npmrc = npm_root/"npmrc"
    npmrc.atomic_write("prefix = #{HOMEBREW_PREFIX}\n")

    npm_root.cd { system "make", "install" }
    system "#{HOMEBREW_PREFIX}/bin/npm", "update", "npm", "-g",
                                         "--prefix", HOMEBREW_PREFIX

    Pathname.glob(npm_root/"man/*") do |man|
      man.children.each do |file|
        ln_sf file, "#{HOMEBREW_PREFIX}/share/man/#{man.basename}"
      end
    end

    if build.with? "completion"
      bash_completion.install_symlink \
        npm_root/"lib/utils/completion.sh" => "npm"
    end
  end

  def caveats
    if build.without? "npm"; <<-end.undent
      Homebrew has NOT installed npm. If you later install it, you should supplement
      your NODE_PATH with the npm module folder:
        #{HOMEBREW_PREFIX}/lib/node_modules
      end
    end
  end

  test do
    path = testpath/"test.js"
    path.write "console.log('hello');"

    output = `#{bin}/node #{path}`.strip
    assert_equal "hello", output
    assert_equal 0, $?.exitstatus

    system "#{HOMEBREW_PREFIX}/bin/npm", "install", "npm" if build.with? "npm"
  end
end


text:
MugenRoleCollectionsController = MeteorisController.extend({
    /* get subscribtion from server with parameter criteria, and sort/limit */
    subscriptions: function() {
        var sort = MeteorisGridView.getSorting();
        sort.limit = this.limit();

        this.subscription = this.subs.subscribe('mugenRoleCollections', this.getCriteria(), sort);
    },
    /* event searching data by user input with parameter */
    search: function(t) {
        Router.go('mugenRoleCollectionsIndex', {limit: this.limit()}, {query: "q=" + t.find('#search').value});
    },
    /* @override getCriteria */
    getCriteria: function() {
        var search = this.params.query.q ? this.params.query.q : "";
        return {
            $or: [
                {name: {$regex: search, $options: 'i'}},
            ]
        };
    },
    index: function() {
        var sort = MeteorisGridView.getSorting();
        sort.limit = this.limit();
        var models = MugenRoleCollections.find(this.getCriteria(), sort);

        return this.render('mugenRoleCollectionsIndex', {
            data: {
                ready: this.subscription.ready,
                isEmpty: models.count() === 0 ? true : false,
                models: models,
                hasMore: this.limit() == models.fetch().length ? this.route.path({limit: this.limit() + this.increment}) : null,
            }
        });
    },
    view: function() {
        return this.render('mugenRoleCollectionsView', {
            data: {
                model: this._loadModel(this.getId()),
            }
        });
    },
    /* private get user input docs */
    _getDoc: function(t) {
        return {
            name: t.find('#name').value,
        };
    },
    /* uploading file using cfs:fileSystem package + cfs:ejson */
    _uploadImage: function() {
        var imageId = null;
        var file = $('#image').get(0).files[0];
        if (file) {
            var image = Images.insert(file, function(err) {
                if (err) {
                    MeteorisFlash.set('danger', err.message);
                    throw new Meteor.Error(err);
                }
            });
            imageId = image._id;
        }

        return imageId;
    },
    /* event inserting data */
    insert: function(t) {
        if (this._post) {
            //uploading file using cfs:fileSystem package + cfs:ejson
            //var imageId = this._uploadImage();

            //set inserted doc
            var doc = this._getDoc(t);
            //doc.imageId = imageId;

            var mugenRoleCollection = MugenRoleCollections.findOne(doc);
            if (mugenRoleCollection) {
                var errMessage = "Mugen Role Collections name must be unique";
                MeteorisFlash.set('danger', errMessage);
                throw new Meteor.Error(errMessage);
            } else {
                MugenRoleCollections.insert(doc, function(err, _id) {
                    if (err) {
                        MeteorisFlash.set('danger', err.message);
                        throw new Meteor.Error(err);
                    }
                    MeteorisFlash.set('success', "Success Inserting MugenRoleCollections");
                    Router.go('mugenRoleCollectionsView', {_id: _id});
                });
            }
        }
        return this.render('mugenRoleCollectionsInsert', {});
    },
    /* event updating data */
    update: function(t) {
        var _id = this.getId();
        var model = this._loadModel(_id);

        if (this._post) {
            //uploading file using cfs:fileSystem package + cfs:ejson
            //var imageId = this._uploadImage();

            //remove old image if user inputting new image
            //if (imageId && model.imageId)
            //Images.remove(model.imageId);

            //set updated doc
            var doc = this._getDoc(t);
            //doc.imageId = imageId ? imageId : model.imageId;

            MugenRoleCollections.update(_id, {$set: doc}, function(err) {
                if (err) {
                    MeteorisFlash.set('danger', err.message);
                    throw new Meteor.Error(err);
                }
                MeteorisFlash.set('success', "Success Updating MugenRoleCollections");
            });
            Router.go('mugenRoleCollectionsView', {_id: _id});
        }
        return this.render('mugenRoleCollectionsUpdate', {
            data: {
                model: model,
            }
        });
    },
    /* event removing data by id */
    remove: function(_id) {
        MugenRoleCollections.remove(_id, function(err) {
            if (err) {
                MeteorisFlash.set('danger', err.message);
                throw new Meteor.Error(err);
            }
            MeteorisFlash.set('success', "Success Removing MugenRoleCollections");
        });
    },
    _loadModel: function(_id) {
        return MugenRoleCollections.findOne(_id);
    },
});


text:
package array1;

import java.util.Arrays;

/*
 * Given an int array of any length, return a new array of its first 2 elements.
 * If the array is smaller than length 2, use whatever elements are present.
 *
 * frontPiece({1, 2, 3}) --> {1, 2}
 * frontPiece({1, 2}) --> {1, 2}
 * frontPiece({1}) --> {1}
 */
public class FrontPieceTest {

	public static void main(String[] args) {

		FrontPieceTest test = new FrontPieceTest();
		System.out.println(Arrays.toString(test.frontPiece(new int[] {1, 2, 3})));
		System.out.println(Arrays.toString(test.frontPiece(new int[] {1, 2})));
		System.out.println(Arrays.toString(test.frontPiece(new int[] {1})));
	}

	public int[] frontPiece(int[] nums) {
		  if (nums.length == 1) {
		    int[] smArray = new int[1];
		    smArray[0] = nums[0];
		    return smArray;
		  }

		  if (nums.length == 0) {
		    int[] emptyArray = new int[0];
		    return emptyArray;
		  }

		  int[] array = new int[2];
		  array[0] = nums[0];
		  array[1] = nums[1];
		  return array;
		}
}


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Sciences Po Grad Econ · A group

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

          Sciences Po Grad Econ

Boldly going where no grad students at The Sciences Po Department of Economics have gone before.

      Home

            About

            Events

      Currently v0.0.1

© 2016. All rights reserved.

        Our First Event

    28 Sep 2016

Hello everyone,

I hope your semester is starting off well. After a fitful start, we finally have a room for a meeting this Friday, 30/9, at 17h00 in room H402.

On the agenda will be...

...a brief presentation by Johannes Boehm on "Things I Wish I'd Known at the Start of My Phd" (M2's: Johannes said he will be updating this, so it won't be a complete repeat for you!).

...a brief presentation by Yours Truly on "How to Apply for Conferences and Travel Funding".

...a discussion of the organizations structure, goals, and future meetings.

All students, M1, M2, and Phd are welcome to attend and participate in an open discussion on all of these topics, so don't be afraid to come!

See you Friday!

-Tyler

    Older

    Newer


text:
'use strict';

const astUtil = require('./core/ast-util');

const create = function (context) {
  const options = context.options[0] || {};
  const shouldCheckArrowFunctions = options.arrowFunctions === true;

  function isCompletelyLiteral(node) {
    switch (node.type) {
      case 'Literal':
        return true;
      case 'BinaryExpression':
        return isCompletelyLiteral(node.left) && isCompletelyLiteral(node.right);
      case 'UnaryExpression':
        return isCompletelyLiteral(node.argument);
      case 'ConditionalExpression':
        return isCompletelyLiteral(node.test) && isCompletelyLiteral(node.consequent) && isCompletelyLiteral(node.alternate);
      default:
        return false;
    }
  }

  function handleFunctionExpression(node) {
    const valueReturnedInFirstLine = astUtil.getValueReturnedInFirstLine(node);
    if (valueReturnedInFirstLine && isCompletelyLiteral(valueReturnedInFirstLine)) {
      context.report(node, 'Prefer `_.constant` over a function returning a literal');
    }
  }

  return {
    FunctionExpression: handleFunctionExpression,
    FunctionDeclaration: handleFunctionExpression,
    ArrowFunctionExpression(node) {
      if (shouldCheckArrowFunctions) {
        handleFunctionExpression(node);
      }
    }
  };
};

const schema = [
  {
    type: 'object',
    properties: {
      arrowFunctions: {
        type: 'boolean'
      }
    }
  }
];

module.exports = {
  create,
  meta: {
    schema,
    docs: {
      description: 'Prefer [`_.constant`](https://lodash.com/docs#constant) over functions returning literals.',
      recommended: ['error', {arrowFunctions: false}]
    }
  }
};


text:
The iSCSI datastore driver provides OpenNebula with the possibility of using block-devices for VM images instead of the default file form. The use of the iSCSI datastores presents several benefits, especially regarding performance. It is developed to work with `tgtd`, the Linux SCSI target framework. However this driver is written in a way it can be easily hacked into working with specific SAN systems or other iSCSI target softwares.

## Development

To contribute bug patches or new features, you can use the github Pull Request model. It is assumed that code and documentation are contributed under the Apache License 2.0.

More info:
* [How to Contribute](http://opennebula.org/addons/contribute/)
* Support: [OpenNebula user mailing list](http://opennebula.org/community:mailinglists)
* Development: [OpenNebula developers mailing list](http://opennebula.org/community:mailinglists)
* Issues Tracking: Github issues (https://github.com/OpenNebula/addon-iscsi/issues)

## Authors

* Leader: Jaime Melis (jmelis@c12g.com)
* Erez Zilber (tgt-setup-lun-one)

## Compatibility

This add-on is compatible with OpenNebula 4.14.

## Requirements

### OpenNebula Front-end

Password-less ssh access to the iSCSI target as the oneadmin user from the frontend.

### The iSCSI Target

Manual installation of the supplied `tgt-setup-lun-one` script. This script will be installed under the share directory of OpenNebula (`/usr/share/one` or `/usr/share/opennebula` depending on the distribution). This script script should be installed in the iSCSI target somewhere in the `PATH`, e.g. `/usr/sbin/tgt-setup-lun-one` and it should belong to root.
Password-less sudo permission for: `tgtadm`, `tgt-setup-lun-one`, `lvcreate`, `lvremove` and `dd`.
LVM2 Linux SCSI target framework (tgt).

## Limitations

There are some limitations that you have to consider, though:

* No iSCSI ACLs. This driver doesn't implement ACLs or zoning for the targets defined in the server. This means that every host will be able to see through discovery all the targets exported by the iSCSI target server, as long as it can make a connection to the host on the iscsi port.

## Installation

To install the driver you have to copy these files:

* `tm` -> `/var/lib/one/remotes/tm/iscsi`
* `datastore` -> `/var/lib/one/remotes/datastore/iscsi`
* `bin/tgt-setup-lun-one` -> `/usr/sbin/tgt-setup-lun-one`

## Configuration

### Configuring the System Datastore

To use iSCSI drivers, you must configure the system datastore as shared. This sytem datastore will hold only the symbolic links to the block devices, so it will not take much space. See more details on the [System Datastore Guide](http://docs.opennebula.org/4.14/administration/storage/system_ds.html).

It will also be used to hold context images and Disks created on the fly, they will be created as regular files.

### Configuring iSCSI Datastores

The first step to create a iSCSI datastore is to set up a template file for it. In the following table you can see the supported configuration attributes. The datastore type is set by its drivers, in this case be sure to add `DS_MAD=iscsi` and `TM_MAD=iscsi` for the transfer mechanism, see below.

* **NAME**: The name of the datastore
* **DS_MAD**: The DS type, use iscsi for the iSCSI datastore
* **TM_MAD**: Transfer drivers for the datastore, use iscsi, see below
* **DISK_TYPE**: Type for the VM disks using images from this datastore. Supported values are: block, file
* **BRIDGE_LIST**: The tgt server host. Defaults to localhost
* **VG_NAME**: The LVM volume group name. Defaults to vg-one
* **BASE_IQN**: The base IQN for iSCSI target. Defaults to iqn.2012-02.org.opennebula
* **RESTRICTED_DIRS**: Paths that can not be used to register images. A space separated list of paths. (1)
* **SAFE_DIRS**: If you need to un-block a directory under one of the RESTRICTED_DIRS. A space separated list of paths.
* **NO_DECOMPRESS**: Do not try to untar or decompress the file to be registered. Useful for specialized Transfer Managers
* **LIMIT_TRANSFER_BW**: Specify the maximum transfer rate in bytes/second when downloading images from a http/https URL. Suffixes K, M or G can be used.
* **DATASTORE_CAPACITY_CHECK**: If "yes", the available capacity of the datastore is checked before creating a new image

> (1) This will prevent users registering important files as VM images and accessing them through their VMs. OpenNebula will automatically add its configuration directories: /var/lib/one, /etc/one and oneadmin's home. If users try to register an image from a restricted directory, they will get the following error message: "Not allowed to copy image file".

For example, the following examples illustrates the creation of a iSCSI datastore using a configuration file. In this case we will use the host iscsitarget as our iSCSI target server.

~~~~
> cat ds.conf
NAME = production
DS_MAD = iscsi
TM_MAD = iscsi
VG_NAME = vg-one
HOST = iscsitarget

> onedatastore create ds.conf
ID: 100

> onedatastore list
  ID NAME            CLUSTER  IMAGES TYPE   TM
   0 system          none     0      fs     shared
   1 default         none     3      fs     shared
 100 production      none     0      iscsi  shared
~~~~

The DS and TM MAD can be changed later using the onedatastore update command. You can check more details of the datastore by issuing the onedatastore show command.

> Note that datastores are not associated to any cluster by default, and they are supposed to be accessible by every single host. If you need to configure datastores for just a subset of the hosts take a look to the [Cluster guide](http://opennebula.org/documentation:rel4.4:cluster_guide).

### Configuring DS_MAD and TM_MAD

These values must be added to `/etc/one/oned.conf`

First we add `iscsi` as an option, replace:

~~~~
TM_MAD = [
    executable = "one_tm",
    arguments = "-t 15 -d dummy,lvm,shared,fs_lvm,qcow2,ssh,vmfs,ceph"
]
~~~~

With:

~~~~
TM_MAD = [
    executable = "one_tm",
    arguments = "-t 15 -d dummy,lvm,shared,fs_lvm,qcow2,ssh,vmfs,ceph,iscsi"
]
~~~~

After that create a new TM_MAD_CONF section:

~~~~
TM_MAD_CONF = [
    name        = "iscsi",
    ln_target   = "NONE",
    clone_target= "SELF",
    shared      = "yes"
]
~~~~

Now we add `iscsi` as a new `DATASTORE_MAD` option, replace:

~~~~
DATASTORE_MAD = [
    executable = "one_datastore",
    arguments  = "-t 15 -d dummy,fs,vmfs,lvm,ceph"
]
~~~~

With:

~~~~
DATASTORE_MAD = [
    executable = "one_datastore",
    arguments  = "-t 15 -d dummy,fs,vmfs,lvm,ceph,iscsi"
]
~~~~

### Configuring Default Values

The default values can be modified in `/var/lib/one/remotes/datastore/iscsi/iscsi.conf`:

* **HOST**: Default iSCSI target host. Default: `localhost`
* **BASE_IQN**: Default IQN path. Default: `iqn.2012-02.org.opennebula`
* **VG_NAME**: Default volume group. Default: `vg-one`
* **NO_ISCSI**: Lists of hosts (separated by spaces) for which no iscsiadm login or logout is performed. Default: `$HOSTNAME`
* **TARGET_CONF**: File where the iSCSI configured is dumped to (`tgt-admin –dump`). If it poings to `/dev/null`, iSCSI targets will not be persistent. Default: `/etc/tgt/targets.conf`

## Usage

The iSCSI transfer driver will issue a iSCSI discover command in the target server with iscsiadm. Once the block device is available in the host, the driver will login, mount it and link it to disk.i.

![ds_iscsi](images/ds_iscsi.png)

### Host Configuration

The hosts must have [Open-iSCSI](http://www.open-iscsi.org/) installed, which provides `iscsiadm`.

In order for `iscsiadm` to work, it needs to be able to make a connection on the default iSCSI port (3260) with the iSCSI target server. Firewalls should be adjusted to allow this connection to take place.

The `oneadmin` user must have sudo permissions to execute `iscsiadm`.

## Tuning & Extending

System administrators and integrators are encouraged to modify these drivers in order to integrate them with their iSCSI SAN/NAS solution. To do so, the following is a list of files that may be adapted:

Under `/var/lib/one/remotes/`:

* `datastore/iscsi/iscsi.conf`: Default values for iSCSI parameters
    * **HOST**: Default iSCSI target host
    * **BASE_IQN**: Default IQN path
    * **VG_NAME**: Default volume group
    * **BASE_TID**: Starting TID for iSCSI targets
    * **NO_ISCSI**: Lists of hosts (separated by spaces) for which no iscsiadm login or logout.
* `scripts_common.sh`: includes all the iSCSI methods:
    * `tgt_admin_dump_config` (file): Dumps the configuration to a file
    * `tgt_setup_lun_install` (host, base_path): checks if tgt-setup-lun-one is installed in host. It creates a file to avoid further ssh connections if it's installed.
    * `tgt_setup_lun` (iqn, dev): creates a new iSCSI target using the tgt-setup-lun-one script.
    * `iscsiadm_discovery` (host): Issues iscsiadm discovery.
    * `iscsiadm_login` (iqn, target_host): Logins to an already discovered IQN.
    * `iscsiadm_logout` (target_it): Logs out from an IQN.
    * `is_iscsi` (host): Returns 0 if logins/logouts should be performed on that host.
    * `iqn_get_lv_name` (iqn): Extracts the logical volume name which is encoded in the IQN.
    * `iqn_get_vg_name` (iqn): Extracts the volume group name which is encoded in the IQN.
    * `iqn_get_host` (iqn): Extracts the iSCSI target host which is encoded in the IQN.
* `datastore/iscsi/cp`: Registers a new image. Creates a new logical volume under LVM and sets an iSCSI target for it.
* `datastore/iscsi/mkfs`: Makes a new empty image. Creates a new logical volume under LVM and sets an iSCSI target for it.
* `datastore/iscsi/rm`: Removes the iSCSI target and removes the logical volume.
* `tm/iscsi/ln`: iscsiadm discover and logs in.
* `tm/iscsi/clone`: Creates a new iSCSI target cloning the source underlying LVM logical volumen.
* `tm/iscsi/mvds`: Logs out for shutdown, cancel, delete, stop and migrate.

> All the actions that perform a change in the iSCSI target server dump the configuration at the end of the action, so the iSCSI server configuration remains persistent. This can be disabled by modifying `/var/lib/one/remotes/datastore/iscsi/iscsi.conf`.


text:
require 'geocodio/legislator'

module Geocodio
  class CongressionalDistrict
    attr_reader :name
    attr_reader :district_number
    attr_reader :congress_number
    attr_reader :proportion
    attr_reader :current_legislators

    def initialize(payload = {})
      @name            = payload['name']
      @district_number = payload['district_number'].to_i
      @congress_number = payload['congress_number'].to_i
      @congress_years  = payload['congress_years']
      @proportion      = payload['proportion'].to_i

      @current_legislators = payload['current_legislators'].map do |legislator|
        Legislator.new(legislator)
      end
    end

    def congress_years
      first, last = @congress_years.split('-').map(&:to_i)
      first..last
    end
  end
end


text:
package com.example.classifieds.realestate.exposure;

import java.util.Objects;

public final class ExposureId {

	private Long campaignId;
	private Long advertisementId;

	public ExposureId(Long campaignId, Long advertisementId) {
		this.campaignId = campaignId;
		this.advertisementId = advertisementId;
	}

	public Long getCampaignId() {
		return campaignId;
	}

	public Long getAdvertisementId() {
		return advertisementId;
	}

	@Override
	public boolean equals(Object obj) {
		return Objects.equals(this, obj);
	}

	@Override
	public int hashCode() {
		return Objects.hash(campaignId, advertisementId);
	}

}


text:
'use babel'

const homeDir = require('os').homedir()
import ServerDownloader from './server-download'

export default {
  mopeExec: {
    type: 'string',
    default: ServerDownloader.defaultServerFile(),
    description: 'Full path to mope-server'
  },
    compilerExec: {
        type: 'string',
        default: '/usr/bin/omc',
        description: "Path to the compiler"
    },
  javaExec: {
    type: 'string',
    default: '/usr/bin/java',
    description: 'Full path to java; `whereis java`'
  },
  startServer: {
    type: 'boolean',
    default: false,
    description: 'Start a new instance of mope-server if none running'
  },
  interface: {
    type: "string",
    default: "localhost"
  },
  port: {
    type: "integer",
    default: 9001
  },
  compileMode: {
    type: 'string',
    default: 'while typing',
    enum: [
      'on demand',
      'while typing'
    ]
  },
  statusViewFontSize: {
    type: 'integer',
    default: 8,
    description: 'Font size of the status view in pt'
  },
  suggestParameters: {
    type: 'boolean',
    default: 'false'
  }
}


text:
<?php
namespace getuisdk;

/**
 * Class PBBytes
 * @package getuisdk
 */
class PBBytes extends PBScalar
{
    /**
     * @param null $reader
     */
    public function __construct($reader = null)
    {
        parent::__construct($reader);
        $this->wired_type = PBMessage::WIRED_LENGTH_DELIMITED;
    }

    /**
     * Parses the message for this type
     *
     * @param array
     */
    public function parseFromArray()
    {
        $this->value = '';
        // first byte is length
        $length = $this->reader->next();

        // just extract the string
        $pointer = $this->reader->getPointer();
        $this->reader->addPointer($length);
        $this->value = $this->reader->getMessageFrom($pointer);
    }

    /**
     * Serializes type
     * @param mixed $rec
     * @return mixed
     */
    public function serializeToString($rec = -1)
    {
        $string = '';

        if ($rec > -1) {
            $string .= $this->base128->setValue($rec << 3 | $this->wired_type);
        }

        $string .= $this->base128->setValue(strlen($this->value));
        $string .= $this->value;

        return $string;
    }
}


text:
<title>GrADS Command: reset</title>

reset

reset <qualifiers>

This command returns GrADS to its initial state with the following exceptions:

No files are closed

No defined variables are released

The set display settings
are not modified

If files are open, the default file is set to 1, and the
dimension environment is set to X,Y varying and Z and T set to 1
(as though file 1 were just opened).

The reset command may be qualified so that only certain
aspects of GrADS are returned to their initial state.

The optional qualifiers are as follows:

reset events
resets the events buffer (e.g., mouse clicks)

reset graphics
resets the graphics, but not the widgets

reset hbuff
resets the display buffer when in double buffer mode

reset norset
resets the X events only

Usage Notes

See the section of the User's Guide
on reinitialization of GrADS.


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.adsense.v2.model;

/**
 * Response definition for the alerts list rpc.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the AdSense Management API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ListAlertsResponse extends com.google.api.client.json.GenericJson {

  /**
   * The alerts returned in this list response.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<Alert> alerts;

  static {
    // hack to force ProGuard to consider Alert used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(Alert.class);
  }

  /**
   * The alerts returned in this list response.
   * @return value or {@code null} for none
   */
  public java.util.List<Alert> getAlerts() {
    return alerts;
  }

  /**
   * The alerts returned in this list response.
   * @param alerts alerts or {@code null} for none
   */
  public ListAlertsResponse setAlerts(java.util.List<Alert> alerts) {
    this.alerts = alerts;
    return this;
  }

  @Override
  public ListAlertsResponse set(String fieldName, Object value) {
    return (ListAlertsResponse) super.set(fieldName, value);
  }

  @Override
  public ListAlertsResponse clone() {
    return (ListAlertsResponse) super.clone();
  }

}


text:
class AddCommentsIdToVotesTable < ActiveRecord::Migration
  def change
    add_column :votes, :comment_id, :integer
  end
end


text:
package network.aika.steps.activation;

import network.aika.neuron.Synapse;
import network.aika.neuron.activation.Activation;
import network.aika.neuron.activation.ConjunctiveActivation;
import network.aika.steps.Phase;
import network.aika.steps.Step;

import static network.aika.steps.Phase.POST_PROCESSING;
import static network.aika.steps.Phase.PROCESSING;

/**
 *
 * @author Lukas Molzberger
 */
public class Instantiation extends Step<Activation> {

    public static void add(Activation act) {
        if(act.instantiationIsQueued)
            return;

        act.instantiationIsQueued = true;

        Step.add(new Instantiation(act));
    }

    public Instantiation(Activation act) {
        super(act);
    }

    @Override
    public void process() {
        getElement()
                .instantiateTemplate();

        getElement().instantiationIsQueued = false;
    }

    @Override
    public Phase getPhase() {
        return POST_PROCESSING;
    }
}


text:
package uk.co.cbray.msc.nhsdsp.dao;

import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anySetOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;

import java.math.BigDecimal;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import uk.co.cbray.msc.nhsdsp.entity.Drug;
import uk.co.cbray.msc.nhsdsp.entity.DrugAllergy;
import uk.co.cbray.msc.nhsdsp.entity.DrugEffect;
import uk.co.cbray.msc.nhsdsp.forms.NewDrugForm;
import uk.co.cbray.msc.nhsdsp.test.utils.TestFactory;
import uk.co.cbray.msc.nhsdsp.utils.Converter;

@RunWith(PowerMockRunner.class)
@PrepareForTest(value={Converter.class})
public class DrugRepositoryTest {

	@Mock
	private DataAccessObject dao;
	@Mock
	private EffectRepository effectRepo;
	private DrugRepository repo;

	@Before
	public void setUp() {
		PowerMockito.mockStatic(Converter.class);
		MockitoAnnotations.initMocks(this);
		repo = new DrugRepository();
		repo.setDao(dao);
		repo.setEffectRepo(effectRepo);
	}

	@Test
	public void testCreateMethodCallsDAOCreateMethod() {
		Drug d = TestFactory.getDrugInstance();

		repo.create(d);

		verify(dao).create(d);
	}

	@Test
	public void testUpdateMethodCallsDaoUpdateMethod() {
		Drug d = TestFactory.getDrugInstance();

		repo.update(d);

		verify(dao).update(d, Drug.class);
	}

	@Test
	public void testFindByIdMethodCallsDaoFindMethod() {
		BigDecimal id = new BigDecimal(1);

		repo.findById(id);

		verify(dao).find(id, Drug.class);
	}

	@Test
	public void testCreateNewDrugMethodAlsoAddsAllergiesAndEffectsAsWellAsTheNewDrug() {

		NewDrugForm form = TestFactory.getNewDrugFormInstance();

		Mockito.when(effectRepo.findByName(anyString())).thenReturn(TestFactory.getEffectInstance());
		Mockito.when(Converter.convert(form)).thenReturn(TestFactory.getDrugInstance());

		repo.createNewDrug(form);

		verify(dao).create((Drug)anyObject());
		verify(dao).updateAll(anyListOf(DrugAllergy.class), eq(DrugAllergy.class));
		verify(dao).createAll(anySetOf(DrugEffect.class));
	}

}


text:
package org.apache.accumulo.core.conf;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CliConfiguration {

  private static final Logger log = LoggerFactory.getLogger(CliConfiguration.class);
  private static volatile Map<String,String> config = new HashMap<>();

  /**
   * Sets CliConfiguration with map of configuration. Additional calls will overwrite existing properties and values.
   *
   * @param conf
   *          Map of configuration
   */
  public static void set(Map<String,String> conf) {
    Objects.requireNonNull(conf);
    config = conf;
  }

  public static void print() {
    log.info("The following configuration was set on the command line:");
    for (Map.Entry<String,String> entry : config.entrySet()) {
      String key = entry.getKey();
      log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue()));
    }
  }

  public static String get(Property property) {
    return config.get(property.getKey());
  }

  public static void getProperties(Map<String,String> props, Predicate<String> filter) {
    for (Map.Entry<String,String> entry : config.entrySet()) {
      if (filter.test(entry.getKey())) {
        props.put(entry.getKey(), entry.getValue());
      }
    }
  }
}


text:
package io.prometheus.jmx;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

/**
 * Runs the JmxExampleApplication on different Java Docker images with the jmx_exporter agent attached,
 * and checks if a couple of example metrics are exposed.
 *

 * Run with
 *
mvn verify

 */
@RunWith(Parameterized.class)
public class AgentJavaVersionsIT {

  private final GenericContainer<?> javaContainer;
  private final Volume volume;
  private final Scraper scraper;

  @Parameterized.Parameters(name="{0}")
  public static String[][] images() {
    return new String[][] {

        // HotSpot
        { "openjdk:8-jre", "jmx_prometheus_javaagent" },
        { "openjdk:8-jre","jmx_prometheus_javaagent_java6" },

        { "openjdk:11-jre", "jmx_prometheus_javaagent_java6" },
        { "openjdk:11-jre", "jmx_prometheus_javaagent" },

        { "openjdk:17-oracle", "jmx_prometheus_javaagent_java6" },
        { "openjdk:17-oracle", "jmx_prometheus_javaagent" },

        { "ticketfly/java:6",  "jmx_prometheus_javaagent_java6" },

        { "openjdk:7", "jmx_prometheus_javaagent_java6" },
        { "openjdk:7", "jmx_prometheus_javaagent" },

        // OpenJ9
        { "ibmjava:8-jre", "jmx_prometheus_javaagent_java6" },
        { "ibmjava:8-jre", "jmx_prometheus_javaagent" },

        { "ibmjava:11", "jmx_prometheus_javaagent_java6" },
        { "ibmjava:11", "jmx_prometheus_javaagent" },

        { "adoptopenjdk/openjdk11-openj9", "jmx_prometheus_javaagent_java6" },
        { "adoptopenjdk/openjdk11-openj9", "jmx_prometheus_javaagent" },
    };
  }

  public AgentJavaVersionsIT(String baseImage, String agentModule) throws IOException, URISyntaxException {
    volume = Volume.create("agent-integration-test-");
    volume.copyAgentJar(agentModule);
    volume.copyConfigYaml("config.yml");
    volume.copyExampleApplication();
    String cmd = "java -javaagent:agent.jar=9000:config.yaml -jar jmx_example_application.jar";
    javaContainer = new GenericContainer<>(baseImage)
            .withFileSystemBind(volume.getHostPath(), "/app", BindMode.READ_ONLY)
            .withWorkingDirectory("/app")
            .withExposedPorts(9000)
            .withCommand(cmd)
            .waitingFor(Wait.forLogMessage(".*registered.*", 1))
            .withLogConsumer(frame -> System.out.print(frame.getUtf8String()));
    javaContainer.start();
    scraper = new Scraper(javaContainer.getHost(), javaContainer.getMappedPort(9000));
  }

  @After
  public void tearDown() throws IOException {
    javaContainer.stop();
    volume.close();
  }

  @Test
  public void testJvmMetric() throws Exception {
    String metricName = "java_lang_Memory_NonHeapMemoryUsage_committed";
    String metric = scraper.scrape(10 * 1000).stream()
        .filter(line -> line.startsWith(metricName))
        .findAny()
        .orElseThrow(() -> new AssertionError("Metric " + metricName + " not found."));
    double value = Double.parseDouble(metric.split(" ")[1]);
    Assert.assertTrue(metricName + " should be > 0", value > 0);
  }

  @Test
  public void testTabularMetric() throws Exception {
    String[] expectedMetrics = new String[] {
        "io_prometheus_jmx_tabularData_Server_1_Disk_Usage_Table_size{source=\"/dev/sda1\"} 7.516192768E9",
        "io_prometheus_jmx_tabularData_Server_1_Disk_Usage_Table_size{source=\"/dev/sda2\"} 1.5032385536E10",
        "io_prometheus_jmx_tabularData_Server_2_Disk_Usage_Table_size{source=\"/dev/sda1\"} 2.5769803776E10",
        "io_prometheus_jmx_tabularData_Server_2_Disk_Usage_Table_size{source=\"/dev/sda2\"} 1.073741824E11"
    };
    List<String> metrics = scraper.scrape(10 * 1000);
    for (String expectedMetric : expectedMetrics) {
      metrics.stream()
          .filter(line -> line.startsWith(expectedMetric))
          .findAny()
          .orElseThrow(() -> new AssertionError("Metric " + expectedMetric + " not found."));
    }
  }
}


text:
package edu.kit.tm.pseprak2.alushare.presenter;

import java.util.List;

import edu.kit.tm.pseprak2.alushare.model.Chat;
import edu.kit.tm.pseprak2.alushare.model.Data;
import edu.kit.tm.pseprak2.alushare.model.DataState;
import edu.kit.tm.pseprak2.alushare.model.helper.AluObserver;
import edu.kit.tm.pseprak2.alushare.model.helper.ChatHelper;
import edu.kit.tm.pseprak2.alushare.model.helper.ContactHelper;
import edu.kit.tm.pseprak2.alushare.model.helper.HelperFactory;
import edu.kit.tm.pseprak2.alushare.view.adapter.ChatTabRecyclerAdapter;
import edu.kit.tm.pseprak2.alushare.view.fragments.ChatTabFragment;

/**
 * @author Niklas Sänger
 *         Presenter for the ChatTab fragment.
 */
public class ChatTabPresenter implements AluObserver<Chat> {
    private static final String TAG = "ChatTabPresenter";
    private final ChatHelper chathelper;
    private ChatTabFragment view;
    private List<Chat> chatList;
    private ChatTabRecyclerAdapter adapter;
    private ContactHelper contactHelper;
    // Field can't be local because the observable holds just weak references. If the field was
    // local, the object would be destroyed. The class wont receive any updates.
    @SuppressWarnings("FieldCanBeLocal")
    private AluObserver<Data> dataAluObserver;

    /**
     * Constructor. Initializes SQLContext
     */
    public ChatTabPresenter(final ChatTabFragment view, ChatTabRecyclerAdapter adapter) {
        if (view == null || adapter == null) {
            throw new IllegalArgumentException();
        }
        this.view = view;
        this.adapter = adapter;

        this.chathelper = HelperFactory.getChatHelper(view.getActivity().getApplicationContext());
        chathelper.addObserver(this);
        this.adapter = adapter;
        this.chatList = chathelper.getChats();
        this.dataAluObserver = new AluObserver<Data>() {
            @Override
            public void updated(final Data data) {
                if (view != null && view.getActivity() != null) {
                    view.getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ChatTabPresenter.this.adapter.updateChat(data);
                        }
                    });
                }
            }

            @Override
            public void inserted(final Data data) {
                if (view != null && view.getActivity() != null) {
                    view.getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ChatTabPresenter.this.adapter.updateChat(data.getNetworkChatID(), data);
                        }
                    });
                }
            }

            @Override
            public void removed(Data data) {
            }
        };
        HelperFactory.getDataHelper(view.getActivity()).addObserver(dataAluObserver);

        this.contactHelper = HelperFactory.getContacHelper(view.getActivity().getApplicationContext());
        adapter.setOwnContact(contactHelper.getSelf());
    }

    /**
     * Loads more chat items..
     */
    public List<Chat> getChatList() {
        return chathelper.getChats();
    }

    /**
     * Returns filterd list of chats.
     *
     * @param query Parameter to filter the list.
     * @return filtered list.
     */
    public List<Chat> getChatList(String query) {
        return chathelper.getChatsByTitle(query.toLowerCase(), Integer.MAX_VALUE, 0);
    }

    public void removeChat(String id) {
        final Chat chat = chathelper.getChat(id);
        new Thread(new Runnable() {
            public void run() {
                chathelper.delete(chat);
            }
        }).run();

    }

    /**
     * Benennt einen Chat um
     *
     * @param netId Identifikation des Chats
     * @param name  neuer Name des Chats
     */
    public void renameChat(String netId, String name) {
        Chat chat = chathelper.getChat(netId);
        chat.setTitle(name);
        chathelper.update(chat);
    }

    /**
     * Gibt Identifikation des Chats zurück
     *
     * @param id ID des Chats
     * @return ID des Chats
     */
    public String getNetworkIdentifier(int id) {
        return chathelper.getChats().get(id).getNetworkChatID();
    }

    @Override
    public void updated(Chat data) {
        this.update(data);
    }

    @Override
    public void inserted(Chat data) {
        this.update();
    }

    @Override
    public void removed(Chat data) {
        this.update();
    }

    //Lädt liste neu
    private void update() {
        if (view != null && view.getActivity() != null) {
            view.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.updateDataSet(getChatList());
                }
            });
        }
    }

    //Lädt nur einzelnes Chat Element neu
    private void update(final Chat chat) {
        if (view != null && view.getActivity() != null) {
            view.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.updateData(chat.getNetworkChatID(), chat);
                }
            });
        }
    }
}


text:
"""
==========================
Plotting Validation Curves
==========================

In this plot you can see the training scores and validation scores of an SVM
for different values of the kernel parameter gamma. For very low values of
gamma, you can see that both the training score and the validation score are
low. This is called underfitting. Medium values of gamma will result in high
values for both scores, i.e. the classifier is performing fairly well. If gamma
is too high, the classifier will overfit, which means that the training score
is good but the validation score is poor.
"""
print(__doc__)

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import validation_curve
from sklearn.svm import SVC

digits = load_digits()
X, y = digits.data, digits.target

param_range = np.logspace(-6, -1, 5)
train_scores, test_scores = validation_curve(
    SVC(), X, y, param_name="gamma", param_range=param_range,
    cv=10, scoring="accuracy", n_jobs=1)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)

plt.title("Validation Curve with SVM")
plt.xlabel("$\gamma$")
plt.ylabel("Score")
plt.ylim(0.0, 1.1)
lw = 2
plt.semilogx(param_range, train_scores_mean, label="Training score",
             color="darkorange", lw=lw)
plt.fill_between(param_range, train_scores_mean - train_scores_std,
                 train_scores_mean + train_scores_std, alpha=0.2,
                 color="darkorange", lw=lw)
plt.semilogx(param_range, test_scores_mean, label="Cross-validation score",
             color="navy", lw=lw)
plt.fill_between(param_range, test_scores_mean - test_scores_std,
                 test_scores_mean + test_scores_std, alpha=0.2,
                 color="navy", lw=lw)
plt.legend(loc="best")
plt.show()


text:
import os

from django.shortcuts import render
from django.template import RequestContext
from django.views.decorators.cache import cache_page

from eulexistdb.db import ExistDB
from eulexistdb.query import QuerySet

from browser.models import RocheTEI

@cache_page(60 * 60)
def index(request):
    # XML and SPARQL numbers

    # Count texts and authors
    qs = QuerySet(using=ExistDB(), xpath='/tei:TEI', collection='docker/texts/', model=RocheTEI)
    qs = qs.filter(chapter='1')
    qs = qs.only('title', 'title_en', 'author')
    # TODO: order by title
    qs = qs.order_by('title_en')

    number_texts = qs.count()
    number_authors = qs.distinct().count()

    wiki_pages = []
    for page in sorted(os.listdir("/docker/dublin-store/sinology/mainSpace")):
        wiki_pages.append([page.replace(" ", "%20"), page])

    data = {'number_texts': number_texts, 'number_authors': number_authors,
            'tei_documents': qs, "wiki_pages": wiki_pages, }

    return render(request, 'roche/index.html', data)


text:
<?php

defined('_JEXEC') or die;

/**
 * Weblink Table class
 *
 * @package     Joomla.Administrator
 * @subpackage  com_weblinks
 * @since       1.5
 */
class WeblinksTableWeblink extends JTable
{
	/**
	 * Constructor
	 *
	 * @param   JDatabaseDriver  &$db  A database connector object
	 */
	public function __construct(&$db)
	{
		parent::__construct('#__weblinks', 'id', $db);

		JTableObserverTags::createObserver($this, array('typeAlias' => 'com_weblinks.weblink'));
		JTableObserverContenthistory::createObserver($this, array('typeAlias' => 'com_weblinks.weblink'));
	}

	/**
	 * Overloaded bind function to pre-process the params.
	 *
	 * @param   mixed  $array   An associative array or object to bind to the JTable instance.
	 * @param   mixed  $ignore  An optional array or space separated list of properties to ignore while binding.
	 *
	 * @return  boolean  True on success.
	 *
	 * @see     JTable:bind
	 * @since   1.5
	 */
	public function bind($array, $ignore = '')
	{
		if (isset($array['params']) && is_array($array['params']))
		{
			$registry = new JRegistry;
			$registry->loadArray($array['params']);
			$array['params'] = (string) $registry;
		}

		if (isset($array['metadata']) && is_array($array['metadata']))
		{
			$registry = new JRegistry;
			$registry->loadArray($array['metadata']);
			$array['metadata'] = (string) $registry;
		}

		if (isset($array['images']) && is_array($array['images']))
		{
			$registry = new JRegistry;
			$registry->loadArray($array['images']);
			$array['images'] = (string) $registry;
		}

		return parent::bind($array, $ignore);
	}

	/**
	 * Overload the store method for the Weblinks table.
	 *
	 * @param   boolean	Toggle whether null values should be updated.
	 * @return  boolean  True on success, false on failure.
	 * @since   1.6
	 */
	public function store($updateNulls = false)
	{
		$date	= JFactory::getDate();
		$user	= JFactory::getUser();

		if ($this->id)
		{
			// Existing item
			$this->modified		= $date->toSql();
			$this->modified_by	= $user->get('id');
		}
		else
		{
			// New weblink. A weblink created and created_by field can be set by the user,
			// so we don't touch either of these if they are set.
			if (!(int) $this->created)
			{
				$this->created = $date->toSql();
			}
			if (empty($this->created_by))
			{
				$this->created_by = $user->get('id');
			}
		}

		// Set publish_up to null date if not set
		if (!$this->publish_up)
		{
			$this->publish_up = $this->_db->getNullDate();
		}

		// Set publish_down to null date if not set
		if (!$this->publish_down)
		{
			$this->publish_down = $this->_db->getNullDate();
		}

		// Verify that the alias is unique
		$table = JTable::getInstance('Weblink', 'WeblinksTable');

		if ($table->load(array('alias' => $this->alias, 'catid' => $this->catid)) && ($table->id != $this->id || $this->id == 0))
		{
			$this->setError(JText::_('COM_WEBLINKS_ERROR_UNIQUE_ALIAS'));
			return false;
		}

		// Convert IDN urls to punycode
		$this->url = JStringPunycode::urlToPunycode($this->url);

		return parent::store($updateNulls);
	}

	/**
	 * Overloaded check method to ensure data integrity.
	 *
	 * @return  boolean  True on success.
	 */
	public function check()
	{
		if (JFilterInput::checkAttribute(array ('href', $this->url)))
		{
			$this->setError(JText::_('COM_WEBLINKS_ERR_TABLES_PROVIDE_URL'));
			return false;
		}

		// check for valid name
		if (trim($this->title) == '')
		{
			$this->setError(JText::_('COM_WEBLINKS_ERR_TABLES_TITLE'));
			return false;
		}

		// Check for existing name
		$query = $this->_db->getQuery(true)
			->select($this->_db->quoteName('id'))
			->from($this->_db->quoteName('#__weblinks'))
			->where($this->_db->quoteName('title') . ' = ' . $this->_db->quote($this->title))
			->where($this->_db->quoteName('catid') . ' = ' . (int) $this->catid);
		$this->_db->setQuery($query);

		$xid = (int) $this->_db->loadResult();
		if ($xid && $xid != (int) $this->id)
		{
			$this->setError(JText::_('COM_WEBLINKS_ERR_TABLES_NAME'));
			return false;
		}

		if (empty($this->alias))
		{
			$this->alias = $this->title;
		}
		$this->alias = JApplication::stringURLSafe($this->alias);
		if (trim(str_replace('-', '', $this->alias)) == '')
		{
			$this->alias = JFactory::getDate()->format("Y-m-d-H-i-s");
		}

		// Check the publish down date is not earlier than publish up.
		if ($this->publish_down > $this->_db->getNullDate() && $this->publish_down < $this->publish_up)
		{
			$this->setError(JText::_('JGLOBAL_START_PUBLISH_AFTER_FINISH'));
			return false;
		}

		// clean up keywords -- eliminate extra spaces between phrases
		// and cr (\r) and lf (\n) characters from string
		if (!empty($this->metakey))
		{
			// only process if not empty
			$bad_characters = array("\n", "\r", "\"", "<", ">"); // array of characters to remove
			$after_clean = JString::str_ireplace($bad_characters, "", $this->metakey); // remove bad characters
			$keys = explode(',', $after_clean); // create array using commas as delimiter
			$clean_keys = array();

			foreach ($keys as $key)
			{
				if (trim($key)) {  // ignore blank keywords
					$clean_keys[] = trim($key);
				}
			}
			$this->metakey = implode(", ", $clean_keys); // put array back together delimited by ", "
		}

		return true;
	}

	/**
	 * Method to set the publishing state for a row or list of rows in the database
	 * table.  The method respects checked out rows by other users and will attempt
	 * to checkin rows that it can after adjustments are made.
	 *
	 * @param   mixed	An optional array of primary key values to update.  If not
	 *					set the instance property value is used.
	 * @param   integer The publishing state. eg. [0 = unpublished, 1 = published]
	 * @param   integer The user id of the user performing the operation.
	 * @return  boolean  True on success.
	 * @since   1.0.4
	 */
	public function publish($pks = null, $state = 1, $userId = 0)
	{
		$k = $this->_tbl_key;

		// Sanitize input.
		JArrayHelper::toInteger($pks);
		$userId = (int) $userId;
		$state  = (int) $state;

		// If there are no primary keys set check to see if the instance key is set.
		if (empty($pks))
		{
			if ($this->$k)
			{
				$pks = array($this->$k);
			}
			// Nothing to set publishing state on, return false.
			else {
				$this->setError(JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED'));
				return false;
			}
		}

		// Build the WHERE clause for the primary keys.
		$where = $k.'='.implode(' OR '.$k.'=', $pks);

		// Determine if there is checkin support for the table.
		if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time'))
		{
			$checkin = '';
		}
		else
		{
			$checkin = ' AND (checked_out = 0 OR checked_out = '.(int) $userId.')';
		}

		// Update the publishing state for rows with the given primary keys.
		$this->_db->setQuery(
			'UPDATE '.$this->_db->quoteName($this->_tbl) .
			' SET '.$this->_db->quoteName('state').' = '.(int) $state .
			' WHERE ('.$where.')' .
			$checkin
		);

		try
		{
			$this->_db->execute();
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());
			return false;
		}

		// If checkin is supported and all rows were adjusted, check them in.
		if ($checkin && (count($pks) == $this->_db->getAffectedRows()))
		{
			// Checkin the rows.
			foreach ($pks as $pk)
			{
				$this->checkin($pk);
			}
		}

		// If the JTable instance value is in the list of primary keys that were set, set the instance.
		if (in_array($this->$k, $pks))
		{
			$this->state = $state;
		}

		$this->setError('');
		return true;
	}
}


text:
<?php
namespace Hawk\Exception;

use Exception;
use Hawk\Interfaces\Exception\DisclosableExceptionInterface;
use Hawk\Route\Param;

class MissingArgumentException extends Exception implements DisclosableExceptionInterface
{
	private $param = null;

	public function __construct(Param $param)
	{
		$this->param = $param;
		$this->message = 'Request is missing an argument for ' . $param->getType() . ' parameter ' . $param->getName() . '.';
	}

	public function getParam()
	{
		return $this->param;
	}

	public function getStatusCode()
	{
		return 400; // 400 Bad Request
	}
}


text:
/**
 * Login
 */
html, body {
  height: 100%;
}
.login {
  background: #222;
}
.form-box {
  width: 360px;
  margin: 90px auto 0 auto;
}
.form-box .login-header {
  -webkit-border-top-left-radius: 4px;
  -webkit-border-top-right-radius: 4px;
  -webkit-border-bottom-right-radius: 0;
  -webkit-border-bottom-left-radius: 0;
  -moz-border-radius-topleft: 4px;
  -moz-border-radius-topright: 4px;
  -moz-border-radius-bottomright: 0;
  -moz-border-radius-bottomleft: 0;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
  box-shadow: inset 0px -3px 0px rgba(0, 0, 0, 0.2);
  padding: 20px 10px;
  text-align: center;
  font-size: 26px;
  font-weight: 300;
  color: #fff;
}
.form-box .login-body {
  background: #eaeaec !important;
}
.form-box .login-body,
.form-box .login-footer {
  padding: 10px 20px;
  background: #fff;
  color: #444;
}
.form-box .login-body > .form-group,
.form-box .footer > .form-group {
  margin-top: 20px;
}
.form-box .login-body > .form-group > input,
.form-box .login-footer > .form-group > input {
  border: #fff;
}
.form-box .login-body > .btn,
.form-box .login-footer > .btn {
  margin-bottom: 10px;
}
.form-box .login-footer {
  -webkit-border-top-left-radius: 0;
  -webkit-border-top-right-radius: 0;
  -webkit-border-bottom-right-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-topleft: 0;
  -moz-border-radius-topright: 0;
  -moz-border-radius-bottomright: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 4px;
  border-bottom-left-radius: 4px;
}
.form-box .login-company {
  color: #444;
}
@media (max-width: 767px) {
  .form-box {
    width: 90%;
  }
}


text:
package com.frameworkexample.android.activity;

import com.frameworkexample.android.R;
import com.frameworkexample.android.activity.base.BaseFragmentTabActivity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

public class MainTabActivity extends BaseFragmentTabActivity {

	final String TAG = MainTabActivity.class.getSimpleName();

	@Override
	public int getLayoutResId() {
		return R.layout.activity_maintab;
	}

	@Override
	protected int provideTabHostId() {
		return R.id.activity_maintab_th;
	}

	@Override
	protected MainTabBuilder provideMainTabBuilder() {
		return new MainTabBuilder()
			// 设置Tab的名称
			.setMainTabLabels(R.string.menu_settings, R.string.menu_settings, R.string.menu_settings)
			// 设置Tab的图标
			.setMainTabIcons(R.drawable.activity_maintab_item_iconselector,
					R.drawable.activity_maintab_item_iconselector,
					R.drawable.activity_maintab_item_iconselector)
			// 设置Tab的选中后显示的Fragment
			.setMainTabViewIds(R.id.fg1, R.id.fg2, R.id.fg3);
	}

	@Override
	protected View provideTabIndicatorView(String tag, int labelResId, int iconResId) {
		View root = getLayoutInflater().inflate(R.layout.activity_maintab_item, null);
		TextView tv = (TextView) root.findViewById(R.id.activity_maintab_item_tv);
		tv.setText(labelResId);
		tv.setBackgroundResource(iconResId);
		return root;
	}

	@Override
	public void initView(View view) {

	}

	@Override
	public void initListener() {

	}

	@Override
	public void initData(View view, Bundle savedInstanceState) {

	}

	@Override
	public Handler createActivityHandler() {
		return null;
	}

	@Override
	public void onClick(View v) {
	}
}