text: var app = require("./app");


text:
<?php

namespace Rad\Utils;

use ErrorException;

/**
 * @require php ssh2 lib
 * @author Guillaume Monet
 */
class SFTPConnection {

    private $connection;
    private $sftp;
    private $host;

    public function __construct(string $host, int $port = 22) {
        $this->host = $host;
        $this->connection = @ssh2_connect($host, $port) || $this->throwError("Could not connect to $host on port $port.");
    }

    /**
     *
     * @param string $username
     * @param string $password
     * @throws ErrroException
     * @throws ErrorException
     */
    public function login(string $username, string $password) {
        @ssh2_auth_password($this->connection, $username, $password) || $this->throwError("Could not authenticate with username $username and password $password.");
        $this->sftp = @ssh2_sftp($this->connection) || $this->throwError("Could not initialize SFTP subsystem.");
    }

    /**
     *
     * @param string $local_file
     * @param string $remote_file
     * @throws ErrorException
     */
    public function uploadFile(string $local_file, string $remote_file) {
        $stream = fopen("ssh2.sftp://" . intval($this->sftp) . "/./in/$remote_file", 'w') || $this->throwError("Could not open file: $remote_file");
        $data_to_send = file_get_contents($local_file) || $this->throwError("Could not open local file: $local_file.");
        fwrite($stream, $data_to_send) || $this->throwError("Could not send data from file: $local_file.");
        fflush($stream);
        fclose($stream);
    }

    /**
     *
     * @param string $local_file
     * @param string $remote_file
     * @throws ErrorException
     */
    public function downloadFile(string $local_file, string $remote_file) {
        $stream = fopen("ssh2.sftp://" . intval($this->sftp) . "/./$remote_file", 'r') || $this->throwError("Could not open file: $remote_file");
        $local = fopen($local_file, 'w') || $this->throwError("Could not open local file: $local_file.");
        $read = 0;
        $filesize = filesize("ssh2.sftp://" . intval($this->sftp) . "/./$remote_file");
        while (($read < $filesize) && ($buffer = fread($stream, $filesize - $read))) {
            $read += strlen($buffer);
            fwrite($local, $buffer) || $this->throwError("Could not write data to file: $local_file.");
        }
        fflush($local);
        fclose($local);
        fclose($stream);
    }

    /**
     *
     * @param string $directory
     * @return array
     * @throws ErrorException
     */
    public function listDirectory(string $directory): array {
        $files = [];
        $stream = opendir("ssh2.sftp://" . intval($this->sftp) . "/./$directory");
        if (!$stream) {
            throw new ErrorException("Could not open directory: $directory");
        }
        while (false != ($entry = readdir($stream))) {
            if (!in_array($entry, array(".", ".."))) {
                $files[] = $entry;
            }
        }
        closedir($stream);
        return $files;
    }

    /**
     *
     * @param string $message
     * @throws ErrorException
     */
    private function throwError(string $message = "") {
        throw new ErrorException($message);
    }

}

redpajama_set_name: RedPajamaGithub


text:
import os

from libcloud.compute.providers import get_driver
from libcloud.compute.base import NodeSize
from libcloud.compute.type import Provider
from libcloud.compute.deployment import ScriptDeployment

cls = get_driver(Provider.GRIDSCALE)
driver = cls('USER-UUID', 'API-TOKEN')

# We don't feature packages containing a fix size so you will have to
# built your own size object. Make sure to use a multiple of 1024MB when
# asigning RAM
size_name = 'my-node-size'
ram = 1024  # amout of ram In MB
disk = 10  # disk size in GB
cores = 1  # numer of cores node should have
size = NodeSize(id=0, bandwidth=0, price=0, name=size_name, ram=ram, disk=disk,
                driver=driver, extra={'cores': cores})

ssh_key = driver.list_key_pairs()[0]
ssh_key_uuid = ssh_key.fingerprint

node_name = 'MyServer'

images = driver.list_images()
image = [i for i in images if i.name == 'Ubuntu 18.04 LTS'][0]

locations = driver.list_locations()
location = [l for l in locations if l.name == 'de/fra'][0]

# Check if a key pair object with the provided name already exists
# If it already exists, using an existing key, otherwise import a new one
key_pair_name = 'libcloud-key-pair'
key_pairs = driver.list_key_pairs()
key_pairs = [kp for kp in key_pairs if kp.name == key_pair_name]

public_key_file_path = os.path.expanduser('~/.ssh/id_rsa_gridscale.pub')
private_key_file_path = os.path.expanduser('~/.ssh/id_rsa_gridscale')

if key_pairs:
    print('Re-using existing SSH Key')
    key_pair = key_pairs[0]
else:
    print('Importing / creating new SSH Key')
    key_pair = driver.import_key_pair_from_file(name=key_pair_name,
        key_file_path=public_key_file_path) # NOQA

step = ScriptDeployment("echo whoami ; date ; ls -la")

node = driver.deploy_node(name=node_name, size=size, image=image,
                          location=location,
                          ex_ssh_key_ids=[key_pair.fingerprint],
                          deploy=step,
                          ssh_key=private_key_file_path)
print(node)


text:
package org.apache.hadoop.test.system;

import java.util.Map;

import org.apache.hadoop.io.Writable;

/**
 * Daemon system level process information.
 */
public interface ProcessInfo extends Writable {
  /**
   * Get the current time in the millisecond.

   *
   * @return current time on daemon clock in millisecond.
   */
  public long currentTimeMillis();

  /**
   * Get the environment that was used to start the Daemon process.

   *
   * @return the environment variable list.
   */
  public Map<String,String> getEnv();

  /**
   * Get the System properties of the Daemon process.

   *
   * @return the properties list.
   */
  public Map<String,String> getSystemProperties();

  /**
   * Get the number of active threads in Daemon VM.

   *
   * @return number of active threads in Daemon VM.
   */
  public int activeThreadCount();

  /**
   * Get the maximum heap size that is configured for the Daemon VM.

   *
   * @return maximum heap size.
   */
  public long maxMemory();

  /**
   * Get the free memory in Daemon VM.

   *
   * @return free memory.
   */
  public long freeMemory();

  /**
   * Get the total used memory in Demon VM.

   *
   * @return total used memory.
   */
  public long totalMemory();
}


text:
package com.vinitello.encryption.isaac;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import com.vinitello.encryption.IEncryptionAlgorithm;

public class ISAACEncryptionAlgorithm implements IEncryptionAlgorithm {

	private final SecureRandom isaac = getSecureRandom("ISAACRandom");

	@Override
	public int nextInt() {
		if (isaac != null) {
			return isaac.nextInt();
		}
		return 0;
	}

	private static SecureRandom getSecureRandom(String algorithm) {
		try {
			return SecureRandom.getInstance("ISAACRandom");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

}


text:
if ! command -v meld > /dev/null; then
    sudo apt-get install -y meld
else
    echo -e "\033[31;4mWarning\033[0m: package already installed"
fi


text:
namespace OpenApoc {

CheckBox::CheckBox( Framework &fw, Control* Owner ) : Control( fw, Owner ), Checked(false)
{
	LoadResources();
	this->buttonclick = fw.data->load_sample("xcom3/RAWSOUND/STRATEGC/INTRFACE/BUTTON1.RAW" );
}

CheckBox::~CheckBox()
{
}

void CheckBox::LoadResources()
{
	if( !imagechecked )
	{
		imagechecked = fw.gamecore->GetImage( "PCK:xcom3/UFODATA/NEWBUT.PCK:xcom3/UFODATA/NEWBUT.TAB:65:UI/UI_PALETTE.PNG" );
		if( Size.x == 0 )
		{
			Size.x = imagechecked->size.x;
		}
		if( Size.y == 0 )
		{
			Size.y = imagechecked->size.y;
		}
	}
	if( !imageunchecked )
	{
		imageunchecked = fw.gamecore->GetImage( "PCK:xcom3/UFODATA/NEWBUT.PCK:xcom3/UFODATA/NEWBUT.TAB:64:UI/UI_PALETTE.PNG" );
	}
}

void CheckBox::EventOccured( Event* e )
{
	Control::EventOccured( e );

	if( e->Type == EVENT_FORM_INTERACTION && e->Data.Forms.RaisedBy == this && e->Data.Forms.EventFlag == FormEventType::MouseDown )
	{
		fw.soundBackend->playSample(buttonclick);
	}

	if( e->Type == EVENT_FORM_INTERACTION && e->Data.Forms.RaisedBy == this && e->Data.Forms.EventFlag == FormEventType::MouseClick )
	{
		Checked = !Checked;
		Event* ce = new Event();
		ce->Type = e->Type;
		memcpy( (void*)&(ce->Data.Forms), (void*)&(e->Data.Forms), sizeof( FRAMEWORK_FORMS_EVENT ) );
		ce->Data.Forms.EventFlag = FormEventType::CheckBoxChange;
		fw.PushEvent( ce );
	}
}

void CheckBox::OnRender()
{
	std::shared_ptr<Image> useimage;

	LoadResources();

	useimage = ( Checked ? imagechecked : imageunchecked);

	if( useimage != nullptr )
	{
		if (useimage->size == Vec2<unsigned int>{Size.x, Size.y})
		{
			fw.renderer->draw(useimage, Vec2<float>{0,0});
		}
		else
		{
			fw.renderer->drawScaled(useimage, Vec2<float>{0,0}, Vec2<float>{this->Size.x, this->Size.y});
		}
	}
}

void CheckBox::Update()
{
	Control::Update();
}

void CheckBox::UnloadResources()
{
	imagechecked.reset();
	imageunchecked.reset();
	Control::UnloadResources();
}

}; //namespace OpenApoc


text:
/*
 * Ext JS Library 2.0
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://www.extjs.com/license
 */

#tasks-grid .x-grid3-header {
    background: #f9f9f9 url(images/hrow.gif) repeat-x left top;
}
#tasks-grid .new-task-row {
    height:24px;
}
#tasks-grid .new-task-row .x-small-editor {
    overflow:hidden;
    width:100%;
}
#tasks-grid .new-task-row .x-small-editor input {
    font-size:11px;
}
#new-task-icon {
    width:16px;
    height:16px;
    margin-left:3px;
    background: transparent url(images/edit.gif) no-repeat;
}
.x-grid3-body .x-grid3-td-task-col .x-grid3-cell-inner {
    padding: 1px 0 0 0 !important;
}

