text:
package tendermint

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path"

	"github.com/hyperledger/burrow/binary"
	"github.com/hyperledger/burrow/consensus/abci"
	"github.com/hyperledger/burrow/crypto"
	"github.com/hyperledger/burrow/genesis"
	"github.com/hyperledger/burrow/logging"
	"github.com/hyperledger/burrow/logging/structure"
	"github.com/tendermint/tendermint/config"
	"github.com/tendermint/tendermint/crypto/ed25519"
	"github.com/tendermint/tendermint/node"
	"github.com/tendermint/tendermint/p2p"
	"github.com/tendermint/tendermint/proxy"
	tmTypes "github.com/tendermint/tendermint/types"
	dbm "github.com/tendermint/tm-db"
)

// Serves as a wrapper around the Tendermint node's closeable resources (database connections)
type Node struct {
	*node.Node
	closers []interface {
		Close()
	}
}

func DBProvider(ID string, backendType dbm.DBBackendType, dbDir string) dbm.DB {
	return dbm.NewDB(ID, backendType, dbDir)
}

// Since Tendermint doesn't close its DB connections
func (n *Node) DBProvider(ctx *node.DBContext) (dbm.DB, error) {
	db := DBProvider(ctx.ID, dbm.DBBackendType(ctx.Config.DBBackend), ctx.Config.DBDir())
	n.closers = append(n.closers, db)
	return db, nil
}

func (n *Node) Close() {
	for _, closer := range n.closers {
		closer.Close()
	}
}

func NewNode(conf *config.Config, privValidator tmTypes.PrivValidator, genesisDoc *tmTypes.GenesisDoc,
	app *abci.App, metricsProvider node.MetricsProvider, logger *logging.Logger) (*Node, error) {

	var err error
	// disable Tendermint's RPC
	conf.RPC.ListenAddress = ""

	nodeKey, err := EnsureNodeKey(conf.NodeKeyFile())
	if err != nil {
		return nil, err
	}

	nde := &Node{}
	nde.Node, err = node.NewNode(conf, privValidator,
		nodeKey, proxy.NewLocalClientCreator(app),
		func() (*tmTypes.GenesisDoc, error) {
			return genesisDoc, nil
		},
		nde.DBProvider,
		metricsProvider,
		NewLogger(logger.WithPrefix(structure.ComponentKey, structure.Tendermint).
			With(structure.ScopeKey, "tendermint.NewNode")))
	if err != nil {
		return nil, err
	}
	app.SetMempoolLocker(nde.Mempool())
	return nde, nil
}

func DeriveGenesisDoc(burrowGenesisDoc *genesis.GenesisDoc, appHash []byte) *tmTypes.GenesisDoc {
	validators := make([]tmTypes.GenesisValidator, len(burrowGenesisDoc.Validators))
	for i, validator := range burrowGenesisDoc.Validators {
		validators[i] = tmTypes.GenesisValidator{
			PubKey: validator.PublicKey.TendermintPubKey(),
			Name:   validator.Name,
			Power:  int64(validator.Amount),
		}
	}
	consensusParams := tmTypes.DefaultConsensusParams()
	// This is the smallest increment we can use to get a strictly increasing sequence
	// of block time - we set it low to avoid skew
	// if the BlockTimeIota is longer than the average block time
	consensusParams.Block.TimeIotaMs = 1

	return &tmTypes.GenesisDoc{
		ChainID:         burrowGenesisDoc.ChainID(),
		GenesisTime:     burrowGenesisDoc.GenesisTime,
		Validators:      validators,
		AppHash:         appHash,
		ConsensusParams: consensusParams,
	}
}

func NewNodeInfo(ni p2p.DefaultNodeInfo) *NodeInfo {
	address, _ := crypto.AddressFromHexString(string(ni.ID()))
	return &NodeInfo{
		ID:            address,
		Moniker:       ni.Moniker,
		ListenAddress: ni.ListenAddr,
		Version:       ni.Version,
		Channels:      binary.HexBytes(ni.Channels),
		Network:       ni.Network,
		RPCAddress:    ni.Other.RPCAddress,
		TxIndex:       ni.Other.TxIndex,
	}
}

func NewNodeKey() *p2p.NodeKey {
	privKey := ed25519.GenPrivKey()
	return &p2p.NodeKey{
		PrivKey: privKey,
	}
}

func WriteNodeKey(nodeKeyFile string, key json.RawMessage) error {
	err := os.MkdirAll(path.Dir(nodeKeyFile), 0777)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(nodeKeyFile, key, 0600)
}

func EnsureNodeKey(nodeKeyFile string) (*p2p.NodeKey, error) {
	err := os.MkdirAll(path.Dir(nodeKeyFile), 0777)
	if err != nil {
		return nil, err
	}

	return p2p.LoadOrGenNodeKey(nodeKeyFile)
}


text:
busl - the bustle part of hustle.

a simple pubsub service that runs on Heroku.

## Usage

### Creating streams

create a stream:

```
$ export STREAM_ID=$(uuidgen)
$ curl http://localhost:5001/streams/$STREAM_ID -X PUT
# STREAM_ID=b7e586c8404b74e1805f5a9543bc516f
```

### Subscribe

connect a consumer using the stream id:

```
$ curl http://localhost:5001/streams/$STREAM_ID
...
```

#### Disconnections

Subscribers can sometimes get disconnected. If the instance is cycled or deployed for example.
When this happens, you can specify a `Range` header specifying which where your streaming stopped.

```
$ curl http://localhost:5001/streams/$STREAM_ID -H "Range: bytes=100-"
```

SSE connections also handle the `Last-Event-ID` header.

### Publish
in a separate terminal, produce some data using the same stream id...

```
$ curl -H "Transfer-Encoding: chunked" http://localhost:5001/streams/$STREAM_ID -X POST
```

...and you see the busl.

## Setup

to setup to test and run busl:

```sh
$ make setup
```

and ensure you have redis running.

## Test

to run tests:

```sh
$ make test
```

## Run

to run the server:

```sh
$ make web
```

## Deploy

[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

## Docker setup

```sh
# Start
$ docker-compose start

# Grab the host / port combination chosen by docker
$ export URL=$(docker-compose port web 5000)

# Check health status
$ curl $URL/health
OK
```

## Busltee

The busltee command allows streaming a command's logs to a busl stream.

### Building

```sh
make busltee
```

redpajama_set_name: RedPajamaGithub


text:
using DevLab.JmesPath.Utils;

namespace DevLab.JmesPath.Tokens
{
    internal sealed class RawStringToken : Token
    {
        private readonly string value_;

        public RawStringToken(string rawText)
            : base(TokenType.T_RSTRING, rawText)
        {
            System.Diagnostics.Debug.Assert(rawText.Length >= 2);
            System.Diagnostics.Debug.Assert(rawText.StartsWith("'"));
            System.Diagnostics.Debug.Assert(rawText.EndsWith("'"));

            value_ = StringUtil.UnwrapRawString(rawText);
        }

        public override object Value => value_;
    }
}


text:
import sys

from fabric.api import *
from fabric.contrib import *

from defaults import fab
from config import ssh, sudoers

import {%= name %}

# Tell Fabric which tasks are exported by this file
__all__ = ['deploy_config']

@task(default=True)
def deploy_config():
  print 'start here'


text:
import requests

with open('data/step03.txt', 'r') as f:
    url = f.readline().strip()

folder = 'https://stepic.org/media/attachments/course67/3.6.3/'
text = ''

while text[:2] != 'We':
    r = requests.get(url)
    text = r.text
    url = folder + text
    print(text)

print('--------------')
print('Thats all. Check "output/step03.text')

with open('output/step03.txt', 'w') as f:
    f.write(text)


text:
/*

        Creating a sprite from following images:

        test/images/irregular/irregular1.png (60x60)
        test/images/irregular/irregular2.png (16x16)
        test/images/irregular/irregular3.png (48x48)
        test/images/irregular/irregular4.png (34x14)
        test/images/irregular/irregular5.png (46x25)

        Output files:
          test/images/irregular.fixed.png
          test/images/irregular.fixed.css

        Output size:
          500x100

*/
img.fixed_irregular1 { width: 100px; height: 100px; background: url(irregular.fixed.png) 0px 0px no-repeat; }
img.fixed_irregular2 { width: 100px; height: 100px; background: url(irregular.fixed.png) -100px 0px no-repeat; }
img.fixed_irregular3 { width: 100px; height: 100px; background: url(irregular.fixed.png) -200px 0px no-repeat; }
img.fixed_irregular4 { width: 100px; height: 100px; background: url(irregular.fixed.png) -300px 0px no-repeat; }
img.fixed_irregular5 { width: 100px; height: 100px; background: url(irregular.fixed.png) -400px 0px no-repeat; }


text:
// This file implements logic for lowering MHLO dialect to SCF dialect.
#include <utility>

#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Casting.h"
#include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "mlir-hlo/Dialect/mhlo/transforms/PassDetail.h"
#include "mlir-hlo/Dialect/mhlo/transforms/passes.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"  // TF:llvm-project
#include "mlir/IR/Block.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/TypeRange.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassRegistry.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/DialectConversion.h"

namespace mlir {
namespace mhlo {
namespace {

// All transformations in this file take mhlo blocks which end with
// mhlo::ReturnOp and lower to SCF ops which end with scf::YieldOp. Inline an
// entire block with the only change being return -> yield.
void inlineMhloRegionIntoSCFRegion(PatternRewriter& rewriter, Region& mhlo,
                                   Region& scf) {
  // Remove an existing block, then move the region over.
  if (!scf.empty()) rewriter.eraseBlock(&scf.back());
  rewriter.inlineRegionBefore(mhlo, scf, scf.end());
  // Fix up the terminator.
  PatternRewriter::InsertionGuard guard(rewriter);
  rewriter.setInsertionPointToEnd(&scf.back());
  auto* terminator = scf.back().getTerminator();
  rewriter.replaceOpWithNewOp<scf::YieldOp>(terminator,
                                            terminator->getOperands());
}

// mhlo ops need inputs to be tensors, but scalar values can be a scalar tensor
// or a 1 element tensor. To handle this, collapse shape before extracting the
// scalar value when necessary.
Value extractTensorValue(OpBuilder& b, Value tensor) {
  auto loc = tensor.getLoc();
  if (tensor.getType().cast<TensorType>().hasRank() &&
      tensor.getType().cast<TensorType>().getRank() != 0) {
    tensor = b.create<tensor::CollapseShapeOp>(
        loc, tensor, SmallVector<ReassociationIndices>());
  }
  return b.create<tensor::ExtractOp>(loc, tensor, ValueRange());
}

// Create a memref descriptor given a pointer and memref type information.
struct WhileOpPattern : public OpConversionPattern<mhlo::WhileOp> {
  using OpConversionPattern<WhileOp>::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mhlo::WhileOp op, OpAdaptor adaptor,
      ConversionPatternRewriter& rewriter) const override {
    auto loc = op.getLoc();

    auto new_while_op = rewriter.create<scf::WhileOp>(loc, op.getResultTypes(),
                                                      adaptor.getOperands());

    // Inline while condition. The block is the same, except the boolean result
    // needs to be extracted and used with an scf.condition.
    rewriter.inlineRegionBefore(op.cond(), new_while_op.getBefore(),
                                new_while_op.getBefore().end());
    auto condition_return =
        cast<mhlo::ReturnOp>(new_while_op.getBefore().front().getTerminator());
    rewriter.setInsertionPointToEnd(&new_while_op.getBefore().front());
    Value i1 = extractTensorValue(rewriter, condition_return->getOperand(0));
    rewriter.replaceOpWithNewOp<scf::ConditionOp>(
        condition_return, i1, new_while_op.getBeforeArguments());

    // Inline while body, and only replace the mhlo.return with an scf.yield.
    inlineMhloRegionIntoSCFRegion(rewriter, op.body(), new_while_op.getAfter());

    rewriter.replaceOp(op, new_while_op.getResults());
    return success();
  }
};

// Create a memref descriptor given a pointer and memref type information.
struct IfOpPattern : public OpConversionPattern<mhlo::IfOp> {
  using OpConversionPattern<IfOp>::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mhlo::IfOp op, OpAdaptor adaptor,
      ConversionPatternRewriter& rewriter) const override {
    auto scf_if =
        rewriter.create<scf::IfOp>(op.getLoc(), op.getResultTypes(),
                                   extractTensorValue(rewriter, adaptor.pred()),
                                   /*withElseRegion=*/true);
    inlineMhloRegionIntoSCFRegion(rewriter, op.true_branch(),
                                  scf_if.getThenRegion());
    inlineMhloRegionIntoSCFRegion(rewriter, op.false_branch(),
                                  scf_if.getElseRegion());
    rewriter.replaceOp(op, scf_if.getResults());
    return success();
  }
};

// Create a memref descriptor given a pointer and memref type information.
struct CaseOpPattern : public OpConversionPattern<mhlo::CaseOp> {
  using OpConversionPattern<CaseOp>::OpConversionPattern;

  // Recursively create if/else ops to handle each possible value in a case op.
  scf::IfOp createNestedCases(int current_idx, CaseOp op, OpAdaptor adaptor,
                              PatternRewriter& outer_builder) const {
    Location loc = op.getLoc();
    Value idx_value = adaptor.index();
    auto final_idx = op.branches().size() - 2;

    // Determine if the current index matches the case index.
    auto scalar_type = idx_value.getType();
    auto const_attr = DenseElementsAttr::get(
        scalar_type,
        {outer_builder.getI32IntegerAttr(current_idx).cast<mlir::Attribute>()});
    Value current_idx_val = outer_builder.create<mhlo::ConstOp>(
        loc, idx_value.getType(), const_attr);
    auto eq_comparison = outer_builder.getStringAttr("EQ");

    auto scf_if = outer_builder.create<scf::IfOp>(
        loc, op.getResultTypes(),
        extractTensorValue(outer_builder,
                           outer_builder.create<mhlo::CompareOp>(
                               loc, idx_value, current_idx_val, eq_comparison)),
        /*withElseRegion=*/true);
    inlineMhloRegionIntoSCFRegion(outer_builder, op.branches()[current_idx],
                                  scf_if.getThenRegion());
    int next_idx = current_idx + 1;
    // Don't recurse for the final default block.
    if (current_idx == final_idx) {
      inlineMhloRegionIntoSCFRegion(outer_builder, op.branches()[next_idx],
                                    scf_if.getElseRegion());
    } else {
      PatternRewriter::InsertionGuard guard(outer_builder);
      outer_builder.setInsertionPointToEnd(&scf_if.getElseRegion().back());
      auto inner_if = createNestedCases(next_idx, op, adaptor, outer_builder);
      outer_builder.create<scf::YieldOp>(op.getLoc(), inner_if.getResults());
    }
    return scf_if;
  }

  LogicalResult matchAndRewrite(
      mhlo::CaseOp op, OpAdaptor adaptor,
      ConversionPatternRewriter& rewriter) const override {
    // Inline the op if there is only a default block.
    if (op.branches().size() == 1) {
      Block& block = op.branches().front().front();
      auto results = block.getTerminator()->getOperands();
      // Remove the mhlo.return terminator, then inline the block.
      rewriter.eraseOp(block.getTerminator());
      rewriter.mergeBlockBefore(/*source=*/&block, /*dest=*/op.getOperation(),
                                /*argValues=*/{});
      rewriter.replaceOp(op, results);
      return success();
    }

    // Begin recursion with case 0.
    rewriter.replaceOp(
        op, createNestedCases(0, op, adaptor, rewriter).getResults());
    return success();
  }
};

struct LegalizeControlFlowPass
    : public LegalizeControlFlowPassBase<LegalizeControlFlowPass> {
  // Perform the lowering to MLIR control flow.
  void runOnOperation() override {
    FuncOp f = getOperation();
    MLIRContext* ctx = f.getContext();

    RewritePatternSet patterns(&getContext());
    patterns.add<WhileOpPattern, IfOpPattern, CaseOpPattern>(&getContext());

    mlir::ConversionTarget target(*ctx);
    target.markUnknownOpDynamicallyLegal([](Operation*) { return true; });
    target.addIllegalOp<mhlo::IfOp, mhlo::WhileOp, mhlo::CaseOp>();

    if (failed(applyPartialConversion(f, target, std::move(patterns)))) {
      signalPassFailure();
    }
  }
};

}  // namespace
}  // namespace mhlo
}  // namespace mlir

