text:
<?php
// include our OAuth2 Server object
require_once __DIR__.'/server.php';
/**
 PHP API for Register Requests and for Email Notifications.
 **/
if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // Get tag
    $tag = $_POST['tag'];
    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
	// response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);
    // check for tag type
    if ($tag == 'register') {
		// Request type is Register new user
        //$fname = $_POST['fname'];
		//$fname = htmlentities($_POST['fname'], ENT_QUOTES,'UTF-8');
		$fname = utf8_encode($_POST['fname']);
		$lname = utf8_encode($_POST['lname']);
        $email = utf8_encode($_POST['email']);
		$pass = utf8_encode($_POST['password']);
        $subject = "Registro de usuario en SafePoll";
        $message = "Hola $fname,\nSe ha registrado con exito esta cuenta en nuestro servicio.\nSaludos,\nAdministración de SafePoll.";
        $from = "contact@umaproject.grn.cc";
        $headers = "From:" . $from;
        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "El usuario ya existe.";
            echo json_encode($response);
        }
        else if(!$db->validEmail($email)){
            $response["error"] = 3;
            $response["error_msg"] = "Email invalido.";
            echo json_encode($response);
		}
		else {
            // store user
            $user = $db->storeUser($fname, $lname, $email, $pass);
            if ($user) {
                // user stored successfully
				$response["success"] = 1;
				$response["email"] = $user["client_id"];
				$response["pass"] = $pass;

				mail($email,$subject,$message,$headers);
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error al intentar el registro.";
                echo json_encode($response);
            }
        }
    } else if ($tag == 'forpass'){
		$forgotpassword = $_POST['forgotpassword'];
		$forgotmail = $_POST['forgotmail'];
		if(empty($forgotpassword)){
			$result = $db->forgotmail($forgotmail);

			if($result){
				$response["success"] = 1;

				$response["result"] = $result["client_id"];

				echo json_encode($response);
			}else{
				$response["error"] = 1;
				echo json_encode($response);
			}
		}else{
			$randomcode = $db->random_string();
			$hash = $db->hashSSHA($randomcode);
			$encrypted_password = $hash["encrypted"]; // encrypted password
			$salt = $hash["salt"];
			$subject = "Recuperacion de contraseña";
			//$message = "Hello User,\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\nRegards,\nSafepoll Team.";

			if ($db->isUserExisted($forgotpassword)) {

				$token = $db->forgotPassword($forgotpassword, $encrypted_password, $salt, $randomcode);
				if (isset($token)) {
					///////////////////
					$scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
					$url = $scheme . '://' . $_SERVER['HTTP_HOST'] . '/grant.php?token=' . $token; // . $_SERVER['REQUEST_URI']
					$message = "Saludos,\nHemos recibido una peticion para reiniciar tu contraseña. Si usted realizó la petición haga click en el link que aparece a continuación:\n\n $url  \n\nTras clickear en el enlace, su contraseña será reiniciada y recibirá un correo con su nueva contraseña.\n\nSaludos,\nAdministración de Safepoll.";
					$from = "contact@umaproject.grn.cc";
					$headers = "From:" . $from;
					////////////////////
					$response["success"] = 1;
					mail($forgotpassword,$subject,$message,$headers);
					echo json_encode($response);
				}
				else {
					$response["error"] = 1;
					echo json_encode($response);
				}
				// user is already existed - error response
			}
			else {
				$response["error"] = 2;
				$response["error_msg"] = "El usuario no existe.";
				echo json_encode($response);
			}
		}

	} else {
         $response["error"] = 3;
         $response["error_msg"] = "JSON ERROR";
        echo json_encode($response);
    }
}
?>


text:
@interface BetableWebViewController : UIViewController <UIWebViewDelegate, UIAlertViewDelegate>

@property (nonatomic, copy) BetableCancelHandler onCancel;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) NSString *onLoadState;
@property BOOL showInternalCloseButton;
@property BOOL finishedLoading;
@property BOOL portraitOnly;
@property BOOL loadCachedStateOnFinish;
@property BOOL forcedOrientationWithNavController;

- (BetableWebViewController*)initWithURL:(NSString*)url onCancel:(BetableCancelHandler)onClose;
- (id)initWithURL:(NSString*)url onCancel:(BetableCancelHandler)onCancel showInternalCloseButton:(BOOL)showInternalCloseButton;

- (void)closeWindow;
- (void)resetView;
- (void)loadCachedState;
@end

redpajama_set_name: RedPajamaGithub


text:
var routes = require("./routes");
var cors = require("cors");

// Starts this instance of bro as a server.
var server = function() {

    var path = require('path');
    var express = require('express');
    var exphbs  = require('express3-handlebars');
    var _ = require("underscore");
    var app = express();

    console.log("Starting server");

    app.set('port', process.env.PORT || 54242);

    app.set('views', path.join(__dirname, 'views'));
    app.engine('handlebars', exphbs({
        defaultLayout: 'main'
    }));
    app.set('view engine', 'handlebars');

    app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));
    app.use(express.logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.methodOverride());
    app.use(cors());

    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));

    if ('development' == app.get('env')) {
        console.log('Application running in development mode.');
        app.use(express.errorHandler());
    }

    // Register APIs.
    _.each(routes, function(route, routeName, routes) {
        console.log("Registering route:", routeName);
        app.all('/api/'+routeName, routes[routeName].api);
    });

    // Usage page.
    app.all('/', function(req, res) {
        var usages = [];
        var route;

        for (route in routes) {
            if (typeof routes[route].usage == "function") {
                usages.push({usage: routes[route].usage()});
            }
        }

        _.sortBy(usages, "usage");

        res.render('home', {usages: usages});
    });

    app.listen(app.get('port'), function() {
        console.log('Server listening on port ' + app.get('port'));
    });

};

if (require.main === module) {
    // Run as a server.
    server();
}


text:
module Howrah
  module Processor
    module Element
      class Base
        attr_accessor :options
        proxy :parent

        def initialize(parent, options = {}, &block)
          raise ArgumentError, "Supplied options must be of type Hash" if ! options.kind_of? Hash
          raise ArgumentError, "Supplied options must not be empty" if options.empty?
          @parent = parent
          @options = options
        end

        def process(&block)
          before
          execute(block) if block && proces_children?
          after
        end

        def before
          self
        end

        def after
          self
        end

        def execute(&block)
          block.arity < 1 ? self.instance_eval(&block) : block.call(self)
        end

        def process_children?
          true
        end
      end
    end
  end
end


text:
	<script type="text/javascript">
	$(document).ready(function() {
		$('#pinterest-icon').tipsy({gravity: 's',fallback: "Pinterest"});
		$('#twitter-icon').tipsy({gravity: 's',fallback: "Twtter"});
		$('#instagram-icon').tipsy({gravity: 's',fallback: "Instagram"});
		$('#facebook-icon').tipsy({gravity: 's',fallback: "Facebook"});
		$('#googleplus-icon').tipsy({gravity: 's',fallback: "Google+"});
		$('#rss-icon').tipsy({gravity: 's',fallback: "RSS Feed"});
	});
	</script>
<?php
echo "\n\r</head>";
echo "\n\r<body>";
?>


text:
#ifndef RNG_H
#define RNG_H

#include <random>
#include <algorithm>
#include <cassert>

/*
 * RNG - random number generator - a wrapper class to simplify random number
 * generation.
 */
class RNG {
public:
    RNG();

    RNG(uint32_t seed);

    /* Returns a random number in the range [0.0, 1.0] */
    double random() { return real_unit_distribution_(generator_); }

    uint32_t rand_uint(uint32_t start, uint32_t end_inclusive) {
        auto dist = std::uniform_int_distribution<uint32_t>(start, end_inclusive);
        return dist(generator_);
    }

    uint32_t get_seed() const { return seed_; }

    template<class RandomIt>
    void shuffle(RandomIt first, RandomIt last) {
        std::shuffle(first, last, generator_);
    }

    /*
     * Returns a random sample taken from the set { start, start+1, ...,
     * end_inclusive }.
     */
    std::vector<uint32_t> random_sample(uint32_t start, uint32_t end_inclusive,
                                        uint32_t sample_size);

private:
    std::random_device rd_; // We need this to initialize our generator
    const uint32_t seed_;
    std::mt19937 generator_;
    std::uniform_real_distribution<double> real_unit_distribution_;
};

#endif /* ifndef RNG_H */


text:
<?php
$lang['L_DUMP_HEADLINE']="bi am backup mache..";
$lang['L_GZIP_COMPRESSION']="GZip-Kompression";
$lang['L_SAVING_TABLE']="Spichere Tabälle";
$lang['L_OF']="vo";
$lang['L_ACTUAL_TABLE']="Aktuelli Tabälle";
$lang['L_PROGRESS_TABLE']="Fortschritt Tabälle";
$lang['L_PROGRESS_OVER_ALL']="Fortschritt gsamt";
$lang['L_ENTRY']="Itrag";
$lang['L_DONE']="Alls gmacht!";
$lang['L_DUMP_SUCCESSFUL']="isch erfolgriich erstellt worde.";
$lang['L_UPTO']="bis";
$lang['L_EMAIL_WAS_SEND']="D E-Mail isch erfolriich verschickt worde an";
$lang['L_BACK_TO_CONTROL']="wiiter";
$lang['L_BACK_TO_OVERVIEW']="zrugg zur Übersicht";
$lang['L_DUMP_FILENAME']="Backup-Datei:";
$lang['L_WITHPRAEFIX']="mit Präfix";
$lang['L_DUMP_NOTABLES']="Es händ kei Tabällen i de Datenbank `<b>%s</b>` chöne gfunde werde.";
$lang['L_DUMP_ENDERGEBNIS']="Es sind %s Tabälle mit zäme %s Datesätz gsicheret worde.
";
$lang['L_MAILERROR']="Leider isch bim Verschicke vo de E-Mail en Fähler underloffe!";
$lang['L_EMAILBODY_ATTACH']="Im Aahang finded Si d Sicherig vo Ihrer MySQL-Datenbank.
Sicherig vo de Datenbank `%s`

Folgende Datei wurde erzeugt:

%s

Fründlichi Grüess

MySQLDumper
";
$lang['L_EMAILBODY_MP_NOATTACH']="Es isch e Multipart-Sicherig erstellt worde.
Die Sicherige werdet nöd als Aahang mitglieferet!
Sicherig vo de Datenbank `%s`

Folgendi Dateie sind erzügt worde:

%s

Fründlichi Grüess

MySQLDumper
";
$lang['L_EMAILBODY_MP_ATTACH']="Es isch e Multipart-Sicherig erstellt worde.
D Sicherige werdet i separate E-Mails als Anhang glieferet!
Sicherig vo de Datenbank `%s`

Folgendi Dateie sind erzügt worde:

%s

Fründlichi Grüess

MySQLDumper
";
$lang['L_EMAILBODY_FOOTER']="

Fründlichi Grüess

MySQLDumper
";
$lang['L_EMAILBODY_TOOBIG']="D Sicherig überschriitet d Maximalgrössi von %s und isch drum nöd aagehänkt worde.
Sicherig vo de Datenbank `%s`