.task-check {
    width:98%;
    height:16px;
    background: transparent url(images/check.gif) no-repeat center 0;
    cursor:pointer;
}

.task-completed .task-check {
    background: transparent url(images/check.gif) no-repeat center -16px;
}

.task-check-over {
    background: transparent url(images/check.gif) no-repeat center -32px;
}

.task-overdue .x-grid3-cell-inner {
    color:#fb223a;
}

.task-completed .x-grid3-cell-inner {
    text-decoration:line-through;
    color:gray;
}

.task-col-hd {
    width:98%;
    height:12px;
    background: transparent url(images/hd-check.gif) no-repeat center center;
    cursor:default;
}

.x-grid3-td-task-title .x-grid3-cell-inner {
    white-space:normal;
}

.icon-show-active {
    background-image:url(images/icon-show-active.gif) !important;
}
.icon-show-complete {
    background-image:url(images/icon-show-complete.gif) !important;
}
.icon-show-all {
    background-image:url(images/icon-show-all.gif) !important;
}
.x-grid3-dirty-cell {
    background:transparent;
}

.icon-active {
    background-image:url(images/icon-active.gif) !important;
}
.icon-complete {
    background-image:url(images/icon-complete.gif) !important;
}
.icon-delete {
    background-image:url(images/delete.gif) !important;
}
.icon-edit {
	background-image:url(images/edit.gif) !important;
}

.icon-by-date {
    background-image:url(images/icon-by-date.gif) !important;
}
.icon-by-category {
    background-image:url(images/icon-by-category.gif) !important;
}
.icon-no-group {
    background-image:url(images/icon-no-group.gif) !important;
}

#action-panel .x-panel {
	margin-bottom:3px;
	margin-right:0;
}
#action-panel .x-panel-body {
	border:0 none;
}
#action-panel .x-panel-body li {
	margin:3px;
}
#action-panel .x-panel-body li img {
	width:16px;
	height:16px;
	vertical-align:middle;
	margin-right:2px;
	margin-bottom:2px;
}
#action-panel .x-panel-body li a {
	text-decoration:none;
	color:#3764A0;
}
#action-panel .x-plain-body {
	background-color:#cad9ec;
    padding:3px 0 0 5px;
}
.x-air #action-panel .x-plain-body {
	padding-left:3px;
}
#action-panel .x-panel-body li a:hover {
	text-decoration:underline;
	color:#15428b;
}

.x-panel-trans {
	background:transparent;
}

.x-layout-split-west {
	cursor:move;
    background-color:#cad9ec;
}
.x-panel-header-text {
	color:#3764A0;
}
#tasks-grid {
	border-left:1px solid #99bbe8;
}


text:
package org.thingml.compilers.javascript.browser;

import java.util.List;

import org.thingml.compilers.Context;
import org.thingml.compilers.builder.Section;
import org.thingml.compilers.builder.SourceBuilder;
import org.thingml.compilers.javascript.JSCfgMainGenerator;
import org.thingml.compilers.javascript.JSContext;
import org.thingml.compilers.javascript.JSSourceBuilder;
import org.thingml.compilers.javascript.JSSourceBuilder.JSFunction;
import org.thingml.xtext.helpers.ConfigurationHelper;
import org.thingml.xtext.thingML.Configuration;
import org.thingml.xtext.thingML.Instance;
import org.thingml.xtext.thingML.ThingMLModel;

public class BrowserJSCfgMainGenerator extends JSCfgMainGenerator {

	protected String setImmediateStart() {
		return "setTimeout(() => {";
	}

	protected String setImmediateStop() {
		return "}, 0);";
	}

	@Override
	public void generateMainAndInit(Configuration cfg, ThingMLModel model, Context ctx) {
		JSContext jctx = (JSContext)ctx;
		SourceBuilder builder = ctx.getSourceBuilder("runtime.js");
		builder.append("'use strict';").append("");

		{
			JSFunction runfunction = JSSourceBuilder.jsFunction(builder, "run", "var RunThingMLConfiguration = function");
			Section body = runfunction.body();

			body.append("/*$REQUIRE_PLUGINS$*/");
			body.append("");

			generateInstances(cfg, body, jctx);
			body.append("");

			generateConnectors(cfg, body, jctx);
			body.append("");

			Section instanceProperties = body.section("properties").lines();
	        for (Instance i : ConfigurationHelper.allInstances(cfg)) {
	        	generatePropertyDecl(i, cfg, instanceProperties, jctx);
	        }

			List<Instance> instances = ConfigurationHelper.orderInstanceInit(cfg);
	        Instance inst;
	        while (!instances.isEmpty()) {
	            inst = instances.get(instances.size() - 1);
	            instances.remove(inst);
	            body.append("inst_" + inst.getName() + "._init();");
	        }
	        body.append("");
	        body.append("/*$PLUGINS_END$*/");
		}

        // Auto-run the configuration when DOM is ready
		builder.append("");
		builder.append("window.addEventListener('DOMContentLoaded', function(){");
		builder.section("DOMContentLoaded").lines().indent()
			   .append("RunThingMLConfiguration();");
		builder.append("});");
		builder.append("");
	}
}


text:
package com.github.pockethub.ui.comment;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;

import com.alorma.github.sdk.bean.dto.response.Repo;
import com.github.pockethub.R;
import com.github.pockethub.ui.FragmentPagerAdapter;

/**
 * Pager of a raw and rendered comment text
 */
public class CommentPreviewPagerAdapter extends FragmentPagerAdapter {
    private final Repo repo;
    private RawCommentFragment textFragment;
    private RenderedCommentFragment htmlFragment;

    /**
     * Text to populate comment window.
     */
    private String initComment;

    private Context context;

    /**
     * @param activity
     * @param repo
     */
    public CommentPreviewPagerAdapter(AppCompatActivity activity,
            Repo repo) {
        super(activity);
        this.context = activity.getApplicationContext();
        this.repo = repo;
    }

    @Override
    public Fragment getItem(final int position) {
        switch (position) {
        case 0:
            textFragment = new RawCommentFragment();
            textFragment.setText(initComment);
            return textFragment;
        case 1:
            htmlFragment = new RenderedCommentFragment();
            return htmlFragment;
        default:
            return null;
        }
    }

    @Override
    public int getCount() {
        return 2;
    }

    /**
     * Get comment text
     *
     * @return text
     */
    public String getCommentText() {
        if (textFragment == null) {
            textFragment = (RawCommentFragment) getFragmentByPosition(0);
        }

        return textFragment != null ? textFragment.getText() : null;
    }

    /**
     * Set comment text
     *
     * @return text
     */
    public void setCommentText(String comment) {
        if (textFragment != null) {
            textFragment.setText(comment);
        }
        initComment = comment;
    }

    /**
     * Set current item
     *
     * @param position
     * @return this adapter
     */
    public CommentPreviewPagerAdapter setCurrentItem(int position) {
        if (position == 1 && htmlFragment != null) {
            htmlFragment.setText(getCommentText(), repo);
        }
        return this;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return context.getResources().getString(R.string.write);
            case 1:
                return context.getResources().getString(R.string.preview);
            default:
                return "";
        }
    }
}


text:
package global.namespace.truelicense.v1;

import global.namespace.truelicense.api.codec.Codec;
import global.namespace.truelicense.api.codec.CodecFactory;

import javax.security.auth.x500.X500Principal;
import java.beans.DefaultPersistenceDelegate;
import java.beans.PersistenceDelegate;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * A codec factory for use with V1 format license keys.
 */