std::unique_ptr<mlir::OperationPass<mlir::FuncOp>>
mlir::mhlo::createLegalizeControlFlowPass() {
  return std::make_unique<LegalizeControlFlowPass>();
}


text:
extern crate rlibc;
extern crate spin;
extern crate multiboot2;
#[macro_use]
mod vga_buffer;
mod memory;

#[no_mangle]
pub extern fn rust_main(multiboot_information_address: usize) {
    use core::fmt::Write;
    vga_buffer::WRITER.lock().write_str("Hello World!");

    let boot_info = unsafe{ multiboot2::load(multiboot_information_address) };
    let memory_map_tag = boot_info.memory_map_tag().expect("Memory map tag required");

    println!("Memory areas:");
    for area in memory_map_tag.memory_areas() {
        println!("    start: 0x{:x}, length: 0x{:x}", area.base_addr, area.length);
    }

    let elf_sections_tag = boot_info.elf_sections_tag()
        .expect("Elf-sections tag required");

    println!("Kernel sections:");
    for section in elf_sections_tag.sections() {
        println!("    addr: 0x{:x}, size: 0x{:x}, flags: 0x{:x}",
            section.addr, section.size, sections.flags);
    }

    let kernel_start = elf_sections_tag.sections().map(|s| s.addr)
        .min().unwrap();
    let kernel_end = elf_sections_tag.sections().map(|s| s.addr + s.size)
        .max().unwrap()

    let multiboot_start = multiboot_information_address;
    let multiboot_end = multiboot_start + (boot_info.total_size as usize);

    println!("kernel_start: 0x{:x}, kernel_end: 0x{:x}", kernel_start, kernel_end);
    println!("multiboot_start: 0x{:x}, multiboot_end: 0x{:x}", multiboot_start, multiboot_end);

    let mut frame_allocator = memory::AreaFrameAllocator::new(
        kernel_start as usize, kernel_end as usize, multiboot_start
        multiboot_end, memory_map_tag.memory_areas()
    );

    loop{}
}

#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "panic_fmt"]
extern fn panic_fmt(fmt: core::fmt::Arguments, file: &str, line: u32) -> ! {
    println!("\n\nPANIC in {} at line {}:", file, line);
    println!("    {}", fmt);
    loop{}
}


text:
package javaguide.advanced.di;

//#cleanup
import javax.inject.*;
import play.inject.ApplicationLifecycle;
import play.libs.F;

import java.util.concurrent.Callable;

@Singleton
public class MessageQueueConnection {
    private final MessageQueue connection;

    @Inject
    public MessageQueueConnection(ApplicationLifecycle lifecycle) {
        connection = MessageQueue.connect();

        lifecycle.addStopHook(new Callable<F.Promise<Void>>() {
            public F.Promise<Void> call() throws Exception {
                connection.stop();
                return F.Promise.pure(null);
            }
        });
    }

    // ...
}
//#cleanup


text:
#include "stdafx.h"
#include "dialog.h"
#include <fstream>
#include <gamesystems/gamesystems.h>
#include "gamesystems/timeevents.h"
#include "infrastructure/vfs.h"
#include <party.h>
#include <rng.h>
#include <critter.h>
#include <sound.h>
#include <gamesystems/objects/objsystem.h>
DialogScripts dialogScripts;

static struct DialogScriptsAddresses : temple::AddressTable {

	bool (__cdecl *GetFilename)(int scriptId, char *filename);

	bool (__cdecl *LoadScript)(const char *filename, int &handleOut);

	void (__cdecl *LoadNpcLine)(DialogState &state, bool force);

	void (__cdecl *FreeScript)(int handle);

	DialogScriptsAddresses() {
		rebase(GetFilename, 0x1007E270);
		rebase(LoadScript, 0x10036600);
		rebase(LoadNpcLine, 0x10038590);
		rebase(FreeScript, 0x100346F0);
	}
} addresses;

class DialogHooks : public TempleFix
{
public:

	static void MapFirstSeenBanter(int mapId);
	static void PlayVoice(objHndl handle, objHndl addressed, int soundId);

	void apply() override {

		static BOOL (__cdecl*orgLoadDialogFile)(char*, int*) =
			replaceFunction<BOOL(__cdecl)(char*, int*)>(0x10036600, [](char* filename, int* dlgFileHandle){
			return dialogScripts.Load(filename, *dlgFileHandle)?TRUE:FALSE;
			//return orgLoadDialogFile(filename, dlgFileHandle);
		});

		// Fixes crash issue:
		// ObjHndl buffer overlow when more than 3 NPCs (leading to junk data handle being used)
		replaceFunction(0x10038470, MapFirstSeenBanter);

		//replaceFunction(0x100354A0, PlayVoice);
	}
} dialogHooks;

bool DialogLine::IsPcLine(){
	return this->minIq != 0;
}

bool DialogLine::IsNpcLine(){
	return !IsPcLine();
}

DialogLine &DialogLine::operator=(DialogLineNew &src){
	auto &dest = *this;

	dest.minIq = src.minIq;
	dest.answerLineId = src.answerLineId;
	dest.key = src.key;
	dest.txt = _strdup(src.txt.c_str());

	// copy testField if not blank
	auto testFieldOk = false;
	for (auto i = 0u; i < src.testField.size(); i++) {
		if (!isspace(src.testField[i])) {
			testFieldOk = true;
			break;
		}
	}
	dest.testField = testFieldOk ? _strdup(src.testField.c_str()) : nullptr;

	// copy effectfield if not blank
	auto effectFieldOk = false;
	for (auto i = 0u; i < src.effectField.size(); i++) {
		if (!isspace(src.effectField[i])) {
			effectFieldOk = true;
			break;
		}
	}
	dest.effectField = effectFieldOk ? _strdup(src.effectField.c_str()) : nullptr;

	if (src.IsNpcLine())
		dest.genderField = _strdup(src.genderField.c_str());
	else
		dest.genderField = (char*)-1;

	return dest;
}

string DialogScripts::GetFilename(int scriptId) {
	char filename[MAX_PATH];
	if (addresses.GetFilename(scriptId, filename)) {
		return filename;
	} else {
		return string();
	}
}

