text:
/*
 * Connection.h
 *
 *  Created on: 2013-7-16
 *      Author: Administrator
 */

#ifndef CONNECTION_H_
#define CONNECTION_H_

#include <common.h>
#include <PoolObject.h>
#include <Runtime.h>
#include <Buffer.h>
#include <Log.h>

#include <boost/asio.hpp>
#include <iostream>

namespace zertcore{ namespace net{

/**
 *
 *
 *
 */
using namespace zertcore::base;
using namespace zertcore::utils;

using namespace asio::ip;

typedef asio::io_service					io_service;

namespace errors {
/**
 * avoid "system" namespace ambiguous
 */
typedef ::boost::system::error_code			error_code_type;

typedef uint	type;
enum {
	ERROR_NONE								= 0,
	ERROR_SOCK_SHUTDOWN						= 1,
	ERROR_UNKNOWN							= 10,
};

}

enum {
	TIMER_HEARTBEAT							= 10,
	TIMER_CONNECTION_EXPIRED				= 30,
	TIMER_INTERVAL							= 1,
};

namespace messages {

enum {
	COMMAND_KEY_BASE						= 0x7ffffff,
	COMMAND_KEY_HEARTBEAT					= COMMAND_KEY_BASE + 1,
	COMMAND_KEY_RECEIVE_HEARTBEAT			= COMMAND_KEY_BASE + 2,
};

}

enum {
/**
* "Size Head" means:
* struct package {
*   uint32 size;
*   byte data[size-sizeof(uint32)];
* }
*/
	PACKAGE_TYPE_SIZEHEAD					= 1 << 0,

/**
* "Special Tail" means:
* struct package {
*    byte data[ N ]; // N is unknown
*    T sign;
* }
*/
	PACKAGE_TYPE_SPECIALTAIL				= 1 << 1,

	PACKAGE_TYPE_BOTH						= PACKAGE_TYPE_SIZEHEAD | PACKAGE_TYPE_SPECIALTAIL,
};

template <typename FC>
class Connection:
		public PoolObject<FC>,
		public Updater<FC>
{
public:
	enum {
		TYPE_NONE							= 0,
		TYPE_CLIENT							= 1 << 0,
		TYPE_SERVER							= 1 << 1,
		TYPE_BOTH							= TYPE_CLIENT | TYPE_SERVER,
	};
public:

public:
	typedef function<void (const BytePointer&)>
											read_handler_type;
	typedef function<void ()>				write_handler_type;
	typedef function<void ()>				connect_handler_type;
	typedef function<void (const errors::type&)>
											error_handler_type;

public:
	explicit Connection(io_service& ios, const uint package_type = PACKAGE_TYPE_BOTH,
								const size_t& max_size = SERVER_IO_PACKAGE_SIZE)
			: type_(TYPE_NONE), is_connected_(false), max_package_size_(max_size), holder_error_(0),
			  socket_(ios), package_type_(package_type), heartbeat_timer_(TIMER_HEARTBEAT),
			  expired_timer_(TIMER_CONNECTION_EXPIRED) {
	}
	virtual ~Connection() {
	}

public:
	tcp::socket& socket() {
		return socket_;
	}
	const tcp::socket& socket() const {
		return socket_;
	}

	void registerReadHandler(read_handler_type handler) {
		read_handler_ = handler;
	}
	void registerConnectHandler(connect_handler_type handler) {
		connect_handler_ = handler;
	}
	void registerWriteHandler(write_handler_type handler) {
		write_handler_ = handler;
	}
	void registerErrorHandler(error_handler_type handler) {
		error_handler_ = handler;
	}

	void shutdown() {
		if (isConnected()) {
			printf("shutdown()\n");
			try {
				socket_.shutdown(tcp::socket::shutdown_both);
			}
			catch(std::exception&) {
				;
			}
			setConnected(false);
		}
	}
	bool isConnected() const {
		return is_connected_;
	}
	void connect(tcp::resolver::iterator endpoint_iterator) {
		endpoint_iterator_ = endpoint_iterator;

		setType(TYPE_CLIENT);
		doConnect();
	}
	void reConnect() {
		printf("Reconnecting..\n");
		doConnect();
	}

	// send heart heat package
	void heartbeat() {
		if (heartbeat_timer_.expired(true)) {
			doSendCommand(messages::COMMAND_KEY_HEARTBEAT);
		}
	}
	bool isExpired() {
		return expired_timer_.expired();
	}
	bool update(const time_type& interval) {
		if (isExpired()) {
			LOG(NOTE) << "Expired with Connection [" << remote_address_.c_str() << "]";
			shutdown();
			return false;
		}

		heartbeat();
		return true;
	}
	void startListen() {
		setType(TYPE_SERVER);
		setConnected();

		getRemoteInfo();
		LOG(NOTE) << "Establish Connection with " << remote_address_.c_str() << "";

		if (connect_handler_)
			connect_handler_();

		doRead();
	}
	void setType(const uint type) {
		type_ |= type;
	}
	uint getType() {
		return type_;
	}

	template <typename T>
	Connection& operator << (const T& d) {
		send_buffer_.append(&d, sizeof(T));
		return *this;
	}

	template <typename T>
	Connection& operator << (const BufferPointer<T>& bp) {
		if (bp.data)
			send_buffer_.append(bp.data, bp.size * sizeof(T));

		return *this;
	}

	template <typename T>
	Connection& operator >> (T& d) {
		recv_buffer_ >> d;
		return *this;
	}

protected:
	void doSendCommand(uint command) {
		BytePointer bp(reinterpret_cast<byte *>(&command), sizeof(command));
		doSend(bp);
	}

	void doFormatSend(const BytePointer& bp, errors::type error = errors::ERROR_NONE) {
		beginFormatSend(bp.size);
		formatSending(bp);
		endFormatSend(error);

	}
	void beginFormatSend(size_t data_size) {
		uint32 total_size = (uint32)data_size;

		if (package_type_ & PACKAGE_TYPE_SPECIALTAIL) {
			total_size += sizeof(eof_key_type);
		}
		if (package_type_ & PACKAGE_TYPE_SIZEHEAD) {
			total_size += sizeof(uint32);
			send_buffer_.append(total_size);
		}
	}
	void formatSending(const BytePointer& bp) {
		send_buffer_.append(bp);
	}
	void endFormatSend(errors::type error = errors::ERROR_NONE) {
		if (package_type_ & PACKAGE_TYPE_SPECIALTAIL) {
			eof_key_type key = (eof_key_type)SERVER_IO_EOF;
			send_buffer_.append(key);
		}

		holder_error_ = error;
		doSendBuffer();
	}
	void doConnect() {
		socket_.async_connect(*endpoint_iterator_, bind(&Connection::handleConnect, this->template thisPtr(),
			asio::placeholders::error));
	}
	void doSend(const BytePointer& bp, errors::type error = errors::ERROR_NONE) {
		if (bp.data) {
			send_buffer_.append(bp);
		}

		holder_error_ = error;

		doSendBuffer();
	}
	void doRead() {
		if (isConnected()) {
			socket_.async_read_some(
				asio::buffer(recv_buffer_.writeBuffer(max_package_size_), max_package_size_),
				bind(&Connection::handleRead, this->template thisPtr(), asio::placeholders::error,
					asio::placeholders::bytes_transferred));
		}
	}

	void handleConnect(const errors::error_code_type& error_code) {
		if (!error_code) {
			LOG(NOTE) << "Connected with " << remote_address_.c_str();

			getRemoteInfo();
			setConnected();

			if (connect_handler_)
				connect_handler_();

			doRead();
		}
	}
	void handleRead(const errors::error_code_type& error_code, size_t bytes_transferred) {
		if (!error_code) {
			recv_buffer_.writeSize(bytes_transferred);

			// printf("bytes_transferred:%ld\n", bytes_transferred);

			if (bytes_transferred >= sizeof(uint32) && handleRequest()) {
				doRead();
				return ;
			}
		}
		else {
			LOG(NOTE) << "ASIO SYS ERROR[" << error_code << "]";
		}
		if (error_handler_)
			error_handler_(errors::ERROR_SOCK_SHUTDOWN);

		if (type_ & TYPE_CLIENT) {
			reConnect();
		}
		else {
			shutdown();
		}
	}
	bool handleRequest() {
		bool first_loop = true;

		do {
			size_t begin = 0, end = 0;
			bool fetch_succeed = false;

			if (recv_buffer_.empty())
				return !first_loop;

			// recv_buffer_.print();

			if (first_loop) {
			/**
			 * reset expired & heart beat timer if any message arrived.
			 */
				expired_timer_.reset();
				heartbeat_timer_.reset();
			}

			if (checkCommandKey())
				/**
				 * if the first package is command key, set first loop is over
				 */
				first_loop = false;

			do {
				if (package_type_ & PACKAGE_TYPE_SIZEHEAD) {
					fetch_succeed = fetchPackageBySizeHead(begin, end);
					if (!fetch_succeed) break;
				}
				if (package_type_ & PACKAGE_TYPE_SPECIALTAIL) {
					fetch_succeed = fetchPackageBySpecialTail(begin, end);
				}
			}while(false);

			if (!fetch_succeed) {
				/**
				 * if the package is in error format, shutdown it to avoid further damage.
				 */
				return first_loop? false: true;
			}
			first_loop = false;

			if (begin < end && read_handler_) {
				BytePointer tmp_bp(recv_buffer_.readBuffer(begin), end - begin);
				read_handler_(tmp_bp);
			}
			recv_buffer_.erase(0, end);
		}
		while(true);

		// never reach here.
		return false;
	}
	bool fetchPackageBySizeHead(size_t& begin, size_t& end) {
		if (recv_buffer_.size() < sizeof(uint32))
			return false;

		/**
		 * this size is calculating including itself.
		 */
		uint32 size = recv_buffer_.offset<uint32>(begin);

		printf("fetchPackageBySizeHead(): head size:%u buffer size:%ld\n", size, recv_buffer_.size());

		if (size <= recv_buffer_.size()) {
			end = begin + size;
			begin += sizeof(uint32);

			return true;
		}

		return false;
	}
	bool fetchPackageBySpecialTail(size_t& begin, size_t& end) {
		/**
		 * if end is setting, means it should be check [end] offset is set up with the EOF key
		 */
		if (end > 0) {
			if (end < sizeof(eof_key_type))
				return false;

			eof_key_type key = recv_buffer_.offset<uint32>(end - sizeof(eof_key_type));
			if (key != SERVER_IO_EOF) {
				return false;
			}

			return true;
		}

		// Deprecated!!
		return false;
	}
	bool checkCommandKey() {
		uint32 key = recv_buffer_.offset<uint32>(0);

		if (key > messages::COMMAND_KEY_BASE) {
			switch (key) {
			case messages::COMMAND_KEY_HEARTBEAT:
				// send heart heat package;
				doSendCommand(messages::COMMAND_KEY_RECEIVE_HEARTBEAT);
				break;
			case messages::COMMAND_KEY_RECEIVE_HEARTBEAT:
				// wouldnt do anything since the expiredtimer is updated
				// when receive the message
				break;

			default:
				break;// handle other command key
			}

			recv_buffer_.erase(0, sizeof(key));
			return true;
		}

		return false;
	}

public:
	string getRemoteAddress() const {
		return remote_address_;
	}

private:
	void getRemoteInfo() {
		try {
			tcp::endpoint remote_ep = socket_.remote_endpoint();
			address remote_ad = remote_ep.address();

			remote_address_ = remote_ad.to_string();
		}
		catch(std::exception&) {
			;
		}
	}

	void doSendBuffer() {
		if (!send_buffer_.empty() && isConnected()) {
			errors::error_code_type error_code;

			asio::write(socket_, asio::buffer(send_buffer_, send_buffer_.size()), error_code);
			/**
			asio::async_write(socket_, asio::buffer(send_buffer_, send_buffer_.size()),
					bind(&Connection::handleWrite, this->template thisPtr(), asio::placeholders::error));
			*/
			handleWrite(error_code);
		}
	}

	void handleWrite(const errors::error_code_type& error_code) {
		if (!error_code) {
			send_buffer_.clear();

			if (write_handler_)
				write_handler_();
		}
		else {
			setConnected(false);
			if (type_ & TYPE_CLIENT)
				reConnect();
			else
				shutdown();
		}
	}

	void setConnected(bool flag = true) {
		is_connected_ = flag;
		if (is_connected_) {
			expired_timer_.reset();
			heartbeat_timer_.reset();

			this->template enableUpdate(TIMER_INTERVAL);
			doSendBuffer();
		}
		else {
			this->template disableUpdate();
		}
	}

private:
	uint						type_;
	bool						is_connected_;

	string						remote_address_;
	const size_t				max_package_size_;
	uint						holder_error_;

	ByteBuffer					recv_buffer_;
	ByteBuffer					send_buffer_;

	tcp::socket					socket_;

	const uint					package_type_;

	connect_handler_type		connect_handler_;
	read_handler_type			read_handler_;
	write_handler_type			write_handler_;
	error_handler_type			error_handler_;

	ExpiredTimer				heartbeat_timer_;
	ExpiredTimer				expired_timer_;

	tcp::resolver::iterator		endpoint_iterator_;
};

/**
 * ConnectionAllocator<Server, Session>
 */
template <class Server, class Session>
class ConnectionAllocator
{
public:
	typename Session::ptr alloc(Server& server, io_service& ios) const {
		return load<Session, Server, asio::io_service> (server, ios);
	}

public:
	static ConnectionAllocator<Server, Session> instance;
};

template <class Server, class Session>
ConnectionAllocator<Server, Session> ConnectionAllocator<Server, Session>::instance;

/**
 *
 * ConnectionOperator<FC, Session, SessionAllocator>
 *
 */
template <class FC, class Session, class SessionAllocator = ConnectionAllocator<FC, Session> >
class ConnectionOperator
{
public:
	typedef typename Session::ptr			session_ptr;
	typedef SessionAllocator&				session_allocator_type;

public:
	explicit ConnectionOperator(io_service& ios,
			session_allocator_type session_allocator = SessionAllocator::instance)
		: io_service_(ios), acceptor_(ios), resolver_(ios),
		  session_allocator_(session_allocator) {
		;
	}