Folgendi Datei isch erzügt worde:

%s

Fründlichi Grüess

MySQLDumper
";
$lang['L_EMAILBODY_NOATTACH']="S Backup isch nöd aaghänkt worde.
Sicherig vo de Datenbank `%s`

Folgendi Datei isch erzügt worde:

%s

Fründlichi Grüess

MySQLDumper
";
$lang['L_EMAIL_ONLY_ATTACHMENT']="... nume dr Aahang";
$lang['L_TABLESELECTION']="Tabälleuswahl";
$lang['L_SELECTALL']="ali uuswähle";
$lang['L_DESELECTALL']="Uswahl ufhebä";
$lang['L_STARTDUMP']="Backup starte";
$lang['L_LASTBUFROM']="sletschti Update vom";
$lang['L_NOT_SUPPORTED']="Das Backup cha diä Funktion nöd.";
$lang['L_MULTIDUMP']="Multidump: Es sind %d Datenbanke gesicheret worde.";
$lang['L_FILESENDFTP']="verschicke grad File via FTP... heb bitte e chli Geduld.";
$lang['L_FTPCONNERROR']="FTP-Verbindig nöd hergstellt! Verbindig mit";
$lang['L_FTPCONNERROR1']="als User";
$lang['L_FTPCONNERROR2']="nöd mögli";
$lang['L_FTPCONNERROR3']="FTP-Upload isch fählerhaft gsi!";
$lang['L_FTPCONNECTED1']="Verbunde mit";
$lang['L_FTPCONNECTED2']="uf";
$lang['L_FTPCONNECTED3']="gschribe";
$lang['L_NR_TABLES_SELECTED']="- mit %s gewählte Tabälle";
$lang['L_NR_TABLES_OPTIMIZED']="%s Tabälle sind optimiert worde.";
$lang['L_DUMP_ERRORS']="
%s Fähler ufträte: aaluege
";
$lang['L_FATAL_ERROR_DUMP']="Fatale Fähler: d CREATE-Aawiisig vo de Tabelle '%s' i de Datenbank '%s' hät nöd chöne gläse werde!";

?>


text:
var utils = require('util');
var assert = require('assert');
var base = require('42-cent-base').BaseGateway;
var Promise = require('bluebird');
var request = require('request');
var mapKeys = require('42-cent-util').mapKeys;
var qs = require('query-string');
var GatewayError = require('42-cent-base').GatewayError;

var schema = require('./schemas.js');

/**
 * @extends BaseGateway
 * @param config
 * @constructor
 */
function NMIGateway (config) {

  assert(config.USERNAME, 'USERNAME must be defined');
  assert(config.PASSWORD, 'PASSWORD must be defined');

  this.endpoint = 'https://secure.nmi.com/api/transact.php';

  utils._extend(this, config);
}

function postRequest (params, service) {

  var post = Promise.promisify(request.post);

  params.username = service.USERNAME;
  params.password = service.PASSWORD;

  return post(service.endpoint, {formData: params}).then(function (result) {
    return qs.parse('?' + result[1]);
  });
}

utils.inherits(NMIGateway, base);

/**
 * @inheritsDoc
 */
NMIGateway.prototype.submitTransaction = function submitTransaction (order, creditCard, prospect, other) {

  var params = Object.assign(order, creditCard, prospect, other);
  params = mapKeys(params, schema);

  params.type = 'sale';
  if (creditCard.expirationMonth && creditCard.expirationYear) {
    params.ccexp = creditCard.expirationMonth.toString() + creditCard.expirationYear.toString();
  }
  return postRequest(params, this).then(function (result) {

    if (result.response !== '1') {
      throw new GatewayError(result.responsetext, result);
    }

    return {
      transactionId: result.transactionid,
      _original: result,
      authCode: result.authcode
    }
  });

};

/**
 * @inheritsDoc
 */
NMIGateway.prototype.authorizeTransaction = function authorizeTransaction (order, creditCard, prospect, other) {

  if (other) {
    console.log('other field is not supported');
  }

  var params = Object.assign(order, creditCard, prospect, other);
  params = mapKeys(params, schema);

  params.type = 'auth';
  params.ccexp = creditCard.expirationMonth.toString() + creditCard.expirationYear.toString();
  return postRequest(params, this).then(function (result) {

    if (result.response !== '1') {
      throw new GatewayError(result.responsetext, result);
    }

    return {
      transactionId: result.transactionid,
      _original: result,
      authCode: result.authcode
    }
  });
};

/**
 * @inheritsDoc
 */
NMIGateway.prototype.refundTransaction = function refundTransaction (transactionId, options) {

  if(options){
    var params = Object.assign(options);
    params = mapKeys(params, schema);
  } else {
    var params = {};
  }

  params.transactionid = transactionId;
  params.type = 'refund';

  return postRequest(params, this).then(function (result) {

    if (result.response !== '1') {
      throw new GatewayError(result.responsetext, result);
    }

    return {
      _original: result
    }
  });

};

/**
 * @inheritsDoc
 */
NMIGateway.prototype.voidTransaction = function voidTransaction (transId, options) {

  if (options) {
    console.log('options is not supported');
  }

  var params = {
    transactionid: transId
  };

  params.type = 'void';

  return postRequest(params, this)
    .then(function (result) {
      if (result.response !== '1') {
        throw new GatewayError(result.responsetext, result);
      }

      return {
        _original: result
      };
    });
};

/**
 * @inheritsDoc
 */
NMIGateway.prototype.createCustomerProfile = function createCustomerProfile (cc, billing, shipping, options) {

  var params = Object.assign(cc, billing, shipping, options);
  var scheme = utils._extend(schema, {customerFirstName: 'first_name', customerLastName: 'last_name'});

  params = mapKeys(params, scheme);

  params.customer_vault = 'add_customer';
  params.ccexp = cc.expirationMonth.toString() + cc.expirationYear.toString();
  return postRequest(params, this).then(function (result) {

    if (result.response !== '1') {
      throw new GatewayError(result.responsetext, result);
    }

    return {
      profileId: result.customer_vault_id,
      _original: result
    }
  });
};

/**
 * @inheritsDoc
 */
NMIGateway.prototype.chargeCustomer = function (order, prospect, other) {
  return this.submitTransaction(order, {}, prospect, other);
};

module.exports = NMIGateway;


text:
#include "paletteTreeWidget.h"

#include <QtGui/QMouseEvent>
#include <QtWidgets/QMenu>

#include "mainWindow/palette/paletteTree.h"
#include "mainWindow/palette/draggableElement.h"
#include "dialogs/metamodelingOnFly/chooseTypeDialog.h"

using namespace qReal;
using namespace gui;

const EditorManagerInterface *PaletteTreeWidget::mEditorManager = nullptr;

PaletteTreeWidget::PaletteTreeWidget(PaletteTree &palette, MainWindow &mainWindow
		, const EditorManagerInterface &editorManagerProxy, bool editable)
	: mMainWindow(mainWindow)
	, mPaletteTree(palette)
	, mEditable(editable)
{
	mEditorManager = &editorManagerProxy;
}

void PaletteTreeWidget::addGroups(QList<QPair<QString, QList<PaletteElement>>> &groups
		, QMap<QString, QString> const &descriptions
		, bool hideIfEmpty
		, const QString &diagramFriendlyName
		, bool sort)
{
	if (groups.isEmpty() && hideIfEmpty) {
		hide();
		return;
	}

	mPaletteItems.clear();
	mPaletteElements.clear();
	mElementsSet.clear();
	mItemsVisible.clear();
	clear();
	show();

	if (sort) {
		qSort(groups.begin(), groups.end()
				, [](QPair<QString, QList<PaletteElement>> const &e1
						, QPair<QString, QList<PaletteElement>> const &e2)
					{
						return e1.first < e2.first;
					}
				);
	}

	int expandedCount = 0;
	for (auto &group : groups) {
		QTreeWidgetItem * const item = new QTreeWidgetItem;
		item->setText(0, group.first);
		item->setToolTip(0, descriptions[group.first]);

		if (sort) {
			sortByFriendlyName(group.second);
		}

		addItemsRow(group.second, item);
		addTopLevelItem(item);

		if (SettingsManager::value(diagramFriendlyName + group.first, 0).toBool()) {
			++expandedCount;
			expandItem(item);
		}
	}

	if (expandedCount == 0) {
		expand();
	}
}

void PaletteTreeWidget::addItemType(const PaletteElement &data, QTreeWidgetItem *parent)
{
	QTreeWidgetItem *leaf = new QTreeWidgetItem;
	DraggableElement *element = new DraggableElement(mMainWindow, data
			, mPaletteTree.iconsView(), *mEditorManager);

	mElementsSet.insert(data);
	mPaletteElements.insert(data.id(), element);
	mPaletteItems.insert(data.id(), leaf);

	parent->addChild(leaf);
	setItemWidget(leaf, 0, element);
}

void PaletteTreeWidget::addItemsRow(QList<PaletteElement> const &items, QTreeWidgetItem *parent)
{
	if (mPaletteTree.itemsCountInARow() == 1 || !mPaletteTree.iconsView()) {
		foreach (const PaletteElement &element, items) {
			addItemType(element, parent);
		}

		return;
	}

	for (QList<PaletteElement>::ConstIterator it = items.begin(); it != items.end();) {
		QWidget *field = new QWidget;
		QHBoxLayout *layout = new QHBoxLayout;
		int count = mPaletteTree.itemsCountInARow();
		for (; it != items.end() && --count > 0; ++it) {
			DraggableElement *element = new DraggableElement(mMainWindow, *it, true, *mEditorManager);
			element->setToolTip((*it).description());
			layout->addWidget(element, count > 0 ? 50 : 0);
		}

		field->setLayout(layout);
		field->setMinimumHeight(80);
		QTreeWidgetItem *leaf = new QTreeWidgetItem;
		parent->addChild(leaf);
		if (mEditable) {
			leaf->setFlags(leaf->flags() | Qt::ItemIsEditable);
		}

		setItemWidget(leaf, 0, field);
	}
}

void PaletteTreeWidget::addElementPaletteActionTriggered()
{
	ChooseTypeDialog *chooseTypeDialog = new ChooseTypeDialog(mPaletteTree.currentEditor()
			, *mEditorManager, &mMainWindow);
	connect(chooseTypeDialog, &ChooseTypeDialog::jobDone, &mMainWindow, &MainWindow::loadEditorPlugins);
	chooseTypeDialog->setModal(true);
	chooseTypeDialog->show();
}

void PaletteTreeWidget::mousePressEvent(QMouseEvent *event)
{
	if (event->button() == Qt::RightButton) {
		if (mEditorManager->isInterpretationMode()) {
			QMenu menu;
			QAction * const addElementPaletteAction = menu.addAction(tr("Add Element"));
			connect(addElementPaletteAction, SIGNAL(triggered()), this, SLOT(addElementPaletteActionTriggered()));
			menu.exec(QCursor::pos());
		}
	}

	QTreeWidget::mousePressEvent(event);
}