bool DialogScripts::Load(const string& filename, int& dlgHandle) {
	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCount = temple::GetRef<int>(0x108ED0C4);

	if (GetFileEntryByFilename(filename, dlgHandle)){
		auto &entry = mFileEntries[dlgHandle];
		entry.refCount++;
		entry.lastTimeLoaded = gameSystems->GetTimeEvent().GetTime();
		return true;
	}

	DialogFile newEntry;
	strcpy(newEntry.filename, filename.c_str());
	newEntry.refCount = 1;
	newEntry.lineCapacity = newEntry.lineCount = 0;
	newEntry.lastTimeLoaded = gameSystems->GetTimeEvent().GetTime();
	newEntry.lines = nullptr;
	newEntry.unk11C = 0;

	newEntry.GetLinesFromFile();
	if (newEntry.lineCount ==0)
		return false;

	memcpy(&mFileEntries[dlgHandle], &newEntry, sizeof DialogFile);
	mFileEntryCount++;

	return true;
	//return addresses.LoadScript(filename.c_str(), dlgHandle);
}

void DialogScripts::LoadNpcLine(DialogState& state, bool force) {
	addresses.LoadNpcLine(state, force);
}

void DialogScripts::Free(int dlgHandle) {
	addresses.FreeScript(dlgHandle);
}

DialogFile* DialogScripts::GetDialogFileEntry(int dlgHandle){
	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCount = temple::GetRef<int>(0x108ED0C4);

	if (dlgHandle >= mFileEntryCount || dlgHandle < 0)
		return nullptr;
	return &mFileEntries[dlgHandle];
}

ostream & operator<<(ostream & result, DialogLine &line){
	/*
	{1}{NPC txt}{Gender}{     }{speechId }{        }{}
	{2}{PC txt }{      }{minIq}{testField}{answerId}{effectField}
	*/
	if (line.IsPcLine()) {
		result << "{" << line.key << "}";
		if (line.txt)
			result << "{" << line.txt << "}";
		else
			result << "{}";
		result << "{}"; // blank gender field

		result << "{" << line.minIq << "}";
		if (line.testField)
			result << "{" << line.testField << "}";
		else
			result << "{}";
		result << "{" << line.answerLineId << "}";

		if (line.effectField)
			result << "{" << line.effectField << "}";
		else
			result << "{}";

		//result = fmt::format("\{{}\}\{{}\}\{\}\{{}\}\{{}\}\{{}\}\{{}\}",
		//	line.key, line.txt, line.minIq, line.testField, line.answerLineId, line.effectField );
	}
	else {

		result << "{" << line.key << "}";
		if (line.txt)
			result << "{" << line.txt << "}";
		else
			result << "{}";

		if (line.genderField)
			result << "{" << line.genderField << "}";
		else
			result << "{}";

		result << "{}";
		result << "{}";
		result << "{}";

		if (line.effectField)
			result << "{" << line.effectField << "}";
		else
			result << "{}";

		//result = fmt::format("\{{}\}\{{}\}\{{}\}\{\}\{\}\{\}\{\}",
		//	line.key, line.txt, line.genderField, line.effectField);
	}
	return result;
}

void DialogScripts::SaveToFile(int dlgHandle){
	auto fileEntry = GetDialogFileEntry(dlgHandle);
	if (!fileEntry)
		return;

	std::string newFileName(fmt::format("", fileEntry->filename));
	//auto newFile = fopen("shit.mes", "wb");
	ofstream newFile("shit.mes");

	for (auto i=0; i < fileEntry->lineCount; i++){
		auto line = fileEntry->lines[i];

		if (i && line.IsNpcLine() && line.key < 10000) {
			newFile << std::endl;
			if (!(line.key % 10))
				newFile << std::endl;
		}
		newFile << line << std::endl;
	}
}

bool DialogScripts::GetFileEntryByFilename(const std::string & filename, int &dlgHandleOut){

	DialogFile *&mFileEntries = temple::GetRef<DialogFile*>(0x108ED0CC);
	int &mFileEntryCapacity = temple::GetRef<int>(0x108ED0C8);

	auto oldestFreeHandle = -1;

	for (auto i=0; i < mFileEntryCapacity; i++){

		auto &entry = mFileEntries[i];

		if (!_stricmp(filename.c_str(), entry.filename)){
			dlgHandleOut = i;
			return true;
		}
		if (!entry.refCount){
			if (oldestFreeHandle == -1){
				oldestFreeHandle = i;
			}
			else{
				auto &lastEntry = mFileEntries[oldestFreeHandle];
				if (lastEntry.filename[0]
				&& (!entry.filename[0])
					|| GameTime::Compare(lastEntry.lastTimeLoaded,
						entry.lastTimeLoaded) > 0){
					oldestFreeHandle = i;
			    }

			}
		}
	}

	if (oldestFreeHandle != -1){
		dlgHandleOut = oldestFreeHandle;
		if (mFileEntries[oldestFreeHandle].filename[0])
			Free(oldestFreeHandle);
		return false;
	}

	auto prevCount = mFileEntryCapacity;
	dlgHandleOut = prevCount;
	// allocate 10 more entries
	mFileEntryCapacity += 10;
	mFileEntries = (DialogFile*)realloc(mFileEntries, mFileEntryCapacity * sizeof DialogFile);
	for (auto i=prevCount; i < mFileEntryCapacity; i++){
		auto &entry = mFileEntries[i];
		entry.filename[0] = 0;
		entry.refCount = 0;
	}
	return false;
}

struct DlgParser {
	stringstream ss;
	string lineBuf; // buffer for storing a line's content

	stringstream bracketStream;
	string bracketContent;

	bool GetSingleLine(DialogLineNew &line, int&fileLine);
	bool GetBracketContent(int &fileLine);

	DlgParser(string & fileContents):ss(fileContents){};
};

