text:
#ifndef _H_TIRAMISU_BLOCK_
#define _H_TIRAMISU_BLOCK_

#include <tiramisu/core.h>

namespace tiramisu {

class computation;

/**
  * A class that represents a group of computations that share schedules up to
  * a level. This class is used for convenience when a set of scheduling
  * commands should be applied to several computations (i.e GPU kernels).
  */
class block: public computation {
private:

    /**
      * List of computations that this block contains. Actual order of the
      * computations is independent of the vector order and determined by the
      * scheduling commands.
      */
    const std::vector<computation *> children;

public:

    /**
      * \brief Constructor for block.
      *
      * \details This constructor creates a block of computations.
      *
      * In Tiramisu each computation should be scheduled separately. If the
      * user has multiple computations and wants to tile them for example,
      * the user has to apply the tiling command on each one of the computations
      * separately which is not convenient. The block class solves this problem.
      * It allows the user to create a block of computations. Any scheduling
      * command applied to the block is automatically applied to all of its
      * computations.
      *
      * \p children is the list of the computations of the block.
      *
      * The actual order of the computations is not determined by the vector
      * order. It is rather determined by the scheduling commands.
      */
    block(const std::vector<computation *> children);

    /**
      * Overriden scheduling methods from computation. These transformations
      * will be applied to all children of the block.
      */
    // @{
    void gpu_tile(var L0, var L1, int sizeX, int sizeY) override;
    void gpu_tile(var L0, var L1, int sizeX, int sizeY,
                  var L0_outer, var L1_outer,
                  var L0_inner, var L1_inner) override;
    void gpu_tile(var L0, var L1, var L2,
                  int sizeX, int sizeY, int sizeZ) override;
    void gpu_tile(var L0, var L1, var L2, int sizeX, int sizeY, int sizeZ,
                  var L0_outer, var L1_outer, var L2_outer,
                  var L0_inner, var L1_inner, var L2_inner) override;
    void interchange(var L0, var L1) override;
    void interchange(int L0, int L1) override;
    void parallelize(var L) override;
    void shift(var L0, int n) override;
    /*
    void skew(var i, var j, int f, var ni, var nj) override;
    void skew(var i, var j, var k, int factor, var ni, var nj, var nk) override;
    void skew(var i, var j, var k, var l, int factor,
              var ni, var nj, var nk, var nl) override;
    void skew(var i, var j, int factor) override;
    void skew(var i, var j, var k, int factor) override;
    void skew(var i, var j, var k, var l, int factor) override;
    void skew(int i, int j, int factor) override;
    void skew(int i, int j, int k, int factor) override;
    void skew(int i, int j, int k, int l, int factor) override;
    */
    void skew(var i, var j, int a, int b, var ni, var nj) override;
    void skew(int i, int j, int a, int b) override;
    void split(var L0, int sizeX) override;
    void split(var L0, int sizeX, var L0_outer, var L0_inner) override;
    void split(int L0, int sizeX) override;
    void storage_fold(var dim, int f) override;
    void tile(var L0, var L1, int sizeX, int sizeY) override;
    void tile(var L0, var L1, int sizeX, int sizeY, var L0_outer, var L1_outer,
              var L0_inner, var L1_inner) override;
    void tile(var L0, var L1, var L2, int sizeX, int sizeY, int sizeZ) override;
    void tile(var L0, var L1, var L2, int sizeX, int sizeY, int sizeZ,
              var L0_outer, var L1_outer, var L2_outer, var L0_inner,
              var L1_inner, var L2_inner) override;
    void tile(int L0, int L1, int sizeX, int sizeY) override;
    void tile(int L0, int L1, int L2, int sizeX, int sizeY, int sizeZ) override;
    void unroll(var L, int fac) override;
    void unroll(var L, int fac, var L_outer, var L_inner) override;
    void unroll(int L, int fac) override;
    void vectorize(var L, int v) override;
    void vectorize(var L, int v, var L_outer, var L_inner) override;
    // @}
};  // class block

}  // namespace tiramisu

#endif  // _H_TIRAMISU_BLOCK_


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _fixtures = require("../fixtures");

var _seriesCellVis = require("./seriesCellVis");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

describe('seriesCellVis', function () {
  test('series as array', function () {
    var series = [{
      cell_visualization: true,
      color: 'blue'
    }, {
      cell_visualization: false,
      visible: false
    }];
    var transformedConfig = (0, _seriesCellVis.seriesCellVis)({
      config: _objectSpread(_objectSpread({}, _fixtures.mockTableConfig), {}, {
        series: series
      }),
      data: _fixtures.mockSdkDataResponse,
      fields: _fixtures.mockFields
    });
    expect(transformedConfig.config.series).toEqual(series);
  });
  test('series as object', function () {
    var series = {
      'orders.count': {
        color: 'blue',
        visible: true
      },
      'orders.average_total_amount_of_order_usd': {
        color: 'red',
        label: 'Average',
        visible: false
      }
    };
    var series_cell_visualizations = {
      'orders.count': {
        is_active: true
      },
      'orders.average_total_amount_of_order_usd': {
        is_active: false
      }
    };
    var transformedConfig = (0, _seriesCellVis.seriesCellVis)({
      config: _objectSpread(_objectSpread({}, _fixtures.mockTableConfig), {}, {
        series: series,
        series_cell_visualizations: series_cell_visualizations
      }),
      data: _fixtures.mockSdkDataResponse,
      fields: _fixtures.mockFields
    });
    expect(transformedConfig.config.series).toEqual({
      'orders.count': _objectSpread({
        cell_visualization: true
      }, series['orders.count']),
      'orders.average_total_amount_of_order_usd': _objectSpread({
        cell_visualization: false
      }, series['orders.average_total_amount_of_order_usd'])
    });
  });
});
//# sourceMappingURL=seriesCellVis.spec.js.map

redpajama_set_name: RedPajamaGithub


text:
//
//  IFAudioEncoder.m
//  IFVideoPickerControllerDemo
//
//  Created by Min Kim on 3/27/13.
//  Copyright (c) 2013 iFactory Lab Limited. All rights reserved.
//

#import "IFAudioEncoder.h"

@interface IFAudioEncoder () {
}

@end

@implementation IFAudioEncoder

@synthesize assetWriterInput;
@synthesize sampleRate;
@synthesize bitRate;
@synthesize codec;

+ (IFAudioEncoder *)createAACAudioWithBitRate:(CGFloat)bitRate
                                   sampleRate:(CGFloat)sampleRate {
  IFAudioEncoder *encoder = [[[IFAudioEncoder alloc] init] autorelease];
  encoder.bitRate = bitRate;
  encoder.sampleRate = sampleRate;
  encoder.codec = kAudioFormatMPEG4AAC;
  [encoder setupWithFormatDescription:nil];
  return encoder;
}

- (void)setupWithFormatDescription:(CMFormatDescriptionRef)formatDescription {
  /*
  const AudioStreamBasicDescription *asbd =
      CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription);
	size_t aclSize = 0;
	const AudioChannelLayout *channelLayout =
      CMAudioFormatDescriptionGetChannelLayout(formatDescription, &aclSize);
	NSData *channelLayoutData = nil;

	// AVChannelLayoutKey must be specified, but if we don't know any better
  // give an empty data and let AVAssetWriter decide.
	if (channelLayout && aclSize > 0)
		channelLayoutData = [NSData dataWithBytes:channelLayout length:aclSize];
	else
   */
  NSData *channelLayoutData = [NSData data];

	NSDictionary *audioCompressionSettings =
      [NSDictionary dictionaryWithObjectsAndKeys:
          [NSNumber numberWithInteger:codec], AVFormatIDKey,
          [NSNumber numberWithFloat:sampleRate], AVSampleRateKey,
          [NSNumber numberWithInt:bitRate], AVEncoderBitRatePerChannelKey,
          [NSNumber numberWithInteger:1], AVNumberOfChannelsKey,
          channelLayoutData, AVChannelLayoutKey,
          nil];
	AVAssetWriterInput *newWriterInput =
      [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeAudio
                                     outputSettings:audioCompressionSettings];
  newWriterInput.expectsMediaDataInRealTime = YES;
  self.assetWriterInput = newWriterInput;
  [newWriterInput release];
}

- (void)dealloc {
  if (assetWriterInput != nil) {
    [assetWriterInput release];
  }

  [super dealloc];
}

@end


text:
Namespace::Namespace() {

}

Namespace::Namespace(std::vector<std::string> parts)
	: mParts(parts), mName(getName("::")), mVMName(getName(".")) {

}

std::string Namespace::getName(std::string sep) {
	return Helpers::join<std::string>(
		mParts,
		[](std::string part) { return part; },
		sep);
}

const std::vector<std::string>& Namespace::parts() const {
	return mParts;
}

std::string Namespace::name() const {
	return mName;
}

std::string Namespace::vmName() const {
	return mVMName;
}


text:
package component // import "go.opentelemetry.io/collector/component"

// Host represents the entity that is hosting a Component. It is used to allow communication
// between the Component and its host (normally the service.Collector is the host).
type Host interface {
	// ReportFatalError is used to report to the host that the component
	// encountered a fatal error (i.e.: an error that the instance can't recover
	// from) after its start function had already returned.
	//
	// ReportFatalError should be called by the component anytime after Component.Start() ends and
	// before Component.Shutdown() begins.
	ReportFatalError(err error)

	// GetFactory of the specified kind. Returns the factory for a component type.
	// This allows components to create other components. For example:
	//   func (r MyReceiver) Start(host component.Host) error {
	//     apacheFactory := host.GetFactory(KindReceiver,"apache").(component.ReceiverFactory)
	//     receiver, err := apacheFactory.CreateMetricsReceiver(...)
	//     ...
	//   }
	//
	// GetFactory can be called by the component anytime after Component.Start() begins and
	// until Component.Shutdown() ends. Note that the component is responsible for destroying
	// other components that it creates.
	GetFactory(kind Kind, componentType Type) Factory

	// GetExtensions returns the map of extensions. Only enabled and created extensions will be returned.
	// Typically is used to find an extension by type or by full config name. Both cases
	// can be done by iterating the returned map. There are typically very few extensions,
	// so there are no performance implications due to iteration.
	//
	// GetExtensions can be called by the component anytime after Component.Start() begins and
	// until Component.Shutdown() ends.
	GetExtensions() map[ID]Component

	// GetExporters returns the map of exporters. Only enabled and created exporters will be returned.
	// Typically is used to find exporters by type or by full config name. Both cases
	// can be done by iterating the returned map. There are typically very few exporters,
	// so there are no performance implications due to iteration.
	// This returns a map by DataType of maps by exporter configs to the exporter instance.
	// Note that an exporter with the same name may be attached to multiple pipelines and
	// thus we may have an instance of the exporter for multiple data types.
	// This is an experimental function that may change or even be removed completely.
	//
	// GetExporters can be called by the component anytime after Component.Start() begins and
	// until Component.Shutdown() ends.
	GetExporters() map[DataType]map[ID]Component
}


text:
#include "ExpressionParser.h"

ExpressionParser::ExpressionParser(const ExpressionLexer & input, int in_k):k(in_k),lexer(input),rpn(){
	lookahead = new Token[k];

	for(int i = 0; i < k; ++i)
		consume();
}

ExpressionParser::ExpressionParser(const ExpressionParser & rhs):k(rhs.k),lexer(rhs.lexer),p(rhs.p),rpn(rhs.rpn) {
	lookahead = new Token[k];
	for(int i = 0; i < k; ++i)
		lookahead[i] = rhs.lookahead[i];
}

ExpressionParser::~ExpressionParser(){
	delete [] lookahead;
}

