text:
package com.group5.android.fd.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;

import com.group5.android.fd.R;
import com.group5.android.fd.activity.dialog.NumberPickerDialog;
import com.group5.android.fd.adapter.FdCursorAdapter;
import com.group5.android.fd.adapter.ItemAdapter;
import com.group5.android.fd.entity.ItemEntity;
import com.group5.android.fd.entity.OrderItemEntity;
import com.group5.android.fd.view.ItemView;

/**
 * The activity to display a list of items of a category
 *
 * @author Nguyen Huu Ha
 *
 */
public class ItemListActivity extends DbBasedActivity implements
		OnDismissListener {

	final public static String EXTRA_DATA_NAME_CATEGORY_ID = "categoryId";
	final public static int DIALOG_QUANTITY_SELECTOR = 1;
	final public static String DIALOG_QUANTITY_SELECTOR_DUNBLE_NAME_ITEM_OBJ = "itemObj";
	public static final String ACTIVITY_RESULT_NAME_ORDER_ITEM_OBJ = "orderItemObj";

	// get Category id for display it's items
	@Override
	protected Cursor initCursor() {
		Intent intent = getIntent();
		int categoryId = intent.getIntExtra(
				ItemListActivity.EXTRA_DATA_NAME_CATEGORY_ID, 0);

		return m_dbAdapter.getItems(categoryId);
	}

	@Override
	protected FdCursorAdapter initAdapter() {
		return new ItemAdapter(this, m_cursor);
	}

	@Override
	protected void initLayout() {
		super.initLayout();
		// set titile for item list activity
		setCustomTitle(R.string.itemlist_choose_item);
	}

	/**
	 * Finishes the activity with an item and a quantity. It simply creates a
	 * new {@link OrderItemEntity} and pass it to
	 * {@link #finish(OrderItemEntity)}
	 *
	 * @param item
	 *            the selected ItemEntity
	 * @param quantity
	 *            the chosen quantity
	 * @see #finish()
	 */
	public void finish(ItemEntity item, int quantity) {
		OrderItemEntity orderItem = new OrderItemEntity();
		orderItem.setup(item, quantity);

		finish(orderItem);
	}

	/**
	 * Finishes the activity with an order item (item with a quantity).
	 *
	 * @param orderItem
	 *            the constructed OrderItemEntity
	 * @see #finish()
	 * @see #finish(ItemEntity, int)
	 */
	public void finish(OrderItemEntity orderItem) {
		if (orderItem == null) {
			setResult(Activity.RESULT_CANCELED);
			finish();
		} else {
			Intent intent = new Intent();
			intent.putExtra(
					ItemListActivity.ACTIVITY_RESULT_NAME_ORDER_ITEM_OBJ,
					orderItem);

			setResult(Activity.RESULT_OK, intent);
			finish();
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (view instanceof ItemView) {
			ItemView itemView = (ItemView) view;
			ItemEntity item = itemView.item;

			finish(item, 1);
		}
	}

	// display NumberPicker when long click
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		if (view instanceof ItemView) {
			ItemView itemView = (ItemView) view;
			ItemEntity item = itemView.item;

			// put ItemEntity for dialog
			Bundle args = new Bundle();
			args.putSerializable(
					ItemListActivity.DIALOG_QUANTITY_SELECTOR_DUNBLE_NAME_ITEM_OBJ,
					item);

			showDialog(ItemListActivity.DIALOG_QUANTITY_SELECTOR, args);

			return true;
		}

		return super.onItemLongClick(parent, view, position, id);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;

		switch (id) {
		case DIALOG_QUANTITY_SELECTOR:
			dialog = new NumberPickerDialog(this);
			dialog.setOnDismissListener(this);
			break;
		}

		return dialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
		switch (id) {
		case DIALOG_QUANTITY_SELECTOR:
			ItemEntity item = (ItemEntity) args
					.getSerializable(ItemListActivity.DIALOG_QUANTITY_SELECTOR_DUNBLE_NAME_ITEM_OBJ);
			((NumberPickerDialog) dialog).setEntity(item);
			break;
		}
	}

	@Override
	public void onDismiss(DialogInterface arg0) {
		if (arg0 instanceof NumberPickerDialog) {
			NumberPickerDialog numberPickerDialog = (NumberPickerDialog) arg0;
			ItemEntity item = (ItemEntity) numberPickerDialog.getEntity();
			if (numberPickerDialog.isSet()) {
				OrderItemEntity orderItem = new OrderItemEntity();
				orderItem.setup(item, numberPickerDialog.getQuantity());
				finish(orderItem);
			}

		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
declare(strict_types=1);

namespace CsvView\Test\App;

use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;

/**
 * Application setup class.
 *
 * This defines the bootstrapping logic and middleware layers you
 * want to use in your application.
 */
class Application extends BaseApplication
{
    /**
     * @inheritDoc
     */
    public function bootstrap(): void
    {
        // Call parent to load bootstrap from files.
        parent::bootstrap();

        $this->addPlugin('CsvView', [
            'path' => ROOT . DS,
            'autoload' => true,
        ]);
    }

    /**
     * Setup the middleware queue your application will use.
     *
     * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
     * @return \Cake\Http\MiddlewareQueue The updated middleware queue.
     */
    public function middleware(\Cake\Http\MiddlewareQueue $middlewareQueue): \Cake\Http\MiddlewareQueue
    {
        $middlewareQueue
            // Catch any exceptions in the lower layers,
            // and make an error page/response
            ->add(ErrorHandlerMiddleware::class)

            // Handle plugin/theme assets like CakePHP normally does.
            ->add(AssetMiddleware::class)

            // Add routing middleware.
            // Routes collection cache enabled by default, to disable route caching
            // pass null as cacheConfig, example: `new RoutingMiddleware($this)`
            // you might want to disable this cache in case your routing is extremely simple
            ->add(new RoutingMiddleware($this, null));

        return $middlewareQueue;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
    http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
    <changeSet author="robertm" id="20220218-add-rollup-table-name">
        <preConditions onFail="MARK_RAN">
            <not>
                <columnExists tableName="rollup_map" columnName="table_name"/>
            </not>
        </preConditions>
        <sql>
          create extension if not exists pgcrypto; <!-- for "digest" -->
          alter table rollup_map add column table_name text null;

          update rollup_map
          set
            table_name = (
              select
               't' || cm.dataset_system_id || '_' || cm.copy_number || coalesce('_' || cmtm.table_modifier, '') || '_r_' || cm.data_version || '_' || substring(encode(digest(rollup_map.name, 'sha1'), 'hex'), 1, 16)
              from
                copy_map cm
                left outer join copy_map_table_modifiers cmtm on cmtm.copy_system_id = cm.system_id
              where cm.system_id = rollup_map.copy_system_id
            );

          alter table rollup_map alter column table_name set not null;
        </sql>
        <rollback>
          <sql>
            alter table rollup_map drop column table_name;
          </sql>
        </rollback>
    </changeSet>
</databaseChangeLog>


text:
package openmods.utils;

import java.util.Collection;
import java.util.List;

import net.minecraft.command.*;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentTranslation;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

public class CommandUtils {

	public static List<String> filterPrefixes(String prefix, Collection<String> proposals) {
		prefix = prefix.toLowerCase();

		List<String> result = Lists.newArrayList();
		for (String s : proposals)
			if (s.toLowerCase().startsWith(prefix)) result.add(s);

		return result;
	}

	public static List<String> getPlayerNames() {
		MinecraftServer server = MinecraftServer.getServer();
		if (server != null) return ImmutableList.copyOf(server.getAllUsernames());
		return ImmutableList.of();
	}

	public static List<String> fiterPlayerNames(String prefix) {
		return filterPrefixes(prefix, getPlayerNames());
	}

	public static void respond(ICommandSender sender, String format, Object... args) {
		sender.addChatMessage(new ChatComponentTranslation(format, args));
	}

	public static CommandException error(String format, Object... args) {
		throw new CommandException(format, args);
	}

	public static EntityPlayerMP getPlayer(ICommandSender sender, String playerName) {
		EntityPlayerMP player = PlayerSelector.matchOnePlayer(sender, playerName);
		if (player != null) return player;

		player = MinecraftServer.getServer().getConfigurationManager().func_152612_a(playerName);
		if (player != null) return player;

		throw new PlayerNotFoundException();
	}
}


text:
<?php
namespace Chamilo\Core\Repository\Implementation\Office365;

use Chamilo\Core\Repository\Instance\Storage\DataClass\Instance;
use Chamilo\Libraries\Format\Theme;
use Chamilo\Libraries\Utilities\StringUtilities;

class ExternalObject extends \Chamilo\Core\Repository\External\ExternalObject
{
    const OBJECT_TYPE = 'office365';
    const PROPERTY_MODIFIER_ID = 'modifier_id';
    const PROPERTY_URL = 'url';
    const TYPE_FILE = 'file';
    const TYPE_IMAGE = 'image';
    const TYPE_FOLDER = 'folder';

    public static function get_default_property_names($extended_property_names = array())
    {
        return parent::get_default_property_names(array(self::PROPERTY_MODIFIER_ID, self::PROPERTY_URL));
    }

    public static function get_object_type()
    {
        return self::OBJECT_TYPE;
    }

    public function getModifierId()
    {
        return $this->get_default_property(self::PROPERTY_MODIFIER_ID);
    }

    public function setModifierId($modifierId)
    {
        return $this->set_default_property(self::PROPERTY_MODIFIER_ID, $modifierId);
    }

    public function getUrl()
    {
        return $this->get_default_property(self::PROPERTY_URL);
    }

    public function setUrl($url)
    {
        return $this->set_default_property(self::PROPERTY_URL, $url);
    }

    public function get_icon_image()
    {
        $type = $this->get_type();
        if ($type == self::TYPE_FOLDER or $type == self::TYPE_IMAGE or $type == self::TYPE_FILE)
        {
            return parent::get_icon_image();
        }
        else
        {
            $camelizedType = StringUtilities::getInstance()->createString($this->get_type())->upperCamelize();
            return '<img src="' . Theme::getInstance()->getFileExtension($camelizedType) . '" alt="' . $camelizedType .
                 '" title="' . $camelizedType . '"/>';
        }
    }

    public function get_content_data()
    {
        $external_repository = \Chamilo\Core\Repository\Instance\Storage\DataManager::retrieve_by_id(
            Instance::class_name(),
            $this->get_external_repository_id());

        return DataConnector::getInstance($external_repository)->import_external_repository_object($this->get_id());
    }
}


text:
using DotVVM.Framework.ViewModel;

namespace DotvvmWeb.Views.Docs.Controls.businesspack.Slider.sample3
{
    public class ViewModel : DotvvmViewModelBase
    {
        public int Price { get; set; } = 50;
        public string PriceString { get; set; }

        public void PriceChanged()
        {
            PriceString = $"{Price}$";
        }
    }
}


text:
          LO

          LotteryObserver

            Toggle navigation

                  {user_name}

                      {user_name}
                      Member since Nov. 2012

                      Followers

                      Sales

                      Friends

                      Profile

                      Sign out


text:
package com.duast.game.ui;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Cell;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import com.badlogic.gdx.utils.Align;
import com.duast.game.stages.UIStage;
import com.duast.game.utils.Assets;
import com.duast.game.utils.C;

/**
 * Created by alex on 10/26/16.
 */

public class DifficultySelectBox extends Table {
    public static final int LIST_WIDTH = Assets.FONT_SIZE*6;
    private static final String[] DIFFICULTIES = {"Easy", "Medium", "Hard"};
    private MyTextButton title;
    private TextButton easy, medium, hard;
    private Table list;
    private int selected;

    public DifficultySelectBox(TextButton.TextButtonStyle tbStyle, int diff) {
        title = new MyTextButton(DIFFICULTIES[diff], tbStyle);
        //title.getLabel().setAlignment(Align.left);
        selected = diff;
        title.pad(UIStage.PAD/3);
        title.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                if(list.isVisible()) hide();
                else show();
            }
        });

        list = new Table();
        //list.setDebug(true);
        add(title).width(LIST_WIDTH);
        row();
        add(list);
        easy = new TextButton("Easy", tbStyle);
        medium = new TextButton("Medium", tbStyle);
        hard = new TextButton("Hard", tbStyle);
        add(easy, DIFFICULTIES[0], 0);
        add(medium, DIFFICULTIES[1], 1);
        add(hard, DIFFICULTIES[2], 2);
        hide();
    }

    public Cell<TextButton> add(TextButton tb, final String text, final int i) {
        list.row();
        tb.getLabel().setAlignment(Align.left);
        tb.pad(UIStage.PAD/3);
        tb.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                if(list.isVisible()) hide();
                if(title!=null) title.setText(text);
                selected = i;
            }
        });
        return list.add(tb).width(LIST_WIDTH);
    }

    public void show() {
        list.setVisible(true);
    }

    public void hide() {
        list.setVisible(false);
    }

    public boolean isListVisible() {
        return list.isVisible();
    }

    public void setTheme(int theme) {
        Color font_color;
        switch(theme) {
            case C.LIGHT: font_color = C.WHITE; break;
            case C.DARK: font_color = C.BLACK; break;
            default: font_color = C.WHITE;
        }
        title.getStyle().fontColor = font_color;
        easy.getStyle().fontColor = font_color;
        medium.getStyle().fontColor = font_color;
        hard.getStyle().fontColor = font_color;
    }

    /* getters */
    public MyTextButton getTitleLabel() {
        return title;
    }

    public int getSelected() {
        return selected;
    }

    public Table getList() {
        return list;
    }
}