bool DlgParser::GetSingleLine(DialogLineNew& line, int& fileLine){
	// parse buf for bracket stuff until a line is complete
	if (!GetBracketContent(fileLine))
		return false;
	line.key = atol(bracketContent.c_str());

	if (!GetBracketContent(fileLine)){
		logger->error("Missing text on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	line.txt = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing gender field on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	line.genderField = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing minimum IQ value on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	auto minIq = atol(bracketContent.c_str());
	if (!minIq && bracketContent.size()) {
		logger->error("Invalid minimum IQ value on line: {} (dialog line {}). Must be blank (for an NPC) or non-zero (for a PC)", fileLine, line.key);
		return false;
	}
	line.minIq = minIq;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing test field on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	line.testField = bracketContent;

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing response value on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	if (bracketContent[0] == '#'){
		logger->error("Saw a # in a response value on line: {} (dialog line {})", fileLine, line.key);
		return 0;
	}
	line.answerLineId = atol(bracketContent.c_str());

	if (!GetBracketContent(fileLine)) {
		logger->error("Missing effect field on line: {} (dialog line {})", fileLine, line.key);
		return false;
	}
	line.effectField = bracketContent;

	// check non-blank gender field for NPC lines
	if (line.IsNpcLine()){

		auto fieldIsBlank= true;
		for (auto i = 0u; i < line.genderField.size(); i++) {
			if (!isspace(line.genderField[i])) {
				fieldIsBlank = false;
				break;
			}
		}

		// if it's blank, check that the txt field isn't also blank (e.g. when using the picker stuff)
		if (fieldIsBlank){

			fieldIsBlank = true;
			for (auto i = 0u; i < line.txt.size(); i++) {
				if (!isspace(line.txt[i])) {
					fieldIsBlank = false;
					break;
				}
			}

			if (!fieldIsBlank)
				logger->warn("Missing NPC response line for females: {} (dialog line {})", fileLine, line.key);
		}
	}

	return true;
}

bool DlgParser::GetBracketContent(int &fileLine){
	string brBuf;
	const int MAX_TEXT_SIZE = 1000;

	getline(ss, brBuf, '{');
	if (ss.eof()) { // no new brackets found
		return false;
	}

	// count how many newlines
	for (auto nl = strchr(brBuf.c_str(), '\n'); nl; fileLine++) {
		nl = strchr(nl + 1, '\n');
	}
	auto rb = strchr(brBuf.c_str(), '}');
	if (rb){
		logger->warn("Possible missing left brace on or before line {}", fileLine);
	}

	// get bracket content
	getline(ss, brBuf, '}');
	if (ss.eof()) {
		logger->error("Unclosed bracket found! Line {}", fileLine);
		return false;
	}
	if (ss.gcount() >= MAX_TEXT_SIZE){
		logger->error("String too long on line: {} (max is {})", fileLine, MAX_TEXT_SIZE);
		return false;
	}
	// count how many newlines inside bracket
	for (auto nl = strchr(brBuf.c_str(), '\n'); nl; fileLine++) {
		nl = strchr(nl + 1, '\n');
	}

	bracketContent = brBuf;
	return true;
}

void DialogFile::GetLinesFromFile()
{
	if (!vfs->FileExists(this->filename))
		return;

	auto fileContents = vfs->ReadAsString(this->filename);
	DlgParser dlgParser(fileContents);

	int fileLine = 1;
	DialogLineNew lineTmp;
	while (dlgParser.GetSingleLine(lineTmp, fileLine)){

		if (this->lineCount == this->lineCapacity){
			this->lineCapacity += 10;
			this->lines = (DialogLine*)realloc(lines, lineCapacity * sizeof DialogLine);
		}
		this->lines[lineCount++] = lineTmp;

	}

	std::sort(this->lines, &this->lines[lineCount-1], [](DialogLine &a, DialogLine &b)->bool{
		return a.key < b.key;
	});
}

bool DialogLineNew::IsPcLine() {
	return minIq != 0;
}

bool DialogLineNew::IsNpcLine(){
	return !IsPcLine();
}

void DialogHooks::MapFirstSeenBanter(int mapId)
{
	auto npcCount = party.GroupNPCFollowersLen();
	char text[1000];
	int soundId = -1;
	static auto GetMapFirstSeenVoiceLine = temple::GetRef<void(__cdecl)(objHndl, objHndl, int, char [], int&)>(0x10037FD0);

	// Temple+: now uses vector instead of fixes size[3] array
	std::vector<objHndl> commentNpcs;
	for (auto i = 0; i < npcCount; ++i) {
		auto npc = party.GroupNPCFollowersGetMemberN(i);
		auto fellowPc = party.GetFellowPc(npc);
		GetMapFirstSeenVoiceLine(npc, fellowPc, mapId, text, soundId);
		if (text[0]) {
			commentNpcs.push_back(npc);
		}
	}

	auto talker = objHndl::null;
	if (commentNpcs.size()) {
		auto idx = rngSys.GetInt(0, commentNpcs.size() - 1);
		talker = commentNpcs[idx];
	}
	else {
		auto idx = rngSys.GetInt(0, party.GroupPCsLen() - 1); // Temple+: was (0, N) instead of (0, N-1) in vanilla
		talker = party.GroupPCsGetMemberN(idx);
	}

	if (talker) {
		auto fellowPc = party.GetFellowPc(talker);
		GetMapFirstSeenVoiceLine(talker, fellowPc, mapId, text, soundId);
		logger->trace("Playing sound {} for talker {}, text {}", soundId, talker, text);
		critterSys.PlayCritterVoiceLine(talker, fellowPc, text, soundId);
	}

	// Append to seen map list
	static auto SeenMaplistAppend = temple::GetRef<void(__cdecl)(objHndl, int)>(0x10080390);
	auto partySize = party.GroupListGetLen();
	for (auto i = 0; i < partySize; ++i) {
		auto partyMem = party.GroupListGetMemberN(i);
		SeenMaplistAppend(partyMem, mapId);
	}
}

void DialogHooks::PlayVoice(objHndl handle, objHndl addressed, int soundId)
{
	if (soundId == -1) {
		return;
	}
	if (!objSystem->IsValidHandle(handle)) {
		return;
	}

	auto mActiveSpeech = temple::GetRef<int>(0x108EC85C);
	if (mActiveSpeech != -1) {
		sound.MssFreeStream(mActiveSpeech);
		mActiveSpeech = -1;
	}

	char filename[260] = { 0, };
	if (critterSys.IsPC(handle)) {
		auto voiceIdx = objects.getInt32(handle, obj_f_pc_voice_idx);
		sprintf(filename, "sound\\speech\\pcvoice\\%.2d\\%d.mp3", voiceIdx, soundId);
	}
	else {
		auto scriptId = (soundId >> 16) & 0x7FFF;
		auto mfChar = objects.StatLevelGet(addressed, stat_gender) != 0 ? 'm' : 'f';
		sprintf(filename, "sound\\speech\\%.5d\\v%d_%c.mp3", scriptId, (soundId & 0xFFFF) , mfChar);
		if (mfChar == 'f' && !tio_fileexists(filename, 0))
			sprintf(filename, "sound\\speech\\%.5d\\v%d_%c.mp3", scriptId, (unsigned __int16)soundId, 'm');
	}

	logger->trace("Playing sound file: {}", filename);
	static auto PlayVoiceFile = temple::GetRef<int(__cdecl)(const char*, int timeToFade)>(0x1003C5F0);
	if (tio_fileexists(filename, nullptr)) {
		mActiveSpeech = PlayVoiceFile(filename, 0);
	}
	else {
		logger->trace("Sound file not found!");
	}
}


text:
export {GitAbortMerge} from './abort.command';
export {GitContinueMerge} from './continue.command';
export {GitMerge} from './merge.command';


text:
import io
import os
import sys
from typing import Generator
from typing import TextIO

import pytest
from _pytest.config import Config
from _pytest.config.argparsing import Parser
from _pytest.nodes import Item
from _pytest.store import StoreKey

fault_handler_stderr_key = StoreKey[TextIO]()

def pytest_addoption(parser: Parser) -> None:
    help = (
        "Dump the traceback of all threads if a test takes "
        "more than TIMEOUT seconds to finish."
    )
    parser.addini("faulthandler_timeout", help, default=0.0)

def pytest_configure(config: Config) -> None:
    import faulthandler

    if not faulthandler.is_enabled():
        # faulthhandler is not enabled, so install plugin that does the actual work
        # of enabling faulthandler before each test executes.
        config.pluginmanager.register(FaultHandlerHooks(), "faulthandler-hooks")
    else:
        # Do not handle dumping to stderr if faulthandler is already enabled, so warn
        # users that the option is being ignored.
        timeout = FaultHandlerHooks.get_timeout_config_value(config)
        if timeout > 0:
            config.issue_config_time_warning(
                pytest.PytestConfigWarning(
                    "faulthandler module enabled before pytest configuration step, "
                    "'faulthandler_timeout' option ignored"
                ),
                stacklevel=2,
            )

class FaultHandlerHooks:
    """Implements hooks that will actually install fault handler before tests execute,
    as well as correctly handle pdb and internal errors."""

    def pytest_configure(self, config: Config) -> None:
        import faulthandler

        stderr_fd_copy = os.dup(self._get_stderr_fileno())
        config._store[fault_handler_stderr_key] = open(stderr_fd_copy, "w")
        faulthandler.enable(file=config._store[fault_handler_stderr_key])

    def pytest_unconfigure(self, config: Config) -> None:
        import faulthandler

        faulthandler.disable()
        # close our dup file installed during pytest_configure
        # re-enable the faulthandler, attaching it to the default sys.stderr
        # so we can see crashes after pytest has finished, usually during
        # garbage collection during interpreter shutdown
        config._store[fault_handler_stderr_key].close()
        del config._store[fault_handler_stderr_key]
        faulthandler.enable(file=self._get_stderr_fileno())

    @staticmethod
    def _get_stderr_fileno():
        try:
            return sys.stderr.fileno()
        except (AttributeError, io.UnsupportedOperation):
            # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.
            # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors
            # This is potentially dangerous, but the best we can do.
            return sys.__stderr__.fileno()

    @staticmethod
    def get_timeout_config_value(config):
        return float(config.getini("faulthandler_timeout") or 0.0)

    @pytest.hookimpl(hookwrapper=True, trylast=True)
    def pytest_runtest_protocol(self, item: Item) -> Generator[None, None, None]:
        timeout = self.get_timeout_config_value(item.config)
        stderr = item.config._store[fault_handler_stderr_key]
        if timeout > 0 and stderr is not None:
            import faulthandler

            faulthandler.dump_traceback_later(timeout, file=stderr)
            try:
                yield
            finally:
                faulthandler.cancel_dump_traceback_later()
        else:
            yield

    @pytest.hookimpl(tryfirst=True)
    def pytest_enter_pdb(self) -> None:
        """Cancel any traceback dumping due to timeout before entering pdb."""
        import faulthandler

        faulthandler.cancel_dump_traceback_later()

    @pytest.hookimpl(tryfirst=True)
    def pytest_exception_interact(self) -> None:
        """Cancel any traceback dumping due to an interactive exception being
        raised."""
        import faulthandler

        faulthandler.cancel_dump_traceback_later()


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

<TITLE>
edu.cmu.ri.createlab.terk.robot.finch (Finch API)
</TITLE>

<META NAME="date" CONTENT="2011-05-31">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Deprecated
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package edu.cmu.ri.createlab.terk.robot.finch

Class Summary

Finch
Contains all methods necessary to program for the Finch robot

      Overview
    Package
      Class
      Deprecated
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
using System.Text;
using Tweetinvi.Core.Extensions;
using Tweetinvi.Core.QueryGenerators.V2;
using Tweetinvi.Parameters.V2;

namespace Tweetinvi.Controllers.Search
{
    public interface ISearchV2QueryGenerator
    {
        string GetSearchTweetsV2Query(ISearchTweetsV2Parameters parameters);
    }

    public class SearchV2QueryGenerator : ISearchV2QueryGenerator
    {
        private readonly ITweetsV2QueryGenerator _tweetsV2QueryGenerator;

        public SearchV2QueryGenerator(ITweetsV2QueryGenerator tweetsV2QueryGenerator)
        {
            _tweetsV2QueryGenerator = tweetsV2QueryGenerator;
        }

        public string GetSearchTweetsV2Query(ISearchTweetsV2Parameters parameters)
        {
            var query = new StringBuilder("https://api.twitter.com/2/tweets/search/recent");
            query.AddParameterToQuery("query", parameters.Query);
            query.AddParameterToQuery("end_time", parameters.EndTime?.ToString("yyy-MM-ddThh:mm:ssZ"));
            query.AddParameterToQuery("max_results", parameters.PageSize);
            query.AddParameterToQuery("next_token", parameters.NextToken);
            query.AddParameterToQuery("since_id", parameters.SinceId);
            query.AddParameterToQuery("start_time", parameters.StartTime?.ToString("yyy-MM-ddThh:mm:ssZ"));
            query.AddParameterToQuery("until_id", parameters.UntilId);
            _tweetsV2QueryGenerator.AddTweetFieldsParameters(parameters, query);
            query.AddFormattedParameterToQuery(parameters.FormattedCustomQueryParameters);
            return query.ToString();
        }
    }
}


text:
import NewUserValidator from 'ghost/validators/new-user';

export default NewUserValidator.create();


text:
package goodsbase.model;

import goodsbase.qserver.QRequest;

import java.util.Date;

/**Describes a product at warehouse*/
public class Supply {

	public enum Type {
		ARRIVAL, WRITEOFF;
	}

	/**@throws NullPointerException if good or unit is null*/
	/**@throws IllegalArgumentException if quantity or price is 0 or lesser*/
	public Supply(Product prod, double quantity, Unit unit, double price, Type type) {
		setProduct(prod);
		setQuantity(quantity);
		setUnit(unit);
		setPrice(price);
		setType(type);
	}

	/**
	 * @param product the product to set
	 */
	public void setProduct(Product product) {
		if(product == null) throw new  NullPointerException("product can't be null");
		this.product = product;
	}

	/**@throws IllegalArgumentException if quantity is 0 or lesser*/
	public void setQuantity(double quantity) {
		if(quantity <= 0) throw new  IllegalArgumentException("Quantity can't be 0 or negative");
		this.quantity = quantity;
	}

	/**@throws NullPointerException if unit is null*/
	public void setUnit(Unit unit) {
		if(unit == null) throw new  NullPointerException("Unit can't be null");
		this.unit = unit;
	}

	/**@throws IllegalArgumentException if price is 0 or lesser*/
	public void setPrice(double price) {
		if(price <= 0) throw new  IllegalArgumentException("Price can't be 0 or negative");
		this.price = price;
	}

	/**
	 * @param type the type to set
	 */
	public void setType(Type type) {
		if(type == null) throw new  NullPointerException("Type can't be null");
		this.type = type;
	}

	/**
	 * @return the product
	 */
	public Product getProduct() {
		return product;
	}

	/**
	 * @return the quantity
	 */
	public double getQuantity() {
		return quantity;
	}

	/**
	 * @return the unit
	 */
	public Unit getUnit() {
		return unit;
	}

	/**
	 * @return the price
	 */
	public double getPrice() {
		return price;
	}

	/**
	 * @return the type
	 */
	public Type getType() {
		return type;
	}

	/**Writes supply to database
	 * @throws DataLoadException*/
	public static boolean updateSupplies(Supply s) throws DataLoadException{
		String query = "INSERT INTO supplies (supplies_date, supplies_type, supplies_product_id, supplies_quantity,"
				+ " supplies_units, supplies_price) VALUES ("
				+ new Date().getTime() + ", '"
				+s.type + "', "
				+s.product.getId() + ", "
				+s.quantity + ", '"
				+s.unit + "', "
				+s.price +");";

		int res = DataExecutor.executeUpdate(query);
		if (res == QRequest.OK_CODE)
			return true;
		return false;
	}

	private Product product;
	private double quantity;
	private Unit unit;
	private double price;
	private Type type;
}


text:
package ru.stqa.pft.rest;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.testng.SkipException;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import static com.jayway.jsonpath.JsonPath.read;

public class TestBase {
  public boolean isIssueOpen(int issueId) throws IOException {
    String status = getIssueStatusById(issueId);
    if (status.equals("Resolved") || status.equals("Closed")) {

      return false;
    } else {
      System.out.println("Issue is open");
      return true;
    }
  }

  public void skipIfNotFixed(int issueId) throws IOException {
    if (isIssueOpen(issueId)) {
      throw new SkipException("Ignored because of issue " + issueId);
    }
  }

  protected Set<Issue> getIssues() throws IOException {
    String json = getExecutor().execute(Request.Get("http://demo.bugify.com/api/issues.json")).returnContent().asString();
    JsonElement parsed = new JsonParser().parse(json);
    JsonElement issues = parsed.getAsJsonObject().get("issues");
    return new Gson().fromJson(issues, new TypeToken<Set<Issue>>() {
    }.getType());
  }

  protected String getIssueStatusById(int id) throws IOException {
    String json = getExecutor().execute(Request.Get("http://demo.bugify.com/api/issues/" + id + ".json")).returnContent().asString();
    List<String> status = read(json, "$.issues[*].state_name");
    return status.get(0);
  }

  protected Executor getExecutor() {
    return Executor.newInstance().auth("LSGjeU4yP1X493ud1hNniA==", "");
  }
}


text:
package org.arquillian.cube.spi;

import java.util.Map;

public class CubeConfiguration {

    private static final String CONNECTION_MODE = "connectionMode";

    private ConnectionMode connectionMode = ConnectionMode.STARTANDSTOP;

    public ConnectionMode getConnectionMode() {
        return connectionMode;
    }

    public static CubeConfiguration fromMap(Map<String, String> map) {
        CubeConfiguration cubeConfiguration = new CubeConfiguration();

        if(map.containsKey(CONNECTION_MODE)) {
            cubeConfiguration.connectionMode = ConnectionMode.valueOf(ConnectionMode.class, map.get(CONNECTION_MODE));
        }
        return cubeConfiguration;
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/gkemulticloud/v1/azure_service.proto

namespace Google\Cloud\GkeMultiCloud\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Response message for `AzureClusters.ListAzureClients` method.
 *
 * Generated from protobuf message google.cloud.gkemulticloud.v1.ListAzureClientsResponse
 */
class ListAzureClientsResponse extends \Google\Protobuf\Internal\Message
{
    /**
     * A list of [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resources in the specified Google Cloud
     * project and region region.
     *
     * Generated from protobuf field repeated .google.cloud.gkemulticloud.v1.AzureClient azure_clients = 1;
     */
    private $azure_clients;
    /**
     * Token to retrieve the next page of results, or empty if there are no more
     * results in the list.
     *
     * Generated from protobuf field string next_page_token = 2;
     */
    private $next_page_token = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type array<\Google\Cloud\GkeMultiCloud\V1\AzureClient>|\Google\Protobuf\Internal\RepeatedField $azure_clients
     *           A list of [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resources in the specified Google Cloud
     *           project and region region.
     *     @type string $next_page_token
     *           Token to retrieve the next page of results, or empty if there are no more
     *           results in the list.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Gkemulticloud\V1\AzureService::initOnce();
        parent::__construct($data);
    }

    /**
     * A list of [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resources in the specified Google Cloud
     * project and region region.
     *
     * Generated from protobuf field repeated .google.cloud.gkemulticloud.v1.AzureClient azure_clients = 1;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getAzureClients()
    {
        return $this->azure_clients;
    }

    /**
     * A list of [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resources in the specified Google Cloud
     * project and region region.
     *
     * Generated from protobuf field repeated .google.cloud.gkemulticloud.v1.AzureClient azure_clients = 1;
     * @param array<\Google\Cloud\GkeMultiCloud\V1\AzureClient>|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setAzureClients($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\GkeMultiCloud\V1\AzureClient::class);
        $this->azure_clients = $arr;

        return $this;
    }

    /**
     * Token to retrieve the next page of results, or empty if there are no more
     * results in the list.
     *
     * Generated from protobuf field string next_page_token = 2;
     * @return string
     */
    public function getNextPageToken()
    {
        return $this->next_page_token;
    }

    /**
     * Token to retrieve the next page of results, or empty if there are no more
     * results in the list.
     *
     * Generated from protobuf field string next_page_token = 2;
     * @param string $var
     * @return $this
     */
    public function setNextPageToken($var)
    {
        GPBUtil::checkString($var, True);
        $this->next_page_token = $var;

        return $this;
    }

}


text:
<!DOCTYPE html>

[Two One]


text:
package co.cask.coopr.provisioner.plugin;

import co.cask.coopr.account.Account;
import co.cask.coopr.common.conf.Configuration;
import co.cask.coopr.common.utils.ImmutablePair;
import co.cask.coopr.common.zookeeper.LockService;
import co.cask.coopr.common.zookeeper.lib.ZKInterProcessReentrantLock;
import co.cask.coopr.scheduler.task.MissingEntityException;
import co.cask.coopr.spec.plugin.AutomatorType;
import co.cask.coopr.spec.plugin.ProviderType;
import co.cask.coopr.spec.plugin.ResourceTypeSpecification;
import co.cask.coopr.store.entity.EntityStoreService;
import co.cask.coopr.store.entity.EntityStoreView;
import co.cask.coopr.store.provisioner.PluginMetaStoreService;
import co.cask.coopr.store.provisioner.PluginResourceTypeView;
import co.cask.coopr.store.provisioner.PluginStore;
import co.cask.http.BodyConsumer;
import co.cask.http.HttpResponder;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.gson.Gson;
import com.google.inject.Inject;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;

/**
 * Service for managing plugin modules.
 */
public class ResourceService extends AbstractIdleService {
  private static final Logger LOG  = LoggerFactory.getLogger(ResourceService.class);
  private final Configuration conf;
  private final PluginStore pluginStore;
  private final EntityStoreService entityStoreService;
  private final PluginMetaStoreService metaStoreService;
  private final LockService lockService;
  private final Gson gson;

  @Inject
  private ResourceService(PluginStore pluginStore,
                          EntityStoreService entityStoreService,
                          PluginMetaStoreService metaStoreService,
                          LockService lockService,
                          Configuration conf,
                          Gson gson) {
    this.conf = conf;
    this.pluginStore = pluginStore;
    this.entityStoreService = entityStoreService;
    this.metaStoreService = metaStoreService;
    this.lockService = lockService;
    this.gson = gson;
  }

  /**
   * Create a body consumer for streaming resource contents into the persistent store.
   *
   * @param account Account that is uploading the resource
   * @param resourceType Type of resource to upload
   * @param name Name of resource to upload
   * @param responder Responder for responding to the upload request
   * @return BodyConsumer for consuming the resource contents and streaming them to the persistent store
   * @throws IOException if there was an error getting the output stream for writing to the persistent store or writing
   *                     the plugin metadata
   */
  public BodyConsumer createResourceBodyConsumer(final Account account,
                                                 final ResourceType resourceType,
                                                 final String name,
                                                 final HttpResponder responder) throws IOException {
    final ZKInterProcessReentrantLock lock = getResourceLock(account, resourceType, name);
    lock.acquire();
    try {
      PluginResourceTypeView view = metaStoreService.getResourceTypeView(account, resourceType);
      // ok to do versioning this way since we have a lock
      final int version = view.getHighestVersion(name) + 1;
      final ResourceMeta resourceMeta = new ResourceMeta(name, version);
      LOG.debug("getting output stream for version {} of resource {} of type {} for account {}",
                version, name, resourceType, account);
      // output stream is used to stream resource contents to the plugin store
      final OutputStream os = pluginStore.getResourceOutputStream(account, resourceType, name, version);
      // we write metadata here before the data completes streaming because we are guaranteed the
      // version will never be used again, and because we need to increment the highest version in case another
      // upload of the same name is started while this one is still going. It is deleted if the upload fails.
      metaStoreService.getResourceTypeView(account, resourceType).add(resourceMeta);

      return new BodyConsumer() {
        @Override
        public void chunk(ChannelBuffer request, HttpResponder responder) {
          try {
            request.readBytes(os, request.readableBytes());
          } catch (IOException e) {
            LOG.error("Error during upload of version {} of resource {} for account {}.",
                      version, name, account, e);
            responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage());
          }
        }

        @Override
        public void finished(HttpResponder responder) {
          try {
            os.close();
            responder.sendJson(HttpResponseStatus.OK, resourceMeta, ResourceMeta.class, gson);
            LOG.debug("finished uploading resource.");
          } catch (Exception e) {
            LOG.error("Error finishing upload of resource {} of type {} for account {}.",
                      resourceMeta, resourceType, account, e);
            responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage());
          }
        }

        @Override
        public void handleError(Throwable t) {
          LOG.error("Error uploading version {} of resource {} of type {} for account {}.",
                    version, name, resourceType, account, t);
          try {
            os.close();
            // deletion flags the entry in the database as deleted
            metaStoreService.getResourceTypeView(account, resourceType).delete(name, version);
            // dont need the file in the plugin store if there was an error so delete it
            pluginStore.deleteResource(account, resourceType, name, version);
            responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, t.getCause().getMessage());
          } catch (IOException e) {
            LOG.error("Error uploading resource {} of type {} for account {}.", resourceMeta, resourceType, account, e);
          }
        }
      };
    } finally {
      lock.release();
    }
  }

  /**
   * Get the number of all versions of all resources in the account. Resources can be in any state.
   *
   * @param account Account to get the number of resources for
   * @return Number of resources in the account
   * @throws IOException
   */
  public int numResources(Account account) throws IOException {
    return metaStoreService.getAccountView(account).numResources();
  }

  /**
   * Bootstrap an account's resources by copying what the superadmin has into the account.
   *
   * @param account Account to bootstrap
   */
  public void bootstrapResources(Account account) throws IOException {
    for (ImmutablePair<ResourceType, ResourceTypeSpecification> typePair : getTypesAndFormats(Account.SUPERADMIN)) {
      ResourceType type = typePair.getFirst();
      Map<String, Set<ResourceMeta>> resources =
        metaStoreService.getResourceTypeView(Account.SUPERADMIN, type).getAll();
      for (Set<ResourceMeta> metas : resources.values()) {
        for (ResourceMeta meta : metas) {
          LOG.debug("copying version {} of resource {} of type {} from superadmin account to account {}",
                    meta.getVersion(), meta.getName(), type, account);
          copySuperadminResource(account, type, meta);
        }
      }
    }
  }

  private void copySuperadminResource(Account account, ResourceType type, ResourceMeta meta) throws IOException {
    String name = meta.getName();
    int version = meta.getVersion();
    ZKInterProcessReentrantLock lock = getResourceLock(account, type, name);
    lock.acquire();
    InputStream inStream = null;
    OutputStream outStream = null;
    try {
      inStream = pluginStore.getResourceInputStream(Account.SUPERADMIN, type, name, version);
      outStream = pluginStore.getResourceOutputStream(account, type, name, version);
      if (inStream == null) {
        LOG.error("Could not get input stream for version {} of resource {} of type {} for account {}.",
                  version, name, type, account);
        throw new IOException("Unable to get plugin data.");
      }
      ByteStreams.copy(inStream, outStream);
      PluginResourceTypeView metaView = metaStoreService.getResourceTypeView(account, type);
      if (!metaView.exists(name, version)) {
        metaView.add(meta);
      }
    } finally {
      if (outStream != null) {
        try {
          outStream.close();
        } catch (IOException e) {
          LOG.error("Exception closing output stream while copying superadmin resource.", e);
        }
      }
      if (inStream != null) {
        try {
          inStream.close();
        } catch (IOException e) {
          LOG.error("Exception closing input stream while copying superadmin resource.", e);
        }
      }
      lock.release();
    }
  }

  /**
   * Get an input stream for reading the plugin resource.
   *
   * @param account Account the resource belongs to
   * @param resourceType Type of resource
   * @param name Name of resource to get an input stream for
   * @param version Version of resource to get an input stream for
   * @return Input stream for reading the given plugin resource
   * @throws MissingEntityException if there is no such resource version
   * @throws IOException if there was an error getting the input stream for the resource
   */
  public InputStream getResourceInputStream(final Account account, ResourceType resourceType, String name, int version)
    throws MissingEntityException, IOException {
    // no lock needed since each resource uploaded gets its own id.
    ResourceMeta meta = metaStoreService.getResourceTypeView(account, resourceType).get(name, version);
    if (meta == null) {
      throw new MissingEntityException("Resource not found.");
    }
    LOG.debug("getting input stream for version {} of resource {} of type {} for account {}.",
              version, name, resourceType, account);
    return pluginStore.getResourceInputStream(account, resourceType, meta.getName(), meta.getVersion());
  }

  /**
   * Atomically stage the specified resource version for the given account and recall the previous staged version.
   * A staged version will get pushed to provisioners during a sync, and will stay staged unless explicitly recalled.
   *
   * @param account Account that contains the resource
   * @param resourceType Type of resource to stage
   * @param name Name of resource to stage
   * @param version Version of resource to stage
   * @throws MissingEntityException if there is no such resource version
   * @throws IOException if there was an error staging the resource
   */
  public void stage(Account account, ResourceType resourceType, String name, int version)
    throws MissingEntityException, IOException {
    LOG.debug("staging version {} of resource {} of type {} for account {}.",
              version, name, resourceType, account);
    ZKInterProcessReentrantLock lock = getResourceLock(account, resourceType, name);
    lock.acquire();
    try {
      PluginResourceTypeView view = metaStoreService.getResourceTypeView(account, resourceType);
      if (!view.exists(name, version)) {
        throw new MissingEntityException("Resource does not exist.");
      }
      view.stage(name, version);
    } finally {
      lock.release();
    }
  }

  /**
   * Recall the given resource for the given account. A no-op if there is no staged version.
   *
   * @param account Account that contains the resource
   * @param resourceType Type of resource to deactivate
   * @param name Name of the resource to deactivate
   * @param version Version of resource to stage
   * @throws MissingEntityException if there is no such module
   * @throws IOException if there was an error deactivating all versions of the module
   */
  public void recall(Account account, ResourceType resourceType, String name, int version)
    throws MissingEntityException, IOException {
    LOG.debug("Recalling version {} of resource {} of type {} for account {}.",
              version, name, resourceType, account);
    ZKInterProcessReentrantLock lock = getResourceLock(account, resourceType, name);
    lock.acquire();
    try {
      PluginResourceTypeView view = metaStoreService.getResourceTypeView(account, resourceType);
      if (!view.exists(name, version)) {
        throw new MissingEntityException("Resource " + name + " does not exist.");
      }
      view.recall(name, version);
    } finally {
      lock.release();
    }
  }

  /**
   * Get all resource metadata of the given type that belong to the given account that have the given status.
   *
   * @param account Account containing the resources
   * @param resourceType Type of resource to get
   * @param status Status of the resources to get. If null, resources of any status are returned.
   * @return Immutable map of resource name to resource metadata
   * @throws IOException if there was an error getting the resources
   */
  public Map<String, Set<ResourceMeta>> getAll(Account account, ResourceType resourceType,
                                               ResourceStatus status) throws IOException {
    if (status == null) {
      return metaStoreService.getResourceTypeView(account, resourceType).getAll();
    }
    return metaStoreService.getResourceTypeView(account, resourceType).getAll(status);
  }

  /**
   * Get all metadata for versions of the given resource that have the given status.
   *
   * @param account Account containing the resource
   * @param resourceType Type of resource to get
   * @param name Name of the resource to get
   * @param status Status of the resources to get. If null, resources of any status are returned.
   * @return Immutable set of metadata for versions of the given module
   * @throws IOException if there was an error getting the module versions
   */
  public Set<ResourceMeta> getAll(Account account, ResourceType resourceType,
                                  String name, ResourceStatus status) throws IOException {
    if (status == null) {
      return metaStoreService.getResourceTypeView(account, resourceType).getAll(name);
    }
    return metaStoreService.getResourceTypeView(account, resourceType).getAll(name, status);
  }

  /**
   * Delete the given resource. Can only be done if the resource is inactive.
   *
   * @param account Account containing the module
   * @param resourceType Type of resource to delete
   * @param name Name of resource to delete
   * @param version Version of resource to delete
   * @throws IllegalStateException if the resource is not in a deletable state
   * @throws IOException if there was an error deleting the module version
   */
  public void delete(Account account, ResourceType resourceType,
                     String name, int version) throws IllegalStateException, IOException {
    LOG.debug("deleting version {} of resource {} of type {} for account {}.", version, name, resourceType, account);
    ZKInterProcessReentrantLock lock = getResourceLock(account, resourceType, name);
    lock.acquire();
    try {
      PluginResourceTypeView view = metaStoreService.getResourceTypeView(account, resourceType);
      ResourceMeta meta = view.get(name, version);
      if (meta.getStatus() != ResourceStatus.INACTIVE) {
        throw new IllegalStateException("Resource must be inactive before it can be deleted.");
      }
      view.delete(name, version);
      LOG.debug("deleted version {} of resource {} of type {} for account {} from meta store.",
                version, name, resourceType, account);
      pluginStore.deleteResource(account, resourceType, meta.getName(), meta.getVersion());
      LOG.debug("deleted version {} of resource {} of type {} for account {} from plugin store.",
                version, name, resourceType, account);
    } finally {
      lock.release();
    }
  }

  /**
   * Delete all versions of the given resource. Can only be done if all versions are inactive.
   *
   * @param account Account containing the module
   * @param resourceType Type of resource to delete
   * @param name Name of resource to delete
   * @throws IllegalStateException if not all the resources are in a deletable state
   * @throws IOException if there was an error deleting the module version
   */
  public void delete(Account account, ResourceType resourceType,
                     String name) throws IllegalStateException, IOException {
    LOG.debug("deleting all versions of resource {} of type {} for account {}.", name, resourceType, account);
    ZKInterProcessReentrantLock lock = getResourceLock(account, resourceType, name);
    lock.acquire();
    try {
      PluginResourceTypeView view = metaStoreService.getResourceTypeView(account, resourceType);
      Set<ResourceMeta> metas = view.getAll(name);
      for (ResourceMeta meta : metas) {
        if (meta.getStatus() != ResourceStatus.INACTIVE) {
          throw new IllegalStateException("All versions must be inactive before the resource can be deleted.");
        }
      }
      for (ResourceMeta meta : metas) {
        view.delete(name, meta.getVersion());
        pluginStore.deleteResource(account, resourceType, meta.getName(), meta.getVersion());
        LOG.debug("deleted version {} of resource {} of type {} for account {}.",
                  meta.getVersion(), name, resourceType, account);
      }
    } finally {
      lock.release();
    }
  }

  /**
   * Get the active resources for a given account.
   *
   * @param account Account to get active resources for
   * @return Active resources for the given account
   */
  public ResourceCollection getLiveResources(Account account) throws IOException {
    ResourceCollection resourceCollection = new ResourceCollection();
    for (ImmutablePair<ResourceType, ResourceTypeSpecification> typeSpecs : getTypesAndFormats(account)) {
      ResourceType resourceType = typeSpecs.getFirst();
      ResourceTypeSpecification typeSpec = typeSpecs.getSecond();
      Set<ResourceMeta> resources = metaStoreService.getResourceTypeView(account, resourceType).getLiveResources();
      resourceCollection.addResources(resourceType, typeSpec, resources);
    }
    return resourceCollection;
  }

  /**
   * Get the resources that should be synced for a given account.
   *
   * @param account Account for which to get resources to sync
   * @return Resources that should be synced for the given account
   */
  public ResourceCollection getResourcesToSync(Account account) throws IOException {
    ResourceCollection resourceCollection = new ResourceCollection();

    Set<ImmutablePair<ResourceType, ResourceTypeSpecification>> typeFormats = getTypesAndFormats(account);
    Set<ResourceType> resourceTypes = Sets.newHashSet();
    for (ImmutablePair<ResourceType, ResourceTypeSpecification> typeFormat : typeFormats) {
      ResourceType resourceType = typeFormat.getFirst();
      ResourceTypeSpecification typeSpec = typeFormat.getSecond();
      Set<ResourceMeta> resources = metaStoreService.getResourceTypeView(account, resourceType).getResourcesToSync();
      resourceCollection.addResources(resourceType, typeSpec, resources);
      resourceTypes.add(resourceType);
    }

    return resourceCollection;
  }

  /**
   * Update the metadata store, syncing the resources in the given collection for the given account.
   *
   * @param account Account containing resources to sync
   * @param resourceCollection Collection of synced resources
   * @throws IOException
   */
  public void syncResourceMeta(Account account, ResourceCollection resourceCollection) throws IOException {
    metaStoreService.getAccountView(account).syncResources(resourceCollection);
  }

  // Helper function for getting all the resource types and formats for plugins belonging to an account.
  private Set<ImmutablePair<ResourceType, ResourceTypeSpecification>> getTypesAndFormats(Account account)
    throws IOException {
    Set<ImmutablePair<ResourceType, ResourceTypeSpecification>> typesAndFormats = Sets.newHashSet();
    EntityStoreView entityStoreView = entityStoreService.getView(account);

    for (AutomatorType plugin : entityStoreView.getAllAutomatorTypes()) {
      String pluginName = plugin.getName();
      for (Map.Entry<String, ResourceTypeSpecification> entry : plugin.getResourceTypes().entrySet()) {
        ResourceType resourceType = new ResourceType(PluginType.AUTOMATOR, pluginName, entry.getKey());
        typesAndFormats.add(ImmutablePair.of(resourceType, entry.getValue()));
      }
    }

    for (ProviderType plugin : entityStoreView.getAllProviderTypes()) {
      String pluginName = plugin.getName();
      for (Map.Entry<String, ResourceTypeSpecification> entry : plugin.getResourceTypes().entrySet()) {
        ResourceType resourceType = new ResourceType(PluginType.PROVIDER, pluginName, entry.getKey());
        typesAndFormats.add(ImmutablePair.of(resourceType, entry.getValue()));
      }
    }

    return typesAndFormats;
  }

  @Override
  protected void startUp() throws Exception {
    pluginStore.initialize(conf);
    metaStoreService.startAndWait();
  }

  @Override
  protected void shutDown() throws Exception {
    metaStoreService.stopAndWait();
  }

  // locks are namespaced by tenant and resource type and name. for example,
  // /tenant1/automator/chef-solo/cookbooks/reactor
  private ZKInterProcessReentrantLock getResourceLock(Account account, ResourceType type, String name) {
    return lockService.getResourceLock(account.getTenantId(), type.getPluginType().name().toLowerCase(),
                                       type.getPluginName(), type.getTypeName(), name);
  }
}


text:
Traim is a microframework for building a RESTful API service from your existing Active Record models.

## Getting started

### Installation
``` ruby
gem install traim
```

### Usage
Here's a simple application:
``` ruby
# cat hello_traim.rb

Traim.config do |app|
  app.logger = Logger.new(STDOUT)
end

class User < ActiveRecord::Base
end

Traim.application do
  resource :users do
    # Inject user model
    model User

    # Response json: {id: 1, name: "example"}
    attribute :id
    attribute :name

    # POST /users
    action :create

    # GET /users/:id
    action :show

    # PUT /users/:id
    action :update

    # DELETE /users/:id
    action :destroy
  end
end
```
Put your Active Record configuration in
` config/database.yml `

To run it, you can create a config.ru file
``` ruby
# cat config.ru
require 'hello_traim.rb'

run Traim
```

Then run `rackup`.

Now, you already get a basic CRUD RESTful API from the User ActiveRecord model.

## Customizable action
By default, `action` can be easily used to create an endpoint for CRUD operations. You can write your own endpoint as well.
``` ruby
Traim.application do
  resources :users do
    model User

    attribute :id

    action :show do

      # attribute for single action
      attribute :name

      user = model.find_by_email params["email"]
      user.name = "[admin] #{user.name}"
      user
    end

    action :create
  end
end
```

Response
``` json
{"id": 1, "name": "[admin] travis"}
```

## Associations
Create a nested JSON reponse with an Active Record association
``` ruby
class User < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :user
end

Traim.application do
  resources :users do
    model User

    attribute :id
    attribute :name

    action :show

    has_many: books
  end

  resources :books do
    model Book

    attribute :isbn
  end
end
```

Response
``` json
{
  "id": 1,
  "name": "travis",
  "books": [
    {"isbn": "978-1-61-729109-8"},
    {"isbn": "561-6-28-209847-7"},
    {"isbn": "527-3-83-394862-5"}
  ]
}
```

## Member
Member block can add actions to a specific record with id
``` Ruby
Traim.application do
  resources :users do
    model User

    attribute :id
    attribute :name

    member :blurred do

      # GET /users/1/blurred
      show do
        record.name[1..2] = 'xx'
        record
      end
    end
  end
end
```

## Collection
Collection block can add actions to operate resources
``` Ruby
Traim.application do
  resources :users do
    model User

    attribute :id
    attribute :name

    collection :admin do

      # GET /users/admin
      show do
        model.all
      end

      # POST /users/admin
      create do
        model.create(params)
      end
    end
  end
end
```

## Namespaces
Organize groups of resources under a namespace. Most commonly, you might arrange resources for versioning.
``` ruby
Traim.application do
  namespace :api do
    namespace :v1 do
      resources :users do
        model User

        attribute :id
        attribute :name

        # endpoint: /api/v1/users
        action :show
      end
    end

    namespace :v2 do
      resources :users do
        model User

        attribute :id
        attribute :name

        # endpoint: /api/v2/users
        action :show
      end
    end
  end
end
```

## Helpers
You can define helper methods that your endpoints can use with the helpers to deal with some common flow controls, like authentication or authorization.
``` ruby
Traim.application do
  resources :users do
    helpers do
      def auth(user_id)
        raise BadRequestError.new(message: "unauthenticated request") unless model.exists?(id: user_id)

        # attribute can be added in helpers as well
        attribute :name
      end
    end

    model User

    attribute :id

    action :show do
      auth(params["id"])
      record
    end
  end
end
```

## Virtual attributes
Built-in attribute is generate response fields from model. Visual can help you present fields outside of model attributes.
``` ruby
Traim.application do
  resources :users do
    model User

    attribute :id
    attribute :name

    attribute :vattr do |record|
      "#{record.id} : #{record.email}"
    end

    action :show
  end
end
```

Response
``` json
{"id": 1, "name": "travis", "vattr": "1 : travis"}
```

### Parameters whitelist
Built-in model operations are using mass assignment. For security concern, Parameters can be whitelisted with permit option.
``` ruby
Traim.application do
  resources :users do
    model User

    attribute :id
    attribute :name

    action :create, permit: ["name"]
  end
end
```


text:
package com.atlassian.maven.plugins.jgitflow.exception;

/**
 * @since version
 */
public class ProjectRewriteException extends Exception
{
    public ProjectRewriteException()
    {
    }

    public ProjectRewriteException(String message)
    {
        super(message);
    }

    public ProjectRewriteException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public ProjectRewriteException(Throwable cause)
    {
        super(cause);
    }
}


text:
@interface Glf_ClearCacheTableViewCell : UITableViewCell

@property (nonatomic, copy) NSString *cacheSizeString;

@end


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61968.Customers;
using TTC2017.SmartGrids.CIM.IEC61968.Metering;
using TTC2017.SmartGrids.CIM.IEC61968.Work;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfOperations;

namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCustomers
{

    /// <summary>
    /// The public interface for PowerQualityPricing
    /// </summary>
    [DefaultImplementationTypeAttribute(typeof(PowerQualityPricing))]
    [XmlDefaultImplementationTypeAttribute(typeof(PowerQualityPricing))]
    public interface IPowerQualityPricing : IModelElement, IDocument
    {

        /// <summary>
        /// The valueUninterruptedServiceEnergy property
        /// </summary>
        float ValueUninterruptedServiceEnergy
        {
            get;
            set;
        }

        /// <summary>
        /// The voltImbalanceViolCost property
        /// </summary>
        float VoltImbalanceViolCost
        {
            get;
            set;
        }

        /// <summary>
        /// The voltLimitViolCost property
        /// </summary>
        float VoltLimitViolCost
        {
            get;
            set;
        }

        /// <summary>
        /// The emergencyLowVoltLimit property
        /// </summary>
        float EmergencyLowVoltLimit
        {
            get;
            set;
        }

        /// <summary>
        /// The valueUninterruptedServiceP property
        /// </summary>
        float ValueUninterruptedServiceP
        {
            get;
            set;
        }

        /// <summary>
        /// The emergencyHighVoltLimit property
        /// </summary>
        float EmergencyHighVoltLimit
        {
            get;
            set;
        }

        /// <summary>
        /// The powerFactorMin property
        /// </summary>
        float PowerFactorMin
        {
            get;
            set;
        }

        /// <summary>
        /// The normalLowVoltLimit property
        /// </summary>
        float NormalLowVoltLimit
        {
            get;
            set;
        }

        /// <summary>
        /// The normalHighVoltLimit property
        /// </summary>
        float NormalHighVoltLimit
        {
            get;
            set;
        }

        /// <summary>
        /// The PricingStructure property
        /// </summary>
        IPricingStructure PricingStructure
        {
            get;
            set;
        }

        /// <summary>
        /// The ServiceDeliveryPoints property
        /// </summary>
        IOrderedSetExpression<IServiceDeliveryPoint> ServiceDeliveryPoints
        {
            get;
        }

        /// <summary>
        /// Gets fired before the ValueUninterruptedServiceEnergy property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ValueUninterruptedServiceEnergyChanging;

        /// <summary>
        /// Gets fired when the ValueUninterruptedServiceEnergy property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ValueUninterruptedServiceEnergyChanged;

        /// <summary>
        /// Gets fired before the VoltImbalanceViolCost property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> VoltImbalanceViolCostChanging;

        /// <summary>
        /// Gets fired when the VoltImbalanceViolCost property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> VoltImbalanceViolCostChanged;

        /// <summary>
        /// Gets fired before the VoltLimitViolCost property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> VoltLimitViolCostChanging;

        /// <summary>
        /// Gets fired when the VoltLimitViolCost property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> VoltLimitViolCostChanged;

        /// <summary>
        /// Gets fired before the EmergencyLowVoltLimit property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> EmergencyLowVoltLimitChanging;

        /// <summary>
        /// Gets fired when the EmergencyLowVoltLimit property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> EmergencyLowVoltLimitChanged;

        /// <summary>
        /// Gets fired before the ValueUninterruptedServiceP property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ValueUninterruptedServicePChanging;

        /// <summary>
        /// Gets fired when the ValueUninterruptedServiceP property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ValueUninterruptedServicePChanged;

        /// <summary>
        /// Gets fired before the EmergencyHighVoltLimit property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> EmergencyHighVoltLimitChanging;

        /// <summary>
        /// Gets fired when the EmergencyHighVoltLimit property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> EmergencyHighVoltLimitChanged;

        /// <summary>
        /// Gets fired before the PowerFactorMin property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> PowerFactorMinChanging;

        /// <summary>
        /// Gets fired when the PowerFactorMin property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> PowerFactorMinChanged;

        /// <summary>
        /// Gets fired before the NormalLowVoltLimit property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> NormalLowVoltLimitChanging;

        /// <summary>
        /// Gets fired when the NormalLowVoltLimit property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> NormalLowVoltLimitChanged;

        /// <summary>
        /// Gets fired before the NormalHighVoltLimit property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> NormalHighVoltLimitChanging;

        /// <summary>
        /// Gets fired when the NormalHighVoltLimit property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> NormalHighVoltLimitChanged;

        /// <summary>
        /// Gets fired before the PricingStructure property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> PricingStructureChanging;

        /// <summary>
        /// Gets fired when the PricingStructure property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> PricingStructureChanged;
    }
}


text:
class ButtonControl
{
public:
    ButtonControl(const int buttonPinUp, const int buttonPinSelect, const int buttonPinDown);
    String getSize();
    int getUpState();
    int getDownState();
    int getSelectState();
    int getMenuState();
    int getValueSize();
    int getVolume();
    void readButtonStates();
    void setMenuState(bool state);

private:
   int _buttonPinUp;
   int _buttonPinDown;
   int _buttonPinSelect;
   int _currentPosition;
   int _sizeSelected;
   int _sizeOptions;
   bool _menuState;
};

#endif


text:
package com.google.gerrit.index.query;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.truth.ThrowableSubject;
import java.util.Collection;
import java.util.Objects;
import org.junit.Test;

public class QueryBuilderTest {
  private static class TestPredicate extends Predicate<Object> {
    private final String field;
    private final String value;

    TestPredicate(String field, String value) {
      this.field = field;
      this.value = value;
    }

    @Override
    public Predicate<Object> copy(Collection<? extends Predicate<Object>> children) {
      throw new UnsupportedOperationException();
    }

    @Override
    public int hashCode() {
      return Objects.hash(field, value);
    }

    @Override
    public boolean equals(Object o) {
      if (!(o instanceof TestPredicate)) {
        return false;
      }
      TestPredicate p = (TestPredicate) o;
      return Objects.equals(field, p.field) && Objects.equals(value, p.value);
    }
  }

  private static class TestQueryBuilder extends QueryBuilder<Object, TestQueryBuilder> {
    TestQueryBuilder() {
      super(new QueryBuilder.Definition<>(TestQueryBuilder.class), null);
    }

    @Operator
    public Predicate<Object> a(String value) {
      return new TestPredicate("a", value);
    }
  }

  @Test
  public void fieldNameAndValue() throws Exception {
    assertThat(parse("a:foo")).isEqualTo(new TestPredicate("a", "foo"));
  }

  @Test
  public void fieldWithParenthesizedValues() throws Exception {
    assertThatParseException("a:(foo bar)").hasMessageThat().contains("no viable alternative");
  }

  @Test
  public void fieldNameAndValueThatLooksLikeFieldNameColonValue() throws Exception {
    assertThat(parse("a:foo:bar")).isEqualTo(new TestPredicate("a", "foo:bar"));
  }

  @Test
  public void fieldNameAndValueThatLooksLikeWordColonValue() throws Exception {
    assertThat(parse("a:*:bar")).isEqualTo(new TestPredicate("a", "*:bar"));
  }

  @Test
  public void fieldNameAndValueWithMultipleColons() throws Exception {
    assertThat(parse("a:*:*:*")).isEqualTo(new TestPredicate("a", "*:*:*"));
  }

  @Test
  public void exactPhraseWithQuotes() throws Exception {
    assertThat(parse("a:\"foo bar\"")).isEqualTo(new TestPredicate("a", "foo bar"));
  }

  @Test
  public void exactPhraseWithQuotesAndColon() throws Exception {
    assertThat(parse("a:\"foo:bar\"")).isEqualTo(new TestPredicate("a", "foo:bar"));
  }

  @Test
  public void exactPhraseWithBraces() throws Exception {
    assertThat(parse("a:{foo bar}")).isEqualTo(new TestPredicate("a", "foo bar"));
  }

  @Test
  public void exactPhraseWithBracesAndColon() throws Exception {
    assertThat(parse("a:{foo:bar}")).isEqualTo(new TestPredicate("a", "foo:bar"));
  }

  private static Predicate<Object> parse(String query) throws Exception {
    return new TestQueryBuilder().parse(query);
  }

  private static ThrowableSubject assertThatParseException(String query) {
    try {
      new TestQueryBuilder().parse(query);
      throw new AssertionError("expected QueryParseException for " + query);
    } catch (QueryParseException e) {
      return assertThat(e);
    }
  }
}


text:
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using UWPHelper.UI;
using UWPHelper.Utilities;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace UWPHelper.SampleApp
{
    public sealed class AppData : ViewSpecificBindableClassBase<AppData>
    {
        private const string FILE_NAME = "AppData.json";

        private static AppData mainAppData;

        public static bool Loaded
        {
            get
            {
                return InstancesCount != 0;
            }
        }

        // Add every property to the GetForCurrentViewMethod cloning
        [JsonIgnore]
        public bool ShowLoadingError { get; set; }
        public int Foo
        {
            get { return (int)GetValue(); }
            set { SetValue(value); }
        }
        public bool? CheckBoxChecked
        {
            get { return (bool?)GetValue(); }
            set { SetValue(value); }
        }
        public SampleEnum SampleEnum
        {
            get { return (SampleEnum)GetValue(); }
            set { SetValue(value); }
        }
        public ElementTheme Theme
        {
            get { return (ElementTheme)GetValue(); }
            set { SetValue(value); }
        }
        public string Uri
        {
            get { return (string)GetValue(); }
            set { SetValue(value); }
        }

        public AppData()
        {
            IsPropertyChangedCallbackInvokingEnabled    = false;
            IsPropertyChangedEventInvokingEnabled       = false;

            RegisterProperty(nameof(Foo), typeof(int), 0);
            RegisterProperty(nameof(CheckBoxChecked), typeof(bool?), true);
            RegisterProperty(nameof(SampleEnum), typeof(SampleEnum), SampleEnum.Zero);
            RegisterProperty(nameof(Theme), typeof(ElementTheme), ThemeSelector.IsDefaultThemeAvailable ? ElementTheme.Default : ElementTheme.Dark, (sender, e) =>
            {
                SetTheme();
            });
            RegisterProperty(nameof(Uri), typeof(string), "");
        }

        public void SetTheme()
        {
            ((Frame)Window.Current.Content).RequestedTheme = Theme;
        }

        public Task SaveAsync()
        {
            return StorageHelper.SaveObjectAsync(this, FILE_NAME, ApplicationData.Current.LocalFolder);
        }

        public static async Task LoadAsync()
        {
#if DEBUG
            if (Loaded)
            {
                throw new Exception("You're not doing it right ;)");
            }
#endif

            StorageFileHelperLoadResult<AppData> loadResult = await StorageHelper.LoadObjectAsync<AppData>(FILE_NAME, ApplicationData.Current.LocalFolder);
            mainAppData                     = BaseGetForCurrentView(() => loadResult.LoadedObject);
            mainAppData.ShowLoadingError    = loadResult.Status == StorageFileHelperStatus.Failure;

            MainPropertyChanged += async (sender, e) =>
            {
                await mainAppData.SaveAsync();
            };

            mainAppData.IsPropertyChangedCallbackInvokingEnabled    = true;
            mainAppData.IsPropertyChangedEventInvokingEnabled       = true;
        }

        public static AppData GetForCurrentView()
        {
            return BaseGetForCurrentView(() => new AppData
            {
                Foo                                         = mainAppData.Foo,
                CheckBoxChecked                             = mainAppData.CheckBoxChecked,
                SampleEnum                                  = mainAppData.SampleEnum,
                Theme                                       = mainAppData.Theme,
                Uri                                         = mainAppData.Uri,
                IsPropertyChangedCallbackInvokingEnabled    = true,
                IsPropertyChangedEventInvokingEnabled       = true
            });
        }
    }
}


text:
<?php

class Braintree_HttpOAuth extends Braintree_HttpBase
{
    protected $_config;

    public function __construct($config)
    {
        $this->_config = $config;
    }

    public function delete($path)
    {
        $response = $this->_doRequest('DELETE', $path);
        if($response['status'] === 200) {
            return true;
        } else {
            Braintree_Util::throwStatusCodeException($response['status']);
        }
    }

    public function get($path)
    {
        $response = $this->_doRequest('GET', $path);
        if($response['status'] === 200) {
            return Braintree_Util::delimiterToCamelCaseArray(json_decode($response['body'], true), '_');
        } else {
            Braintree_Util::throwStatusCodeException($response['status']);
        }
    }

    public function post($path, $params = null)
    {
        $body = http_build_query(Braintree_Util::camelCaseToDelimiterArray($params, '_'));
        $response = $this->_doRequest('POST', $path, $body);
        $responseCode = $response['status'];
        if($responseCode === 200 || $responseCode === 201 || $responseCode === 422 || $responseCode === 400) {
            return Braintree_Util::delimiterToCamelCaseArray(json_decode($response['body'], true), '_');
        } else {
            Braintree_Util::throwStatusCodeException($responseCode);
        }
    }

    public function put($path, $params = null)
    {
        $body = http_build_query(Braintree_Util::camelCaseToDelimiterArray($params, '_'));
        $response = $this->_doRequest('PUT', $path, $body);
        $responseCode = $response['status'];
        if($responseCode === 200 || $responseCode === 201 || $responseCode === 422 || $responseCode === 400) {
            return Braintree_Util::delimiterToCamelCaseArray(json_decode($response['body'], true), '_');
        } else {
            Braintree_Util::throwStatusCodeException($responseCode);
        }
    }

    protected function _getHeaders()
    {
        return array(
            'Accept: application/json',
            'Content-Type: application/x-www-form-urlencoded',
        );
    }

    protected function _getAuthorization()
    {
        return array(
            'user' => $this->_config->getClientId(),
            'password' => $this->_config->getClientSecret(),
        );
    }
}


text:
/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//   Ludic Game Library                                                    //
//   Copyright (C)2014 - Michell Stuttgart Faria                           //
//                       Paulo Vicente Gomes dos Santos                    //
//                       Alfredo José de Paula Barbosa                     //
//                                                                         //
//   Ludic is a FREE SOFTWARE released under the BSD License.              //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////
#pragma once

#include "vector2_d.hpp"

namespace Ludic
{

#define VERTEX_I    0
#define VERTEX_F    1

/**
 * @file collisionBox.hpp
 * @author Michell Stuttgart
 * @date 02/20/14
 * @class CollisionBox
 * @brief Class used for collision checking by rectangles.
 *
 * Prove own methods of collision checking and positioning.
 * The Sprite, and AnimatedSprite StaticSprite class have
 * supports collision detection provided by CollisionBox class.
 */
class CollisionBox
{

private:

    Vector2D positions[2];
    float w, h;

public:

    /**
     * @brief Default Constructor. The initial dimension of box will be 0x0
     */
    CollisionBox();

    /**
     * @brief Parameter Constructor
     * @param position Vector2D object indicating the coordinates x, y CollisionBox on screen.
     * @param w The width of CollisionBox.
     * @param h The height of CollisionBox.
     */
    CollisionBox( const Vector2D &position, float _w, float _h );

    /**
     * @brief Default Destructor.
     */
    ~CollisionBox();

    /**
     * @brief Set the position of CollisionBox on screen.
     * @param position The Vector2D object initialized with desired coordinates.
     */
    void setPosition( const Vector2D &position );

    /**
    * @brief Set the dimension of CollisionBox.
    * @param w The new width of CollisionBox.
    * @param h The new height of CollisionBox.
    */
    void setDimension( float w, float h );

    /**
     * @brief performs a shift in the CollisionBox.
     * @param Vector2D represents the shift.
     */
    void move( const Vector2D &vec );

    /**
     * @brief Get the width of CollisionBox.
     * @return The width of CollisionBox.
     */
    int getWidth() const;

    /**
     * @brief Get the height of CollisionBox.
     * @return The height of ColissionBox.
     */
    int getHeight() const;

    /**
     * @brief Get the position of left-up corner of CollisionBox.
     * @return The Vector2D object containing the coordinates of left-up corner of CollisioBox.
     */
    const Vector2D &getPosition_i() const;

    /**
     * @brief Get the position of right-down corner of CollisionBox.
     * @return The Vector2D object containing the coordinates of right-down corner of CollisioBox.
     */
    const Vector2D &getPosition_f() const;

    /**
     * @brief Check the collision of other CollisionBox object.
     * Verify directly a collision between two CollisionBox.
     * @param r The reference a CollisionBox object that will be checked.
     * @return True id the collision occurred. False, otherwise.
     */
    bool checkCollision(const CollisionBox &r) const;

    /**
     * @brief Check the collision of other rectangle.
     *
     * @param x The x coordinate of rectangle.
     * @param y The y coordinate of rectangle.
     * @param w The width of rectangle.
     * @param h The height of rectangle.
     * @return True if the collision curred. False, otherwise.
     */
    bool checkCollision( int x, int y, int w, int h ) const;

};

} /* namespace */


text:
extern int generated_by_testExe1();
extern int generated_by_testExe3();
extern int generated_by_testExe4();
extern int testLib2();
extern int testLib3();
extern int testLib4();
extern int testLib4lib();
extern int testLib5();
extern int testLib6();
extern int testLib7();
extern int testLibCycleA1();
extern int testLibPerConfigDest();

/* Switch a symbol between debug and optimized builds to make sure the
   proper library is found from the testLib4 link interface.  */
#ifdef EXE_DBG
# define testLib4libcfg testLib4libdbg
#else
# define testLib4libcfg testLib4libopt
#endif
extern testLib4libcfg(void);

int main()
{
  return (testLib2() + generated_by_testExe1() + testLib3() + testLib4()
          + testLib5() + testLib6() + testLib7() + testLibCycleA1()
          + testLibPerConfigDest()
          + generated_by_testExe3() + generated_by_testExe4() + testLib4lib() + testLib4libcfg());
}