	virtual ~ConnectionOperator() {}

public:
	void bind(const string& host, int port) {
		address addr; addr.from_string(host);
		tcp::endpoint endpoint(addr, port);

		acceptor_.open(endpoint.protocol());
		acceptor_.set_option(tcp::acceptor::reuse_address(true));
		acceptor_.bind(endpoint);
		acceptor_.listen();

		startAccept();
	}

	session_ptr connect(const string& host, int port) {
		tcp::resolver::query query(tcp::v4(), host, lexical_cast<string>(port));
		tcp::resolver::iterator iterator = resolver_.resolve(query);

		session_ptr conn = session_allocator_.template alloc(dynamic_cast<FC&>(*this), io_service_);
		conn->connect(iterator);

		return conn;
	}

private:
	void startAccept() {
		session_ptr conn = session_allocator_.template alloc(dynamic_cast<FC&>(*this), io_service_);
		acceptor_.async_accept(conn->socket(),
			::boost::bind(&ConnectionOperator::handleAccept, this, conn, asio::placeholders::error));
	}
	void handleAccept(session_ptr conn, const errors::error_code_type& error) {
		conn->startListen();
		startAccept();
	}

private:
	tcp::endpoint& buildPoint(const string& host, int port) {
		address addr; addr.from_string(host);
		static tcp::endpoint endpoint(addr, port);

		return endpoint;
	}

private:
	io_service&					io_service_;
	tcp::acceptor				acceptor_;
	tcp::resolver				resolver_;
	session_allocator_type		session_allocator_;
};

}}

#endif /* CONNECTION_H_ */


text:
//
//  Created by Mathieu Bolard on 31/07/12.
//  Copyright (c) 2012 Mathieu Bolard. All rights reserved.
//
//  https://github.com/mattlawer/BButton
//
//
//  BButton is licensed under the MIT license
//  http://opensource.org/licenses/MIT
//
//
//  -----------------------------------------
//  Edited and refactored by Jesse Squires on 2 April, 2013.
//
//  http://github.com/jessesquires/BButton
//
//  http://hexedbits.com
//

#import <UIKit/UIKit.h>
#import "UIColor+BButton.h"
#import "NSString+FontAwesome.h"

/**
 *  A constant describing the button style.
 */
typedef NS_ENUM(NSUInteger, BButtonStyle) {
    /**
     *  Styles the button like bootstrap version 2.x.x.
     */
    BButtonStyleBootstrapV2,
    /**
     *  Styles the button like bootstrap version 3.x.x.
     */
    BButtonStyleBootstrapV3
};

/**
 *  A constant describing the button type. This sets the button color.
 */
typedef NS_ENUM(NSUInteger, BButtonType) {
    BButtonTypeDefault,
    BButtonTypePrimary,
    BButtonTypeInfo,
    BButtonTypeSuccess,
    BButtonTypeWarning,
    BButtonTypeDanger,
    BButtonTypeInverse,
    BButtonTypeTwitter,
    BButtonTypeFacebook,
    BButtonTypePurple,
    BButtonTypeGray
};

/**
 *  An instanace of `BButton` is a subclass of `UIButton` that is styled like the Twitter Bootstrap buttons and is drawn entirely with `CoreGraphics`.
 */
@interface BButton : UIButton <UIAppearance>

/**
 *  The color of the button in its normal state. `BButton` automatically darks this color when the button enters its pressed state. The default value is `[UIColor bb_defaultColorV3]`, the color value associated with `BButtonTypeDefault`. @see BButtonType.
 */
@property (strong, nonatomic) UIColor *color;

/**
 *  The corner radius of the button. The default value is 6.0 for buttons initialized with style `BButtonStyleBootstrapV2`, or 4.0 for buttons initialized with style `BButtonStyleBootstrapV3`. @see BButtonType.
 */
@property (strong, nonatomic) NSNumber *buttonCornerRadius UI_APPEARANCE_SELECTOR;

/**
 *  A boolean value indicating whether or not the button should be drawn to reflect a disabled state when `enabled` is set to `NO`. The default value is `YES`.
 */
@property (assign, nonatomic) BOOL shouldShowDisabled;

#pragma mark - Initialization

/**
 *  Initializes and returns a button having the given frame, type, and style.
 *
 *  @param frame  A rectangle specifying the initial location and size of the button in its superview's coordinates.
 *  @param type   A constant that specifies the type of the button. @see BButtonType.
 *  @param style  A constant that specifies the style of the button. @see BButtonStyle.
 *
 *  @return An initialized `BButton` object or `nil` if the object could not be successfully initialized.
 */
- (instancetype)initWithFrame:(CGRect)frame type:(BButtonType)type style:(BButtonStyle)style;

/**
 *  Initializes and returns a button having the given frame, type, style, icon, and font size.
 *
 *  @param frame  A rectangle specifying the initial location and size of the button in its superview's coordinates.
 *  @param type   A constant that specifies the type of the button. @see BButtonType.
 *  @param style  A constant that specifies the style of the button. @see BButtonStyle.
 *  @param icon     A contant that specifies the FontAwesome icon of the button. @see FAIcon.
 *  @param fontSize A float specifying the font size of the button's `textLabel`.
 *
 *  @return An initialized `BButton` object or `nil` if the object could not be successfully initialized.
 */
- (instancetype)initWithFrame:(CGRect)frame
                         type:(BButtonType)type
                        style:(BButtonStyle)style
                         icon:(FAIcon)icon
                     fontSize:(CGFloat)fontSize;

/**
 *  Initializes and returns a button having the given frame, color, and style.
 *
 *  @param frame  A rectangle specifying the initial location and size of the button in its superview's coordinates.
 *  @param color  A `UIColor` object specifying the color of the button.
 *  @param style  A constant that specifies the style of the button. @see BButtonStyle.
 *
 *  @return An initialized `BButton` object or `nil` if the object could not be successfully initialized.
 */
- (instancetype)initWithFrame:(CGRect)frame color:(UIColor *)color style:(BButtonStyle)style;

/**
 *  Initializes and returns a button having the given frame, color, style, icon, and font size.
 *
 *  @param frame  A rectangle specifying the initial location and size of the button in its superview's coordinates.
 *  @param color  A `UIColor` object specifying the color of the button.
 *  @param style  A constant that specifies the style of the button. @see BButtonStyle.
 *  @param icon     A contant that specifies the FontAwesome icon of the button. @see FAIcon.
 *  @param fontSize A float specifying the font size of the button's `textLabel`.
 *
 *  @return An initialized `BButton` object or `nil` if the object could not be successfully initialized.
 */
- (instancetype)initWithFrame:(CGRect)frame
                        color:(UIColor *)color
                        style:(BButtonStyle)style
                         icon:(FAIcon)icon
                     fontSize:(CGFloat)fontSize;

/**
 *  Initializes and returns a special icon-only button having the given icon, type, and style. The button frame is set with an origin of `(0.0, 0.0)` and a size of `(40.0, 40.0)`. The button font size is set to `20.0`.
 *
 *  @param icon  A contant that specifies the FontAwesome icon of the button. @see FAIcon.
 *  @param type  A constant that specifies the type of the button. @see BButtonType.
 *  @param style A constant that specifies the style of the button. @see BButtonStyle.
 *
 *  @return An initialized `BButton` object or `nil` if the object could not be successfully initialized.
 */
+ (instancetype)awesomeButtonWithOnlyIcon:(FAIcon)icon
                                     type:(BButtonType)type
                                    style:(BButtonStyle)style;

/**
 *  Initializes and returns a special icon-only button having the given icon, color, and style. The button frame is set with an origin of `(0.0, 0.0)` and a size of `(40.0, 40.0)`. The button font size is set to `20.0`.
 *
 *  @param icon  A contant that specifies the FontAwesome icon of the button. @see FAIcon.
 *  @param color A `UIColor` object specifying the color of the button.
 *  @param style A constant that specifies the style of the button. @see BButtonStyle.
 *
 *  @return An initialized `BButton` object or `nil` if the object could not be successfully initialized.
 */
+ (instancetype)awesomeButtonWithOnlyIcon:(FAIcon)icon
                                    color:(UIColor *)color
                                    style:(BButtonStyle)style;

#pragma mark - BButton

/**
 *  Sets the style of the button after. @see BButtonStyle.
 *
 *  @param style A constant describing the button style.
 *
 *  @bug If also setting the button type via `setType:`, *you must set the button style first*, via this method.
 */