void PaletteTreeWidget::expand()
{
	for (int i = 0; i < topLevelItemCount(); i++) {
		if (topLevelItem(i)) {
			expandChildren(topLevelItem(i));
		}
	}
}

void PaletteTreeWidget::sortByFriendlyName(IdList &ids)
{
	qSort(ids.begin(), ids.end(), idLessThan);
}

void PaletteTreeWidget::sortByFriendlyName(QList<PaletteElement> &elements)
{
	qSort(elements.begin(), elements.end(), paletteElementLessThan);
}

void PaletteTreeWidget::editItem(QTreeWidgetItem * const item)
{
	edit(indexFromItem(item));
}

void PaletteTreeWidget::expandChildren(QTreeWidgetItem *item)
{
	for (int i = 0; i < item->childCount(); i++) {
		if (item->child(i)) {
			expandChildren(item->child(i));
		}
	}

	item->treeWidget()->expandItem(item);
}

void PaletteTreeWidget::collapse()
{
	for (int i = 0; i < topLevelItemCount(); i++) {
		if (topLevelItem(i)) {
			collapseChildren(topLevelItem(i));
		}
	}
}

void PaletteTreeWidget::collapseChildren(QTreeWidgetItem *item)
{
	for (int i = 0; i < item->childCount(); i++) {
		if (item->child(i)) {
			collapseChildren(item->child(i));
		}
	}

	item->treeWidget()->collapseItem(item);
}

bool PaletteTreeWidget::idLessThan(const Id &s1, const Id &s2)
{
	return mEditorManager->friendlyName(s1).toLower() < mEditorManager->friendlyName(s2).toLower();
}

bool PaletteTreeWidget::paletteElementLessThan(const PaletteElement &s1, const PaletteElement &s2)
{
	return idLessThan(s1.id(), s2.id());
}

void PaletteTreeWidget::setElementVisible(const Id &metatype, bool visible)
{
	if (mPaletteItems.contains(metatype)) {
		mItemsVisible[mPaletteItems[metatype]] = visible;
		mPaletteItems[metatype]->setHidden(!visible);
	}
}

void PaletteTreeWidget::setVisibleForAllElements(bool visible)
{
	for (const Id &element : mPaletteElements.keys()) {
		setElementVisible(element, visible);
	}
}

void PaletteTreeWidget::setElementEnabled(const Id &metatype, bool enabled)
{
	if (mPaletteElements.contains(metatype)) {
		mPaletteElements[metatype]->setEnabled(enabled);
	}
}

void PaletteTreeWidget::setEnabledForAllElements(bool enabled)
{
	foreach (QWidget * const element, mPaletteElements.values()) {
		element->setEnabled(enabled);
	}
}

void PaletteTreeWidget::filter(const QRegExp &regexp)
{
	QHash<QTreeWidgetItem *, int> visibleCount;
	traverse([this, &regexp, &visibleCount](QTreeWidgetItem *item) {
		if (DraggableElement * const element = dynamic_cast<DraggableElement *>(itemWidget(item, 0))) {
			const QString text = element->text();
			const bool itemDisabledBySystem = mItemsVisible.contains(item) && !mItemsVisible[item];
			item->setHidden(itemDisabledBySystem || !text.contains(regexp));
			if (!item->isHidden()) {
				++visibleCount[item->parent()];
			}
		}
	});

	for (int i = 0; i < topLevelItemCount(); ++i) {
		QTreeWidgetItem * const item = topLevelItem(i);
		item->setHidden(visibleCount[item] == 0);
	}
}

void PaletteTreeWidget::traverse(const PaletteTreeWidget::Action &action) const
{
	for (int i = 0; i < topLevelItemCount(); ++i) {
		traverse(topLevelItem(i), action);
	}
}

const QSet<PaletteElement> &PaletteTreeWidget::elementsSet() const
{
	return mElementsSet;
}

void PaletteTreeWidget::traverse(QTreeWidgetItem * const item, const PaletteTreeWidget::Action &action) const
{
	action(item);
	for (int i = 0; i < item->childCount(); ++i) {
		traverse(item->child(i), action);
	}
}


text:
package bind

import (
	"testing"

	"github.com/mholt/caddy"
	"github.com/mholt/caddy/caddyhttp/httpserver"
)

func TestSetupBind(t *testing.T) {
	c := caddy.NewTestController("http", `bind 1.2.3.4`)
	err := setupBind(c)
	if err != nil {
		t.Fatalf("Expected no errors, but got: %v", err)
	}

	cfg := httpserver.GetConfig(c)
	if got, want := cfg.ListenHost, "1.2.3.4"; got != want {
		t.Errorf("Expected the config's ListenHost to be %s, was %s", want, got)
	}
	if got, want := cfg.TLS.Manager.ListenHost, "1.2.3.4"; got != want {
		t.Errorf("Expected the TLS config's ListenHost to be %s, was %s", want, got)
	}
}


text:
package ui;

import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import java.awt.GridBagLayout;
import javax.swing.JScrollPane;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import data.Conexion;
import entidades.LineaVenta;
import entidades.Producto;
import entidades.Venta;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import java.awt.event.ActionEvent;

public class ListaVentas {

	private JFrame frame;
	private JTable table;
	private DefaultTableModel modelVtas;
	private JButton btnVerVenta;
	private ArrayList<Venta> ventas;
	private JButton btnBusquedaPorNumero;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ListaVentas window = new ListaVentas();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ListaVentas() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {

		frame = new JFrame();
		ventas = new ArrayList<Venta>();

		frame.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Program Files\\PosFiscal\\688-MEC4563139385_062013-O.png"));
		frame.setBounds(100, 100, 650, 500);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[] {30, 0, 0, 30, 0};
		gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{0.0, 1.0, 1.0, 0.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE};
		frame.getContentPane().setLayout(gridBagLayout);

		JScrollPane scrollPane = new JScrollPane();
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.gridwidth = 2;
		gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridx = 1;
		gbc_scrollPane.gridy = 1;
		frame.getContentPane().add(scrollPane, gbc_scrollPane);
		String [] columnNames = {
				"id",
				"fecha y hora",
				"forma de pago",
				"total cobrado"
		};
		modelVtas = new DefaultTableModel(columnNames, 0){

		    @Override
		    public boolean isCellEditable(int row, int column) {
		       //all cells false
		       return false;
		    }
		};
		table = new JTable(modelVtas);
		scrollPane.setViewportView(table);

		btnVerVenta = new JButton("Ver detalle");
		btnVerVenta.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selecc = table.getSelectedRow();
				ResultSet res = Conexion.queryLineas(Integer.parseInt((String) modelVtas.getValueAt(selecc, 0)));
				Venta v = ventas.get(table.getSelectedRow());
				ArrayList<LineaVenta> lineas = new ArrayList<LineaVenta>();
				try {
					while (res.next())
					{
						LineaVenta lv = new LineaVenta();
						lv.setNro(res.getInt(1));
						lv.setFacturanro(res.getInt(2));
						Producto prod = control.Hub.buscaCodigo(res.getString(3));
						lv.setProducto(prod);
						lv.setCantidad(res.getFloat(4));
						lv.setPrecioUnit(res.getFloat(5));
						lineas.add(lv);
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				ListaLineas.carga(lineas, v);

			}
		});
		GridBagConstraints gbc_btnVerVenta = new GridBagConstraints();
		gbc_btnVerVenta.insets = new Insets(0, 0, 5, 5);
		gbc_btnVerVenta.gridx = 1;
		gbc_btnVerVenta.gridy = 2;
		frame.getContentPane().add(btnVerVenta, gbc_btnVerVenta);

		btnBusquedaPorNumero = new JButton("Busqueda por numero");
		btnBusquedaPorNumero.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String texto = JOptionPane.showInputDialog("Ingrese el numero de la factura");
				ResultSet res = Conexion.queryLineas(Integer.parseInt(texto));
				ArrayList<LineaVenta> lineas = new ArrayList<LineaVenta>();
				ResultSet resu = Conexion.queryVentas();
				Venta v = new Venta();
				try {
					while (resu.next())
					{
						if (resu.getInt(1)==Integer.parseInt(texto))
						{
							v.setNro(resu.getInt(1));
							v.setFormaPago(resu.getInt(3));
							v.setTotalCobrado(resu.getFloat(4));
							v.setFechaHora(resu.getTimestamp(2).toLocalDateTime());
							ventas.add(v);
						}
					}
					while (res.next())
					{
						LineaVenta lv = new LineaVenta();
						lv.setNro(res.getInt(1));
						lv.setFacturanro(res.getInt(2));
						Producto prod = control.Hub.buscaCodigo(res.getString(3));
						lv.setProducto(prod);
						lv.setCantidad(res.getFloat(4));
						lineas.add(lv);
					}
				} catch (SQLException e1) {
					System.out.println(e1.getMessage());
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				ListaLineas.carga(lineas, v);
			}
		});
		GridBagConstraints gbc_btnBusquedaPorNumero = new GridBagConstraints();
		gbc_btnBusquedaPorNumero.insets = new Insets(0, 0, 5, 5);
		gbc_btnBusquedaPorNumero.gridx = 2;
		gbc_btnBusquedaPorNumero.gridy = 2;
		frame.getContentPane().add(btnBusquedaPorNumero, gbc_btnBusquedaPorNumero);
		ResultSet res = Conexion.queryVentas();

		try {
			while(res.next())
			{
				Venta v = new Venta();
				v.setNro(res.getInt(1));
				v.setFormaPago(res.getInt(3));
				v.setTotalCobrado(res.getFloat(4));
				v.setFechaHora(res.getTimestamp(2).toLocalDateTime());
				ventas.add(v);
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		for (Venta venta : ventas) {
			Vector<String> vec = new Vector<String>();
			vec.add(String.valueOf(venta.getNro()));
			vec.add(venta.getFechaHora().toString());
			switch (venta.getFormaPago()) {
			case 0:
				vec.add("Efectivo");break;
			case 1:
				vec.add("Tarjeta"); break;
			case 2:
				vec.add("Cuenta Corriente"); break;
			case 3:
				vec.add("Pago Mixto"); break;
				default:
					vec.add("indefinido?");
			}
			vec.add(String.valueOf(venta.getTotalCobrado()));
			modelVtas.addRow(vec);
			table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		}

	}

}


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

/**
 * Operator x ? y : z uses GetValue
 *
 * @path ch11/11.12/S11.12_A2.1_T4.js
 * @description If ToBoolean(x) is false and GetBase(z) is null, throw ReferenceError
 */

//CHECK#1
try {
  false ? true : z;
  $ERROR('#1.1: false ? true : z throw ReferenceError. Actual: ' + (false ? true : z));
}
catch (e) {
  if ((e instanceof ReferenceError) !== true) {
    $ERROR('#1.2: false ? true : z throw ReferenceError. Actual: ' + (e));
  }
}


text:
# Building the SDK for Use in the Browser

This section explains how you can create your own build of the AWS SDK for
JavaScript. If you are working with the SDK outside of an environment that
enforces CORS in your browser and want access to the full gamut of services
provided by the **AWS SDK for JavaScript**, it is possible to build a custom
copy of the SDK locally by cloning the repository and running the same build
tools used to generate the default hosted version of the SDK. This chapter
outlines the steps to build the SDK on your own with extra services and API
versions.

