text:
[ -z "$DEBUG" ] || set -x

export PATH=/var/vcap/packages/erlang/bin:$PATH

UPGRADE_PREPARATION_BINARY="/var/vcap/packages/rabbitmq-upgrade-preparation/bin/rabbitmq-upgrade-preparation"
LOG_DIR="/var/vcap/sys/log/rabbitmq-server"

write_log() {
  echo "$(date -u +"%Y-%m-%dT%H:%M:%SZ"): $*"
}

_run_rabbitmq_upgrade_preparation_on_every_node() {
  write_log "$STARTUP_LOG" "Preparing RabbitMQ for potential upgrade"

  local remote_nodes remote_node new_rabbitmq_version new_erlang_version rmq_server_package
  rmq_server_package="$1"
  erlang_package="$1"
  remote_nodes=($(cat /var/vcap/data/upgrade_preparation_nodes))
  new_rabbitmq_version="$(cat "$rmq_server_package/rmq_version")"
  new_erlang_version="$(cat "$erlang_package/erlang_version")"

  for remote_node in "${remote_nodes[@]}" ; do
    "$UPGRADE_PREPARATION_BINARY" \
      -rabbitmqctl-path "$rmq_server_package/bin/rabbitmqctl" \
      -node "$remote_node" \
      -new-rabbitmq-version "$new_rabbitmq_version" \
      -new-erlang-version "$new_erlang_version" \
      1> >(tee -a "$LOG_DIR/upgrade.log") 2>&1
  done
}

_prepare_for_upgrade () {
  if [ -z "$SKIP_PREPARE_FOR_UPGRADE" ]
  then
    _run_rabbitmq_upgrade_preparation_on_every_node "$1" "$2"
  fi
}

run_rabbitmq_upgrade_preparation_shutdown_cluster_if_cookie_changed () {
    local rmq_server_package="$4"

    if [[ ! -d $rmq_server_package ]]; then
      write_log "$rmq_server_package is not a valid directory" 1> >(tee -a "$LOG_DIR/upgrade.log") 2>&1
    fi

    "$UPGRADE_PREPARATION_BINARY" \
      -rabbitmqctl-path "$rmq_server_package/bin/rabbitmqctl" \
      shutdown-cluster-if-cookie-changed \
      -new-cookie "$1" \
      -old-cookie-path "$2" \
      -nodes "$3" \
      1> >(tee -a "$LOG_DIR/upgrade.log") 2>&1
}

run_prepare_for_upgrade_when_first_deploy() {
  local mnesia_dir="${1:?mnesia_dir must be provided as first argument}"
  local rmq_server_dir="${2:?rmq_server_dir must be provided as second argument}"
  local erlang_dir="${3:?erlang_dir must be provided as third argument}"

  if [ -d "$mnesia_dir" ] && [ -d "$rmq_server_dir" ] && [ -d "$erlang_dir" ]
  then
    _prepare_for_upgrade "$rmq_server_dir" "$erlang_dir"
  fi
}


text:
/*
 * rpcserver.cpp
 *
 *  Created on: 28. 2. 2017
 *      Author: ondra
 */

#include  <condition_variable>
#include <mutex>
#include "rpc.h"

#include "array.h"
#include "object.h"
#include "operations.h"
#include "validator.h"
#include "fnv.h"
namespace json {

RpcRequest::ParseRequest::ParseRequest(const Value & request) {

	methodName = request["method"];
	params = request["params"];
	context = request["context"];
	id = request["id"];
	version = request["jsonrpc"];

}

RpcRequest::ParseRequest::ParseRequest(const Value &methodName, const Value &params, const Value &id, const Value &context, const Value &version)
	:methodName(methodName)
	,params(params)
	,id(id)
	,context(context)
	,version(version) {}

template<std::size_t pos>
static inline Value pick(const std::initializer_list<Value> &items) {
	if (pos < items.size()) return *(items.begin()+pos); else return Value();
}

RpcRequest::ParseRequest::ParseRequest(const std::initializer_list<Value> &items)
	:methodName(pick<0>(items))
	,params(pick<1>(items))
	,id(pick<2>(items))
	,context(pick<3>(items))
	,version(pick<4>(items))
{

}

RpcRequest::RequestData::RequestData(const ParseRequest& request, RpcFlags::Type flags,const PRpcConnContext &connctx)
	:ParseRequest(request), flags(flags),connctx(connctx)
{

	if (params.type() != array) {
		if (params.type() != object || (flags & RpcFlags::namedParams) == 0) {
			params = Value(array, {params});
		}
	}
	if (flags & RpcFlags::preResponseNotify) notifyEnabled = true;
}

Value RpcServer::defaultFormatError(int code, const String& message, Value data) {
	return Value(object,{
			Value("code",code),
			Value("message",message),
			Value("data",data)
	});
}

static Value formatNotify(RpcVersion ver, const String name, Value data, Value context) {
	Value obj;
	switch (ver) {
	case RpcVersion::ver1:
		obj = Object("id", nullptr)("method", name)("params", data)("context",context);
		break;
	case RpcVersion::ver2:
		obj = Object("method", name)("params", data)("jsonrpc", "2.0")("context",context);
		break;
	}
	return obj;
}

const Value& RpcRequest::getMethodName() const {
	return data->methodName;
}

const Value& RpcRequest::getArgs() const {
	return data->params;
}

const Value& RpcRequest::getParams() const {
	return data->params;
}

const Value& RpcRequest::getId() const {
	return data->id;
}

const Value& RpcRequest::getContext() const {
	return data->context;
}

void RpcRequest::RequestData::sendResult(const Value &result, const Value &context) {
	if (id.defined() && !id.isNull() && !responseSent) {
		Value ctxch = context.empty()? Value():context;
		switch (getVersion()) {
		case RpcVersion::ver1:
				return postSendResponse(
					response(Object("id",id)
									 ("result",result)
									 ("error",nullptr)
									 ("context",ctxch)));

		case RpcVersion::ver2:
			return postSendResponse(
					response(Object("id",id)
							 ("result",result)
							 ("jsonrpc","2.0")
							 ("context",ctxch)));
		}
	}
}
void RpcRequest::RequestData::sendError(const Value &error) {
	if (id.defined() && !id.isNull() && !responseSent) {
		responseSent = true;
		errorSent = true;
		switch (getVersion()) {
		case RpcVersion::ver1:
			return postSendResponse(
					response(Object("id",id)
								 ("error",error)
								 ("result",nullptr)));
		case RpcVersion::ver2:
			return postSendResponse(
					response(Object("id",id)
							 ("error",error)
							 ("jsonrpc","2.0")));
				return;
		}
	}

}
void RpcRequest::RequestData::postSendResponse(bool sendResult) {
	responseSent = true;
	notifyEnabled =  (flags & RpcFlags::postResponseNotify) != 0 && sendResult;
}

bool RpcRequest::RequestData::sendNotify(const RpcNotify &notify) {
	if (notifyEnabled) {
		notifyEnabled = response(formatNotify(getVersion(),notify.eventName, notify.data, notify.context));
	}
	return notifyEnabled;

}
bool RpcRequest::RequestData::sendCallback(RpcRequest request) {
	request.setError(RpcServer::errorCallbackIsNotSupported,"Callback is not supported");
	return true;
}

void RpcRequest::setResult(const Value& result) {
	setResult(result, undefined);

}

void RpcRequest::setResult(const Value& result, const Value& context) {

	data->sendResult(result,context);
	/*
	Value resp;
	Value ctxch = context.empty()?Value():context;
	switch (data->ver) {
	case RpcVersion::ver1:
		resp = Object("id",data->id)
				("result",result)
				("error",nullptr)
				("context", ctxch);
		break;
	case RpcVersion::ver2:
		resp = Object("id",data->id)
				("result",result)
				("jsonrpc","2.0")
				("context", ctxch);
		break;
	}
	*/

	//data->setResponse(resp);

}

void RpcRequest::setError(const Value& error) {
	data->sendError(error);
	/*
	Value resp;
	switch (data->ver) {
	case RpcVersion::ver1:
		resp = Object("id",data->id)
				("result",nullptr)
				("error",error);;
		break;
	case RpcVersion::ver2:
		resp = Object("id",data->id)
				("error",error)
				("jsonrpc","2.0");
		break;
	}

	return data->setResponse(resp);
	*/
}

Value RpcRequest::operator [](unsigned int index) const {
	return data->params[index];
}

Value RpcRequest::operator [](const StrViewA name) const {
	return data->context[name];
}

class RpcArgValidator: public Validator {
public:
	RpcArgValidator():Validator(object) {}
	RpcArgValidator(const Value &customClasses):Validator(customClasses) {}

	bool checkArgs(const Value &subject, const Value &pattern) {
		curPath = &Path::root;
		return evalRuleArray(subject, pattern, pattern.size(),0);
	}
};

void RpcRequest::setDiagData(Value v) {
	data->diagData = v;
}
///Retrieve diagnostic data
const Value &RpcRequest::getDiagData() const {
	return data->diagData;
}

bool RpcRequest::checkArgs(const Value& argDefTuple) {
	if (argDefTuple.type() != json::array) return checkArgs(Value(array, {argDefTuple}));
	Value v = data->srvsvc->validateArgs(data->params,argDefTuple);
	if (v.isNull() || !v.defined()) return true;
	data->rejections = v;
	return false;
}

Value RpcRequest::getRejections() const {
	return data->rejections;
}

void RpcRequest::setArgError(Value rejections) {
	setError(-32602, "Invalid params", rejections);
}

void RpcRequest::setArgError() {
	return setArgError(getRejections());
}

void RpcRequest::setError(int code, String message, Value d) {
	if (data->srvsvc == nullptr) {
		return setError(RpcServer::defaultFormatError(code,message,d));
	} else {
		return setError(data->srvsvc->formatError(code,message,d));
	}
}

void RpcServer::operator ()(const RpcRequest &req) const noexcept {
	exec(req);
}
void RpcServer::exec( RpcRequest req) const noexcept {
	try {
		req.init(this);
		Value name = req.getMethodName();
		Value args = req.getArgs();
		Value context = req.getContext();
		if (name.defined() && name.type() == string && (args.type() == array || args.type() == object || args.type() == undefined)
				&& (!context.defined() || context.type() == object)) {
			AbstractMethodReg *m = find(name.getString());
			if (m == nullptr) {
				if (proxy != nullptr)
					if (proxy(req)) return;
				req.setError(errorMethodNotFound,"Method not found",name);
			} else {
				m->call(req);
			}
		} else {
			req.setError(errorInvalidRequest,"Invalid request");
		}
	} catch (std::exception &e) {
		try {
			if (exception_handler==nullptr || !exception_handler(req))
					req.setInternalError(e.what());
		} catch (...) {
			req.setInternalError(e.what());
		}
	} catch (...) {
		try {
			if (exception_handler==nullptr || !exception_handler(req))
					req.setInternalError(nullptr);
		} catch (...) {
			req.setInternalError(nullptr);
		}
	}
}

void RpcServer::remove(const StrViewA& name) {
	mapReg.erase(name);
}

void RpcServer::removeAll() {
	mapReg.clear();
}

RpcServer::AbstractMethodReg* RpcServer::find(const StrViewA& name) const {
	auto f = mapReg.find(name);
	if (f == mapReg.end()) return nullptr;
	return &(*(f->second));
}

void RpcServer::add_listMethods(const String& name) {
	add(name, [this](RpcRequest req){

		Array res;
		for(auto &x : mapReg) {
			res.push_back(x.second->name);
		}
		Value r(res);

		if (proxy != nullptr) {
			auto proxyReq = RpcRequest::create(RpcRequest::ParseRequest(
							req.getMethodName(),
							req.getArgs(),
							req.getId(),
							req.getContext(),
							req.getVersionField()),
					[=](Value resp) mutable {

					Array res2(r);
					res2.addSet(resp["result"]);
					req.setResult(res2);

					return true;
				});
			if (proxy(proxyReq)) return;

		}
		req.setResult(r);
	});
}

class MulticallContext {
public:
	typedef std::function<std::pair<Value,Value>()> NextFn;
	Array results;
	Array errors;
	Value context;
	Value contextchange;

	std::atomic<int> mtfork;