- (void)setStyle:(BButtonStyle)style;

/**
 *  Sets the type of the button. @see BButtonType.
 *
 *  @param type A constant describing the button type.
 */
- (void)setType:(BButtonType)type;

/**
 *  Adds the specified icon to the buttons's `titleLabel`, and sets `titleLabel.font` to `FontAwesome.ttf`.
 *
 *  @param icon   A constant describing the FontAwesome Icon. @see FAIcon.
 *  @param before A boolean value indicating if the icon should be placed before or after any existing text. Pass `YES` to place the icon before the text, and `NO` to place the icon after the text.
 *
 *  @warning A single space is inserted between the added icon and existing text.
 */
- (void)addAwesomeIcon:(FAIcon)icon beforeTitle:(BOOL)before;

@end

redpajama_set_name: RedPajamaGithub


text:
@import '../../../styles/variables.css';

:root {
  --activity-search-list-font-family: var(--default-font-family);
}

/* Reset */
.container {
  all: initial;
}

/* Styles */
.container {
  font-family: var(--activity-search-list-font-family);
  display: block;
  overflow-x: hidden;
  overflow-y: auto;
  flex: 1 1 auto;
  @apply --flex-fix;
}

.spinnerWrapper {
  padding: calc(var(--default-padding-large) * 2.5) 0;
  text-align: center;
}

.spinner {
  display: inline-block;
}

.text {
  padding: calc(var(--default-padding-large) * 2) var(--default-padding);
  text-align: center;

  & strong {
    font-weight: 500;
  }
}

.textEmoji {
  display: inline-block;
  margin-bottom: 1rem;
}

.error {
  display: block;
  text-align: center;
}


text:
Ext.define('App.model.Orders.mApproval',{
	extend: 'Ext.data.Model',
	fields:['id', 'name'],
	proxy: {
		type: 'rest',
		url: api_url +'/currency',
		reader: {
			type: 'json',
			root: 'results',successProperty: 'success',
			totalProperty: 'total'
		}
	},
});


text:
using System;
using Lib.AspNetCore.Mvc.JqGrid.Infrastructure.Enums;
using Lib.AspNetCore.Mvc.JqGrid.Infrastructure.Constants;

namespace Lib.AspNetCore.Mvc.JqGrid.Infrastructure.Options.Navigator
{
    /// <summary>
    /// Class which represents options for jqGrid Navigator edit action.
    /// </summary>
    public class JqGridNavigatorEditActionOptions : JqGridNavigatorModifyActionOptions, IJqGridNavigatorPageableFormActionOptions
    {
        #region Properties
        /// <summary>
        /// Gets or sets the options for keyboard navigation.
        /// </summary>
        public JqGridFormKeyboardNavigation NavigationKeys { get; set; }

        /// <summary>
        /// Gets or sets the value indicating if the pager buttons should appear on the form.
        /// </summary>
        public bool ViewPagerButtons { get; set; }

        /// <summary>
        /// Gets or sets the value indicating if the form should be recreated every time the dialog is activeted with the new options from colModel (if they are changed).
        /// </summary>
        public bool RecreateForm { get; set; }

        /// <summary>
        /// Gets or sets value indicating where the row just added should be placed.
        /// </summary>
        public JqGridNewRowPositions AddedRowPosition { get; set; }

        /// <summary>
        /// Gets or sets the information which is placed just after the modal header as additional row.
        /// </summary>
        public string TopInfo { get; set; }

        /// <summary>
        /// Gets or sets the information which is placed just after the buttons of the form as additional row.
        /// </summary>
        public string BottomInfo { get; set; }

        /// <summary>
        /// Gets or sets the value indicating if add action dialog should be cleared after submiting.
        /// </summary>
        public bool ClearAfterAdd { get; set; }

        /// <summary>
        /// Gets or sets the value indicating if add action dialog should be closed after submiting.
        /// </summary>
        public bool CloseAfterAdd { get; set; }

        /// <summary>
        /// Gets or sets the value indicating if edit action dialog should be closed after submiting.
        /// </summary>
        public bool CloseAfterEdit { get; set; }

        /// <summary>
        /// Gets or sets the value indicating if the user should confirm the changes uppon saving or cancel them.
        /// </summary>
        public bool CheckOnSubmit { get; set; }

        /// <summary>
        /// Gets or sets the value indicating if the user should be prompted when leaving unsaved changes.
        /// </summary>
        public bool CheckOnUpdate { get; set; }

        /// <summary>
        /// Gets or sets the value indicating if the form can be saved by pressing a key.
        /// </summary>
        public bool SaveKeyEnabled { get; set; }

        /// <summary>
        /// Gets or sets the key for saving.
        /// </summary>
        public char SaveKey { get; set; }

        /// <summary>
        /// Gets or sets the icon for the save button.
        /// </summary>
        public JqGridFormButtonIcon SaveButtonIcon { get; set; }

        /// <summary>
        /// Gets or sets the icon for the close button.
        /// </summary>
        public JqGridFormButtonIcon CloseButtonIcon { get; set; }

        /// <summary>
        /// Gets or sets the function for event which is raised after the data for the new row is loaded from the grid (if navigator buttons are enabled in edit mode).
        /// </summary>
        public string AfterClickPgButtons { get; set; }

        /// <summary>
        /// Gets or sets the function for event which is raised fires immediately after all actions and events are completed and the row is inserted or updated in the grid.
        /// </summary>
        public string AfterComplete { get; set; }

        /// <summary>
        /// Gets or sets the function for event which is raised before checking the values (if checking is defined in colModel via editrules option).
        /// </summary>
        public string BeforeCheckValues { get; set; }

        /// <summary>
        /// Gets or sets the function for event which is raised immediately after the previous or next button is clicked, before leaving the current row (if navigator buttons are enabled in edit mode).
        /// </summary>
        public string OnClickPgButtons { get; set; }

        /// <summary>
        /// Gets or sets the function for event which is raised only once when creating the form for editing and adding.
        /// </summary>
        public string OnInitializeForm { get; set; }
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes a new instance of the JqGridNavigatorEditActionOptions class.
        /// </summary>
        public JqGridNavigatorEditActionOptions()
        {
            Width = JqGridOptionsDefaults.Navigator.EditActionWidth;
            NavigationKeys = new JqGridFormKeyboardNavigation();
            ViewPagerButtons = JqGridOptionsDefaults.Navigator.ViewPagerButtons;
            RecreateForm = JqGridOptionsDefaults.Navigator.RecreateForm;
            AddedRowPosition = JqGridOptionsDefaults.Navigator.AddedRowPosition;
            ClearAfterAdd = JqGridOptionsDefaults.Navigator.ClearAfterAdd;
            CloseAfterAdd = JqGridOptionsDefaults.Navigator.CloseAfterAdd;
            CloseAfterEdit = JqGridOptionsDefaults.Navigator.CloseAfterEdit;
            CheckOnSubmit = JqGridOptionsDefaults.Navigator.CheckOnSubmit;
            CheckOnUpdate = JqGridOptionsDefaults.Navigator.CheckOnUpdate;
            TopInfo = String.Empty;
            BottomInfo = String.Empty;
            SaveKeyEnabled = JqGridOptionsDefaults.Navigator.SaveKeyEnabled;
            SaveKey = JqGridOptionsDefaults.Navigator.SaveKey;
            SaveButtonIcon = JqGridFormButtonIcon.SaveIcon;
            CloseButtonIcon = JqGridFormButtonIcon.CloseIcon;

            AfterClickPgButtons = null;
            AfterComplete = null;
            BeforeCheckValues = null;
            OnClickPgButtons = null;
            OnInitializeForm = null;
        }
        #endregion
    }
}


text:
package terrors

// SimpleError provides a simple type for type based error handling.
// This type can hold a message that is returned upon Error().
type SimpleError struct {
	Message string
}

func (s SimpleError) Error() string {
	return s.Message
}


text:
package bbejeck.nosql.antlr;

import bbejeck.nosql.antlr.generated.LuceneSqlLexer;
import bbejeck.nosql.antlr.generated.LuceneSqlParser;
import bbejeck.nosql.lucene.LuceneQueryListener;
import bbejeck.nosql.lucene.QueryParseResults;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.lucene.search.BooleanQuery;

import java.util.function.Function;
import java.util.function.Supplier;

/**
 * User: Bill Bejeck
 * Date: 10/14/14
 * Time: 10:10 PM
 */
public class LuceneQueryParser {

    private static Function<String, ANTLRInputStream> createAntlrInputStream = ANTLRInputStream::new;
    private static Function<ANTLRInputStream, LuceneSqlLexer> createLexer = LuceneSqlLexer::new;
    private static Function<LuceneSqlLexer, CommonTokenStream> createTokenStream = CommonTokenStream::new;
    private static Function<CommonTokenStream, LuceneSqlParser> createLuceneSqlParser = LuceneSqlParser::new;
    private static Function<LuceneSqlParser, LuceneSqlParser.QueryContext> createParseTree = LuceneSqlParser::query;
    private static Supplier<ParseTreeWalker> parseTreeWalkerSupplier = ParseTreeWalker::new;
    private static Supplier<LuceneQueryListener> luceneQueryListenerSupplier = LuceneQueryListener::new;

    private static Function<String, LuceneSqlParser> createParser = createAntlrInputStream.andThen(createLexer).andThen(createTokenStream).andThen(createLuceneSqlParser);

    private static Function<LuceneSqlParser, QueryParseResults> parse = parser -> {
        LuceneQueryListener listener = luceneQueryListenerSupplier.get();
        ParseTree parseTree = createParseTree.apply(parser);
        ParseTreeWalker walker = parseTreeWalkerSupplier.get();
        walker.walk(listener, parseTree);
        return listener.getParseResults();
    };

    public static QueryParseResults parseQuery(String query) {
        return parse.apply(createParser.apply(query));
    }