## Setting Up

In order to build the SDK, you first need to clone the Git repository containing
the SDK source. These instructions assume you have [Git](http://git-scm.org) and
a version of [Node.js](http://nodejs.org) installed on your machine.

First, clone the repository from GitHub and cd into the directory:

```bash
git clone git://github.com/aws/aws-sdk-js
cd aws-sdk-js
```

After you have cloned the repository, you need to download the dependency modules
for both the SDK and build tool:

```bash
npm install --production && cd dist-tools && npm install --production && cd ..
```

You should now be able to build a packaged version of the SDK.

## Building

The builder tool is found in `dist-tools/browser-builder.js`. You can run
this script by typing:

```bash
node dist-tools/browser-builder.js > aws-sdk.js
```

This will build to the file `aws-sdk.js`. By default this package includes
only the services documented in the {file:browser-services.md Working With Services}
chapter. Building custom services is discussed later in this chapter. Note
also that by default, this file is uncompressed.

### Minifying Output

The builder tool can also compress output. To do this, set the `MINIFY`
environment variable like so:

```bash
MINIFY=1 node dist-tools/browser-builder.js > aws-sdk.js
```

### Building Specific Services and API Versions

#### Selecting Services to Build

When building via the builder tool, you can select which services you want to
build into the SDK. To select services, specify the names of the services
delimited by commas as arguments to the tool on the command-line. For example,
to build only Amazon S3 and Amazon EC2, use the following command:

```bash
node dist-tools/browser-builder.js s3,ec2 > aws-sdk-s3-ec2.js
```

#### Selecting API Versions

You can also select specific API versions of services when building
by suffixing the version name after the service identifier. For example, to
build both API versions of Amazon DynamoDB, you could use the following
command:

```bash
node dist-tools/browser-builder.js dynamodb-2011-12-05,dynamodb-2012-08-10
```

Available service identifiers and API versions can be found by looking at the
file list in https://github.com/aws/aws-sdk-js/tree/master/lib/services/api

#### Building All Services

Finally, you can build **all services** (and API versions) by passing "all"
as a command-line argument:

```bash
node dist-tools/browser-builder.js all > aws-sdk-full.js
```

## The Build Server

The `dist-tools` directory also comes with a utility server that can bundle
and serve the SDK over HTTP. To launch the server, type:

```bash
node dist-tools/server.js
```

You can then access a bundled version of the SDK by hitting either:

```no-highlight
http://localhost:8080/aws-sdk.js
```

or

```no-highlight
http://localhost:8080/aws-sdk.min.js
```

For the uncompressed or compressed versions.

### Loading Specific Services

The build server can also bundle custom services by accepting a query string
to the respecitve bundle URLs with the services and API versions to be used.
The syntax for this is the same as the builder tool syntax on the command-line,
but you can also use a conventional query string syntax. An example to load
the DynamoDB 2011-12-05 API version and latest S3 service would look like:

```no-highlight
http://localhost:8080/aws-sdk.min.js?dynamodb=2011-12-05&s3
```


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.execution;

import com.intellij.ide.actions.runAnything.activity.RunAnythingProvider;
import com.intellij.ide.actions.runAnything.groups.RunAnythingHelpGroup;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

/**
 * @author ibessonov
 */
public class MavenRunAnythingHelpGroup extends RunAnythingHelpGroup {

  @NotNull
  @Override
  public String getTitle() {
    return "Maven";
  }

  @NotNull
  @Override
  public Collection<RunAnythingProvider> getProviders() {
    return ContainerUtil.immutableSingletonList(RunAnythingProvider.EP_NAME.findExtension(MavenRunAnythingProvider.class));
  }
}


text:
#ifndef NXOGRE_DISTANCEJOINT_H
#define NXOGRE_DISTANCEJOINT_H

#include "NxOgreStable.h"
#include "NxOgreCommon.h"
#include "NxOgreJoint.h"

namespace NxOgre
{

/*! class. DistanceJoint
    desc.
        The distance joint tries to maintain a certain minimum and/or maximum distance between two points
        attached to a pair of actors. It can be set to springy in order to behave like a rubber band.
*/
class NxOgrePublicClass DistanceJoint : public Joint
{

  NXOGRE_GC_FRIEND_NEW3
  NXOGRE_GC_FRIEND_DELETE

  public: // Functions

  protected: // Functions

  /** \internal Private Constructor. Use Scene::createDistanceJoint.
  */
                                              DistanceJoint(RigidBody* first, RigidBody* second, const DistanceJointDescription&);

  /** \internal Private Destructor. Use Scene::destroyJoint.
  */
                                             ~DistanceJoint();

  protected: // Protected

                         NxDistanceJoint*     mDistanceJoint;

}; // class DistanceJoint

} // namespace NxOgre

#endif


text:
Template.posts.events({
	'click .load-more': function(event, instance) {
		event.preventDefault();

		//get current value for limit, i.e, how many posts are currently displayed
		var limit = instance.limit.get();

		//increase limit by 5 and update it
		limit += 100;
		instance.limit.set(limit);
	}
});

Template.posts.helpers({
	//the posts cursor
	posts: function() {
		return Template.instance().posts();
	},
	//are there more posts to show?
	hasMorePosts: function() {
		return Template.instance().posts().count() >= Template.instance().limit.get();
	}
});

Template.posts.onCreated(function() {
	//1. initialization
	var instance = this;

	//initialize the reactive variables
	instance.loaded = new ReactiveVar(0);
	instance.limit = new ReactiveVar(100);

	//2. Autorun

	//will re-run when the "limit" reactive variables changes
	instance.autorun(function () {

		//get the limit
		var limit = instance.limit.get();

		console.log("Asking for "+limit+" posts...")

		//subscribe to the posts publication
		var subscription = instance.subscribe('posts', limit);

		//if subscription is ready set limit to newLimit
		if(subscription.ready()) {
			console.log("> Received "+limit+" posts. \n\n")
			instance.loaded.set(limit);
		} else {
			console.log("> Subscription is not ready yet. \n\n");
		}
	});

	//3. Cursor

	instance.posts = function() {
		return Posts.find({}, {limit: instance.loaded.get()});
	}
});


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.books.model;

/**
 * Model definition for Bookshelves.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Books API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Bookshelves extends com.google.api.client.json.GenericJson {

  /**
   * A list of bookshelves.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<Bookshelf> items;

  static {
    // hack to force ProGuard to consider Bookshelf used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(Bookshelf.class);
  }

  /**
   * Resource type.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String kind;

  /**
   * A list of bookshelves.
   * @return value or {@code null} for none
   */
  public java.util.List<Bookshelf> getItems() {
    return items;
  }

  /**
   * A list of bookshelves.
   * @param items items or {@code null} for none
   */
  public Bookshelves setItems(java.util.List<Bookshelf> items) {
    this.items = items;
    return this;
  }

  /**
   * Resource type.
   * @return value or {@code null} for none
   */
  public java.lang.String getKind() {
    return kind;
  }

  /**
   * Resource type.
   * @param kind kind or {@code null} for none
   */
  public Bookshelves setKind(java.lang.String kind) {
    this.kind = kind;
    return this;
  }

  @Override
  public Bookshelves set(String fieldName, Object value) {
    return (Bookshelves) super.set(fieldName, value);
  }

  @Override
  public Bookshelves clone() {
    return (Bookshelves) super.clone();
  }

}


text:
Bank:

						Posted on
						,
						Updated on

			<fieldset>

					Username

						<input type="text" id="username" name="username" class="form-control" data-ng-model="controller.bank.username" placeholder="Username"  disabled>

					Email

						<input type="email" id="email" name="email" class="form-control" data-ng-model="controller.bank.email" placeholder="Email" disabled>

					Account balance

						<input type="text" id="account_balance" name="account_balance" class="form-control" data-ng-model="controller.bank.account.balance" jm-rs-number-format placeholder="account_balance" disabled>

					State

						<input type="text" id="state" name="state" class="form-control" data-ng-model="controller.bank.state" placeholder="State" disabled>

			</fieldset>


text:
namespace bp = boost::python;

/// @brief Type that allows for registration of conversions from
///        python iterable types.
struct iterable_converter
{
/// @note Registers converter from a python interable type to the
///       provided type.
    template <typename Container> iterable_converter& from_python()
    {
        bp::converter::registry::push_back(
                &iterable_converter::convertible,
                &iterable_converter::construct<Container>,
                bp::type_id<Container>());
        return *this;
    }

    /// @brief Check if PyObject is iterable.
    static void* convertible(PyObject* object)
    {
        return PyObject_GetIter(object) ? object : NULL;
    }

    /// @brief Convert iterable PyObject to C++ container type.
    ///
    /// Container Concept requirements:
    ///
    ///   * Container::value_type is CopyConstructable.
    ///   * Container can be constructed and populated with two iterators.
    ///     I.e. Container(begin, end)
    template <typename Container>
    static void construct(PyObject* object,
            bp::converter::rvalue_from_python_stage1_data* data)
    {
        namespace python = bp;
        // Object is a borrowed reference, so create a handle indicting
        // it is
        // borrowed for proper reference counting.
        bp::handle<> handle(bp::borrowed(object));

        // Obtain a handle to the memory block that the converter
        // has allocated
        // for the C++ type.
        typedef bp::converter::rvalue_from_python_storage<Container>
                                                     storage_type;
        void* storage =
            reinterpret_cast<storage_type*>(data)->storage.bytes;

        typedef bp::stl_input_iterator<typename Container::value_type>
                                                         iterator;

        // Allocate the C++ type into the converter's memory block, and
        // assign
        // its handle to the converter's convertible variable.  The C++
        // container is populated by passing the begin and end iterators of
        // the python object to the container's constructor.
        // TODO: POSSIBLE MEMORY LEAK?
        data->convertible = new (storage) Container(
            iterator(bp::object(handle)), // begin
            iterator());                      // end
    }
};
#endif


text:
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js tools             **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013-2014, LAMP/EPFL   **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */

package org.scalajs.core.tools.classpath.builder

import scala.collection.mutable
import scala.annotation.tailrec

import java.util.zip._
import java.io.{InputStream, InputStreamReader, Reader}

import org.scalajs.core.tools.io._
import org.scalajs.core.tools.jsdep.JSDependencyManifest

trait JarTraverser extends ClasspathContentHandler with FileSystem {

  private val jsFiles = mutable.Map.empty[String, MemVirtualJSFile]

  /** Traverse a Jar and return a version */
  protected def traverseJar(jar: File): String = {
    val zipStream = new ZipInputStream(toInputStream(jar))

    try readEntries(zipStream, getAbsolutePath(jar))
    finally zipStream.close()

    for {
      (relPath, jsFile) <- jsFiles
      if jsFile.content != "" // drop if this is just a lone sourcemap
    } handleJS(relPath, jsFile)

    getGlobalVersion(jar)
  }

  private def getOrCreateJSFile(relPath: String, fullPath: String, fn: String) =
    jsFiles.getOrElseUpdate(relPath, new MemVirtualJSFile(fullPath) {
      override val name = fn
    })

  @tailrec
  private def readEntries(in: ZipInputStream, jarPath: String): Unit = {
    val entry = in.getNextEntry()
    if (entry != null) {
      readEntry(entry, in, jarPath)
      readEntries(in, jarPath)
    }
  }

  private def readEntry(entry: ZipEntry, in: InputStream, jarPath: String) = {
    val longName = entry.getName
    val shortName = VirtualFile.nameFromPath(longName)
    val fullPath = jarPath + "#" + longName

    def entryReader: Reader = new InputStreamReader(in, "UTF-8")
    def entryContent: String = IO.readInputStreamToString(in)
    def entryBinaryContent: Array[Byte] = IO.readInputStreamToByteArray(in)
    def entryVersion: Option[String] = Some(entry.getTime.toString)

    if (longName == JSDependencyManifest.ManifestFileName)
      handleDepManifest(JSDependencyManifest.read(entryReader))
    else if (longName.endsWith(".js")) {
      val relPath = longName
      getOrCreateJSFile(relPath, fullPath, shortName)
        .withContent(entryContent)
        .withVersion(entryVersion)
    } else if (longName.endsWith(".js.map")) {
      // assume the source map of a JS file
      val relPath = longName.dropRight(".map".length)
      getOrCreateJSFile(relPath, fullPath, shortName)
        .withSourceMap(Some(entryContent))
    } else if (longName.endsWith(".sjsir")) {
      def vf = new MemVirtualSerializedScalaJSIRFile(fullPath) {
        override val name = shortName
      }.withContent(entryBinaryContent)
       .withVersion(entryVersion)

      handleIR(longName, vf)
    }
  }
}


text:
import mock
import os
import time
from tempfile import mkdtemp
from shutil import rmtree

from twisted.trial import unittest
from twisted.internet import defer

from scrapy.contrib.pipeline.files import FilesPipeline, FSFilesStore
from scrapy.item import Item, Field
from scrapy.http import Request, Response
from scrapy.settings import Settings

def _mocked_download_func(request, info):
    response = request.meta.get('response')
    return response() if callable(response) else response

class FilesPipelineTestCase(unittest.TestCase):

    def setUp(self):
        self.tempdir = mkdtemp()
        self.pipeline = FilesPipeline.from_settings(Settings({'FILES_STORE': self.tempdir}))
        self.pipeline.download_func = _mocked_download_func
        self.pipeline.open_spider(None)

    def tearDown(self):
        rmtree(self.tempdir)

    def test_file_path(self):
        image_path = self.pipeline.file_key
        self.assertEqual(image_path("https://dev.mydeco.com/mydeco.pdf"),
                         'full/c9b564df929f4bc635bdd19fde4f3d4847c757c5.pdf')
        self.assertEqual(image_path("http://www.maddiebrown.co.uk///catalogue-items//image_54642_12175_95307.txt"),
                         'full/4ce274dd83db0368bafd7e406f382ae088e39219.txt')
        self.assertEqual(image_path("https://dev.mydeco.com/two/dirs/with%20spaces%2Bsigns.doc"),
                         'full/94ccc495a17b9ac5d40e3eabf3afcb8c2c9b9e1a.doc')
        self.assertEqual(image_path("http://www.dfsonline.co.uk/get_prod_image.php?img=status_0907_mdm.jpg"),
                         'full/4507be485f38b0da8a0be9eb2e1dfab8a19223f2.jpg')
        self.assertEqual(image_path("http://www.dorma.co.uk/images/product_details/2532/"),
                         'full/97ee6f8a46cbbb418ea91502fd24176865cf39b2')
        self.assertEqual(image_path("http://www.dorma.co.uk/images/product_details/2532"),
                         'full/244e0dd7d96a3b7b01f54eded250c9e272577aa1')

    def test_fs_store(self):
        assert isinstance(self.pipeline.store, FSFilesStore)
        self.assertEqual(self.pipeline.store.basedir, self.tempdir)

        key = 'some/image/key.jpg'
        path = os.path.join(self.tempdir, 'some', 'image', 'key.jpg')
        self.assertEqual(self.pipeline.store._get_filesystem_path(key), path)

    @defer.inlineCallbacks
    def test_file_not_expired(self):
        item_url = "http://example.com/file.pdf"
        item = _create_item_with_files(item_url)
        patchers = [
            mock.patch.object(FilesPipeline, 'inc_stats', return_value=True),
            mock.patch.object(FSFilesStore, 'stat_file', return_value={
                'checksum': 'abc', 'last_modified': time.time()}),
            mock.patch.object(FilesPipeline, 'get_media_requests',
                              return_value=[_prepare_request_object(item_url)])
        ]
        for p in patchers:
            p.start()

        result = yield self.pipeline.process_item(item, None)
        self.assertEqual(result['files'][0]['checksum'], 'abc')

        for p in patchers:
            p.stop()

    @defer.inlineCallbacks
    def test_file_expired(self):
        item_url = "http://example.com/file2.pdf"
        item = _create_item_with_files(item_url)
        patchers = [
            mock.patch.object(FSFilesStore, 'stat_file', return_value={
                'checksum': 'abc',
                'last_modified': time.time() - (FilesPipeline.EXPIRES * 60 * 60 * 24 * 2)}),
            mock.patch.object(FilesPipeline, 'get_media_requests',
                              return_value=[_prepare_request_object(item_url)]),
            mock.patch.object(FilesPipeline, 'inc_stats', return_value=True)
        ]
        for p in patchers:
            p.start()

        result = yield self.pipeline.process_item(item, None)
        self.assertNotEqual(result['files'][0]['checksum'], 'abc')

        for p in patchers:
            p.stop()

class FilesPipelineTestCaseFields(unittest.TestCase):

    def test_item_fields_default(self):
        from scrapy.contrib.pipeline.files import FilesPipeline
        class TestItem(Item):
            name = Field()
            file_urls = Field()
            files = Field()
        url = 'http://www.example.com/files/1.txt'
        item = TestItem({'name': 'item1', 'file_urls': [url]})
        pipeline = FilesPipeline.from_settings(Settings({'FILES_STORE': 's3://example/files/'}))
        requests = list(pipeline.get_media_requests(item, None))
        self.assertEqual(requests[0].url, url)
        results = [(True, {'url': url})]
        pipeline.item_completed(results, item, None)
        self.assertEqual(item['files'], [results[0][1]])

    def test_item_fields_override_settings(self):
        from scrapy.contrib.pipeline.files import FilesPipeline
        class TestItem(Item):
            name = Field()
            files = Field()
            stored_file = Field()
        url = 'http://www.example.com/files/1.txt'
        item = TestItem({'name': 'item1', 'files': [url]})
        pipeline = FilesPipeline.from_settings(Settings({'FILES_STORE': 's3://example/files/',
                'FILES_URLS_FIELD': 'files', 'FILES_RESULT_FIELD': 'stored_file'}))
        requests = list(pipeline.get_media_requests(item, None))
        self.assertEqual(requests[0].url, url)
        results = [(True, {'url': url})]
        pipeline.item_completed(results, item, None)
        self.assertEqual(item['stored_file'], [results[0][1]])

class ItemWithFiles(Item):
    file_urls = Field()
    files = Field()

def _create_item_with_files(*files):
    item = ItemWithFiles()
    item['file_urls'] = files
    return item

def _prepare_request_object(item_url):
    return Request(
        item_url,
        meta={'response': Response(item_url, status=200, body='data')})

if __name__ == "__main__":
    unittest.main()


text:
package org.gradle.internal.component.local.model;

import org.gradle.api.artifacts.component.ProjectComponentSelector;

public interface ProjectDependencyMetaData extends DslOriginDependencyMetaData {
    ProjectComponentSelector getSelector();
}


text:
<?php

namespace Grav\Framework\Cache\Adapter;

use Grav\Framework\Cache\AbstractCache;

/**
 * Cache class for PSR-16 compatible "Simple Cache" implementation using session backend.
 *
 * @package Grav\Framework\Cache
 */
class SessionCache extends AbstractCache
{
    public const VALUE = 0;
    public const LIFETIME = 1;

    /**
     * @param string $key
     * @param mixed $miss
     * @return mixed
     */
    public function doGet($key, $miss)
    {
        $stored = $this->doGetStored($key);

        return $stored ? $stored[self::VALUE] : $miss;
    }

    /**
     * @param string $key
     * @param mixed $value
     * @param int $ttl
     * @return bool
     */
    public function doSet($key, $value, $ttl)
    {
        $stored = [self::VALUE => $value];
        if (null !== $ttl) {
            $stored[self::LIFETIME] = time() + $ttl;
        }

        $_SESSION[$this->getNamespace()][$key] = $stored;

        return true;
    }

    /**
     * @param string $key
     * @return bool
     */
    public function doDelete($key)
    {
        unset($_SESSION[$this->getNamespace()][$key]);

        return true;
    }

    /**
     * @return bool
     */
    public function doClear()
    {
        unset($_SESSION[$this->getNamespace()]);

        return true;
    }

    /**
     * @param string $key
     * @return bool
     */
    public function doHas($key)
    {
        return $this->doGetStored($key) !== null;
    }

    /**
     * @return string
     */
    public function getNamespace()
    {
        return 'cache-' . parent::getNamespace();
    }

    /**
     * @param string $key
     * @return mixed|null
     */
    protected function doGetStored($key)
    {
        $stored = $_SESSION[$this->getNamespace()][$key] ?? null;

        if (isset($stored[self::LIFETIME]) && $stored[self::LIFETIME] < time()) {
            unset($_SESSION[$this->getNamespace()][$key]);
            $stored = null;
        }

        return $stored ?: null;
    }
}


text:
package uk.co.bristlecone.vpt.runner.console.impl;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;

import org.junit.Test;

import uk.co.bristlecone.vpt.VptRuntimeException;
import uk.co.bristlecone.vpt.runner.console.impl.ConsoleConfiguration;
import uk.co.bristlecone.vpt.runner.impl.Configuration;

public class ConsoleConfigurationTest {
  private static final Path EXP_SRC = Paths.get("src/main/java");
  private static final Path EXP_DEST = Paths.get("src/main/resources");
  private static final String EXP_PKG_BASE = "some.package.base.runner";
  private static final Pattern EXP_REGEX = Pattern.compile("some\\.package\\.base\\.voltdb\\.(.*)");
  private static final String[] ARGS_WITH_ALL_EXPECTED_OPTIONS = new String[] { "--source=" + EXP_SRC,
      "--destination=" + EXP_DEST, "--packagebase=" + EXP_PKG_BASE, "--regexsuffix=" + EXP_REGEX.pattern() };
  private static final String[] ARGS_WITH_UNEXPECTED_OPTION = new String[] { "--source=someSourceDir",
      "--destination=someDestinationDir", "--packagebase=somePackageBase", "--regexsuffix=someRegex", "--foo=bar" };
  private static final String[] ARGS_WITH_MISSING_OPTION = new String[] { "--source=someSourceDir",
      "--destination=someDestinationDir", "--packagebase=somePackageBase" };
  private static final String[] ARGS_WITH_HELP = new String[] { "--help", "--source=someSourceDir" };
  private static final String[] ARGS_WITH_VERSION = new String[] { "--source=someSourceDir", "--version" };

  @Test
  public void sourceDirReturnsExpectedValue() {
    final Configuration testee = new ConsoleConfiguration(ARGS_WITH_ALL_EXPECTED_OPTIONS);
    assertThat(testee.sourceDir(), is(equalTo(EXP_SRC)));
  }

  @Test
  public void destDirReturnsExpectedValue() {
    final Configuration testee = new ConsoleConfiguration(ARGS_WITH_ALL_EXPECTED_OPTIONS);
    assertThat(testee.destDir(), is(equalTo(EXP_DEST)));
  }

  @Test
  public void packageBaseReturnsExpectedValue() {
    final Configuration testee = new ConsoleConfiguration(ARGS_WITH_ALL_EXPECTED_OPTIONS);
    assertThat(testee.packageBase(), is(equalTo(EXP_PKG_BASE)));
  }

  @Test
  public void regexSuffixReturnsExpectedValue() {
    final Configuration testee = new ConsoleConfiguration(ARGS_WITH_ALL_EXPECTED_OPTIONS);
    assertThat(testee.regexSuffix().pattern(), is(equalTo(EXP_REGEX.pattern())));
  }

  @Test
  public void showHelpIsSetIfHelpOptionIsSet() {
    final ConsoleConfiguration testee = new ConsoleConfiguration(ARGS_WITH_HELP);
    assertThat(testee.showHelp(), is(equalTo(true)));
    assertThat(testee.showVersion(), is(equalTo(false)));
  }

  @Test
  public void showVersionIsSetIfVersionOptionIsSet() {
    final ConsoleConfiguration testee = new ConsoleConfiguration(ARGS_WITH_VERSION);
    assertThat(testee.showVersion(), is(equalTo(true)));
    assertThat(testee.showHelp(), is(equalTo(false)));
  }

  @Test(expected = VptRuntimeException.class)
  public void constructorThrowsOnUnexpectedOption() {
    new ConsoleConfiguration(ARGS_WITH_UNEXPECTED_OPTION);
  }

  @Test(expected = VptRuntimeException.class)
  public void constructorThrowsOnMissingOption() {
    new ConsoleConfiguration(ARGS_WITH_MISSING_OPTION);
  }
}


text:
#include "GameResources.h"
#include "Defines.h"
#include "Fire.h"
#include "Weapon.h"
#include "Bonus.h"

namespace Duel6 {
    void GameResources::load(Console &console, Sound &sound, TextureManager &textureManager) {
        console.printLine("\n===Initializing game resources===");
        console.printLine("\n...Weapon initialization");
        Weapon::initialize(sound, textureManager);
        console.printLine("...Building water-list");
        Water::initialize(sound, textureManager);
        console.printLine("...Loading game sounds");
        roundStartSound = sound.loadSample("sound/game/round-start.wav");
        gameOverSound = sound.loadSample("sound/game/game-over.wav");
        console.printLine(Format("...Loading block meta data: {0}") << D6_FILE_BLOCK_META);
        blockMeta = Block::loadMeta(D6_FILE_BLOCK_META);
        console.printLine(Format("...Loading block textures: {0}") << D6_TEXTURE_BLOCK_PATH);
        blockTextures = textureManager.loadStack(D6_TEXTURE_BLOCK_PATH, TextureFilter::Linear, true);
        console.printLine(Format("...Loading explosion textures: {0}") << D6_TEXTURE_EXPL_PATH);
        explosionTextures = textureManager.loadStack(D6_TEXTURE_EXPL_PATH, TextureFilter::Nearest, true);
        console.printLine(Format("...Loading bonus textures: {0}") << D6_TEXTURE_EXPL_PATH);
        bonusTextures = textureManager.loadStack(D6_TEXTURE_BONUS_PATH, TextureFilter::Linear, true);
        console.printLine(Format("...Loading elevator textures: {0}") << D6_TEXTURE_ELEVATOR_PATH);
        elevatorTextures = textureManager.loadStack(D6_TEXTURE_ELEVATOR_PATH, TextureFilter::Linear, true);

        console.printLine(Format("...Loading background textures: {0}") << D6_TEXTURE_BCG_PATH);
        bcgTextures = textureManager.loadDict(D6_TEXTURE_BCG_PATH, TextureFilter::Linear, true);
        std::string animationPath(D6_TEXTURE_MAN_PATH);
        animationPath += "man.ase";
        playerAnimation = textureManager.loadAnimation(animationPath);
        console.printLine(Format("...Loading fire textures: {0}") << D6_TEXTURE_FIRE_PATH);
        for (const FireType &fireType : FireType::values()) {
            Texture texture = textureManager.loadStack(Format("{0}{1,3|0}/") << D6_TEXTURE_FIRE_PATH << fireType.getId(),
                                                       TextureFilter::Nearest, true);
            fireTextures[fireType.getId()] = texture;
        }

        Texture burn = textureManager.loadStack("textures/fire/burn/", TextureFilter::Linear, true);
        burningTexture = burn;
    }
}


text:
<?php
include '../../src/Cloudinary.php';
include '../../src/Uploader.php';
if (file_exists('settings.php')) {
  include 'settings.php';
}

$sample_paths = array(
  "pizza" => getcwd(). DIRECTORY_SEPARATOR . "pizza.jpg",
  "lake" => getcwd(). DIRECTORY_SEPARATOR . "lake.jpg",
  "couple" => "http://res.cloudinary.com/demo/image/upload/couple.jpg",
);

$default_upload_options = array("tags" => "basic_sample");
$eager_params = array("width" => 200, "height" => 150, "crop" => "scale");
$files = array();

# This function, when called uploads all files into your Cloudinary storage and saves the
# metadata to the $files array.
function do_uploads() {
  global $files, $sample_paths, $default_upload_options, $eager_params;

  # public_id will be generated on Cloudinary's backend.
  $files["unnamed_local"] = \Cloudinary\Uploader::upload($sample_paths["pizza"],
    $default_upload_options);

  # Same image, uploaded with a public_id
  $files["named_local"] = \Cloudinary\Uploader::upload($sample_paths["pizza"],
    array_merge($default_upload_options, array("public_id" => "custom_name")));

  # Eager transformations are applied as soon as the file is uploaded, instead of waiting
  # for a user to request them.
  $files["eager"] = \Cloudinary\Uploader::upload($sample_paths["lake"],
    array_merge($default_upload_options, array(
      "public_id" => "eager_custom_name",
      "eager" => $eager_params,
    )
  ));

  # In the two following examples, the file is fetched from a remote URL and stored in Cloudinary.
  # This allows you to apply the same transformations, and serve those using Cloudinary's CDN layer.
  $files["remote"] = \Cloudinary\Uploader::upload($sample_paths["couple"],
    $default_upload_options);

  $files["remote_trans"] = \Cloudinary\Uploader::upload($sample_paths["couple"],
    array_merge($default_upload_options, array(
      "width" => 500,
      "height" => 500,
      "crop" => "fit",
      "effect" => "saturation:-70",
    ))
  );
}

# Output an image in HTML along with provided caption and public_id
function show_image($img, $options = array(), $caption = "") {
    $options["format"] = $img["format"];
	$transformation_url = cloudinary_url($img["public_id"], $options);

	echo "
";
    echo "
" . $caption . "
";
    echo "" .
      cl_image_tag($img["public_id"], $options) . "";
    echo "
" . $img["public_id"] . "
";

	echo "
" . $transformation_url . "
";
	echo "
";
}
?>

    <meta charset="utf-8">
    <title>Cloudinary - Basic PHP Sample</title>
    <link rel="shortcut icon"
 href="<?php echo cloudinary_url("http://cloudinary.com/favicon.png",
       array("type" => "fetch")); ?>" />

    <?php
      echo "