ExpressionParser & ExpressionParser::operator=(const ExpressionParser & rhs){
	if(this != &rhs){
		ExpressionParser tmp(rhs);
		swap(tmp);
	}
	return *this;
}

void ExpressionParser::swap(ExpressionParser & rhs) {
	std::swap(k, rhs.k);
	std::swap(lexer,rhs.lexer);
	std::swap(p, rhs.p);
	std::swap(lookahead, rhs.lookahead);
	std::swap(rpn,rhs.rpn);
}

void ExpressionParser::consume() {
	lookahead[p] = lexer.nextToken();
	p = (++p) % k;
}

Token ExpressionParser::lookupToken(int i) const{
	return lookahead[(p+i-1) % k];
}

int ExpressionParser::lookupTokenType(int i) const{
	return lookupToken(i).getType();
}

void ExpressionParser::match(int x){
	if( lookupTokenType(1) == x) consume();

	else
		throw;
}

void ExpressionParser::parse(){
	/*Token t;
	t = lookupToken(1);

	while(t.getType() != Lexer::EOF_TYPE){
		lexer.displayToken(t);
		consume();
		t = lookupToken(1);
	}*/

	//expression();
	infixToRPN();
	/*while(!rpn.empty()){
		std::cout << rpn.front().getText() << " ";
		rpn.pop();
	}
	std::cout << std::endl;*/
	evaluate();

}

void ExpressionParser::infixToRPN(){
	//lexer.rewind();
	std::stack<Token> ops;
	Token t;
	int tmpType;

	while((t = lookupToken(1)).getType() != Lexer::EOF_TYPE){
		consume();
		tmpType = t.getType();
		if(tmpType == ExpressionLexer::SCALAR || tmpType == ExpressionLexer::MATRIX){
			rpn.push(t);
		} else if(isOperator(tmpType)){
			while(!ops.empty() && isOperator(ops.top().getType()) && tmpType/6 <= ops.top().getType()/6){
				rpn.push(ops.top());
				ops.pop();
			}
			ops.push(t);
		} else if(tmpType == ExpressionLexer::LPARENS){
			ops.push(t);
		} else if(tmpType == ExpressionLexer::RPARENS){
			while(ops.top().getType() != ExpressionLexer::LPARENS){
				rpn.push(ops.top());
				ops.pop();
				if(ops.empty())
					throw 10;
			}
			ops.pop();
		} else {
			throw 1;
		}
	}

	while(!ops.empty()){
		if(ops.top().getType() == ExpressionLexer::LPARENS){
			throw 10;
		} else {
			rpn.push(ops.top());
			ops.pop();
		}

	}
}

void ExpressionParser::evaluate() {

	Token t1,t2;
	bool matFlag = false;

	Matrix resultM;
	double resultS;

	std::stack<Token> values;

	while(!rpn.empty()){
		switch(rpn.front().getType()){
			case ExpressionLexer::MATRIX:
				matFlag = true;
			case ExpressionLexer::SCALAR:
				values.push(rpn.front());

				break;
			case ExpressionLexer::PLUS:
				t1 = values.top();
				values.pop();
				t2 = values.top();
				values.pop();

				if(matFlag){
					if(t1.getType() == ExpressionLexer::MATRIX && t2.getType() == ExpressionLexer::MATRIX){
						resultM = MatProps::add(Matrix(t1.getText()),Matrix(t2.getText()));
						values.push(Token(ExpressionLexer::MATRIX,resultM.to_str()));
					} else if(t1.getType() == ExpressionLexer::SCALAR && t2.getType() == ExpressionLexer::SCALAR){
						resultS = std::stod(t1.getText()) + std::stod(t2.getText());
						values.push(Token(ExpressionLexer::SCALAR,std::to_string(resultS)));
					} else {
						throw 2;
					}
				} else {
					resultS = std::stod(t1.getText()) + std::stod(t2.getText());
					values.push(Token(ExpressionLexer::SCALAR,std::to_string(resultS)));
				}

				break;

			case ExpressionLexer::MINUS:

				t1 = values.top();
				values.pop();
				t2 = values.top();
				values.pop();

				if(matFlag){
					if(t1.getType() == ExpressionLexer::MATRIX && t2.getType() == ExpressionLexer::MATRIX){
						resultM = MatProps::add(Matrix(t1.getText()),MatProps::multiply(-1,Matrix(t2.getText())));
						values.push(Token(ExpressionLexer::MATRIX,resultM.to_str()));
					} else if(t1.getType() == ExpressionLexer::SCALAR && t2.getType() == ExpressionLexer::SCALAR){
						resultS = std::stod(t1.getText()) - std::stod(t2.getText());
						values.push(Token(ExpressionLexer::SCALAR,std::to_string(resultS)));
					} else {
						throw 2;
					}
				} else {
					resultS = std::stod(t1.getText()) - std::stod(t2.getText());
					values.push(Token(ExpressionLexer::SCALAR,std::to_string(resultS)));
				}

				break;

			case ExpressionLexer::MULT:
				t1 = values.top();
				values.pop();
				t2 = values.top();
				values.pop();

				if(t1.getType() == ExpressionLexer::MATRIX && t2.getType() == ExpressionLexer::MATRIX){
					resultM = MatProps::multiply(Matrix(t1.getText()),Matrix(t2.getText()));
					values.push(Token(ExpressionLexer::MATRIX,resultM.to_str()));
				} else if(t1.getType() == ExpressionLexer::MATRIX && t2.getType() == ExpressionLexer::SCALAR){
					resultM = MatProps::multiply(Matrix(t1.getText()),std::stod(t2.getText()));
					values.push(Token(ExpressionLexer::MATRIX,resultM.to_str()));
				} else if(t1.getType() == ExpressionLexer::SCALAR && t2.getType() == ExpressionLexer::MATRIX){
					resultM = MatProps::multiply(std::stod(t1.getText()),Matrix(t2.getText()));
					values.push(Token(ExpressionLexer::MATRIX,resultM.to_str()));
				} else {
					resultS = std::stod(t1.getText()) * std::stod(t2.getText());
					values.push(Token(ExpressionLexer::SCALAR,std::to_string(resultS)));
				}

				break;

			case ExpressionLexer::DIVIDE:
				t1 = values.top();
				values.pop();
				t2 = values.top();
				values.pop();

				if(t1.getType() == ExpressionLexer::MATRIX && t2.getType() == ExpressionLexer::SCALAR){
					resultM = MatProps::divide(Matrix(t1.getText()),std::stod(t2.getText()));
					values.push(Token(ExpressionLexer::MATRIX,resultM.to_str()));
				} else if(t1.getType() == ExpressionLexer::SCALAR && t2.getType() == ExpressionLexer::MATRIX){
					resultM = MatProps::divide(std::stod(t1.getText()),Matrix(t2.getText()));
					values.push(Token(ExpressionLexer::MATRIX,resultM.to_str()));
				} else if(t1.getType() == ExpressionLexer::SCALAR && t2.getType() == ExpressionLexer::SCALAR){
					resultS = std::stod(t1.getText()) / std::stod(t2.getText());
					values.push(Token(ExpressionLexer::SCALAR,std::to_string(resultS)));
				} else {
					throw 2;
				}

				break;

		}
		rpn.pop();
	}

	if(matFlag){
		t1 = values.top();
		Matrix(t1.getText()).display();
	} else {
		std::cout << std::stod(values.top().getText()) << std::endl;
	}
}

void ExpressionParser::expression(){
	element();
	if(isOperator(lookupTokenType(1))) {
		op();
		expression();
	}
}

void ExpressionParser::op(){
	std::cout << "OPERATOR: ";
	lexer.displayToken(lookupToken(1));
	switch(lookupTokenType(1)){
		case ExpressionLexer::PLUS:
			match(ExpressionLexer::PLUS);
			break;
		case ExpressionLexer::MINUS:
			match(ExpressionLexer::MINUS);
			break;
		case ExpressionLexer::MULT:
			match(ExpressionLexer::MULT);
			break;
		case ExpressionLexer::DIVIDE:
			match(ExpressionLexer::DIVIDE);
			break;
		default:
			throw 1;
	}
}

void ExpressionParser::element(){
	std::cout << "ELEMENT: ";
	lexer.displayToken(lookupToken(1));
	if(lookupTokenType(1) == ExpressionLexer::SCALAR){
		match(ExpressionLexer::SCALAR);
	} else if(lookupTokenType(1) == ExpressionLexer::MATRIX){
		match(ExpressionLexer::MATRIX);
	} else {
		throw 1;
	}
}

bool ExpressionParser::isOperator(int type){
	return type >= ExpressionLexer::PLUS && type <= ExpressionLexer::DIVIDE;
}


text:
title: Docker design principles
description: Docker extension design
keywords: Docker, extensions, design
---

## Provide actionable guidance

We anticipate needs and provide simple explanations with clear actions so people are never lost and always know what to do next. Recommendations lead users to functionality that enhances the experience and extends their knowledge.

## Create value through confidence

People from all levels of experience should feel they know how to use our product. Experiences are familiar, unified, and easy to use so all users feel like experts.

## Infuse productivity with delight

We seek out moments of purposeful delight that elevate rather than distract, making work easier and more gratifying. Simple tasks are automated and users are left with more time for innovation.

## Build trust through transparency

We always provide clarity on what is happening and why. No amount of detail is withheld; the right information is shown at the right time and is always accessible.

## Scale with intention

Our products focus on inclusive growth and are continuously useful and adapt to match changing individual needs. We support all levels of expertise by meeting users where they are with conscious personalization.

## What's next?

- Take a look at our [UI styling guidelines](overview.md).
- Learn how to [publish your extension](../extensions/index.md).


text:
<?php use_helper('Text', 'I18N') ?>

<?php echo $article['title'] ?>

<?php echo simple_format_text($article['content']) ?>

<?php foreach (
  sfConfig::get('app_cultures_available', array()) as $lang): ?>

    <?php echo format_language($lang) ?>
    <?php echo link_to($article['Translation'][$lang]['title'],
                       'article', array(
      'sf_subject' => $article['Translation'][$lang],
      'sf_culture' => $lang,
    )) ?>

<?php endforeach; ?>

Comments

<?php foreach ($article['Comments'] as $comment): ?>

<?php echo $comment['Author']['name'] ?>

<?php echo $comment['content'] ?>

<?php endforeach; ?>

  <?php echo link_to('Back to list', 'article_index', array(
    'sf_culture' => $sf_user->getCulture(),
  )) ?>


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>My Project: nn_xrespondent Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

My Project

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Members

Public Attributes |
List of all members

nn_xrespondent Struct Reference

#include <xrespondent.h>

Collaboration diagram for nn_xrespondent:

<map name="nn__xrespondent_coll__map" id="nn__xrespondent_coll__map">
<area shape="rect" id="node2" href="structnn__fq.html" title="{nn_fq\n||}" alt="" coords="113,1139,167,1216"/>
<area shape="rect" id="node3" href="structnn__priolist.html" title="{nn_priolist\n|+ current\l|}" alt="" coords="99,936,180,1013"/>
<area shape="rect" id="node4" href="structnn__priolist__slot.html" title="{nn_priolist_slot\n||}" alt="" coords="85,549,195,627"/>
<area shape="rect" id="node5" href="structnn__list.html" title="{nn_list\n||}" alt="" coords="102,213,161,291"/>
<area shape="rect" id="node8" href="structnn__hash.html" title="{nn_hash\n|+ slots\l+ items\l|}" alt="" coords="5,718,75,810"/>
<area shape="rect" id="node23" href="structnn__timerset.html" title="{nn_timerset\n||}" alt="" coords="628,549,719,627"/>
<area shape="rect" id="node11" href="structnn__sock.html" title="{nn_sock\n|+ state\l+ flags\l+ termsem\l+ eid\l+ linger\l+ sndbuf\l+ rcvbuf\l+ rcvmaxsize\l+ sndtimeo\l+ rcvtimeo\land 19 more...\l|}" alt="" coords="456,1581,563,1805"/>
<area shape="rect" id="node6" href="structnn__list__item.html" title="{nn_list_item\n||}" alt="" coords="197,28,288,105"/>
<area shape="rect" id="node7" href="structnn__priolist__data.html" title="{nn_priolist_data\n|+ pipe\l+ priority\l|}" alt="" coords="186,206,299,298"/>
<area shape="rect" id="node30" href="structnn__socktype.html" title="{nn_socktype\n|+ domain\l+ protocol\l+ flags\l+ create\l+ ispeer\l|}" alt="" coords="367,323,463,459"/>
<area shape="rect" id="node9" href="structnn__sockbase.html" title="{nn_sockbase\n||}" alt="" coords="325,1869,424,1947"/>
<area shape="rect" id="node10" href="structnn__sockbase__vfptr.html" title="{nn_sockbase_vfptr\n|+ stop\l+ destroy\l+ add\l+ rm\l+ in\l+ out\l+ events\l+ send\l+ recv\l+ setopt\l+ getopt\l|}" alt="" coords="274,1581,405,1805"/>
<area shape="rect" id="node12" href="structnn__fsm.html" title="{nn_fsm\n|+ state\l+ src\l+ srcptr\l|}" alt="" coords="1140,1411,1207,1517"/>
<area shape="rect" id="node13" href="structnn__fsm__event.html" title="{nn_fsm_event\n|+ src\l+ srcptr\l+ type\l|}" alt="" coords="1245,1640,1349,1747"/>
<area shape="rect" id="node14" href="structnn__queue__item.html" title="{nn_queue_item\n||}" alt="" coords="1075,213,1185,291"/>
<area shape="rect" id="node17" href="structnn__queue.html" title="{nn_queue\n||}" alt="" coords="1091,549,1169,627"/>
<area shape="rect" id="node19" href="structnn__worker.html" title="{nn_worker\n|+ cp\l|}" alt="" coords="868,835,951,912"/>
<area shape="rect" id="node15" href="structnn__ctx.html" title="{nn_ctx\n||}" alt="" coords="984,1255,1045,1332"/>
<area shape="rect" id="node16" href="structnn__mutex.html" title="{nn_mutex\n|+ mutex\l|}" alt="" coords="989,549,1067,627"/>
<area shape="rect" id="node18" href="structnn__pool.html" title="{nn_pool\n||}" alt="" coords="899,1037,965,1115"/>
<area shape="rect" id="node20" href="structnn__poller__hndl.html" title="{nn_poller_hndl\n|+ fd\l+ events\l+ events\l+ index\l|}" alt="" coords="745,6,849,127"/>
<area shape="rect" id="node22" href="structnn__poller_1_1nn__hndls__item.html" title="{nn_poller::nn_hndls_item\n|+ prev\l+ next\l|}" alt="" coords="794,206,960,298"/>
<area shape="rect" id="node21" href="structnn__poller.html" title="{nn_poller\n|+ ep\l+ nevents\l+ index\l+ events\l+ kq\l+ events\l+ size\l+ capacity\l+ pollset\l+ removed\l|}" alt="" coords="794,483,877,693"/>
<area shape="rect" id="node24" href="structnn__clock.html" title="{nn_clock\n|+ last_tsc\l+ last_time\l|}" alt="" coords="502,206,588,298"/>
<area shape="rect" id="node25" href="structnn__efd.html" title="{nn_efd\n|+ efd\l+ r\l+ w\l+ r\l+ w\l+ fds\l|}" alt="" coords="1195,513,1256,663"/>
<area shape="rect" id="node26" href="structnn__thread.html" title="{nn_thread\n|+ routine\l+ arg\l+ handle\l+ handle\l|}" alt="" coords="525,527,603,649"/>
<area shape="rect" id="node27" href="structnn__optset.html" title="{nn_optset\n||}" alt="" coords="315,1425,393,1503"/>
<area shape="rect" id="node28" href="structnn__optset__vfptr.html" title="{nn_optset_vfptr\n|+ destroy\l+ setopt\l+ getopt\l|}" alt="" coords="291,1240,403,1347"/>
<area shape="rect" id="node29" href="structnn__ep__options.html" title="{nn_ep_options\n|+ sndprio\l+ rcvprio\l+ ipv4only\l|}" alt="" coords="625,1411,732,1517"/>
</map>

Public Attributes

struct nn_sockbase 	sockbase

uint32_t 	next_key

struct nn_hash 	outpipes

struct nn_fq 	inpipes

Member Data Documentation

          struct nn_fq nn_xrespondent::inpipes

          uint32_t nn_xrespondent::next_key

          struct nn_hash nn_xrespondent::outpipes

          struct nn_sockbase nn_xrespondent::sockbase

The documentation for this struct was generated from the following file:

src/protocols/survey/xrespondent.h

<address class="footer">
Generated by

 1.8.11
</address>


text:
.pad20 {padding-top: 20px !important;}
.pad20 > * {padding-top: 20px !important;}

.pad80 {padding-top: 80px !important;}
.pad80 > * {padding-top: 80px !important;}


text:
#import <ObjFW/ObjFW.h>
#import "PLSqlitePreparedStatement.h"

#import "OFException+NSException.h"

#include <assert.h>

#pragma mark Parameter Strategy

/**
 * @internal
 * Parameter fetching strategy.
 */
@protocol PLSqliteParameterStrategy <OFObject>

/**
 * Return the number of available parameters
 */
- (int) count;

/**
 * Return the value for the given parameter. May
 * return nil if the parameter is unavailable,
 * and NSNull if the parameter's value is null.
 */
- (id) valueForParameter: (int) parameterIndex withStatement: (sqlite3_stmt *) stmt;

@end

@interface PLSqliteArrayParameterStrategy : OFObject <PLSqliteParameterStrategy> {
@private
    OFArray *_values;
}
@end

/**
 * @internal
 * NSArray parameter strategy.
 */
@implementation PLSqliteArrayParameterStrategy

- (instancetype) initWithValues: (OFArray *) values {
    self = [super init];

    _values = [values retain];

    return self;
}

- (void) dealloc {
    [_values release];
    [super dealloc];
}

- (int) count {
    return (int)[_values count];
}

// from PLSqliteParameterStrategy protocol
- (id) valueForParameter: (int) parameterIndex withStatement: (sqlite3_stmt *) stmt {
    /* Arrays are zero-index, sqlite is 1-indexed, so adjust the index
     * for the array */
    return [_values objectAtIndex: parameterIndex - 1];
}

@end

@interface PLSqliteDictionaryParameterStrategy : OFObject <PLSqliteParameterStrategy> {
@private
    OFDictionary *_values;
}
@end

/**
 * @internal
 * NSDictionary parameter strategy.
 */
@implementation PLSqliteDictionaryParameterStrategy

- (instancetype) initWithValueDictionary: (OFDictionary *) values {
    self = [super init];

    _values = [values retain];

    return self;
}

- (void) dealloc {
    [_values release];
    [super dealloc];
}

- (int) count {
    return (int)[_values count];
}

// from PLSqliteParameterStrategy protocol
- (id) valueForParameter: (int) parameterIndex withStatement: (sqlite3_stmt *) stmt {
    const char *sqlite_name;

    /* Fetch the parameter name. */
    sqlite_name = sqlite3_bind_parameter_name(stmt, parameterIndex);

    /* If there is no name, or if it's blank, we can't retrieve the value. */
    if (sqlite_name == NULL || *sqlite_name == '\0')
        return NULL;

    /* Fetch the value, stripping the initial ':' characeter. */
    assert(*sqlite_name != '\0'); // checked above.
    return [_values objectForKey: [OFString stringWithUTF8String: sqlite_name + 1]];
}

@end

#pragma mark Private Declarations

@interface PLSqlitePreparedStatement (PLSqlitePreparedStatementPrivate)

- (int) bindValueForParameter: (int) parameterIndex withValue: (id) value;

- (void) assertNotClosed;
- (void) assertNotInUse;

- (PLSqliteResultSet *) checkoutResultSet;

@end

#pragma mark Public Implementation

/**
 * @internal
 * SQLite prepared query implementation.
 *
 * @par Thread Safety
 * PLSqlitePreparedStatement instances implement no locking and must not be shared between threads
 * without external synchronization.
 */
@implementation PLSqlitePreparedStatement

@synthesize database = _database;

/**
 * @internal
 *
 * Initialize the prepared statement with an open database and an sqlite3 prepared statement.
 *
 * @param db A reference to the managing PLSqliteDatabase instance.
 * @param statementCache The statement cache into which the backing sqlite3_stmt should be checked back in.
 * @param sqlite_stmt The prepared sqlite statement. This class will assume ownership of the reference.
 * @param queryString The original SQL query string, used for error reporting.
 * @param closeAtCheckin A flag specifying whether the statement should be closed at first checkin. Used to support returning
 * only the result set to a caller. When the result set is closed, the prepared statement is closed.
 *
 * MEMORY OWNERSHIP WARNING:
 * We are passed an sqlite3_stmt reference which now we now assume authority for releasing
 * that statement using sqlite3_finalize().
 *
 * @par Designated Initializer
 * This method is the designated initializer for the PLSqlitePreparedStatement class.
 */
- (instancetype) initWithDatabase: (PLSqliteDatabase *) db
         statementCache: (PLSqliteStatementCache *) statementCache
             sqliteStmt: (sqlite3_stmt *) sqlite_stmt
            queryString: (OFString *) queryString
         closeAtCheckin: (BOOL) closeAtCheckin
{
    self = [super init];
    /* Mark whether we should close when the first result set is checked in */
    _closeAtCheckin = closeAtCheckin;

    /* Save our database and statement reference. */
    _database = [db retain];
    _statementCache = [statementCache retain];
    _sqlite_stmt = sqlite_stmt;
    _queryString = [queryString retain];
    _inUse = NO;

    /* Cache parameter count */
    _parameterCount = sqlite3_bind_parameter_count(_sqlite_stmt);
    assert(_parameterCount >= 0); // sanity check

    return self;
}

- (void) dealloc {
    /* The statement must be released before the database is released, as the statement has a reference
     * to the database which would cause a SQLITE_BUSY error when the database is released. */
    [self close];

    /* Now release the database. */
    [_database release];

    /* Drop the statement cache reference */
    [_statementCache release];

    /* Release the query statement */
    [_queryString release];

    [super dealloc];
}

/* from PLPreparedStatement */
- (void) close {
    if (_sqlite_stmt == NULL)
        return;

    /* Check in the statement. */
    [_statementCache checkinStatement: _sqlite_stmt forQuery: _queryString];
    _sqlite_stmt = NULL;
}

/**
 * @internal
 *
 * Populate an NSError (if not nil) and log it, using this prepared statement's query string
 * and database connection. The vendor error code and message will be populated.
 *
 * Should only be called by PLSqliteResultSet.
 *
 * @param error Pointer to NSError instance to populate. If nil, the error message will be logged instead.
 * @param errorCode A PLDatabaseError error code.
 * @param description A localized description of the error message.
 */
- (void) populateError: (id *) error withErrorCode: (PLDatabaseError) errorCode description: (OFString *) description {
    [_database populateError: error withErrorCode: errorCode description: description queryString: _queryString];
}