text:
FROM dockerfile/nodejs
MAINTAINER Vangie Du from Coding IDE Team <duwan@coding.net>

EXPOSE 5000

ADD *.json index.* ./

RUN npm install && node_modules/.bin/bower install --allow-root

CMD ["npm", "start"]


text:
package cruise.umple.cpp.utils;

import cruise.umple.core.CommonConstants;

/**
 * The common  constants for C++ code generation
 */
public interface CPPCommonConstants {

	public static String HEADER_FILE_EXTENSION = "h"; // default value //$NON-NLS-1$
	public static String BODY_FILE_EXTENSION = "cpp"; // default value //$NON-NLS-1$

	public static final String DECLARATION_PREFIX= " : "; //$NON-NLS-1$
	public static final String DECLARATION_COMMON_PREFIX= "::"; //$NON-NLS-1$
	public static final String UNDEFINED= "undefined"; //There is no keyword in C++ such undefined, but we use this as a way to indicate badly undefined types, etc on the code generation //$NON-NLS-1$
	public static final String BODY= "body"; //$NON-NLS-1$
	public static final String HEADER= "header"; //$NON-NLS-1$
	public static final String NAME= "name"; //$NON-NLS-1$
	public static final String VISIBILITY= "visibility"; //$NON-NLS-1$
	public static final String QUALIFIED_NAME= "qualified_name"; //$NON-NLS-1$

	public static final String CPP_LANGUAGE= "Cpp"; //$NON-NLS-1$
	public static final String C_LANGUAGE= "C"; //$NON-NLS-1$
	public static final String C_CPP_LANGUAGES= CPPCommonConstants.C_LANGUAGE+
			CommonConstants.FORWARD_SLASH+CPPCommonConstants.CPP_LANGUAGE;

	public static final String FUNCTION_INITAILISATION= "initialisation"; //$NON-NLS-1$

	public static final String NIL= "NIL"; //$NON-NLS-1$
	public static final String NULL= "NULL"; //$NON-NLS-1$
	public static final String THIS= "this"; //$NON-NLS-1$
	public static final String AND= "&&"; 	//$NON-NLS-1$

	public static final String BEGIN= "begin"; //$NON-NLS-1$
	public static final String END= "end"; //$NON-NLS-1$

	public static final String ENUM= "enum"; //$NON-NLS-1$

}


text:
package org.wso2.carbon.apimgt.core.dao.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.wso2.carbon.apimgt.core.SampleTestObjectCreator;
import org.wso2.carbon.apimgt.core.TestUtil;
import org.wso2.carbon.apimgt.core.api.APIMgtAdminService;
import org.wso2.carbon.apimgt.core.dao.PolicyDAO;
import org.wso2.carbon.apimgt.core.exception.APIMgtDAOException;
import org.wso2.carbon.apimgt.core.models.BlockConditions;
import org.wso2.carbon.apimgt.core.models.policy.APIPolicy;
import org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy;
import org.wso2.carbon.apimgt.core.models.policy.CustomPolicy;
import org.wso2.carbon.apimgt.core.models.policy.Policy;
import org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy;
import org.wso2.carbon.apimgt.core.util.APIMgtConstants;
import org.wso2.carbon.apimgt.core.util.ETagUtils;

import java.util.List;

public class PolicyDAOImplIT extends DAOIntegrationTestBase {

    private static final Logger log = LoggerFactory.getLogger(PolicyDAOImplIT.class);