	RpcRequest req;
	NextFn nextfn;
	RpcServer &server;

	MulticallContext(RpcServer &server, RpcRequest req, const NextFn &nextFn):req(req),nextfn(nextFn),server(server) {
		context = req.getContext();

	}

	void run() {
		do {
			auto p = nextfn();
			mtfork = 0;
			if (p.first.defined()) {
				RpcRequest::ParseRequest pr (p.first, p.second, req.getId(), context, req.getVersionField());
				class CBS: public RpcRequest::Callbacks {
				public:
					virtual bool onResult(const RpcRequest &, const Value &res, const Value &ctx) noexcept override  {
						owner.results.push_back(res);
						if (ctx.defined()) {
							owner.context = AbstractRpcClient::updateContext(owner.context,ctx);
							owner.contextchange = AbstractRpcClient::updateContext(owner.contextchange,ctx);
						}
						if (++owner.mtfork == 2) {
							owner.run();
						}
						return true;
					}
					virtual bool onError(const RpcRequest &, const Value &err) noexcept override  {
						owner.results.push_back(Value(nullptr));
						owner.errors.push_back(err);
						if (++owner.mtfork == 2) {
							owner.run();
						}
						return true;
					}
					virtual bool onNotify(const RpcRequest &, const RpcNotify &ntf) noexcept override  {
						return req.sendNotify(ntf.eventName, ntf.data);
					}
					virtual bool onCallback(const RpcRequest &, RpcRequest &) noexcept override  {
						return false;
					}

					MulticallContext &owner;
					RpcRequest req;
					CBS(MulticallContext &owner):owner(owner),req(owner.req) {}
				};

				RpcRequest req = RpcRequest::create(pr,new CBS(*this));

				server.exec(req);
			} else {
				req.setResult(Value(object,{key/"results"=results, key/"errors"= errors}));
				delete this;
				return ;
			}
		} while (++mtfork == 2);

	}

protected:

};

void RpcServer::add_multicall(const String& name) {
	add(name, [this](RpcRequest req) {

		if (req.getArgs().empty()) req.setError(errorInvalidParams,"Empty arguments");
		else if (req[0].type() == string) {
			std::size_t pos = 1;
			MulticallContext *m = new MulticallContext(*this,req, [pos,req] () mutable {
				if (pos < req.getArgs().size())
					return std::make_pair(req[0],req[pos++]);
				else
					return std::make_pair(Value(),Value());
			});
			m->run();
		} else if (req[0].type() == array) {
			std::size_t pos = 0;
			MulticallContext *m = new MulticallContext(*this,req,[pos,req] () mutable {
				std::size_t x = pos++;
				if (x < req.getArgs().size())
					return std::make_pair(req[x][0],req[x][1]);
				else
					return std::make_pair(Value(),Value());
			});
			m->run();
		} else {
			req.setError(errorInvalidParams,"The first argument must be either string or array");
		}
	});
}

void RpcServer::add_ping(const String &name) {
	add(name, [](RpcRequest req) {
		req.setResult(req.getArgs());
	});
}

Value RpcServer::validateArgs(const Value& args, const Value& def) const {
	RpcArgValidator v(customRules);
	if (v.checkArgs(args, def)) return null;
	else return v.getRejections();
}

void RpcServer::add_help(const Value& helpContent, const String &name) {

	Value helpCtx = helpContent;
	add(name, [helpCtx](RpcRequest req) {
		String n (req[0]);
		req.setResult(helpCtx[n]);
	});

}

RpcResult::RpcResult(Value result, bool isError, Value context)
	:Value(result),context(context),error(isError)
{}

AbstractRpcClient::PreparedCall::PreparedCall(AbstractRpcClient& owner, const Value &id, const Value& msg)
	:owner(owner),id(id),msg(msg),executed(false)
{
}

//object receives result and stores it
class AbstractRpcClient::LocalPendingCall: public AbstractRpcClient::PendingCall {
public:
	virtual void onResponse(const RpcResult &response) override {
		res = response;
	}

	LocalPendingCall(std::recursive_mutex &lock)
		:received(false),lock(lock) {}

	void release() {
		std::unique_lock<std::recursive_mutex> _(lock);
		//when the storage is destroyed - set received to true
		received = true;
		//notify conditional variable
		trig.notify_one();
	}

	RpcResult res;
	bool received;
	std::condition_variable_any trig;
	std::recursive_mutex &lock;
};

AbstractRpcClient::PreparedCall::operator RpcResult() {

	if (executed) return RpcResult();

	executed = true;

	Sync _(owner.lock);

	//declare storage here
	LocalPendingCall lpc(owner.lock);
	//register the storage (under its id)
	owner.addPendingCall(id,PPendingCall(&lpc, [](PendingCall *d){
		static_cast<LocalPendingCall *>(d)->release();}));
	//send request now
	owner.sendRequest(id, msg);

	lpc.trig.wait(_,[&]{return lpc.received;});

	//return received result
	return lpc.res;
}

AbstractRpcClient::PreparedCall AbstractRpcClient::operator ()(String methodName, Value args) {
	Sync _(lock);
	Value id = genRequestID();
	Value ctx = context.empty()?Value():context;
	return this->operator ()(methodName, args, ctx);
}

AbstractRpcClient::PreparedCall AbstractRpcClient::operator ()(String methodName, Value args, Value context) {
	Sync _(lock);
	Value id = genRequestID();
	switch (ver) {
	case RpcVersion::ver1:
		return PreparedCall(*this, id, Object("method", methodName)
											 ("params",args)
											 ("id",id)
											 ("context",context));
	case RpcVersion::ver2:
		return PreparedCall(*this, id, Object("method", methodName)
											 ("params",args)
											 ("id",id)
											 ("jsonrpc","2.0")
											 ("context",context));
	};
	throw std::runtime_error("Invalid JSONRPC version (client-call)");
}

bool AbstractRpcClient::cancelAsyncCall(Value id, RpcResult result) {
	return cancelPendingCall(id, result);
}

bool AbstractRpcClient::cancelPendingCall(Value id, RpcResult result) {
	Sync _(lock);
	auto it = callMap.find(id);
	if (it == callMap.end()) return false;
	PPendingCall pc = std::move(it->second);
	callMap.erase(it);
	_.unlock();
	pc->onResponse(std::move(result));
	return true;
}

void AbstractRpcClient::cancelAllPendingCalls(RpcResult result) {
	std::vector<Value> ids;
	{
		Sync _(lock);
		ids.reserve(callMap.size());
		for (auto &&x: callMap) ids.push_back(x.first);
	}
	for (auto &&x: ids) cancelPendingCall(x, result);
}

void AbstractRpcClient::filterPendingCalls(const std::vector<Value> &ids, std::vector<PPendingCall> &out) {
	Sync _(lock);
	out.clear();
	CallMap newMap;
	for (const auto &x: ids) {
		auto iter = callMap.find(x);
		if (iter != callMap.end()) {
			newMap.emplace(x, std::move(iter->second));
		}
	}
	for (auto &x: callMap) {
		if (x.second != nullptr)
			out.emplace_back(std::move(x.second));
	}
	callMap = std::move(newMap);
}

AbstractRpcClient::Response AbstractRpcClient::parseResponse(Value response) {
	Value id = response["id"];
	if (id.defined() && !id.isNull()) {
		Value result = response["result"];
		Value error = response["error"];
		if (result.defined() || error.defined()) {
			Value ctx = response["context"];
			updateContext(ctx);
			RpcResult r;
			if (result.defined() && (!error.defined() || error.isNull()))  {
				r = RpcResult(result, false, ctx);
			} else {
				r = RpcResult(error, true, ctx);
			}
			auto iter = callMap.find(id);
			if (iter == callMap.end()) {
				return Response{unexpected, r, PPendingCall(nullptr,nullptr)};
			} else {
				PPendingCall pcall (std::move(iter->second));
				callMap.erase(iter);
				return Response{success, r, std::move(pcall)};
			}
		} else {
			return Response {
				request, RpcResult(), PPendingCall(nullptr,nullptr)
			};
		}
	} else {
		return Response {
			notification, RpcResult(), PPendingCall(nullptr,nullptr)
		};

	}

}

AbstractRpcClient::ReceiveStatus AbstractRpcClient::processResponse(Value response) {
	Value id = response["id"];
	if (id.defined() && !id.isNull()) {
		Value result = response["result"];
		Value error = response["error"];
		if (result.defined() || error.defined()) {
			Value ctx = response["context"];
			updateContext(ctx);
			if (result.defined() && (!error.defined() || error.isNull()))  {
				if (!cancelAsyncCall(id,RpcResult(result,false,ctx))) return unexpected;
			} else {
				if (!cancelAsyncCall(id,RpcResult(error,true,ctx))) return unexpected;
			}
			return success;

		} else {
			return request;
		}
	} else {
		return notification;
	}
}

Value AbstractRpcClient::getContext() const {
	std::lock_guard _(lock);
	return context;
}

void AbstractRpcClient::setContext(const Value& value) {
	std::lock_guard _(lock);
	context = value;
}
void AbstractRpcClient::updateContext(const Value& value) {
	std::lock_guard _(lock);
	setContext(updateContext(context,value));
}
Value AbstractRpcClient::updateContext(const Value& context, const Value& value) {
	Object newContext(context);
	for (Value v: value) {
		if (v.isNull()) newContext.unset(v.getKey());
		else newContext.set(v);
	}
	return newContext;
}

void AbstractRpcClient::addPendingCall(const Value &id, PPendingCall &&pcall) {
	callMap.emplace(id,	std::move(pcall));
}

Value RpcServer::formatError(int code, const String& message, Value data) const {
	return defaultFormatError(code,message,data);
}

void RpcRequest::setNoResultError(RequestData *r) {
	r->addRef();
	if (r->srvsvc != nullptr) {
		try {
			Value err =r->srvsvc->formatError(RpcServer::errorMethodDidNotProduceResult,"The method did not produce a result");
			r->sendError(err);
		} catch (...) {

		}
	}
	r->release();

}

void RpcRequest::setNoResultError() {
	setNoResultError(data);
}

void RpcRequest::init(const IServerServices *srvsvc) {
	data->srvsvc = srvsvc;
}

void RpcRequest::setInternalError(const char *what) {
	Value whatV = what?Value(what):Value();
	setError(RpcServer::errorInternalError, "Internal error", whatV);
}

///Send notify - note that owner can disable notify, then this function fails
bool RpcRequest::sendNotify(const String name, Value data) {
//	Value obj= formatNotify(this->data->ver, name, data);
	return this->data->sendNotify(RpcNotify(name, data));

}

bool RpcRequest::RequestData::hearthbeat() {
	return response(Value());
}

bool RpcRequest::hearthbeat() noexcept {
	return this->data->hearthbeat();
}

///Determines whether notification is enabled
bool RpcRequest::isSendNotifyEnabled() const {
		return data->notifyEnabled;
}

void AbstractRpcClient::notify(String notifyName, Value args) {
	Sync _(lock);
	sendRequest(formatNotify(ver, notifyName, args, Value()));
}
void AbstractRpcClient::notify(String notifyName, Value args, Value context) {
	Sync _(lock);
	sendRequest(formatNotify(ver, notifyName, args, context));
}

AbstractRpcClient::AbstractRpcClient(RpcVersion version)
: idCounter(0)
, ver(version)
{
}

RpcNotify::RpcNotify(Value js)
	:eventName(String(js["method"]))
	,data(js["params"])
{
}

RpcNotify::RpcNotify(String eventName, Value data)
	:eventName(eventName)
	,data(data)
{

}
RpcNotify::RpcNotify(String eventName, Value data, Value context)
	:eventName(eventName)
	,data(data)
	,context(context)
{

}

RpcRequest RpcNotify::asRequest() const {
	return RpcRequest::create(RpcRequest::ParseRequest(eventName, data, Value(), context), [](Value){return false;}, 0);
}

bool RpcRequest::isResponseSent() const {
	return data->responseSent;
}

bool RpcRequest::isErrorSent() const {
	return data->errorSent;
}

void RpcServer::setCustomValidationRules(Value customRules) {
	this->customRules = customRules;
}

Value AbstractRpcClient::genRequestID () {
	unsigned int id = ++idCounter;
	return id;

}

std::size_t RpcServer::HashStr::operator()(StrViewA str) const {
	std::size_t h = 0;
	FNV1a<sizeof(std::size_t)> c(h);
	for(char x:str) c(x);
	return h;
}

RpcVersion RpcRequest::RequestData::getVersion() const {
	if (version.defined()) return RpcVersion::ver2;
	else return RpcVersion::ver1;
}

RpcRequest RpcRequest::create(const ParseRequest& reqdata, Callbacks* cbs, const PRpcConnContext &connCtx) {
	class Call: public RequestData {
	public:
		Call(const ParseRequest &req, Callbacks* cbs, RpcFlags::Type flags, const PRpcConnContext &connCtx)
			:RequestData(req,flags,connCtx)
			,cbs(cbs) {}

		virtual void sendResult(const Value &result, const Value &context) override {
			postSendResponse(cbs->onResult(RpcRequest(this),result,context));
		}
		virtual void sendError(const Value &error) noexcept override {
			postSendResponse(cbs->onError(RpcRequest(this),error));
		}
		virtual bool sendNotify(const RpcNotify &notify) noexcept override{
			return cbs->onNotify(RpcRequest(this),notify);
		}
		virtual bool sendCallback(RpcRequest request) noexcept override {
			return cbs->onCallback(RpcRequest(this), request);
		}
		virtual bool response(const Value &) noexcept override {return false;}

		virtual bool hearthbeat() noexcept override {
			return cbs->onHearthbeat(RpcRequest(this));
		}

		~Call() {
			if (!responseSent) {
				RpcRequest::setNoResultError(this);
			}
			cbs->release();
		}
	protected:
		Callbacks* cbs;
	};

	return RpcRequest(new Call(reqdata, cbs,RpcFlags::notify, connCtx));

}

RpcVersion RpcRequest::getVersion() const {
	return data->getVersion();
}

Value RpcRequest::getVersionField() const {
	return data->version;
}

void RpcRequest::setParams(Value args) {
	data->params = args;
}

RpcResult RpcResult::makeError(int error, const StrViewA &message, Value data) {
	return RpcResult(Object
		("code",error)
		("message",message)
		("data", data), true, json::undefined);
}

void AbstractRpcClient::sendRequest(const Value &, const Value &request) {
	sendRequest(request);
}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Bonder\Http;

/**
 * A Http Response.
 *
 * @author burzak
 * @author hbandura
 */
interface HttpResponse extends \Bonder\Response {

