text:
These are installation steps for users who do not have access to WSL (Windows Subsystem for Linux),
or people who just prefer not to use it. For WSL, follow the Linux instructions instead.

### Setting up MSYS2 and keeping it up to date

Go visit the [MSYS2](http://www.msys2.org/) website and go through the installer.
Follow the instructions carefully to make sure the packages are up to date.

### Install required packages

Open up a "MSYS2 MinGW 64-bit" terminal and enter the following:
 - `pacman -S make git mingw-w64-x86_64-toolchain texinfo tar wget`

Note: All of these instructions should also work in the 32-bit terminal if you replace `x86_64` with `i686`.

If you plan on using `SGDK`, you need Java 1.8 or newer.
It's a bit annoying to set up, but basically:
 1. Download and run the installer from: https://www.java.com/en/download/
 2. Take note of where it gets installed, and add to `~/.bash_profile`:
   - `export JAVA_HOME="/C/Program Files/Java/jre*/"`
   - `export PATH="${PATH}:${JAVA_HOME}/bin/"`
 3. Run `source ~/.bash_profile` or just close and reopen the terminal

If you plan on using `sik-tools`:
 - `pacman -S mingw-w64-x86_64-libpng`

If you plan on using `flamewing-tools`:
 - `pacman -S mingw-w64-x86_64-cmake mingw-w64-x86_64-boost`

### Start compiling targets

Check the [Target Reference](targets.md)


text:
<?xml version="1.0"?>
<config>
    <modules>
        <Snowcode_GoogleCloudPrint>
            <version>0.1.0</version>
        </Snowcode_GoogleCloudPrint>
    </modules>
    <global>
        <models>
            <scgooglecloudprint>
                <class>Snowcode_GoogleCloudPrint_Model</class>
                <resourceModel>scgooglecloudprint_resource</resourceModel>
            </scgooglecloudprint>
            <scgooglecloudprint_resource>
                <class>Snowcode_GoogleCloudPrint_Model_Resource</class>
            </scgooglecloudprint_resource>
        </models>
        <blocks>
            <scgooglecloudprint>
                <class>Snowcode_GoogleCloudPrint_Block</class>
            </scgooglecloudprint>
        </blocks>
        <helpers>
            <scgooglecloudprint>
                <class>Snowcode_GoogleCloudPrint_Helper</class>
            </scgooglecloudprint>
        </helpers>
    </global>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <payperrentals before="Mage_Adminhtml_Sales">Snowcode_GoogleCloudPrint_Adminhtml</payperrentals>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <adminhtml>
        <translate>
            <modules>
                <scgooglecloudprint>
                    <files>
                        <default>Snowcode_GoogleCloudPrint.csv</default>
                    </files>
                </scgooglecloudprint>
            </modules>
        </translate>
    </adminhtml>
    <frontend>
        <translate>
            <modules>
                <scgooglecloudprint>
                    <files>
                        <default>Snowcode_GoogleCloudPrint.csv</default>
                    </files>
                </scgooglecloudprint>
            </modules>
        </translate>
    </frontend>
    <default>
        <scgooglecloudprint>
            <print_replace>
                <print_invoice>0</print_invoice>
                <print_creditmemo>0</print_creditmemo>
                <print_shipment>0</print_shipment>
            </print_replace>
        </scgooglecloudprint>
    </default>
</config>

redpajama_set_name: RedPajamaGithub


text:
package org.ethereum.net.eth.message;

import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.ethereum.util.Utils;
import org.spongycastle.util.encoders.Hex;

import java.util.ArrayList;
import java.util.List;

/**
 * Wrapper around an Ethereum GetBlockBodies message on the network
 *
 * @see EthMessageCodes#GET_BLOCK_BODIES
 *
 * @author Mikhail Kalinin
 * @since 04.09.2015
 */
public class GetBlockBodiesMessage extends EthMessage {

    /**
     * List of block hashes for which to retrieve the block bodies
     */
    private List<byte[]> blockHashes;

    public GetBlockBodiesMessage(byte[] encoded) {
        super(encoded);
    }

    public GetBlockBodiesMessage(List<byte[]> blockHashes) {
        this.blockHashes = blockHashes;
        parsed = true;
    }

    private synchronized void parse() {
        if (parsed) return;
        RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);

        blockHashes = new ArrayList<>();
        for (int i = 0; i < paramsList.size(); ++i) {
            blockHashes.add(paramsList.get(i).getRLPData());
        }
        parsed = true;
    }

    private void encode() {
        List<byte[]> encodedElements = new ArrayList<>();
        for (byte[] hash : blockHashes)
            encodedElements.add(RLP.encodeElement(hash));
        byte[][] encodedElementArray = encodedElements.toArray(new byte[encodedElements.size()][]);
        this.encoded = RLP.encodeList(encodedElementArray);
    }

    @Override
    public byte[] getEncoded() {
        if (encoded == null) encode();
        return encoded;
    }

    @Override
    public Class<BlockBodiesMessage> getAnswerMessage() {
        return BlockBodiesMessage.class;
    }

    public List<byte[]> getBlockHashes() {
        parse();
        return blockHashes;
    }

    @Override
    public EthMessageCodes getCommand() {
        return EthMessageCodes.GET_BLOCK_BODIES;
    }

    public String toString() {
        parse();

        StringBuilder payload = new StringBuilder();

        payload.append("count( ").append(blockHashes.size()).append(" ) ");

        if (logger.isDebugEnabled()) {
            for (byte[] hash : blockHashes) {
                payload.append(Hex.toHexString(hash).substring(0, 6)).append(" | ");
            }
            if (!blockHashes.isEmpty()) {
                payload.delete(payload.length() - 3, payload.length());
            }
        } else {
            payload.append(Utils.getHashListShort(blockHashes));
        }

        return "[" + getCommand().name() + " " + payload + "]";
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Skeddly.Model
{
	public class GenerateIamPolicyRequest
	{
		public string CredentialId { get; set; }

		public IEnumerable<string> Extras { get; set; }
	}
}


text:
\page opengl_octree_render_huge_pointcloud Example: opengl_octree_render_huge_pointcloud
C++ example source code:
\include opengl_octree_render_huge_pointcloud/test.cpp


text:
.class public Landroid/graphics/PixelFormat;
.super Ljava/lang/Object;
.source "PixelFormat.java"

# static fields
.field public static final A_8:I = 0x8
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final JPEG:I = 0x100
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final LA_88:I = 0xa
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final L_8:I = 0x9
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final OPAQUE:I = -0x1

.field public static final RGBA_1010102:I = 0x2b

.field public static final RGBA_4444:I = 0x7
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final RGBA_5551:I = 0x6
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final RGBA_8888:I = 0x1

.field public static final RGBA_F16:I = 0x16

.field public static final RGBX_8888:I = 0x2

.field public static final RGB_332:I = 0xb
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final RGB_565:I = 0x4

.field public static final RGB_888:I = 0x3

.field public static final TRANSLUCENT:I = -0x3

.field public static final TRANSPARENT:I = -0x2

.field public static final UNKNOWN:I = 0x0

.field public static final YCbCr_420_SP:I = 0x11
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final YCbCr_422_I:I = 0x14
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final YCbCr_422_SP:I = 0x10
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

# instance fields
.field public bitsPerPixel:I

.field public bytesPerPixel:I

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static formatHasAlpha(I)Z
    .locals 1

    sparse-switch p0, :sswitch_data_0

    const/4 v0, 0x0

    return v0

    :sswitch_0
    const/4 v0, 0x1

    return v0

    nop

    :sswitch_data_0
    .sparse-switch
        -0x3 -> :sswitch_0
        -0x2 -> :sswitch_0
        0x1 -> :sswitch_0
        0x6 -> :sswitch_0
        0x7 -> :sswitch_0
        0x8 -> :sswitch_0
        0xa -> :sswitch_0
        0x16 -> :sswitch_0
        0x2b -> :sswitch_0
    .end sparse-switch
.end method

.method public static getPixelFormatInfo(ILandroid/graphics/PixelFormat;)V
    .locals 3

    const/16 v0, 0x10

    const/16 v2, 0x8

    const/4 v1, 0x1

    sparse-switch p0, :sswitch_data_0

    new-instance v0, Ljava/lang/IllegalArgumentException;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v2, "unknown pixel format "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0

    :sswitch_0
    const/16 v0, 0x20

    iput v0, p1, Landroid/graphics/PixelFormat;->bitsPerPixel:I

    const/4 v0, 0x4

    iput v0, p1, Landroid/graphics/PixelFormat;->bytesPerPixel:I

    :goto_0
    return-void

    :sswitch_1
    const/16 v0, 0x18

    iput v0, p1, Landroid/graphics/PixelFormat;->bitsPerPixel:I

    const/4 v0, 0x3

    iput v0, p1, Landroid/graphics/PixelFormat;->bytesPerPixel:I

    goto :goto_0

    :sswitch_2
    iput v0, p1, Landroid/graphics/PixelFormat;->bitsPerPixel:I

    const/4 v0, 0x2

    iput v0, p1, Landroid/graphics/PixelFormat;->bytesPerPixel:I

    goto :goto_0

    :sswitch_3
    iput v2, p1, Landroid/graphics/PixelFormat;->bitsPerPixel:I

    iput v1, p1, Landroid/graphics/PixelFormat;->bytesPerPixel:I

    goto :goto_0

    :sswitch_4
    iput v0, p1, Landroid/graphics/PixelFormat;->bitsPerPixel:I

    iput v1, p1, Landroid/graphics/PixelFormat;->bytesPerPixel:I

    goto :goto_0

    :sswitch_5
    const/16 v0, 0xc

    iput v0, p1, Landroid/graphics/PixelFormat;->bitsPerPixel:I

    iput v1, p1, Landroid/graphics/PixelFormat;->bytesPerPixel:I

    goto :goto_0

    :sswitch_6
    const/16 v0, 0x40

    iput v0, p1, Landroid/graphics/PixelFormat;->bitsPerPixel:I

    iput v2, p1, Landroid/graphics/PixelFormat;->bytesPerPixel:I

    goto :goto_0

    :sswitch_data_0
    .sparse-switch
        0x1 -> :sswitch_0
        0x2 -> :sswitch_0
        0x3 -> :sswitch_1
        0x4 -> :sswitch_2
        0x6 -> :sswitch_2
        0x7 -> :sswitch_2
        0x8 -> :sswitch_3
        0x9 -> :sswitch_3
        0xa -> :sswitch_2
        0xb -> :sswitch_3
        0x10 -> :sswitch_4
        0x11 -> :sswitch_5
        0x14 -> :sswitch_4
        0x16 -> :sswitch_6
        0x2b -> :sswitch_0
    .end sparse-switch
.end method

.method public static isPublicFormat(I)Z
    .locals 1

    sparse-switch p0, :sswitch_data_0

    const/4 v0, 0x0

    return v0

    :sswitch_0
    const/4 v0, 0x1

    return v0

    nop

    :sswitch_data_0
    .sparse-switch
        0x1 -> :sswitch_0
        0x2 -> :sswitch_0
        0x3 -> :sswitch_0
        0x4 -> :sswitch_0
        0x16 -> :sswitch_0
        0x2b -> :sswitch_0
    .end sparse-switch
.end method


text:
function [ idx ] = resampleMixtureComponents( xNoiseMixcompsCnt, stateMixcompsCnt, weights, resample_method )
    % resampleMixtureComponents. Residual resampling for Gaussian Mixture Models.
    %
    %   [ idx ] = resampleMixtureComponents( mixcompsCnt, weights )
    %
    %   Performs the resampling stage of the SIR GMM algorithm in order (number of samples) steps. Applicable for GSPF algorithm.
    %
    %   INPUT
    %       xNoiseMixcompsCnt   number of state noise gaussian mixture components;
    %       stateMixcompsCnt    number of state gaussian mixture components;
    %       weights             component weigths;
    %       resample_method     reample method.
    %
    %   OUTPUT
    %       idx     resampled indices.
    %
    %%
    mixcompsCnt = xNoiseMixcompsCnt * stateMixcompsCnt;
    resampleIndex = resample(resample_method, weights, mixcompsCnt);

    [~, rIdx] = sort(rand(1, mixcompsCnt));
    rIdx = rIdx(1 : stateMixcompsCnt);

    idx  = resampleIndex(rIdx);
end


text:
Uma prática muito importante no desenvolvimento de software em equipe é o Code Review, usado para garantir a qualidade do código, ajudar a disseminar conhecimento entre os membros do time e evitar que erros que não foram pegos pelo processo automatizado passem para as branchs estáveis.

O processo de Code Review leva tempo e exige dedicação dos envolvidos, mas apesar de ser muito útil, é comum que as pessoas se esqueçam ou às vezes nem pensem em checar detalhes que deveriam ser corrigidos durante o Code Review.

Felizmente, isso não é mais um problema. Os criadores do Cocoapods e Fastlane, ferramentas já bem conhecidas no mundo do desenvolvimento iOS, criaram a Danger.

Danger é uma ferramenta escrita em Ruby que veio para auxiliar o processo de Code Review para todos os desenvolvedores, independente da plataforma. Ela garante que tudo que foi definido que seria analisado durante o Code Review seja de fato analisado. E, a melhor parte, de forma automatizada, integrada com o servidor de integração contínua e a plataforma de controle de versão.

Durante o processo de build do projeto a Danger vai analisar as regras definidas em um script Ruby e permitir que o time codifique suas normas de Code Review, deixando que as pessoas usem seu tempo para pensar em tarefas mais complicadas. De acordo com o que foi definido, a Danger vai comentar nos pull requests o que está de acordo ou não, permitindo também quebrar o processo de build caso alguma regra mais importante seja violada. Conforme as correções vão sendo feitas as mensagens são alteradas para deixar a evolução que ocorreu transparente .

Implementar a Danger em seu projeto é bem simples, basta cinco passos:

- Instale a gem 'danger' no projeto. É recomendável que isso seja feito utilizando o Bundler, um gerenciador de dependências Ruby. Com a gem instalada você pode utilizar o comando `Danger init`, que irá guiá-lo pelos próximos passos.

- Crie um arquivo vazio chamado Dangerfile. É neste arquivo que será escrito o script em Ruby que ditará as regras seguidas para o seu Code Review. Caso você não esteja familiarizado com Ruby não se preocupe, apesar de ser a linguagem utilizada não é necessário conhecimento prévio, basta conhecer conceitos básicos de programação. Além disso, a escrita do script é feita de forma quase natural.

- Este passo não é necessário para utilizar a Danger, mas sim para que ela possa comentar diretamente nos Pull Requests. Crie uma conta em sua plataforma de controle de versão (Github, Gitlab, Bitbucket Server). Esta conta será usada como um bot pela Danger para comentar nos Pull Requests.
A conta é criada como uma conta de usuário normal e a configuração para ser usada como bot vária de uma plataforma para outra. Sugiro que leia a documentação sobre o assunto na plataforma que for usar.

- Adicione ao seu servidor de integração contínua uma variável de ambiente chamada `DANGER_GITHUB_API_TOKEN`. O valor desta variável é fornecido pela plataforma de controle de versão e varia de uma para a outra, mas pode ser facilmente achada utilizando a documentação da plataforma.

- Adicione ao processo de build de seu servidor de integração contínua a Danger. Novamente, a forma como isto deve ser feito pode variar de um servidor para o outro, mas o que deve ser feito é adicionar o comando `danger` (ou `bundle exec danger`) à sua pipeline e pronto, já está tudo preparado.

# Danger em uso

Aqui temos um exemplo de uma Dangerfile, agora vamos explicar o que cada parte do script está fazendo.

![screenshots/Dangerfile.png](screenshots/Dangerfile.png)

```Ruby
# Warn when there is a big PR
warn("Big PR") if git.lines_of_code > 5000
```
Um aviso é dado se o Pull Request for muito grande e estiver com mais linhas do que o definido.

```Ruby
# Force tests to be made within all PRs that changes files
has_app_changes = !git.modified_files.grep(/DangerPoc/).empty?
has_test_changes = !git.modified_files.grep(/DangerPocTests/).empty?

if has_app_changes && !has_test_changes
  fail "Tests were not updated"
end
```
Define duas variáveis locais e checa se tiveram arquivos modificados mas não foram adicionados testes destes arquivos. Neste caso a build irá falhar, pois viola uma regra definida como primordial por este time.

![screenshots/PR_Tests.png](screenshots/PR_Tests.png)

```Ruby
# Make a note about contributors not in the organization
unless github.api.organization_member?('DangerPoc', github.pr_author)
  message "@#{github.pr_author} is not a contributor yet"
end
```
Aparece uma mensagem se o autor do Pull Request não for um colaborador do projeto.

![screenshots/Contributor.png](screenshots/Contributor.png)

```Ruby
# Fail the build based on code coverage
xcov.report(
  workspace: "DangerPoc.xcworkspace",
  scheme: "DangerPoc",
  minimum_coverage_percentage: 50.0
)
```
Aqui está sendo utilizado um plugin para a Danger. Xcov é uma ferramenta usada para geração de relatório de cobertura de testes em iOS.
Este plugin permite que a Danger falhe a build caso a cobertura de código esteja abaixo do esperado, que neste caso é de 50%.

![screenshots/Contributor_CodeCoverageUnder.png](screenshots/Contributor_CodeCoverageUnder.png)
![screenshots/CodeCoverageOk.png](screenshots/CodeCoverageOk.png)
![screenshots/Xcov.png](screenshots/Xcov.png)

```Ruby
commit_lint.check warn: :all
```
Outro plugin muito útil para garantir que as mensagens de commit estejam sendo escritas de forma clara e respeitando os guidelines conhecidos de git.

![screenshots/CommitLintWarning.png](screenshots/CommitLintWarning.png)
![screenshots/CommitLintOk.png](screenshots/CommitLintOk.png)

# Conclusão

Danger ainda é uma ferramenta nova, mas está em crescimento e com um potencial enorme. Code Review é algo presente diariamente na vida de quase todos os desenvolvedores e uma ferramenta que possa facilitar e melhorar este processo de forma simples tem tudo para ser incorporada por todos nós em nossos processos de build.

Obs: Danger é referida como "a/ela" apesar de ser uma ferramenta, pois é uma homenagem dos criadores para Gem "Danger" McShane, que esteve envolvida com o processo de concepção e com a idealização do projeto em si.

### Referências:

http://danger.systems

https://github.com/danger/danger


text:
class Course::MaterialsComponent < SimpleDelegator
  include Course::ControllerComponentHost::Component

  def self.display_name
    I18n.t('components.materials.name')
  end

  def sidebar_items
    main_sidebar_items + settings_sidebar_items
  end

  private

  def main_sidebar_items
    [
      {
        key: :materials,
        icon: 'folder-open',
        title: settings.title || t('course.material.sidebar_title'),
        weight: 9,
        path: course_material_folder_path(current_course, current_course.root_folder),
        unread: 0
      }
    ]
  end

  def settings_sidebar_items
    [
      {
        title: t('course.material.sidebar_title'),
        type: :settings,
        weight: 10,
        path: course_admin_materials_path(current_course)
      }
    ]
  end
end


text:
package mil.nga.giat.geowave.adapter.vector.utils;

import static org.junit.Assert.assertEquals;
import mil.nga.giat.geowave.adapter.vector.util.FeatureDataUtils;
import mil.nga.giat.geowave.core.index.StringUtils;

import org.geotools.feature.SchemaException;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;

public class FeatureDataUtilsTest
{

	@Test
	public void testWithSRID()
			throws SchemaException {
		SimpleFeatureType type = FeatureDataUtils.decodeType(
				"http://somens.org",
				"type1",
				"geometry:Geometry:srid=4326,pop:java.lang.Long,when:Date,whennot:Date,pid:String",
				"east");
		assertEquals(
				"type1",
				type.getName().getLocalPart());
	}

	/**
	 *
	 * This test only works in some versions. So, comment out for now.
	 *
	 * public void testWithSRIDAndMisMatch() throws SchemaException {
	 * SimpleFeatureType type = FeatureDataUtils.decodeType("http://somens.org",
	 * "type1",
	 * "geometry:Geometry:srid=4326,pop:java.lang.Long,when:Date,whennot:Date,pid:String"
	 * , "north"); assertEquals("type1",type.getName().getLocalPart());
	 * assertEquals
	 * ("NORTH",type.getCoordinateReferenceSystem().getCoordinateSystem
	 * ().getAxis(0).getDirection().name()); }
	 */

	@Test
	public void testWithoutSRID()
			throws SchemaException {
		SimpleFeatureType type = FeatureDataUtils.decodeType(
				"http://somens.org",
				"type1",
				"geometry:Geometry,pop:java.lang.Long,when:Date,whennot:Date,pid:String",
				StringUtils.stringFromBinary(new byte[0]));
		assertEquals(
				"type1",
				type.getName().getLocalPart());
	}

}


text:
namespace DRVEngine {

//=============================================================================
Texture::Texture( Renderer& renderer, int width, int height, int channels, const u8* data ) :
    m_renderer( &renderer ),
    m_width( width ),
    m_height( height ),
    m_id( DRV_INVALID_RENDER_HANDLE ) {

    m_id = m_renderer->CreateTexture( width, height, channels, data );
}

//=============================================================================
Texture::Texture( Renderer& renderer, const Image& image ) :
    Texture( renderer, image.width, image.height, 4, image.data ) {}

//=============================================================================
Texture::Texture( Renderer & renderer, Image images[6] ) :
    m_renderer( &renderer ),
    m_width( images[0].width ),
    m_height( images[0].height ),
    m_id( DRV_INVALID_RENDER_HANDLE ) {

    u8* data[6] = { images[0].data, images[1].data, images[2].data, images[3].data, images[4].data, images[5].data };
    m_id = m_renderer->CreateCubemapTexture( m_width, m_height, 4, data );
}

//=============================================================================
Texture::Texture( Texture&& other ) :
    m_renderer( other.m_renderer ),
    m_width( other.m_width ),
    m_height( other.m_height ),
    m_id( other.m_id ) {
    other.m_id = DRV_INVALID_RENDER_HANDLE;
}

//=============================================================================
Texture::~Texture() {
    if ( m_id != DRV_INVALID_RENDER_HANDLE ) {
        m_renderer->ReleaseTexture( m_id );
    }
}

//=============================================================================
Texture& Texture::operator=( Texture&& other ) {
    m_renderer = other.m_renderer;
    m_width = other.m_width;
    m_height = other.m_height;
    m_id = other.m_id;
    other.m_id = DRV_INVALID_RENDER_HANDLE;
    return *this;
}

}


text:
PropertyComponent::PropertyComponent (const String& name, const int preferredHeight_)
    : Component (name), preferredHeight (preferredHeight_)
{
    jassert (name.isNotEmpty());
}

PropertyComponent::~PropertyComponent() {}

void PropertyComponent::paint (Graphics& g)
{
    LookAndFeel& lf = getLookAndFeel();

    lf.drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
    lf.drawPropertyComponentLabel      (g, getWidth(), getHeight(), *this);
}

void PropertyComponent::resized()
{
    if (Component* const c = getChildComponent(0))
        c->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
}

void PropertyComponent::enablementChanged()
{
    repaint();
}


text:
module.exports = {
    "ACCELERATE FOR (steps)": "ACELERAR PARA (pasos)",
    "Account Settings": "Ajustes de cuenta",
    "Add": "Añadir",
    "Add Farm Event": "Añadir Farm Event",
    "Age": "Edad",
    "Agree to Terms of Service": "Aceptar los Términos del Servicio",
    "ALLOW NEGATIVES": "PERMITIR NEGATIVOS",
    "BACK": "ATRÁS",
    "Bot ready": "Bot listo",
    "CALIBRATE {{axis}}": "CALIBRAR {{axis}}",
    "CALIBRATION": "CALIBRACIÓN",
    "calling FarmBot with credentials": "llamando a FarmBot con credenciales",
    "Camera": "Camera",
    "Choose a species": "Elige una especie",
    "Confirm Password": "Confirmar Contraseña",
    "CONTROLLER": "CONTROLADOR",
    "Copy": "Copiar",
    "Could not download sync data": "No se pudieron descargar los datos de sincronización",
    "Create Account": "Crear Cuenta",
    "Create An Account": "Crear Una Cuenta",
    "Crop Info": "Información del Cultivo",
    "Data Label": "Etiqueta de Datos",
    "days old": "days old",
    "Delete": "Eliminar",
    "DELETE ACCOUNT": "ELIMINAR CUENTA",
    "Delete this plant": "Eliminar esta planta",
    "Designer": "Diseñador",
    "DEVICE": "DISPOSITIVO",
    "downloading device credentials": "descargando credenciales del dispositivo",
    "Drag and drop into map": "Arrastra y suelta dentro del mapa",
    "DRAG STEP HERE": "DRAG STEP HERE",
    "Edit": "Editar",
    "EDIT": "EDITAR",
    "Edit Farm Event": "Editar Farm Event",
    "Email": "Email",
    "ENABLE ENCODERS": "ACTIVAR CODIFICADORES",
    "Enter Email": "Introducir Email",
    "Error establishing socket connection": "Error estableciendo la conexión con el socket",
    "Execute Script": "Ejecutar Script",
    "EXECUTE SCRIPT": "EJECUTAR SCRIPT",
    "Execute Sequence": "Ejecutar Secuencia",
    "EXECUTE SEQUENCE": "EJECUTAR SECUECNIA",
    "Factory Reset": "Restauración de fábrica",
    "Farm Events": "Farm Events",
    "FIRMWARE": "FIRMWARE",
    "Forgot Password": "Olvidar contraseña",
    "GO": "IR",
    "I Agree to the Terms of Service": "Estoy de acuerdo con los Términos del Servicio",
    "I agree to the terms of use": "Estoy de acuerdo con los términos de uso",
    "If Statement": "If Statement",
    "IF STATEMENT": "IF STATEMENT",
    "Import coordinates from": "Importar coordenadas desde",
    "initiating connection": "iniciando conexión",
    "INVERT ENDPOINTS": "INVERT ENDPOINTS",
    "INVERT MOTORS": "INVENTIR MOTORES",
    "LENGTH (m)": "LONGITUD (m)",
    "Location": "Localización",
    "Login": "Login",
    "Logout": "Logout",
    "Message": "Mensage",
    "Move Absolute": "Mover Absoluto",
    "MOVE ABSOLUTE": "MOVER ABSOLUTO",
    "MOVE AMOUNT (mm)": "MOVER CANTIDAD (mm)",
    "Move Relative": "Mover Relativo",
    "MOVE RELATIVE": "MOVER RELATIVO",
    "NAME": "NOMBRE",
    "NETWORK": "RED",
    "never connected to device": "nunca se conectó al dispositivo",
    "New Password": "Nueva Contraseña",
    "no": "no",
    "Not Connected to bot": "No Conectado al bot",
    "Old Password": "Última Contraseña",
    "Operator": "Operador",
    "Package Name": "Nombre del Paquete",
    "Parameters": "Parámetros",
    "Password": "Contraseña",
    "Pin {{num}}": "Pin {{num}}",
    "Pin Mode": "Modo Pin",
    "Pin Number": "Número Pin",
    "Plant Info": "Información de la Planta",
    "Plants": "Plantas",
    "Problem Loading Terms of Service": "Problemas Cargando los Términos del Servicio",
    "Read Pin": "Leer Pin",
    "READ PIN": "LEER PIN",
    "Regimen Name": "Regimen Name",
    "Regimens": "Regimens",
    "Repeats Every": "Repetir Cada",
    "Request sent": "Enviar petición",
    "Reset": "Reiniciar",
    "RESET": "REINICIAR",
    "Reset Password": "Reiniciar Password",
    "Reset your password": "Reinicia tu contraseña",
    "RESTART": "VOLVER A INICIAR",
    "RESTART FARMBOT": "VOLVER A INICIAR FARMBOT",
    "Save": "Guarda",
    "SAVE": "GUARDAR",
    "Send Message": "Enviar Mensaje",
    "SEND MESSAGE": "ENVIAR MENSAJE",
    "Send Password reset": "Enviar reinicio de Contraseña",
    "Sequence": "Secuencia",
    "Sequence Editor": "Editor de Secuencia",
    "Sequence or Regimen": "Sequence or Regimen",
    "Sequences": "Secuencias",
    "Server Port": "Puerto del Servidor",
    "Server URL": "URL del Servidor",
    "SHUTDOWN": "APAGAR",
    "SHUTDOWN FARMBOT": "APAGAR FARMBOT",
    "SLOT": "SLOT",
    "Socket Connection Established": "Conexión con el Socket Establecida",
    "Speed": "Velocidad",
    "Started": "Iniciado",
    "Starts": "Inicios",
    "STATUS": "ESTADO",
    "Steps per MM": "Passos para MM",
    "Sync Required": "Sincronización Requerida",
    "Take a Photo": "Tomar una Foto",
    "Take Photo": "Tomar Foto",
    "TAKE PHOTO": "TOMAR FOTO",
    "TEST": "PRUEBA",
    "Time": "Tiempo",
    "Time in milliseconds": "Tiempo en milisegundos",
    "TIMEOUT AFTER (seconds)": "TIMEOUT DESPUES DE (segundos)",
    "TOOL": "HERRAMIENTAS",
    "TOOL NAME": "NOMBRE DE LA HERRAMIENTA",
    "TOOLBAY NAME": "TOOLBAY NAME",
    "Tried to delete Farm Event": "Se intentó eliminar el Farm Event",
    "Tried to delete plant": "Se intentó eliminar la planta",
    "Tried to save Farm Event": "Se intentó guardar el Farm Event",
    "Tried to save plant": "Se intentó guardar la planta",
    "Tried to update Farm Event": "Se intentó actualizar Farm Event",
    "Unable to delete sequence": "No se pudo eliminar la secuencia",
    "Unable to download device credentials": "No se pudieron descargar las credenciales del dispositivo",
    "Until": "HASTA",
    "UP TO DATE": "ACTUALIZADO",
    "UPDATE": "ACTUALIZAR",
    "Value": "Valor",
    "Variable": "Variable",
    "Verify Password": "Verificar Contraseña",
    "Version": "Version",
    "Wait": "Esperar",
    "WAIT": "ESPERAR",
    "Weed Detector": "Detector de Hierba",
    "Week": "Semana",
    "Write Pin": "Escribir Pin",
    "WRITE PIN": "ESCRIBIR PIN",
    "X": "X",
    "X (mm)": "X (mm)",
    "X AXIS": "EJE X",
    "Y": "Y",
    "Y (mm)": "Y (mm)",
    "Y AXIS": "EJE Y",
    "yes": "yes",
    "Your Name": "Tu nombre",
    "Z": "Z",
    "Z (mm)": "Z (mm)",
    "Z AXIS": "EJE Z",
    "Day {{day}}": "Día {{day}}",
    "Enter Password": "Introducir Contraseña"
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mycroft.Cmd.Msg;

namespace Mycroft.Tests.Cmd.Msg
{
    [TestClass]
    public class TestMsgCommand
    {
        [TestMethod]
        public void TestMethod1()
        {

        }
    }
}


text:
describe('Clique.browser', function(){
	var _c = window.Clique;

	describe('#loaded', function() {
		it('Browser is saved as a component', function() {
			_c.components.should.have.property('browser');
		});
	});

	describe('#instatiation', function() {
		it('Browser is booted', function() {
			console.log(_c.components);
			_c.components.browser.booted.should.be.true;
		});
	});

	describe('#methods', function() {
		it('Should have method `boot`', function() {
			var obj = _c.components.browser;
			obj.prototype.boot.should.be.a.Function;
		});
		it('Should have method `init`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `getProperties`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `test`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `exec`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `uamatches`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `version`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `detectDevice`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `detectScreen`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `detectTouch`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `detectOS`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `detectBrowser`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `detectLanguage`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `detectPlugins`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `detectSupport`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `addClasses`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
		it('Should have method `removeClasses`', function() {
			var obj = _c.components.browser;
			obj.prototype.init.should.be.a.Function;
		});
	});

});


text:
<?php

namespace ZendTest\Http\Header;

use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\WWWAuthenticate;

class WWWAuthenticateTest extends TestCase
{
    public function testWWWAuthenticateFromStringCreatesValidWWWAuthenticateHeader()
    {
        $wWWAuthenticateHeader = WWWAuthenticate::fromString('WWW-Authenticate: xxx');
        $this->assertInstanceOf(HeaderInterface::class, $wWWAuthenticateHeader);
        $this->assertInstanceOf(WWWAuthenticate::class, $wWWAuthenticateHeader);
    }

    public function testWWWAuthenticateGetFieldNameReturnsHeaderName()
    {
        $wWWAuthenticateHeader = new WWWAuthenticate();
        $this->assertEquals('WWW-Authenticate', $wWWAuthenticateHeader->getFieldName());
    }

    public function testWWWAuthenticateGetFieldValueReturnsProperValue()
    {
        $this->markTestIncomplete('WWWAuthenticate needs to be completed');

        $wWWAuthenticateHeader = new WWWAuthenticate();
        $this->assertEquals('xxx', $wWWAuthenticateHeader->getFieldValue());
    }

    public function testWWWAuthenticateToStringReturnsHeaderFormattedString()
    {
        $this->markTestIncomplete('WWWAuthenticate needs to be completed');

        $wWWAuthenticateHeader = new WWWAuthenticate();

        // @todo set some values, then test output
        $this->assertEmpty('WWW-Authenticate: xxx', $wWWAuthenticateHeader->toString());
    }

    /** Implementation specific tests here */

    /**
     * @see http://en.wikipedia.org/wiki/HTTP_response_splitting
     * @group ZF2015-04
     */
    public function testPreventsCRLFAttackViaFromString()
    {
        $this->expectException(InvalidArgumentException::class);
        $header = WWWAuthenticate::fromString("WWW-Authenticate: xxx\r\n\r\nevilContent");
    }

    /**
     * @see http://en.wikipedia.org/wiki/HTTP_response_splitting
     * @group ZF2015-04
     */
    public function testPreventsCRLFAttackViaConstructor()
    {
        $this->expectException(InvalidArgumentException::class);
        $header = new WWWAuthenticate("xxx\r\n\r\nevilContent");
    }
}


text:
package com.joyfulmath.agileexample.principle.singletheroy;

/**
 * @author deman.lu
 * @version on 2016-05-25 14:16
 */
public interface IConnect {
    void dial(String a);
    void handleup(int id);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DocumentClassification.Classification
{
    public class DecisionNode : DNode
    {
        public int Index;
        public double Value;
        public DNode LeftChild;
        public DNode RightChild;

        public DecisionNode( int Index, double Value )
        {
            this.Index = Index;
            this.Value = Value;
        }

        public DecisionNode(List<LabeledDocumentVector> TrainingData)
        {
            Dictionary<string, int> LabelCount = GetLabelCount(TrainingData);
            double Entropy = GetEntropy(LabelCount, TrainingData.Count );

            int features = TrainingData[0].Document.Vector.Length;
            int samples = 100;  //for 0 and 1 only, choose 1 sample

            int feature = -1;
            double max = double.MinValue;
            double value = -1;
            //cached values to prevent multiple calculations on the same object
            List<LabeledDocumentVector> LeftCandidateData = null;
            List<LabeledDocumentVector> RightCandidateData = null;
            double left_cand_entropy = -1;
            double right_cand_entropy = -1;

            //calculate maximum information gain
            for (int i = 0; i < features; i++)
            {
                for (int j = 1; j < samples; j++)
                {
                    double val = (double) j / (samples*10);
                    List<LabeledDocumentVector>[] Children = Filter(TrainingData, val, i);

                    List<LabeledDocumentVector> Left = Children[0];
                    List<LabeledDocumentVector> Right = Children[1];

                    double left_entropy = GetEntropy(Left);
                    double right_entropy = GetEntropy(Right);

                    double expect_entropy = (Left.Count / TrainingData.Count) * left_entropy +
                                            (Right.Count / TrainingData.Count) * right_entropy;

                    double info_gain = Entropy - expect_entropy;
                    if (info_gain > max)
                    {
                        max = info_gain;
                        feature = i;
                        value = val;
                        LeftCandidateData = Left;
                        RightCandidateData = Right;
                        left_cand_entropy = left_entropy;
                        right_cand_entropy = right_entropy;
                    }
                }
            }

            this.Index = feature;
            this.Value = value;

            if (left_cand_entropy > 0)
                LeftChild = new DecisionNode(LeftCandidateData);
            else
                LeftChild = new DLeafNode(LeftCandidateData[0].Classification);

            if (right_cand_entropy > 0)
                RightChild = new DecisionNode(RightCandidateData);
            else
                RightChild = new DLeafNode(RightCandidateData[0].Classification);
        }

        public string Decision(DocumentVector vector)
        {
            if (vector.Vector[Index] < Value)
                return LeftChild.Decision(vector);
            else
                return RightChild.Decision(vector);
        }

        private List<LabeledDocumentVector>[] Filter(List<LabeledDocumentVector> TrainingData, double value, int feature)
        {
            List<LabeledDocumentVector> Left = new List<LabeledDocumentVector>();
            List<LabeledDocumentVector> Right = new List<LabeledDocumentVector>();

            foreach (LabeledDocumentVector Document in TrainingData)
            {
                if (Document.Document.Vector[feature] < value)
                    Left.Add(Document);
                else
                    Right.Add(Document);
            }

            return new List<LabeledDocumentVector>[2]{ Left, Right };
        }

        private double GetEntropy(Dictionary<string, int> LabelCount, int Documents )
        {
            double total = 0;
            foreach( KeyValuePair<string,int> pair in LabelCount )
            {
                double p = (double) pair.Value/Documents;
                total += p * Math.Log(p);
            }

            return -1 * total;
        }

        private double GetEntropy( List<LabeledDocumentVector> Data )
        {
            Dictionary<string, int> LabelCount = GetLabelCount(Data);
            return GetEntropy(LabelCount, Data.Count);
        }

        private Dictionary<string, int> GetLabelCount(List<LabeledDocumentVector> Data)
        {
            Dictionary<string, int> LabelCount = new Dictionary<string, int>();

            for (int i = 0; i < Data.Count; i++)
            {
                if (!LabelCount.ContainsKey(Data[i].Classification))
                    LabelCount[Data[i].Classification] = 0;

                LabelCount[Data[i].Classification]++;
            }

            return LabelCount;
        }
    }
}


text:
package org.infinispan.loaders.hbase.configuration;

import static org.infinispan.commons.util.StringPropertyReplacer.replaceProperties;

import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;

import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.LoadersConfigurationBuilder;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ConfigurationParser;
import org.infinispan.configuration.parsing.Namespace;
import org.infinispan.configuration.parsing.ParseUtils;
import org.infinispan.configuration.parsing.Parser52;
import org.infinispan.configuration.parsing.XMLExtendedStreamReader;

/**
 *
 * HBaseCacheStoreConfigurationParser52.
 *
 * @author Tristan Tarrant
 * @since 5.2
 */
@Namespace(uri = "urn:infinispan:config:hbase:5.2", root = "hbaseStore")
public class HBaseCacheStoreConfigurationParser52 implements ConfigurationParser {

   public HBaseCacheStoreConfigurationParser52() {
   }

   @Override
   public void readElement(final XMLExtendedStreamReader reader, final ConfigurationBuilderHolder holder) throws XMLStreamException {
      ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();

      Element element = Element.forName(reader.getLocalName());
      switch (element) {
      case HBASE_STORE: {
         parseHBaseStore(reader, builder.loaders(), holder.getClassLoader());
         break;
      }
      default: {
         throw ParseUtils.unexpectedElement(reader);
      }
      }
   }

   private void parseHBaseStore(final XMLExtendedStreamReader reader, LoadersConfigurationBuilder loadersBuilder, ClassLoader classLoader) throws XMLStreamException {
      HBaseCacheStoreConfigurationBuilder builder = new HBaseCacheStoreConfigurationBuilder(loadersBuilder);
      parseHBaseStoreAttributes(reader, builder);

      while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) {
         Parser52.parseCommonStoreChildren(reader, builder);
      }
      loadersBuilder.addStore(builder);
   }

   private void parseHBaseStoreAttributes(XMLExtendedStreamReader reader, HBaseCacheStoreConfigurationBuilder builder) throws XMLStreamException {
      for (int i = 0; i < reader.getAttributeCount(); i++) {
         ParseUtils.requireNoNamespaceAttribute(reader, i);
         String value = replaceProperties(reader.getAttributeValue(i));
         Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
         switch (attribute) {
         case AUTO_CREATE_TABLE: {
            builder.autoCreateTable(Boolean.parseBoolean(value));
            break;
         }
         case ENTRY_COLUMN_FAMILY: {
            builder.entryColumnFamily(value);
            break;
         }
         case ENTRY_TABLE: {
            builder.entryTable(value);
            break;
         }
         case ENTRY_VALUE_FIELD: {
            builder.entryValueField(value);
            break;
         }
         case EXPIRATION_COLUMN_FAMILY: {
            builder.expirationColumnFamily(value);
            break;
         }
         case EXPIRATION_TABLE: {
            builder.expirationTable(value);
            break;
         }
         case EXPIRATION_VALUE_FIELD: {
            builder.expirationValueField(value);
            break;
         }
         case HBASE_ZOOKEEPER_QUORUM_HOST: {
            builder.hbaseZookeeperQuorumHost(value);
            break;
         }
         case HBASE_ZOOKEEPER_CLIENT_PORT: {
            builder.hbaseZookeeperClientPort(Integer.parseInt(value));
            break;
         }
         case KEY_MAPPER: {
            builder.keyMapper(value);
            break;
         }
         case SHARED_TABLE: {
            builder.sharedTable(Boolean.parseBoolean(value));
            break;
         }
         default: {
            Parser52.parseCommonStoreAttributes(reader, i, builder);
            break;
         }
         }
      }
   }
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: degola
 * Date: 24.02.13
 * Time: 16:08
 * To change this template use File | Settings | File Templates.
 */

namespace slc\MVC;

class Router_Driver_Redirect extends Router_Driver {
    /**
     * @var Router_Driver
     */
    private $originalRouter;
	protected function parseRoute() {
		$QueryString = $this->getQueryString();
		if(isset($QueryString["View"])) {
			if($result = $this->findControllerAndViewByRouteString($QueryString["View"])) {
				$this->setController($result->FilePath, $result->Class);
				$this->setView((object)array(
					'View' => $result->View,
					'Path' => $result->ViewPath,
				));
				if(isset($QueryString["Arguments"]))
					$this->setViewArguments($QueryString["Arguments"]);
				return true;
			}
		}
		return false;
	}
    public function setOriginalRouterDriver(Router_Driver $router) {
        $this->originalRouter = $router;
        return $this;
    }
    public function link($link, array $arguments = null, $includeDomain = false) {
        if($this->originalRouter instanceof Router_Driver) {
            return $this->originalRouter->link($link, $arguments, $includeDomain);
        }
        throw new Router_Driver_Exception('ORIGINAL_ROUTER_DRIVER_NOT_SET', array());
    }
}

?>


text:
import os
import json
from enum import IntEnum
from enum import unique
import paddle

@unique
class DeviceType(IntEnum):
    UNKNOWN = 0
    CPU = 1
    GPU = 2
    XPU = 3
    NPU = 4
    DCU = 5
    NIC = 6

@unique
class LinkType(IntEnum):
    UNKNOWN = 0
    LOC = 1
    SYS = 2
    PHB = 3
    PIX = 4
    PIB = 5
    NVL = 6
    NVB = 7
    NET = 8

class Device:
    NON_ACCELERATOR_TYPE = [DeviceType.CPU, DeviceType.NIC, DeviceType.UNKNOWN]

    def __init__(self, global_id, local_id, machine):
        self._global_id = global_id
        self._local_id = local_id
        self._machine = machine
        self._type = None
        # Different device have different models, such as
        # "Tesla V100-SXM2-32GB" and "A100-SXM4-40GB" etc.
        self._model = None
        # Double precision GFLOPS
        self._dp_gflops = None
        # Single precision GFLOPS
        self._sp_gflops = None
        # Memory is stored by GB
        self._memory = None

    @property
    def global_id(self):
        return self._global_id

    @global_id.setter
    def global_id(self, value):
        self._global_id = value

    @property
    def local_id(self):
        return self._local_id

    @local_id.setter
    def local_id(self, value):
        self._local_id = value

    @property
    def machine(self):
        return self._machine

    @machine.setter
    def machine(self, value):
        self._machine = value

    @property
    def type(self):
        return self._type

    @type.setter
    def type(self, value):
        self._type = value

    @property
    def model(self):
        return self._model

    @model.setter
    def model(self, value):
        self._model = value

    @property
    def dp_gflops(self):
        return self._dp_gflops

    @dp_gflops.setter
    def dp_gflops(self, value):
        self._dp_gflops = value

    @property
    def sp_gflops(self):
        return self._sp_gflops

    @sp_gflops.setter
    def sp_gflops(self, value):
        self._sp_gflops = value

    @property
    def memory(self):
        return self._memory

    @memory.setter
    def memory(self, value):
        self._memory = value

    def __str__(self):
        str = ""
        str += "global_id: {}, local_id: {}, machine_id: {}, type: {}, model: {}, dp_flops: {}, sp_flops: {}, memory: {}".format(
            self.global_id,
            self.local_id,
            self.machine.id,
            self.type.name,
            self.model,
            self.dp_gflops,
            self.sp_gflops,
            self.memory,
        )
        return str

    def __repr__(self):
        return self.__str__()

class Link:

    default_hop = 1
    default_nic_bandwidth = 24

    def __init__(self, source, target):
        self._src = source
        self._tgt = target
        self._type = None
        # bandwidth is stored by GB/s
        self._bandwidth = None
        # latency is stored by millisecond
        self._latency = None
        self._hop = None

    @property
    def source(self):
        return self._src

    @source.setter
    def source(self, value):
        self._source = value

    @property
    def target(self):
        return self._tgt

    @target.setter
    def target(self, value):
        self._target = value

    @property
    def type(self):
        return self._type

    @type.setter
    def type(self, value):
        self._type = value

    @property
    def bandwidth(self):
        return self._bandwidth

    @bandwidth.setter
    def bandwidth(self, value):
        self._bandwidth = value

    @property
    def latency(self):
        return self._latency

    @latency.setter
    def latency(self, value):
        self._latency = value

    @property
    def hop(self):
        return self._hop

    @hop.setter
    def hop(self, value):
        self._hop = value

    def __str__(self):
        str = ""
        str += "source_global_id: {}, target_global_id: {}, type: {}, bandwidth: {}, latency: {}".format(
            self.source.global_id,
            self.target.global_id,
            self.type,
            self.bandwidth,
            self.latency,
        )
        return str

    def __repr__(self):
        return self.__str__()

class Machine:
    def __init__(self, id):
        self._id = id
        self._hostname = None
        self._addr = None
        self._port = None
        self._devices = {}
        self._links = {}
        self._accelerators = {}
        self._non_accelerator_cumulative_count = 0

    @property
    def id(self):
        return self._id

    @id.setter
    def id(self, value):
        self._id = value

    @property
    def hostname(self):
        return self._hostname

    @hostname.setter
    def hostname(self, value):
        self._hostname = value

    @property
    def addr(self):
        return self._addr

    @addr.setter
    def addr(self, value):
        self._addr = value

    @property
    def port(self):
        return self._port

    @port.setter
    def port(self, value):
        self._port = value

    @property
    def devices(self):
        return self._devices

    @property
    def links(self):
        return self._links

    @property
    def accelerators(self):
        return self._accelerators

    def add_device(self, device):
        # Use the device global_id as the key
        self._devices[device.global_id] = device
        if device.type not in Device.NON_ACCELERATOR_TYPE:
            self._accelerators[device.global_id] = device

    def add_link(self, link):
        # Use the source device global_id and target device global_id as the key
        self._links[(link.source.global_id, link.target.global_id)] = link

    def get_link(self, source_global_id, target_global_id):
        return self._links.get((source_global_id, target_global_id), None)

    def __str__(self):
        str = ""
        for device in self.devices.values():
            str += ", device: {}".format(device)
        for link in self.links.values():
            str += ", link: {}".format(link)
        return str

    def __repr__(self):
        return self.__str__()

class AlphaLatency:
    def __init__(self, alpha_latency):
        assert isinstance(alpha_latency, dict)
        self._base = alpha_latency.get("base", None)
        self._inter = alpha_latency.get("inter", None)
        self._intra = alpha_latency.get("intra", None)
        self._switch = alpha_latency.get("switch", None)
        if self._switch is not None:
            try:
                self._switch = float(self._switch)
            except:
                raise TypeError("The switch latency must be float")
        self._base_ring = (
            self._base.get("ring", None) if self._base is not None else None
        )
        self._base_tree = (
            self._base.get("tree", None) if self._base is not None else None
        )
        self._base_inter = (
            self._base.get("inter", None) if self._base is not None else None
        )
        if self._base_ring is not None:
            try:
                self._base_ring = float(self._base_ring)
            except:
                raise TypeError("The base ring latency must be float.")
        if self._base_tree is not None:
            try:
                self._base_tree = float(self._base_tree)
            except:
                raise TypeError("The base ring latency must be float.")

        self._inter_ring = self._inter.get("ring", None)
        self._inter_tree = self._inter.get("tree", None)
        self._intra_ring = self._intra.get("ring", None)
        self._intra_tree = self._intra.get("tree", None)

        if self._inter_ring is not None:
            if isinstance(self._inter_ring, str):
                assert self._inter_ring in ["NET"]
                self._inter_ring = LinkType[self._inter_ring]
            else:
                try:
                    self._inter_ring = float(self._inter_ring)
                except:
                    raise TypeError("The inter ring latency must be float.")

        if self._inter_tree is not None:
            if isinstance(self._inter_tree, str):
                assert self._inter_tree in ["NET"]
                self._inter_tree = LinkType[self._inter_tree]
            else:
                try:
                    self._inter_tree = float(self._inter_tree)
                except:
                    raise TypeError("The inter tree latency must be float.")

        if self._intra_ring is not None:
            if isinstance(self._intra_ring, str):
                assert self._intra_ring in ["NVL", "PHB"]
                self._intra_ring = LinkType[self._intra_ring]
            else:
                try:
                    self._intra_ring = float(self._intra_ring)
                except:
                    raise TypeError("The intra ring latency must be float.")

        if self._intra_tree is not None:
            if isinstance(self._intra_tree, str):
                assert self._intra_tree in ["NVL", "PHB"]
                self._intra_tree = LinkType[self._intra_tree]
            else:
                try:
                    self._intra_tree = float(self._intra_tree)
                except:
                    raise TypeError("The intra tree latency must be float.")

    @property
    def base_ring(self):
        return self._base_ring

    @property
    def base_tree(self):
        return self._base_tree

    @property
    def switch(self):
        return self._switch

    @property
    def inter_ring(self):
        return self._inter_ring

    @property
    def inter_tree(self):
        return self._inter_tree

    @property
    def intra_ring(self):
        return self._intra_ring

    @property
    def intra_tree(self):
        return self._intra_tree

class Cluster:
    """
    The cluster is an abstract of the hardware resource for training, which contains the cluster topology and
    related hardware information. It will serve the task mapping, cost model and auto searching.
    """

    def __init__(self):
        # Used to compute machine id
        self._num_machines = 0
        # Store all machines within the cluster
        self._machines = {}
        # Cluster graph topology
        self._topology = None
        # Latency for communication cost model
        self._alpha_latency = None
        self._rank_to_device_id = {}
        self._device_id_to_rank = {}
        # This property only be valid when the cluster consists of machines,
        # which have the same number accelerators.
        self._num_devices_per_machine = None

    def gen_default_config_cluster(
        self,
        gpu_model="V100",
        cpu_model="6271C",
        node_count=1,
        device_count=1,
        gpu_memory=32,
        cpu_memory=503,
        inter_bandwidth=24,
        intra_bandwidth=235,
        gpu_dp_gflops=7800,
        gpu_sp_gflops=15700,
        cpu_dp_gflops=75,
        cpu_sp_gflops=150,
    ):
        """Generate cluster by default config."""
        gpu_models = ["V100", "A100", "H100", "A2", "A10", "A16", "A30", "A40"]
        xpu_models = ["XPU"]
        npu_models = ["NPU"]
        dcu_models = ["DCU"]
        all_gpu_models = gpu_models + xpu_models + npu_models + dcu_models
        assert gpu_model in all_gpu_models
        self._num_devices_per_machine = device_count

        def _convert_to_type(gpu_model):
            type = None
            if gpu_model in gpu_models:
                type = "GPU"
            elif gpu_model in xpu_models:
                type = "XPU"
            elif gpu_model in npu_models:
                type = "NPU"
            elif gpu_model in dcu_models:
                type = "DCU"
            assert type is not None

            return type

        def _convert_to_model(gpu_model, gpu_memory):
            model = None
            if gpu_model == "V100":
                model = "Tesla V100-SXM2-" + str(gpu_memory) + "GB"
            assert model is not None

            return model

        def _convert_to_cpu_info(cpu_model):
            arch, vendor, model = None, None, None
            if cpu_model == "6271C":
                arch = "x86_64"
                vendor = "GenuineIntel"
                model = "Intel(R) Xeon(R) Gold 6271C CPU @ 2.60G"
            elif cpu_model == "6148":
                arch = "x86_64"
                vendor = "GenuineIntel"
                model = "Intel(R) Xeon(R) Gold 6148 CPU @ 2.40G"
            assert arch is not None
            assert vendor is not None
            assert model is not None

            return arch, vendor, model

        cluster_info = {}
        cluster_info["machines"] = []
        global_id = 0
        global_id_to_device_type = {}
        global_id_to_node = {}
        # NOTE: It will support NPU, XPU, DCU models in the future, it is just a fake value now
        for i in range(node_count):
            machine = {}
            # NOTE: The hostname is host_0, host_1, ...
            machine["hostname"] = "host_" + str(i)
            # NOTE: The addr is localhost, if need actual addr, it should be reset manually
            machine["addr"] = "127.0.0.1"
            # NOTE: The port is a default value
            machine["port"] = 60009
            machine["links"] = []

            devices = []
            local_id = 0

            for j in range(device_count):
                device = {}
                global_id = global_id if i == 0 and j == 0 else global_id + 1

                local_id += 1
                type = _convert_to_type(gpu_model)
                model = _convert_to_model(gpu_model, gpu_memory)
                dp_gflops = gpu_dp_gflops
                sp_gflops = gpu_dp_gflops
                memory = gpu_memory

                device["global_id"] = global_id
                device["local_id"] = local_id
                device["type"] = type
                device["model"] = model
                device["memory"] = memory
                device["sp_gflops"] = sp_gflops
                device["dp_gflops"] = dp_gflops
                global_id_to_device_type[global_id] = type
                global_id_to_node[global_id] = i
                devices.append(device)

            # add cpu device and nic device, just one cpu
            cpu_device = {}
            arch, vendor, model = _convert_to_cpu_info(cpu_model)
            sp_gflops = cpu_sp_gflops
            dp_gflops = cpu_dp_gflops
            global_id += 1
            local_id = 0
            memory = cpu_memory
            type = "CPU"
            cpu_device["arch"] = arch
            cpu_device["vendor"] = vendor
            cpu_device["model"] = model
            cpu_device["sp_gflops"] = sp_gflops
            cpu_device["dp_gflops"] = dp_gflops
            cpu_device["global_id"] = global_id
            cpu_device["local_id"] = local_id
            cpu_device["memory"] = memory
            cpu_device["type"] = type
            global_id_to_node[global_id] = i
            global_id_to_device_type[global_id] = type
            devices.append(cpu_device)

            nic_device = {}
            global_id += 1

            # add NIC
            type = "NIC"
            width = 12.5
            ip = "127.0.0.1"
            local_id = 0
            nic_device["type"] = type
            nic_device["local_id"] = type
            nic_device["global_id"] = global_id
            global_id_to_device_type[global_id] = type
            global_id_to_node[global_id] = i
            devices.append(nic_device)
            machine["devices"] = devices
            cluster_info["machines"].append(machine)

        # build link
        for i in range(0, global_id + 1):
            for j in range(0, global_id + 1):
                if i == j:
                    continue
                node_id_i = global_id_to_node[i]
                node_id_j = global_id_to_node[j]
                device_type_i = global_id_to_device_type[i]
                device_type_j = global_id_to_device_type[j]
                link = {}
                source_global_id = i
                target_global_id = j
                link["source_global_id"] = source_global_id
                link["target_global_id"] = target_global_id
                # the same node and device_type, set intra_bandwidth, NVL
                if node_id_i == node_id_j and device_type_i == device_type_j:
                    link["type"] = "NVL"
                    link["bandwidth"] = intra_bandwidth
                else:
                    link["type"] = "PHB"
                    link["bandwidth"] = inter_bandwidth
                cluster_info["machines"][node_id_i]["links"].append(link)

        self._build_from_dict(cluster_info)

    @property
    def rank_to_device_id(self):
        return self._rank_to_device_id

    @property
    def device_id_to_rank(self):
        return self._device_id_to_rank

    @property
    def machines(self):
        return self._machines

    def add_machine(self, machine):
        assert isinstance(machine, Machine)
        self._machines[machine.id] = machine

        # map rank to device id and map device id to rank
        if machine.id != 0:
            prev_machine = self._machines[machine.id - 1]
            offset = prev_machine._non_accelerator_cumulative_count
            for global_id in machine.devices:
                if (
                    machine.devices[global_id].type
                    not in Device.NON_ACCELERATOR_TYPE
                ):
                    rank_id = global_id - offset
                    self._rank_to_device_id[rank_id] = global_id
                    self._device_id_to_rank[global_id] = rank_id
            machine._non_accelerator_cumulative_count = (
                len(machine.devices)
                - len(machine.accelerators)
                + prev_machine._non_accelerator_cumulative_count
            )
        else:
            for global_id in machine.devices:
                if (
                    machine.devices[global_id].type
                    not in Device.NON_ACCELERATOR_TYPE
                ):
                    rank_id = global_id
                    self._rank_to_device_id[rank_id] = global_id
                    self._device_id_to_rank[global_id] = rank_id
                    machine.accelerators[global_id] = machine.devices[global_id]
            machine._non_accelerator_cumulative_count = len(
                machine.devices
            ) - len(machine.accelerators)

    @property
    def alpha_latency(self):
        return self._alpha_latency

    def add_device(self, device):
        assert isinstance(device, Device)
        device.machine.add_device(device)

    def add_link(self, link):
        assert isinstance(link, Link)
        # Only add the link to the source machine
        link.source.machine.add_link(link)

    def get_device(self, device_global_id):
        device = None
        for machine in self.machines.values():
            if device_global_id in machine.devices.keys():
                device = machine.devices[device_global_id]
        return device

    def _build_from_dict(self, cluster_info):
        machines_info = cluster_info["machines"]
        for machine_info in machines_info:
            machine_id = self._generate_machine_id()
            machine = Machine(machine_id)
            machine.hostname = machine_info.get("hostname")
            machine.addr = machine_info.get("addr")
            machine.port = machine_info.get("port")
            devices_info = machine_info.get("devices", [])
            for device_info in devices_info:
                device_global_id = device_info.get("global_id")
                device_local_id = device_info.get("local_id")
                device = Device(device_global_id, device_local_id, machine)
                device_type = device_info.get("type", None)
                if device_type is not None:
                    device_type = DeviceType[device_type]
                else:
                    device_type = DeviceType.UNKNOWN
                device.type = device_type
                device.model = device_info.get("model", None)
                device.dp_gflops = float(device_info.get("dp_gflops", 0))
                device.sp_gflops = float(device_info.get("sp_gflops", 0))
                device.memory = float(device_info.get("memory", 0))
                self.add_device(device)
            self.add_machine(machine)
        for machine_info in machines_info:
            links_info = machine_info.get("links", [])
            for link_info in links_info:
                source_global_id = link_info.get("source_global_id")
                target_global_id = link_info.get("target_global_id")
                source = self.get_device(source_global_id)
                target = self.get_device(target_global_id)
                link = Link(source, target)
                link_type = link_info.get("type", None)
                if link_type is not None:
                    link_type = LinkType[link_type]
                else:
                    link_type = LinkType.UNKNOWN
                link.type = link_type
                link.bandwidth = float(link_info.get("bandwidth", 0))
                link.latency = float(link_info.get("latency", 0))
                link.hop = link_info.get("hop", None)
                if link.hop is None:
                    # Set the default of hop: If in the same machine, hop is 0. And if in the different machine, hop is 1.
                    source_machine = source.machine
                    target_machine = target.machine
                    if source_machine.id == target_machine.id:
                        link.hop = 0
                    else:
                        link.hop = Link.default_hop
                self.add_link(link)

        if "alpha_latency" in cluster_info:
            self._alpha_latency = AlphaLatency(
                cluster_info.get("alpha_latency")
            )
        else:
            self._alpha_latecy = None

    def build_from_file(self, json_file_path):
        with open(json_file_path) as json_file:
            cluster_info = json.load(json_file)
        self._build_from_dict(cluster_info)

    def _generate_machine_id(self):
        cur_machine_id = self._num_machines
        self._num_machines += 1
        return cur_machine_id

    def get_all_devices(self, device_type):
        devices = []
        for machine in self.machines.values():
            for device in machine.devices.values():
                if device.type == DeviceType[device_type]:
                    devices.append(device)
        return devices

    def get_beta(self, source_device_id, target_device_id):
        # beta means the time transferring a byte, us/B
        beta = None
        convert_base = 1000
        device = self.get_device(source_device_id)
        machine = device.machine
        link = machine.get_link(source_device_id, target_device_id)
        bandwidth = None
        # None means the source and target are not connected directly, set NIC in default
        if link is None:
            bandwidth = Link.default_nic_bandwidth
        else:
            bandwidth = link.bandwidth

        if bandwidth == 0.0:
            beta = 0
        else:
            beta = 1 / (bandwidth * (convert_base**3 / 10**6))

        return beta

    def get_hop(self, source_device_id, target_device_id):
        beta = None
        hop = None
        device = self.get_device(source_device_id)
        machine = device.machine
        link = machine.get_link(source_device_id, target_device_id)
        if link is not None:
            hop = link.hop
        else:
            hop = Link.default_hop
        return hop

    def cross_machine(self, device_ids):
        machine_ids = set()
        for device_id in device_ids:
            device = self.get_device(device_id)
            machine_id = device.machine.id
            machine_ids.add(machine_id)
        if len(machine_ids) == 1:
            return False
        else:
            return True

    def convert_rank_to_device_id(self, group_ranks):
        # group_ranks is global id of the rank in paddle
        # task will use all of machine in this cluster with accelerators in default
        device_ids = []
        for rank in group_ranks:
            device_ids.append(self.rank_to_device_id[rank])
        return device_ids

    def get_involved_machine_count(self, device_ids):
        machine_ids = set()
        for device_id in device_ids:
            device = self.get_device(device_id)
            machine_id = device.machine.id
            machine_ids.add(machine_id)
        count = len(machine_ids)
        assert count > 0
        return count

    def get_num_machines(self):
        return len(self._machines)

    def get_num_devices_per_machine(self):
        # Only return the number of accelerators of each machine.
        # All machines must has the same number of devices and same type of devices.
        assert self._num_devices_per_machine
        return self._num_devices_per_machine

    def __str__(self):
        str = ""
        for machine in self.machines.values():
            str += "machine: {}\n".format(machine)
        return str

    def __repr__(self):
        return self.__str__()

def get_default_cluster():
    cluster = Cluster()
    local_device_count = os.getenv("PADDLE_LOCAL_SIZE")
    if local_device_count is None:
        local_device_count = 1
    else:
        local_device_count = int(local_device_count)
    global_device_count = os.getenv("PADDLE_GLOBAL_SIZE")
    if global_device_count is None:
        node_count = 1
    else:
        global_device_count = int(global_device_count)
        assert global_device_count % local_device_count == 0
        node_count = int(global_device_count) // local_device_count
    print(
        "Node Count: ",
        node_count,
        "Local Device Size: ",
        local_device_count,
        "World size: ",
        paddle.distributed.get_world_size(),
        flush=True,
    )
    cluster.gen_default_config_cluster(
        node_count=node_count, device_count=local_device_count
    )
    return cluster


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.voltdb.SQLStmt (VoltDB Server APIs)</title>
<meta name="date" content="2013-12-09">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Class
org.voltdb.SQLStmt

Packages that use SQLStmt

Package
Description

org.voltdb

Main package for VoltDB contains public interfaces.

Uses of SQLStmt in org.voltdb

Methods in org.voltdb with parameters of type SQLStmt

Modifier and Type
Method and Description

void
VoltProcedure.voltQueueSQL(SQLStmt stmt,
            org.voltdb.Expectation expectation,
            Object... args)

Queue the SQL statement for execution with the specified argument list,
 and an Expectation describing the expected results.

void
VoltProcedure.voltQueueSQL(SQLStmt stmt,
            Object... args)

Queue the SQL statement for execution with the specified argument list.

Overview

Package

Class

Use

Tree

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes


text:
/* jshint node: true */

var RSVP = require('rsvp');
var readline = require('readline');

function askFor(params) {
  var rl = readline.createInterface({input: process.stdin, output: process.stdout});
  var output = {};

  var questions = params.map(function(param){
    var prompt = param[0];
    var key = param[1];
    return function(){
      return new RSVP.Promise(function(resolve) {
        rl.question(prompt, function(answer){
          output[key] = answer;
          resolve();
        });
      });
    };
  });

  function nextQuestion(){
    var q = questions.shift();
    if (!q) {
      return output;
    } else {
      return q().then(nextQuestion);
    }
  }

  return nextQuestion().finally(function(){
    rl.close();
  });
}

module.exports = askFor;


text:
.class final Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge$5;
.super Ljava/lang/Object;
.source ""

# interfaces
.implements Landroid/view/View$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge;->ˏ(Lo/ᔿ;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field private synthetic ˊ:Lo/ᔿ;

.field private synthetic ˋ:Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge;

# direct methods
.method constructor <init>(Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge;Lo/ᔿ;)V
    .locals 0

    .line 205
    iput-object p1, p0, Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge$5;->ˋ:Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge;

    iput-object p2, p0, Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge$5;->ˊ:Lo/ᔿ;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public final onClick(Landroid/view/View;)V
    .locals 7

    .line 209
    sget-object v0, Lo/Ꮮ;->ˏ:Lo/Ꮮ;

    invoke-static {v0}, Lo/ᒥ;->ˊ(Lo/Ꮮ;)V

    .line 210
    iget-object v0, p0, Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge$5;->ˊ:Lo/ᔿ;

    iget-object v0, v0, Lo/ᔿ;->ˏ:Ljava/lang/String;

    goto :goto_0

    :catchall_0
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/Throwable;->getCause()Ljava/lang/Throwable;

    move-result-object v0

    throw v0

    :goto_0
    :try_start_0
    const/4 v1, 0x1

    new-array v1, v1, [Ljava/lang/Object;

    const/4 v2, 0x0

    aput-object v0, v1, v2

    const-string v0, "o.\u1fd3"

    invoke-static {v0}, Lo/Ꮀ$Ɩ;->ィ(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    const-string v2, "\u02ca"

    const/4 v3, 0x1

    new-array v3, v3, [Ljava/lang/Class;

    const-class v4, Ljava/lang/String;

    const/4 v5, 0x0

    aput-object v4, v3, v5

    invoke-virtual {v0, v2, v3}, Ljava/lang/Class;->getMethod(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;

    move-result-object v0

    const/4 v2, 0x0

    invoke-virtual {v0, v2, v1}, Ljava/lang/reflect/Method;->invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 211
    const-string v0, "opponent"

    iget-object v1, p0, Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge$5;->ˊ:Lo/ᔿ;

    iget-object v1, v1, Lo/ᔿ;->ͺ:Ljava/lang/String;

    invoke-static {v0, v1}, Lo/ﺩ;->ˊ(Ljava/lang/String;Ljava/lang/String;)V

    .line 212
    new-instance v0, Landroid/content/Intent;

    iget-object v1, p0, Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge$5;->ˋ:Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge;

    invoke-virtual {v1}, Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge;->getContext()Landroid/content/Context;

    move-result-object v1

    const-class v2, Lcom/quizup/core/activities/VsActivity;

    invoke-direct {v0, v1, v2}, Landroid/content/Intent;-><init>(Landroid/content/Context;Ljava/lang/Class;)V

    .line 213
    move-object p1, v0

    const-string v1, "is_challenge"

    const/4 v2, 0x1

    invoke-virtual {v0, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Z)Landroid/content/Intent;

    .line 214
    iget-object v0, p0, Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge$5;->ˋ:Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge;

    invoke-virtual {v0}, Lcom/quizup/core/widgets/topicButton/challenge/TopicDrawerChallenge;->getContext()Landroid/content/Context;

    move-result-object v0

    invoke-virtual {v0, p1}, Landroid/content/Context;->startActivity(Landroid/content/Intent;)V

    .line 216
    goto :goto_1

    :catchall_1
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/Throwable;->getCause()Ljava/lang/Throwable;

    move-result-object v0

    throw v0

    :goto_1
    :try_start_1
    const-string v0, "o.\u1ec8"

    invoke-static {v0}, Lo/Ỉ$ง;->ī(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    const-string v1, "\u02cb"

    const/4 v2, 0x0

    invoke-virtual {v0, v1, v2}, Ljava/lang/Class;->getMethod(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;

    move-result-object v0

    const/4 v1, 0x0

    const/4 v2, 0x0

    invoke-virtual {v0, v1, v2}, Ljava/lang/reflect/Method;->invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_1

    const-string v0, "o.\u1ec8"

    invoke-static {v0}, Lo/Ỉ$ง;->ī(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    const-string v2, "\u02cb"

    invoke-virtual {v0, v2}, Ljava/lang/Class;->getField(Ljava/lang/String;)Ljava/lang/reflect/Field;

    move-result-object v0

    const/4 v2, 0x0

    invoke-virtual {v0, v2}, Ljava/lang/reflect/Field;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    goto :goto_2

    :catchall_2
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/Throwable;->getCause()Ljava/lang/Throwable;

    move-result-object v0

    throw v0

    :goto_2
    :try_start_2
    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/Object;

    const/4 v3, 0x0

    aput-object v0, v2, v3

    const-string v0, "o.\u1ec8"

    invoke-static {v0}, Lo/Ỉ$ง;->ī(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    const-string v3, "equals"

    const/4 v4, 0x1

    new-array v4, v4, [Ljava/lang/Class;

    const-class v5, Ljava/lang/Object;

    const/4 v6, 0x0

    aput-object v5, v4, v6

    invoke-virtual {v0, v3, v4}, Ljava/lang/Class;->getMethod(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;

    move-result-object v0

    invoke-virtual {v0, v1, v2}, Ljava/lang/reflect/Method;->invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/Boolean;

    invoke-virtual {v0}, Ljava/lang/Boolean;->booleanValue()Z

    move-result v0
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_2

    if-eqz v0, :cond_0

    .line 218
    const-string v0, "o.\u216c"

    invoke-static {v0}, Lo/Ꮀ$Ɩ;->ィ(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    const-string v1, "\u02cc"

    invoke-virtual {v0, v1}, Ljava/lang/Class;->getField(Ljava/lang/String;)Ljava/lang/reflect/Field;

    move-result-object v0

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Ljava/lang/reflect/Field;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1

    const-string v0, "o.\u216c"

    invoke-static {v0}, Lo/Ꮀ$Ɩ;->ィ(Ljava/lang/String;)Ljava/lang/Class;

    move-result-object v0

    const-string v2, "\ufe73"

    invoke-virtual {v0, v2}, Ljava/lang/Class;->getField(Ljava/lang/String;)Ljava/lang/reflect/Field;

    move-result-object v0

    const/4 v2, 0x0

    invoke-virtual {v0, v2, v1}, Ljava/lang/reflect/Field;->set(Ljava/lang/Object;Ljava/lang/Object;)V

    .line 221
    :cond_0
    return-void
.end method


text:
module FootballBroadcaster
  class Engine < ::Rails::Engine
    isolate_namespace FootballBroadcaster

    config.generators do |g|
      g.test_framework :rspec, view_specs: false
    end
  end
end

require 'simple_form'
require 'responders'


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Text Test: text-align-last - left (basic)</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel="author" title="Shiyou Tan" href="mailto:shiyoux.tan@intel.com">
<link rel="help" title="7.2. Last Line Alignment: the 'text-align-last' property" href="http://www.w3.org/TR/css-text-3/#text-align-last">
<meta name="flags" content="">
<meta name="assert" content="The 'text-align-last' property set to 'left' on a block element aligns the last line text to the left.">

Test passes if the last line of "FillerText" below is aligned to the left, inside the blue box.

FillerText FillerText FillerText FillerText FillerText


text:
FactoryGirl.define do
  factory :user do
    password Devise.friendly_token[0, 20]
    email 'user@test.com'
    lastfm_name 'erikdstock'
    after(:create) do |user, _evaluator|
      create(:authentication, user: user)
    end

    # after(:build) { |u| u.class.skip_callback(:create, :after, :queue_initial_refresh) }

    # Create a user with only 5 plays so far. At the end of this month
    # (may 2016) it should be 12 plays.
    factory :user_with_stats do
      after(:create) do |user, _evaluator|
        artist = create :artist, name: 'MisterWives'
        create(:monthly_top_artist, artist: artist, play_count: 5, user: user, month: 1.month.ago)
      end
    end
  end

  # # user_with_posts will create post data after the user has been created
  # factory :user_with_stats do
  #   # posts_count is declared as a transient attribute and available in
  #   # attributes on the factory, as well as the callback via the evaluator
  #   transient do
  #     posts_count 5
  #   end
  #
  #   # the after(:create) yields two values; the user instance itself and the
  #   # evaluator, which stores all values from the factory, including transient
  #   # attributes; `create_list`'s second argument is the number of records
  #   # to create and we make sure the user is associated properly to the post
  #   after(:create) do |user, evaluator|
  #     create_list(:post, evaluator.posts_count, user: user)
  #   end
  # end
end


text:
package uk.co.ribot.easyadapterdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;

/**
 * Please go to {@link ListViewFragment} to see an example of using EasyAdapter with a ListView
 * or {@link RecyclerViewFragment} for an example with a RecyclerView.
 *
 * This class only has boilerplate code to set up the the tabs and the ViewPager.
 */
public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(new MyPageAdapter(getSupportFragmentManager()));
        mViewPager.setOnPageChangeListener(mPageChangeListener);
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar!= null) {
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            actionBar.addTab(actionBar
                    .newTab()
                    .setText(getString(R.string.tab_1_name))
                    .setTabListener(mTabListener));
            actionBar.addTab(actionBar
                    .newTab()
                    .setText(getString(R.string.tab_2_name))
                    .setTabListener(mTabListener));
        }
    }

    // Create a tab listener that is called when the user changes tabs.
    private ActionBar.TabListener mTabListener = new ActionBar.TabListener() {
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
            mViewPager.setCurrentItem(tab.getPosition());
        }

        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

        }

        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

        }
    };

    private ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setSelectedNavigationItem(position);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private class MyPageAdapter extends FragmentPagerAdapter {
        private MyPageAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 1) {
                return new RecyclerViewFragment();
            }
            return new ListViewFragment();
        }

        @Override
        public int getCount() {
            return 2;
        }

    }

}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <pthread.h>
#include <pami.h>
#include <hwi/include/bqc/A2_inlines.h>

#include "safemalloc.h"
#include "preamble.h"
#include "coll.h"

void dispatch_done_cb(pami_context_t context, void * cookie, pami_result_t result)
{
  free(cookie);
  printf("dispatch_done_cb \n");
  fflush(stdout);
  return;
}

void dispatch_recv_cb(pami_context_t context,
                      void * cookie,
                      const void * header_addr, size_t header_size,
                      const void * pipe_addr,
                      size_t data_size,
                      pami_endpoint_t origin,
                      pami_recv_t * recv)
{
  pami_result_t result = PAMI_ERROR;

  size_t task;
  size_t ctxoff;
  result = PAMI_Endpoint_query(origin, &task, &ctxoff);
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Endpoint_query");

  int * c = (int *) cookie;
  printf("dispatch_recv_cb: origin = (%ld,%ld) cookie = %d \n", task, ctxoff, *c);

  printf("dispatch_recv_cb: header_size = %ld \n", header_size);
  const long * h = header_addr;
  printf("dispatch_recv_cb: header_addr[] = %ld \n", *h);
  fflush(stdout);

  if (pipe_addr!=NULL)
  {
    printf("dispatch_recv_cb: immediate protocol \n");
    fflush(stdout);

    printf("dispatch_recv_cb: data_size = %ld \n", data_size);
    const char * p = pipe_addr;
    printf("dispatch_recv_cb: pipe_addr[] = %s \n", p);
    fflush(stdout);
  }
  else
  {
    printf("dispatch_recv_cb: asychronous protocol \n");
    printf("dispatch_recv_cb: data_size = %ld \n", data_size);
    fflush(stdout);

    char * buffer = safemalloc(data_size);

    recv->cookie      = buffer;
    recv->local_fn    = dispatch_done_cb;
    recv->addr        = buffer;
    recv->type        = PAMI_TYPE_BYTE;
    recv->offset      = 0;
    recv->data_fn     = PAMI_DATA_COPY;
    recv->data_cookie = NULL;
  }

  return;
}

int main(int argc, char* argv[])
{
  pami_result_t result = PAMI_ERROR;
  size_t world_size, world_rank;

  /* initialize the second client */
  char * clientname = "";
  pami_client_t client;
  result = PAMI_Client_create(clientname, &client, NULL, 0);
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Client_create");

  /* query properties of the client */
  pami_configuration_t config[3];
  size_t num_contexts;

  config[0].name = PAMI_CLIENT_NUM_TASKS;
  config[1].name = PAMI_CLIENT_TASK_ID;
  config[2].name = PAMI_CLIENT_NUM_CONTEXTS;
  result = PAMI_Client_query(client, config, 3);
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Client_query");
  world_size   = config[0].value.intval;
  world_rank   = config[1].value.intval;
  num_contexts = config[2].value.intval;
  TEST_ASSERT(num_contexts>1,"num_contexts>1");

  if (world_rank==0)
  {
    printf("hello world from rank %ld of %ld \n", world_rank, world_size );
    fflush(stdout);
  }

  /* initialize the contexts */
  contexts = (pami_context_t *) safemalloc( num_contexts * sizeof(pami_context_t) );

  result = PAMI_Context_createv( client, NULL, 0, contexts, num_contexts );
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Context_createv");

  /* setup the world geometry */
  pami_geometry_t world_geometry;
  result = PAMI_Geometry_world(client, &world_geometry );
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Geometry_world");

  int status = pthread_create(&Progress_thread, NULL, &Progress_function, NULL);
  TEST_ASSERT(status==0, "pthread_create");

  /************************************************************************/

  int n = (argc>1 ? atoi(argv[1]) : 1000);

  size_t bytes = n * sizeof(int);

  int *  local  = (int *) safemalloc(bytes);
  for (int i=0; i<n; i++)
    local[i] = world_rank;

  /* create the endpoint */
  int target = (world_rank>0 ? world_rank-1 : world_size-1);
  pami_endpoint_t target_ep;
  //result = PAMI_Endpoint_create(client, (pami_task_t) target, 0, &target_ep);
  result = PAMI_Endpoint_create(client, (pami_task_t) target, 1, &target_ep);
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Endpoint_create");

  /* register the dispatch function */
  pami_dispatch_callback_function dispatch_cb;
  size_t dispatch_id                 = 37;
  dispatch_cb.p2p                    = dispatch_recv_cb;
  pami_dispatch_hint_t dispatch_hint = {0};
  int dispatch_cookie                = 1000000+world_rank;
  /* setting this hint to "disable" will disable the pipe_addr!=NULL code path */
  //dispatch_hint.recv_immediate       = PAMI_HINT_DISABLE;
  result = PAMI_Dispatch_set(contexts[0], dispatch_id, dispatch_cb, &dispatch_cookie, dispatch_hint);
  result = PAMI_Dispatch_set(contexts[1], dispatch_id, dispatch_cb, &dispatch_cookie, dispatch_hint);
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Dispatch_set");

  /* make sure everything is ready */
  result = barrier(world_geometry, contexts[0]);
  TEST_ASSERT(result == PAMI_SUCCESS,"barrier");

  // The iovec structure describes a buffer. It contains two fields:
  // void *iov_base - Contains the address of a buffer.
  // size_t iov_len - Contains the length of the buffer.

  int header  = 37373;

  int active = 1;
  pami_send_t parameters;
  parameters.send.header.iov_base = &header;
  parameters.send.header.iov_len  = sizeof(int);
  parameters.send.data.iov_base   = local;
  parameters.send.data.iov_len    = bytes;
  parameters.send.dispatch        = dispatch_id;
  //parameters.send.hints           = ;
  parameters.send.dest            = target_ep;
  parameters.events.cookie        = &active;
  parameters.events.local_fn      = cb_done;
  parameters.events.remote_fn     = NULL;//cb_done;

  uint64_t t0 = GetTimeBase();

  result = PAMI_Send(contexts[0], &parameters);
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Send");

  while (active)
  {
    //result = PAMI_Context_advance( contexts[0], 100);
    //TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Context_advance");
    result = PAMI_Context_trylock_advancev(&(contexts[0]), 1, 1000);
    TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Context_trylock_advancev");
  }

  uint64_t t1 = GetTimeBase();
  uint64_t dt = t1-t0;

  /* barrier on non-progressing context to make sure CHT does its job */
  barrier(world_geometry, contexts[0]);

  printf("%ld: PAMI_Send of %ld bytes achieves %lf MB/s \n", (long)world_rank, bytes, 1.6e9*1e-6*(double)bytes/(double)dt );
  fflush(stdout);

  result = barrier(world_geometry, contexts[0]);
  TEST_ASSERT(result == PAMI_SUCCESS,"barrier");

  free(local);

  /************************************************************************/

  void * rv;

  status = pthread_cancel(Progress_thread);
  TEST_ASSERT(status==0, "pthread_cancel");

  status = pthread_join(Progress_thread, &rv);
  TEST_ASSERT(status==0, "pthread_join");

  result = barrier(world_geometry, contexts[0]);
  TEST_ASSERT(result == PAMI_SUCCESS,"barrier");

  /* finalize the contexts */
  result = PAMI_Context_destroyv( contexts, num_contexts );
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Context_destroyv");

  free(contexts);

  /* finalize the client */
  result = PAMI_Client_destroy( &client );
  TEST_ASSERT(result == PAMI_SUCCESS,"PAMI_Client_destroy");

  if (world_rank==0)
    printf("%ld: end of test \n", world_rank );
  fflush(stdout);

  return 0;
}


text:
package com.faforever.api.data.domain;

import com.faforever.api.data.checks.IsEntityOwner;
import com.faforever.api.data.checks.Prefab;
import com.yahoo.elide.annotation.CreatePermission;
import com.yahoo.elide.annotation.DeletePermission;
import com.yahoo.elide.annotation.Include;
import com.yahoo.elide.annotation.UpdatePermission;
import lombok.Setter;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Setter
@Include(name = "modVersionReview")
@Entity
@Table(name = "mod_version_review")
@CreatePermission(expression = Prefab.ALL)
@DeletePermission(expression = IsEntityOwner.EXPRESSION)
public class ModVersionReview extends Review {

  private ModVersion modVersion;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "mod_version_id")
  @UpdatePermission(expression = Prefab.ALL)
  public ModVersion getModVersion() {
    return modVersion;
  }
}


text:
class IdentityProcessor : public Processor {
  public:
    cv::Mat operator()(cv::Mat);
};

cv::Mat IdentityProcessor::operator()(cv::Mat im) {
  return im;
}

namespace {
  auto idProcReg = ProcessorRegister<IdentityProcessor>("Id");
}


text:
package org.locationtech.geowave.core.store.metadata;

import org.locationtech.geowave.core.store.BaseStoreFactory;
import org.locationtech.geowave.core.store.StoreFactoryHelper;
import org.locationtech.geowave.core.store.StoreFactoryOptions;
import org.locationtech.geowave.core.store.index.IndexStore;

public class IndexStoreFactory extends BaseStoreFactory<IndexStore> {

  public IndexStoreFactory(
      final String typeName,
      final String description,
      final StoreFactoryHelper helper) {
    super(typeName, description, helper);
  }

  @Override
  public IndexStore createStore(final StoreFactoryOptions options) {
    return new IndexStoreImpl(helper.createOperations(options), options.getStoreOptions());
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>statsmodels.genmod.families.links.nbinom — statsmodels 0.6.1 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="top" title="statsmodels 0.6.1 documentation" href="../index.html" />
    <link rel="up" title="Generalized Estimating Equations" href="../gee.html" />
    <link rel="next" title="statsmodels.genmod.families.links.nbinom.deriv" href="statsmodels.genmod.families.links.nbinom.deriv.html" />
<link rel="stylesheet" href="../../_static/facebox.css" type="text/css" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />

Navigation

          index

          next |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Generalized Estimating Equations |

statsmodels.genmod.families.links.nbinom¶

class statsmodels.genmod.families.links.nbinom(alpha=1.0)[source]¶

The negative binomial link function.

Notes

g(p) = log(p/(p + 1/alpha))

nbinom is an alias of NegativeBinomial.
nbinom = NegativeBinomial(alpha=1.)

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

deriv(p)
Derivative of the negative binomial transform

inverse(z)
Inverse of the negative binomial transform

inverse_deriv(z)
Derivative of the inverse of the negative binomial transform

Next topic

statsmodels.genmod.families.links.nbinom.deriv

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

        © Copyright 2009-2013, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.3.1.