    @Test
    public void testFingerprintAfterUpdatingAPIPolicy() throws Exception {
        APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicy();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        policyDAO.addApiPolicy(policy);
        String fingerprintBeforeUpdatingPolicy = ETagUtils
                .generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel.api,
                        policy.getPolicyName()));
        Assert.assertNotNull(fingerprintBeforeUpdatingPolicy);
        APIPolicy updatedAPIPolicy = SampleTestObjectCreator.updateAPIPolicy(policy);
        Thread.sleep(100L);
        policyDAO.updateApiPolicy(updatedAPIPolicy);
        String fingerprintAfterUpdatingPolicy = ETagUtils
                .generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel.api,
                        updatedAPIPolicy.getPolicyName()));
        Assert.assertNotNull(fingerprintAfterUpdatingPolicy);
        Assert.assertNotEquals(fingerprintBeforeUpdatingPolicy, fingerprintAfterUpdatingPolicy, "Policy "
                + "fingerprint expected to be different before and after updating for policy: "
                + policy.getPolicyName());
    }

    @Test
    public void testFingerprintAfterUpdatingApplicationPolicy() throws Exception {
        ApplicationPolicy policy = SampleTestObjectCreator.createDefaultApplicationPolicy();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        policyDAO.addApplicationPolicy(policy);
        String fingerprintBeforeUpdatingPolicy = ETagUtils
                .generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel.application,
                        policy.getPolicyName()));
        Assert.assertNotNull(fingerprintBeforeUpdatingPolicy);
        ApplicationPolicy updatedPolicy = SampleTestObjectCreator.updateApplicationPolicy(policy);
        Thread.sleep(100L);
        policyDAO.updateApplicationPolicy(updatedPolicy);
        String fingerprintAfterUpdatingPolicy = ETagUtils
                .generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel.application,
                        updatedPolicy.getPolicyName()));
        Assert.assertNotNull(fingerprintAfterUpdatingPolicy);
        Assert.assertNotEquals(fingerprintBeforeUpdatingPolicy, fingerprintAfterUpdatingPolicy, "Policy "
                + "fingerprint expected to be different before and after updating for policy: "
                + policy.getPolicyName());
    }

    @Test
    public void testFingerprintAfterUpdatingSubscriptionPolicy() throws Exception {
        SubscriptionPolicy policy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        policyDAO.addSubscriptionPolicy(policy);
        String fingerprintBeforeUpdatingPolicy = ETagUtils
                .generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel
                                .subscription, policy.getPolicyName()));
        Assert.assertNotNull(fingerprintBeforeUpdatingPolicy);
        SubscriptionPolicy updatedPolicy = SampleTestObjectCreator.updateSubscriptionPolicy(policy);
        Thread.sleep(100L);
        policyDAO.updateSubscriptionPolicy(updatedPolicy);
        String fingerprintAfterUpdatingPolicy = ETagUtils
                .generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel
                        .subscription, updatedPolicy.getPolicyName()));
        Assert.assertNotNull(fingerprintAfterUpdatingPolicy);
        Assert.assertNotEquals(fingerprintBeforeUpdatingPolicy, fingerprintAfterUpdatingPolicy, TestUtil.printDiff
                (fingerprintBeforeUpdatingPolicy, fingerprintAfterUpdatingPolicy));
    }

    @Test (description = "Add, Get and Delete an API policy")
    public void testAddGetAndDeleteApiPolicy() throws Exception {
        APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicy();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        //add policy
        policyDAO.addApiPolicy(policy);
        //get added policy
        Policy addedPolicy = policyDAO.getApiPolicy(policy.getPolicyName());
        Assert.assertNotNull(addedPolicy);
        Assert.assertEquals(addedPolicy.getPolicyName(), policy.getPolicyName());
        //delete policy
        policyDAO.deletePolicy(APIMgtAdminService.PolicyLevel.api, policy.getPolicyName());
        //get policy after deletion
        try {
            policyDAO.getApiPolicy(policy.getPolicyName());
            Assert.fail("Exception expected, but not thrown.");
        } catch (APIMgtDAOException ex) {
            Assert.assertEquals(ex.getMessage(), "API Policy not found for name: " + addedPolicy.getPolicyName());
        }
    }

    @Test(description = "Add, Get and Delete an Application policy")
    public void testAddGetAndDeleteApplicationPolicy() throws Exception {
        ApplicationPolicy policy = SampleTestObjectCreator.createDefaultApplicationPolicy();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        //add policy
        policyDAO.addApplicationPolicy(policy);
        //get added policy
        Policy addedPolicy = policyDAO
                .getApplicationPolicy(policy.getPolicyName());
        Assert.assertNotNull(addedPolicy);
        Assert.assertEquals(addedPolicy.getPolicyName(), policy.getPolicyName());
        //delete policy
        policyDAO.deletePolicy(APIMgtAdminService.PolicyLevel.application, policy.getPolicyName());
        //get policy after deletion
        try {
            policyDAO.getApplicationPolicy(policy.getPolicyName());
            Assert.fail("Exception expected, but not thrown.");
        } catch (APIMgtDAOException ex) {
            Assert.assertEquals(ex.getMessage(), "Application Policy not found for name: " +
                    addedPolicy.getPolicyName());
        }
    }

    @Test(description = "Add,Get and Delete Subscription Policies")
    public void testAddGetDeleteSubscriptionPolicies()
            throws Exception {
        SubscriptionPolicy policy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
        policy.setUuid("3d253272-25b3-11e7-93ae-92361f002671");
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        //add policy
        policyDAO.addSubscriptionPolicy(policy);
        //get added policy
        Policy addedPolicy = policyDAO.getSubscriptionPolicy(policy.getPolicyName());
        Assert.assertNotNull(addedPolicy);
        Assert.assertEquals(addedPolicy.getPolicyName(), policy.getPolicyName());
        //delete policy
        policyDAO.deletePolicy(APIMgtAdminService.PolicyLevel.subscription, policy.getPolicyName());
        //get policy after deletion
        try {
            policyDAO.getSubscriptionPolicy(policy.getPolicyName());
            Assert.fail("Exception expected, but not thrown.");
        } catch (APIMgtDAOException ex) {
            Assert.assertEquals(ex.getMessage(), "Subscription Policy not found for name: "
                    + addedPolicy.getPolicyName());
        }
    }

    @Test(description = "Get API Policies")
    public void testGetAPIPolicies() throws Exception {
        APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicy();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        //add policy
        policyDAO.addApiPolicy(policy);
        List<APIPolicy> policyList = policyDAO.getApiPolicies();
        Assert.assertNotNull(policyList);
        Assert.assertNotNull(policyDAO.getApiPolicy(policy.getPolicyName()), "Retrieving API policy by name failed "
                + "for policy with name: " + policy.getPolicyName());
        Assert.assertNotNull(policyDAO.getApiPolicyByUuid(policy.getUuid()), "Retrieving API policy by id failed for "
                + "policy with id: " + policy.getUuid());
    }

    @Test(description = "Get Application Policies")
    public void testGetApplicationPolicies() throws Exception {
        ApplicationPolicy policy = SampleTestObjectCreator.createDefaultApplicationPolicy();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        //add policy
        policyDAO.addApplicationPolicy(policy);
        List<ApplicationPolicy> policyList = policyDAO.getApplicationPolicies();
        Assert.assertNotNull(policyList);
        Assert.assertNotNull(policyDAO.getApplicationPolicy(policy.getPolicyName()), "Retrieving Application policy by "
                + "name failed for policy with name: " + policy.getPolicyName());
        Assert.assertNotNull(policyDAO.getApplicationPolicyByUuid(policy.getUuid()), "Retrieving Application policy "
                + "by id failed for policy with id: " + policy.getUuid());
    }
    @Test(description = "Get Subscription Policies")
    public void testGetSubscriptionPolicies() throws Exception {
        SubscriptionPolicy policy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        //add policy
        policyDAO.addSubscriptionPolicy(policy);
        List<SubscriptionPolicy> policyList = policyDAO.getSubscriptionPolicies();
        Assert.assertNotNull(policyList);
        Assert.assertNotNull(policyDAO.getSubscriptionPolicy(policy.getPolicyName()), "Retrieving Subscription policy "
                + "by name failed for policy with name: " + policy.getPolicyName());
        Assert.assertNotNull(policyDAO.getSubscriptionPolicyByUuid(policy.getUuid()), "Retrieving Subscription policy "
                + "by id failed for policy with id: " + policy.getUuid());
    }

    @Test(description = "Get API Policies with bandwidth limit")
    public void testGetAPIPolicyWithBandwidthLimit()
            throws Exception {
        APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicyWithBandwidthLimit();
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        //add policy
        policyDAO.addApiPolicy(policy);
        Policy policyAdded = policyDAO.getApiPolicy(policy.getPolicyName());
        Assert.assertNotNull(policyAdded);
        Assert.assertEquals(policyAdded.getPolicyName(), policy.getPolicyName());
    }

    @Test(description = "policy exists test")
    public void testPolicyExists () throws Exception {
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();

        ApplicationPolicy applicationPolicy = SampleTestObjectCreator.createDefaultApplicationPolicy();
        policyDAO.addApplicationPolicy(applicationPolicy);
        Assert.assertTrue(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.application,
                applicationPolicy.getPolicyName()), "Application policy with name: " + applicationPolicy.getPolicyName()
                + " does not exist");
        policyDAO.deletePolicyByUuid(APIMgtAdminService.PolicyLevel.application, applicationPolicy.getUuid());
        Assert.assertFalse(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.application,
                applicationPolicy.getPolicyName()), "Deleted Application policy with name: "
                + applicationPolicy.getPolicyName() + " still exists");

        SubscriptionPolicy subscriptionPolicy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
        policyDAO.addSubscriptionPolicy(subscriptionPolicy);
        Assert.assertTrue(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.subscription,
                subscriptionPolicy.getPolicyName()), "Subscription policy with name: "
                + subscriptionPolicy.getPolicyName() + " does not exist");
        policyDAO.deletePolicyByUuid(APIMgtAdminService.PolicyLevel.subscription, subscriptionPolicy.getUuid());
        Assert.assertFalse(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.subscription,
                subscriptionPolicy.getPolicyName()), "Deleted Subscription policy with name: "
                + subscriptionPolicy.getPolicyName() + " still exists");

        APIPolicy apiPolicy = SampleTestObjectCreator.createDefaultAPIPolicy();
        policyDAO.addApiPolicy(apiPolicy);
        Assert.assertTrue(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.api, apiPolicy.getPolicyName()), "API"
                + " policy with name: " + apiPolicy.getPolicyName() + " does not exist");
        policyDAO.deletePolicyByUuid(APIMgtAdminService.PolicyLevel.api, apiPolicy.getUuid());
        Assert.assertFalse(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.api, apiPolicy.getPolicyName()),
                "Deleted API policy with name: " + apiPolicy.getPolicyName() + " still exists");
    }

    @Test(description = "Add, Get, Delete block condition")
    public void testAddGetDeleteBlockConditions() throws Exception {

        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();

        BlockConditions blockConditionsIP = SampleTestObjectCreator
                .createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_IP);
        BlockConditions blockConditionsIpRange = SampleTestObjectCreator
                .createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITION_IP_RANGE);
        BlockConditions blockConditionsApi = SampleTestObjectCreator
                .createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_API);
        BlockConditions blockConditionsApp = SampleTestObjectCreator
                .createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_APPLICATION);
        BlockConditions blockConditionsUser = SampleTestObjectCreator
                .createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_USER);

        String uuidIp = policyDAO.addBlockConditions(blockConditionsIP);
        String uuidIpRange = policyDAO.addBlockConditions(blockConditionsIpRange);
        String uuidApi = policyDAO.addBlockConditions(blockConditionsApi);
        String uuidApp = policyDAO.addBlockConditions(blockConditionsApp);
        String uuidUser = policyDAO.addBlockConditions(blockConditionsUser);

        BlockConditions blockConditionsAddedIP = policyDAO.getBlockConditionByUUID(uuidIp);
        BlockConditions blockConditionsAddedIpRange = policyDAO.getBlockConditionByUUID(uuidIpRange);
        BlockConditions blockConditionsAddedApi = policyDAO.getBlockConditionByUUID(uuidApi);
        BlockConditions blockConditionsAddedApp = policyDAO.getBlockConditionByUUID(uuidApp);
        BlockConditions blockConditionsAddedUser = policyDAO.getBlockConditionByUUID(uuidUser);

        Assert.assertEquals(blockConditionsIP.getConditionValue(), blockConditionsAddedIP.getConditionValue());
        Assert.assertEquals(blockConditionsApi.getConditionValue(), blockConditionsAddedApi.getConditionValue());
        Assert.assertEquals(blockConditionsApp.getConditionValue(), blockConditionsAddedApp.getConditionValue());
        Assert.assertEquals(blockConditionsUser.getConditionValue(), blockConditionsAddedUser.getConditionValue());
        Assert.assertEquals(blockConditionsIpRange.getStartingIP(), blockConditionsAddedIpRange.getStartingIP());

        Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidIp));
        Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidIpRange));
        Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidApi));
        Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidApp));
        Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidUser));
    }

    @Test
    public void testAddGetDeleteCustomPolicy() throws Exception {
        PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
        CustomPolicy customPolicy = SampleTestObjectCreator.createDefaultCustomPolicy();
        String uuid = policyDAO.addCustomPolicy(customPolicy);

        CustomPolicy policyAdded = policyDAO.getCustomPolicyByUuid(uuid);
        Assert.assertEquals(customPolicy.getSiddhiQuery(), policyAdded.getSiddhiQuery());

        policyDAO.deleteCustomPolicy(uuid);
        CustomPolicy policyDeletion = policyDAO.getCustomPolicyByUuid(uuid);
        Assert.assertNull(policyDeletion);
    }
}


text:
<?php

namespace Respect\Validation\Exceptions\SubdivisionCode;

use Respect\Validation\Exceptions\SubdivisionCodeException;

/**
 * Exception class for Turks and Caicos Islands subdivision code.
 *
 * ISO 3166-1 alpha-2: TC
 */
class TcSubdivisionCodeException extends SubdivisionCodeException
{
    public static $defaultTemplates = [
        self::MODE_DEFAULT => [
            self::STANDARD => '{{name}} must be a subdivision code of Turks and Caicos Islands',
        ],
        self::MODE_NEGATIVE => [
            self::STANDARD => '{{name}} must not be a subdivision code of Turks and Caicos Islands',
        ],
    ];
}


text:
(function() {
  'use strict';

  Polymer({
    is: 'gr-agreements-list',
    _legacyUndefinedCheck: true,

    properties: {
      _agreements: Array,
    },

    behaviors: [
      Gerrit.BaseUrlBehavior,
    ],

    attached() {
      this.loadData();
    },

    loadData() {
      return this.$.restAPI.getAccountAgreements().then(agreements => {
        this._agreements = agreements;
      });
    },

    getUrl() {
      return this.getBaseUrl() + '/settings/new-agreement';
    },

    getUrlBase(item) {
      return this.getBaseUrl() + '/' + item;
    },
  });
})();


text:
package com.opentok.accelerator.core.listeners;

import android.os.Handler;
import com.opentok.android.OpentokError;

import java.util.concurrent.ConcurrentLinkedQueue;

public class PausableAdvancedListener<Wrapper> implements RetriableAdvancedListener<Wrapper> {

    private AdvancedListener mUnderlyingListener = null;
    private ConcurrentLinkedQueue<Runnable> mPendingOperations;

    public PausableAdvancedListener(AdvancedListener listener) {
        mUnderlyingListener = listener;
        mPendingOperations = new ConcurrentLinkedQueue<Runnable>();
    }

    @Override
    public AdvancedListener setInternalListener(AdvancedListener listener) {
        AdvancedListener previous = mUnderlyingListener;
        mUnderlyingListener = listener;
        return previous;
    }

    @Override
    public AdvancedListener getInternalListener() {
        return mUnderlyingListener;
    }

    @Override
    public void resume() {
        while(!mPendingOperations.isEmpty()) {
            // Stage the pending events letting the screen refresh between each event...
            new Handler().postDelayed(mPendingOperations.poll(), 18);
        }
    }