  /**
   * Returns the http status code.
   *
   * @return int
   */
  public function getStatusCode();

  /**
   * Returns the header we should sent to the browser before any other content
   *
   * @return Array
   */
  public function getHeaders();

  /**
   * This is the request content (HTML for example)
   *
   * @return string
   */
  public function getContent();

}


text:
package apps::apache::serverstatus::mode::workers;

use base qw(centreon::plugins::mode);

use strict;
use warnings;
use centreon::plugins::http;

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $options{options}->add_options(arguments => {
        "hostname:s"    => { name => 'hostname' },
        "port:s"        => { name => 'port', },
        "proto:s"       => { name => 'proto' },
        "urlpath:s"     => { name => 'url_path', default => "/server-status/?auto" },
        "credentials"   => { name => 'credentials' },
        "basic"         => { name => 'basic' },
        "username:s"    => { name => 'username' },
        "password:s"    => { name => 'password' },
        "header:s@"     => { name => 'header' },
        "warning:s"     => { name => 'warning' },
        "critical:s"    => { name => 'critical' },
        "timeout:s"     => { name => 'timeout' },
    });
    $self->{http} = centreon::plugins::http->new(%options);
    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::init(%options);

    if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) {
        $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'.");
        $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) {
        $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'.");
        $self->{output}->option_exit();
    }
    $self->{http}->set_options(%{$self->{option_results}});
}

sub run {
    my ($self, %options) = @_;

    my $webcontent = $self->{http}->request();
    my ($BusyWorkers, $IdleWorkers, $ScoreBoard);
    if ($webcontent =~ /^BusyWorkers:\s+([^\s]+)/mi) {
        $BusyWorkers = $1;
    }
    if ($webcontent =~ /^IdleWorkers:\s+([^\s]+)/mi) {
        $IdleWorkers = $1;
    }
    if ($webcontent =~ /^Scoreboard:\s+([^\s]+)/mi) {
        $ScoreBoard = $1;
    }

    my $srvLimit = length($ScoreBoard);
    my $prct_busy = $BusyWorkers / $srvLimit * 100;

    my $exit = $self->{perfdata}->threshold_check(value => $prct_busy,
                                                 threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]);
    $self->{output}->output_add(severity => $exit,
                                short_msg => sprintf("Busy workers: %d Idle workers: %d (Server Limit: %d - %d %% Busy)", $BusyWorkers, $IdleWorkers, $srvLimit, $prct_busy));
    $self->{output}->perfdata_add(label => "idle_workers",
                                  value => $IdleWorkers,
                                  min => 0,
                                  max => $srvLimit);
    $self->{output}->perfdata_add(label => "busy_workers",
                                  value => $BusyWorkers,
                                  warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $srvLimit, cast_int => 1),
                                  critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $srvLimit, cast_int => 1),
                                  min => 0, max => $srvLimit);

    $self->{output}->display();
    $self->{output}->exit();
}

1;

__END__

=head1 MODE

Check Apache WebServer busy processes.

=over 8

=item B<--hostname>

IP Addr/FQDN of the webserver host

=item B<--port>

Port used by Apache

=item B<--proto>

Protocol to use http or https, http is default

=item B<--urlpath>

Set path to get server-status page in auto mode (Default: '/server-status/?auto')

=item B<--credentials>

Specify this option if you access server-status page with authentication

=item B<--username>

Specify username for authentication (Mandatory if --credentials is specified)

=item B<--password>

Specify password for authentication (Mandatory if --credentials is specified)

=item B<--basic>

Specify this option if you access server-status page over basic authentication and don't want a '401 UNAUTHORIZED' error to be logged on your webserver.

Specify this option if you access server-status page over hidden basic authentication or you'll get a '404 NOT FOUND' error.

(Use with --credentials)

=item B<--timeout>

Threshold for HTTP timeout

=item B<--header>

Set HTTP headers (Multiple option)

=item B<--warning>

Warning Threshold (%) of busy workers

=item B<--critical>

Critical Threshold (%) of busy workers

=back

=cut


text:
/* @flow */

import VNode, { emptyVNode } from './vnode'
import config from '../config'
import { createComponent } from './create-component'
import { normalizeChildren } from './helpers/index'
import { warn, resolveAsset } from '../util/index'

// wrapper function for providing a more flexible interface
// without getting yelled at by flow
export function createElement (
  tag: any,
  data: any,
  children: any
): VNode | void {
  if (data && (Array.isArray(data) || typeof data !== 'object')) {
    children = data
    data = undefined
  }
  // make sure to use real instance instead of proxy as context
  return _createElement(this._self, tag, data, children)
}