/* from PLPreparedStatement */
- (int) parameterCount {
    [self assertNotClosed];

    return _parameterCount;
}

/**
 * @internal
 * Bind all parameters, fetching their value using the provided selector.
 */
- (void) bindParametersWithStrategy: (id<PLSqliteParameterStrategy>) strategy {
    [self assertNotInUse];

    /* Verify that a complete parameter list was provided */
    if ([strategy count] < _parameterCount)
        @throw [OFInvalidArgumentException exception]; //TODO: implement SQLIte specified exception
        //[NSException raise: PLSqliteException
                    //format: @"%@ prepared statement provided invalid parameter count (expected %d, but %d were provided)", [self class], _parameterCount, [strategy count]];

    /* Sqlite counts parameters starting at 1. */
    for (int valueIndex = 1; valueIndex <= _parameterCount; valueIndex++) {
        /* (Note that NSArray indexes from 0, so we subtract one to get the current value) */
        id value = [strategy valueForParameter: valueIndex withStatement: _sqlite_stmt];
        if (value == nil) {
            [OFException raise:PLSqliteException format:@"Missing parameter %d binding for query %@", valueIndex, _queryString];
        }

        /* Bind the parameter */
        int ret = [self bindValueForParameter: valueIndex
                                    withValue: value];

        /* If the bind fails, throw an exception (programmer error). */
        if (ret != SQLITE_OK) {
            @throw [OFInvalidArgumentException exception]; //TODO: implement SQLIte specified exception
            //[NSException raise: PLSqliteException
                        //format: @"SQlite error binding parameter %d for query %@: %@", valueIndex - 1, _queryString, [_database lastErrorMessage]];
        }
    }

    /* If you got this far, all is well */
}

/* from PLPreparedStatement */
- (void) bindParameters: (OFArray *) parameters {
    PLSqliteArrayParameterStrategy *strategy;

    strategy = [[[PLSqliteArrayParameterStrategy alloc] initWithValues: parameters] autorelease];
    [self bindParametersWithStrategy: strategy];
}

- (void) bindParameterDictionary: (OFDictionary *) parameters {
    PLSqliteDictionaryParameterStrategy *strategy;

    strategy = [[[PLSqliteDictionaryParameterStrategy alloc] initWithValueDictionary: parameters] autorelease];
    [self bindParametersWithStrategy: strategy];
}

/* from PLPreparedStatement */
- (BOOL) executeUpdate {
    return [self executeUpdateAndReturnError: NULL];
}

/* from PLPreparedStatement */
- (BOOL) executeUpdateAndReturnError: (id *) outError {
    [self assertNotInUse];

    PLSqliteResultSet *rs;
    BOOL ret;

    /* Execute the query */
    rs = (PLSqliteResultSet *)[self executeQueryAndReturnError: outError];
    if (rs == nil)
        return NO;

    /* Step the virtual machine once to execute the statement. */
    if ([rs nextAndReturnError: outError] == PLResultSetStatusError) {
        /* Error occured. outError has been populated. */
        ret = NO;
    } else {
        ret = YES;
    }

    /* Clean up the result set */
    [rs close];

    /* Finished */
    return ret;
}

/* from PLPreparedStatement */
- (id<PLResultSet>) executeQuery {
    return [self executeQueryAndReturnError: NULL];
}

/* from PLPreparedStatement */
- (id<PLResultSet>) executeQueryAndReturnError: (id *) outError {
    /*
     * Check out a new PLSqliteResultSet statement.
     * At this point, is there any way for the query to actually fail? It has already been compiled and verified.
     */
    return [self checkoutResultSet];
}

/**
 * @internal
 *
 * Check a result set back in, releasing any associated data
 * and releasing any exclusive ownership on the prepared statement.
 */
- (void) checkinResultSet: (PLSqliteResultSet *) resultSet {
    assert(_inUse == YES); // That would be strange.

    _inUse = NO;
    sqlite3_reset(_sqlite_stmt);

    /* If the statement is to be closed on the first checkin, do so, and
     * release our database resources */
    if (_closeAtCheckin)
        [self close];
}

@end

#pragma mark Private Implementation

/**
 * @internal
 *
 * Private PLSqliteDatabase methods.
 */
@implementation PLSqlitePreparedStatement (PLSqlitePreparedStatementPrivate)

/**
 * @internal
 * Assert that the result set has not been closed
 */
- (void) assertNotClosed {
    if (_sqlite_stmt == NULL)
        [OFException raise:PLSqliteException format:@"Attempt to access already-closed prepared statement."];
}

/**
 * @internal
 *
 * Assert that this instance is not in use by a PLSqliteResult.
 */
- (void) assertNotInUse {
    [self assertNotClosed];

    if (_inUse)
        [OFException raise:PLSqliteException format:@"A PLSqliteResultSet is already active and has not been properly closed for prepared statement '%@'", _queryString];
}

/**
 * @internal
 *
 * Check out a new PLSqliteResultSet, acquiring exclusive ownership
 * of the prepared statement. If another result set is currently checked
 * out, will throw an exception;
 */
- (PLSqliteResultSet *) checkoutResultSet {
    /* State validation. Only one result set may be checked out at a time */
    [self assertNotInUse];
    _inUse = YES;

   /*
    * MEMORY OWNERSHIP WARNING:
    * We pass our sqlite3_stmt reference to the PLSqliteResultSet, and gaurantee (by contract)
    * that the statement reference will remain valid until checkinResultSet is called for
    * the new PLSqliteResultSet instance.
    */
    return [[[PLSqliteResultSet alloc] initWithPreparedStatement: self sqliteStatemet: _sqlite_stmt] autorelease];
}

/**
 * @internal
 * Bind a value to a statement parameter, returning the SQLite bind result value.
 *
 * @param parameterIndex Index of parameter to be bound.
 * @param value Objective-C object to use as the value.
 */
- (int) bindValueForParameter: (int) parameterIndex withValue: (id) value {
    /* NULL */
    if (value == nil || value == [OFNull null]) {
        return sqlite3_bind_null(_sqlite_stmt, parameterIndex);
    }

    /* Data */
    else if ([value isKindOfClass: [OFData class]]) {
        OFData *data = (OFData *)value;
        return sqlite3_bind_blob(_sqlite_stmt, parameterIndex, data.items, (int)(data.count * data.itemSize), SQLITE_TRANSIENT);
    }

    /* Date */
    else if ([value isKindOfClass: [OFDate class]]) {
        return sqlite3_bind_double(_sqlite_stmt, parameterIndex, [value timeIntervalSince1970]);
    }

    /* String */
    else if ([value isKindOfClass: [OFString class]]) {
        return sqlite3_bind_text(_sqlite_stmt, parameterIndex, [value UTF8String], -1, SQLITE_TRANSIENT);
    }

    /* Number */
    else if ([value isKindOfClass: [OFNumber class]]) {
        OFNumber* val = value;
        of_number_type_t type = [val type];
        int64_t number = [val longLongValue];

        /* Handle floats and doubles */
        if (type == OF_NUMBER_TYPE_FLOAT || type == OF_NUMBER_TYPE_DOUBLE) {
            return sqlite3_bind_double(_sqlite_stmt, parameterIndex, [val doubleValue]);
        }

        /* If the value can fit into a 32-bit value, use that bind type. */
        else if (number <= INT32_MAX && number >= INT32_MIN) {
            return sqlite3_bind_int(_sqlite_stmt, parameterIndex, (int)number);

            /* Otherwise use the 64-bit bind. */
        } else {
            return sqlite3_bind_int64(_sqlite_stmt, parameterIndex, number);
        }
    }

    /* Not a known type */
    [OFException raise:PLSqliteException format:@"SQLite error binding unknown parameter type '%@'. Value: '%@'", [value class], value];

    /* Unreachable */
    OF_UNREACHABLE;
}

@end


text:
<?php

namespace Sylius\Component\Product\Model;

use Sylius\Component\Variation\Model\VariantInterface as BaseVariantInterface;

/**
 * Product variant interface.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
interface VariantInterface extends BaseVariantInterface
{
    /**
     * Get product.
     *
     * @return ProductInterface
     */
    public function getProduct();

    /**
     * Set product.
     *
     * @param |null $product
     */
    public function setProduct(ProductInterface $product = null);

    /**
     * Check whether the product is available.
     */
    public function isAvailable();

    /**
     * Return available on.
     *
     * @return \DateTime
     */
    public function getAvailableOn();

    /**
     * Set available on.
     *
     * @param \DateTime $availableOn
     */
    public function setAvailableOn(\DateTime $availableOn);
}


text:
/*--------------------------------------------------*/

#import "GLBWordPressSpinnerView.h"

/*--------------------------------------------------*/
#if defined(GLB_TARGET_IOS)
/*--------------------------------------------------*/

@implementation GLBWordPressSpinnerView

- (void)prepareAnimation {
    [super prepareAnimation];

    NSTimeInterval beginTime = CACurrentMediaTime();

    CALayer* spinner = [CALayer layer];
    spinner.frame = CGRectMake(0, 0, self.size, self.size);
    spinner.anchorPoint = CGPointMake(0.5, 0.5);
    spinner.transform = CATransform3DIdentity;
    spinner.backgroundColor = self.color.CGColor;
    spinner.rasterizationScale = UIScreen.mainScreen.scale;
    spinner.shouldRasterize = YES;
    [self.layer addSublayer:spinner];

    CAKeyframeAnimation* spinnerAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    spinnerAnimation.removedOnCompletion = NO;
    spinnerAnimation.repeatCount = HUGE_VALF;
    spinnerAnimation.duration = 1;
    spinnerAnimation.beginTime = beginTime;
    spinnerAnimation.keyTimes = @[
        @(0), @(0.25), @(0.5), @(0.75), @(1)
    ];
    spinnerAnimation.timingFunctions = @[
        [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear],
        [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear],
        [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear],
        [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear],
        [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]
    ];
    spinnerAnimation.values = @[
        [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0, 0, 1)],
        [NSValue valueWithCATransform3D:CATransform3DMakeRotation((CGFloat)(M_PI_2), 0, 0, 1)],
        [NSValue valueWithCATransform3D:CATransform3DMakeRotation((CGFloat)(M_PI), 0, 0, 1)],
        [NSValue valueWithCATransform3D:CATransform3DMakeRotation((CGFloat)(3 * M_PI_2), 0, 0, 1)],
        [NSValue valueWithCATransform3D:CATransform3DMakeRotation((CGFloat)(2 * M_PI), 0, 0, 1)]
    ];
    [spinner addAnimation:spinnerAnimation forKey:@"spinner-animation"];

    CAShapeLayer* circleMask = [CAShapeLayer layer];
    circleMask.frame = spinner.bounds;
    circleMask.fillColor = UIColor.blackColor.CGColor;
    circleMask.anchorPoint = CGPointMake(0.5, 0.5);

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddEllipseInRect(path, nil, spinner.frame);

    CGFloat circleSize = (CGFloat)(self.size * 0.25);
    CGPathAddEllipseInRect(path, nil, CGRectMake(CGRectGetMidX(spinner.frame) - (circleSize / 2), 3, circleSize, circleSize));
    CGPathCloseSubpath(path);
    circleMask.path = path;
    circleMask.fillRule = kCAFillRuleEvenOdd;
    CGPathRelease(path);

    spinner.mask = circleMask;
}

@end

/*--------------------------------------------------*/
#endif
/*--------------------------------------------------*/