    public static BooleanQuery  parseToBooleanQuery(String query) {
        return parseQuery(query).getBooleanQuery();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ 版权所有:蒋才
  ~ (c) Copyright Cai Jiang
  ~ 2013-2017. All rights reserved.
  -->

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>goods</artifactId>
        <groupId>me.jiangcai.goods</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <packaging>war</packaging>
    <artifactId>demo-web</artifactId>
    <description>
        一个完整的web demo
        本身提供了一整套可运行程序,并且自己添加了一个插件
    </description>

    <properties>
        <maven.install.skip>true</maven.install.skip>
        <maven.deploy.skip>true</maven.deploy.skip>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>${javaee.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>me.jiangcai.goods</groupId>
            <artifactId>goods-core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>me.jiangcai.lib</groupId>
            <artifactId>spring</artifactId>
            <version>${jiangcai.version}</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.192</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>me.jiangcai.lib</groupId>
            <artifactId>test</artifactId>
            <version>${jiangcai.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/share/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
            <testResource>
                <directory>src/share_test/resources</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>1.9.1</version>
                <executions>
                    <execution>
                        <id>add-source</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>add-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>src/share/java</source>
                            </sources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>add-test-source</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>add-test-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>src/share_test/java</source>
                            </sources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "campo_composicion_quimica".
 *
 * @property integer $id
 * @property string $nombre_campo
 */
class CampoComposicionQuimica extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'campo_composicion_quimica';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nombre_campo'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'nombre_campo' => Yii::t('app', 'Nombre Campo'),
        ];
    }

    /**
     * @inheritdoc
     * @return CampoComposicionQuimicaQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new CampoComposicionQuimicaQuery(get_called_class());
    }
}


text:
/**************************************************************************/
/*!
    @file     uart_buf.c
    @author   Christopher Wang (Freaklabs)
              Modified by: K. Townsend (microBuilder.eu)
    @date     19 May 2010

    Original code taken from the FreakUSB Open Source USB Device Stack
    http://freaklabs.org/index.php/FreakUSB-Open-Source-USB-Device-Stack.html

    If it works well, you can thank Akiba at Freaklabs.  If it fails
    miserably, you can blame me (since parts of it it were rather
    ungraciously modified). :-)

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

#include "uart.h"

/**************************************************************************/
/*!
  Initialises the RX FIFO buffer
*/
/**************************************************************************/
void uartRxBufferInit()
{
  uart_pcb_t *pcb = uartGetPCB();
  pcb->rxfifo.len = 0;
}

/**************************************************************************/
/*!
  Read one byte out of the RX buffer. This function will return the byte
  located at the array index of the read pointer, and then increment the
  read pointer index.  If the read pointer exceeds the maximum buffer
  size, it will roll over to zero.
*/
/**************************************************************************/
uint8_t uartRxBufferRead()
{
  uart_pcb_t *pcb = uartGetPCB();
  uint8_t data;

  data = pcb->rxfifo.buf[pcb->rxfifo.rd_ptr];
  pcb->rxfifo.rd_ptr = (pcb->rxfifo.rd_ptr + 1) % CFG_UART_BUFSIZE;
  pcb->rxfifo.len--;
  return data;
}

/**************************************************************************/
/*!
  Read byte array from uart
 */
/**************************************************************************/
bool uartRxBufferReadArray(byte_t* rx, size_t* len)
{
  uart_pcb_t *pcb = uartGetPCB();
  *len = 0;

  while(pcb->rxfifo.len != 0)
  {
    (*rx) = uartRxBufferRead();
    (*len)++;
    rx++;
  }

  return (*len != 0);
}

/**************************************************************************/
/*!
  Write one byte into the RX buffer. This function will write one
  byte into the array index specified by the write pointer and increment
  the write index. If the write index exceeds the max buffer size, then it
  will roll over to zero.
*/
/**************************************************************************/
void uartRxBufferWrite(uint8_t data)
{
  uart_pcb_t *pcb = uartGetPCB();

  pcb->rxfifo.buf[pcb->rxfifo.wr_ptr] = data;
  pcb->rxfifo.wr_ptr = (pcb->rxfifo.wr_ptr + 1) % CFG_UART_BUFSIZE;
  pcb->rxfifo.len++;
}

/**************************************************************************/
/*!
    Clear the fifo read and write pointers and set the length to zero.
*/
/**************************************************************************/
void uartRxBufferClearFIFO()
{
  uart_pcb_t *pcb = uartGetPCB();

  pcb->rxfifo.rd_ptr = 0;
  pcb->rxfifo.wr_ptr = 0;
  pcb->rxfifo.len = 0;
}

/**************************************************************************/
/*!
    Check whether there is any data pending on the RX buffer.
*/
/**************************************************************************/
uint8_t uartRxBufferDataPending()
{
  uart_pcb_t *pcb = uartGetPCB();

  if (pcb->rxfifo.len != 0)
  {
    return 1;
  }

  return 0;
}


text:
/* @flow */
const RESET_ERROR = 'RESET_ERROR';

export type TAction = { type: string, payload: any, error: any };
export type TState = { error: Object };

const resetError = () => ({ type: RESET_ERROR, payload: null });

const initialState = {
  error: null,
};

function errorReducer(state: TState = initialState, action: TAction): TState {
  const { type, error } = action;
  if (type === RESET_ERROR) {
    return { error: null };
  } else if (error) {
    return action.payload;
  }
  return state;
}

export { resetError };
export default errorReducer;


text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide source control management (versioning) information.
//
//@CLASSES:
// bdlscm::Version: namespace for RCS and SCCS versioning information for 'bdl'
//
//@DESCRIPTION: This component provides source control management (versioning)
// information for the 'bdl' package group.  In particular, this component
// embeds RCS-style and SCCS-style version strings in binary executable files
// that use one or more components from the 'bdl' package group.  This version
// information may be extracted from binary files using common UNIX utilities
// (e.g., 'ident' and 'what').  In addition, the 'version' 'static' member
// function in the 'bdlscm::Version' 'struct' can be used to query version
// information for the 'bdl' package group at runtime.  The following usage
// examples illustrate these two basic capabilities.
//
// Note that unless the 'version' method will be called, it is not necessary to
// '#include' this component header file to get 'bdl' version information
// embedded in an executable.  It is only necessary to use one or more 'bdl'
// components (and, hence, link in the 'bdl' library).
//
///Usage
///-----
// A program can display the version of BDL that was used to build it by
// printing the version string returned by 'bdlscm::Version::version()' to
// 'stdout' as follows:
//..
//  bsl::printf("BDL version: %s\n", bdlscm::Version::version());
//..

#ifndef INCLUDED_BSLSCM_VERSION
#include <bslscm_version.h>
#endif

#ifndef INCLUDED_BDLSCM_VERSIONTAG
#include <bdlscm_versiontag.h>     // 'BDL_VERSION_MAJOR', 'BDL_VERSION_MINOR'
#endif

#ifndef INCLUDED_BSLS_LINKCOERCION
#include <bsls_linkcoercion.h>
#endif

#ifndef INCLUDED_BSLS_PLATFORM
#include <bsls_platform.h>
#endif

namespace BloombergLP {
namespace bdlscm {

struct Version {
    static const char *s_ident;
    static const char *s_what;

#define BDLSCM_CONCAT2(a,b,c,d,e) a ## b ## c ## d ## e
#define BDLSCM_CONCAT(a,b,c,d,e)  BDLSCM_CONCAT2(a,b,c,d,e)

// 'BDLSCM_D_VERSION' is a symbol whose name warns users of version mismatch
// linking errors.  Note that the exact string "compiled_this_object" must be
// present in this version coercion symbol.  Tools may look for this pattern to
// warn users of mismatches.
#define BDLSCM_D_VERSION BDLSCM_CONCAT(                \
                       d_version_BDL_,                 \
                       BDL_VERSION_MAJOR,              \
                       _,                              \
                       BDL_VERSION_MINOR,              \
                       _compiled_this_object)

    static const char *BDLSCM_S_VERSION;

    static const char *s_dependencies;
    static const char *s_buildInfo;
    static const char *s_timestamp;
    static const char *s_sourceControlInfo;

    static const char *version();
};

inline
const char *Version::version()
{
    return BDLSCM_S_VERSION;
}

}  // close package namespace

BSLS_LINKCOERCION_FORCE_SYMBOL_DEPENDENCY(const char *,
                                          bdlscm_version_assertion,
                                          bdlscm::Version::BDLSCM_S_VERSION);

}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2012 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
const PlotCard = require('../../plotcard.js');

class Duel extends PlotCard {
    setupCardAbilities() {
        this.whenRevealed({
            chooseOpponent: true,
            handler: context => {
                let opponent = context.opponent;

                if(this.notEnoughTargets()) {
                    return;
                }

                this.game.addMessage('{0} uses {1} to have {2} choose 2 non-Army characters with printed cost 6 or higher',
                    this.controller, this, opponent);

                this.game.promptForSelect(opponent, {
                    mode: 'exactly',
                    numCards: 2,
                    activePromptTitle: 'Select two characters',
                    source: this,
                    cardCondition: card => (
                        card.location === 'play area' &&
                        !card.hasTrait('Army') &&
                        card.getType() === 'character' &&
                        card.getPrintedCost() >= 6),
                    onSelect: (player, cards) => this.targetsSelected(player, cards)
                });
            }
        });
    }

    targetsSelected(player, cards) {
        this.targets = cards;
        this.game.addMessage('{0} chooses {1} as the targets for {2}', player, cards, this);

        this.game.promptWithMenu(player, this, {
            activePrompt: {
                menuTitle: 'Choose character to kneel',
                buttons: [
                    { card: cards[0], method: 'resolve', arg: [0,1]},
                    { card: cards[1], method: 'resolve', arg: [1,0]},
                    { text: 'Cancel', method: 'cancel'}
                ]
            },
            source: this
        });

        return true;
    }

    resolve(player, index) {
        player.kneelCard(this.targets[index[0]]);
        this.game.killCharacter(this.targets[index[1]], { allowSave: false });

        this.game.addMessage('{0} then chooses {1} to kneel, {2} is killed', player, this.targets[index[0]], this.targets[index[1]]);

        return true;
    }

    cancel(player) {
        this.game.addMessage('{0} cancels the resolution of {1}', player, this);

        return true;
    }

    notEnoughTargets() {
        let targets = this.game.filterCardsInPlay(card => !card.hasTrait('Army') && card.getType() === 'character' && card.getPrintedCost() >= 6);
        return targets.length <= 1;
    }
}

Duel.code = '06060';

module.exports = Duel;


text:
<?php

namespace Wedeto\DB;

use PHPUnit\Framework\TestCase;

use Wedeto\DB\Driver;
use Wedeto\DB\Schema;
use Wedeto\DB\Query;

use Wedeto\DB\Exception\TableNotExistsException;
use Wedeto\DB\Exception\MigrationException;
use Wedeto\DB\Exception\NoMigrationTableException;
use Wedeto\DB\Exception\DriverException;
use Wedeto\DB\Exception\ConfigurationException;
use Wedeto\DB\Exception\DAOException;
use Wedeto\DB\Exception\IOException;
use Wedeto\DB\Model\DBVersion;

use Wedeto\Util\Validation\Type;
use Wedeto\Util\DI\DI;
use Wedeto\Util\DI\BasicFactory;
use Wedeto\Util\Configuration;

use Prophecy\Argument;

/**
 * @covers Wedeto\DB\DB
 */
class DBTest extends TestCase
{
    private $config;

    public function setUp()
    {
        $config = new Configuration();
        $config->setType('sql', Type::ARRAY);

        $config->set('sql', 'default', 'lazy', false);
        $config->set('sql', 'default', 'username', 'foo');
        $config->set('sql', 'default', 'password', 'bar');
        $config->set('sql', 'default', 'hostname', 'localhost');
        $config->set('sql', 'default', 'database', 'foobardb');
        $config->set('sql', 'default', 'type', 'MySQL');

        $this->config = new DBConfig($config);
    }