Cloudinary - Basic PHP Sample";
      echo "
Uploading ...
";
      do_uploads();
      echo "
... Done uploading!
";
    ?>

    <?php
      show_image($files["unnamed_local"],
        array("width" => 200, "height" => 150, "crop" => "fill"), "Local file, Fill 200x150");

      show_image($files["named_local"],
        array("width" => 200, "height" => 150, "crop" => "fit"), "Local file, custom public ID, Fit into 200x150");

      show_image($files["eager"], $eager_params, "Local file, Eager trasnformation of scaling to 200x150");

      show_image($files["remote"],
        array("width" => 200, "height" => 150, "crop" => "thumb", "gravity" => "faces"),
        "Uploaded remote image, Face detection based 200x150 thumbnail");

      show_image($files["remote_trans"],
        array("width" => 200, "height" => 150, "crop" => "fill", "gravity" => "face", "radius" => 10, "effect" => "sepia"),
        "Uploaded remote image, Fill 200x150, round corners, apply the sepia effect");
    ?>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.storage.generated;

import com.azure.core.util.Context;

/** Samples for Operations List. */
public final class OperationsListSamples {
    /*
     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2022-05-01/examples/OperationsList.json
     */
    /**
     * Sample code: OperationsList.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void operationsList(com.azure.resourcemanager.AzureResourceManager azure) {
        azure.storageAccounts().manager().serviceClient().getOperations().list(Context.NONE);
    }
}


text:
using ArangoDB.Client.Advanced;
using ArangoDB.Client.ChangeTracking;
using ArangoDB.Client.Data;
using ArangoDB.Client.Http;
using ArangoDB.Client.Query;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ArangoDB.Client
{
    public interface IArangoDatabase : IDisposable
    {
        IAdvancedOperation Advanced { get; set; }

        IHttpConnection Connection { get; set; }

        DocumentTracker ChangeTracker { get; set; }

        DatabaseSharedSetting SharedSetting { get; set; }

        DatabaseSetting Setting { get; set; }

        IDocumentCollection<T> Collection<T>();

        IEdgeCollection<T> EdgeCollection<T>();

        IDocumentCollection Collection(string collection);

        IEdgeCollection EdgeCollection(string collection);

        ICursor<T> CreateStatement<T>(string query, IList<QueryParameter> bindVars = null, bool? count = null,
            int? batchSize = null, TimeSpan? ttl = null, QueryOption options = null);

        ArangoQueryable<T> Query<T>();

        ArangoQueryable<AQL> Query();

        string NameOf<T>();

        string NameOf(Type type);

        string NameOf<T>(Expression<Func<T, object>> member);

        void Log(string message);

        bool LoggerAvailable { get; }

        ///
        /// Get Document JsonObject and Identifiers
        ///
        /// <param name="id">id of document</param>
        /// <returns>A DocumentContainer</returns>
        DocumentContainer FindDocumentInfo(string id);

        ///
        /// Get Document JsonObject and Identifiers
        ///
        /// <param name="id">document object</param>
        /// <returns>A DocumentContainer</returns>
        DocumentContainer FindDocumentInfo(object document);

        ///
        /// Creates a new document in the collection
        ///
        /// <param name="documents">Representation of the documents</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns>Documents identifiers</returns>
        Task<List<IDocumentIdentifierResult>> InsertMultipleAsync<T>(IList documents, bool? waitForSync = null, Action<List<BaseResult>> baseResults = null);

        ///
        /// Creates a new document in the collection
        ///
        /// <param name="documents">Representation of the documents</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns>Documents identifiers</returns>
        List<IDocumentIdentifierResult> InsertMultiple<T>(IList documents, bool? waitForSync = null, Action<List<BaseResult>> baseResults = null);

        ///
        /// Creates a new document in the collection for specific type
        ///
        /// <param name="document">Representation of the document</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns>Document identifiers</returns>
        Task<IDocumentIdentifierResult> InsertAsync<T>(object document, bool? waitForSync = null, Action<BaseResult> baseResult = null);

        ///
        /// Creates a new document in the collection for specific type
        ///
        /// <param name="document">Representation of the document</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns>Document identifiers</returns>
        IDocumentIdentifierResult Insert<T>(object document, bool? waitForSync = null, Action<BaseResult> baseResult = null);

        ///
        /// Completely updates the document
        ///
        /// <param name="document">Representation of the new document</param>
        /// <param name="rev">Conditionally replace a document based on revision id</param>
        /// <param name="policy">To control the update behavior in case there is a revision mismatch</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns>Document identifiers</returns>
        IDocumentIdentifierResult Replace<T>(object document, bool? waitForSync = null, bool? ignoreRevs = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Completely updates the document
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <param name="document">Representation of the new document</param>
        /// <param name="rev">Conditionally replace a document based on revision id</param>
        /// <param name="policy">To control the update behavior in case there is a revision mismatch</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns>Document identifiers</returns>
        Task<IDocumentIdentifierResult> ReplaceAsync<T>(object document, bool? waitForSync = null, bool? ignoreRevs = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Completely updates the document with no change tracking
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <param name="document">Representation of the new document</param>
        /// <param name="rev">Conditionally replace a document based on revision id</param>
        /// <param name="policy">To control the update behavior in case there is a revision mismatch</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns>Document identifiers</returns>
        IDocumentIdentifierResult ReplaceById<T>(string id, object document, bool? waitForSync = null, bool? ignoreRevs = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Completely updates the document with no change tracking
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <param name="document">Representation of the new document</param>
        /// <param name="rev">Conditionally replace a document based on revision id</param>
        /// <param name="policy">To control the update behavior in case there is a revision mismatch</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns>Document identifiers</returns>
        Task<IDocumentIdentifierResult> ReplaceByIdAsync<T>(string id, object document, bool? waitForSync = null, bool? ignoreRevs = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        ///Partially updates the document without change tracking
        ///
        ///<param name="id">The document handle or key of document</param>
        ///<param name="document">Representation of the patch document</param>
        ///<param name="keepNull">For remove any attributes from the existing document that are contained in the patch document with an attribute value of null</param>
        ///<param name="mergeObjects">Controls whether objects (not arrays) will be merged if present in both the existing and the patch document</param>
        ///<param name="rev">Conditionally replace a document based on revision id</param>
        ///<param name="policy">To control the update behavior in case there is a revision mismatch</param>
        ///<param name="waitForSync">Wait until document has been synced to disk</param>
        ///<returns>Document identifiers</returns>
        IDocumentIdentifierResult UpdateById<T>(string id, object document, bool? keepNull = null, bool? mergeObjects = null, bool? waitForSync = null, bool? ignoreRevs = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        ///Partially updates the document without change tracking
        ///
        ///<param name="id">The document handle or key of document</param>
        ///<param name="document">Representation of the patch document</param>
        ///<param name="keepNull">For remove any attributes from the existing document that are contained in the patch document with an attribute value of null</param>
        ///<param name="mergeObjects">Controls whether objects (not arrays) will be merged if present in both the existing and the patch document</param>
        ///<param name="rev">Conditionally replace a document based on revision id</param>
        ///<param name="policy">To control the update behavior in case there is a revision mismatch</param>
        ///<param name="waitForSync">Wait until document has been synced to disk</param>
        ///<returns>Document identifiers</returns>
        Task<IDocumentIdentifierResult> UpdateByIdAsync<T>(string id, object document, bool? keepNull = null, bool? mergeObjects = null, bool? waitForSync = null, bool? ignoreRevs = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        ///Partially updates the document
        ///
        ///<param name="document">Representation of the patch document</param>
        ///<param name="keepNull">For remove any attributes from the existing document that are contained in the patch document with an attribute value of null</param>
        ///<param name="mergeObjects">Controls whether objects (not arrays) will be merged if present in both the existing and the patch document</param>
        ///<param name="policy">To control the update behavior in case there is a revision mismatch</param>
        ///<param name="waitForSync">Wait until document has been synced to disk</param>
        ///<returns>Document identifiers</returns>
        IDocumentIdentifierResult Update<T>(object document, bool? keepNull = null, bool? mergeObjects = null, bool? waitForSync = null, bool? ignoreRevs = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        ///Partially updates the document
        ///
        ///<param name="document">Representation of the patch document</param>
        ///<param name="keepNull">For remove any attributes from the existing document that are contained in the patch document with an attribute value of null</param>
        ///<param name="mergeObjects">Controls whether objects (not arrays) will be merged if present in both the existing and the patch document</param>
        ///<param name="policy">To control the update behavior in case there is a revision mismatch</param>
        ///<param name="waitForSync">Wait until document has been synced to disk</param>
        ///<returns>Document identifiers</returns>
        Task<IDocumentIdentifierResult> UpdateAsync<T>(object document, bool? keepNull = null, bool? mergeObjects = null, bool? waitForSync = null, bool? ignoreRevs = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Deletes the document without change tracking
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <param name="rev">Conditionally replace a document based on revision id</param>
        /// <param name="policy">To control the update behavior in case there is a revision mismatch</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns></returns>
        IDocumentIdentifierResult RemoveById<T>(string id, bool? waitForSync = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Deletes the document without change tracking
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <param name="rev">Conditionally replace a document based on revision id</param>
        /// <param name="policy">To control the update behavior in case there is a revision mismatch</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns></returns>
        Task<IDocumentIdentifierResult> RemoveByIdAsync<T>(string id, bool? waitForSync = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Deletes the document
        ///
        /// <param name="document">document reference</param>
        /// <param name="policy">To control the update behavior in case there is a revision mismatch</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns></returns>
        IDocumentIdentifierResult Remove<T>(object document, bool? waitForSync = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Deletes the document
        ///
        /// <param name="document">document reference</param>
        /// <param name="policy">To control the update behavior in case there is a revision mismatch</param>
        /// <param name="waitForSync">Wait until document has been synced to disk</param>
        /// <returns></returns>
        Task<IDocumentIdentifierResult> RemoveAsync<T>(object document, bool? waitForSync = null, string ifMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Reads a single document
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <returns>A Document</returns>
        T Document<T>(string id, string ifMatchRev = null, string ifNoneMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Reads a single document
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <returns>A Document</returns>
        Task<T> DocumentAsync<T>(string id, string ifMatchRev = null, string ifNoneMatchRev = null, Action<BaseResult> baseResult = null);

        ///
        /// Check if document exists
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <param name="onDocumentLoad">Runs when document loaded</param>
        /// <param name="baseResult">Runs when base result is ready</param>
        /// <returns>A Document</returns>
        Task<bool> ExistsAsync<T>(string id, Action<T> onDocumentLoad = null, Action<BaseResult> baseResult = null);

        ///
        /// Check if document exists
        ///
        /// <param name="id">The document handle or key of document</param>
        /// <param name="onDocumentLoad">Runs when document loaded</param>
        /// <param name="baseResult">Runs when base result is ready</param>
        /// <returns>A Document</returns>
        bool Exists<T>(string id, Action<T> onDocumentLoad = null, Action<BaseResult> baseResult = null);

        ///
        /// Read in or outbound edges
        ///
        /// <param name="vertexId">The document handle of the start vertex</param>
        /// <param name="direction">Selects in or out direction for edges. If not set, any edges are returned</param>
        /// <returns>Returns a list of edges starting or ending in the vertex identified by vertex document handle</returns>
        List<T> Edges<T>(string vertexId, EdgeDirection? direction = null, Action<BaseResult> baseResult = null);

        ///
        /// Read in or outbound edges
        ///
        /// <param name="vertexId">The document handle of the start vertex</param>
        /// <param name="direction">Selects in or out direction for edges. If not set, any edges are returned</param>
        /// <returns>Returns a list of edges starting or ending in the vertex identified by vertex document handle</returns>
        Task<List<T>> EdgesAsync<T>(string vertexId, EdgeDirection? direction = null, Action<BaseResult> baseResult = null);

        ///
        /// Returns all documents of a collections
        ///
        /// <param name="skip">The number of documents to skip in the query</param>
        /// <param name="limit">The maximal amount of documents to return. The skip is applied before the limit restriction</param>
        /// <param name="batchSize">Limits the number of results to be transferred in one batch</param>
        /// <returns>Returns a cursor</returns>
        ICursor<T> All<T>(int? skip = null, int? limit = null, int? batchSize = null);

        ///
        /// Finds all documents within a given range
        ///
        /// <param name="attribute">The attribute to check</param>
        /// <param name="left">The lower bound</param>
        /// <param name="right">The upper bound</param>
        /// <param name="closed">If true, use interval including left and right, otherwise exclude right, but include left</param>
        /// <param name="skip">The number of documents to skip in the query</param>
        /// <param name="limit">The maximal amount of documents to return. The skip is applied before the limit restriction</param>
        /// <param name="batchSize">Limits the number of results to be transferred in one batch</param>
        /// <returns>Returns a cursor</returns>
        ICursor<T> Range<T>(Expression<Func<T, object>> attribute, object left, object right, bool? closed = false,
            int? skip = null, int? limit = null, int? batchSize = null);

        ///
        /// Finds all documents matching a given example
        ///
        /// <param name="example">The example document</param>
        /// <param name="skip">The number of documents to skip in the query</param>
        /// <param name="limit">The maximal amount of documents to return. The skip is applied before the limit restriction</param>
        /// <param name="batchSize">Limits the number of results to be transferred in one batch</param>
        /// <returns>Returns a cursor</returns>
        ICursor<T> ByExample<T>(object example, int? skip = null, int? limit = null, int? batchSize = null);

        ///
        /// Returns the first document matching a given example
        ///
        /// <param name="example">The example document</param>
        /// <returns>A Document</returns>
        T FirstExample<T>(object example, Action<BaseResult> baseResult = null);

        ///
        /// Returns the first document matching a given example
        ///
        /// <param name="example">The example document</param>
        /// <returns>A Document</returns>
        Task<T> FirstExampleAsync<T>(object example, Action<BaseResult> baseResult = null);

        ///
        /// Returns a random document
        ///
        /// <returns>A Document</returns>
        T Any<T>(Action<BaseResult> baseResult = null);

        ///
        /// Returns a random document
        ///
        /// <returns>A Document</returns>
        Task<T> AnyAsync<T>(Action<BaseResult> baseResult = null);

        ///
        /// Retrieves information about the current database
        ///
        /// <returns>DatabaseInformation</returns>
        DatabaseInformation CurrentDatabaseInformation(Action<BaseResult> baseResult = null);

        ///
        /// Retrieves information about the current database
        ///
        /// <returns>DatabaseInformation</returns>
        Task<DatabaseInformation> CurrentDatabaseInformationAsync(Action<BaseResult> baseResult = null);

        ///
        /// List of accessible databases
        ///
        /// <returns>List of database names</returns>
        List<string> ListAccessibleDatabases(Action<BaseResult> baseResult = null);

        ///
        /// List of accessible databases
        ///
        /// <returns>List of database names</returns>
        Task<List<string>> ListAccessibleDatabasesAsync(Action<BaseResult> baseResult = null);

        ///
        /// List of databases
        ///
        /// <returns>List of database names</returns>
        List<string> ListDatabases(Action<BaseResult> baseResult = null);

        ///
        /// List of databases
        ///
        /// <returns>List of database names</returns>
        Task<List<string>> ListDatabasesAsync(Action<BaseResult> baseResult = null);

        ///
        /// Creates a database
        ///
        /// <param name="name">Name of the database</param>
        /// <param name="users">list of database user</param>
        /// <returns></returns>
        void CreateDatabase(string name, List<DatabaseUser> users = null, Action<BaseResult> baseResult = null);

        ///
        /// Creates a database
        ///
        /// <param name="name">Name of the database</param>
        /// <param name="users">list of database user</param>
        /// <returns></returns>
        Task CreateDatabaseAsync(string name, List<DatabaseUser> users = null, Action<BaseResult> baseResult = null);

        ///
        /// Drops the collection identified by collection-name
        ///
        /// <param name="name">Name of the collection</param>
        /// <param name="baseResult"></param>
        /// <returns>DropCollectionResult</returns>
        DropCollectionResult DropCollection(string name, Action<BaseResult> baseResult = null);

        ///
        /// Drops the collection identified by collection-name
        ///
        /// <param name="name">Name of the collection</param>
        /// <param name="baseResult"></param>
        /// <returns>DropCollectionResult</returns>
        Task<DropCollectionResult> DropCollectionAsync(string name, Action<BaseResult> baseResult = null);

        ///
        /// Creates a collection
        ///
        /// <param name="name">Name of the collection</param>
        /// <param name="waitForSync">If true then the data is synchronised to disk before returning from a document create, update, replace or removal operation</param>
        /// <param name="doCompact">Whether or not the collection will be compacted</param>
        /// <param name="journalSize"> The maximal size of a journal or datafile in bytes. The value must be at least 1048576 (1 MB).</param>
        /// <param name="isSystem"> If true, create a system collection. In this case collection-name should start with an underscore</param>
        /// <param name="isVolatile">If true then the collection data is kept in-memory only and not made persistent</param>
        /// <param name="type"> The type of the collection to create</param>
        /// <param name="numberOfShards">In a cluster, this value determines the number of shards to create for the collection</param>
        /// <param name="shardKeys">In a cluster, this attribute determines which document attributes are used to determine the target shard for documents</param>
        /// <returns>CreateCollectionResult</returns>
        CreateCollectionResult CreateCollection(string name, bool? waitForSync = null, bool? doCompact = null, double? journalSize = null,
            bool? isSystem = null, bool? isVolatile = null, CollectionType? type = null, int? numberOfShards = null, string shardKeys = null, CreateCollectionKeyOption keyOptions = null, int? IndexBuckets = null, Action<BaseResult> baseResult = null);

        ///
        /// List of collections
        ///
        /// <param name="excludeSystem">Exclude system collections</param>
        /// <param name="baseResult">Runs when base result is ready</param>
        /// <returns>List of collection properties</returns>
        List<CreateCollectionResult> ListCollections(bool excludeSystem = true, Action<BaseResult> baseResult = null);

        ///
        /// List of collections
        ///
        /// <param name="excludeSystem">Exclude system collections</param>
        /// <param name="baseResult">Runs when base result is ready</param>
        /// <returns>List of collection properties</returns>
        Task<List<CreateCollectionResult>> ListCollectionsAsync(bool excludeSystem = true, Action<BaseResult> baseResult = null);

        ///
        /// Creates a collection
        ///
        /// <param name="name">Name of the collection</param>
        /// <param name="waitForSync">If true then the data is synchronised to disk before returning from a document create, update, replace or removal operation</param>
        /// <param name="doCompact">Whether or not the collection will be compacted</param>
        /// <param name="journalSize"> The maximal size of a journal or datafile in bytes. The value must be at least 1048576 (1 MB).</param>
        /// <param name="isSystem"> If true, create a system collection. In this case collection-name should start with an underscore</param>
        /// <param name="isVolatile">If true then the collection data is kept in-memory only and not made persistent</param>
        /// <param name="type"> The type of the collection to create</param>
        /// <param name="numberOfShards">In a cluster, this value determines the number of shards to create for the collection</param>
        /// <param name="shardKeys">In a cluster, this attribute determines which document attributes are used to determine the target shard for documents</param>
        /// <returns>CreateCollectionResult</returns>
        Task<CreateCollectionResult> CreateCollectionAsync(string name, bool? waitForSync = null, bool? doCompact = null, double? journalSize = null,
            bool? isSystem = null, bool? isVolatile = null, CollectionType? type = null, int? numberOfShards = null, string shardKeys = null, CreateCollectionKeyOption keyOptions = null, int? IndexBuckets = null, Action<BaseResult> baseResult = null);

        ///
        /// Graph methods container
        ///
        /// <param name="graphName">The name of the graph</param>
        /// <returns></returns>
        IArangoGraph Graph(string graphName);

        ///
        /// Lists all graphs
        ///
        /// <param name="baseResult"></param>
        /// <returns>List<GraphIdentifierResult></returns>
        Task<List<GraphIdentifierResult>> ListGraphsAsync(Action<BaseResult> baseResult = null);

        ///
        /// Lists all graphs
        ///
        /// <param name="baseResult"></param>
        /// <returns>List<GraphIdentifierResult></returns>
        List<GraphIdentifierResult> ListGraphs(Action<BaseResult> baseResult = null);

        ///
        /// Finds documents near the given coordinate
        ///
        /// <param name="latitude">The latitude of the coordinate</param>
        /// <param name="longitude">The longitude of the coordinate</param>
        /// <param name="distance">If True, distances are returned in meters</param>
        /// <param name="skip">The number of documents to skip in the query</param>
        /// <param name="limit">The maximal amount of documents to return. The skip is applied before the limit restriction</param>
        /// <param name="batchSize">Limits the number of results to be transferred in one batch</param>
        /// <returns>Returns a cursor</returns>
        ICursor<T> Near<T>(double latitude, double longitude, Expression<Func<T, object>> distance = null, string geo = null
            , int? skip = null, int? limit = null, int? batchSize = null);

        ///
        /// Finds documents within a given radius around the coordinate
        ///
        /// <param name="latitude">The latitude of the coordinate</param>
        /// <param name="longitude">The longitude of the coordinate</param>
        /// <param name="radius">The maximal radius</param>
        /// <param name="distance">If True, distances are returned in meters</param>
        /// <param name="geo">The identifier of the geo-index to use</param>
        /// <param name="skip">The number of documents to skip in the query</param>
        /// <param name="limit">The maximal amount of documents to return. The skip is applied before the limit restriction</param>
        /// <param name="batchSize">Limits the number of results to be transferred in one batch</param>
        /// <returns>Returns a cursor</returns>
        ICursor<T> Within<T>(double latitude, double longitude, double radius, Expression<Func<T, object>> distance = null, string geo = null
            , int? skip = null, int? limit = null, int? batchSize = null);

        ///
        /// Finds all documents from the collection that match the fulltext query
        ///
        /// <param name="attribute">The attribute that contains the texts</param>
        /// <param name="query">The fulltext query</param>
        /// <param name="index">The identifier of the fulltext-index to use</param>
        /// <param name="skip">The number of documents to skip in the query</param>
        /// <param name="limit">The maximal amount of documents to return. The skip is applied before the limit restriction</param>
        /// <param name="batchSize">Limits the number of results to be transferred in one batch</param>
        /// <returns>Returns a cursor</returns>
        ICursor<T> Fulltext<T>(Expression<Func<T, object>> attribute, string query, string index = null
            , int? skip = null, int? limit = null, int? batchSize = null);

        ///
        /// Deletes a database
        ///
        /// <param name="name">Name of the database</param>
        /// <returns></returns>
        void DropDatabase(string name, Action<BaseResult> baseResult = null);

        ///
        /// Deletes a database
        ///
        /// <param name="name">Name of the database</param>
        /// <returns></returns>
        Task DropDatabaseAsync(string name, Action<BaseResult> baseResult = null);

        Task<TResult> ExecuteTransactionAsync<TResult>(TransactionData data, Action<BaseResult> baseResult = null);
        Task ExecuteTransactionAsync(TransactionData data, Action<BaseResult> baseResult = null);

        TResult ExecuteTransaction<TResult>(TransactionData data, Action<BaseResult> baseResult = null);
        void ExecuteTransaction(TransactionData data, Action<BaseResult> baseResult = null);

        ///
        /// Executes a server-side traversal
        ///
        /// <typeparam name="TVertex">Type of vertex</typeparam>
        /// <typeparam name="TEdge">Type of edge</typeparam>
        /// <param name="config">Configuration for the traversal</param>
        /// <param name="startVertex">Id of the startVertex</param>
        /// <param name="baseResult"></param>
        /// <returns>TraversalResult<TVertex TEdge></returns>
        TraversalResult<TVertex, TEdge> Traverse<TVertex, TEdge>(TraversalConfig config, string startVertex = null, Action<BaseResult> baseResult = null);

        ///
        /// Executes a server-side traversal
        ///
        /// <typeparam name="TVertex">Type of vertex</typeparam>
        /// <typeparam name="TEdge">Type of edge</typeparam>
        /// <param name="config">Configuration for the traversal</param>
        /// <param name="startVertex">Id of the startVertex</param>
        /// <param name="baseResult"></param>
        /// <returns>TraversalResult[TVertex, TEdge]</returns>
        Task<TraversalResult<TVertex, TEdge>> TraverseAsync<TVertex, TEdge>(TraversalConfig config, string startVertex = null, Action<BaseResult> baseResult = null);

    }
}


text:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PingServlet
 */
public class PingServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	private PPCounter counter = null;

    public PingServlet()
    {
        super();
        counter = PPCounter.getInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		++counter.ping;
		PrintWriter out = response.getWriter();

		out.println("<!DOCTYPE html>");
		out.println("");
	    out.println("<title>Ping</title>");
		out.println("");
		out.println("
");
		out.println("
Ping: " + counter.ping);
		out.println("
Pong: " + counter.pong);
		out.println("
");
		out.println("
Pong
");
		out.println("");
		out.println("");
	}
}