text:
package org.elasticsearch.http.netty4;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.AttributeKey;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.network.CloseableChannel;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsException;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.http.AbstractHttpServerTransport;
import org.elasticsearch.http.HttpChannel;
import org.elasticsearch.http.HttpHandlingSettings;
import org.elasticsearch.http.HttpServerChannel;
import org.elasticsearch.http.netty4.cors.Netty4CorsConfig;
import org.elasticsearch.http.netty4.cors.Netty4CorsConfigBuilder;
import org.elasticsearch.http.netty4.cors.Netty4CorsHandler;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.netty4.Netty4Utils;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import static org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_CREDENTIALS;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_HEADERS;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_METHODS;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_ORIGIN;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ENABLED;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_MAX_AGE;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_CHUNK_SIZE;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_CONTENT_LENGTH;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_HEADER_SIZE;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_INITIAL_LINE_LENGTH;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_READ_TIMEOUT;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_TCP_KEEP_ALIVE;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_TCP_NO_DELAY;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_TCP_REUSE_ADDRESS;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_TCP_SEND_BUFFER_SIZE;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_PIPELINING_MAX_EVENTS;
import static org.elasticsearch.http.netty4.cors.Netty4CorsHandler.ANY_ORIGIN;

public class Netty4HttpServerTransport extends AbstractHttpServerTransport {

    static {
        Netty4Utils.setup();
    }

    /*
     * Size in bytes of an individual message received by io.netty.handler.codec.MessageAggregator which accumulates the content for an
     * HTTP request. This number is used for estimating the maximum number of allowed buffers before the MessageAggregator's internal
     * collection of buffers is resized.
     *
     * By default we assume the Ethernet MTU (1500 bytes) but users can override it with a system property.
     */
    private static final ByteSizeValue MTU = new ByteSizeValue(Long.parseLong(System.getProperty("es.net.mtu", "1500")));

    private static final String SETTING_KEY_HTTP_NETTY_MAX_COMPOSITE_BUFFER_COMPONENTS = "http.netty.max_composite_buffer_components";

    public static Setting<Integer> SETTING_HTTP_NETTY_MAX_COMPOSITE_BUFFER_COMPONENTS =
        new Setting<>(SETTING_KEY_HTTP_NETTY_MAX_COMPOSITE_BUFFER_COMPONENTS, (s) -> {
            ByteSizeValue maxContentLength = SETTING_HTTP_MAX_CONTENT_LENGTH.get(s);
            /*
             * Netty accumulates buffers containing data from all incoming network packets that make up one HTTP request in an instance of
             * io.netty.buffer.CompositeByteBuf (think of it as a buffer of buffers). Once its capacity is reached, the buffer will iterate
             * over its individual entries and put them into larger buffers (see io.netty.buffer.CompositeByteBuf#consolidateIfNeeded()
             * for implementation details). We want to to resize that buffer because this leads to additional garbage on the heap and also
             * increases the application's native memory footprint (as direct byte buffers hold their contents off-heap).
             *
             * With this setting we control the CompositeByteBuf's capacity (which is by default 1024, see
             * io.netty.handler.codec.MessageAggregator#DEFAULT_MAX_COMPOSITEBUFFER_COMPONENTS). To determine a proper default capacity for
             * that buffer, we need to consider that the upper bound for the size of HTTP requests is determined by `maxContentLength`. The
             * number of buffers that are needed depend on how often Netty reads network packets which depends on the network type (MTU).
             * We assume here that Elasticsearch receives HTTP requests via an Ethernet connection which has a MTU of 1500 bytes.
             *
             * Note that we are *not* pre-allocating any memory based on this setting but rather determine the CompositeByteBuf's capacity.
             * The tradeoff is between less (but larger) buffers that are contained in the CompositeByteBuf and more (but smaller) buffers.
             * With the default max content length of 100MB and a MTU of 1500 bytes we would allow 69905 entries.
             */
            long maxBufferComponentsEstimate = Math.round((double) (maxContentLength.getBytes() / MTU.getBytes()));
            // clamp value to the allowed range
            long maxBufferComponents = Math.max(2, Math.min(maxBufferComponentsEstimate, Integer.MAX_VALUE));
            return String.valueOf(maxBufferComponents);
            // Netty's CompositeByteBuf implementation does not allow less than two components.
        }, s -> Setting.parseInt(s, 2, Integer.MAX_VALUE, SETTING_KEY_HTTP_NETTY_MAX_COMPOSITE_BUFFER_COMPONENTS), Property.NodeScope);

    public static final Setting<Integer> SETTING_HTTP_WORKER_COUNT = new Setting<>("http.netty.worker_count",
        (s) -> Integer.toString(EsExecutors.numberOfProcessors(s) * 2),
        (s) -> Setting.parseInt(s, 1, "http.netty.worker_count"), Property.NodeScope);

    public static final Setting<ByteSizeValue> SETTING_HTTP_NETTY_RECEIVE_PREDICTOR_SIZE =
        Setting.byteSizeSetting("http.netty.receive_predictor_size", new ByteSizeValue(64, ByteSizeUnit.KB), Property.NodeScope);

    private final ByteSizeValue maxInitialLineLength;
    private final ByteSizeValue maxHeaderSize;
    private final ByteSizeValue maxChunkSize;

    private final int workerCount;

    private final int pipeliningMaxEvents;

    private final RecvByteBufAllocator recvByteBufAllocator;
    private final int readTimeoutMillis;

    private final int maxCompositeBufferComponents;

    protected volatile ServerBootstrap serverBootstrap;

    private final Netty4CorsConfig corsConfig;

    public Netty4HttpServerTransport(Settings settings, NetworkService networkService, BigArrays bigArrays, ThreadPool threadPool,
                                     NamedXContentRegistry xContentRegistry, Dispatcher dispatcher) {
        super(settings, networkService, bigArrays, threadPool, xContentRegistry, dispatcher);
        Netty4Utils.setAvailableProcessors(EsExecutors.PROCESSORS_SETTING.get(settings));

        this.maxChunkSize = SETTING_HTTP_MAX_CHUNK_SIZE.get(settings);
        this.maxHeaderSize = SETTING_HTTP_MAX_HEADER_SIZE.get(settings);
        this.maxInitialLineLength = SETTING_HTTP_MAX_INITIAL_LINE_LENGTH.get(settings);
        this.pipeliningMaxEvents = SETTING_PIPELINING_MAX_EVENTS.get(settings);

        this.maxCompositeBufferComponents = SETTING_HTTP_NETTY_MAX_COMPOSITE_BUFFER_COMPONENTS.get(settings);
        this.workerCount = SETTING_HTTP_WORKER_COUNT.get(settings);

        this.readTimeoutMillis = Math.toIntExact(SETTING_HTTP_READ_TIMEOUT.get(settings).getMillis());

        ByteSizeValue receivePredictor = SETTING_HTTP_NETTY_RECEIVE_PREDICTOR_SIZE.get(settings);
        recvByteBufAllocator = new FixedRecvByteBufAllocator(receivePredictor.bytesAsInt());

        this.corsConfig = buildCorsConfig(settings);

        logger.debug("using max_chunk_size[{}], max_header_size[{}], max_initial_line_length[{}], max_content_length[{}], " +
                "receive_predictor[{}], max_composite_buffer_components[{}], pipelining_max_events[{}]",
            maxChunkSize, maxHeaderSize, maxInitialLineLength, maxContentLength, receivePredictor, maxCompositeBufferComponents,
            pipeliningMaxEvents);
    }

    public Settings settings() {
        return this.settings;
    }

    @Override
    protected void doStart() {
        boolean success = false;
        try {
            serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings,
                HTTP_SERVER_WORKER_THREAD_NAME_PREFIX)));
            serverBootstrap.channel(NioServerSocketChannel.class);

            serverBootstrap.childHandler(configureServerChannelHandler());
            serverBootstrap.handler(new ServerChannelExceptionHandler(this));

            serverBootstrap.childOption(ChannelOption.TCP_NODELAY, SETTING_HTTP_TCP_NO_DELAY.get(settings));
            serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, SETTING_HTTP_TCP_KEEP_ALIVE.get(settings));

            final ByteSizeValue tcpSendBufferSize = SETTING_HTTP_TCP_SEND_BUFFER_SIZE.get(settings);
            if (tcpSendBufferSize.getBytes() > 0) {
                serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.getBytes()));
            }

            final ByteSizeValue tcpReceiveBufferSize = SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE.get(settings);
            if (tcpReceiveBufferSize.getBytes() > 0) {
                serverBootstrap.childOption(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.getBytes()));
            }

            serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
            serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

            final boolean reuseAddress = SETTING_HTTP_TCP_REUSE_ADDRESS.get(settings);
            serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
            serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress);

            bindServer();
            success = true;
        } finally {
            if (success == false) {
                doStop(); // otherwise we leak threads since we never moved to started
            }
        }
    }

    // package private for testing
    static Netty4CorsConfig buildCorsConfig(Settings settings) {
        if (SETTING_CORS_ENABLED.get(settings) == false) {
            return Netty4CorsConfigBuilder.forOrigins().disable().build();
        }
        String origin = SETTING_CORS_ALLOW_ORIGIN.get(settings);
        final Netty4CorsConfigBuilder builder;
        if (Strings.isNullOrEmpty(origin)) {
            builder = Netty4CorsConfigBuilder.forOrigins();
        } else if (origin.equals(ANY_ORIGIN)) {
            builder = Netty4CorsConfigBuilder.forAnyOrigin();
        } else {
            try {
                Pattern p = RestUtils.checkCorsSettingForRegex(origin);
                if (p == null) {
                    builder = Netty4CorsConfigBuilder.forOrigins(RestUtils.corsSettingAsArray(origin));
                } else {
                    builder = Netty4CorsConfigBuilder.forPattern(p);
                }
            } catch (PatternSyntaxException e) {
                throw new SettingsException("Bad regex in [" + SETTING_CORS_ALLOW_ORIGIN.getKey() + "]: [" + origin + "]", e);
            }
        }
        if (SETTING_CORS_ALLOW_CREDENTIALS.get(settings)) {
            builder.allowCredentials();
        }
        String[] strMethods = Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_METHODS.get(settings), ",");
        HttpMethod[] methods = Arrays.stream(strMethods)
            .map(HttpMethod::valueOf)
            .toArray(HttpMethod[]::new);
        return builder.allowedRequestMethods(methods)
            .maxAge(SETTING_CORS_MAX_AGE.get(settings))
            .allowedRequestHeaders(Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_HEADERS.get(settings), ","))
            .shortCircuit()
            .build();
    }

    @Override
    protected HttpServerChannel bind(InetSocketAddress socketAddress) throws Exception {
        ChannelFuture future = serverBootstrap.bind(socketAddress).sync();
        Channel channel = future.channel();
        Netty4HttpServerChannel httpServerChannel = new Netty4HttpServerChannel(channel);
        channel.attr(HTTP_SERVER_CHANNEL_KEY).set(httpServerChannel);
        return httpServerChannel;
    }

    @Override
    protected void stopInternal() {
        if (serverBootstrap != null) {
            serverBootstrap.config().group().shutdownGracefully(0, 5, TimeUnit.SECONDS).awaitUninterruptibly();
            serverBootstrap = null;
        }
    }

    @Override
    protected void onException(HttpChannel channel, Exception cause) {
        if (cause instanceof ReadTimeoutException) {
            if (logger.isTraceEnabled()) {
                logger.trace("Http read timeout {}", channel);
            }
            CloseableChannel.closeChannel(channel);
        } else {
            super.onException(channel, cause);
        }
    }

    public ChannelHandler configureServerChannelHandler() {
        return new HttpChannelHandler(this, handlingSettings);
    }

    static final AttributeKey<Netty4HttpChannel> HTTP_CHANNEL_KEY = AttributeKey.newInstance("es-http-channel");
    static final AttributeKey<Netty4HttpServerChannel> HTTP_SERVER_CHANNEL_KEY = AttributeKey.newInstance("es-http-server-channel");

    protected static class HttpChannelHandler extends ChannelInitializer<Channel> {

        private final Netty4HttpServerTransport transport;
        private final Netty4HttpRequestHandler requestHandler;
        private final HttpHandlingSettings handlingSettings;

        protected HttpChannelHandler(final Netty4HttpServerTransport transport, final HttpHandlingSettings handlingSettings) {
            this.transport = transport;
            this.handlingSettings = handlingSettings;
            this.requestHandler = new Netty4HttpRequestHandler(transport);
        }

        @Override
        protected void initChannel(Channel ch) throws Exception {
            Netty4HttpChannel nettyHttpChannel = new Netty4HttpChannel(ch);
            ch.attr(HTTP_CHANNEL_KEY).set(nettyHttpChannel);
            ch.pipeline().addLast("read_timeout", new ReadTimeoutHandler(transport.readTimeoutMillis, TimeUnit.MILLISECONDS));
            final HttpRequestDecoder decoder = new HttpRequestDecoder(
                handlingSettings.getMaxInitialLineLength(),
                handlingSettings.getMaxHeaderSize(),
                handlingSettings.getMaxChunkSize());
            decoder.setCumulator(ByteToMessageDecoder.COMPOSITE_CUMULATOR);
            ch.pipeline().addLast("decoder", decoder);
            ch.pipeline().addLast("decoder_compress", new HttpContentDecompressor());
            ch.pipeline().addLast("encoder", new HttpResponseEncoder());
            final HttpObjectAggregator aggregator = new HttpObjectAggregator(handlingSettings.getMaxContentLength());
            aggregator.setMaxCumulationBufferComponents(transport.maxCompositeBufferComponents);
            ch.pipeline().addLast("aggregator", aggregator);
            if (handlingSettings.isCompression()) {
                ch.pipeline().addLast("encoder_compress", new HttpContentCompressor(handlingSettings.getCompressionLevel()));
            }
            if (handlingSettings.isCorsEnabled()) {
                ch.pipeline().addLast("cors", new Netty4CorsHandler(transport.corsConfig));
            }
            ch.pipeline().addLast("pipelining", new Netty4HttpPipeliningHandler(transport.logger, transport.pipeliningMaxEvents));
            ch.pipeline().addLast("handler", requestHandler);
            transport.serverAcceptedChannel(nettyHttpChannel);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ExceptionsHelper.maybeDieOnAnotherThread(cause);
            super.exceptionCaught(ctx, cause);
        }
    }

    @ChannelHandler.Sharable
    private static class ServerChannelExceptionHandler extends ChannelHandlerAdapter {

        private final Netty4HttpServerTransport transport;

        private ServerChannelExceptionHandler(Netty4HttpServerTransport transport) {
            this.transport = transport;
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            ExceptionsHelper.maybeDieOnAnotherThread(cause);
            Netty4HttpServerChannel httpServerChannel = ctx.channel().attr(HTTP_SERVER_CHANNEL_KEY).get();
            if (cause instanceof Error) {
                transport.onServerException(httpServerChannel, new Exception(cause));
            } else {
                transport.onServerException(httpServerChannel, (Exception) cause);
            }
        }
    }
}