@SuppressWarnings("WeakerAccess")
public class V1CodecFactory implements CodecFactory {

    private static final PersistenceDelegate delegate = new DefaultPersistenceDelegate(new String[]{"name"});

    public final Codec codec() {
        return new V1Codec(this);
    }

    /**
     * Returns a new XML encoder.
     */
    public XMLEncoder xmlEncoder(OutputStream out) {
        return configure(new XMLEncoder(out));
    }

    /**
     * Configures and returns the given XML encoder.
     */
    protected final XMLEncoder configure(XMLEncoder encoder) {
        encoder.setPersistenceDelegate(X500Principal.class, delegate);
        return encoder;
    }

    /**
     * Returns a new XML decoder.
     */
    public XMLDecoder xmlDecoder(InputStream in) {
        return configure(new XMLDecoder(in));
    }

    /**
     * Configures and returns the given XML decoder.
     */
    protected final XMLDecoder configure(XMLDecoder decoder) {
        return decoder;
    }
}


text:
<?php

namespace backend\tests\functional\lead;

use backend\helpers\Url;
use backend\tests\Step\Functional\LeadManager;
use common\fixtures\helpers\LeadFixtureHelper;
use common\modules\lead\controllers\MarketUserController;
use common\modules\lead\models\forms\LeadMarketAccessRequest;
use common\modules\lead\models\LeadMarket;
use common\modules\lead\models\LeadMarketUser;

class MarketUserCest {

	/** @see MarketUserController::actionIndex() */
	public const ROUTE_INDEX = '/lead/market-user/index';
	/** @see MarketUserController::actionAccept() */
	public const ROUTE_ACCEPT = '/lead/market-user/accept';
	/** @see MarketUserController::actionAccessRequest() */
	public const ROUTE_ACCESS_REQUEST = '/lead/market-user/access-request';
	/** @see MarketUserController::actionReject() */
	public const ROUTE_REJECT = '/lead/market-user/reject';

	public const PERMISSION = MarketCest::PERMISSION;

	public function _fixtures(): array {
		return array_merge(
			LeadFixtureHelper::lead(),
			LeadFixtureHelper::market(),
			LeadFixtureHelper::user(),
		);
	}

	public function checkIndexPageWithoutPermission(LeadManager $I): void {
		$I->amLoggedIn();
		$I->amOnRoute(static::ROUTE_INDEX);
		$I->seeResponseCodeIs(403);
	}

	public function checkIndexPageWithPermission(LeadManager $I): void {
		$I->assignPermission(static::PERMISSION);
		$I->amLoggedIn();
		$I->amOnRoute(static::ROUTE_INDEX);
		$I->seeResponseCodeIsSuccessful();
		$I->see('Market User');
	}

	public function actionAccessRequestDefault(LeadManager $I): void {
		$I->assignPermission(static::PERMISSION);
		$I->amLoggedIn();

		$I->amOnRoute(static::ROUTE_ACCESS_REQUEST, ['market_id' => 1]);

		$I->submitForm('#lead-market-access-request-form', []);

		$I->seeRecord(LeadMarketUser::class, [
			'user_id' => $I->getUser()->getId(),
			'days_reservation' => LeadMarketAccessRequest::DEFAULT_DAYS,
			'market_id' => 1,
		]);

		$I->seeEmailIsSent();
	}

	public function actionAccessRequestWithNotDefaultDaysWithoutDetails(LeadManager $I): void {
		$I->assignPermission(static::PERMISSION);
		$I->amLoggedIn();

		$I->amOnRoute(static::ROUTE_ACCESS_REQUEST, ['market_id' => 1]);

		$I->submitForm('#lead-market-access-request-form', [
			'LeadMarketAccessRequest[days]' => LeadMarketAccessRequest::DEFAULT_DAYS + 1,
		]);

		$I->seeValidationError('Details cannot be blank when Days is other than: ' . LeadMarketAccessRequest::DEFAULT_DAYS . '.');

		$I->dontSeeRecord(LeadMarketUser::class, [
			'user_id' => $I->getUser()->getId(),
			'days_reservation' => LeadMarketAccessRequest::DEFAULT_DAYS + 1,
			'market_id' => 1,
		]);

		$I->dontSeeEmailIsSent();
	}

	public function actionAccessRequestWithNotDefaultDaysWithDetails(LeadManager $I): void {
		$I->assignPermission(static::PERMISSION);
		$I->amLoggedIn();

		$I->amOnRoute(static::ROUTE_ACCESS_REQUEST, ['market_id' => 1]);

		$I->submitForm('#lead-market-access-request-form', [
			'LeadMarketAccessRequest[days]' => LeadMarketAccessRequest::DEFAULT_DAYS + 1,
			'LeadMarketAccessRequest[details]' => 'Please mi Give up for longer term.',

		]);

		$I->seeRecord(LeadMarketUser::class, [
			'user_id' => $I->getUser()->getId(),
			'days_reservation' => LeadMarketAccessRequest::DEFAULT_DAYS + 1,
			'details' => 'Please mi Give up for longer term.',
			'market_id' => 1,
		]);

		$I->seeEmailIsSent();
	}

	public function actionAcceptedSelfMarketLead(LeadManager $I): void {
		$I->assignPermission(static::PERMISSION);
		$I->amLoggedIn();
		$marketId = $I->haveRecord(LeadMarket::class, [
			'creator_id' => $I->getUser()->getId(),
			'lead_id' => 1,
			'status' => LeadMarket::STATUS_NEW,
		]);

		$I->haveRecord(LeadMarketUser::class, [
			'user_id' => 2,
			'market_id' => $marketId,
			'days_reservation' => LeadMarketAccessRequest::DEFAULT_DAYS,
		]);

		$I->sendAjaxPostRequest(Url::to([
				static::ROUTE_ACCEPT, 'market_id' => $marketId, 'user_id' => 2,
			]
		), $I->getCSRF()
		);

		$I->seeRecord(LeadMarketUser::class, [
			'user_id' => 2,
			'market_id' => $marketId,
			'days_reservation' => LeadMarketAccessRequest::DEFAULT_DAYS,
			'status' => LeadMarketUser::STATUS_ACCEPTED,
		]);

		$I->seeRecord(LeadMarket::class, [
			'id' => $marketId,
			'status' => LeadMarket::STATUS_BOOKED,
		]);
	}

	public function actionRejectSelfMarketLead(LeadManager $I): void {
		$I->assignPermission(static::PERMISSION);
		$I->amLoggedIn();
		$marketId = $I->haveRecord(LeadMarket::class, [
			'creator_id' => $I->getUser()->getId(),
			'lead_id' => 1,
			'status' => LeadMarket::STATUS_NEW,
		]);

		$I->haveRecord(LeadMarketUser::class, [
			'user_id' => 2,
			'market_id' => $marketId,
			'status' => LeadMarketUser::STATUS_TO_CONFIRM,
			'reserved_at' => '2020-01-01',
		]);

		$I->sendAjaxPostRequest(Url::to([
				static::ROUTE_REJECT, 'market_id' => $marketId, 'user_id' => 2,
			]
		), $I->getCSRF()
		);

		$I->seeRecord(LeadMarketUser::class, [
			'user_id' => 2,
			'market_id' => $marketId,
			'reserved_at' => null,
			'status' => LeadMarketUser::STATUS_REJECTED,
		]);
	}
}


text:
import logging
from urllib.parse import urljoin

import requests

from appconf.manager import SettingManager

logger = logging.getLogger(__name__)

def get_url(path, base=None):
    return urljoin(base or SettingManager.get("l2_patients_url", default='http://localhost/if', default_type='s'), path)

def get_headers(token=None):
    return {"Authorization": "Bearer {}".format(token or SettingManager.get("l2_patients_token", default='token', default_type='s'))}

def make_request(path, json_data=None, base=None, token=None):
    if json_data is None:
        json_data = {}
    text_resp = None
    try:
        url = get_url(path, base=base)
        headers = get_headers(token=token)
        data = requests.post(url, headers=headers, json=json_data)
        text_resp = data.text
        data = data.json()
        return data
    except Exception as e:
        logger.exception(e)
        logger.exception(text_resp)
        return {}

def check_l2_enp(enp) -> dict:
    data = make_request("check-enp", {"enp": enp, "check_mode": "l2-enp"})
    return data

def check_l2_patient(family, name, patronymic, bd) -> dict:
    data = make_request("check-enp", {"family": family, "name": name, "patronymic": patronymic, "bd": bd, "check_mode": "l2-enp-full"})
    return data

def update_doc_call_status(external_num, status, oid, code_tfoms) -> dict:
    data = make_request("doc-call-update-status", {"externalNum": external_num, "status": status, "org": {"oid": oid, "codeTFOMS": code_tfoms}})
    return data

def send_doc_call(base, token, data) -> dict:
    data = make_request("doc-call-send", data, base=base, token=token)
    return data