    private interface ListenerTask {
        public void run() throws ListenerException;
    }

    private void runUIListenerTask(final ListenerTask task) {
        new Runnable() {
            @Override
            public void run() {
                if (mUnderlyingListener == null) {
                    return;
                }
                try {
                    task.run();
                } catch (ListenerException e) {
                    mPendingOperations.add(this);
                }
            }
        }.run();
    }

    @Override
    public void onReconnecting(final Wrapper wrapper)  {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onReconnecting(wrapper);
            }
        });
    }

    @Override
    public void onReconnected(final Wrapper wrapper)  {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onReconnected(wrapper);
            }
        });
    }

    @Override
    public void onReconnected(final Wrapper wrapper, final String remoteId) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onReconnected(wrapper, remoteId);
            }
        });
    }

    @Override
    public void onDisconnected(final Wrapper wrapper, final String remoteId) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onDisconnected(wrapper, remoteId);
            }
        });
    }

    @Override
    public void onAudioEnabled(final Wrapper wrapper, final String remoteId) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onAudioEnabled(wrapper, remoteId);
            }
        });
    }

    @Override
    public void onAudioDisabled(final Wrapper wrapper, final String remoteId) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onAudioDisabled(wrapper, remoteId);
            }
        });
    }

    @Override
    public void onVideoQualityWarning(final Wrapper wrapper, final String remoteId) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onVideoQualityWarning(wrapper, remoteId);
            }
        });
    }

    @Override
    public void onVideoQualityWarningLifted(final Wrapper wrapper, final String remoteId) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onVideoQualityWarningLifted(wrapper, remoteId);
            }
        });
    }

    @Override
    public void onAudioLevelUpdated(final float audioLevel) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onAudioLevelUpdated(audioLevel);
            }
        });
    }

    @Override
    public void onError(final Wrapper wrapper, final OpentokError error) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onError(wrapper, error);
            }
        });
    }

    @Override
    public void onCameraChanged(final Wrapper wrapper) {
        runUIListenerTask(new ListenerTask() {
            @Override
            public void run() throws ListenerException {
                mUnderlyingListener.onCameraChanged(wrapper);
            }
        });
    }
}


text:
/// <reference path="../Scripts/angular-1.1.4.js" />

var app = angular.module('travelApp', [ 'ngRoute', 'ngCookies', 'ngResource',
		'travelApp.directives.localWeather' ,'travelApp.directives.switch','travelApp.directives.equalHeight','travelApp.directives.canvasjs','googlechart' , 'i18n','angularSmoothscroll','ui.bootstrap','travelapp.config','ngDialog','ngMap','catalogService','catalogFilters']);

app.factory('Poll', function($resource) {
	return $resource('polls/:pollId', {pollId: "@pollId" },
	{
		query : {
			method : 'GET',
			params : {
				pollId : 'polls'
			},
			isArray : true
		}
	});
});

app.factory('socket', function($rootScope) {
	var socket = io.connect();
	return {
		on : function(eventName, callback) {
			socket.on(eventName, function() {
				var args = arguments;
				$rootScope.$apply(function() {
					callback.apply(socket, args);
				});
			});
			},
		emit : function(eventName, data, callback) {
			socket.emit(eventName, data, function() {
				var args = arguments;
				$rootScope.$apply(function() {
					if (callback) {
						callback.apply(socket, args);
					}
				});
			});
		}
	};
});

// This configures the routes and associates each route with a view and a
// controller
app.config(function($routeProvider) {
	$routeProvider.when('/', {
		controller : 'MenuController',
		templateUrl : 'travelapp/partials/landingPage.html',
		resolve  : {
                           i18n    : [ "i18n", function( i18n ) { return i18n.i18n(); } ],
                           loggedin: checkLoggedin
                    }
	}).when('/placesAll', {
		controller : 'DestinationsController',
		templateUrl : 'travelapp/partials/destinations.html',
		resolve  : {
                           i18n    : [ "i18n", function( i18n ) { return i18n.i18n(); } ]
                    }
	}).when('/groupedDestinations', {
		controller : 'GroupedDestinationsController',
		templateUrl : 'travelapp/partials/groupedDestinations.html',
		resolve  : {
                           i18n    : [ "i18n", function( i18n ) { return i18n.i18n(); } ]
                    }
	}).when('/profile', {
		controller : 'ProfileController',
		templateUrl : 'travelapp/partials/profile.html',
		resolve  : {
                           i18n    : [ "i18n", function( i18n ) { return i18n.i18n(); } ]
                    }
	}).when('/polls', {
		templateUrl : 'travelapp/partials/pollListing.html',
		controller : 'PollListCtrl',
		resolve  : {
                           loggedin: checkLoggedin
                    }
	}).when('/poll/:pollId', {
		templateUrl : 'travelapp/partials/pollItem.html',
		controller : 'PollItemCtrl'
	}).when('/remove/:pollId', {
		templateUrl : 'travelapp/partials/pollListing.html',
		controller : 'PollRemoveItemCtrl'
	}).when('/new', {
		templateUrl : 'travelapp/partials/pollCreation.html',
		controller : 'PollNewCtrl'
	}).when('/dash', {
		templateUrl : 'travelapp/partials/dashboard.html',
		controller : 'DashController'
	}).when('/invoice', {
		templateUrl : 'travelapp/partials/invoice.html',
		controller : 'InvoiceController'
	}).when('/catalog', {
		templateUrl : 'travelapp/partials/packageList.html',
		controller : 'PackageListController'
	}).when('/catalog/:catalogId', {
		templateUrl : 'travelapp/partials/packageDetails.html',
		controller : 'PackageDetailsController'
	}).otherwise({
		redirectTo : '/'
	});
});

// Interceptor to avoid user from accessing protected pages which
// require logging in.
app.config(function($httpProvider) {
	$httpProvider.responseInterceptors.push(function($q, $location) {
    return function(promise) {
     return promise.then(
     // Success: just return the response
     function(response){
     	return response;
     },
     // Error: check the error status to get only the 401
     function(response) {
     	if (response.status === 401)
     		$location.url('/login');
     	return $q.reject(response);
     }
     );
     };
	});
});

var checkLoggedin = function($q, $timeout, $http, $location, $rootScope)
{
	// Make an AJAX call to check if the user is logged in
	var loggedIn = $http.get('/loggedin');
	$rootScope.user = 0;
	loggedIn.then(function(dataResponse) {
        $rootScope.user = dataResponse.data;

	});
};


text:
<?php

/**
 * Autoloader for Fork CMS.
 *
 * @author Dieter Vanden Eynde <dieter@dieterve.be>
 */
class Autoloader
{
	/**
	 * @param string $className
	 */
	public function load($className)
	{
		$unifiedClassName = strtolower((string) $className);
		$pathToLoad = '';

		// exceptions
		$exceptions = array();
		$exceptions['frontend'] = __DIR__ . '/frontend/core/engine/frontend.php';
		$exceptions['frontendtemplatecompiler'] = __DIR__ . '/frontend/core/engine/template_compiler.php';
		$exceptions['backend'] = __DIR__ . '/backend/core/engine/backend.php';
		$exceptions['backendajaxaction'] = __DIR__ . '/backend/core/engine/ajax_action.php';
		$exceptions['fl'] = __DIR__ . '/frontend/core/engine/language.php';
		$exceptions['bl'] = __DIR__ . '/backend/core/engine/language.php';
		$exceptions['api'] = __DIR__ . '/api/1.0/engine/api.php';

		// is it an exception?
		if(isset($exceptions[$unifiedClassName])) $pathToLoad = $exceptions[$unifiedClassName];

		// if it is a Spoon-class we can stop using this autoloader
		elseif(substr($unifiedClassName, 0, 5) == 'spoon') return;

		elseif(substr($unifiedClassName, 0, 12) == 'frontendbase') $pathToLoad = __DIR__ . '/frontend/core/engine/base.php';
		elseif(substr($unifiedClassName, 0, 13) == 'frontendblock') $pathToLoad = __DIR__ . '/frontend/core/engine/block.php';
		elseif(substr($unifiedClassName, 0, 8) == 'frontend') $pathToLoad = __DIR__ . '/frontend/core/engine/' . str_replace('frontend', '', $unifiedClassName) . '.php';
		elseif(substr($unifiedClassName, 0, 11) == 'backendbase') $pathToLoad = __DIR__ . '/backend/core/engine/base.php';
		elseif(substr($unifiedClassName, 0, 15) == 'backenddatagrid') $pathToLoad = __DIR__ . '/backend/core/engine/datagrid.php';
		elseif(substr($unifiedClassName, 0, 7) == 'backend') $pathToLoad = __DIR__ . '/backend/core/engine/' . str_replace('backend', '', $unifiedClassName) . '.php';
		elseif(substr($unifiedClassName, 0, 6) == 'common') $pathToLoad = __DIR__ . '/library/base/' . str_replace('common', '', $unifiedClassName) . '.php';

		// file check in core
		if($pathToLoad != '' && file_exists($pathToLoad)) require_once $pathToLoad;

		// check if module file exists
		else
		{
			// split in parts, if nothing is found we stop processing
			if(!preg_match_all('/[A-Z][a-z0-9]*/', $className, $parts)) return;

			// the real matches
			$parts = $parts[0];

			// root path based on the application we are trying to load
			$root = array_shift($parts);
			$root = __DIR__ . '/' . strtolower($root);

			foreach($parts as $i => $part)
			{
				// skip the first
				if($i == 0) continue;

				// action
				$action = strtolower(implode('_', $parts));

				// module
				$module = '';
				for($j = 0; $j < $i; $j++) $module .= strtolower($parts[$j]) . '_';

				// fix action & module
				$action = substr($action, strlen($module));
				$module = substr($module, 0, -1);

				// check the actions, engine & widgets directories
				foreach(array('actions', 'engine', 'widgets') as $dir)
				{
					// file to be loaded
					$pathToLoad = $root . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $action . '.php';

					// if it exists, load it!
					if($pathToLoad != '' && file_exists($pathToLoad))
					{
						require_once $pathToLoad;
						break;
					}
				}
			}
		}
	}
}

// register the autoloader
spl_autoload_register(array(new Autoloader(), 'load'));

// use vendor generated autoloader
require_once 'vendor/autoload.php';

// Spoon is not autoloaded via Composer but uses its own old skool autoloader
set_include_path(__DIR__ . '/vendor/spoon/library' . PATH_SEPARATOR . get_include_path());
require_once 'spoon/spoon.php';


text:
package com.brooks.jeremy.starglider.glglue;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;

import com.brooks.jeremy.starglider.GameState;
import com.brooks.jeremy.starglider.IReleaseListener;

public class StarCatcherSurfaceView extends GLSurfaceView
{
	private boolean mRendererSet = false;
	StarCatcherRenderer mRenderer = null;

	public StarCatcherSurfaceView(Context context)
	{
		super(context);
		init(context);
	}