    public function testConstruction()
    {
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) {
            return new MockPDO($args['dsn'], $args['username'], $args['passwd']);
        }));

        $db = new DB($this->config);
        $pdo = $db->getPDO();
        $this->assertInstanceOf(MockPDO::class, $pdo);

        $args = $pdo->args;
        $this->assertEquals('mysql:host=localhost;dbname=foobardb;charset=utf8', $args[0]);
        $this->assertEquals('foo', $args[1]);
        $this->assertEquals('bar', $args[2]);

        $di = $db->__debuginfo();
        $this->assertTrue(isset($di['dsn']), "DSN should be set");
        $this->assertTrue(isset($di['driver']), "Driver should be set");
    }

    public function testGetPDOWithLazyLoading()
    {
        $this->config->set('lazy', true);
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) {
            return new MockPDO($args['dsn'], $args['username'], $args['passwd']);
        }));

        $db = new DB($this->config);
        $pdo = $db->getPDO();
        $this->assertInstanceOf(MockPDO::class, $pdo);

        $args = $pdo->args;
        $this->assertEquals('mysql:host=localhost;dbname=foobardb;charset=utf8', $args[0]);
        $this->assertEquals('foo', $args[1]);
        $this->assertEquals('bar', $args[2]);
    }

    public function testGetDriverWithLazyLoading()
    {
        $this->config->set('lazy', true);
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) {
            return new MockPDO($args['dsn'], $args['username'], $args['passwd']);
        }));

        $db = new DB($this->config);

        $driver = $db->getDriver();
        $this->assertInstanceOf(Driver\Driver::class, $driver);
    }

    public function testConstructionWithSubclassedPGSQL()
    {
        $this->config->set('type', MockDriver::class);
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) {
            return new MockPDO($args['dsn'], $args['username'], $args['passwd']);
        }));

        $db = new DB($this->config);

        $pdo = $db->getPDO();
        $this->assertInstanceOf(MockPDO::class, $pdo);

        $args = $pdo->args;
        $this->assertEquals('pgsql:host=localhost;dbname=foobardb', $args[0]);
        $this->assertEquals('foo', $args[1]);
        $this->assertEquals('bar', $args[2]);
    }

    public function testConstructionWithNonExistingDriver()
    {
        $this->config->set('type', 'Wedeto\\DB\\Non\\Existing\\Driver');
        $this->expectException(DriverException::class);
        $this->expectExceptionMessage("No driver available for database type");
        $db = new DB($this->config);
    }

    public function testConstructionWithNoDriver()
    {
        unset($this->config['type']);
        $this->expectException(ConfigurationException::class);
        $this->expectExceptionMessage("Please specify the database type in the configuration section [sql]");
        $db = new DB($this->config);
    }

    public function testDBDelegatesToPDO()
    {
        $this->config->set('lazy', true);
        $pdo_mocker = $this->prophesize(\PDO::class);
        $pdo = $pdo_mocker->reveal();
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) use ($pdo) {
            return $pdo;
        }));

        $this->config->set('type', 'MySQL');
        $db = new DB($this->config);

        $this->assertSame($pdo, $db->getPDO());
        $pdo = $db->getPDO();

        $pdo_mocker->beginTransaction()->shouldBeCalledTimes(1);
        $db->beginTransaction();

        $pdo_mocker->commit()->shouldBeCalledTimes(1);
        $db->commit();

        $pdo_mocker->rollBack()->shouldBeCalledTimes(1);
        $db->rollBack();

        $pdo_mocker->exec("Foo")->shouldBeCalled();
        $db->exec("Foo");

        $pdo_mocker->prepare("BAR")->shouldBeCalled();
        $db->prepare("BAR");

        $pdo_mocker->setAttribute(Argument::type('int'), Argument::type('int'))->shouldBeCalledTimes(4);
        $db = new DB($this->config);
        $pdo_mocker->quote("FOOBAR")->shouldBeCalled();
        $db->quote("FOOBAR");

        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage("Function nonExisting does not exist");
        $db->nonExisting("FUNC");
    }

    public function testGetSchemaReturnsSchema()
    {
        $pdo_mocker = $this->prophesize(\PDO::class);
        $pdo = $pdo_mocker->reveal();
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) use ($pdo) {
            return $pdo;
        }));
        $db = new DB($this->config);

        $schema_mocker = $this->prophesize(Schema\Schema::class);
        $schema_mock = $schema_mocker->reveal();

        $received_args = [];
        DI::getInjector()->registerFactory(
            Schema\Schema::class,
            new BasicFactory(function (array $args) use ($schema_mock, &$received_args) {
                foreach ($args as $k => $v)
                    $received_args[$k] = $v;
                return $schema_mock;
            })
        );

        $schema = $db->getSchema();
        $this->assertSame($schema_mock,$schema);
        $expectedName = "MySQL_localhost_foobardb_foobardb";
        $this->assertEquals($expectedName, $received_args['schema_name']);
    }

    public function testGetDAOReturnsProperDAO()
    {
        $pdo_mocker = $this->prophesize(\PDO::class);
        $pdo = $pdo_mocker->reveal();
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) use ($pdo) {
            return $pdo;
        }));

        $db = new DB($this->config);
        $dao = $db->getDAO(DBVersion::class);
        $this->assertInstanceOf(DAO::class, $dao, "A DAO instance should be returned");
        $this->assertEquals(DBVersion::getTablename(), $dao->getTablename(), "The table name should match");

        $dao2 = $db->getDAO(MockModel::class);
        $this->assertNotSame($dao, $dao2, "A different DAO should be returned for a different Model");
        $this->assertInstanceOf(DAO::class, $dao2, "A DAO instance should be returned");
        $this->assertEquals(MockModel::getTablename(), $dao2->getTablename(), "The table name should match");

        $db->setDAO(MockModel::class, $dao);
        $dao3 = $db->getDAO(MockModel::class);
        $this->assertSame($dao, $dao3, "The overridden DAO should be returned");

        $dao4 = $db->getDAO(MockModel::class);
        $this->assertSame($dao3, $dao4, "The same overridden DAO should be returned again");
    }

    public function testGetDAOWithInvalidClass()
    {
        $pdo_mocker = $this->prophesize(\PDO::class);
        $pdo = $pdo_mocker->reveal();
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) use ($pdo) {
            return $pdo;
        }));
        $db = new DB($this->config);

        $this->expectException(DAOException::class);
        $this->expectExceptionMessage("is not a valid Model");
        $dao = $db->getDAO(\Stdclass::class);
    }

    public function testSetDAOWithInvalidClass()
    {
        $pdo_mocker = $this->prophesize(\PDO::class);
        $pdo = $pdo_mocker->reveal();
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) use ($pdo) {
            return $pdo;
        }));
        $db = new DB($this->config);

        $dao_mocker = $this->prophesize(DAO::class);
        $dao = $dao_mocker->reveal();

        $this->expectException(DAOException::class);
        $this->expectExceptionMessage("is not a valid Model");
        $dao = $db->setDAO(\Stdclass::class, $dao);
    }

    public function testPrepareQuery()
    {
        $this->config->set('lazy', true);
        $pdo_mocker = $this->prophesize(\PDO::class);
        $pdo_mocker->setAttribute(3, 2)->shouldBeCalledTimes(1);
        $pdo_mocker->setAttribute(19, 2)->shouldBeCalledTimes(1);
        $pdo = $pdo_mocker->reveal();
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) use ($pdo) {
            return $pdo;
        }));
        $db = new DB($this->config);

        $drv_mocker = $this->prophesize(Driver\PGSQL::class);
        $drv = $drv_mocker->reveal();

        DI::getInjector()->registerFactory(Driver\PGSQL::class, new BasicFactory(function (array $args) use ($drv) {
            echo "BUILDING PGSQL\n";
            return $drv;
        }));

        $st_mocker = $this->prophesize(\PDOStatement::class);
        $st = $st_mocker->reveal();

        $pdo_mocker->prepare(Argument::any())->willReturn($st);

        $query_mocker = $this->prophesize(Query\Query::class);
        $statement = $db->prepareQuery($query_mocker->reveal());

        $this->assertSame($st, $statement);
    }

    public function testExecuteSQL()
    {
        $this->config->set('lazy', false);
        $pdo_mocker = $this->prophesize(\PDO::class);
        $pdo = $pdo_mocker->reveal();
        DI::getInjector()->registerFactory(\PDO::class, new BasicFactory(function (array $args) use ($pdo) {
            return $pdo;
        }));
        $db = new DB($this->config);

        $db->getDriver()->setTablePrefix("WDIFB");
        $pdo_mocker->exec("SELECT * FROM foo;")->shouldBeCalledTimes(1);
        $pdo_mocker->exec("DROP TABLE foo;")->shouldBeCalledTimes(1);
        $pdo_mocker->exec("CREATE TABLE WDIFBtab (id integer primary key auto_increment, varchar(32) foo);")->shouldBeCalledTimes(1);

        $file = __DIR__ . DIRECTORY_SEPARATOR . '/testStatements.sql';
        $db->executeSQL($file);

        $file = __DIR__ . DIRECTORY_SEPARATOR . '/nonExistingTestStatements.sql';

        $this->expectException(IOException::class);
        $this->expectExceptionMessage("Unable to open file '$file'");
        $db->executeSQL($file);
    }
}

class MockPDO extends \PDO
{
    public $args;

    public function __construct($dsn, $username, $passwd)
    {
        $this->args = func_get_args();
    }

    public function setAttribute($attrib, $value)
    { }
}

class MockDriver extends Driver\PGSQL
{ }

class MockModel extends Model
{
    protected static $_table = "foobar";
}


text:
<?php

class DatabaseActions {
    protected $cfg;
    protected $db;
    protected $pwHasher;

    /**
     * DatabaseActions constructor.
     * @param DatabaseConnection $db
     * @param array $cfg
     */
    public function __construct($cfg) {
        $this->cfg = $cfg;
        $this->db = new DatabaseConnection(
            $cfg['db_type'],
            $cfg['db_host'],
            $cfg['db_port'],
            $cfg['db_user'],
            $cfg['db_password'],
            $cfg['db_database']
        );
        $this->pwHasher = new PasswordHasher($cfg['db_passwordHashMethod']);
    }

    private function getConnection() {
        return $this->db->connect();
    }

    public function getUserEmail($username) {
        try {
            if ($this->cfg['db_useDBFunctions'] === true) {
                return $this->getUserEmailViaFunction($username);
            }
            return $this->getUserEmailDirectly($username);
        } catch (\Exception $e) {
            Logger::getInstance()->logDatabaseError($e->getMessage());
            throw $e;
        }
    }

    private function getUserEmailDirectly($username) {
        if (!(self::stringHasValue($this->cfg['db_userTable'])
            && self::stringHasValue($this->cfg['db_emailColumn'])
            && self::stringHasValue($this->cfg['db_usernameColumn'])
        )) {
            throw new Exception('Missing database configuration: user table & columns');
        }

        $stmt = $this->getConnection()->createQueryBuilder()
            ->select($this->cfg['db_emailColumn'])
            ->from($this->cfg['db_userTable']);
        if ($this->isEmailUsername()) {
            $stmt = $stmt->where('LOWER(' . $this->cfg['db_usernameColumn'] . ') = LOWER(?)');
        } else {
            $stmt = $stmt->where($this->cfg['db_usernameColumn'] . ' = ?');
        }
        $stmt = $stmt->setParameter(0, $username)
            ->execute();
        $email = $stmt->fetchColumn();

        return $email;
    }

    private function getUserEmailViaFunction($username) {
        if (!self::stringHasValue($this->cfg['db_getUserEmailFunction'])) {
            throw new Exception('Missing database configuration: db_getUserEmailFunction');
        }

        $sql = 'SELECT ' . $this->cfg['db_getUserEmailFunction'] . '(:username)';
        $sql = $this->addDualIfOracle($sql);
        $stmt = $this->getConnection()->executeQuery(
            $sql, array('username' => $username), array(PDO::PARAM_STR));

        $email = $stmt->fetchColumn();
        return $email;
    }