text:
"""
The MSSQL backend is based on the work of ``django-mssql``.

https://bitbucket.org/Manfre/django-mssql/
"""


text:
/**
    Static image line-type.
    @module     lines/image/image
    @requires   LineModel
    @requires   LineView
 */
define(function (require) {
    "use strict";

    /* Base objects */
    var LineModel   = require('LineModel'),
        LineView    = require('LineView');

    /* Templates */
    var tplView     = require('tpl!lines/image/view'),
        tplEdit     = require('tpl!lines/blank/edit');

    /**
     * Static image line-type.
     * @exports lines/image/image
     */
    var image = {

        /* Model extensions. */
        model: LineModel.extend({
            /** @lends LineModel.prototype */

            /**
             * Default values for a new title.
             * @property {string} defaults.source - The url of the image source.
             * @lends LineModel.defaults
             */
            defaults: {
                lineType:   "Image",
                source:     ""
            }

        }),

        /* View extensions. */
        view: LineView.extend({
            templates: {
                view: tplView,
                edit: tplEdit
            }
        }),

        /* Toolbar item. */
        toolbar: undefined
    };
    return image;
});


text:
.applyBan .wrap{width:862px;margin-top:70px;text-align: left;}
.applyForm{background: #fff;padding:15px;margin:15px 0;}
.applyForm h2,.loanBox h2{font-size:19px;color:#1c50a8;padding-bottom:5px;}
.fSubmit{display:block;width:174px;height:150px;background:url(../images/applyBtn.jpg) no-repeat;cursor:pointer;}
.fLeft{width:636px;}
.applyForm form{margin-top:15px;}
.applyForm .fDl{padding:15px 8px;background:#f2f2f2;box-shadow:0 0 8px rgba(0,0,0,0.3) inset;border:1px solid #c8c8c8;margin-bottom:7px;}
.applyForm .fDl .fut{display:block;background:none;width:100%;color:#012464;font-family:'Microsoft Yahei';}
.applyForm .fDl textarea.fut{height:61px;}
.loanBox{background: #fff;padding:15px;}
.loanDiv{position:relative; background:url(../images/loanBg.jpg) no-repeat;height:162px;margin-top:5px;background-size:100% 100%;}
.send_phone{position: absolute;right:17px;bottom:20px;background:#0261bf;width:120px;height:40px;line-height:40px;color:#fff;text-align: center;font-size:14px;font-weight: bold;}
.send_phone:hover{background:#f60;color:#fff;}
.select{padding:15px;}
.select p{float:left;width:226px;color:#fff;}
.select p input,.select p select{margin-top:3px; border:none;border-radius:0px; height:39px;line-height:39px;display:block;width:100%;background:#fff;}
.select p.right{float:right;margin-right:0;}
.select p select{border-radius:0;}
.loanPrice{color:#fff;padding:20px 0 0 15px;}
.loanPrice span{font-size:18px;}
.loanPrice span b{font-size:22px;}

.apy-a{background:url(../images/ay1.jpg) no-repeat;height:483px;width:100%;margin-bottom:35px;}
.apy-a .wrap{padding-top:80px;}
.apy-a dt{width:717px;padding-top:90px;color:#fff;}
.apy-a dt h2{font-size:53px;font-weight:normal;}
.apy-a dt p{font-size:22px;}
.apy-a dd{width:470px;}
.apy-a dd .applyForm{width:auto;}
.apy-a dd .applyForm .fLeft {width:440px;}
.apy-a dd .applyForm .fSubmit{width:145px;height:39px;background:url(../images/applyBtn1.jpg) no-repeat;cursor:pointer;text-align:center;line-height:39px;color:#fff;font-size:16px;font-family:'Microsoft Yahei'}
.apy-a dd .applyForm .fDl textarea.fut{height:80px;}
.apy-b dl.dl1{background:#f4f4f4 url(../images/apy1.jpg) no-repeat right top;height:472px;padding:44px 545px 0 35px;}
.apy-b dl h2{font-size:30px;font-weight:normal;color:#0050a4;}
.apy-b dl p{line-height:20px;color:#272727;padding:15px 0 30px 0;}
.apy-b dl .yh-a{padding:35px 0 15px 0;}
.apy-b dl .yh-a a{display:inline-block;margin-right:5px;margin-bottom:10px;}
.apy-b dl.dl2{background:#f4f4f4 url(../images/apy3.jpg) no-repeat left top;height:391px;padding:100px 36px 0 570px;}
.apy-b dl.dl2 .yh-a,.apy-b dl.dl3 .yh-a{padding-top:5px;}
.apy-b dl.dl3{height:475px;background:#f4f4f4 url(../images/apy4.jpg) no-repeat right top;}
.apy-b dl.dl3 h2{padding-top:55px;}
.apy-c .loanBox {width:914px;background:#009cd5;height:170px;}
.apy-c .loanBox .loanDiv{background:none;width:830px;margin:0 auto;}
.popForm{background:#fff;width:400px;height:260px;position:absolute;left:50%;top:50%;margin-left:-200px;margin-top:-130px;}
.popForm form{padding:20px;}
.popForm p{padding:0 5px;border:1px solid #ddd;margin-top:25px;}
 input{padding:8px 0;width: 100%;font-family:'Microsoft Yahei'}
.popForm  a.getCode{display:block;background: #0261bf;color: #fff;text-align: center;font-family:'Microsoft Yahei';padding:10px 0;font-size:14px;}
.closed{position:absolute;right:0;top:0;width:35px;line-height:35px;height:35px;text-align:center;background:#0261bf;color:#fff;font-size:17px;font-family:'宋体';font-weight: bold;}
.closed:hover{opacity:.8;color:#fff;}


text:
'use babel';

import Peer from 'peerjs';
import {Emitter} from 'atom';

export default class Client {
  constructor(serverId) {
    this.serverId     = serverId;
    this.emitter      = new Emitter;
    this.peer         = new Peer({key: 'qs7hwii89g2satt9'});

    this.peer.on('open', (id) => {
      console.log('client: open', id);

      this.conn = this.peer.connect(this.serverId);

      this.conn.on('open', () => {
        console.log('client: conn open');

        this.emitter.emit('open', id);
      });

      this.conn.on('data', (payload) => {
        console.log('client: conn data');

        this.emitter.emit('data', payload);
      });

      this.conn.on('disconnected', () => {
        console.log('client: conn disconnected');

        this.peer.destroy();
        this.emitter.emit('destroy');
      });

      this.conn.on('error', (err) => {
        console.log('client: conn error', err);
      });
    });

    this.peer.on('error', (err) => {
      console.log('client: error', err);
    });
  }

  send(data) {
    this.conn.send(data);
  }

  destroy() {
    this.peer.disconnect();
  }

  onDidOpen(fn) {
    this.emitter.on('open', fn);
  }

  onDidData(fn) {
    this.emitter.on('data', fn);
  }

  onDidDestroy(fn) {
    this.emitter.on('destroy', fn);
  }

  get id() {
    return this.peer.id;
  }
}


text:
package me.justgame.vote.common.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by xcl on 2017-01-06.
 */

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyBatisMapper {

}


text:
namespace Gu.Persist.NewtonsoftJson.Tests
{
    using System.IO;
    using System.Threading.Tasks;
    using Gu.Persist.Core;
    using Gu.Persist.Core.Tests;
    using Newtonsoft.Json;
    using NUnit.Framework;

    public class JsonFileTests
    {
        private static readonly JsonSerializerSettings JsonSettings = NewtonsoftJson.RepositorySettings.CreateDefaultJsonSettings();
        private readonly DirectoryInfo directory;

        public JsonFileTests()
        {
            this.directory = new DirectoryInfo($@"C:\Temp\Gu.Persist\{this.GetType().Name}").CreateIfNotExists();
        }

        [SetUp]
        public void SetUp()
        {
            this.directory.Delete(recursive: true);
            this.directory.Create();
        }

        [OneTimeTearDown]
        public void OneTimeTearDown()
        {
            this.directory.Delete(recursive: true);
        }

        [Test]
        public void Clone()
        {
            var dummy = new DummySerializable { Value = 1 };
            var clone = JsonFile.Clone(dummy);
            Assert.AreNotSame(dummy, clone);
            Assert.AreEqual(dummy.Value, clone.Value);
        }

        [Test]
        public void CloneWithSettings()
        {
            var dummy = new DummySerializable { Value = 1 };
            var clone = JsonFile.Clone(dummy, JsonSettings);
            Assert.AreNotSame(dummy, clone);
            Assert.AreEqual(dummy.Value, clone.Value);
        }

        [Test]
        public void SaveTwice()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            JsonFile.Save(file, dummy);
            JsonFile.Save(file, dummy);
            var read = JsonFile.Read<DummySerializable>(file);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public void SaveThenRead()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            JsonFile.Save(file, dummy);
            var read = JsonFile.Read<DummySerializable>(file);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public void SaveThenReadName()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            JsonFile.Save(file.FullName, dummy);
            var read = JsonFile.Read<DummySerializable>(file.FullName);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public void SaveThenReadWithSettings()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            JsonFile.Save(file, dummy, JsonSettings);
            var read = JsonFile.Read<DummySerializable>(file, JsonSettings);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public void SaveThenReadWithSettingsName()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            JsonFile.Save(file.FullName, dummy, JsonSettings);
            var read = JsonFile.Read<DummySerializable>(file.FullName, JsonSettings);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public void SaveTwiceWithSettings()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            JsonFile.Save(file, dummy, JsonSettings);
            JsonFile.Save(file, dummy, JsonSettings);
            var read = JsonFile.Read<DummySerializable>(file, JsonSettings);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public async Task SaveAsyncThenRead()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            await JsonFile.SaveAsync(file, dummy).ConfigureAwait(false);
            var read = await JsonFile.ReadAsync<DummySerializable>(file).ConfigureAwait(false);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public async Task SaveAsyncThenReadName()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            await JsonFile.SaveAsync(file.FullName, dummy).ConfigureAwait(false);
            var read = await JsonFile.ReadAsync<DummySerializable>(file.FullName).ConfigureAwait(false);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public async Task SaveAsyncTwice()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            await JsonFile.SaveAsync(file, dummy).ConfigureAwait(false);
            await JsonFile.SaveAsync(file, dummy).ConfigureAwait(false);
            var read = await JsonFile.ReadAsync<DummySerializable>(file).ConfigureAwait(false);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public async Task SaveAsyncThenReadWithSettings()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            await JsonFile.SaveAsync(file, dummy, JsonSettings).ConfigureAwait(false);
            var read = await JsonFile.ReadAsync<DummySerializable>(file, JsonSettings).ConfigureAwait(false);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public async Task SaveAsyncThenReadWithSettingsName()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            await JsonFile.SaveAsync(file.FullName, dummy, JsonSettings).ConfigureAwait(false);
            var read = await JsonFile.ReadAsync<DummySerializable>(file.FullName, JsonSettings).ConfigureAwait(false);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }

        [Test]
        public async Task SaveAsyncTwiceWithSettings()
        {
            var dummy = new DummySerializable { Value = 1 };
            var file = this.directory.CreateFileInfoInDirectory("dummy.json");
            await JsonFile.SaveAsync(file, dummy, JsonSettings).ConfigureAwait(false);
            await JsonFile.SaveAsync(file, dummy, JsonSettings).ConfigureAwait(false);
            var read = await JsonFile.ReadAsync<DummySerializable>(file, JsonSettings).ConfigureAwait(false);
            Assert.AreNotSame(dummy, read);
            Assert.AreEqual(dummy.Value, read.Value);
        }
    }
}


text:
package model.catalog;

import javax.xml.bind.annotation.*;

/**
 * Simple representation of a catalog category.
 * Corresponds to a record in the category relation
 * within the catalog database.
 */
@XmlRootElement(name="category")
@XmlType(propOrder={"id", "name", "description", "picture"})
public class Category {

    private int    id;
    private String name;
    private String description;
    private byte[] picture;

    // Getters
    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public byte[] getPicture() {
        return picture;
    }

    // Setters

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setPicture(byte[] picture) { // base64 encoded
        this.picture = picture;
    }

} // Category


text:
package com.example.bot.spring.webapplication.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.example.bot.spring.webapplication.domain.Customer;
import com.example.bot.spring.webapplication.service.CustomerService;

@Controller
class CustomerController {
    @Autowired
    CustomerService customerService;

    @RequestMapping(value = "/customer", method = RequestMethod.GET)
    ModelAndView home() {
    	ModelAndView modelAndView = new ModelAndView("customer");
    	try {
			modelAndView.addObject("customers", customerService.getCustomers());
        	modelAndView.addObject("tours",customerService.getAllTours());
		} catch (Exception e) {
			e.printStackTrace();
			modelAndView.addObject("message", "Failed to get customer infos");
		}
        return modelAndView;
    }

    @RequestMapping(value = "/addcustomer", method = RequestMethod.POST)
    ModelAndView addCustomer(@RequestParam(value="name", required=true, defaultValue= "") String name,
    						@RequestParam(value="bootableid", required=true, defaultValue= "") String bootableid,
                            @RequestParam(value="adults", required=true, defaultValue= "") Integer adults,
                            @RequestParam(value="children", required=true, defaultValue= "") Integer children,
                            @RequestParam(value="toddler", required=true, defaultValue= "") Integer toddler,
                            @RequestParam(value="phone", required=true, defaultValue= "") String phone,
                            @RequestParam(value="special", required=true, defaultValue= "") String special) throws Exception {

        ModelAndView modelAndView = new ModelAndView("customer");
        try {
            Customer customer = new Customer();
            customer.setBootableId(bootableid);
            customer.setName(name);
            customer.setAdults(adults);
            customer.setToddler(toddler);
            customer.setChildren(children);
            customer.setSpecial(special);
            customer.setPhone(phone);
            customer = customerService.addCustomer(customer);
            modelAndView.addObject("message", "customer added with name: " + customer.getName());
        }
        catch (Exception e){
        	e.printStackTrace();
            modelAndView.addObject("message", "Failed to add customer " + e.getMessage());
        }
        try {
        	modelAndView.addObject("customers", customerService.getCustomers());
        	modelAndView.addObject("tours",customerService.getAllTours());
        }catch(Exception e) {
        	e.printStackTrace();
        	modelAndView.addObject("message", "Failed to get customer infos");
        }
        return modelAndView;
    }

    @RequestMapping(value = "/updatePayment", method = RequestMethod.POST)
    ModelAndView updatePayment(@RequestParam(value="", required=true, defaultValue= "") String name,
			@RequestParam(value="bootableid", required=true, defaultValue= "") String bootableid,
            @RequestParam(value="payment", required=true, defaultValue= "") Double payment,
            @RequestParam(value="pricePaid", required=true, defaultValue= "") Double pricePaid,
            @RequestParam(value="totalPrice", required=true, defaultValue= "") Double totalPrice,
            @RequestParam(value="adults", required=true, defaultValue= "") Integer adults,
            @RequestParam(value="children", required=true, defaultValue= "") Integer children,
            @RequestParam(value="toddler", required=true, defaultValue= "") Integer toddler) {
    	ModelAndView modelAndView = new ModelAndView("customer");
    	try {
    		Customer customer = new Customer();
    		customer.setName(name);
    		customer.setBootableId(bootableid);
    		customer.setPricePaid(pricePaid+payment);
    		customer.setTotalPrice(totalPrice);
    		customer.setAdults(adults);
    		customer.setChildren(children);
    		customer.setToddler(toddler);
    		customerService.updatePayment(customer);
    	}catch(Exception e) {
    		modelAndView.addObject("message", "Failed update payment information.");
    	}
        try {
        	modelAndView.addObject("customers", customerService.getCustomers());
        	modelAndView.addObject("tours",customerService.getAllTours());
        }catch(Exception e) {
        	e.printStackTrace();
        	modelAndView.addObject("message", "Failed to get customer infos.");
        }
        return modelAndView;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sakaiproject</groupId>
        <artifactId>master</artifactId>
        <version>21-SNAPSHOT</version>
        <relativePath>../master/pom.xml</relativePath>
    </parent>

	<name>Delegated Access - Base</name>
	<groupId>org.sakaiproject.delegatedaccess</groupId>
	<artifactId>delegatedaccess</artifactId>

	<packaging>pom</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<wicket.version>6.30.0</wicket.version>
	</properties>

    <modules>
        <module>tool</module>
        <module>api</module>
        <module>impl</module>
    </modules>

	<dependencyManagement>
		<dependencies>
			<dependency>
      			<groupId>org.sakaiproject.delegatedaccess</groupId>
      			<artifactId>delegatedaccess-api</artifactId>
      			<version>${project.version}</version>
      			<scope>provided</scope>
    		</dependency>
    		<dependency>
      			<groupId>org.sakaiproject.delegatedaccess</groupId>
      			<artifactId>delegatedaccess-impl</artifactId>
      			<version>${project.version}</version>
      			<scope>runtime</scope>
    		</dependency>
			<dependency>
				<groupId>org.apache.wicket</groupId>
				<artifactId>wicket</artifactId>
				<version>${wicket.version}</version>
				<type>pom</type>
			</dependency>
			<dependency>
				<groupId>org.apache.wicket</groupId>
				<artifactId>wicket-spring</artifactId>
				<version>${wicket.version}</version>
	    	</dependency>
			<dependency>
                <groupId>org.apache.wicket</groupId>
                <artifactId>wicket-extensions</artifactId>
                <version>${wicket.version}</version>
            </dependency>
		</dependencies>
	</dependencyManagement>
</project>


text:
This Python script identifies the features enabled on a switch.  The list
of features is discovered by a series of if/then else statements and includes
most of the common features that may be enabled by a switch.  This list does
not include all possible features of a switch and may be modified to
include the unique features running on your network.

### Files
* [EnabledFeatures.py](EnabledFeatures.py)
* [README.md](README.md)

### Requirements
* Firmware: ExtremeXOS(TM) 12.1 and Newer
* Platform(s): Any ExtremeXOS switch

## Example

`EnabledFeatures.py`

```
RADIUS                : disabled
TACACS                : disabled
Access List(s)        : None Configured
BGP                   : disabled
Configuration logging : disabled
CLI scripting         : enabled
EAPS                  : disabled
EDP                   : disabled
ELRP                  : disabled
ELSM                  : disabled
Debug Mode            : disabled
ESRP                  : disabled
IPARP                 : enabled
IGMP Snooping         : enabled
MLD                   : disabled
MVR                   : disabled
MSDP                  : disabled
NetLogin              : disabled
OSPF                  : disabled
OSPFv3                : disabled
PIM                   : disabled
RIP                   : disabled
RIPNG                 : disabled
IP route sharing      : enabled
SNMP                  : enabled
Spanning Tree         : disabled
Telnet                : enabled
Web mode HTTP         : enabled
Web mode HTTPS        : disabled
VLAN(s)               : created
VMAN(s)               : created
```

## Notes
This script is not meant to run on the switch itself.

## License
Copyright© 2015, Extreme Networks.  All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

## Support
The software is provided as is and Extreme Networks has no obligation to provide
maintenance, support, updates, enhancements or modifications.
Any support provided by Extreme Networks is at its sole discretion.

Issues and/or bug fixes may be reported on [The Hub](https://community.extremenetworks.com/extreme).

>Be Extreme


text:
<?php

namespace Faker\Test\Provider\pt_PT;

use Faker\Provider\pt_PT\PhoneNumber;
use Faker\Test\TestCase;

/**
 * @group legacy
 */
final class PhoneNumberTest extends TestCase
{
    public function testPhoneNumberReturnsPhoneNumberWithOrWithoutPrefix()
    {
        self::assertMatchesRegularExpression('/^(9[1,2,3,6][0-9]{7})|(2[0-9]{8})|(\+351 [2][0-9]{8})|(\+351 9[1,2,3,6][0-9]{7})/', $this->faker->phoneNumber());
    }

    public function testMobileNumberReturnsMobileNumberWithOrWithoutPrefix()
    {
        self::assertMatchesRegularExpression('/^(9[1,2,3,6][0-9]{7})/', $this->faker->mobileNumber());
    }

    protected function getProviders(): iterable
    {
        yield new PhoneNumber($this->faker);
    }
}


text:
from __future__ import unicode_literals
# from builtins import str
import six

import logging
logger = logging.getLogger(__name__)

import os
import shutil
import datetime
from lxml import etree

from django.conf import settings
from django.utils.timezone import make_aware

from lino.core.actions import Action, ShowDetail, ShowTable
from lino.api import rt, _
from lino.core import dbutils

from lino.core.roles import SiteStaff
from etgen.html import E
from lino.utils.media import TmpMediaFile
from lino.utils.pdf import merge_pdfs

from .choicelists import BuildMethods

davlink = settings.SITE.plugins.get('davlink', None)
has_davlink = davlink is not None and settings.SITE.use_java

class BasePrintAction(Action):
    sort_index = 50
    url_action_name = 'print'
    label = _('Print')
    build_method = None

    def __init__(self, build_method=None, label=None, **kwargs):
        super(BasePrintAction, self).__init__(label, **kwargs)
        if build_method is not None:
            self.build_method = build_method

    def attach_to_actor(self, actor, name):
        if not dbutils.resolve_app('system'):
            return False
        # if actor.__name__ == 'ExcerptsByProject':
        #     logger.info("20140401 attach_to_actor() %r", self)
        return super(BasePrintAction, self).attach_to_actor(actor, name)

    def is_callable_from(self, caller):
        # including ShowEmptyTable which is subclass of
        # ShowDetail. But not callable from ShowInsert.
        return isinstance(caller, (ShowTable, ShowDetail))

    def get_print_templates(self, bm, elem):
        return elem.get_print_templates(bm, self)

    def get_printable_context(self, bm, elem, ar):
        """A hook for defining action-specific context variables.
        The default
        implementation calls
        :meth:`lino.core.model.Model.get_printable_context`.

        """
        return elem.get_printable_context(ar)

    def before_build(self, bm, elem):
        """Return the target filename if a document needs to be built,
        otherwise return ``None``.
        """
        elem.before_printable_build(bm)
        # raise Exception("20170519 before_build didn't warn")
        filename = bm.get_target_name(self, elem)
        if not filename:
            return
        if os.path.exists(filename):
            logger.debug(u"%s %s -> overwrite existing %s.",
                         bm, elem, filename)
            os.remove(filename)
        else:
            # logger.info("20121221 makedirs_if_missing %s",os.path.dirname(filename))
            rt.makedirs_if_missing(os.path.dirname(filename))
        logger.debug(u"%s : %s -> %s", bm, elem, filename)
        return filename

    def notify_done(self, ar, bm, leaf, url, **kw):
        # help_url = ar.get_help_url("print", target='_blank')
        # if bm.use_webdav:
        #     url = ar.build_webdav_uri(url)
        msg = _("Your printable document ({}) "
                "should now open in a new browser window. "
                # "If it doesn't, please consult %(help)s "
                "If it doesn't, please "
                "ask your system administrator.")
        msg = msg.format(
            etree.tostring(E.a(leaf, href=url), encoding="unicode"))
        # msg %= dict(doc=leaf, help=etree.tostring(
        #     help_url, encoding="unicode"))
        kw.update(message=msg, alert=True)
        if has_davlink and bm.use_webdav and ar.request is not None:
            kw.update(
                open_webdav_url=ar.request.build_absolute_uri(url))
        else:
            kw.update(open_url=url)
        ar.success(**kw)
        return

    def run_from_ui(self, ar, **kw):
        elem = ar.selected_rows[0]
        bm = self.build_method or elem.get_build_method()
        if isinstance(bm, six.string_types):
            bm = BuildMethods.get_by_value(bm)
        bm.build(ar, self, elem)
        mf = bm.get_target(self, elem)
        leaf = mf.parts[-1]
        self.notify_done(ar, bm, leaf, mf.get_url(ar.request), **kw)

class DirectPrintAction(BasePrintAction):
    url_action_name = None
    icon_name = 'printer'
    tplname = None

    def __init__(self, label=None, tplname=None, build_method=None, **kw):
        super(DirectPrintAction, self).__init__(build_method, label, **kw)
        if tplname is not None:
            self.tplname = tplname

    def get_print_templates(self, bm, obj):
        # assert bm is self.build_method
        if self.tplname:
            return [self.tplname + bm.template_ext]
        return obj.get_print_templates(bm, self)

class CachedPrintAction(BasePrintAction):

    # select_rows = False
    http_method = 'POST'
    icon_name = 'printer'

    def before_build(self, bm, elem):
        if elem.build_time:
            return
        return BasePrintAction.before_build(self, bm, elem)

    def run_from_ui(self, ar, **kw):

        if len(ar.selected_rows) == 1:
            obj = ar.selected_rows[0]
            bm = obj.get_build_method()
            mf = bm.get_target(self, obj)
            leaf = mf.parts[-1]
            if obj.build_time is None:
                obj.build_target(ar)
                ar.info("%s has been built.", leaf)
            else:
                ar.info("Reused %s from cache.", leaf)

            url = mf.get_url(ar.request)
            self.notify_done(ar, bm, leaf, url, **kw)
            ar.set_response(refresh=True)
            return

        def ok(ar2):
            # qs = [ar.actor.get_row_by_pk(pk) for pk in ar.selected_pks]
            mf = self.print_multiple(ar, ar.selected_rows)
            ar2.success(open_url=mf.get_url(ar.request))
            # kw.update(refresh_all=True)
            # return kw
        msg = _("This will print %d rows.") % len(ar.selected_rows)
        ar.confirm(ok, msg, _("Are you sure?"))

    def print_multiple(self, ar, qs):
        pdfs = []
        for obj in qs:
            # assert isinstance(obj,CachedPrintable)
            if obj.printed_by_id is None:
                obj.build_target(ar)
            pdf = obj.get_target_name()
            assert pdf is not None
            pdfs.append(pdf)

        mf = TmpMediaFile(ar, 'pdf')
        rt.makedirs_if_missing(os.path.dirname(mf.name))
        merge_pdfs(pdfs, mf.name)
        return mf

class EditTemplate(BasePrintAction):
    sort_index = 51
    url_action_name = 'edit_tpl'
    label = _('Edit Print Template')
    required_roles = set([SiteStaff])

    def attach_to_actor(self, actor, name):
        # if not settings.SITE.is_installed('davlink'):
        if not (settings.SITE.webdav_protocol or has_davlink):
            return False
        return super(EditTemplate, self).attach_to_actor(actor, name)

    def run_from_ui(self, ar, **kw):

        lcd = settings.SITE.confdirs.LOCAL_CONFIG_DIR
        if lcd is None:
            # ar.info("No local config directory in %s " %
            #         settings.SITE.confdirs)
            raise Warning("No local config directory. "
                          "Contact your system administrator.")

        elem = ar.selected_rows[0]
        bm = elem.get_build_method()
        leaf = bm.get_template_leaf(self, elem)

        filename = bm.get_template_file(ar, self, elem)
        local_file = None
        groups = elem.get_template_groups()
        assert len(groups) > 0
        for grp in reversed(groups):
            # subtle: if there are more than 1 groups
            parts = [grp, leaf]
            local_file = os.path.join(lcd.name, *parts)
            if filename == local_file:
                break

        parts = ['webdav', 'config'] + parts
        url = settings.SITE.build_media_url(*parts)
        # url = ar.build_webdav_uri(url)

        if not (settings.SITE.webdav_protocol or has_davlink):
            msg = "cp %s %s" % (filename, local_file)
            ar.info(msg)
            raise Warning("WebDAV is not enabled. "
                          "Contact your system administrator.")

        def doit(ar):
            ar.info("Going to open url: %s " % url)
            if settings.SITE.webdav_protocol:
                ar.success(open_url=url)
            else:
                ar.success(open_webdav_url=url)
            # logger.info('20140313 EditTemplate %r', kw)

        if filename == local_file:
            doit(ar)
        else:
            ar.info("Gonna copy %s to %s", filename, local_file)

            def ok(ar2):
                logger.info(
                    "%s made local template copy %s", ar.user, local_file)
                rt.makedirs_if_missing(os.path.dirname(local_file))
                shutil.copy(filename, local_file)
                doit(ar2)

            msg = _(
                "Before you can edit this template we must create a "
                "local copy on the server. "
                "This will exclude the template from future updates.")
            ar.confirm(ok, msg, _("Are you sure?"))

class ClearCacheAction(Action):
    sort_index = 51
    url_action_name = 'clear'
    label = _('Clear cache')
    icon_name = 'printer_delete'

    # def disabled_for(self,obj,request):
    #     if not obj.build_time:
    #         return True

    def get_action_permission(self, ar, obj, state):
        # obj may be None when Lino asks whether this action
        # should be visible in the UI
        if obj is not None and not obj.build_time:
            return False
        return super(ClearCacheAction, self).get_action_permission(
            ar, obj, state)

    def run_from_ui(self, ar):
        elem = ar.selected_rows[0]

        def doit(ar):
            elem.clear_cache()
            ar.success(_("%s printable cache has been cleared.") %
                       elem, refresh=True)

        t = elem.get_cache_mtime()
        if t is not None:
            # set microseconds to those of the stored field because
            # Django DateTimeField can have microseconds precision or
            # not depending on the database backend.

            t = datetime.datetime(
                t.year, t.month, t.day, t.hour,
                t.minute, t.second, elem.build_time.microsecond)
            if settings.USE_TZ:
                t = make_aware(t)
            if t != elem.build_time:
                # logger.info("20140313 %r != %r", t, elem.build_time)
                return ar.confirm(
                    doit,
                    _("This will discard all changes in the generated file."),
                    _("Are you sure?"))
        return doit(ar)


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("cases", "0026_auto_20160222_1203")]

    operations = [
        migrations.AlterField(
            model_name="partner",
            name="labels",
            field=models.ManyToManyField(
                help_text="Labels that this partner can access",
                related_name="partners",
                verbose_name="Labels",
                to="msgs.Label",
            ),
        )
    ]


text:
package org.slf4j.helpers;

import org.slf4j.ILoggerFactory;
import org.slf4j.IMarkerFactory;
import org.slf4j.spi.MDCAdapter;
import org.slf4j.spi.SLF4JServiceProvider;

public class SubstitureServiceProvider implements SLF4JServiceProvider {
    private SubstituteLoggerFactory loggerFactory = new SubstituteLoggerFactory();
    private IMarkerFactory markerFactory = new BasicMarkerFactory();
    private MDCAdapter mdcAdapter = new BasicMDCAdapter();

    @Override
    public ILoggerFactory getLoggerFactory() {
        return loggerFactory;
    }

    public SubstituteLoggerFactory getSubstituteLoggerFactory() {
        return loggerFactory;
    }

    @Override
    public IMarkerFactory getMarkerFactory() {
        return markerFactory;
    }

    @Override
    public MDCAdapter getMDCAdapter() {
        return mdcAdapter;
    }

    @Override
    public String getRequesteApiVersion() {
       throw new UnsupportedOperationException();
    }

    @Override
    public void initialize() {

    }
}


text:
package info.sargis.gedi.parser;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.transform.*;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import java.io.OutputStream;
import java.io.Writer;

public class EDI2XML {

    public static void toXML(XMLReader xmlReader, InputSource inputSource, Writer writer) throws TransformerException {
        writeToTargetOutput(xmlReader, inputSource, new StreamResult(writer));
    }

    public static void toXML(XMLReader xmlReader, InputSource inputSource, OutputStream outputStream) throws TransformerException {
        writeToTargetOutput(xmlReader, inputSource, new StreamResult(outputStream));
    }

    private static void writeToTargetOutput(XMLReader xmlReader, InputSource inputSource, Result targetOutput) throws TransformerException {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        Source source = new SAXSource(xmlReader, inputSource);

        transformer.transform(source, targetOutput);
    }

}


text:
<<<<<<< HEAD
<<<<<<< HEAD
cms.test_utils.project.pluginapp.plugins.extra_context package
==============================================================

Submodules
----------

cms.test_utils.project.pluginapp.plugins.extra_context.cms_plugins module
-------------------------------------------------------------------------

.. automodule:: cms.test_utils.project.pluginapp.plugins.extra_context.cms_plugins
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: cms.test_utils.project.pluginapp.plugins.extra_context
    :members:
    :undoc-members:
    :show-inheritance:
=======
cms.test_utils.project.pluginapp.plugins.extra_context package
==============================================================

Submodules
----------

cms.test_utils.project.pluginapp.plugins.extra_context.cms_plugins module
-------------------------------------------------------------------------

.. automodule:: cms.test_utils.project.pluginapp.plugins.extra_context.cms_plugins
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: cms.test_utils.project.pluginapp.plugins.extra_context
    :members:
    :undoc-members:
    :show-inheritance:
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
cms.test_utils.project.pluginapp.plugins.extra_context package
==============================================================

Submodules
----------

cms.test_utils.project.pluginapp.plugins.extra_context.cms_plugins module
-------------------------------------------------------------------------

.. automodule:: cms.test_utils.project.pluginapp.plugins.extra_context.cms_plugins
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: cms.test_utils.project.pluginapp.plugins.extra_context
    :members:
    :undoc-members:
    :show-inheritance:
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453


text:
module User
  class UpdateDetails < UserPlane::Command
    include ActiveModel::Validations::Callbacks

    # Setting the plural route key won't work, polymorphic_url will still
    # generate a path key with the singular name, so the inflector was updated
    # in this case.
    # model_name.instance_variable_set(:@singular_route_key, 'update_details')

    PasswordDetails = Struct.new(:current_password, :password, :password_confirmation) do
      def changed?
        has_passwords = password || password_confirmation
        has_passwords && (!password.empty? || !password_confirmation.empty?)
      end
    end

    attribute :account

    %w(password password_confirmation current_password).each do |attribute|
      delegate attribute.to_sym, "#{attribute}=".to_sym, to: :password_details
    end

    delegate :name, :name=, to: :account

    validates :email_identity, receiver: {map_attributes: {address:  :email,
                                                           password: :password,
                                                           password_confirmation: :password_confirmation}}
    validates :account,        receiver: {map_attributes: {name:       :user_name,
                                                           identities: :email_or_omniauth}}

    validate do |record|
      record.errors.add(:current_password, 'is not correct') if record.failed_password_change?
      if new_address = email_identity.unverified_address
        existing_identity = User::Identities::Email.where(address: new_address).first
        record.errors.add(:email, :taken, value: new_address) if existing_identity
      end
    end

    before_validation do
      if password_details.changed? && current_password_is_valid?
        email_identity.password = password_details.password
        email_identity.password_confirmation = password_details.password_confirmation
      end
    end

    # Ensures that polymorphic_url treats this as a singular resource
    def persisted?
      true
    end

    # Ensures that polymorphic_url treats this as a singular resource
    def to_param
      nil
    end

    action do
      @account.save
    end

    def email
      email_identity && email_identity.address
    end

    def email= address
      unless address == email
        if email_identity.new_record?
          email_identity.address = address
        else
          email_identity.unverified_address = address
        end
      end
    end

    def email_verification
      email_identity.address_change_verification if email_identity.unverified_address_changed?
    end

    # Returns ture if a new password was set, but the change was rejected.
    def failed_password_change?
      password_details.changed? && !email_identity.password_digest_changed? ? true : false
    end

    def email_identity
      @account.email || @account.build_email
    end

    def password_details
      @password_details ||= PasswordDetails.new()
    end

  private

    def current_password_is_valid?
      unless email_identity.new_record?
        email_identity.authenticate(password_details.current_password) ? true : false
      else
        false
      end
    end

  end
end


text:
'use strict';

// About controller class
function AboutCtrl () {
	this.content = 'This is about page';
}

module.exports = AboutCtrl;


text:
package org.motechproject.mds.repository;

import org.motechproject.mds.filter.Filters;
import org.motechproject.mds.query.Property;
import org.motechproject.mds.query.QueryExecutor;
import org.motechproject.mds.query.QueryParams;
import org.motechproject.mds.query.QueryUtil;
import org.motechproject.mds.util.InstanceSecurityRestriction;
import org.motechproject.mds.util.PropertyUtil;
import org.springframework.stereotype.Repository;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * This is a basic repository class with standard CRUD operations. It should be used by other
 * repositories inside this package.
 * <p/>
 * This class is also used as super class to create a repository related with the given entity
 * schema in {@link org.motechproject.mds.builder.EntityInfrastructureBuilder}.
 *
 * @param <T> the type of class
 */
@Repository
public abstract class MotechDataRepository<T> extends AbstractRepository {
    private Class<T> classType;
    private Integer fetchDepth;
    private Map<String, String> fieldTypeMap;

    protected MotechDataRepository(Class<T> classType) {
        this.classType = classType;
    }

    protected MotechDataRepository(Class<T> classType, int fetchDepth) {
        this.classType = classType;
        this.fetchDepth = fetchDepth;
    }

    public Class<T> getClassType() {
        return classType;
    }

    public void setFieldTypeMap(Map<String, String> fieldTypeMap) {
        this.fieldTypeMap = fieldTypeMap;
    }

    @Override
    public PersistenceManager getPersistenceManager() {
        PersistenceManager pm = super.getPersistenceManager();

        if (fetchDepth != null && pm != null) {
            pm.getFetchPlan().setMaxFetchDepth(fetchDepth);
        }

        return pm;
    }

    public void evictAll() {
        if (getPersistenceManagerFactory() != null) {
            getPersistenceManagerFactory().getDataStoreCache().evictAll();
        }
    }

    public void evictEntity(boolean withSubclasses) {
        if (getPersistenceManagerFactory() != null) {
            getPersistenceManagerFactory().getDataStoreCache().evictAll(withSubclasses, classType);
        }
    }

    public void evictOne(T object) {
        if (getPersistenceManagerFactory() != null) {
            getPersistenceManagerFactory().getDataStoreCache().evict(object);
        }
    }

    public T retrieve(Object key) {
        return getPersistenceManager().getObjectById(classType, key);
    }

    public List<T> retrieveAll(Collection<Long> keys) {
        Query query = getPersistenceManager().newQuery(classType);
        query.setFilter(":keys.contains(this.id)");
        Collection result = (Collection) query.execute(keys);
        return new ArrayList<>(result);
    }

    public T create(T object) {
        return getPersistenceManager().makePersistent(object);
    }

    public List<T> retrieveAll() {
        return retrieveAll(new String[0], new Object[0], null);
    }

    public List<T> retrieveAll(InstanceSecurityRestriction restriction) {
        return retrieveAll(new String[0], new Object[0], restriction);
    }

    public List<T> retrieveAll(String property, Object value) {
        return retrieveAll(new String[]{property}, new Object[]{value}, null);
    }

    public List<T> retrieveAll(String property, Object value, InstanceSecurityRestriction restriction) {
        return retrieveAll(new String[]{property}, new Object[]{value}, restriction);
    }

    public List<T> retrieveAll(String[] properties, Object[] values, InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, values, restriction);
        Collection collection = (Collection) QueryExecutor.executeWithArray(query, values, restriction);

        return new ArrayList<>(collection);
    }

    public List<T> retrieveAll(String[] properties, Object[] values, QueryParams queryParams,
                               InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, values, restriction);
        QueryUtil.setQueryParams(query, queryParams);

        Collection collection = (Collection) QueryExecutor.executeWithArray(query, values, restriction);

        return new ArrayList<>(collection);
    }

    public List<T> retrieveAll(QueryParams queryParams, InstanceSecurityRestriction restriction) {
        Query query = createQuery(new String[0], new Object[0], restriction);
        QueryUtil.setQueryParams(query, queryParams);
        Collection collection = (Collection) QueryExecutor.execute(query, restriction);

        return new ArrayList<>(collection);
    }

    public List<T> retrieveAll(List<Property> properties, InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, restriction);

        Collection collection = (Collection) QueryExecutor.executeWithArray(query, properties);

        return new ArrayList<>(collection);
    }

    public List<T> retrieveAll(List<Property> properties, QueryParams queryParams, InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, restriction);
        QueryUtil.setQueryParams(query, queryParams);

        Collection collection = (Collection) QueryExecutor.executeWithArray(query, properties);

        return new ArrayList<>(collection);
    }

    public T retrieve(String property, Object value) {
        return retrieve(new String[]{property}, new Object[]{value}, null);
    }

    public T retrieve(String property, Object value, InstanceSecurityRestriction restriction) {
        return retrieve(new String[]{property}, new Object[]{value}, restriction);
    }

    public T retrieve(String[] properties, Object[] values) {
        return retrieve(properties, values, null);
    }

    public T retrieve(String[] properties, Object[] values, InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, values, restriction);
        query.setUnique(true);

        return (T) QueryExecutor.executeWithArray(query, values, restriction);
    }

    public T retrieveUnique(List<Property> properties, InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, restriction);
        query.setUnique(true);

        return (T) QueryExecutor.executeWithArray(query, properties);
    }

    public boolean exists(String property, Object value) {
        return exists(new String[]{property}, new Object[]{value});
    }

    public boolean exists(String[] properties, Object[] values) {
        return !retrieveAll(properties, values, null).isEmpty();
    }

    public T update(T object) {
        return getPersistenceManager().makePersistent(object);
    }

    public void delete(T object) {
        getPersistenceManager().deletePersistent(object);
    }

    public long delete(String property, Object value) {
        return delete(new String[]{property}, new Object[]{value}, null);
    }

    public long delete(String property, Object value, InstanceSecurityRestriction restriction) {
        return delete(new String[]{property}, new Object[]{value}, restriction);
    }

    public long delete(String[] properties, Object[] values, InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, values, restriction);
        return QueryExecutor.executeDelete(query, values, restriction);
    }

    public T detachedCopy(T object) {
        return getPersistenceManager().detachCopy(object);
    }

    public Object getDetachedField(T instance, String field) {
        T attached = getPersistenceManager().makePersistent(instance);
        return PropertyUtil.safeGetProperty(attached, field);
    }

    public long count(InstanceSecurityRestriction restriction) {
        return count(new String[0], new Object[0], restriction);
    }

    public long count(String[] properties, Object[] values, InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, values, restriction);
        QueryUtil.setCountResult(query);
        return (long) QueryExecutor.executeWithArray(query, values, restriction);
    }

    public List<T> filter(Filters filters, QueryParams queryParams, InstanceSecurityRestriction restriction) {
        Query query = queryForFilters(filters, queryParams, restriction);

        Collection collection = (Collection) QueryExecutor.executeWithFilters(query, filters, restriction);

        return new ArrayList<>(collection);
    }

    public long countForFilters(Filters filters, InstanceSecurityRestriction restriction) {
        Query query = queryForFilters(filters, null, restriction);
        QueryUtil.setCountResult(query);

        return (long) QueryExecutor.executeWithFilters(query, filters, restriction);
    }

    public long count(List<Property> properties, InstanceSecurityRestriction restriction) {
        Query query = createQuery(properties, restriction);
        QueryUtil.setCountResult(query);

        return (long) QueryExecutor.executeWithArray(query, properties);
    }

    private Query createQuery(String[] properties, Object[] values, InstanceSecurityRestriction restriction) {
        Query query = getPersistenceManager().newQuery(classType);
        QueryUtil.useFilter(query, properties, values, fieldTypeMap, restriction);

        return query;
    }

    private Query createQuery(List<Property> properties, InstanceSecurityRestriction restriction) {
        Query query = getPersistenceManager().newQuery(classType);
        QueryUtil.useFilter(query, properties, restriction);

        return query;
    }

    private Query queryForFilters(Filters filters, QueryParams queryParams, InstanceSecurityRestriction restriction) {
        Query query = createQuery(new String[0], new Object[0], restriction);
        QueryUtil.setQueryParams(query, queryParams);
        QueryUtil.useFilters(query, filters);

        return query;
    }
}