	private void init(Context context)
	{
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		ConfigurationInfo configurationInfo = activityManager
				.getDeviceConfigurationInfo();

		final boolean supportsEs2 = (configurationInfo.reqGlEsVersion >= 0x20000);

		if (supportsEs2)
		{
			// Create an OpenGL ES 2.0 context.
			setEGLContextClientVersion(2);
			mRenderer = new StarCatcherRenderer();
			mRenderer.setSurface(this);
			setRenderer(mRenderer);
			mRendererSet = true;
		}

	}

	public void release(IReleaseListener released)
	{
		this.onPause();
		mRenderer.release(released);
	}

	public StarCatcherSurfaceView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		init(context);
	}

	public StarCatcherSurfaceView(Context context, AttributeSet attrs,
			int defStyle)
	{
		super(context, attrs);
		init(context);
	}

	public boolean GetRendererSet()
	{
		return mRendererSet;
	}

	public GameState getGameState()
	{
		return mRenderer.mGame.getGameState();
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev)
	{

		// Let the ScaleGestureDetector inspect all events.

		final int action = MotionEventCompat.getActionMasked(ev);

		switch (action)
		{
		case MotionEvent.ACTION_DOWN:
		{
			final int pointerIndex = MotionEventCompat.getActionIndex(ev);
			final float x = MotionEventCompat.getX(ev, pointerIndex);
			final float y = MotionEventCompat.getY(ev, pointerIndex);
			mRenderer.getGame().mouseDown(x, y);
			invalidate();

			break;
		}

		case MotionEvent.ACTION_MOVE:
		{
			// Find the index of the active pointer and fetch its position
			final int pointerIndex = MotionEventCompat.getActionIndex(ev);

			final float x = MotionEventCompat.getX(ev, pointerIndex);
			final float y = MotionEventCompat.getY(ev, pointerIndex);

			mRenderer.getGame().mouseMotion(x, y);

			invalidate();

			break;
		}

		case MotionEvent.ACTION_UP:
		{
			final int pointerIndex = MotionEventCompat.getActionIndex(ev);
			final float x = MotionEventCompat.getX(ev, pointerIndex);
			final float y = MotionEventCompat.getY(ev, pointerIndex);
			mRenderer.getGame().mouseUp(x, y);
			invalidate();

			break;

		}

		case MotionEvent.ACTION_POINTER_UP:
		{

			final int pointerIndex = MotionEventCompat.getActionIndex(ev);
			final float x = MotionEventCompat.getX(ev, pointerIndex);
			final float y = MotionEventCompat.getY(ev, pointerIndex);
			invalidate();
			mRenderer.getGame().mouseUp(x, y);
			break;

		}
		}
		return true;

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		mRenderer.getGame().keyDown();
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event)
	{
		mRenderer.getGame().keyUp();
		return super.onKeyUp(keyCode, event);
	}
}


text:
namespace TicketingSystem.Server.Areas.HelpPage.ModelDescriptions
{
    public class SimpleTypeModelDescription : ModelDescription
    {
    }
}


text:
import Helpers from '../../test-helpers'
import FixedQueue from '../../../src/js/utils/fixed-queue'

const { module, test } = Helpers

module('Unit: Utils: FixedQueue')

test('basic implementation', assert => {
  let queue = new FixedQueue(3)
  for (let i = 0; i < 3; i++) {
    queue.push(i)
  }

  assert.equal(queue.length, 3)

  let popped = []
  while (queue.length) {
    popped.push(queue.pop())
  }

  assert.deepEqual(popped, [2, 1, 0])
})

test('empty queue', assert => {
  let queue = new FixedQueue(0)
  assert.equal(queue.length, 0)
  assert.equal(queue.pop(), undefined)
  queue.push(1)

  assert.equal(queue.length, 0)
  assert.deepEqual(queue.toArray(), [])
})

test('push onto full queue ejects first item', assert => {
  let queue = new FixedQueue(1)
  queue.push(0)
  queue.push(1)

  assert.deepEqual(queue.toArray(), [1])
})


text:
class AddTimestampsToNodes < ActiveRecord::Migration
  def change
    add_column :nodes, :created_at, :datetime
    add_column :nodes, :updated_at, :datetime
  end
end


text:
import prerender from "../prerender";
import stats from "../../build/stats.json";

var publicPath = stats.publicPath;

var STYLE_URL;
var SCRIPT_URL_COMMON;
var SCRIPT_URL_APP = publicPath + [].concat(stats.assetsByChunkName.app)[0];
var SCRIPT_URL_ADMIN = publicPath + [].concat(stats.assetsByChunkName.admin)[0];
if (process.env.NODE_ENV === "production") {
  var COMMON_CHUNK = stats.assetsByChunkName.commons;
  STYLE_URL = (publicPath + "app.css?" + stats.hash);
  SCRIPT_URL_COMMON =  publicPath + "commons.js?" + stats.hash;
  SCRIPT_URL_APP += "?" + stats.hash;
  SCRIPT_URL_ADMIN += "?" + stats.hash;
}

exports.index = function *() {
  try {
    const { appString, DATA } = yield prerender(this);
    this.body = yield this.render("index", {
      isAuth: !!this.passport.user,
      render: appString,
      DATA: JSON.stringify(DATA),
      version: stats.appVersion,
      commit: stats.appCommit,
      STYLE_URL: STYLE_URL,
      SCRIPT_URL_COMMON: SCRIPT_URL_COMMON,
      SCRIPT_URL_APP: SCRIPT_URL_APP,
    });
  } catch (error) {
    if (error.redirect) {
      return this.redirect(error.redirect);
    }
    throw error;
  }
};

exports.admin = function *() {
  this.body = yield this.render("admin", {
    user: this.passport.user,
    version: stats.appVersion,
    commit: stats.appCommit,
    STYLE_URL: STYLE_URL,
    SCRIPT_URL_COMMON: SCRIPT_URL_COMMON,
    SCRIPT_URL_ADMIN: SCRIPT_URL_ADMIN,
  });
};


text: serviceworkers-enhancment


text:
def remove_adjacent(nums):
  return list(set(nums))

# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
	result=[]
	while len(list1) and len(list2):
		if list1[0]<list2[0]:
			result.append(list1.pop(0))
		else:
			result.append(list2.pop(0))
	result.extend(list1)
	result.extend(list2)
	return result

# Note: the solution above is kind of cute, but unforunately list.pop(0)
# is not constant time with the standard python list implementation, so
# the above is not strictly linear time.
# An alternate approach uses pop(-1) to remove the endmost elements
# from each list, building a solution list which is backwards.
# Then use reversed() to put the result back in the correct order. That
# solution works in linear time, but is more ugly.

# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
  if got == expected:
    prefix = ' OK '
  else:
    prefix = '  X '
  print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))

# Calls the above functions with interesting inputs.
def main():
  print 'remove_adjacent'
  test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
  test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
  test(remove_adjacent([]), [])

  print
  print 'linear_merge'
  test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']),
       ['aa', 'bb', 'cc', 'xx', 'zz'])
  test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']),
       ['aa', 'bb', 'cc', 'xx', 'zz'])
  test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']),
       ['aa', 'aa', 'aa', 'bb', 'bb'])

if __name__ == '__main__':
  main()


text:
namespace atomic_ns = std;

#else // !defined(BOOST_FILESYSTEM_NO_CXX20_ATOMIC_REF)

#include <boost/memory_order.hpp>
#include <boost/atomic/atomic_ref.hpp>

namespace atomic_ns = boost;

#endif // !defined(BOOST_FILESYSTEM_NO_CXX20_ATOMIC_REF)

#endif // BOOST_FILESYSTEM_SRC_ATOMIC_REF_HPP_


text:
package com.epam.catgenome.manager.vcf.reader;

import static com.epam.catgenome.entity.BiologicalDataItemResourceType.GA4GH;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import com.epam.catgenome.entity.BiologicalDataItemResourceType;
import com.epam.catgenome.entity.reference.Chromosome;
import com.epam.catgenome.entity.track.Track;
import com.epam.catgenome.entity.vcf.Variation;
import com.epam.catgenome.entity.vcf.VariationType;
import com.epam.catgenome.entity.vcf.VcfFile;
import com.epam.catgenome.exception.VcfReadingException;
import com.epam.catgenome.manager.FileManager;
import com.epam.catgenome.manager.externaldb.HttpDataManager;
import com.epam.catgenome.manager.reference.ReferenceGenomeManager;
import com.epam.catgenome.util.feature.reader.EhCacheBasedIndexCache;

/**
 *  {@code AbstractVcfReader} provides an abstract implementation of
 *  {@code VcfReader}. It defines several constants for VCf format
 *   and provides a factory method for creating {@code VcfReader} instances.
 */
public abstract class AbstractVcfReader implements VcfReader {
    protected static final List<Pattern> BIND_PATTERNS = new ArrayList<>();
    protected static final String BIND_CHR_ATTRIBUTE = "BIND_CHR";
    protected static final String BIND_POS_ATTRIBUTE = "BIND_POS";
    protected static final String STRUCT_DEL_TAG = "<DEL>";
    protected static final String STRUCT_INS_TAG = "<INS>";
    protected static final Pattern DUP_TAG = Pattern.compile("<DUP.*>");
    protected static final String INV_TAG = "<INV>";

    static {
        BIND_PATTERNS.add(Pattern.compile("\\w*\\[(\\w++):(\\d++)\\[\\w*"));
        BIND_PATTERNS.add(Pattern.compile("\\w*\\](\\w++):(\\d++)\\]\\w*"));
    }

    protected ReferenceGenomeManager referenceGenomeManager;

    protected Variation findLastNotBndVariation(List<Variation> variations) {
        for (int i = variations.size() - 1; i >= 0; i--) {
            if (variations.get(i).getType() != VariationType.BND) {
                return variations.get(i);
            }
        }
        return null;
    }

    /**
     * Factory method for creating a {@code VcfReader} instance according to the data resource type.
     * File system and GA4GH services are supported for VCF files.
     * @param resourceType determines the class of created {@code VcfReader}
     * @param httpDataManager for access to VCF data in the GA4GH service
     * @param fileManager for access to VCF file in the file system
     * @param referenceGenomeManager for loading reference data
     * @return a {@code VcfReader} instance for reading VCF data
     */
    public static VcfReader createVcfReader(final BiologicalDataItemResourceType resourceType, final HttpDataManager
            httpDataManager, final FileManager fileManager, final ReferenceGenomeManager referenceGenomeManager) {
        return resourceType == GA4GH ? new VcfGa4ghReader(httpDataManager, referenceGenomeManager) :
                new VcfFileReader(fileManager, referenceGenomeManager);
    }

    /**
     * Reads the variations data from the VCF source and loads it into a track
     * @param vcfFile data source
     * @param track for loading data
     * @param chromosome reference sequence
     * @param sampleIndex determines fro which sample from the file variations are loaded
     * @param loadInfo if true data from the INFO fields from VCF file will be loaded into the track,
     *                 otherwise it will be ignored
     * @return {@code Track} filled with variations from a specified {@code VcfFile}
     * @throws VcfReadingException
     */
    @Override
    public abstract Track<Variation> readVariations(VcfFile vcfFile, Track<Variation> track, Chromosome chromosome,
                            Integer sampleIndex, boolean loadInfo, boolean collapse,
                                                    EhCacheBasedIndexCache indexCache) throws VcfReadingException;