function _createElement (
  context: Component,
  tag?: string | Class<Component> | Function | Object,
  data?: VNodeData,
  children?: VNodeChildren | void
): VNode | void {
  if (data && data.__ob__) {
    process.env.NODE_ENV !== 'production' && warn(
      `Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
      'Always create fresh vnode data objects in each render!',
      context
    )
    return
  }
  if (!tag) {
    // in case of component :is set to falsy value
    return emptyVNode()
  }
  if (typeof tag === 'string') {
    let Ctor
    const ns = config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
      // platform built-in elements
      return new VNode(
        tag, data, normalizeChildren(children, ns),
        undefined, undefined, ns, context
      )
    } else if ((Ctor = resolveAsset(context.$options, 'components', tag))) {
      // component
      return createComponent(Ctor, data, context, children, tag)
    } else {
      // unknown or unlisted namespaced elements
      // check at runtime because it may get assigned a namespace when its
      // parent normalizes children
      return new VNode(
        tag, data, normalizeChildren(children, ns),
        undefined, undefined, ns, context
      )
    }
  } else {
    // direct component options / constructor
    return createComponent(tag, data, context, children)
  }
}


text:
#include "bindnames.h"
#include <assert.h>
extern int outputStage; // This variable is located in vslc.c
char* thisClass;
static int stack_offset_of_variables = 0;
//Solutions to last assignment, precompiled in bindsol.o
int bc(node_t* root, int stackOffset);
int bd(node_t* root, int stackOffset);

int bind_default ( node_t *root, int stackOffset)
{
	return bd(root, stackOffset);
}

int bind_function ( node_t *root, int stackOffset)
{
	/**
	 * function
	 * data_type = {...}
	 * label = "foo"
	 *   	-parameter_list
	 *   	-statement_list
	 */
	if(outputStage == 6)
		printf( "FUNCTION: Start: %s\n", root->label);
	assert(root);
	assert(root->n_children == 2);
	node_t *para_list = root->children[0];
	node_t *stat_list = root->children[1];
	scope_add();
	if(para_list){
		/**
		 * para_list can be NULL after simplification
		 */
		stack_offset_of_variables = 8 + 4*para_list->n_children;
		bind_default(para_list, stack_offset_of_variables);
	}
	stack_offset_of_variables = 0;
	bind_default(stat_list, stack_offset_of_variables);
	scope_remove();
	if(outputStage == 6)
		printf( "FUNCTION: End\n");
	return 0;
}

function_symbol_t* create_function_symbol(node_t* function_node)
{
	/**
	 * function
	 * data_type = {...}
	 * label = "foo"
	 *   	-parameter_list
	 *   	-statement_list
	 */
	assert(function_node);
	function_symbol_t *new_func_symbol = calloc(1, sizeof(function_symbol_t));
	if(new_func_symbol == NULL){
		perror("calloc");
		exit(EXIT_FAILURE);
	}
	node_t *para_list = function_node->children[0];
	if(para_list){
		new_func_symbol->nArguments = para_list->n_children;
		new_func_symbol->argument_types = calloc(para_list->n_children, sizeof(data_type_t));
		if(new_func_symbol->argument_types == NULL){
			perror("calloc");
			exit(EXIT_FAILURE);
		}
		for (int i = 0; i < para_list->n_children; ++i) {
			new_func_symbol->argument_types[i]
				= para_list->children[i]->data_type;
		}
	}
	new_func_symbol->label = STRDUP(function_node->label);
	new_func_symbol->return_type = function_node->data_type;

	return new_func_symbol;
}

int bind_function_list ( node_t *root, int stackOffset)
{
	if(outputStage == 6)
		printf( "FUNCTION_LIST: Start\n");
	scope_add();
	/**
	 * create new function symbol table
	 */
	for(int i=0; i<root->n_children; i++){
		function_symbol_t *new = create_function_symbol(root->children[i]);
		function_add((root->children[i]->label), new);
		//bind_function(root->children[i], stackOffset);
	}
	bind_default(root, stackOffset);
	scope_remove();
	if(outputStage == 6)
		printf( "FUNCTION_LIST: End\n");
	return 0;
}

int bind_constant ( node_t *root, int stackOffset)
{
    return bc(root, stackOffset);
}

symbol_t* create_symbol(node_t* declaration_node, int stackOffset)
{
    /**
     *  declaration
     *  data_type = {...}
     *  label = "foo"
     */
	assert(declaration_node);
	symbol_t *new_symbol = malloc(sizeof(symbol_t));
	if(!new_symbol){
		perror("malloc");
		exit(EXIT_FAILURE);
	}
	new_symbol->depth = 0;
	new_symbol->label = STRDUP(declaration_node->label);
	new_symbol->stack_offset = stackOffset;
	new_symbol->type = declaration_node->data_type;
	return new_symbol;
}

int bind_declaration ( node_t *root, int stackOffset)
{
	stack_offset_of_variables-=4;
	stackOffset = stack_offset_of_variables;
	if(outputStage == 6)
		printf( "DECLARATION: parameter/variable : '%s', offset: %d\n", root->label, stackOffset);
	//bind_default(root, stackOffset);

	symbol_t *new_symbol = create_symbol(root, stack_offset_of_variables);
	symbol_insert(new_symbol->label, new_symbol);
	return 0;
}

int bind_variable ( node_t *root, int stackOffset)
{
	/**
	 * make sure it's masked out in declaration part (symbol_insert)
	 * and also masked out int call_e (where func_symbol inserts)
	 * here we retrieve (symbol_get)
	 */
	if(outputStage == 6)
		printf( "VARIABLE: access: %s\n", root->label);
	root->entry = symbol_get(root->label);
	/* keep terminals(const and variable)' data_type field synchronized with entry */
	root->data_type = root->entry->type;
	return 0;

}

int bind_expression( node_t* root, int stackOffset)
{
	if(outputStage == 6)
		printf( "EXPRESSION: Start: %s\n", root->expression_type.text);
	if(root->expression_type.index == FUNC_CALL_E){
		/**
		 * call_e := variable expression_list
		 */
		root->function_entry = function_get(root->children[0]->label);
		if(root->children[1]){
			bind_default(root->children[1], stackOffset);
		}
		/**
		 * sychronize the date_type field like in variable
		 */
		root->data_type = root->function_entry->return_type;
	}else{
	   bind_default(root, stackOffset);
	}

	if(outputStage == 6)
		printf( "EXPRESSION: End\n");
	return 0;
}


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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Start template definition [deprecated]</title>

PDF_begin_template_ext

PDF_circle

PDF Functions

PHP Manual

PDF_begin_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_template — Start template definition [deprecated]

Description

   int PDF_begin_template
    ( resource $pdfdoc
   , float $width
   , float $height
   )

   Starts a new template definition.

   This function is deprecated since PDFlib version 7,
   use PDF_begin_template_ext() instead.

PDF_begin_template_ext

PDF_circle

PDF Functions

PHP Manual


text:
import React from "react";
import PropTypes from "prop-types";
import "./App.css";
import MarkerSection from "../pages/marker/MarkerSection";
import PanBySection from "../pages/pan-by/PanBySection";
import PanToSection from "../pages/pan-to/PanToSection";
import PolylineSection from "../pages/polyline/PolylineSection";
import FitBoundsSection from "../pages/fit-bounds/FitBoundsSection";
import GoogleMapSection from "../pages/google-map/GoogleMapSection";
import InfoWindowSection from "../pages/info-window/InfoWindowSection";
import MarkerIconSection from "../pages/marker-icon/MarkerIconSection";
import DataPolygonSection from "../pages/data-polygon/DataPolygonSection";
import ZoomControlSection from "../pages/zoom-control/ZoomControlSection";
import MarkerSymbolSection from "../pages/marker-symbol/MarkerSymbolSection";
import PanToBoundsSection from "../pages/pan-to-bounds/PanToBoundsSection";
import ScaleControlSection from "../pages/scale-control/ScaleControlSection";
import CustomControlSection from "../pages/custom-control/CustomControlSection";
import RotateControlSection from "../pages/rotate-control/RotateControlSection";
import DrawingControlSection from "../pages/drawing-control/DrawingControlSection";
import MapTypeControlSection from "../pages/map-type-control/MapTypeControlSection";
import FullscreenControlSection from "../pages/fullscreen-control/FullscreenControlSection";
import StreetViewControlSection from "../pages/street-view-control/StreetViewControlSection";

export default class App extends React.Component {
  static childContextTypes = {
    maps: PropTypes.object.isRequired,
    center: PropTypes.object.isRequired,
    styles: PropTypes.object.isRequired,
  };

  getChildContext() {
    const { google: { maps } } = window;

    return {
      maps,
      center: { lat: 36.964, lng: -122.015 },
      styles: { map: { minHeight: "320px", height: "100%" } },
    };
  }

  render() {
    return (

Basic Components

          <GoogleMapSection />
          <MarkerSection />
          <MarkerIconSection />
          <MarkerSymbolSection />
          <InfoWindowSection />
          <PolylineSection />

Map Controls

          <FullscreenControlSection />
          <MapTypeControlSection />
          <RotateControlSection />
          <ScaleControlSection />
          <StreetViewControlSection />
          <ZoomControlSection />

          <CustomControlSection />
          <DrawingControlSection />

Map Transitions

          <FitBoundsSection />
          <PanBySection />
          <PanToSection />
          <PanToBoundsSection />

Data Layer

          <DataPolygonSection />

                  Github

                  Twitter

    );
  }
}


text:
package env

import (
	"flag"
)

func (this *Env) BindFlags() {
	flag.BoolVar(&this.ReadStdin, "stdin", false, "True to source env from standard input")
	flag.BoolVar(&this.Publish, "publish", false, "True to publish entries to destination path")
	flag.BoolVar(&this.Overwrite, "overwrite", false, "True to overwrite env value during publish")
}


text:
FROM python:3

# Install necessary packages
RUN pip install buildbot buildbot-worker requests
RUN pip install txrequests git+https://github.com/iblis17/buildbot-freebsd.git

# Setup our image to live in the right place and run the right command
WORKDIR /app
CMD buildbot checkconfig master.cfg

# Copy in our code
COPY master /app/

# Mock up secret variables, etc..
COPY mock/* /app/


text:
<?php

namespace NetSuite\Classes;

class GlobalAccountMappingSearchRow extends SearchRow {
    public $basic;
    public $classJoin;
    public $departmentJoin;
    public $destinationAccountJoin;
    public $locationJoin;
    public $sourceAccountJoin;
    public $subsidiaryJoin;
    public $customSearchJoin;
    static $paramtypesmap = array(
        "basic" => "GlobalAccountMappingSearchRowBasic",
        "classJoin" => "ClassificationSearchRowBasic",
        "departmentJoin" => "DepartmentSearchRowBasic",
        "destinationAccountJoin" => "AccountSearchRowBasic",
        "locationJoin" => "LocationSearchRowBasic",
        "sourceAccountJoin" => "AccountSearchRowBasic",
        "subsidiaryJoin" => "SubsidiarySearchRowBasic",
        "customSearchJoin" => "CustomSearchRowBasic[]",
    );
}


text:
teaching
========

Teaching Materials


text:
///////////////////////////////////////////////////////////////////////////////
//
// This file is part of Serleena.
//
// The MIT License (MIT)
//
// Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto,
//   Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////

/**
 * Name: CloudJSONOutboundStreamBuilder.java
 * Package: com.kyloth.serleena.synchronization.kylothcloud.outbound
 * Author: Tobia Tesan
 *
 * History:
 * Version  Programmer        Changes
 * 1.0.0    Tobia Tesan       Creazione file
 */
package com.kyloth.serleena.synchronization.kylothcloud.outbound;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
import com.kyloth.serleena.common.TelemetryEvent;
import com.kyloth.serleena.common.UserPoint;
import com.kyloth.serleena.persistence.IExperienceStorage;
import com.kyloth.serleena.persistence.ITelemetryStorage;
import com.kyloth.serleena.persistence.ITrackStorage;
import com.kyloth.serleena.synchronization.JSONOutboundStream;
import com.kyloth.serleena.synchronization.OutboundStream;
import com.kyloth.serleena.synchronization.OutboundStreamBuilder;
import com.kyloth.serleena.synchronization.kylothcloud.OutboundExperienceDataEntity;
import com.kyloth.serleena.synchronization.kylothcloud.OutboundRootEntity;
import com.kyloth.serleena.synchronization.kylothcloud.OutboundTelemetryEntity;
import com.kyloth.serleena.synchronization.kylothcloud.OutboundRootSerializer;
import com.kyloth.serleena.synchronization.kylothcloud.TrackEntity;
import com.kyloth.serleena.synchronization.kylothcloud.UserPointEntity;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * Concretizza OutboundStreamBuilder in modo da poter costruire e scrivere su stream JSON
 * nel formato che KylothCloud si attende.
 * @field radice per la gerarchia di dati in uscita
 * @use Viene usato da Synchronizer per scrivere su un OutboundStream nel formato idoneo ad essere passato a SerleenaJSONNetProxy per l'invio a KylothCloud
 * @author Tobia Tesan <tobia.tesan@gmail.com>
 * @version 1.0.0
 */
public class CloudJSONOutboundStreamBuilder implements OutboundStreamBuilder {
    OutboundRootEntity root;
    final Gson gson = new GsonBuilder().registerTypeAdapter(OutboundRootEntity.class,
                                                                 new OutboundRootSerializer()).create();

    /**
     * Costruisce un nuovo CloudJSONOutboundStreamBuilder
     */
    public CloudJSONOutboundStreamBuilder() {
        root = new OutboundRootEntity();
        root.data = new ArrayList<OutboundExperienceDataEntity>();
    }

    /**
     * Aggiunge un'Esperienza (e di conseguenza i suoi Punti Utente
     * e eventuali altri dati raccolti localmente) all'OutboundStream
     * da scrivere.
     *
     * @param exp Un'Esperienza le cui componenti raccolte sul dispositivo
     *          si vogliono  inviare al servizio remoto.
     */
    @Override
    public void addExperience(IExperienceStorage exp) {
        OutboundExperienceDataEntity e = new OutboundExperienceDataEntity();
        e.experience = exp.getUUID();
        int userPointCounter = 0;
        for (UserPoint p : exp.getUserPoints(true)) { // HACK
            UserPointEntity pe = new UserPointEntity();
            pe.point = p;
            pe.name = "Punto personalizzato #"+userPointCounter++;
            e.userPoints.add(pe);
        }
        for (ITrackStorage t : exp.getTracks()) {
            TrackEntity te = new TrackEntity();
            te.name = "";
            // TODO: Noi non ce l'abbiamo?
            te.uuid = t.getUUID();
            // HACK per SHANDROID-372
            for (ITelemetryStorage ts : t.getTelemetries(false)) {
                OutboundTelemetryEntity tse = new OutboundTelemetryEntity();
                for (TelemetryEvent tsv : ts.getEvents()) {
                    long ee;
                    ee = tsv.timestamp();
                    tse.events.add(ee * 1000);
                }
                tse.track = te.uuid;
                e.telemetryData.add(tse);
            }
        }
        root.data.add(e);
    }

    /**
     * Costruisce il json per i dati
     *
     * @return String Il json dei dati
     */
    public String build() {
        return gson.toJson(root, OutboundRootEntity.class);
    }

    /**
     * Scrive nell'OutboundStream fornito i dati preaprati in formato JSON
     * @param s OutputStream su cui scrivere
     */
    @Override
    public void stream(OutboundStream s) throws IOException {
        if (s instanceof JSONOutboundStream) {
            JsonWriter writer = null;
            try {
                URLEncodedWriter urlw = new URLEncodedWriter(
                        new OutputStreamWriter(
                                (OutputStream) s,
                                "UTF-8")
                );
                writer = new JsonWriter(urlw);
                writer.setIndent("  ");

                gson.toJson(root, OutboundRootEntity.class, writer);
                writer.flush();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            throw new IllegalArgumentException();
        }
    }
}


text:
#include "ThinClientDurableInterest.hpp"

DUNIT_MAIN
  {
    CALL_TASK(StartLocator);

    startServers();

    CALL_TASK(FeederInit);
    CALL_TASK(Clnt1Init);
    CALL_TASK(Clnt2Init);
    CALL_TASK(FeederUpdate1);
    CALL_TASK(Clnt1Down);
    CALL_TASK(Clnt2Down);
    CALL_TASK(Clnt1Up);
    CALL_TASK(Clnt2Up);
    CALL_TASK(FeederUpdate2);
    CALL_TASK(ValidateClient1ListenerEventPayloads);
    CALL_TASK(ValidateClient2ListenerEventPayloads);
    CALL_TASK(CloseFeeder);
    CALL_TASK(CloseClient1);
    CALL_TASK(CloseClient2);
    CALL_TASK(CloseServer);

    closeLocator();
  }
END_MAIN


text:
from django import forms
from django.core.exceptions import ValidationError

from munchee.models import Company

class CompanyForm(forms.Form):
    companies = forms.CharField(
        label = "e.g. Google, Apple, Bloomberg, ...",
        required = True,
    )
    keywords = forms.CharField(
        label = "e.g. software, technology, ...",
        required = False,
    )

class OAuthCallbackForm(forms.Form):
    code = forms.CharField()
    state = forms.CharField()


text:
package io.hawt.web.plugin;

/**
 * Plugin interface
 */
public interface Plugin {

    String getName();

    String getContext();

    String getDomain();

    String[] getScripts();

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package airportApp;

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

/**
 * The class allows the creation of Airport objects with an id,
 * identification (ident), name and country reference code (iso_country).
 * Additional attributes like type, latitude_deg, longitude_deg, elevation_ft,
 * continent, iso_region, municipality, scheduled_service, gps_code, iata_code,
 * local_code, home_link, wikipedia_link or keywords
 * are not included since they are not viable for the task
 * but the class can easily be extended. The class is immutable
 * (objects cannot be modified after creation except for adding runaways)
 * but it allows access to its attributes.
 * The class uses an array to keep track of runways.
 *
 * @author Atanas Angelov (atanas3angelov@gmail.com)
 */
public class Airport {

    private final int id;
    private final String ident;
    private final String name;
    private final String iso_country;
    private List<Runway> runways;

    /**
     * The constructor for the airport, requires an id, an identification (ident),
     * a name and a country code (iso_country).
     *
     * @param id Requires a positive integer. Be careful, the id is not necessarily unique.
     * @param ident The identification of the airport as a String.
     * @param name The name of the airport as a String.
     * @param iso_country The code of the country as a String.
     * @throws PositiveIntegerRequiredException Requires that the id is a positive integer.
     */
    public Airport(int id, String ident, String name, String iso_country) throws PositiveIntegerRequiredException {
        if(id < 0) throw new PositiveIntegerRequiredException("The id of a airport cannot be negative.");
        this.id = id;
        this.ident = ident;
        this.name = name;
        this.iso_country = iso_country;
        runways = new ArrayList<>();
    }

    /**
     *
     * @return Returns the id of an airport.
     */
    public int getID() {
        return id;
    }

    /**
     *
     * @return Returns the identification of an airport. Ex. 00AK
     */
    public String getIdentification() {
        return ident;
    }

    /**
     *
     * @return Returns the name of an airport.
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @return Returns the country code of an airport. Ex. US
     */
    public String getCountryCode() {
        return iso_country;
    }

    /**
     *
     * @return Returns a copy of the runways. The original array is kept safe.
     */
    public List<Runway> getRunways() {
        List<Runway> copy = new ArrayList<>();
        runways.stream().forEach((r) -> {
            copy.add(r);
        });
        return copy;
    }

    /**
     * Adds a runway to the list of runways for the airport.
     * @param r A runway object.
     */
    public void addRunway(Runway r) {
        runways.add(r);
    }

    /**
     *
     * @return The default toString() method has been overwritten to return the country
     * in the format "id identification name country_code".
     */
    public String toString() {
        return "" + id + " " + ident + " " + name + " " + iso_country;
    }
}


text:
import argparse
from my_math import power

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Square all of hte numbers that we have

parser = argparse.ArgumentParser()
parser.add_argument("power",
                    help="The power to raise the number to")  # Add help
args = parser.parse_args()      # returns data from the options specified
print("Power is: %i" % args.power)

for number in data:
    print(power(number, int(args.power)))


text:
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Christian Schulte <schulte@gecode.org>
 *
 *  Copyright:
 *     Christian Schulte, 2012
 *
 *  Last modified:
 *     $Date: 2012-09-19 15:14:28 +0200 (on, 19 sep 2012) $ by $Author: schulte $
 *     $Revision: 13103 $
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

namespace Gecode {

  forceinline
  IntAssign::IntAssign(Select s0)
    : s(s0) {}

  forceinline
  IntAssign::IntAssign(Rnd r)
    : ValBranch(r), s(SEL_RND) {}

  forceinline
  IntAssign::IntAssign(VoidFunction v, VoidFunction c)
    : ValBranch(v,c), s(SEL_VAL_COMMIT) {}

  forceinline IntAssign::Select
  IntAssign::select(void) const {
    return s;
  }

  inline IntAssign
  INT_ASSIGN_MIN(void) {
    return IntAssign(IntAssign::SEL_MIN);
  }

  inline IntAssign
  INT_ASSIGN_MED(void) {
    return IntAssign(IntAssign::SEL_MED);
  }

  inline IntAssign
  INT_ASSIGN_MAX(void) {
    return IntAssign(IntAssign::SEL_MAX);
  }

  inline IntAssign
  INT_ASSIGN_RND(Rnd r) {
    return IntAssign(r);
  }

  inline IntAssign
  INT_ASSIGN(IntBranchVal v, IntBranchCommit c) {
    return IntAssign(function_cast<VoidFunction>(v),
                     function_cast<VoidFunction>(c));
  }

  inline IntAssign
  INT_ASSIGN(BoolBranchVal v, BoolBranchCommit c) {
    return IntAssign(function_cast<VoidFunction>(v),
                     function_cast<VoidFunction>(c));
  }

}

// STATISTICS: int-branch


text:
package types

import (
	"bytes"
	"strconv"
	"strings"
)

type String string

func (s String) String() string {
	return string(s)
}

func (s String) Bytes() []byte {
	return []byte(s)
}

func (s String) Len() int {
	return len(s.String())
}

func (s String) Join(joiningStrs ...String) String {
	var buffer bytes.Buffer

	buffer.WriteString(s.String())

	for _, joiningStr := range joiningStrs {
		buffer.WriteString(joiningStr.String())
	}

	return String(buffer.String())
}

func (s String) Contains(contain string) bool {
	return strings.Contains(s.String(), contain)
}

func (s String) Cut(start, end int) String {
	result := ""
	str := s.String()
	strLen := len(str)
	strLastIdx := strLen - 1

	if strLen <= 0 {
		return String("")
	}

	if start > strLastIdx || end > strLastIdx {
		return String("")
	}

	if end < 0 || start < 0 {
		return String("")
	}

	if start < end {
		for i := start; i <= end; i++ {
			result += string(str[i])
		}
	} else {
		for i := start; i >= end; i-- {
			result += string(str[i])
		}
	}

	return String(result)
}

func (s String) SelectHead(selLen int) (String, String) {
	strLastIdx := s.Len() - 1
	strEndIdx := selLen - 1
	strTail := String("")

	if strLastIdx < 0 {
		return String(""), String("")
	}

	if strEndIdx > strLastIdx {
		strEndIdx = strLastIdx
	}

	if strLastIdx > strEndIdx {
		strTail = s.Cut(strEndIdx+1, strLastIdx)
	}

	return s.Cut(0, strEndIdx), strTail
}

func (s String) SelectTail(selLen int) (String, String) {
	strHead := String("")
	strLen := s.Len()

	strEndIdx := strLen - 1

	if strEndIdx < 0 {
		return String(""), String("")
	}

	strBeginIdx := strEndIdx - (selLen - 1)

	if strBeginIdx < 0 {
		strBeginIdx = 0
	}

	if strBeginIdx > 0 {
		strHead = s.Cut(0, strBeginIdx-1)
	}

	return strHead, s.Cut(strBeginIdx, strEndIdx)
}

func (s String) SpiltWith(spiltter string) (String, String) {
	pureString := s.String()

	if !strings.Contains(pureString, spiltter) {
		return s, ""
	}

	spIndex := strings.Index(pureString, spiltter)

	return String(pureString[0:spIndex]),
		String(pureString[spIndex+1 : len(pureString)])
}

func (s String) Trim() String {
	return String(strings.TrimSpace(s.String()))
}

func (s String) Int16() Int16 {
	resultUint, err := strconv.ParseInt(s.String(), 10, 16)

	if err != nil {
		return 0
	}

	return Int16(resultUint)
}

func (s String) Int32() Int32 {
	resultUint, err := strconv.ParseInt(s.String(), 10, 32)

	if err != nil {
		return 0
	}

	return Int32(resultUint)
}

func (s String) Int64() Int64 {
	resultUint, err := strconv.ParseInt(s.String(), 10, 64)

	if err != nil {
		return 0
	}

	return Int64(resultUint)
}

func (s String) UInt16() UInt16 {
	resultUint, err := strconv.ParseUint(s.String(), 10, 16)

	if err != nil {
		return 0
	}

	return UInt16(resultUint)
}

func (s String) UInt32() UInt32 {
	resultUint, err := strconv.ParseUint(s.String(), 10, 32)

	if err != nil {
		return 0
	}

	return UInt32(resultUint)
}

func (s String) UInt64() UInt64 {
	resultUint, err := strconv.ParseUint(s.String(), 10, 64)

	if err != nil {
		return 0
	}

	return UInt64(resultUint)
}

func (s String) Lower() String {
	return String(strings.ToLower(s.String()))
}

func (s String) Upper() String {
	return String(strings.ToUpper(s.String()))
}

func (s String) ExplodeWith(exploder string) []String {
	var stringSlice []String

	for _, str := range strings.Split(s.String(), exploder) {
		stringSlice = append(stringSlice, String(str))
	}

	return stringSlice
}

func (s String) Replace(find String, replace String) String {
	f := string(find)
	t := string(replace)

	return String(strings.Replace(string(s), f, t, -1))
}


text:
from voucherify import Client as voucherifyClient

voucherify = voucherifyClient(
    application_id="c70a6f00-cf91-4756-9df5-47628850002b",
    client_secret_key="3266b9f8-e246-4f79-bdf0-833929b1380c"
)

def test_publishVoucher():
    params = {
        "channel": "Email",
        "customer": {
            "source_id": "donny.roll@mail.com"
        },
        "campaign": "Predefined Gift Cards"
    }
    result = voucherify.distributions.publish(params)
    assert result.get('voucher').get('active') is True
    assert result.get('voucher').get('type') == 'GIFT_VOUCHER'


text:
@implementation EKCollection

- (instancetype)initWithEmoji:(NSArray *)emoji {
    if (self = [super init]) {
        [self loadEmoji:emoji];
    }

    return self;
}

- (void)loadEmoji:(NSArray *)emoji {
    NSMutableArray *collection = [NSMutableArray array];

    for (id eachItem in emoji) {
        EKEmoji *anEmoji = [EKEmoji new];
        if ([eachItem isKindOfClass:[NSDictionary class]]) {
            anEmoji.image = [UIImage imageNamed:eachItem[EKEmojiImageNameKey]];
            anEmoji.title = eachItem[EKEmojiTitleNameKey];
            anEmoji.name = eachItem[EKEmojiImageNameKey];
        }
        else if ([eachItem isKindOfClass:[NSString class]]) {
            anEmoji.image = [UIImage imageNamed:eachItem];
            anEmoji.name = eachItem;
        }
        else continue;

        [collection addObject:anEmoji];
    }

    self.emoji = collection;
}

@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>QUnit测试</title>
  <link rel="stylesheet" href="../node_modules/qunitjs/qunit/qunit.css">


text:
ENV['RACK_ENV'] = 'test'

require 'spec_helper'
require 'llt/segmenter/api'
require 'rack/test'

def app
  Api
end

describe "segmenter api" do
  include Rack::Test::Methods

  describe '/segment' do
    context "with URI as input" do
    end

    let(:text) {{text: "homo mittit. Marcus est."}}

    context "with text as input" do
      context "with accept header json" do
        it "segments the given sentences" do
          pending
          get '/segment', text,
            {"HTTP_ACCEPT" => "application/json"}
          last_response.should be_ok
          response = last_response.body
          parsed_response = JSON.parse(response)
          parsed_response.should have(2).items
        end
      end

      context "with accept header xml" do
        it "segments the given sentences" do
          get '/segment', text,
            {"HTTP_ACCEPT" => "application/xml"}
          last_response.should be_ok
          body = last_response.body
          body.should =~ /<s n="1">homo mittit\.<\/s>/
          body.should =~ /<s n="2">Marcus est\.<\/s>/
        end

        it "receives params for segmentation and markup" do
          params = { indexing: false }.merge(text)

          get '/segment', params,
            {"HTTP_ACCEPT" => "application/xml"}
          last_response.should be_ok
          body = last_response.body
          body.should =~ /<s>homo mittit\.<\/s>/
          body.should =~ /<s>Marcus est\.<\/s>/
        end
      end
    end
  end
end


text:
package generated.zcsclient.mail;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;

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

 * <complexType name="rawInvite">
 *   <simpleContent>
 *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
 *       <attribute name="uid" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="summary" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </extension>
 *   </simpleContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "rawInvite", propOrder = {
    "value"
})
public class testRawInvite {

    @XmlValue
    protected String value;
    @XmlAttribute(name = "uid")
    protected String uid;
    @XmlAttribute(name = "summary")
    protected String summary;

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * Gets the value of the uid property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUid() {
        return uid;
    }

    /**
     * Sets the value of the uid property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUid(String value) {
        this.uid = value;
    }

    /**
     * Gets the value of the summary property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSummary() {
        return summary;
    }

    /**
     * Sets the value of the summary property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSummary(String value) {
        this.summary = value;
    }

}


text:
""" How-to add float support to ModbusClient. """

from pyModbusTCP.client import ModbusClient
from pyModbusTCP.utils import encode_ieee, decode_ieee, \
                              long_list_to_word, word_list_to_long

class FloatModbusClient(ModbusClient):
    """A ModbusClient class with float support."""

    def read_float(self, address, number=1):
        """Read float(s) with read holding registers."""
        reg_l = self.read_holding_registers(address, number * 2)
        if reg_l:
            return [decode_ieee(f) for f in word_list_to_long(reg_l)]
        else:
            return None

    def write_float(self, address, floats_list):
        """Write float(s) with write multiple registers."""
        b32_l = [encode_ieee(f) for f in floats_list]
        b16_l = long_list_to_word(b32_l)
        return self.write_multiple_registers(address, b16_l)

if __name__ == '__main__':
    # init modbus client
    c = FloatModbusClient(host='localhost', port=502, auto_open=True)

    # write 10.0 at @0
    c.write_float(0, [10.0])

    # read @0 to 9
    float_l = c.read_float(0, 10)
    print(float_l)

    c.close()


text:
import { Component, Input, ViewChild } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Events, Slides } from 'ionic-angular';
import { OldMeal, User, Serving } from '../../models';

@Component({
  selector: 'control-serving',
  templateUrl: 'serving.html',
  providers: [
    { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: ServingControl }
  ]
})
export class ServingControl implements ControlValueAccessor {

  @Input('user') user: User;
  @Input('meal') meal: OldMeal;
  @ViewChild(Slides) slides: Slides;
  value: any;
  _onChange: (value: any) => void;

  constructor( public events: Events) {}

  ngAfterViewInit() {
    console.log(this.meal)
    this.slides.freeMode = true;
  }

  changeValue(serving: Serving) {
    this.value = serving.$key;
    this._onChange(serving.$key);
  }

  reset() {
    this.value = null;
    this._onChange(null);
  }

  slideChanged() {
    let currentIndex = this.slides.getActiveIndex();
    console.log("Current index is", currentIndex);
  }

  writeValue(value: any) {
    this.value = value;
  }

  registerOnChange(fn: (value: any) => void) {
    this._onChange = fn;
  }

  registerOnTouched() {}

}


text:
package dm.kafka.consumer;

import java.util.Timer;
import java.util.TimerTask;

public class OneShotTimer extends TimerTask {
	DataReplaceXmit sender = null;
	Timer timer;

	public OneShotTimer(DataReplaceXmit inf, int timeOut){
		sender = inf;
		timer = new Timer(true);
		timer.schedule(this, timeOut*60000);
	}

	@Override
    public void run() {
        completeTask();
    }

    private void completeTask() {
    	timer.cancel();
    	if(sender != null){
    		sender.dataTimeOut();
    	}
    }

//    public static void main(String args[]){
//    	DMTimer timerTask = new DMTimer(null,1);
//
//        //cancel after sometime
//        try {
//        	while(true)
//            Thread.sleep(120000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        /*System.out.println("TimerTask cancelled");
//        try {
//            Thread.sleep(30000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }*/
//    }
}


text:
package com.googlecode.jmapper.integrationtest.others.bean;

public class EnumBean {

	public enum Test{ FIELD, FIELD2}

	Test field;

	public Test getField() {
		return field;
	}

	public void setField(Test field) {
		this.field = field;
	}

}


text:
<tool id="bedtools_sortbed" name="SortBED" version="@WRAPPER_VERSION@.0">
    <description>order the intervals</description>
    <macros>
        <import>macros.xml</import>
    </macros>
    <expand macro="requirements" />
    <expand macro="stdio" />
    <command>
<![CDATA[
        sortBed
            -i $input
            $option
            > $output
]]>
    </command>
    <inputs>
        <param format="bed" name="input" type="data" label="Sort the following BED file"/>
        <param name="option" type="select" label="Sort by">
            <!-- sort -k 1,1 -k2,2 -n a.bed -->
            <option value="">chromosome, then by start position (asc)</option>
            <option value="-sizeA">feature size in ascending order.</option>
            <option value="-sizeD">feature size in descending order.</option>
            <option value="-chrThenSizeA">chromosome, then by feature size (asc).</option>
            <option value="-chrThenSizeD">chromosome, then by feature size (desc).</option>
            <option value="-chrThenScoreA">chromosome, then by score (asc).</option>
            <option value="-chrThenScoreD">chromosome, then by score (desc).</option>
        </param>
    </inputs>
    <outputs>
        <data format="bed" name="output" metadata_source="input" label="${input.name} (as BED)"/>
    </outputs>
    <tests>
        <test>
            <param name="input" value="sortBed1.bed" ftype="bed" />
            <param name="option" value="" />
            <output name="output" file="sortBed_result1.bed" ftype="bed" />
        </test>
    </tests>
    <help>
<![CDATA[
**What it does**

Sorts a feature file by chromosome and other criteria.

.. class:: warningmark

It should be noted that sortBed is merely a convenience utility, as the UNIX sort utility
will sort BED files more quickly while using less memory. For example, UNIX sort will sort a BED file
by chromosome then by start position in the following manner: sort -k 1,1 -k2,2 -n a.bed

@REFERENCES@
]]>
    </help>
    <expand macro="citations" />
</tool>


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
CBaseScreen *g_CurrentScreen = NULL;
//----------------------------------------------------------------------------------
CBaseScreen::CBaseScreen(CGump &gump)
    : CBaseQueue()
    , m_Gump(gump)
{
}
//----------------------------------------------------------------------------------
/*!
Отрисовка/выбор объектов
@param [__in] mode true - отрисовка, false - выбор
@return При выборе объектов - идентификатор выбранного объекта
*/
void CBaseScreen::Render(bool mode)
{
    WISPFUN_DEBUG("c159_f1");
    if (mode)
    {
        g_GL.BeginDraw();

        if (DrawSmoothMonitor())
            return;

        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

        m_Gump.Draw();

        InitToolTip();

        DrawSmoothMonitorEffect();

        g_MouseManager.Draw(CursorGraphic);

        g_GL.EndDraw();
    }
    else
    {
        g_SelectedObject.Clear();

        CRenderObject *selected = m_Gump.Select();

        if (selected != NULL)
            g_SelectedObject.Init(selected, &m_Gump);

        if (g_SelectedObject.Object != g_LastSelectedObject.Object)
        {
            if (g_SelectedObject.Object != NULL)
                g_SelectedObject.Object->OnMouseEnter();

            if (g_LastSelectedObject.Object != NULL)
                g_LastSelectedObject.Object->OnMouseExit();
        }

        g_LastSelectedObject.Init(g_SelectedObject);
    }
}
//----------------------------------------------------------------------------------
/*!
Вычисление состояния перехода
@return Индекс состояния
*/
int CBaseScreen::DrawSmoothMonitor()
{
    WISPFUN_DEBUG("c159_f2");
    if (g_ScreenEffectManager.Process() && SmoothScreenAction)
    {
        ProcessSmoothAction();

        g_GL.EndDraw();

        return 1;
    }

    return 0;
}
//----------------------------------------------------------------------------------
/*!
Наложение эффекта перехода
@return
*/
void CBaseScreen::DrawSmoothMonitorEffect()
{
    WISPFUN_DEBUG("c159_f3");
    g_ScreenEffectManager.Draw();
}
//----------------------------------------------------------------------------------
/*!
Создание плавного затемнения экрана
@param [__in] action Идентификатор действия
@return
*/
void CBaseScreen::CreateSmoothAction(BYTE action)
{
    WISPFUN_DEBUG("c159_f4");
    if (g_ScreenEffectManager.UseSunset())
        SmoothScreenAction = action;
    else
        ProcessSmoothAction(action);
}
//----------------------------------------------------------------------------------


text:
require 'assert'
require 'qs/daemon_data'

require 'qs/queue'
require 'qs/route'

class Qs::DaemonData

  class UnitTests < Assert::Context
    desc "Qs::DaemonData"
    setup do
      @current_env_process_label = ENV['QS_PROCESS_LABEL']
      ENV['QS_PROCESS_LABEL']    = Factory.string

      @current_env_debug = ENV['QS_DEBUG']
      ENV.delete('QS_DEBUG')

      @queues = Factory.integer(3).times.map do
        Qs::Queue.new{ name Factory.string }
      end

      @routes = Factory.integer(3).times.map do
        Qs::Route.new(Factory.string, TestHandler.to_s).tap(&:validate!)
      end

      @config_hash = {
        :name             => Factory.string,
        :pid_file         => Factory.file_path,
        :shutdown_timeout => Factory.integer,
        :worker_class     => Class.new,
        :worker_params    => { Factory.string => Factory.string },
        :num_workers      => Factory.integer,
        :error_procs      => Factory.integer(3).times.map{ proc{} },
        :logger           => Factory.string,
        :queues           => @queues,
        :verbose_logging  => Factory.boolean,
        :routes           => @routes
      }
      @daemon_data = Qs::DaemonData.new(@config_hash)
    end
    teardown do
      ENV['QS_DEBUG']         = @current_env_debug
      ENV['QS_PROCESS_LABEL'] = @current_env_process_label
    end
    subject{ @daemon_data }

    should have_readers :name, :pid_file, :shutdown_timeout
    should have_readers :worker_class, :worker_params, :num_workers
    should have_readers :error_procs, :logger, :queue_redis_keys
    should have_readers :verbose_logging
    should have_readers :debug, :dwp_logger, :routes, :process_label
    should have_imeths :route_for

    should "know its attrs" do
      h = @config_hash
      assert_equal h[:name],     subject.name
      assert_equal h[:pid_file], subject.pid_file

      assert_equal h[:shutdown_timeout], subject.shutdown_timeout

      assert_equal h[:worker_class],  subject.worker_class
      assert_equal h[:worker_params], subject.worker_params
      assert_equal h[:num_workers],   subject.num_workers
      assert_equal h[:error_procs],   subject.error_procs
      assert_equal h[:logger],        subject.logger

      exp = @queues.map(&:redis_key)
      assert_equal exp, subject.queue_redis_keys

      assert_equal h[:verbose_logging], subject.verbose_logging

      assert_false subject.debug
      assert_nil   subject.dwp_logger

      exp = @routes.inject({}){ |h, r| h.merge(r.id => r) }
      assert_equal exp, subject.routes
    end

    should "know its process label" do
      assert_equal ENV['QS_PROCESS_LABEL'], subject.process_label

      ENV['QS_PROCESS_LABEL'] = ""
      daemon_data = Qs::DaemonData.new(@config_hash)
      assert_equal @config_hash[:name], daemon_data.process_label

      ENV.delete('QS_PROCESS_LABEL')
      daemon_data = Qs::DaemonData.new(@config_hash)
      assert_equal @config_hash[:name], daemon_data.process_label
    end

    should "use the debug env var if set" do
      ENV['QS_DEBUG'] = Factory.string
      daemon_data = Qs::DaemonData.new(@config_hash)
      assert_true daemon_data.debug
      assert_equal daemon_data.logger, daemon_data.dwp_logger
    end

    should "look up a route using `route_for`" do
      exp_route = @routes.sample
      assert_equal exp_route, subject.route_for(exp_route.id)
    end

    should "raise a not found error using `route_for` with an invalid name" do
      assert_raises(Qs::NotFoundError) do
        subject.route_for(Factory.string)
      end
    end

    should "default its attrs when they aren't provided" do
      daemon_data = Qs::DaemonData.new
      assert_nil daemon_data.name
      assert_nil daemon_data.pid_file
      assert_nil daemon_data.shutdown_timeout

      assert_nil daemon_data.worker_class
      assert_equal({}, daemon_data.worker_params)
      assert_nil daemon_data.num_workers

      assert_equal [], daemon_data.error_procs

      assert_nil daemon_data.logger
      assert_equal [], daemon_data.queue_redis_keys

      assert_false daemon_data.verbose_logging

      assert_false daemon_data.debug
      assert_nil daemon_data.dwp_logger

      assert_equal({}, daemon_data.routes)
    end

  end

  TestHandler = Class.new

end


text:
OPT = 0

# Object files directory
# Warning: this will be removed by make clean!
#
OBJDIR = obj

# Target file name (without extension)
TARGET = $(OBJDIR)/STM32F4_Test

# Define all C source files (dependencies are generated automatically)
#
SOURCES += src/uart.c
SOURCES += src/ustime.c
SOURCES += src/main.c
SOURCES += src/startup_stm32f4xx.s
SOURCES += src/system_stm32f4xx.c
SOURCES += src/syscalls.c

SOURCES += FreeRTOS/Source/tasks.c
SOURCES += FreeRTOS/Source/queue.c
SOURCES += FreeRTOS/Source/list.c
SOURCES += FreeRTOS/Source/croutine.c
SOURCES += FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c

SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/misc.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_adc.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_can.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_crc.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_cryp.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_cryp_aes.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_cryp_des.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_cryp_tdes.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_dac.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_dbgmcu.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_dcmi.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_dma.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_exti.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_flash.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_fsmc.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_gpio.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_hash.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_hash_md5.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_hash_sha1.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_i2c.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_iwdg.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_pwr.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_rcc.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_rng.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_rtc.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_sdio.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_spi.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_syscfg.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_tim.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_usart.c
SOURCES += libs/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_wwdg.c

OBJECTS  = $(addprefix $(OBJDIR)/,$(addsuffix .o,$(basename $(SOURCES))))

# Place -D, -U or -I options here for C and C++ sources
CPPFLAGS += -Isrc
CPPFLAGS += -IFreeRTOS/Source/include
CPPFLAGS += -Ilibs/CMSIS/Include
CPPFLAGS += -Ilibs/Device/STM32F4xx/Include
CPPFLAGS += -Ilibs/STM32F4xx_StdPeriph_Driver/inc

#---------------- Compiler Options C ----------------
#  -g*:          generate debugging information
#  -O*:          optimization level
#  -f...:        tuning, see GCC documentation
#  -Wall...:     warning level
#  -Wa,...:      tell GCC to pass this to the assembler.
#    -adhlns...: create assembler listing
CFLAGS  = -O$(OPT)
CFLAGS += -std=gnu99
CFLAGS += -gdwarf-2
CFLAGS += -ffunction-sections
CFLAGS += -fdata-sections
CFLAGS += -Wall
#CFLAGS += -Wextra
#CFLAGS += -Wpointer-arith
#CFLAGS += -Wstrict-prototypes
#CFLAGS += -Winline
#CFLAGS += -Wunreachable-code
#CFLAGS += -Wundef
CFLAGS += -Wa,-adhlns=$(OBJDIR)/$(*F).lst

# Optimize use of the single-precision FPU
#
CFLAGS += -fsingle-precision-constant

# This will not work without recompiling libs
#
# CFLAGS += -fshort-double

#---------------- Compiler Options C++ ----------------
#
CXXFLAGS  = $(CFLAGS)

#---------------- Assembler Options ----------------
#  -Wa,...:   tell GCC to pass this to the assembler
#  -adhlns:   create listing
#
ASFLAGS = -Wa,-adhlns=$(OBJDIR)/$(*F).lst

#---------------- Linker Options ----------------
#  -Wl,...:     tell GCC to pass this to linker
#    -Map:      create map file
#    --cref:    add cross reference to  map file
LDFLAGS += -lm
LDFLAGS += -Wl,-Map=$(TARGET).map,--cref
LDFLAGS += -Wl,--gc-sections
LDFLAGS += -Tsrc/stm32_flash.ld

#============================================================================

# Define programs and commands
TOOLCHAIN = arm-none-eabi
CC        = $(TOOLCHAIN)-gcc
OBJCOPY   = $(TOOLCHAIN)-objcopy
OBJDUMP   = $(TOOLCHAIN)-objdump
SIZE      = $(TOOLCHAIN)-size
NM        = $(TOOLCHAIN)-nm
OPENOCD   = openocd
DOXYGEN   = doxygen
STLINK    = tools/ST-LINK_CLI.exe

ifeq (AMD64, $(PROCESSOR_ARCHITEW6432))
  SUBWCREV = tools/SubWCRev64.exe
else
  SUBWCREV = tools/SubWCRev.exe
endif

# Compiler flags to generate dependency files
GENDEPFLAGS = -MMD -MP -MF $(OBJDIR)/$(*F).d

# Combine all necessary flags and optional flags
# Add target processor to flags.
#
#CPU = -mcpu=cortex-m3 -mthumb -mfloat-abi=soft
#CPU = -mcpu=cortex-m4 -mthumb
#

#CPU = -march=armv7e-m -mfpu=fpv4-sp-d16  -mfloat-abi=softfp -std=gnu99 -fsingle-precision-constant
CPU = -mcpu=cortex-m4 -mthumb -mfloat-abi=softfp -mfpu=fpv4-sp-d16

CFLAGS   += $(CPU)
CXXFLAGS += $(CPU)
ASFLAGS  += $(CPU)
LDFLAGS  += $(CPU)

# Default target.
all:  gccversion build showsize

build: elf hex lss sym bin

elf: $(TARGET).elf
hex: $(TARGET).hex
bin: $(TARGET).bin
lss: $(TARGET).lss
sym: $(TARGET).sym

doxygen:
	@echo
	@echo Creating Doxygen documentation
	@$(DOXYGEN)

# Display compiler version information
gccversion:
	@$(CC) --version

# Show the final program size
showsize: elf
	@echo
	@$(SIZE) $(TARGET).elf 2>/dev/null

# Flash the device
flash: hex
#	$(OPENOCD) -f "openocd.cfg" -c "flash_image $(TARGET).elf; shutdown"
	$(STLINK) -c SWD -P $(TARGET).hex -Run

# Target: clean project
clean:
	@echo Cleaning project:
	rm -rf $(OBJDIR)
	rm -rf docs/html

# Create extended listing file from ELF output file
%.lss: %.elf
	@echo
	@echo Creating Extended Listing: $@
	$(OBJDUMP) -h -S -z $< > $@

# Create a symbol table from ELF output file
%.sym: %.elf
	@echo
	@echo Creating Symbol Table: $@
	$(NM) -n $< > $@

# Link: create ELF output file from object files
.SECONDARY: $(TARGET).elf
.PRECIOUS:  $(OBJECTS)
$(TARGET).elf: $(OBJECTS)
	@echo
	@echo Linking: $@
	$(CC) $^ $(LDFLAGS) --output $@

# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
	@echo
	@echo Creating hex file: $@
	$(OBJCOPY) -O ihex $< $@

# Create bin file :
%.bin: %.elf
	@echo
	@echo Creating bin file: $@
	$(OBJCOPY) -O binary $< $@

# Compile: create object files from C source files
$(OBJDIR)/%.o : %.c
	@echo
	@echo Compiling C: $<
	$(CC) -c $(CPPFLAGS) $(CFLAGS) $(GENDEPFLAGS) $< -o $@

# Compile: create object files from C++ source files
$(OBJDIR)/%.o : %.cpp
	@echo
	@echo Compiling CPP: $<
	$(CC) -c $(CPPFLAGS) $(CXXFLAGS) $(GENDEPFLAGS) $< -o $@

# Assemble: create object files from assembler source files
$(OBJDIR)/%.o : %.s
	@echo
	@echo Assembling: $<
	$(CC) -c $(CPPFLAGS) $(ASFLAGS) $< -o $@

# Create object file directories
$(shell mkdir -p $(OBJDIR) 2>/dev/null)
$(shell mkdir -p $(OBJDIR)/src 2>/dev/null)
$(shell mkdir -p $(OBJDIR)/FreeRTOS/Source/ 2>/dev/null)
$(shell mkdir -p $(OBJDIR)/FreeRTOS/Source/portable/GCC/ARM_CM4F 2>/dev/null)
$(shell mkdir -p $(OBJDIR)/libs/STM32F4xx_StdPeriph_Driver/src 2>/dev/null)

# Include the dependency files
-include $(wildcard $(OBJDIR)/*.d)

# Listing of phony targets
.PHONY: all build flash clean \
        doxygen elf lss sym \
        showsize gccversion


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#include "SlatePrivatePCH.h"
#include "MultiBox.h"

namespace EExtensionType
{
	enum Type
	{
		/** Menu bar extension (FMenuBarBuilder) */
		MenuBar,

		/** Menu extension (FMenuBuilder) */
		Menu,

		/** Toolbar extension (FToolBarBuilder) */
		ToolBar,
	};
}

class FExtensionBase
{

public:

	/** Virtual destructor needed, so that our members get cleaned up properly */
	virtual ~FExtensionBase()
	{
	}

	/** @return Returns the type of extension object.  Implement this in derived classes */
	virtual EExtensionType::Type GetType() const = 0;

	/** The ID of the extension point. */
	FName Hook;

	/** Where to hook in relation to the extension point */
	EExtensionHook::Position HookPosition;

	/** Command list to use for the actions being added to the UI */
	TSharedPtr< FUICommandList > CommandList;

};

class FMenuBarExtension : public FExtensionBase
{

public:

	/** FExtensionBase implementation */
	virtual EExtensionType::Type GetType() const override
	{
		return EExtensionType::MenuBar;
	}

	/** Called to populate the menu bar */
	FMenuBarExtensionDelegate MenuBarExtensionDelegate;
};

class FMenuExtension : public FExtensionBase
{

public:

	/** FExtensionBase implementation */
	virtual EExtensionType::Type GetType() const override
	{
		return EExtensionType::Menu;
	}

	/** Called to populate the menu */
	FMenuExtensionDelegate MenuExtensionDelegate;
};

class FToolBarExtension : public FExtensionBase
{

public:

	/** FExtensionBase implementation */
	virtual EExtensionType::Type GetType() const override
	{
		return EExtensionType::ToolBar;
	}

	/** Called to populate the menu */
	FToolBarExtensionDelegate ToolBarExtensionDelegate;
};

TSharedRef< const FExtensionBase > FExtender::AddMenuBarExtension( FName ExtensionHook, EExtensionHook::Position HookPosition, const TSharedPtr< FUICommandList >& CommandList, const FMenuBarExtensionDelegate& MenuBarExtensionDelegate )
{
	TSharedRef< FMenuBarExtension > MenuBarExtension( new FMenuBarExtension );
	MenuBarExtension->Hook = ExtensionHook;
	MenuBarExtension->HookPosition = HookPosition;
	MenuBarExtension->CommandList = CommandList;
	MenuBarExtension->MenuBarExtensionDelegate = MenuBarExtensionDelegate;
	Extensions.Add( MenuBarExtension );

	return MenuBarExtension;
}

TSharedRef< const FExtensionBase > FExtender::AddMenuExtension( FName ExtensionHook, EExtensionHook::Position HookPosition, const TSharedPtr< FUICommandList >& CommandList, const FMenuExtensionDelegate& MenuExtensionDelegate )
{
	TSharedRef< FMenuExtension > MenuExtension( new FMenuExtension );
	MenuExtension->Hook = ExtensionHook;
	MenuExtension->HookPosition = HookPosition;
	MenuExtension->CommandList = CommandList;
	MenuExtension->MenuExtensionDelegate = MenuExtensionDelegate;
	Extensions.Add( MenuExtension );

	return MenuExtension;
}

TSharedRef< const FExtensionBase > FExtender::AddToolBarExtension( FName ExtensionHook, EExtensionHook::Position HookPosition, const TSharedPtr< FUICommandList >& CommandList, const FToolBarExtensionDelegate& ToolBarExtensionDelegate )
{
	TSharedRef< FToolBarExtension > ToolBarExtension( new FToolBarExtension );
	ToolBarExtension->Hook = ExtensionHook;
	ToolBarExtension->HookPosition = HookPosition;
	ToolBarExtension->CommandList = CommandList;
	ToolBarExtension->ToolBarExtensionDelegate = ToolBarExtensionDelegate;
	Extensions.Add( ToolBarExtension );

	return ToolBarExtension;
}

void FExtender::RemoveExtension( const TSharedRef< const FExtensionBase >& Extension )
{
	Extensions.Remove( Extension );
}

void FExtender::Apply( FName ExtensionHook, EExtensionHook::Position HookPosition, FMenuBarBuilder& MenuBarBuilder ) const
{
	for( auto ExtensionIt( Extensions.CreateConstIterator() ); ExtensionIt; ++ExtensionIt )
	{
		const auto& Extension = *ExtensionIt;
		if( Extension->GetType() == EExtensionType::MenuBar && Extension->Hook == ExtensionHook && Extension->HookPosition == HookPosition )
		{
			const auto& MenuBarExtension = StaticCastSharedPtr< const FMenuBarExtension >( Extension );

			if ( Extension->CommandList.IsValid() )
			{
				// Push the command list needed for this extension's menu items
				MenuBarBuilder.PushCommandList( Extension->CommandList.ToSharedRef() );
			}

			// Extend the menu!
			MenuBarExtension->MenuBarExtensionDelegate.ExecuteIfBound( MenuBarBuilder );

			if ( Extension->CommandList.IsValid() )
			{
				// Restore the original command list
				MenuBarBuilder.PopCommandList();
			}
		}
	}
}

void FExtender::Apply( FName ExtensionHook, EExtensionHook::Position HookPosition, FMenuBuilder& MenuBuilder ) const
{
	for( auto ExtensionIt( Extensions.CreateConstIterator() ); ExtensionIt; ++ExtensionIt )
	{
		const auto& Extension = *ExtensionIt;
		if( Extension->GetType() == EExtensionType::Menu && Extension->Hook == ExtensionHook && Extension->HookPosition == HookPosition )
		{
			const auto& MenuExtension = StaticCastSharedPtr< const FMenuExtension >( Extension );

			if ( Extension->CommandList.IsValid() )
			{
				// Push the command list needed for this extension's menu items
				MenuBuilder.PushCommandList( Extension->CommandList.ToSharedRef() );
			}

			// Extend the menu!
			MenuExtension->MenuExtensionDelegate.ExecuteIfBound( MenuBuilder );

			if ( Extension->CommandList.IsValid() )
			{
				// Restore the original command list
				MenuBuilder.PopCommandList();
			}
		}
	}
}

void FExtender::Apply( FName ExtensionHook, EExtensionHook::Position HookPosition, FToolBarBuilder& ToolBarBuilder ) const
{
	for( auto ExtensionIt( Extensions.CreateConstIterator() ); ExtensionIt; ++ExtensionIt )
	{
		const auto& Extension = *ExtensionIt;
		if( Extension->GetType() == EExtensionType::ToolBar && Extension->Hook == ExtensionHook && Extension->HookPosition == HookPosition )
		{
			const auto& ToolBarExtension = StaticCastSharedPtr< const FToolBarExtension >( Extension );

			if ( Extension->CommandList.IsValid() )
			{
				// Push the command list needed for this extension's menu items
				ToolBarBuilder.PushCommandList( Extension->CommandList.ToSharedRef() );
			}

			// Extend the menu!
			ToolBarExtension->ToolBarExtensionDelegate.ExecuteIfBound( ToolBarBuilder );

			if ( Extension->CommandList.IsValid() )
			{
				// Restore the original command list
				ToolBarBuilder.PopCommandList();
			}
		}
	}
}

TSharedPtr<FExtender> FExtender::Combine(const TArray< TSharedPtr<FExtender> >& Extenders)
{
	TSharedPtr<FExtender> OutExtender = MakeShareable(new FExtender);
	for (int32 i = 0; i < Extenders.Num(); ++i)
	{
		OutExtender->Extensions.Append(Extenders[i]->Extensions);
	}
	return OutExtender;
}


text:
package org.derekwyatt.concurrent

import com.google.common.util.concurrent.ListenableFuture
import java.util.concurrent.{TimeUnit, Executor}
import scala.concurrent.{CanAwait, ExecutionContext, Future}
import scala.concurrent.duration._
import scala.util.{Try, Success}

// Most of this code came from https://github.com/eigengo/activator-akka-cassandra

/**
 * Google's `ListenableFuture` requires a [[java.util.concurrent.Executor]] and
 * we've got a [[scala.concurrent.ExecutionContext]].  This wraps it up so we
 * can use it to execute the given [[java.lang.Runnable]].
 */
private case class ExecutionContextExecutor(executionContext: ExecutionContext) extends Executor {
  def execute(command: Runnable): Unit = executionContext.execute(command)
}

/**
 * Provides implicit enrichments for Google's `ListenableFuture` that, while
 * much better than the `java.util.concurrent.Future`, still sucks in comparison
 * to [[scala.concurrent.Future]]. :)
 */
trait ListenableEnrichments {
  implicit class RichListenableFuture[T](listenableFuture: ListenableFuture[T]) extends Future[T] {
    /**
     * See [[scala.concurrent.Future#ready]].
     */
    def ready(atMost: Duration)(implicit permit: CanAwait): this.type = {
      listenableFuture.get(atMost.toMillis, TimeUnit.MILLISECONDS)
      this
    }

    /**
     * See [[scala.concurrent.Future#result]].
     */
    def result(atMost: Duration)(implicit permit: CanAwait): T =
      listenableFuture.get(atMost.toMillis, TimeUnit.MILLISECONDS)

    /**
     * See [[scala.concurrent.Future#onComplete]].
     */
    def onComplete[U](func: Try[T] => U)(implicit executionContext: ExecutionContext): Unit = {
      if (isCompleted) {
        func(Success(listenableFuture.get))
      } else {
        listenableFuture.addListener(new Runnable {
          def run() {
            func(Try(listenableFuture.get))
          }
        }, ExecutionContextExecutor(executionContext))
      }
    }

    /**
     * See [[scala.concurrent.Future#isCompleted]].
     */
    def isCompleted: Boolean = listenableFuture.isDone

    /**
     * See [[scala.concurrent.Future#value]].
     */
    def value: Option[Try[T]] =
      if (isCompleted)
        Some(Try(listenableFuture.get))
      else
        None
  }
}


text:
// Copyright 2011 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * JSON.parse must create a property with the given property name
 *
 * @path ch15/15.12/15.12.2/S15.12.2_A1.js
 * @description Tests that JSON.parse treats "__proto__" as a regular property name
 */

var x = JSON.parse('{"__proto__":[]}');
if (Object.getPrototypeOf(x) !== Object.prototype) {
  $FAIL('#1: JSON.parse confused by "__proto__"');
}
if (!Array.isArray(x.__proto__)) {
  $FAIL('#2: JSON.parse did not set "__proto__" as a regular property');
}


text:
package com.opengamma.analytics.financial.model.option.definition;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;

import org.testng.annotations.Test;
import org.threeten.bp.ZonedDateTime;

import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.financial.model.volatility.surface.VolatilitySurface;
import com.opengamma.analytics.math.curve.ConstantDoublesCurve;
import com.opengamma.analytics.math.surface.ConstantDoublesSurface;
import com.opengamma.timeseries.date.localdate.ImmutableLocalDateDoubleTimeSeries;
import com.opengamma.timeseries.date.localdate.LocalDateDoubleTimeSeries;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class StandardOptionWithSpotTimeSeriesDataBundleTest {
  private static final double R = 0.05;
  private static final double SIGMA = 0.15;
  private static final YieldAndDiscountCurve CURVE = YieldCurve.from(ConstantDoublesCurve.from(R));
  private static final double B = 0.01;
  private static final VolatilitySurface SURFACE = new VolatilitySurface(ConstantDoublesSurface.from(SIGMA));
  private static final double SPOT = 100;
  private static final ZonedDateTime DATE = DateUtils.getUTCDate(2010, 5, 1);
  private static final LocalDateDoubleTimeSeries TS = ImmutableLocalDateDoubleTimeSeries.of(new int[] {19700101, 19700102}, new double[] {3, 4});
  private static final YieldAndDiscountCurve OTHER_CURVE = YieldCurve.from(ConstantDoublesCurve.from(R + 1));
  private static final double OTHER_B = B + 1;
  private static final VolatilitySurface OTHER_SURFACE = new VolatilitySurface(ConstantDoublesSurface.from(SIGMA + 1));
  private static final double OTHER_SPOT = SPOT + 1;
  private static final ZonedDateTime OTHER_DATE = DateUtils.getDateOffsetWithYearFraction(DATE, 1);
  private static final LocalDateDoubleTimeSeries OTHER_TS = ImmutableLocalDateDoubleTimeSeries.of(new int[] {19700101, 19700102}, new double[] {5, 6});
  private static final StandardOptionWithSpotTimeSeriesDataBundle DATA = new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, SURFACE, SPOT, DATE, TS);

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNullBundle() {
    new StandardOptionWithSpotTimeSeriesDataBundle(null);
  }

  @Test
  public void testGetters() {
    assertEquals(DATA.getInterestRateCurve(), CURVE);
    assertEquals(DATA.getCostOfCarry(), B, 0);
    assertEquals(DATA.getDate(), DATE);
    assertEquals(DATA.getSpot(), SPOT, 0);
    assertEquals(DATA.getVolatilitySurface(), SURFACE);
    assertEquals(DATA.getSpotTimeSeries(), TS);
  }

  @Test
  public void testGetInterestRate() {
    for (int i = 0; i < 10; i++) {
      assertEquals(DATA.getInterestRate(Math.random()), R, 1e-15);
    }
  }

  @Test
  public void testGetVolatility() {
    for (int i = 0; i < 10; i++) {
      assertEquals(DATA.getVolatility(Math.random(), Math.random()), SIGMA, 1e-15);
    }
  }

  @Test
  public void testEqualsAndHashCode() {
    final StandardOptionDataBundle other1 = new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, SURFACE, SPOT, DATE, TS);
    final StandardOptionDataBundle other2 = new StandardOptionWithSpotTimeSeriesDataBundle(new StandardOptionDataBundle(CURVE, B, SURFACE, SPOT, DATE), TS);
    final StandardOptionDataBundle other3 = new StandardOptionWithSpotTimeSeriesDataBundle(DATA);
    assertEquals(DATA, other1);
    assertEquals(DATA.hashCode(), other1.hashCode());
    assertEquals(DATA, other2);
    assertEquals(DATA.hashCode(), other2.hashCode());
    assertEquals(DATA, other3);
    assertEquals(DATA.hashCode(), other3.hashCode());
    assertFalse(DATA.equals(new StandardOptionWithSpotTimeSeriesDataBundle(OTHER_CURVE, B, SURFACE, SPOT, DATE, TS)));
    assertFalse(DATA.equals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, OTHER_B, SURFACE, SPOT, DATE, TS)));
    assertFalse(DATA.equals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, OTHER_SURFACE, SPOT, DATE, TS)));
    assertFalse(DATA.equals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, SURFACE, OTHER_SPOT, DATE, TS)));
    assertFalse(DATA.equals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, SURFACE, SPOT, OTHER_DATE, TS)));
    assertFalse(DATA.equals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, SURFACE, SPOT, DATE, OTHER_TS)));
  }

  @Test
  public void testBuilders() {
    assertEquals(new StandardOptionWithSpotTimeSeriesDataBundle(OTHER_CURVE, B, SURFACE, SPOT, DATE, TS), DATA.withInterestRateCurve(OTHER_CURVE));
    assertEquals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, OTHER_B, SURFACE, SPOT, DATE, TS), DATA.withCostOfCarry(OTHER_B));
    assertEquals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, OTHER_SURFACE, SPOT, DATE, TS), DATA.withVolatilitySurface(OTHER_SURFACE));
    assertEquals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, SURFACE, OTHER_SPOT, DATE, TS), DATA.withSpot(OTHER_SPOT));
    assertEquals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, SURFACE, SPOT, OTHER_DATE, TS), DATA.withDate(OTHER_DATE));
    assertEquals(new StandardOptionWithSpotTimeSeriesDataBundle(CURVE, B, SURFACE, SPOT, DATE, OTHER_TS), DATA.withSpotTimeSeries(OTHER_TS));
  }
}