    public function authenticateUser($username, $password) {
        try {
            if ($this->cfg['db_useDBFunctions'] === true) {
                return $this->authenticateUserViaFunction($username, $password);
            }
            return $this->authenticateUserDirectly($username, $password);
        } catch (\Exception $e) {
            Logger::getInstance()->logDatabaseError($e->getMessage());
            throw $e;
        }
    }

    private function authenticateUserDirectly($username, $password) {
        if (!(self::stringHasValue($this->cfg['db_userTable'])
            && self::stringHasValue($this->cfg['db_passwordColumn'])
            && self::stringHasValue($this->cfg['db_usernameColumn'])
        )) {
            throw new Exception('Missing database configuration: user table & columns');
        }

        $stmt = $this->getConnection()->createQueryBuilder()
            ->select($this->cfg['db_passwordColumn'])
            ->from($this->cfg['db_userTable']);
        if ($this->isEmailUsername()) {
            $stmt = $stmt->where('LOWER(' . $this->cfg['db_usernameColumn'] . ') = LOWER(?)');
        } else {
            $stmt = $stmt->where($this->cfg['db_usernameColumn'] . ' = ?');
        }
        $stmt = $stmt->setParameter(0, $username)
            ->execute();
        $hash = $stmt->fetchColumn();

        return $this->pwHasher->checkPassword($password, $hash);
    }

    private function authenticateUserViaFunction($username, $password) {
        $hashInDB = $this->cfg['db_doPasswordHashingInDatabaseForFunctions'] === true;

        if ($hashInDB && !self::stringHasValue($this->cfg['db_userAuthenticateFunction'])) {
            throw new Exception('Missing database configuration: db_userAuthenticateFunction');
        } else if (!$hashInDB && !self::stringHasValue($this->cfg['db_getUserPasswordHashFunction'])) {
            throw new Exception('Missing database configuration: db_getUserPasswordHashFunction');
        }

        $result = false;

        if ($hashInDB) {
            $sql = 'SELECT ' . $this->cfg['db_userAuthenticateFunction'] . '(:username, :password)';
            $sql = $this->addDualIfOracle($sql);
            $stmt = $this->getConnection()->executeQuery(
                $sql, array(
                    'username' => $username,
                    'password' => $password
                ), array(
                    'username' => PDO::PARAM_STR,
                    'password' => PDO::PARAM_STR
                ));
            $result = $stmt->fetchColumn();
        } else {
            $sql = 'SELECT ' . $this->cfg['db_getUserPasswordHashFunction'] . '(:username)';
            $sql = $this->addDualIfOracle($sql);
            $stmt = $this->getConnection()->executeQuery(
                $sql, array(
                    'username' => $username
                ), array(
                    'username' => PDO::PARAM_STR
                ));
            $pwHash = $stmt->fetchColumn();
            if (!empty($pwHash)) {
                $result = $this->pwHasher->checkPassword($password, $pwHash);
            }
        }

        return $result;
    }

    public function changeUserPassword($username, $newPassword) {
        try {
            if ($this->cfg['db_useDBFunctions'] === true) {
                return $this->changeUserPasswordViaFunction($username, $newPassword);
            }
            return $this->changeUserPasswordDirectly($username, $newPassword);
        } catch (\Exception $e) {
            Logger::getInstance()->logDatabaseError($e->getMessage());
            throw $e;
        }
    }

    private function changeUserPasswordDirectly($username, $newPassword) {
        if (!(self::stringHasValue($this->cfg['db_userTable'])
                && self::stringHasValue($this->cfg['db_passwordColumn'])
                && self::stringHasValue($this->cfg['db_usernameColumn'])
            )) {
            throw new Exception('Missing database configuration: user table & columns');
        }

        $newHash = $this->pwHasher->hashPassword($newPassword);

        $stmt = $this->getConnection()->createQueryBuilder()
            ->update($this->cfg['db_userTable'])
            ->set($this->cfg['db_passwordColumn'], ':newHash');
        if ($this->isEmailUsername()) {
            $stmt = $stmt->where('LOWER(' . $this->cfg['db_usernameColumn'] . ') = LOWER(:username)');
        } else {
            $stmt = $stmt->where($this->cfg['db_usernameColumn'] . ' = :username');
        }
        $affectedRows = $stmt->setParameter('newHash', $newHash)
            ->setParameter('username', $username)
            ->execute();

        return $affectedRows > 0;
    }

    private function changeUserPasswordViaFunction($username, $newPassword) {
        if (!self::stringHasValue($this->cfg['db_changePasswordFunction'])) {
            throw new Exception('Missing database configuration: db_changePasswordFunction');
        }

        if ($this->cfg['db_doPasswordHashingInDatabaseForFunctions'] === false) {
            $newPassword = $this->pwHasher->hashPassword($newPassword);
        }

        $sql = 'SELECT ' . $this->cfg['db_changePasswordFunction'] . '(:username, :password)';
        $sql = $this->addDualIfOracle($sql);
        $stmt = $this->getConnection()->executeQuery(
            $sql, array(
                'username' => $username,
                'password' => $newPassword
            ), array(
                'username' => PDO::PARAM_STR,
                'password' => PDO::PARAM_STR
            ));
        $stmt->fetchColumn();

        return true;
    }

    public function raisePasswordChangedEvent($username) {
        try {
            if (!self::stringHasValue($this->cfg['db_passwordChangedEventFunction'])) {
                return;
            }

            $sql = 'SELECT ' . $this->cfg['db_passwordChangedEventFunction'] . '(:username)';
            $sql = $this->addDualIfOracle($sql);
            $this->getConnection()->executeQuery(
                $sql, array(
                    'username' => $username
                ), array(
                    'username' => PDO::PARAM_STR
                ));
        } catch (\Exception $e) {
            Logger::getInstance()->logDatabaseError($e->getMessage());
            throw $e;
        }
    }

    private function addDualIfOracle($sql) {
        if ($this->cfg['db_type'] === 'oracle') {
            return $sql . ' FROM DUAL';
        }
        return $sql;
    }

    private static function stringHasValue($str) {
        return !($str === null || !strlen(trim($str)));
    }

    private function isEmailUsername() {
        return $this->cfg['db_usernameColumn'] === $this->cfg['db_emailColumn'];
    }
}


text:
package erepnikov.storage;

import erepnikov.interfaces.Storage;
import erepnikov.jdbc.JdbcUtil;
import erepnikov.models.User;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Class JdbcStorage.
 *
 * @author Egor Repnikov
 * @version 0.0.1
 * @since 26.10.2017
 */
public class JdbcStorage implements Storage {

    /**
     * JdbcUtil for calling db.
     */
    private final JdbcUtil jdbcUtil;

    /**
     * Inits jdbcUtil and check db.
     *
     * @param jdbcUtil JdbcUtil
     */
    public JdbcStorage(final JdbcUtil jdbcUtil) {
        this.jdbcUtil = jdbcUtil;
        this.checkDB();
    }