    /**
     * Allows navigating between the neighbouring variations
     * @param fromPosition start position for finding a neighbouring variation
     * @param vcfFile data source
     * @param sampleIndex determines fro which sample from the file variations are loaded
     * @param chromosome reference sequence
     * @param forward if true the next variation is loaded, otherwise the previous
     * @return
     * @throws VcfReadingException
     */
    @Override
    public abstract Variation getNextOrPreviousVariation(int fromPosition, VcfFile vcfFile,
                                                Integer sampleIndex, Chromosome chromosome,
                                                boolean forward, EhCacheBasedIndexCache indexCache)
            throws VcfReadingException;
}


text:
//
//  IFFormView.h
//  SemoContent
//
//  Created by Julian Goacher on 12/02/2016.
//  Copyright © 2016 InnerFunction. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "IFIOCContainerAware.h"
#import "IFFormField.h"
#import "IFHTTPClient.h"

typedef void (^IFFormViewDataEvent)(IFFormView *, id);
typedef void (^IFFormViewErrorEvent)(IFFormView *, NSError *);

/**
 * Protocol implemented by form fields which can indicate form loading status.
 */
@protocol IFFormLoadingIndicator <NSObject>

- (void)showFormLoading:(BOOL)loading;

@end

@interface IFFormView : UITableView <UITableViewDataSource, UITableViewDelegate, IFIOCContainerAware> {
    NSInteger _focusedFieldIdx;
    UIEdgeInsets _defaultInsets;
    NSDictionary *_defaultValues;
    NSDictionary *_inputValues;
    id<IFFormLoadingIndicator> _loadingIndicator;
}

/** The list of form fields. */
@property (nonatomic, strong) NSArray *fields;
/** The form submit method, e.g. GET or POST. */
@property (nonatomic, strong) NSString *method;
/** The URL to submit the form to. */
@property (nonatomic, strong) NSString *submitURL;
/** An internal URI to post when submitting the form. */
@property (nonatomic, strong) NSString *submitURI;
/** A dictionary containing values for all named input fields. */
@property (nonatomic, strong) NSDictionary *inputValues;
/** Flag specifying whether the form is enabled or not. */
@property (nonatomic, assign) BOOL isEnabled;
/** A HTTP client to use when submitting the form to a URL. */
@property (nonatomic, strong) IFHTTPClient *httpClient;

@property (nonatomic, copy) IFFormViewErrorEvent onSubmitRequestError;
@property (nonatomic, copy) IFFormViewDataEvent onSubmitError;
@property (nonatomic, copy) IFFormViewDataEvent onSubmitOk;

// The view controller the form is displayed within. This is needed by some field types to
// e.g. present modal dialogs.
@property (nonatomic, weak) UIViewController *viewController;

/** Get the current value of a named field. */
- (id)getFieldValue:(NSString *)name;
/** Get the currently focused field. */
- (IFFormField *)getFocusedField;
/** Clear the current field focus. */
- (void)clearFieldFocus;
/** Move field focus to the next focusable field. */
- (void)moveFocusToNextField;
/** Reset all fields to the original values. */
- (void)reset;
/**
 * Validate all field values.
 * If any field is invalid then moves field focus to the first invalid field, and then returns false.
 */
- (BOOL)validate;
/**
 * Submit the form.
 * Validates the form before submitting. Returns true if the form is valid and was submitted.
 */
- (BOOL)submit;
/**
 * Update the form's visible state to show that it is submitting.
 */
- (void)submitting:(BOOL)submitting;
/**
 * Submit event callback.
 * Called if the request failed below the application layer.
 */
- (void)submitRequestError:(NSError *)error;
/**
 * Test if a submit response is an application level error.
 */
- (BOOL)isSubmitErrorResponse:(IFHTTPClientResponse *)response;
/**
 * Submit event callback.
 * Called if an application level error occurs on submit.
 */
- (void)submitError:(IFHTTPClientResponse *)response;
/**
 * Submit event callback.
 * Called if the submit request is successful.
 */
- (void)submitOk:(IFHTTPClientResponse *)response;
/**
 * Display a notification of a form error.
 */
- (void)notifyError:(NSString *)message;
/**
 * Notify the form of a field resize.
 */
- (void)notifyFormFieldResize:(IFFormField *)field;
/**
 * Return a list of the fields on this form within the same name group.
 */
- (NSArray *)getFieldsInNameGroup:(NSString *)name;

@end


text:
package org.jmock;

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

import org.jmock.core.CoreMock;
import org.jmock.core.DynamicMock;
import org.jmock.core.Formatting;
import org.jmock.core.Verifiable;
import org.jmock.util.Dummy;
import org.jmock.util.Verifier;

/**
 * @author Andres Almiray <aalmiray@users.sourceforge.net>
 */
public class DefaultMockTester implements MockTester
{
   private List objectsThatRequireVerification = new ArrayList();

   public DefaultMockTester()
   {

   }

   public String defaultMockNameForType( Class mockedType )
   {
      return "mock" + Formatting.classShortName( mockedType );
   }

   public Mock mock( Class mockedType )
   {
      return mock( mockedType, defaultMockNameForType( mockedType ) );
   }

   public Mock mock( Class mockedType, String roleName )
   {
      Mock newMock = new Mock( newCoreMock( mockedType, roleName ) );
      registerToVerify( newMock );
      return newMock;
   }

   public DynamicMock newCoreMock( Class mockedType, String roleName )
   {
      return new CoreMock( mockedType, roleName );
   }

   public Object newDummy( Class dummyType )
   {
      return Dummy.newDummy( dummyType );
   }

   public Object newDummy( Class dummyType, String name )
   {
      return Dummy.newDummy( dummyType, name );
   }

   public Object newDummy( String name )
   {
      return Dummy.newDummy( name );
   }

   public void registerToVerify( Verifiable verifiable )
   {
      objectsThatRequireVerification.add( verifiable );
   }

   public void unregisterToVerify( Verifiable verifiable )
   {
      objectsThatRequireVerification.remove( verifiable );
   }

   public void verify()
   {
      for( Iterator iterator = objectsThatRequireVerification.iterator(); iterator.hasNext(); ){
         Verifiable verifiable = (Verifiable) iterator.next();
         verifiable.verify();
      }
      Verifier.verifyObject( this );
   }
}


text:
using System;

namespace DotNetXri.Syntax
{
	/// <summary>
	/// This class provides a strong typing for a XRI subsegment.  Any
	/// obj of this class that appears outside of the package is a valid
	/// subsegment.
	/// </summary>
	public class XRISubSegment : Parsable
	{
		bool mbPersistant = false;
		XRef moXRef = null;
		bool mbAllowColon = false;
		bool mbAllowImpliedDelimiter = false;

		/// <summary>
		///
		/// </summary>
		/// <param name="bAllowImpliedDelimiter"></param>
		/// <param name="bAllowColon"></param>
		/// <remarks>
		/// Protected Constructor used by package only
		/// </remarks>
		internal XRISubSegment(bool bAllowImpliedDelimiter, bool bAllowColon)
		{
			mbAllowImpliedDelimiter = bAllowImpliedDelimiter;
			mbAllowColon = bAllowColon;
		}

		/// <summary>
		/// Constructs SubSegment from String
		/// </summary>
		/// <param name="sXRI"></param>
		public XRISubSegment(string sXRI)
			: base(sXRI)
		{
			parse();
		}

		/// <summary>
		/// Constructs SubSegment from String
		/// </summary>
		/// <param name="sXRI"></param>
		/// <param name="bAllowColon"></param>
		public XRISubSegment(string sXRI, bool bAllowColon)
			: base(sXRI)
		{
			mbAllowColon = bAllowColon;
			parse();
		}

		/// <summary>
		/// Indicates whether Subsegment is persistent or not
		/// </summary>
		/// <returns>Indicates whether Subsegment is persistent or not</returns>
		public bool isPersistant()
		{
			return mbPersistant;
		}

		/// <summary>
		/// Returns the cross-reference of this obj
		/// </summary>
		/// <returns>XRef the cross-reference of this obj</returns>
		public XRef getXRef()
		{
			parse();
			return moXRef;
		}

		/// <summary>
		/// String representation of the obj.
		/// </summary>
		/// <returns>the String form of the SubSegment with its persistent indicator.</returns>
		public override string ToString()
		{
			return ToString(true);
		}

		public string ToString(bool wantOptionalDelim)
		{
			parse();

			// add the dot if necessary
			string sRetval = base.ToString();
			if ((sRetval.Length > 0) &&
				(sRetval[0] != XRI.RDELIM) &&
				(sRetval[0] != XRI.PDELIM) &&
				wantOptionalDelim)
			{
				sRetval = XRI.RDELIM_S + sRetval;
			}

			return sRetval;
		}

		public bool Equals(XRISubSegment subseg)
		{
			return ToString(true).Equals(subseg.ToString(true));
		}

		public bool EqualsIgnoreCase(XRISubSegment subseg)
		{
			return ToString(true).Equals(subseg.ToString(true), StringComparison.InvariantCultureIgnoreCase);
		}

		/// <summary>
		/// Parses the input stream into the obj
		/// </summary>
		/// <param name="oStream">The input stream to scan from</param>
		/// <returns>True if part of the Stream was consumed into the obj</returns>
		bool doScan(ParseStream oStream)
		{
			if (oStream.getData()[0] == XRI.PDELIM)
			{
				this.mbPersistant = true;
				oStream.consume(1);
			}
			else if (oStream.getData()[0] == XRI.RDELIM)
			{
				oStream.consume(1);
			}
			else if (!mbAllowImpliedDelimiter)
			{
				return false;
			}

			// if there is a cross-reference, it has priority in scanning
			XRef oXRef = new XRef();
			if (oXRef.scan(oStream))
			{
				moXRef = oXRef;
				return true;
			}

			// read the characters, it is ok if they are empty
			int n = scanPChars(oStream.getData());
			oStream.consume(n);

			return true;
		}

		/// <summary>
		/// Reads xri-pchars from the String
		/// </summary>
		/// <param name="s">The String to scan from</param>
		/// <returns>The number of characters read in</returns>
		private int scanPChars(string s)
		{
			int c;
			for (int i = 0; i < s.Length; i += UTF16.getCharCount(c))
			{
				c = UTF16.charAt(s, i);

				if (Characters.isPChar(c))
				{
					// pchar includes colon, but our configuration might not allow it
					if (c != ':')
						continue;

					// it's a colon, only let through if our configuration allows it
					if (mbAllowColon)
						continue;
				}

				//
				// escaped
				//
				if (Characters.isEscaped(c, s, i))
				{
					i += 2;
					continue;
				}

				return i;
			}

			return s.Length;
		}