text:
using System;
using Server;
using Server.Mobiles;
using Server.Items;
using Server.Engines.Plants;
using Server.Engines.Quests;

namespace Server.Engines.Quests.Naturalist
{
	public class Naturalist : BaseQuester
	{
		[Constructable]
		public Naturalist() : base( "the Naturalist" )
		{
		}

		public override void InitBody()
		{
			InitStats( 100, 100, 25 );

			Hue = Utility.RandomSkinHue();

			Female = false;
			Body = 0x190;
			Name = NameList.RandomName( "male" );
		}

		public override void InitOutfit()
		{
			AddItem( new Tunic( 0x598 ) );
			AddItem( new LongPants( 0x59B ) );
			AddItem( new Boots() );

			Utility.AssignRandomHair( this );
			Utility.AssignRandomFacialHair( this, HairHue );
		}

		public override void OnTalk( PlayerMobile player, bool contextMenu )
		{
			StudyOfSolenQuest qs = player.Quest as StudyOfSolenQuest;

			if ( qs != null && qs.Naturalist == this )
			{
				StudyNestsObjective study = qs.FindObjective( typeof( StudyNestsObjective ) ) as StudyNestsObjective;

				if ( study != null )
				{
					if ( !study.Completed )
					{
						PlaySound( 0x41F );
						qs.AddConversation( new NaturalistDuringStudyConversation() );
					}
					else
					{
						QuestObjective obj = qs.FindObjective( typeof( ReturnToNaturalistObjective ) );

						if ( obj != null && !obj.Completed )
						{
							Seed reward;

							PlantType type;
							switch ( Utility.Random( 17 ) )
							{
								case 0: type = PlantType.CampionFlowers; break;
								case 1: type = PlantType.Poppies; break;
								case 2: type = PlantType.Snowdrops; break;
								case 3: type = PlantType.Bulrushes; break;
								case 4: type = PlantType.Lilies; break;
								case 5: type = PlantType.PampasGrass; break;
								case 6: type = PlantType.Rushes; break;
								case 7: type = PlantType.ElephantEarPlant; break;
								case 8: type = PlantType.Fern; break;
								case 9: type = PlantType.PonytailPalm; break;
								case 10: type = PlantType.SmallPalm; break;
								case 11: type = PlantType.CenturyPlant; break;
								case 12: type = PlantType.WaterPlant; break;
								case 13: type = PlantType.SnakePlant; break;
								case 14: type = PlantType.PricklyPearCactus; break;
								case 15: type = PlantType.BarrelCactus; break;
								default: type = PlantType.TribarrelCactus; break;
							}

							if ( study.StudiedSpecialNest )
							{
								reward = new Seed( type, PlantHue.FireRed, false );
							}
							else
							{
								PlantHue hue;
								switch ( Utility.Random( 3 ) )
								{
									case 0: hue = PlantHue.Pink; break;
									case 1: hue = PlantHue.Magenta; break;
									default: hue = PlantHue.Aqua; break;
								}

								reward = new Seed( type, hue, false );
							}

							if ( player.PlaceInBackpack( reward ) )
							{
								obj.Complete();

								PlaySound( 0x449 );
								PlaySound( 0x41B );

								if ( study.StudiedSpecialNest )
									qs.AddConversation( new SpecialEndConversation() );
								else
									qs.AddConversation( new EndConversation() );
							}
							else
							{
								reward.Delete();

								qs.AddConversation( new FullBackpackConversation() );
							}
						}
					}
				}
			}
			else
			{
				QuestSystem newQuest = new StudyOfSolenQuest( player, this );

				if ( player.Quest == null && QuestSystem.CanOfferQuest( player, typeof( StudyOfSolenQuest ) ) )
				{
					PlaySound( 0x42F );
					newQuest.SendOffer();
				}
				else
				{
					PlaySound( 0x448 );
					newQuest.AddConversation( new DontOfferConversation() );
				}
			}
		}

		public Naturalist( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.WriteEncodedInt( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadEncodedInt();
		}
	}
}


text:
package com.MisterBlock11.MagicCraft.blocks;

import java.util.List;

import com.MisterBlock11.MagicCraft.MagicCraft;
import com.MisterBlock11.MagicCraft.util.ExtendedPlayer;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.material.Material;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;

public class BlockChalk extends BlockMod {