    /**
     * Checks table in db.
     */
    private void checkDB() {
        try (Statement statement = this.jdbcUtil.getConnection().createStatement()) {
            statement.execute(
                    "create table if not exists users (id integer unique, name varchar (255));"
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Add Users to Storage.
     *
     * @param user User
     */
    @Override
    public void add(User user) {
        try (PreparedStatement ps = this.jdbcUtil.getConnection().prepareStatement(
                "insert into users (id, name) values (?, ?)"
        )) {
            ps.setInt(1, user.getId());
            ps.setString(2, user.getName());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Update User in Storage.
     *
     * @param user User
     */
    @Override
    public void update(User user) {
        try (PreparedStatement ps = this.jdbcUtil.getConnection().prepareStatement(
                "update users set name = ? where id = ?"
        )) {
            ps.setString(1, user.getName());
            ps.setInt(2, user.getId());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Delete User from Storage.
     *
     * @param user User
     */
    @Override
    public void delete(User user) {
        try (PreparedStatement ps = this.jdbcUtil.getConnection().prepareStatement(
                "delete from users where id = ?"
        )) {
            ps.setInt(1, user.getId());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Getter of User of Storage.
     *
     * @param id int
     * @return List of Users
     */
    @Override
    public User get(int id) {
        User user = null;
        try (PreparedStatement ps = this.jdbcUtil.getConnection().prepareStatement(
                "select * from users where id = ?"
        )) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setName(rs.getString("name"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * Getter of All Users in List.
     *
     * @return List of Users
     */
    @Override
    public List<User> getAll() {
        List<User> result = new ArrayList<>();
        try (Statement statement = this.jdbcUtil.getConnection().createStatement();
             ResultSet rs = statement.executeQuery("select * from users")) {
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                result.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}


text:
package cz.cuni.mff.d3s.perf;

import java.io.PrintStream;

public class BenchmarkResultsPrinter {
	public static void toCsv(BenchmarkResults results, PrintStream stream) {
		toCsv(results, stream, "\t", true);
	}

	public static void toCsv(BenchmarkResults results, PrintStream stream, String separator, boolean printHeader) {
		if (printHeader) {
			String[] eventNames = results.getEventNames();
			for (int i = 0; i < eventNames.length; i++) {
				if (i > 0) {
					stream.append(separator);
				}
				stream.append(eventNames[i]);
			}
			stream.append("\n");
		}

		for (long[] row : results.getData()) {
			for (int i = 0; i < row.length; i++) {
				if (i > 0) {
					stream.append(separator);
				}
				stream.append(String.format("%d", row[i]));
			}
			stream.append("\n");
		}
	}

	public static void table(BenchmarkResults results, PrintStream stream) {
		table(results, stream, 15, true);
	}

	public static void table(BenchmarkResults results, PrintStream stream, int columnWidth, boolean printHeader) {
		if (printHeader) {
			String format = String.format("%%%ds", columnWidth);
			for (String name : results.getEventNames()) {
				String nameBeginning = name.substring(0, Math.min(name.length(), columnWidth - 1));
				stream.append(String.format(format, nameBeginning));
			}
			stream.append("\n");
		}

		String format = String.format("%%%dd", columnWidth);
		for (long[] row : results.getData()) {
			for (long r : row) {
				stream.append(String.format(format, r));
			}
			stream.append("\n");
		}
	}

}


text:
package org.wikipedia.dataclient.okhttp;

import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;

import com.github.kevinsawicki.http.HttpRequest;

import org.wikipedia.WikipediaApp;
import org.wikipedia.dataclient.SharedPreferenceCookieManager;
import org.wikipedia.settings.Prefs;
import org.wikipedia.settings.RbSwitch;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

import okhttp3.Cache;
import okhttp3.CacheDelegate;
import okhttp3.CookieJar;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.OkUrlFactory;
import okhttp3.internal.cache.CacheDelegateInterceptor;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpConnectionFactory implements HttpRequest.ConnectionFactory {
    private static final String CACHE_DIR_NAME = "okhttp-cache";
    private static final long NET_CACHE_SIZE = 64 * 1024 * 1024;
    @VisibleForTesting @NonNull public static final Cache NET_CACHE = new Cache(new File(WikipediaApp.getInstance().getCacheDir(),
            CACHE_DIR_NAME), NET_CACHE_SIZE);
    private static final long SAVED_PAGE_CACHE_SIZE = NET_CACHE_SIZE * 1024;
    @NonNull public static final Cache SAVE_CACHE = new Cache(new File(WikipediaApp.getInstance().getFilesDir(),
            CACHE_DIR_NAME), SAVED_PAGE_CACHE_SIZE);

    @NonNull private static final OkHttpClient CLIENT = createClient();

    @NonNull public static OkHttpClient getClient() {
        return CLIENT;
    }

    @Override
    public HttpURLConnection create(URL url) throws IOException {
        return new OkUrlFactory(getClient()).open(url); // TODO: update to newer API
    }

    @Override
    public HttpURLConnection create(URL url, Proxy proxy) throws IOException {
        throw new UnsupportedOperationException(
                "Per-connection proxy is not supported. Use OkHttpClient's setProxy instead.");
    }

    @NonNull
    private static OkHttpClient createClient() {
        SharedPreferenceCookieManager cookieManager = WikipediaApp.getInstance().getCookieManager();
        // TODO: consider using okhttp3.CookieJar implementation instead of JavaNetCookieJar wrapper
        CookieJar cookieJar = new JavaNetCookieJar(cookieManager);

        return new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .cache(NET_CACHE)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(Prefs.getRetrofitLogLevel()))
                .addInterceptor(new UnsuccessfulResponseInterceptor())
                .addInterceptor(new StatusResponseInterceptor(RbSwitch.INSTANCE))
                .addNetworkInterceptor(new StripMustRevalidateResponseInterceptor())
                .addInterceptor(new CommonHeaderRequestInterceptor())
                .addInterceptor(new DefaultMaxStaleRequestInterceptor())
                .addInterceptor(new CacheIfErrorInterceptor())
                .addInterceptor(new CacheDelegateInterceptor(CacheDelegate.internalCache(SAVE_CACHE), CacheDelegate.internalCache(NET_CACHE)))
                .addInterceptor(new WikipediaZeroResponseInterceptor(WikipediaApp.getInstance().getWikipediaZeroHandler()))
                .build();
    }
}


text:
namespace OmmitedDatabaseModel3;

public class Entity13 : BaseEntity
{
    public Guid Entity17Id { get; set; }
    public Entity17 Entity17 { get; set; }
    public Guid Entity8Id { get; set; }
    public Entity8 Entity8 { get; set; }
}


text:
        <?php
        if (has_nav_menu('primary_navigation')) :
          wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav']);
        endif;
        ?>

  <img src="<?php echo bloginfo('template_url'); ?>/dist/images/home__masshead_bg_2.png" class="img-fluid" />
  <a class="brand" href="<?= esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?>


text:
.DOTFILES
========

## My Dotfiles ( the secret sauce )

 Just clone and then run linker.sh to softlink all the dotfiles(you may want to backup your existing ones).


text: Imagens docker para iniciar projetos


text:
namespace JoinProto.Areas.HelpPage
{
    /// <summary>
    /// Indicates whether the sample is used for request or response
    /// </summary>
    public enum SampleDirection
    {
        Request = 0,
        Response
    }
}


text:
package nom.bdezonia.zorbage.storage.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import nom.bdezonia.zorbage.tuple.Tuple2;
import nom.bdezonia.zorbage.algebra.Allocatable;
import nom.bdezonia.zorbage.algebra.StorageConstruction;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
import nom.bdezonia.zorbage.storage.coder.StringCoder;

/**
 *
 * @author Barry DeZonia
 *
 */
public class JdbcStorageString<U extends StringCoder & Allocatable<U>>
	extends AbstractJdbcStorage<U>
	implements IndexedDataSource<U>, Allocatable<JdbcStorageString<U>>
{
	// string passed to createTable based on info from:
	//   https://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html

	public JdbcStorageString(Connection conn, U type, long size) {
		super(size, type, conn);
		createTable(conn, tableName, "VARCHAR(256)", type.stringCount());
		zeroFill(type.stringCount());
	}

	public JdbcStorageString(JdbcStorageString<U> other) {
		super(other.size, other.type, other.conn);
		createTable(conn, tableName, "VARCHAR(256)", type.stringCount());
		copyTableToTable(conn, other.tableName, tableName);
	}

	@Override
	public JdbcStorageString<U> duplicate() {
		return new JdbcStorageString<U>(this);
	}

	@Override
	public void set(long index, U value) {
		if (index < 0 || index >= size)
			throw new IllegalArgumentException("index out of bounds");
		String[] arr = tmpSpace.get();
		value.toStringArray(arr, 0);
		String sql = setHelper(index, arr.length);
		try {
			PreparedStatement statement = conn.prepareStatement(sql);
			for (int i = 0; i < arr.length; i++) {
				statement.setString(i+1, arr[i]);
			}
			statement.executeUpdate();
			statement.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
	}

	@Override
	public void get(long index, U value) {
		if (index < 0 || index >= size)
			throw new IllegalArgumentException("index out of bounds");
		Tuple2<Statement,ResultSet> result = getHelper(index, type.stringCount());
		String[] arr = tmpSpace.get();
		try {
			result.b().next();
			for (int i = 0; i < arr.length; i++) {
				arr[i] = result.b().getString(i+1);
			}
			value.fromStringArray(arr, 0);
			result.a().close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
	}

	// Thread local variable containing each thread's temp array
	private final ThreadLocal<String[]> tmpSpace =
		new ThreadLocal<String[]>() {
			@Override protected String[] initialValue() {
				return new String[type.stringCount()];
			}
		};

	@Override
	public JdbcStorageString<U> allocate() {
		return new JdbcStorageString<U>(conn, type, size());
	}

	@Override
	public StorageConstruction storageType() {
		// There is no exact match for our type. But if someone has a large JDBC backed structure
		// that we want to derive an allocation from then a VIRTUAL structure might be best. This
		// return value reflects that idea and kind of generalizes the idea of how the data is
		// stored in actuality.
		return StorageConstruction.MEM_VIRTUAL;
	}

	@Override
	String zeroValueAsString() {
		return "''";  // unlike char we will not use a space here. maybe that is a mistake.
	}

	@Override
	public boolean accessWithOneThread() {
		return false;
	}
}


text:
define([ "GenomeFactory" ], function(GenomeFactory)
{
    "use strict";
    QUnit.module("GenomeFactory");

    QUnit.test("create()", function(assert)
    {
        // Setup.
        var genes = [ "a", "b", "c", "d", "e" ];
        var genomeLength = 3;
        var factory = new GenomeFactory(genes, genomeLength);

        // Run.
        var result = factory.create();

        // Verify.
        assert.ok(result);
        LOGGER.debug("result = " + result);
        assert.equal(result.length, genomeLength);
    });
});


text:
// stdafx.h : include file for standard system include files,
//  or project specific include files that are used frequently, but
//      are changed infrequently
//

#ifndef _DG_PHYSICS_STDAFX_H__
#define _DG_PHYSICS_STDAFX_H__

#ifndef WIN32_LEAN_AND_MEAN
#	define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers
#endif

#include <dg.h>

//#define DG_PROFILE_PHYSICS

#endif


text:
package com.sibvisions.rad.ui.javafx.ext.panes;

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class FXFluidFlowPaneTestMain extends Application
{

	public static void main(String[] args)
	{
		launch(args);
	}

	@Override
	public void start(Stage primaryStage)
	{
		FXFluidFlowPane flowPane = new FXFluidFlowPane();
		flowPane.setStyle("-fx-background-color: #FFBBBB;");

		FXFluidFlowPane fixedFlowPane = new FXFluidFlowPane();
		fixedFlowPane.setStyle("-fx-background-color: #BBBBFF;");

		// Needed so that the flow pane can resize itself.
		VBox containerBox = new VBox();
		containerBox.setFillWidth(false);
		containerBox.getChildren().add(flowPane);
		containerBox.getChildren().add(new Label("This is a label to show you that\nthe FluidFlowPane does not overlap\nother elements unless necessary."));

		ComboBox<Orientation> orientationBox = new ComboBox<>();
		orientationBox.getItems().addAll(Orientation.values());
		orientationBox.setValue(flowPane.getOrientation());
		flowPane.orientationProperty().bind(orientationBox.valueProperty());
		fixedFlowPane.orientationProperty().bind(orientationBox.valueProperty());

		ComboBox<Pos> alignmentBox = new ComboBox<>();
		alignmentBox.getItems().addAll(Pos.values());
		alignmentBox.setValue(flowPane.getAlignment());
		flowPane.alignmentProperty().bind(alignmentBox.valueProperty());
		fixedFlowPane.alignmentProperty().bind(alignmentBox.valueProperty());

		ComboBox<HPos> inlineHPosBox = new ComboBox<>();
		inlineHPosBox.getItems().addAll(HPos.values());
		inlineHPosBox.setValue(flowPane.getInlineHPos());
		flowPane.inlineHPosProperty().bind(inlineHPosBox.valueProperty());
		fixedFlowPane.inlineHPosProperty().bind(inlineHPosBox.valueProperty());

		ComboBox<VPos> inlineVPosBox = new ComboBox<>();
		inlineVPosBox.getItems().addAll(VPos.values());
		inlineVPosBox.setValue(flowPane.getInlineVPos());
		flowPane.inlineVPosProperty().bind(inlineVPosBox.valueProperty());
		fixedFlowPane.inlineVPosProperty().bind(inlineVPosBox.valueProperty());

		CheckBox autoWrapCheckBox = new CheckBox("Auto Wrap");
		autoWrapCheckBox.setSelected(flowPane.isAutoWrap());
		flowPane.autoWrapProperty().bind(autoWrapCheckBox.selectedProperty());
		fixedFlowPane.autoWrapProperty().bind(autoWrapCheckBox.selectedProperty());

		Slider hGapSlider = new Slider(0, 100, flowPane.getHGap());
		flowPane.hGapProperty().bind(hGapSlider.valueProperty());
		fixedFlowPane.hGapProperty().bind(hGapSlider.valueProperty());

		Slider vGapSlider = new Slider(0, 100, flowPane.getVGap());
		flowPane.vGapProperty().bind(vGapSlider.valueProperty());
		fixedFlowPane.vGapProperty().bind(vGapSlider.valueProperty());

		CheckBox inlineStretchCheckBox = new CheckBox("Inline Stretch");
		inlineStretchCheckBox.setSelected(flowPane.isInlineStretch());
		flowPane.inlineStretchProperty().bind(inlineStretchCheckBox.selectedProperty());
		fixedFlowPane.inlineStretchProperty().bind(inlineStretchCheckBox.selectedProperty());

		CheckBox stretchHorizontalCheckBox = new CheckBox("Stretch Horizontal");
		stretchHorizontalCheckBox.setSelected(flowPane.isStretchHorizontal());
		flowPane.stretchHorizontalProperty().bind(stretchHorizontalCheckBox.selectedProperty());
		fixedFlowPane.stretchHorizontalProperty().bind(stretchHorizontalCheckBox.selectedProperty());

		CheckBox stretchVerticalCheckBox = new CheckBox("Stretch Vertical");
		stretchVerticalCheckBox.setSelected(flowPane.isStretchVertical());
		flowPane.stretchVerticalProperty().bind(stretchVerticalCheckBox.selectedProperty());
		fixedFlowPane.stretchVerticalProperty().bind(stretchVerticalCheckBox.selectedProperty());

		Button addButton = new Button("Add component");
		addButton.setOnAction((pActionEvent) ->
		{
			addComponent(flowPane);
			addComponent(fixedFlowPane);
		});

		Button removeButton = new Button("Remove last component");
		removeButton.setOnAction((pActionEvent) ->
		{
			if (!flowPane.getChildren().isEmpty())
			{
				flowPane.getChildren().remove(flowPane.getChildren().size() - 1);
			}
			if (!fixedFlowPane.getChildren().isEmpty())
			{
				fixedFlowPane.getChildren().remove(fixedFlowPane.getChildren().size() - 1);
			}
		});

		FXFormPane controlPane = new FXFormPane();
		controlPane.setNewlineCount(7);
		controlPane.getChildren().add(new Label("Orientation"));
		controlPane.getChildren().add(orientationBox);
		controlPane.getChildren().add(new Label("Alignment"));
		controlPane.getChildren().add(alignmentBox);
		controlPane.getChildren().add(addButton);
		controlPane.addChildInNewLine(new Label("Inline Horizontal Alignment"));
		controlPane.getChildren().add(inlineHPosBox);
		controlPane.getChildren().add(new Label("Inline Vertical Alignment"));
		controlPane.getChildren().add(inlineVPosBox);
		controlPane.getChildren().add(removeButton);
		controlPane.addChildInNewLine(new Label("Horizontal Gap"));
		controlPane.getChildren().add(hGapSlider);
		controlPane.getChildren().add(new Label("Vertical Gap"));
		controlPane.getChildren().add(vGapSlider);
		controlPane.getChildren().add(autoWrapCheckBox);
		controlPane.addChildInNewLine(inlineStretchCheckBox);
		controlPane.getChildren().add(stretchHorizontalCheckBox);
		controlPane.getChildren().add(stretchVerticalCheckBox);

		SplitPane splitPane = new SplitPane();
		splitPane.getItems().add(containerBox);
		splitPane.getItems().add(fixedFlowPane);

		BorderPane root = new BorderPane();
		containerBox.setPrefSize(800, 600);
		root.setTop(controlPane);
		root.setCenter(splitPane);
		BorderPane.setAlignment(root.getCenter(), Pos.CENTER);

		primaryStage.setScene(new Scene(root));
		primaryStage.setTitle("JavaFX FluidFlowPane Test");
		primaryStage.show();

		addButton.fire();
		addButton.fire();
		addButton.fire();
		addButton.fire();
	}

	private void addComponent(Pane pPane)
	{
		int type = pPane.getChildren().size() % 3;

		switch (type)
		{
			case 0:
				Label label = new Label("Label " + Integer.toString(pPane.getChildren().size()));
				label.setMinSize(32, 32);
				label.setStyle("-fx-background-color: #0099FF;");
				pPane.getChildren().add(label);
				break;

			case 1:
				Button button = new Button("Button " + Integer.toString(pPane.getChildren().size()));
				button.setPrefSize(64, 64);
				pPane.getChildren().add(button);
				break;

			case 2:
				CheckBox checkBox = new CheckBox("Some CheckBox " + Integer.toString(pPane.getChildren().size()));
				checkBox.setStyle("-fx-background-color: #99FF00;");
				pPane.getChildren().add(checkBox);
				break;

		}
	}
}


text:
package org.apache.storm.benchmark.lib.bolt;

import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.BasicOutputCollector;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseBasicBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.Map;

public class ConstBolt extends BaseBasicBolt {
    public static final String FIELDS = "message";
    private static final long serialVersionUID = -5313598399155365865L;

    public ConstBolt() {
    }

    @Override
    public void prepare(Map conf, TopologyContext context) {
    }

    @Override
    public void execute(Tuple tuple, BasicOutputCollector collector) {
        collector.emit(new Values(tuple.getValue(0)));
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields(FIELDS));
    }
}


text:
<?php

namespace Tests;

use PHPUnit\Framework\TestCase;
use Ice\Exception;
use Ice\Arr;
use Tests\App\Bootstrap;
use Tests\App\Models\Roles;
use Tests\App\Models\MongoRoles;

class ModelTest extends TestCase
{
    private static $di;

    public static function setUpBeforeClass(): void
    {
        self::$di = (new Bootstrap(['config', 'db', 'mongo']))->getDi();
    }

    public static function tearDownAfterClass(): void
    {
        self::$di = null;
    }

    public function __get($service)
    {
        return self::$di->{$service};
    }

    /**
     * Test find one
     *
     * @dataProvider roles
     */
    public function testFindOne($filters, $expected)
    {
        $return = Roles::findOne($filters);

        if ($return instanceof Roles) {
            $return = $return->getData();
        }

        $this->assertEquals($expected, $return);
    }

    /**
     * Test construct
     *
     * @dataProvider roles
     */
    public function testConstruct($filters, $expected)
    {
        $role = new Roles($filters);

        if ($expected) {
            $data = $role->getData();
            $this->assertEquals($expected, $data);
        } else {
            $this->assertFalse($role->exists());
        }
    }

    /**
     * Test find one
     *
     * @dataProvider roles
     */
    public function testMongoFindOne($filters, $expected)
    {
        $return = MongoRoles::findOne($filters);

        if ($return instanceof MongoRoles) {
            // Remove the ObjectId
            unset($return['_id']);

            $return = $return->getData();
        }

        $this->assertEquals($expected, $return);
    }

    /**
     * Roles
     *
     * @return array
     */
    public function roles()
    {
        return [
            [['id' => 1], ['id' => '1', 'name' => 'login', 'description' => 'Login privileges, granted after account confirmation.']],
            [['name' => 'admin'], ['id' => '2', 'name' => 'admin', 'description' => 'Administrative user, has access to everything.']],
            [['name' => 'mod'], false],
        ];
    }
}


text:
def qsort lst
  return [] if lst.size() == 0
  less, more = left.partition {|x| x < first}
  return qsort(less) + [first] + qsort(more)
end


text:
require "spec_helper"

describe Memory do
  before(:each) { FileUtils.mkdir_p("spec/Users/test/sheldon") }
  after(:each) { FileUtils.rm_r("spec/Users") }

  let(:memory) { Memory.new("spec/Users/test/sheldon") }

  describe "#add" do
    context "when a cue has not previously been used" do
      it "should persist the new entry" do
        expect(memory.size).to eq 0
        memory.add("lightbulb", {filepath: "/path/to/lightbulb"})
        expect(memory.size).to eq 1
      end
    end

    context "when a cue has been previously used" do
      it "should raise an error" do
        memory.add("lightbulb", {filepath: "/path/to/lightbulb"})
        expect{ memory.add("lightbulb", {filepath: "/path/to/lightbulb"}) }.to raise_error("cue already used")
      end
    end
  end

  describe "#has_cue" do
    context "when a cue is not saved in memory" do
      it "should return false" do
        expect(memory.has_cue?("lightbulb")).to be false
      end
    end

    context "when a cue is saved in memory" do
      it "should return true" do
        memory.add("lightbulb", {filepath: "/path/to/lightbulb"})
        expect(memory.has_cue?("lightbulb")).to be true
      end
    end
  end

  describe "#forget" do
    context "when a cue does not exist in memory" do
      it "should raise an error" do
        expect{ memory.recall("lightbulb") }.to raise_error("no entry for cue 'lightbulb'")
      end
    end

    context "when a cue does exist in memory" do
      before(:each) { memory.add("lightbulb", {filepath: "/path/to/lightbulb"}) }

      it "should remove the entry from the database" do
        expect(memory.has_cue?("lightbulb")). to be true
        memory.forget("lightbulb")
        expect(memory.has_cue?("lightbulb")). to be false
      end
    end
  end

  describe "#list_cues" do
    context "when the memory contains zero cues" do
      it "should return an empty list" do
        expect(memory.list_cues).to be_empty
      end
    end

    context "when memory contains multiple cues" do
      it "should return the cues" do
        memory.add("rolo", {filepath: "/path/to/rolo"})
        memory.add("bounty", {filepath: "/path/to/bounty"})
        expect(memory.list_cues).to eq ['rolo','bounty']
      end
    end
  end

  describe "#save!" do
    it "should write Sheldon's memory to local storage" do
      expect(File).not_to exist("spec/Users/test/sheldon/db.yml")
      memory.save!
      expect(File).to exist("spec/Users/test/sheldon/db.yml")
    end
  end

  describe "#present?" do
    context "when memory hasn't been persisted to storage" do
      it "should return false" do
        expect(memory.present?).to be false
      end
    end

    context "when memory has been saved to storage" do
      it "should return true" do
        memory.save!
        expect(memory.present?).to be true
      end
    end
  end

  describe "#recall" do
    context "when a cue does not exist in memory" do
      it "should raise an error" do
        expect{ memory.recall("lightbulb") }.to raise_error("no entry for cue 'lightbulb'")
      end
    end

    context "when a cue does exist in memory" do
      it "should return the value associated with that cue" do
        memory.add("lightbulb", {filepath: "/path/to/lightbulb"})
        expect(memory.recall("lightbulb")).to eq ({filepath: "/path/to/lightbulb"})
      end
    end
  end

  describe "#size" do
    it "should increase by 1 with each new entry" do
      expect{ memory.add("lightbulb", {filepath: "/path/to/lightbulb"}) }.to change{ memory.size }.by(1)
    end
  end

end


text:
package org.jetbrains.plugins.groovy.lang.parser.parsing.auxiliary.parameters;

import com.intellij.lang.PsiBuilder;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.parser.GroovyParser;
import org.jetbrains.plugins.groovy.lang.parser.parsing.util.ParserUtils;

/**
 * @author: Dmitry.Krasilschikov, ilyas
 * @date: 26.03.2007
 */
public class ParameterList implements GroovyElementTypes {

  /**
   * @param builder Given builder
   * @param ending  ending:  -> or ) in various cases
   */
  public static void parse(PsiBuilder builder, IElementType ending, GroovyParser parser) {
    if (builder.getTokenType() == mRPAREN && mRPAREN.equals(ending)) {
      PsiBuilder.Marker marker = builder.mark();
      marker.done(PARAMETERS_LIST);
      return;
    }

    PsiBuilder.Marker marker = builder.mark();

    if (!ParameterDeclaration.parseSimpleParameter(builder, parser)) {
      marker.rollbackTo();
      marker = builder.mark();
      marker.done(PARAMETERS_LIST);
      return;
    }

    while (!builder.eof() &&
            mCOMMA.equals(builder.getTokenType())) {
      ParserUtils.getToken(builder, mCOMMA);
      ParserUtils.getToken(builder, mNLS);
      if (!ParameterDeclaration.parseSimpleParameter(builder, parser)) {
        builder.error(GroovyBundle.message("param.expected"));
      }
    }

    ParserUtils.getToken(builder, mNLS);

    if ((ending.equals(mCLOSABLE_BLOCK_OP) &&
            mCLOSABLE_BLOCK_OP.equals(builder.getTokenType()))
            || ending.equals(mRPAREN)) {
      marker.done(PARAMETERS_LIST);
    } else {
      marker.rollbackTo();
      marker = builder.mark();
      marker.done(PARAMETERS_LIST);
    }

  }
}