		/// <summary>
		/// Serializes SubSegment into IRI normal from
		/// </summary>
		/// <returns>The IRI normal form of the SubSegment</returns>
		public string toIRINormalForm()
		{
			return toIRINormalForm(true);
		}

		public string toIRINormalForm(bool wantOptionalDelim)
		{
			if (moXRef != null)
			{
				string value;
				if (isPersistant())
					value = XRI.PDELIM_S;
				else
					value = wantOptionalDelim ? XRI.RDELIM_S : "";
				return value + moXRef.toIRINormalForm();
			}

			return IRIUtils.XRItoIRI(ToString(wantOptionalDelim), false);
		}

		/// <summary>
		/// Serializes SubSegment into URI normal from
		/// </summary>
		/// <returns>The URI normal form of the SubSegment</returns>
		public string toURINormalForm()
		{
			return toURINormalForm(true);
		}

		public string toURINormalForm(bool wantOptionalDelim)
		{
			return IRIUtils.IRItoURI(toIRINormalForm(wantOptionalDelim));
		}
	}
}


text:
QT_BEGIN_NAMESPACE

NumList LGraphicsWebView::overrideIds = NumList() << 24 << 223 << 211 << 212 << 229 << 243 << 214 << 215 << 216 << 217 << 218 << 15 << 35 << 16 << 221 << 222 << 37 << 17 << 18 << 224 << 225 << 226 << 227 << 242 << 231;
NumList LWebHistoryInterface::overrideIds = NumList() << 353 << 354;
NumList LWebInspector::overrideIds = NumList() << 26 << 36 << 41 << 42;
NumList LWebPage::overrideIds = NumList() << 355 << 356 << 357 << 358 << 359 << 360 << 361 << 362 << 363 << 364 << 365 << 366;
NumList LWebPluginFactory::overrideIds = NumList() << 367 << 355 << 368 << 369 << 356;
NumList LWebView::overrideIds = NumList() << 370 << 24 << 26 << 14 << 29 << 30 << 31 << 32 << 33 << 15 << 35 << 16 << 37 << 17 << 18 << 39 << 19 << 20 << 21 << 22 << 41 << 44;
NumList LWebDatabase::overrideIds = NumList();
NumList LWebElement::overrideIds = NumList();
NumList LWebElementCollection::overrideIds = NumList();
NumList LWebHistoryItem::overrideIds = NumList();
NumList LWebHitTestResult::overrideIds = NumList();
NumList LWebSecurityOrigin::overrideIds = NumList();

void ini() {
    static bool _ = false; if(_) return; _ = true;
    ini2();
    LObjects::Q[81] = new Q82;
    LObjects::Q[213] = new Q214;
    LObjects::Q[214] = new Q215;
    LObjects::Q[215] = new Q216;
    LObjects::Q[216] = new Q217;
    LObjects::Q[217] = new Q218;
    LObjects::Q[218] = new Q219;
    LObjects::N[192] = new N193;
    LObjects::N[193] = new N194;
    LObjects::N[194] = new N195;
    LObjects::N[195] = new N196;
    LObjects::N[196] = new N197;
    LObjects::N[197] = new N198;
    LObjects::N[198] = new N199;
    LObjects::N[199] = new N200; }

const QMetaObject* staticMetaObject(int n) {
    const QMetaObject* m = 0;
    switch(n) {
        case 82: m = &QGraphicsWebView::staticMetaObject; break;
        case 214: m = &QWebFrame::staticMetaObject; break;
        case 215: m = &QWebHistoryInterface::staticMetaObject; break;
        case 216: m = &QWebInspector::staticMetaObject; break;
        case 217: m = &QWebPage::staticMetaObject; break;
        case 218: m = &QWebPluginFactory::staticMetaObject; break;
        case 219: m = &QWebView::staticMetaObject; break; }
    return m; }

void deleteNObject(int n, void* p, int gc) {
    switch(n) {
        case 193: if(gc) delete (QWebDatabase*)p; else delete (LWebDatabase*)p; break;
        case 194: if(gc) delete (QWebElement*)p; else delete (LWebElement*)p; break;
        case 195: if(gc) delete (QWebElementCollection*)p; else delete (LWebElementCollection*)p; break;
        case 197: if(gc) delete (QWebHistoryItem*)p; else delete (LWebHistoryItem*)p; break;
        case 198: if(gc) delete (QWebHitTestResult*)p; else delete (LWebHitTestResult*)p; break;
        case 199: if(gc) delete (QWebSecurityOrigin*)p; else delete (LWebSecurityOrigin*)p; break; }}

NumList* overrideFunctions(const QByteArray& name) {
    NumList* ids = 0;
    int n = LObjects::q_names.value(name, -1);
    if(n != -1) {
        switch(n) {
            case 82: ids = &LGraphicsWebView::overrideIds; break;
            case 215: ids = &LWebHistoryInterface::overrideIds; break;
            case 216: ids = &LWebInspector::overrideIds; break;
            case 217: ids = &LWebPage::overrideIds; break;
            case 218: ids = &LWebPluginFactory::overrideIds; break;
            case 219: ids = &LWebView::overrideIds; break; }}
    else {
        n = LObjects::n_names.value(name);
        switch(n) {
            case 193: ids = &LWebDatabase::overrideIds; break;
            case 194: ids = &LWebElement::overrideIds; break;
            case 195: ids = &LWebElementCollection::overrideIds; break;
            case 197: ids = &LWebHistoryItem::overrideIds; break;
            case 198: ids = &LWebHitTestResult::overrideIds; break;
            case 199: ids = &LWebSecurityOrigin::overrideIds; break; }}
    return ids; }

QT_END_NAMESPACE


text:
Please visit project Wiki pages for more information:

https://github.com/syampolsky/yankee-cookies/wiki


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Binance.Net.Enums;

namespace Binance.Net.Converters
{
    internal class FuturesOrderTypeConverter : JsonConverter
    {
        private readonly bool quotes;

        public FuturesOrderTypeConverter()
        {
            quotes = true;
        }

        public FuturesOrderTypeConverter(bool useQuotes)
        {
            quotes = useQuotes;
        }

        private readonly Dictionary<FuturesOrderType, string> values = new Dictionary<FuturesOrderType, string>
        {
            { FuturesOrderType.Limit, "LIMIT" },
            { FuturesOrderType.Market, "MARKET" },
            { FuturesOrderType.TakeProfit, "TAKE_PROFIT" },
            { FuturesOrderType.TakeProfitMarket, "TAKE_PROFIT_MARKET" },
            { FuturesOrderType.Stop, "STOP" },
            { FuturesOrderType.StopMarket, "STOP_MARKET" },
            { FuturesOrderType.TrailingStopMarket, "TRAILING_STOP_MARKET" },
            { FuturesOrderType.Liquidation, "LIQUIDATION" }
        };

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(FuturesOrderType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
        {
            return values.Single(v => v.Value == (string?)reader.Value).Key;
        }

        public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            if (quotes)
                writer.WriteValue(values[(FuturesOrderType)value!]);
            else
                writer.WriteRawValue(values[(FuturesOrderType)value!]);
        }
    }
}


text:
package editor;

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class BevelArrows
{
    public static void main ( String...args )
    {
        SwingUtilities.invokeLater ( new Runnable () {
            BevelArrows arrows = new BevelArrows();

            @Override
            public void run () {
                JFrame frame = new JFrame ( "Bevel Arrows" );

                frame.add ( new JPanel() {
                    public void paintComponent ( Graphics g ) {
                        arrows.draw ( ( Graphics2D ) g, getWidth(), getHeight() );
                    }
                }
                , BorderLayout.CENTER );

                frame.setSize ( 800, 400 );
                frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
                frame.setVisible ( true );
            }
        } );
    }

    interface Arrow {
        void draw ( Graphics2D g );
    }

    Arrow[] arrows = { new LineArrow(), new CurvedArrow() };

    void draw ( Graphics2D g, int width, int height )
    {
        g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

        g.setColor ( Color.WHITE );
        g.fillRect ( 0, 0, width, height );
        g.setColor ( Color.BLACK );
        g.draw(createArrowShape(new Point(100,100), new Point(200,200)));

    }

    public static Shape createArrowShape(Point fromPt, Point toPt) {
        Polygon arrowPolygon = new Polygon();
        arrowPolygon.addPoint(-6,1);
        arrowPolygon.addPoint(3,1);
        arrowPolygon.addPoint(3,3);
        arrowPolygon.addPoint(6,0);
        arrowPolygon.addPoint(3,-3);
        arrowPolygon.addPoint(3,-1);
        arrowPolygon.addPoint(-6,-1);

        Point midPoint = midpoint(fromPt, toPt);

        double rotate = Math.atan2(toPt.y - fromPt.y, toPt.x - fromPt.x);

        AffineTransform transform = new AffineTransform();
        transform.translate(midPoint.x, midPoint.y);
        double ptDistance = fromPt.distance(toPt);
        double scale = ptDistance / 12.0; // 12 because it's the length of the arrow polygon.
        transform.scale(scale, scale);
        transform.rotate(rotate);

        return transform.createTransformedShape(arrowPolygon);
    }

    private static Point midpoint(Point p1, Point p2) {
        return new Point((int)((p1.x + p2.x)/2.0),
                         (int)((p1.y + p2.y)/2.0));
    }

    static class LineArrow  implements Arrow
    {
        public void draw ( Graphics2D g )
        {
            // where the control point for the intersection of the V needs calculating
            // by projecting where the ends meet

            float arrowRatio = 0.5f;
            float arrowLength = 80.0f;

            BasicStroke stroke = ( BasicStroke ) g.getStroke();

            float endX = 350.0f;

            float veeX;

            switch ( stroke.getLineJoin() ) {
                case BasicStroke.JOIN_BEVEL:
                    // IIRC, bevel varies system to system, this is approximate
                    veeX = endX - stroke.getLineWidth() * 0.25f;
                    break;
                default:
                case BasicStroke.JOIN_MITER:
                    veeX = endX - stroke.getLineWidth() * 0.5f / arrowRatio;
                    break;
                case BasicStroke.JOIN_ROUND:
                    veeX = endX - stroke.getLineWidth() * 0.5f;
                    break;
            }

            // vee
            Path2D.Float path = new Path2D.Float();

            path.moveTo ( veeX - arrowLength, -arrowRatio*arrowLength );
            path.lineTo ( veeX, 0.0f );
            path.lineTo ( veeX - arrowLength, arrowRatio*arrowLength );

            g.setColor ( Color.BLUE );
            g.draw ( path );

            // stem for exposition only
            g.setColor ( Color.YELLOW );
            g.draw ( new Line2D.Float ( 50.0f, 0.0f, veeX, 0.0f ) );

            // in practice, move stem back a bit as rounding errors
            // can make it poke through the sides of the Vee
            g.setColor ( Color.RED );
            g.draw ( new Line2D.Float ( 50.0f, 0.0f, veeX - stroke.getLineWidth() * 0.25f, 0.0f ) );
        }
    }

    static class CurvedArrow  implements Arrow
    {
        // to draw a nice curved arrow, fill a V shape rather than stroking it with lines
        public void draw ( Graphics2D g )
        {
            // as we're filling rather than stroking, control point is at the apex,

            float arrowRatio = 0.5f;
            float arrowLength = 80.0f;

            BasicStroke stroke = ( BasicStroke ) g.getStroke();

            float endX = 350.0f;

            float veeX = endX - stroke.getLineWidth() * 0.5f / arrowRatio;

            // vee
            Path2D.Float path = new Path2D.Float();

            float waisting = 0.5f;

            float waistX = endX - arrowLength * 0.5f;
            float waistY = arrowRatio * arrowLength * 0.5f * waisting;
            float arrowWidth = arrowRatio * arrowLength;

            path.moveTo ( veeX - arrowLength, -arrowWidth );
            path.quadTo ( waistX, -waistY, endX, 0.0f );
            path.quadTo ( waistX, waistY, veeX - arrowLength, arrowWidth );

            // end of arrow is pinched in
            path.lineTo ( veeX - arrowLength * 0.75f, 0.0f );
            path.lineTo ( veeX - arrowLength, -arrowWidth );

            g.setColor ( Color.BLUE );
            g.fill ( path );

            // move stem back a bit
            g.setColor ( Color.RED );
            g.draw ( new Line2D.Float ( 50.0f, 0.0f, veeX - arrowLength * 0.5f, 0.0f ) );
        }
    }
}


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