	public BlockChalk() {
		super(Material.clay);
		setBlockName("chalk");
		setBlockTextureName(MagicCraft.MODID + ":" + getUnlocalizedName().substring(5));
		setHardness(3.5F);
		setResistance(5.0F);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@SideOnly(Side.CLIENT)
    public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean bool) {
		ExtendedPlayer props = ExtendedPlayer.get(player);
		if (GuiScreen.isShiftKeyDown()) {
			list.add("Purely decorative");
		} else {
			list.add(EnumChatFormatting.ITALIC.GREEN + "Hold Shift For More Info");
		}
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Taylor County Airport, WI</location>
	<station_id>KMDZ</station_id>
	<latitude>45.10462</latitude>
	<longitude>-90.30253</longitude>
	<observation_time>Last Updated on Jan 4 2016, 8:55 pm CST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 20:55:00 -0600</observation_time_rfc822>
	<weather>Fair</weather>
	<temperature_string>12.0 F (-11.2 C)</temperature_string>
	<temp_f>12.0</temp_f>
	<temp_c>-11.2</temp_c>
	<relative_humidity>76</relative_humidity>
	<wind_string>South at 8.1 MPH (7 KT)</wind_string>
	<wind_dir>South</wind_dir>
	<wind_degrees>160</wind_degrees>
	<wind_mph>8.1</wind_mph>
	<wind_kt>7</wind_kt>
	<pressure_in>30.40</pressure_in>
	<dewpoint_string>5.7 F (-14.6 C)</dewpoint_string>
	<dewpoint_f>5.7</dewpoint_f>
	<dewpoint_c>-14.6</dewpoint_c>
	<visibility_mi>10.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KMDZ.html</two_day_history_url>
	<icon_url_name>nskc.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KMDZ.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
	${nls.title}

		${nls.heightLabel}

				0
                     (± 0.00)
				<select class="unitsSelect" name="unitsSelect" data-dojo-attach-point="unitsSelect" data-dojo-type="dijit/form/Select"></select>


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

namespace NBAStatistics.DataInputSeeders
{
    public class Class1
    {
    }
}


text:
1. установите Django, использую менеджер пакетов apt
1. Определите установленную версию Django, используя интерпретатор python
1. Определите, установлены ли в системе `pip` и `virtualenv`. Если нет, установите их

## Работа с виртуальными окружениями

1. Создайте два виртуальных окружения `~/envs/bart` и `~/envs/lisa`. Окружение bart не должно иметь доступ к установленным в основной системе библиотекам python.
1. Активируйте окружение *bart*
1. Определите, сколько библиотек доступно изнутри окружения, используя `pip`
1. Установите django, используя `pip`
1. Активируйте окружение *lisa*
1. Используя `pip`, определите, что доступна библиотека django из родительского окружения
1. Используя `pip` установите Django версии 1.4.0
1. Убедитесь, что python теперь имеет доступ к Djando 1.4.0
1. Деактивируйте окружение *lisa* и удалите каталог с окружением *lisa*


text:
package com.svbio.cloudkeeper.model;

import com.svbio.cloudkeeper.model.util.ImmutableList;

import java.util.List;
import java.util.Objects;

/**
 * Signals that an exception occurred during linking.
 */
public class LinkerException extends Exception {
    private static final long serialVersionUID = 7123251199596227723L;

    private final ImmutableList<LinkerTraceElement> linkerTrace;

    /**
     * Constructs a new linker exception with the specified detail message and linker trace.
     *
     * <p>This method is equivalent to calling {@link #LinkerException(String, Throwable, java.util.List)} with
     * {@code null} as cause.
     *
     * @param message The detail message (which is saved for later retrieval by the {@link #getMessage()} method).
     * @param linkerTrace linker trace (which is saved for later retrieval by the {@link #getLinkerTrace()}
     *     method).
     * @throws NullPointerException if any of the arguments is {@code null}
     */
    public LinkerException(String message, List<LinkerTraceElement> linkerTrace) {
        this(message, null, linkerTrace);
    }

    /**
     * Constructs a new linker exception with the specified detail message and linker trace.
     *
     * @param message The detail message (which is saved for later retrieval by the {@link #getMessage()} method).
     * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). A {@code null}
     *     value is permitted, and indicates that the cause is nonexistent or unknown.
     * @param linkerTrace linker trace (which is saved for later retrieval by the {@link #getLinkerTrace()}
     *     method). An empty list is permitted, and indicates that the trace is unknown.
     * @throws NullPointerException if {@code message} or {@code linkerTrace} are {@code null}
     */
    public LinkerException(String message, Throwable cause, List<LinkerTraceElement> linkerTrace) {
        super(appendLinkerTrace(Objects.requireNonNull(message), Objects.requireNonNull(linkerTrace)), cause);
        this.linkerTrace = ImmutableList.copyOf(linkerTrace);
    }

    private static String appendLinkerTrace(String message, List<LinkerTraceElement> linkerTrace) {
        assert message != null && linkerTrace != null;

        if (linkerTrace.isEmpty()) {
            return message;
        } else {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(message).append("\n\nLinking backtrace:\n");
            for (LinkerTraceElement element: linkerTrace) {
                stringBuilder.append("    ").append(element).append('\n');
            }
            return stringBuilder.toString();
        }
    }

    /**
     * Returns the linker trace.
     *
     * The returned list cannot be modified.
     */
    public List<LinkerTraceElement> getLinkerTrace() {
        return linkerTrace;
    }
}


text:
#include <ctime>
#include <iostream>
#include <cassert>

#include "keystate/rollover_list_cmd.h"
#include "keystate/rollover_list_task.h"
#include "shared/duration.h"
#include "shared/file.h"
#include "shared/str.h"
#include "daemon/engine.h"

static const char *module_str = "rollover_list_cmd";

void help_rollover_list_cmd(int sockfd)
{
	ods_printf(sockfd,
	           "rollover list          List upcoming rollovers.\n");
}

int handled_rollover_list_cmd(int sockfd, engine_type* engine,
	const char *cmd, ssize_t n)
{
	char buf[ODS_SE_MAXLINE];
	const char *argv[8];
	const int NARGV = sizeof(argv)/sizeof(char*);
	int argc;
	const char *scmd = "rollover list";

	cmd = ods_check_command(cmd,n,scmd);
	if (!cmd)
		return 0; // not handled

	ods_log_debug("[%s] %s command", module_str, scmd);

	// Use buf as an intermediate buffer for the command.
	strncpy(buf,cmd,sizeof(buf));
	buf[sizeof(buf)-1] = '\0';

	// separate the arguments
	argc = ods_str_explode(buf,NARGV,argv);
	if (argc > NARGV) {
		ods_log_warning("[%s] too many arguments for %s command",
						module_str,scmd);
		ods_printf(sockfd,"too many arguments\n");
		return 1; // errors, but handled
	}

	bool bVerbose = ods_find_arg(&argc,argv,"verbose","v") != -1;
	if (argc) {
		ods_log_warning("[%s] unknown arguments for %s command",
						module_str,scmd);
		ods_printf(sockfd,"unknown arguments\n");
		return 1; // errors, but handled
	}

	time_t tstart = time(NULL);

	perform_rollover_list(sockfd, engine->config, bVerbose?1:0);

	ods_printf(sockfd,"%s completed in %ld seconds.\n",scmd,time(NULL)-tstart);

	return 1;
}


text:
declare module "plist" {
    export function build(json: any): string;
}

declare interface MapLike<T> {
    [s: string]: T;
}

declare interface TmGrammarRuleName {
    name: string;
}

declare interface TmGrammarRule {
    name?: string;
}
declare interface TmGrammarMatchRule extends TmGrammarRule {
    match: string;
    captures: MapLike<TmGrammarRuleName>;
}
declare interface TmGrammarBeginEndRule extends TmGrammarRule {
    contentName?: string;
    begin: string;
    end: string;
    beginCaptures?: MapLike<TmGrammarRuleName>;
    endCaptures?: MapLike<TmGrammarRuleName>;
    patterns: AnyTmGrammarRule[];
}
declare interface TmGrammarIncludeRule extends TmGrammarRule {
    include: string;
}
declare type AnyTmGrammarRule = TmGrammarMatchRule | TmGrammarBeginEndRule | TmGrammarIncludeRule;
declare interface TmGrammarRepositoryPatterns {
    patterns: AnyTmGrammarRule[];
}
declare type TmGrammarRepositaryRule = AnyTmGrammarRule | TmGrammarRepositoryPatterns;
declare interface TmGrammar {
    name: string;
    scopeName: string;
    fileTypes: string[];
    uuid: string;
    variables?: MapLike<string>;
    patterns?: AnyTmGrammarRule[];
    repository: MapLike<TmGrammarRepositaryRule>;
}

declare interface TmThemeSetting {
    scope: string;
    settings: { vsclassificationtype: string; };
}
declare interface TmTheme {
    name: string;
    uuid: string;
    settings: TmThemeSetting[];
}


text:
/* eslint-disable import/prefer-default-export */

export const SET_RUNTIME_VARIABLE = 'SET_RUNTIME_VARIABLE';

export const UPLOAD         = 'UPLOAD';
export const UPLOAD_LOADING = 'UPLOAD_LOADING';
export const UPLOAD_SUCCESS = 'UPLOAD_SUCCESS';
export const UPLOAD_ERROR   = 'UPLOAD_ERROR';

export const FETCH_LIST         = 'FETCH_LIST';
export const FETCH_LIST_LOADING = 'FETCH_LIST_LOADING';
export const FETCH_LIST_SUCCESS = 'FETCH_LIST_SUCCESS';
export const FETCH_LIST_ERROR   = 'FETCH_LIST_ERROR';

export const CHECK_FOLDERS         = 'CHECK_FOLDERS';
export const CHECK_FOLDERS_LOADING = 'CHECK_FOLDERS_LOADING';
export const CHECK_FOLDERS_SUCCESS = 'CHECK_FOLDERS_SUCCESS';
export const CHECK_FOLDERS_ERROR   = 'CHECK_FOLDERS_ERROR';

export const DELETE_FILE         = 'DELETE_FILE';
export const DELETE_FILE_LOADING = 'DELETE_FILE_LOADING';
export const DELETE_FILE_SUCCESS = 'DELETE_FILE_SUCCESS';
export const DELETE_FILE_ERROR   = 'DELETE_FILE_ERROR';

export const CHECK_INVALID_FILES         = 'CHECK_INVALID_FILES';
export const CHECK_INVALID_FILES_LOADING = 'CHECK_INVALID_FILES_LOADING';
export const CHECK_INVALID_FILES_SUCCESS = 'CHECK_INVALID_FILES_SUCCESS';
export const CHECK_INVALID_FILES_ERROR   = 'CHECK_INVALID_FILES_ERROR';

export const SYSTEM_STATS         = 'SYSTEM_STATS';
export const SYSTEM_STATS_LOADING = 'SYSTEM_STATS_LOADING';
export const SYSTEM_STATS_SUCCESS = 'SYSTEM_STATS_SUCCESS';
export const SYSTEM_STATS_ERROR   = 'SYSTEM_STATS_ERROR';

export const SYSTEM_TEMPERATURE         = 'SYSTEM_TEMPERATURE';
export const SYSTEM_TEMPERATURE_LOADING = 'SYSTEM_TEMPERATURE_LOADING';
export const SYSTEM_TEMPERATURE_SUCCESS = 'SYSTEM_TEMPERATURE_SUCCESS';
export const SYSTEM_TEMPERATURE_ERROR   = 'SYSTEM_TEMPERATURE_ERROR';


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150705_225506_view_count extends Migration
{
    public function up()
    {
        $this->addColumn('user', 'view_count', Schema::TYPE_INTEGER);
    }

    public function down()
    {
        echo "m150705_225506_view_count cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
import numpy as np

def load_inkml(path):
    print 'load inkml from ', path
    return 1


text:
import styled from 'styled-components'

import type { TMetric } from '@/spec'
import css, { WIDTH } from '@/utils/css'
import { pixelAdd } from '@/utils/dom'

import { BaseBanner } from '../index'

const getMinHeight = (isMobile) => {
  if (isMobile) {
    return '140px'
  }

  return '116px'
}

type TWrapper = {
  isMobile: boolean
  metric?: TMetric
}
export const Wrapper = styled(BaseBanner)<TWrapper>`
  width: 100%;
  min-height: ${({ isMobile }) => getMinHeight(isMobile)};
`
export const InnerWrapper = styled.div<TWrapper>`
  ${css.flex('justify-center')};
  padding-top: 10px;
  min-height: ${({ isMobile }) => getMinHeight(isMobile)};
  width: 100%;
  // if use margin-left will cause horizontal scrollbar
  // 70 是经典布局为缩小帖子列表"视觉宽度"手动缩小的值
  padding-left: ${pixelAdd(WIDTH.COMMUNITY.CONTENT_OFFSET, 70)};
  ${({ metric }) => css.fitPageWidth(metric)};
  transition: min-height 0.25s;

  ${css.media.mobile`
     padding-left: 0;
  `};
`
export const BaseBannerContent = styled.div`
  ${css.flexColumn('align-center')};
  width: 100%;
  max-width: ${WIDTH.COMMUNITY.CONTENT};

  ${css.media.mobile`
    padding-left: 6%;
    padding-right: 5.5%;
  `};
`
export const BannerContentWrapper = styled(BaseBannerContent)`
  ${css.flexColumn('justify-between')};
  align-items: 'center';
`
export const BannerContainer = styled(BaseBanner)`
  /* min-height: 125px; */
`
export const TabBarWrapper = styled.div`
  ${css.flex()};
  width: 100%;
  margin-left: -16px;

  ${css.media.tablet`
    padding-left: calc(2%);
  `};

  ${css.media.mobile`
    padding-left: 0;
    margin-left: -10px;
  `};
`
export const CommunityBaseInfo = styled.div`
  ${css.flex('justify-between')};
  width: 100%;
  padding-top: 20px;
  // 60 是经典布局为缩小帖子列表"视觉宽度"手动缩小的值
  padding-right: 60px;

  ${css.media.mobile`
    padding-right: 0;
  `};
`


text:
/*
---
description: Provides functionality for links that load content into a target element via ajax.
provides: [Delegator.Ajax]
requires: [Behavior/Delegator, Core/Request.HTML, More/Spinner]
script: Delegator.Ajax.js
name: Delegator.Ajax
...
*/

(function(){

	Delegator.register('click', 'Ajax', {
		require: ['target'],
		defaults: {
			action: 'injectBottom'
		},
		handler: function(event, link, api){
			var target,
				action = api.get('action'),
				selector = api.get('target');
			if (selector) {
				if (selector == "self") {
					target = element;
				} else {
					target = link.getElement(selector);
				}
			}

			if (!target) api.fail('ajax trigger error: element matching selector %s was not found', selector);

			var requestTarget = new Element('div');

			var spinnerTarget = api.get('spinner-target');
			if (spinnerTarget) spinnerTarget = link.getElement(spinnerTarget);

			event.preventDefault();
			new Request.HTML(
				Object.cleanValues({
					method: 'get',
					evalScripts: api.get('evalScripts'),
					url: api.get('href') || link.get('href'),
					spinnerTarget: spinnerTarget || target,
					useSpinner: api.getAs(Boolean, 'useSpinner'),
					update: requestTarget,
					onSuccess: function(){
						//reverse the elements and inject them
						//reversal is required since it injects each after the target
						//pushing down the previously added element
						var elements = requestTarget.getChildren();
						if (api.get('filter')){
							elements = new Element('div').adopt(elements).getElements(api.get('filter'));
						}
						switch(action){
							case 'replace':
								var container = target.getParent();
								elements.reverse().injectAfter(target);
								this.fireEvent('destroyDom', target);
								target.destroy();
								this.fireEvent('ammendDom', [container, elements]);
								break;
							case 'update':
								this.fireEvent('destroyDom', target.getChildren());
								target.empty();
								elements.inject(target);
								this.fireEvent('ammendDom', [target, elements]);
								break;
							default:
								//injectTop, injectBottom, injectBefore, injectAfter
								if (action == "injectTop" || action == "injectAfter") elements.reverse();
								elements[action](target);
								this.fireEvent('ammendDom', [target, elements]);
						}
					}.bind(this)
				})
			).send();
		}
	});

})();


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using ClipperLib;

namespace EnvelopeDistortion.Utility
{
    internal class ClipperUtility
    {
        private const int Scale = 1000;

        public static GraphicsPath unionTwo(ref GraphicsPath p1, ref GraphicsPath p2)
        {
            List<List<IntPoint>> polygonB = ConvertToClipperPolygons(p1);
            var polygons = new List<List<IntPoint>>();
            List<List<IntPoint>> polygonA = ConvertToClipperPolygons(p2);

            var c = new Clipper();
            c.AddPolygons(polygonB, PolyType.ptSubject);
            c.AddPolygons(polygonA, PolyType.ptClip);
            c.Execute(ClipType.ctUnion, polygons, PolyFillType.pftEvenOdd, PolyFillType.pftEvenOdd);

            return ConvertClipperToGraphicsPath(polygons);
        }

        internal static GraphicsPath Clip(List<List<IntPoint>> clippingPath, List<List<IntPoint>> distortionPoints)
        {
            var c = new Clipper();
            c.AddPolygons(distortionPoints, PolyType.ptSubject);
            c.AddPolygons(clippingPath, PolyType.ptClip);
            var polygons = new List<List<IntPoint>>();
            c.Execute(ClipType.ctIntersection, polygons, PolyFillType.pftEvenOdd, PolyFillType.pftEvenOdd);

            return ConvertClipperToGraphicsPath(polygons);
        }

        public static GraphicsPath ConvertClipperToGraphicsPath(List<List<IntPoint>> path)
        {
            var returnPath = new GraphicsPath();

            foreach (List<IntPoint> intPoints in path)
            {
                returnPath.AddPolygon(ToPointList(intPoints).ToArray());
            }
            return returnPath;
        }

        private static List<PointF> ToPointList(IEnumerable<IntPoint> pointList)
        {
            return pointList.Select(pt => new PointF((pt.X/(float) Scale), (pt.Y/(float) Scale))).ToList();
        }

        public static List<List<IntPoint>> ConvertToClipperPolygons(GraphicsPath path)
        {
            var Polygon = new List<IntPoint>();
            var Polygons = new List<List<IntPoint>>();

            var it = new GraphicsPathIterator(path);
            it.Rewind();
            for (int i = 0; i < it.SubpathCount; i++)
            {
                bool isClosed;
                int startIndex;
                int endIndex;
                it.NextSubpath(out startIndex, out endIndex, out isClosed);
                Polygon.AddRange(
                    path.PathPoints
                        .Skip(startIndex)
                        .Take((endIndex - startIndex) + 1)
                        .Select(x => new IntPoint(Convert.ToInt64(x.X*Scale), Convert.ToInt64(x.Y*Scale)))
                    );
                Polygons.Add(new List<IntPoint>(Polygon));
                Polygon.Clear();
            }
            it.Dispose();
            return Polygons;
        }

    }
}


text:
layout: post
title: Introduction to setting up a Go development environment VM
status: public
type: post
published: true
author: Ken Mugrage
---

The Go team has created a VirtualBox VM image to help people interested in development go get started quickly. This short video
shows the process of downloading and setting up the virtual machine.

The Vagrant box and Vagrantfile can be found at https://github.com/gocd/documentation/blob/master/developer/2/2.1.md

Please note: You _must_ have Vagrant 1.4.3+ and VirtualBox 4.3.6+ installed to use this environment.


text: <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
 package martin.mogrid.globus.service.dispatcher;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.globus.ftp.GridFTPClient;
import org.globus.ftp.Session;
import org.globus.ftp.exception.ClientException;
import org.globus.ftp.exception.ServerException;
import org.globus.gram.GramJob;
import org.globus.io.gass.server.GassServer;
import org.globus.io.gass.server.JobOutputListener;
import org.globus.io.gass.server.JobOutputStream;
import org.gridforum.jgss.ExtendedGSSManager;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;

public abstract class JobRequestConfiguration {

   class JobRequestOutputListenerStdout implements JobOutputListener {

      public synchronized void  outputChanged( String output ) {
             stdoutReturn = output;
       }

      public void outputClosed() {

      }

   }

   class JobRequestOutputListenerStderr implements JobOutputListener {

      public synchronized void  outputChanged( String output ) {
          stderrReturn = output;
       }

      public void outputClosed() {

      }

   }

     private        GassServer       gassServer   = null;
     private        String           gassURL      = null;
     private        JobOutputStream  stdoutStream = null;
     private        JobOutputStream  stderrStream = null;
     private        String           jobId        = null;
     private        GSSCredential    cred         = null;
     private        String           stdoutReturn    = null;
     private        String           stderrReturn    = null;

    private static final Logger logger = Logger.getLogger(JobRequestConfiguration.class);

    protected abstract void jobRequest( JobElements jobEl ) throws JobSubmitionException;

    protected boolean startGassServer() {

       ExtendedGSSManager manager = (ExtendedGSSManager) ExtendedGSSManager.getInstance();

       try {
          cred = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
          }
        catch ( GSSException ee ) {
          logger.error("Error in credential definition!");
          return false;
        }

        if (gassServer != null)
          return true;
        try {
          gassServer = new GassServer( cred, 0 );
          gassURL = gassServer.getURL();
        }
        catch (Exception e) {
            logger.error("Error in GassServer initialization!");
            e.printStackTrace();
            return false;
        }
         gassServer.registerDefaultDeactivator();
       return true;
     }

    protected void initJobOutListeners() {

       if (stdoutStream != null)
          return;
        stdoutStream = new JobOutputStream( new JobRequestOutputListenerStdout() );
        stderrStream = new JobOutputStream( new JobRequestOutputListenerStderr() );
        jobId = String.valueOf( System.currentTimeMillis() );

        gassServer.registerJobOutputStream( "err-" + jobId, stderrStream );
        gassServer.registerJobOutputStream( "out-" + jobId, stdoutStream );
        return;
    }

    public String createRsl( JobElements jobElements ) {
       String executable = jobElements.getExecutable();
       String arguments  = jobElements.getArguments();
       String srcDir     = jobElements.getJobId();
       String directory = "";

       if( srcDir != null)
          directory = "(directory="+srcDir+")";

       String args = "";

       if( arguments != null ) {
          args = " (arguments=" + arguments + ")";
       }

       String rsl = "&(executable=" + executable + ")" + directory + args +
                    " (stdout=" + gassURL + "/dev/stdout-" + jobId + ")" +
                    " (stderr=" + gassURL + "/dev/stderr-" + jobId + ")";

       return rsl;
    }

   public String getStdoutReturn(){
      return stdoutReturn;
   }

   public String getStderrReturn() {
      return stderrReturn;
   }

   public void copy( File[] files, String hostTo, String jobId ) throws JobStageException {

       boolean isConnected = false;
       String dir = null;
       String host     = null;
       GassServer gass;
       try {
          gass = new GassServer();
          host = gass.getHostname();
       } catch (IOException e) {
          throw new JobStageException("Couldn't get the host name", e );
       }

       logger.info( "Starting file stage" );

       for(int i=0;i<files.length;i++) {
          GridFTPClient origin      = null;
          GridFTPClient destination = null;

          try {
             logger.info( "Origin: " + host );
             origin = new GridFTPClient( host, 2811 );
             origin.authenticate(null);
             origin.setType(Session.TYPE_IMAGE);

             logger.info( "Destination: " + hostTo );
             destination = new GridFTPClient(hostTo,2811);
             destination.authenticate(null);

             dir = destination.getCurrentDir();
             if ( jobId != null )
                dir += File.separator + jobId ;
             if( !destination.exists( dir ) )
                destination.makeDir( dir );
             if( dir.equals("/") ) { //Quando o uduário não tem home dir a / é default
                logger.warn( "Couldn't find the user home dir: " + dir);
                throw new IOException( "Couldn't find the user home dir" );
             }
             destination.setType(Session.TYPE_IMAGE);

             String file = files[i].getName();
             String remoteSrcFile = files[i].getAbsolutePath();
             String remoteDstFile = dir+File.separator+file;

             logger.info( "Origin file "+remoteSrcFile );
             logger.info( "Destination file: "+remoteDstFile );

             if( destination.exists(remoteDstFile) ) {
                logger.info( "File already exists!" );
                continue;
             }
             origin.transfer( remoteSrcFile, destination, remoteDstFile, false, null );
             isConnected = true;

           } catch ( ServerException e ) {
              throw new JobStageException( "Problems in the server", e );
           } catch ( IOException e ) {
              throw new JobStageException( "Problems while copying the file", e );
           } catch ( ClientException e ) {
              throw new JobStageException( "Problems in the client", e );
           } finally {
              try {
                 if( isConnected ) {
                    if ( origin != null )
                       origin.close();
                    if ( destination != null )
                       destination.close();
                 }
            } catch (ServerException e) {
               throw new JobStageException( "Couldn't close the server", e );
            } catch (IOException e) {
               throw new JobStageException( e );
            }
          }
       }
       logger.info( "File stage successful" );
   }

   public void copy( JobElements jobEl ) throws JobStageException {
      File[] files = jobEl.getFiles();
      String hostTo   = jobEl.getHost();
      String jobId = jobEl.getJobId();

      copy( files, hostTo, jobId );
   }

   public void allowExecution( File[] files, String host, String jobId ) throws JobSubmitionException {

      logger.info( "Starting file permission change" );
      GramJob job        = null;
      String directory = "";

      if ( jobId != null) {
         directory = "(directory="+jobId +")";
      }
      for( int i = 0; i < files.length; i++ ) {

         String rsl = "&(executable =/bin/chmod)" +directory+
                      "(arguments= \"+x\" " + files[i].getName() + ")";

         logger.info( "Permission RSL: "+rsl );

         job = new GramJob( rsl );

         try {
            job.request( host, false );
         }catch( Exception e ) {
            throw new JobSubmitionException ("Error in changing the permition of the job", e );
         }
      }
      logger.info( "Permission change successful" );
   }

   public void allowExecution( JobElements jobEl ) throws JobSubmitionException {
      String  host       = jobEl.getHost();
      File[] files = jobEl.getFiles();
      String jobId = jobEl.getJobId();

      allowExecution( files, host, jobId );
   }

   public void deleteFilesStaged( JobElements jobElements ) throws JobSubmitionException {
      logger.info( "Starting file remotion" );
      File[] files = jobElements.getFiles();
      String host = jobElements.getHost();

      String args = "(arguments=";
      for( int i = 0; i < files.length; i++ ) {
         args += "\"" + files[i].getName() + "\"" + " ";
      }

      String rsl = "&(executable=/bin/rm)" + args + ")";
      GramJob job = new GramJob( rsl );
      try {
         job.request( host, false );
      } catch ( Exception e ) {
         throw new JobSubmitionException( "Erron in deleting the job", e );
      }
      logger.info( "File remotion successful" );
   }
}