<title>hr.fer.zemris.ml.training.decision_tree</title>
<meta name="date" content="2017-07-01">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

hr.fer.zemris.ml.training.decision_tree

Interfaces

ITerminalNodeFactory

ITreeGenerator

Classes

CARTGenerator

TerminalNodeFactories


text:
@echo off
title Testing EZ.JWAF Rule
call msg info "[INFO] Testing EZ.JWAF Rule" & echo.

set BASEDIR=%~sdp0

pushd %BASEDIR%\..\src
  call mvn clean package -DperformTest=true -DperformSource=true
popd

call beep.bat
timeout /t 1 >NUL
call beep.bat
timeout /t 1 >NUL
call beep.bat
timeout /t 1 >NUL
call beep.bat
timeout /t 1 >NUL
call beep.bat
timeout /t 1 >NUL

pause


text:
Sherpa
=================
# What is Sherpa
* Sherpa is a library and a command-line tool create for easy deployment of customizations and sandboxed solutions On-premises and to SharePoint Online (Office 365)
* Sherpa allows you to
  * Deploy taxonomy (groups, term sets and terms) with known IDs and export to the same format
  * Upload, activate and upgrade sandboxed solutions
  * Create fields and content types
  * Configure sites (features, lists, quicklaunch, properties, upload files)
  * Import search configuration

# Why use Sherpa
The deployment story with especially SharePoint Online leaves a lot to be desired. If you're creating anything but apps, the deploy process is manual or requires you to write your own deploy scrips and code from scratch. Sherpa allows you to deploy your artifacts in a repeatable manner from day one, without having to spend time writing code.

# How does Sherpa work?
* The Sherpa library communicates with SharePoint exclusively through the Client Side Object Model (CSOM). Sherpa can thus configure both SharePoint on-premises and SharePoint Online
* The bundled console application uses the Sherpa library allows us to quickly get started

# Getting started
1. Clone the project from github
2. Add your fields, content types, taxonomy and site hierarchy etc through configuration, look at the sample config for guidance
3. In case you are doing sandboxed solutions, build the solution and navigate to the out folder, typically Sherpa.Installer\bin\debug. Put any Sandboxed solutions you might have in the folder 'solutions'
4. Start Sherpa.exe and pass the parameters 'url' and 'username' to hint where and as whom the application should connect. Add the flag --spo if and only if you are connecting to SharePoint Online. You can type 'Sherpa.exe --help' for help
5. Sherpa will authenticate the user after you provide the password. After this you can choose which action you want to perform. Sherpa also supports Windows Credential Manager

# What Sherpa won't do
At the moment Sherpa is connecting to a single site collection, which means that Sherpa will not create new site collections. This also means that a site collection has to be created by an administrator up front. Sherpa also does not do any tenant administration tasks, except for setting up taxonomy in the term store.

# Tools and resources
* JSON Prettifier - Format JSON nicely
* Mr. Data Converter - Convert Excel to JSON
* JSONLint - JSON validator

# About
The sherpa tool is built by Puzzlepart AS as part of the Project portal for SharePoint project for Asker Kommune and KommIT.

# Disclaimer
The tool is a work in progress, and not considered finished. Use at own risk. We do not recommend usage of the tool in production environments. The maintainers takes no responsibility of errors or bugs in the tool, problems caused by the tool or by usage errors.

# Maintainers
Tarjei Ormestøyl [tarjeieo@puzzlepart.com],
Ole Kristian Mørch-Storstein [olekms@puzzlepart.com]


text:
<?php

class Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpec extends Google_Collection
{
  protected $collection_key = 'childParameterSpecs';
  protected $categoricalValueSpecType = 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecCategoricalValueSpec';
  protected $categoricalValueSpecDataType = '';
  protected $childParameterSpecsType = 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpec';
  protected $childParameterSpecsDataType = 'array';
  protected $discreteValueSpecType = 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecDiscreteValueSpec';
  protected $discreteValueSpecDataType = '';
  protected $doubleValueSpecType = 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecDoubleValueSpec';
  protected $doubleValueSpecDataType = '';
  protected $integerValueSpecType = 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecIntegerValueSpec';
  protected $integerValueSpecDataType = '';
  public $parameter;
  protected $parentCategoricalValuesType = 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentCategoricalValueSpec';
  protected $parentCategoricalValuesDataType = '';
  protected $parentDiscreteValuesType = 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentDiscreteValueSpec';
  protected $parentDiscreteValuesDataType = '';
  protected $parentIntValuesType = 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentIntValueSpec';
  protected $parentIntValuesDataType = '';
  public $scaleType;
  public $type;

  /**
   * @param Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecCategoricalValueSpec
   */
  public function setCategoricalValueSpec(Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecCategoricalValueSpec $categoricalValueSpec)
  {
    $this->categoricalValueSpec = $categoricalValueSpec;
  }
  /**
   * @return Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecCategoricalValueSpec
   */
  public function getCategoricalValueSpec()
  {
    return $this->categoricalValueSpec;
  }
  /**
   * @param Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpec
   */
  public function setChildParameterSpecs($childParameterSpecs)
  {
    $this->childParameterSpecs = $childParameterSpecs;
  }
  /**
   * @return Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpec
   */
  public function getChildParameterSpecs()
  {
    return $this->childParameterSpecs;
  }
  /**
   * @param Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecDiscreteValueSpec
   */
  public function setDiscreteValueSpec(Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecDiscreteValueSpec $discreteValueSpec)
  {
    $this->discreteValueSpec = $discreteValueSpec;
  }
  /**
   * @return Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecDiscreteValueSpec
   */
  public function getDiscreteValueSpec()
  {
    return $this->discreteValueSpec;
  }
  /**
   * @param Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecDoubleValueSpec
   */
  public function setDoubleValueSpec(Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecDoubleValueSpec $doubleValueSpec)
  {
    $this->doubleValueSpec = $doubleValueSpec;
  }
  /**
   * @return Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecDoubleValueSpec
   */
  public function getDoubleValueSpec()
  {
    return $this->doubleValueSpec;
  }
  /**
   * @param Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecIntegerValueSpec
   */
  public function setIntegerValueSpec(Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecIntegerValueSpec $integerValueSpec)
  {
    $this->integerValueSpec = $integerValueSpec;
  }
  /**
   * @return Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecIntegerValueSpec
   */
  public function getIntegerValueSpec()
  {
    return $this->integerValueSpec;
  }
  public function setParameter($parameter)
  {
    $this->parameter = $parameter;
  }
  public function getParameter()
  {
    return $this->parameter;
  }
  /**
   * @param Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentCategoricalValueSpec
   */
  public function setParentCategoricalValues(Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentCategoricalValueSpec $parentCategoricalValues)
  {
    $this->parentCategoricalValues = $parentCategoricalValues;
  }
  /**
   * @return Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentCategoricalValueSpec
   */
  public function getParentCategoricalValues()
  {
    return $this->parentCategoricalValues;
  }
  /**
   * @param Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentDiscreteValueSpec
   */
  public function setParentDiscreteValues(Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentDiscreteValueSpec $parentDiscreteValues)
  {
    $this->parentDiscreteValues = $parentDiscreteValues;
  }
  /**
   * @return Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentDiscreteValueSpec
   */
  public function getParentDiscreteValues()
  {
    return $this->parentDiscreteValues;
  }
  /**
   * @param Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentIntValueSpec
   */
  public function setParentIntValues(Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentIntValueSpec $parentIntValues)
  {
    $this->parentIntValues = $parentIntValues;
  }
  /**
   * @return Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1StudyConfigParameterSpecMatchingParentIntValueSpec
   */
  public function getParentIntValues()
  {
    return $this->parentIntValues;
  }
  public function setScaleType($scaleType)
  {
    $this->scaleType = $scaleType;
  }
  public function getScaleType()
  {
    return $this->scaleType;
  }
  public function setType($type)
  {
    $this->type = $type;
  }
  public function getType()
  {
    return $this->type;
  }
}


text:
package controllers.admin

import akka.util.Timeout
import controllers.BaseController
import play.api.i18n.MessagesApi
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import services.scheduled.ScheduledTask

import services.sandbox._
import services.user.AuthenticationEnvironment
import utils.DateUtils

import scala.concurrent.Future
import scala.concurrent.duration._

object SandboxController {
  val sandboxes = Seq(
    "scratchpad" -> "A one-off I don't feel like putting anwhere else.",
    "scheduled-task" -> "Run the scheduled task.",
    "error-mail" -> "Send the error email.",
    "backfill-metrics" -> "Backfill missing daily metrics."
  )
}

@javax.inject.Singleton
class SandboxController @javax.inject.Inject() (
    override val messagesApi: MessagesApi,
    override val env: AuthenticationEnvironment,
    scheduledTask: ScheduledTask
) extends BaseController {
  implicit val timeout = Timeout(10.seconds)

  def defaultSandbox() = sandbox("list")

  def sandbox(key: String) = withAdminSession(key) { implicit request =>
    val ret = key match {
      case "scratchpad" => Scratchpad.run()
      case "scheduled-task" => runScheduledTask()
      case "error-mail" => runErrorMail()
      case "backfill-metrics" => BackfillMetrics.run()
      case x => throw new IllegalArgumentException(s"Invalid sandbox [$x].")
    }
    ret.map {
      case s: String => Ok(s)
      case other => Ok("?: " + other.getClass.getName)
    }
  }

  private[this] def runScheduledTask() = scheduledTask.go(true).map { ret =>
    ret.map(x => s"${x._1}: ${x._2.getOrElse("No progress")}").mkString("\n")
  }

  private[this] def runErrorMail() = Future.successful(
    views.html.email.severeErrorHtml(
      "Error Message",
      "Test Context",
      Some(new Exception("Text Exception")),
      None,
      DateUtils.now
    )
  )
}