text:
package ru.yandex.money.android.sample;

import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yandex.money.api.methods.payment.params.P2pTransferParams;
import com.yandex.money.api.methods.payment.params.PaymentParams;
import com.yandex.money.api.methods.payment.params.PhoneParams;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Properties;

import ru.yandex.money.android.PaymentActivity;
import ru.yandex.money.android.sample.storage.DatabaseHelper;
import ru.yandex.money.android.utils.Views;

public class PayActivity extends ListActivity {

    private static final int REQUEST_CODE = 101;

    private static final String EXTRA_PAYMENT = "ru.yandex.money.android.sample.extra.PAYMENT";

    private Payment payment;
    private DatabaseHelper helper;

    private EditText paymentTo;
    private EditText amount;
    private TextView previous;

    public static void startP2P(Context context) {
        startActivity(context, Payment.P2P);
    }

    public static void startPhone(Context context) {
        startActivity(context, Payment.PHONE);
    }

    private static void startActivity(Context context, Payment payment) {
        Intent intent = new Intent(context, PayActivity.class);
        intent.putExtra(EXTRA_PAYMENT, payment);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        payment = (Payment) getIntent().getSerializableExtra(EXTRA_PAYMENT);
        helper = DatabaseHelper.getInstance(this);

        init();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK &&
                !loadValues().contains(getPaymentTo())) {
            switch (payment) {
                case P2P:
                    helper.saveAccountNumber(getPaymentTo());
                    break;
                case PHONE:
                    helper.savePhoneNumber(getPaymentTo());
                    break;
            }
            updatePrevious();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_pay, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.pay:
                pay();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        paymentTo.setText((String) l.getItemAtPosition(position));
    }

    private void init() {
        paymentTo = (EditText) findViewById(R.id.payment_to);
        switch (payment) {
            case P2P:
                paymentTo.setHint(R.string.activity_pay_account_hint);
                break;
            case PHONE:
                paymentTo.setHint(R.string.activity_pay_phone_hint);
                break;
        }

        amount = (EditText) findViewById(R.id.amount);

        previous = (TextView) findViewById(R.id.previous);
        updatePrevious();
    }

    private void updatePrevious() {
        List<String> values = prepareValues(loadValues());
        if (values.isEmpty()) {
            setListAdapter(null);
            getListView().setVisibility(View.GONE);
            previous.setVisibility(View.GONE);
        } else {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_list_item_1, values);
            setListAdapter(adapter);
            getListView().setVisibility(View.VISIBLE);
            previous.setVisibility(View.VISIBLE);
        }
    }

    private List<String> prepareValues(List<String> values) {
        if (payment == Payment.PHONE) {
            for (int i = 0; i < values.size(); ++i) {
                String number = PhoneNumberUtils.formatNumber("+" + values.get(i));
                values.remove(i);
                values.add(i, number);
            }
        }
        return values;
    }

    private List<String> loadValues() {
        switch (payment) {
            case P2P:
                return helper.getAccountNumbers();
            case PHONE:
                return helper.getPhoneNumber();
            default:
                throw new IllegalArgumentException();
        }
    }

    private void pay() {
        if (isValid()) {
            switch (payment) {
                case P2P:
                    startPaymentActivityForResult(new P2pTransferParams.Builder(getPaymentTo())
                            .setAmount(getAmount())
                            .create());
                    break;
                case PHONE:
                    startPaymentActivityForResult(PhoneParams.newInstance(getPaymentTo(),
                            getAmount()));
                    break;
            }
        } else {
            Toast.makeText(this, R.string.activity_pay_toast, Toast.LENGTH_SHORT).show();
        }
    }

    private void startPaymentActivityForResult(PaymentParams paymentParams) {
        ApiData apiData = ApiData.getFromProperties(this);
        Intent intent = PaymentActivity.getBuilder(this)
                .setPaymentParams(paymentParams)
                .setClientId(apiData.clientId)
                .setHost(apiData.host)
                .build();
        startActivityForResult(intent, REQUEST_CODE);
    }

    private String getPaymentTo() {
        return Views.getTextSafely(paymentTo).replaceAll("\\D", "");
    }

    private BigDecimal getAmount() {
        return new BigDecimal(Views.getTextSafely(amount));
    }

    private boolean isValid() {
        return !TextUtils.isEmpty(Views.getTextSafely(paymentTo)) &&
                !TextUtils.isEmpty(Views.getTextSafely(amount)) && getAmount().doubleValue() > 0;
    }

    private static class ApiData {

        final String clientId;
        final String host;

        private ApiData(String clientId, String host) {
            this.clientId = clientId;
            this.host = host;
        }

        static ApiData getFromProperties(Context context) {
            Properties prop = loadProperties(context);
            return new ApiData(prop.getProperty("client_id"), prop.getProperty("host"));
        }

        private static Properties loadProperties(Context context) {
            InputStream is = null;
            try {
                is = context.getAssets().open("app.properties");
                Properties prop = new Properties();
                prop.load(is);
                return prop;
            } catch (IOException e) {
                throw new IllegalStateException("no properties file found", e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        // does nothing
                    }
                }
            }
        }
    }

    private enum Payment {
        P2P,
        PHONE
    }
}


text:
package speedtyper.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import speedtyper.dao.HighscoreDao;
import speedtyper.model.HighscoreModel;
import speedtyper.service.HighscoreService;

@Service
public class HighscoreServiceImpl implements HighscoreService {

	@Autowired
	private HighscoreDao highscoreDao;

	@Transactional
	public void add(HighscoreModel highscore) {
		this.highscoreDao.add(highscore);
	}

	@Transactional
	public void update(HighscoreModel highscore) {
		this.highscoreDao.update(highscore);
	}

	@Transactional
	public void delete(int id) {
		this.highscoreDao.delete(id);
	}

	@Transactional
	public HighscoreModel getHighscore(int userId, int roomId) {
		return this.highscoreDao.getHighscore(userId, roomId);
	}

	@Transactional
	public List<HighscoreModel> getHighscoreByUserId(int userId) {
		return this.highscoreDao.getHighscoreByUserId(userId);
	}

	@Transactional
	public HighscoreModel getHighscoreById(int id) {
		return this.highscoreDao.getHighscoreById(id);
	}

	@Transactional
	public List<HighscoreModel> getTop100() {
		return this.highscoreDao.getTop100();
	}

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * This have the keycode of the TvKeys.
 * @ {Objects}
 */
var tvKey = {};
/**
 * Contains the main tasks of the app.
 * @ {Object}
 */
var app = {
    /**
     * App initializations.
     */
    initialize: function() {
        this.bindEvents();
    },
    /**
     * Bind all the common events that are required on startup.
     */
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
        document.addEventListener("visibilitychange", this.onVisibilityChange.bind(this), false);
    },
    /**
     * Deviceready Even Handler.
     */
    onDeviceReady: function() {
        toast.inputdevice.getSupportedKeys(function(keys){
            for(var i = 0; i < keys.length; i++)
            {
                switch(keys[i].name)
                {
                case 'ArrowUp':
                    tvKey.KEY_UP = keys[i].code;
                    break;
                case 'ArrowDown':
                    tvKey.KEY_DOWN = keys[i].code;
                    break;
                case 'ArrowLeft':
                    tvKey.KEY_LEFT = keys[i].code;
                    break;
                case 'ArrowRight':
                    tvKey.KEY_RIGHT = keys[i].code;
                    break;
                case 'Enter':
                    tvKey.KEY_ENTER = keys[i].code;
                    break;
                case 'Return':
                    tvKey.KEY_RETURN = keys[i].code;
                    break;
                case 'Exit':
                    tvKey.KEY_EXIT = keys[i].code;
                    toast.inputdevice.registerKey("Exit", function(args) {});
                    break;
                }
            }
        });
        this.initGame();
    },
    /**
     * Manages the multitasking behavior.
     */
    onVisibilityChange: function() {
        if(document.hidden) {
            this.onPauseApp();
        } else if(SceneManager) {
            /**
             * This timeout is to avoid bad resume for native client on 2015 models,
             * it's applies when the TV have instant on activated and is turned on back .
             */
            setTimeout(this.onResumeApp, 1000);
        }
    },
    /**
     * Pause the game activity.
     */
    onResumeApp: function() {
        window.resumming = true;
        if(SceneManager.current.indexOf('Game') >= 0) {
            if(SceneManager.current.indexOf('Two' >= 0)) {
                player.play(sounds.stage_01_bg_sound,true);
            } else {
                player.play(sounds["stage_0"+(currentLevel.stageIndex+1)+"_bg_sound"],true);
            }
        } else {
            player.play(sounds.game_menu,true);
        }
    },
    /**
     * Resumes the game activity.
     */
    onPauseApp: function() {
        player.stopAll();
        window.suspending = true;
        if(SceneManager[SceneManager.current] && SceneManager[SceneManager.current].closeTutorial) {
            SceneManager[SceneManager.current].closeTutorial();
        }
        if(SceneManager.current != "MainMenu" && SceneManager.current.indexOf('Pause') < 0) {
            triggerKey(tvKey.KEY_RETURN);
        }
    },
    initGame: function() {
        head.js(
            /*Default Libraries*/
            {Jquery: "app/javascripts/jquery-2.2.3.min.js"},
            {Move: "app/javascripts/move.js"},
            {State_machine: "app/javascripts/state-machine.min.js"},
            {Easeljs: "app/javascripts/easeljs-0.7.1.min.js"},
            {Tweenjs: "app/javascripts/tweenjs-0.5.1.min.js"},
            {Preloadjs: "app/javascripts/preloadjs-0.4.0.min.js"},
            {Player: "app/javascripts/player_nacl.js"},
            /*Common functions*/
            {Common: "app/common.js"},
            {Init: "app/init.js"},
            /*Easter Egg*/
            {game: "app/javascripts/samsung/game.js"},
            {breakout: "app/javascripts/samsung/breakout.js"},
            {levels: "app/javascripts/samsung/levels.js"},
            /*Scenes functions*/
            {Title: "app/scenes/Title.js"},
            {MainMenu: "app/scenes/MainMenu.js"},
            {EasterEgg: "app/scenes/EasterEgg.js"},
            {ArcadeLevels: "app/scenes/ArcadeLevels.js"},
            {GameStart: "app/scenes/GameStart.js"},
            {GamePause: "app/scenes/GamePause.js"},
            {GameEnd: "app/scenes/GameEnd.js"},
            {TwoPlayersGameStart: "app/scenes/TwoPlayersGameStart.js"},
            {TwoPlayersGamePause: "app/scenes/TwoPlayersGamePause.js"},
            {TwoPlayersGameEnd: "app/scenes/TwoPlayersGameEnd.js"},
            /*Game Functions*/
            {ImageLoader: "app/imageLoader.js"},
            {GameConfig: "app/gameConfig.js"},
            {StageConfig: "app/stages/stageConfig.js"},
            {Stage0: "app/stages/stage0.js"},
            {Stage1: "app/stages/stage1.js"},
            {Stage2: "app/stages/stage2.js"},
            {StagePlayer2_0: "app/stages/stageplayer20.js"},
            {GameEngine: "app/gameEngine.js"},
            {ImageLoader: "app/spriteGenerator.js"},
            /*Language management*/
            {LanguageConfig: "resources/language/languageConfig.js"},

            function(){
            SceneManager.start();
            // Checks the language of the TV set.
            navigator.globalization.getPreferredLanguage(
                function (language) {
                    if (language.value.indexOf('es') > -1) {
                        $("body").addClass("LANG-ESP");
                        head.js({Esp: "resources/language/esp.js"});
                        window.LANGUAGE.current = window.LANGUAGE.ESP;
                    } else {
                        $("body").addClass("LANG-ENG");
                        head.js({Esp: "resources/language/eng.js"});
                        window.LANGUAGE.current = window.LANGUAGE.ENG;
                    }
                }
            );
            Utils.logger.log("/*----- All scripts has been loaded --------*/");
            player =  new Player_NaCl(playerCallback, "resources/sounds/");
            imageArray.load();
        });
    }
};

app.initialize();


text:
"""This module exports the StylelintG plugin class."""
import os
from SublimeLinter.lint import Linter, util

class StylelintG(Linter):
    """Provides an interface to stylelint-g."""

    syntax = ('css', 'css3', 'sass', 'scss', 'postcss')
    cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@')
    error_stream = util.STREAM_BOTH
    config_file = ('--config', '.stylelintrc', '~')
    tempfile_suffix = 'css'
    regex = (
        r'^(?P<line>[0-9]+)\:(?P<col>[0-9]+)(?P<message>.+)'
    )


text:
package org.apache.spark.sql.sources.v2.streaming;

import java.util.Optional;

import org.apache.spark.annotation.InterfaceStability;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.DataSourceV2Options;
import org.apache.spark.sql.sources.v2.streaming.reader.MicroBatchReader;
import org.apache.spark.sql.types.StructType;

/**
 * A mix-in interface for {@link DataSourceV2}. Data sources can implement this interface to
 * provide streaming micro-batch data reading ability.
 */
@InterfaceStability.Evolving
public interface MicroBatchReadSupport extends DataSourceV2 {
  /**
   * Creates a {@link MicroBatchReader} to read batches of data from this data source in a
   * streaming query.
   *
   * The execution engine will create a micro-batch reader at the start of a streaming query,
   * alternate calls to setOffsetRange and createReadTasks for each batch to process, and then
   * call stop() when the execution is complete. Note that a single query may have multiple
   * executions due to restart or failure recovery.
   *
   * @param schema the user provided schema, or empty() if none was provided
   * @param checkpointLocation a path to Hadoop FS scratch space that can be used for failure
   *                           recovery. Readers for the same logical source in the same query
   *                           will be given the same checkpointLocation.
   * @param options the options for the returned data source reader, which is an immutable
   *                case-insensitive string-to-string map.
   */
  MicroBatchReader createMicroBatchReader(
      Optional<StructType> schema,
      String checkpointLocation,
      DataSourceV2Options options);
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of AdpType in UD_Romanian-SiMoNERo</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Romanian-SiMoNERo: Features: AdpType

This feature is language-specific.
It occurs with 1 different values: Prep.

20672 tokens (14%) have a non-empty value of AdpType.
69 types (0%) occur at least once with a non-empty value of AdpType.
42 lemmas (0%) occur at least once with a non-empty value of AdpType.
The feature is used with 2 part-of-speech tags: <tt>ADP</tt> (20076; 14% instances), <tt>PUNCT</tt> (596; 0% instances).

ADP

20076 <tt>ADP</tt> tokens (100% of all ADP tokens) have a non-empty value of AdpType.

The most frequent other feature values with which ADP and AdpType co-occurred: <tt>Case</tt><tt>=Acc</tt> (19775; 99%).

ADP tokens may have the following values of AdpType:

Prep (20076; 100% of non-empty AdpType): de, în, la, cu, din, pentru, prin, pe, dintre, după

AdpType seems to be lexical feature of ADP. 100% lemmas (40) occur only with one value of AdpType.

PUNCT

596 <tt>PUNCT</tt> tokens (3% of all PUNCT tokens) have a non-empty value of AdpType.

PUNCT tokens may have the following values of AdpType:

Prep (596; 100% of non-empty AdpType): /, ;

Relations with Agreement in AdpType

The 10 most frequent relations where parent and child node agree in AdpType:
<tt>ADP –[<tt>fixed</tt>]–> ADP</tt> (539; 100%),
<tt>ADP –[<tt>conj</tt>]–> ADP</tt> (13; 100%),
<tt>ADP –[<tt>mark</tt>]–> ADP</tt> (2; 100%),
<tt>ADP –[<tt>advmod</tt>]–> ADP</tt> (1; 100%),
<tt>ADP –[<tt>appos</tt>]–> ADP</tt> (1; 100%).

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
<link rel="import" href="/bower_components/polymer/polymer.html">

<!--
For Chrome Apps that use Bluetooth, add the bluetooth entry to the manifest
and specify, if appropriate, the UUIDs of profiles, protocols or services
you wish to implement along with whether you wish to implement these with
the socket and/or Low Energy APIs.

For example for a socket implementation:

...
"bluetooth": {
  "uuids": [ "1105", "1106" ],
  "socket": true
}
...

And for a Low Energy implementation:

...
"bluetooth": {
  "uuids": [ "180D", "1809", "180F" ],
  "low_energy": true
}
...

To only access adapter state, discover nearby devices, and obtain
basic information about devices, only the entry itself is required:

"bluetooth": { }

Use `chrome-bluetooth` element to connect to a Bluetooth device.

-->
<dom-module id="chrome-bluetooth">
  <template>
    <style>
      :host {
        display: block;
      }
    </style>

  </template>
  <script src="chrome-bluetooth.js"></script>
</dom-module>


text:
package mireka.pop;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;

import mireka.login.GlobalUser;
import mireka.login.GlobalUsers;
import mireka.pop.store.Maildrop;
import mireka.pop.store.MaildropAppender;
import mireka.pop.store.MaildropRepository;
import mireka.transmission.LocalMailSystemException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Import mails from remote POP3 servers to the local POP3 maildrops at system
 * startup. This is useful during migration.
 */
public class PopMailImporter {
    private final Logger logger = LoggerFactory
            .getLogger(PopMailImporter.class);
    private GlobalUsers users;
    private MaildropRepository maildropRepository;
    private String remoteHost = "localhost";
    private int remotePort = 110;
    private int totalMailCount = 0;
    private int totalUsersWithAtLeastOneMail = 0;

    @PostConstruct
    public void doImport() {
        logger.info("Importing mail from remote POP3 maildrops");
        for (GlobalUser user : users) {
            try {
                importMails(user);
            } catch (MessagingException e) {
                logger.error("Importing mails for " + user.getUsernameObject()
                        + " failed", e);
            }
        }
        logger.info("Importing mail from remote POP3 maildrops completed, "
                + totalMailCount + " mails were imported for "
                + totalUsersWithAtLeastOneMail
                + " users who had at least one mail.");
    }

    private void importMails(GlobalUser user) throws MessagingException {
        logger.debug("Importing mail for " + user.getUsernameObject());
        Properties properties = new Properties();
        Session session = Session.getInstance(properties);
        Store store =
                session.getStore(new URLName("pop3://"
                        + user.getUsernameObject() + ":" + user.getPassword()
                        + "@" + remoteHost + ":" + +remotePort + "/INBOX"));
        store.connect();
        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        Message[] messages = folder.getMessages();
        int cSuccessfulMails = 0;
        // user name currently equals with the maildrop name, but this is
        // not necessarily true in general.
        String maildropName = user.getUsernameObject().toString();
        for (Message message : messages) {
            try {
                importMail(maildropName, message);
                message.setFlag(Flags.Flag.DELETED, true);
                cSuccessfulMails++;
            } catch (Exception e) {
                logger.error("Importing a mail for " + user.getUsernameObject()
                        + " failed", e);
            }
        }
        folder.close(true);
        store.close();
        totalMailCount += cSuccessfulMails;
        if (cSuccessfulMails > 0)
            totalUsersWithAtLeastOneMail++;
        logger.debug(cSuccessfulMails + " mails were imported for "
                + user.getUsernameObject());
    }

    private void importMail(String maildropName, Message message)
            throws LocalMailSystemException, IOException, MessagingException {
        Maildrop maildrop = maildropRepository.borrowMaildrop(maildropName);
        try {
            MaildropAppender appender = maildrop.allocateAppender();
            try {
                OutputStream outputStream = appender.getOutputStream();
                message.writeTo(outputStream);
                appender.commit();
            } catch (IOException e) {
                appender.rollback();
                throw e;
            } catch (MessagingException e) {
                appender.rollback();
                throw e;
            }
        } finally {
            maildropRepository.releaseMaildrop(maildrop);
        }
    }

    /**
     * @x.category GETSET
     */
    public GlobalUsers getUsers() {
        return users;
    }

    /**
     * @x.category GETSET
     */
    public void setUsers(GlobalUsers users) {
        this.users = users;
    }

    /**
     * @x.category GETSET
     */
    public MaildropRepository getMaildropRepository() {
        return maildropRepository;
    }

    /**
     * @x.category GETSET
     */
    public void setMaildropRepository(MaildropRepository maildropRepository) {
        this.maildropRepository = maildropRepository;
    }

    /**
     * @x.category GETSET
     */
    public String getRemoteHost() {
        return remoteHost;
    }

    /**
     * @x.category GETSET
     */
    public void setRemoteHost(String remoteHost) {
        this.remoteHost = remoteHost;
    }

    /**
     * @x.category GETSET
     */
    public int getRemotePort() {
        return remotePort;
    }

    /**
     * @x.category GETSET
     */
    public void setRemotePort(int remotePort) {
        this.remotePort = remotePort;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">test_title_map</string>
</resources>


text:
package com.amazonaws.services.waf.model.waf.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.waf.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * GetSampledRequestsResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetSampledRequestsResultJsonUnmarshaller implements Unmarshaller<GetSampledRequestsResult, JsonUnmarshallerContext> {

    public GetSampledRequestsResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        GetSampledRequestsResult getSampledRequestsResult = new GetSampledRequestsResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return getSampledRequestsResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("SampledRequests", targetDepth)) {
                    context.nextToken();
                    getSampledRequestsResult.setSampledRequests(new ListUnmarshaller<SampledHTTPRequest>(SampledHTTPRequestJsonUnmarshaller.getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("PopulationSize", targetDepth)) {
                    context.nextToken();
                    getSampledRequestsResult.setPopulationSize(context.getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("TimeWindow", targetDepth)) {
                    context.nextToken();
                    getSampledRequestsResult.setTimeWindow(TimeWindowJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return getSampledRequestsResult;
    }

    private static GetSampledRequestsResultJsonUnmarshaller instance;

    public static GetSampledRequestsResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new GetSampledRequestsResultJsonUnmarshaller();
        return instance;
    }
}


text:
var Promise = require('bluebird');
var errs = libRequire('errors');
var qb = require('marklogic').queryBuilder;

module.exports = {
  // POJO-managed docs "bury" the content under a Java fully qualified
  // class name, so we find the first key an use it to locate the actual
  // content
  unwrapPojo: function (pojo) {
    return pojo[Object.keys(pojo)[0]];
  },

  getOnlyContent: function (response) {
    if (response.length !== 1) {
      throw errs.cardinality({ length: response.length,
        response: response });
    }
    else {
      return response[0].content;
    }
  },
  getOneOrNoneContent: function (response) {
    if (response.length > 1) {
      throw errs.cardinality({ length: response.length,
        response: response });
    }
    else {
      return response[0] ? response[0].content : undefined;
    }
  },

  specToValues: function (spec) {
    return _.map(spec, function (property, name) {
      return qb.value(name, property);
    });
  },

  uuid: require('node-uuid').v4
};


text:
package edu.tamu.tcat.db.postgresql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A set of utilities to help build database entities in PostgreSQL, such as databases and schemas.
 * @since 1.4
 */
public class PostgreSqlEntityHelper
{
   private static final Logger debug = Logger.getLogger(PostgreSqlEntityHelper.class.getName());

   /**
    * @param connDefaultDb A connection to the db server on the database "postgres"
    * @param targetDatabase The name of the database to create
    */
   public static boolean createDatabase(Connection connDefaultDb, String targetDatabase)
   {
      String sqlCheck = "SELECT EXISTS (SELECT * FROM pg_catalog.pg_database WHERE datname = ?)";
      try (PreparedStatement existsCheck = connDefaultDb.prepareStatement(sqlCheck))
      {
         existsCheck.setString(1, targetDatabase);
         try (ResultSet results = existsCheck.executeQuery())
         {
            if (!results.next())
            {
               debug.log(Level.WARNING, "Failed testing for database existence ["+sqlCheck+"]");
               return false;
            }

            boolean exists = results.getBoolean(1);
            if (exists)
               return false;
         }
      }
      catch (Exception e)
      {
         debug.log(Level.SEVERE, "Failed checking for existence of database ["+targetDatabase+"] with sql ["+sqlCheck+"]", e);
         // don't try to create if exist check failed
         return false;
      }

      debug.log(Level.INFO, "Database [" + targetDatabase + "] not found, creating it now");
      String sqlCreate = "CREATE DATABASE \"" + targetDatabase + "\"";
      try (PreparedStatement create = connDefaultDb.prepareStatement(sqlCreate))
      {
         create.executeUpdate();
         return true;
      }
      catch (Exception e)
      {
         debug.log(Level.SEVERE, "Failed creating database ["+targetDatabase+"] with sql ["+sqlCreate+"]", e);
         return false;
      }
   }

   /**
    * Create the "postgis" extension on the database for the given connection. The extension module
    * must already be installed on the database server, and this will ensure it is available in the database.
    *
    * @param conn
    */
   public static boolean createExtensionPostGis(Connection conn)
   {
      String sqlCheck = "SELECT EXISTS(select * from pg_extension where extname = 'postgis')";
      try (PreparedStatement existsCheck = conn.prepareStatement(sqlCheck))
      {
         try (ResultSet results = existsCheck.executeQuery())
         {
            if (!results.next())
            {
               debug.log(Level.WARNING, "Failed testing for extension existence ["+sqlCheck+"]");
               return false;
            }

            boolean exists = results.getBoolean(1);
            // schema already exists, exit early
            if (exists)
               return false;
         }
      }
      catch (Exception e)
      {
         debug.log(Level.SEVERE, "Failed checking for existence of extension [postgis] with sql ["+sqlCheck+"]", e);
         // don't try to create if exist check failed
         return false;
      }

      debug.log(Level.INFO, "Installing PostGIS extensions");
      try (PreparedStatement install = conn.prepareStatement("CREATE EXTENSION postgis"))
      {
         install.executeUpdate();
      }
      catch (Exception e)
      {
         debug.log(Level.WARNING, "Cannot create PostGIS extension, the package may need to be installed on the db server", e);
      }
      return true;
   }

   //NOTE: if these SQL statements fail, things are likely still okay; if the db is in trouble, using the schema later will fail
   public static boolean createSchema(Connection conn, String targetSchemaName)
   {
      String sqlCheck = "SELECT EXISTS(SELECT schema_name FROM information_schema.schemata WHERE schema_name = ?)";
      try (PreparedStatement existsCheck = conn.prepareStatement(sqlCheck))
      {
         existsCheck.setString(1, targetSchemaName);
         try (ResultSet results = existsCheck.executeQuery())
         {
            if (!results.next())
            {
               debug.log(Level.WARNING, "Failed testing for schema existence ["+sqlCheck+"]");
               return false;
            }

            boolean exists = results.getBoolean(1);
            // schema already exists, exit early
            if (exists)
               return false;
         }
      }
      catch (Exception e)
      {
         debug.log(Level.SEVERE, "Failed checking for existence of schema ["+targetSchemaName+"] with sql ["+sqlCheck+"]", e);
         // don't try to create if exist check failed
         return false;
      }

      debug.log(Level.INFO, "Schema [" + targetSchemaName + "] not found, creating it now");
      String sqlCreate = "CREATE SCHEMA \"" + targetSchemaName + "\"";
      try (PreparedStatement create = conn.prepareStatement(sqlCreate))
      {
         debug.log(Level.INFO, "Schema [" + targetSchemaName + "] not found, creating it now");
         create.executeUpdate();
         return true;
      }
      catch (Exception e)
      {
         debug.log(Level.SEVERE, "Failed creating schema ["+targetSchemaName+"] with sql ["+sqlCreate+"]", e);
         return false;
      }
   }
}


text:
/*******************************************************************************
 * 2018, All rights reserved.
 *******************************************************************************/

// Start of user code (user defined imports)

// End of user code

/**
 * Description of Cat.
 *
 * @author Utilisateur
 */
public class Cat {
	/**
	 * Description of the property articles.
	 */
	public HashSet<Article> articles = new HashSet<Article>();

	/**
	 * Description of the property lib.
	 */
	public Object lib = ;

	// Start of user code (user defined attributes for Cat)

	// End of user code

	/**
	 * The constructor.
	 */
	public Cat() {
		// Start of user code constructor for Cat)
		super();
		// End of user code
	}

	// Start of user code (user defined methods for Cat)

	// End of user code
	/**
	 * Returns articles.
	 * @return articles
	 */
	public HashSet<Article> getArticles() {
		return this.articles;
	}

	/**
	 * Returns lib.
	 * @return lib
	 */
	public Object getLib() {
		return this.lib;
	}

	/**
	 * Sets a value to attribute lib.
	 * @param newLib
	 */
	public void setLib(Object newLib) {
		this.lib = newLib;
	}

}


text:
package melware

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
    "time"

    "github.com/stretchr/testify/assert"
    "github.com/ridewindx/mel"
)

func newTestApp(cors *Cors) *mel.Mel {
    app := mel.New()
    app.Use(cors.Middleware())
    app.Get("/", func(c *mel.Context) {
        c.Text(200, "get")
    })
    app.Post("/", func(c *mel.Context) {
        c.Text(200, "post")
    })
    app.Patch("/", func(c *mel.Context) {
        c.Text(200, "patch")
    })
    return app
}

func performRequest(r http.Handler, method, origin string) *httptest.ResponseRecorder {
    req, _ := http.NewRequest(method, "/", nil)
    if len(origin) > 0 {
        req.Header.Set("Origin", origin)
    }
    w := httptest.NewRecorder()
    r.ServeHTTP(w, req)
    return w
}

func TestCorsDefaultConfig(t *testing.T) {
    cors := NewCors()
    cors.ExposeHeaders = []string{"exposed", "header", "hey"}

    assert.Equal(t, cors.AllowOrigins, []string{"*"})
    assert.Equal(t, cors.AllowMethods, []string{"GET", "POST", "HEAD"})
    assert.Equal(t, cors.AllowHeaders, []string{"Origin", "Accept", "Content-Type"})
    assert.Equal(t, cors.ExposeHeaders, []string{"exposed", "header", "hey"})
    assert.Equal(t, cors.AllowCredentials, false)
}

func TestCorsBadConfig(t *testing.T) {
    cors := NewCors()

    cors.AllowOrigins = []string{"*", "http://google.com"}
    assert.Panics(t, func() {
        cors.validateAllowOrigins()
    })

    cors.AllowOrigins = []string{"ftp://ftp.google.com"}
    assert.Panics(t, func() {
        cors.validateAllowOrigins()
    })

    cors.AllowOrigins = []string{"*"}
    cors.AllowOriginFunc = func(string) bool { return false }
    assert.Panics(t, func() {
        cors.validateAllowOrigins()
    })

    cors.AllowOrigins = nil
    cors.AllowOriginFunc = nil
    assert.Panics(t, func() {
        cors.validateAllowOrigins()
    })
}

func TestCorsNormalize(t *testing.T) {
    cors := NewCors()
    values := cors.normalizeStrs([]string{
        "http-Access ", "Post", "POST", " poSt  ",
        "HTTP-Access", "",
    })
    assert.Equal(t, values, []string{"http-access", "post", ""})

    values = cors.normalizeStrs(nil)
    assert.Nil(t, values)

    values = cors.normalizeStrs([]string{})
    assert.Nil(t, values)
}

func TestCorsConvert(t *testing.T) {
    cors := NewCors()
    methods := []string{"Get", "GET", "get"}
    headers := []string{"X-CSRF-TOKEN", "X-CSRF-Token", "x-csrf-token"}

    assert.Equal(t, []string{"GET", "GET", "GET"}, cors.convert(methods, strings.ToUpper))
    assert.Equal(t, []string{"X-Csrf-Token", "X-Csrf-Token", "X-Csrf-Token"}, cors.convert(headers, http.CanonicalHeaderKey))
}

func TestCorsGenerateNormalHeadersForAllowAllOrigins(t *testing.T) {
    cors := NewCors()
    cors.AllowOrigins = nil
    header := cors.generateNormalHeaders()
    assert.Equal(t, header.Get("Access-Control-Allow-Origin"), "")
    assert.Equal(t, header.Get("Vary"), "Origin")
    assert.Len(t, header, 1)

    cors.AllowOrigins = []string{"*"}
    cors.validateAllowOrigins()
    header = cors.generateNormalHeaders()
    assert.Equal(t, header.Get("Access-Control-Allow-Origin"), "*")
    assert.Equal(t, header.Get("Vary"), "")
    assert.Len(t, header, 1)
}

func TestCorsGenerateNormalHeadersForAllowCredentials(t *testing.T) {
    cors := NewCors()
    cors.AllowCredentials = true
    header := cors.generateNormalHeaders()
    assert.Equal(t, header.Get("Access-Control-Allow-Credentials"), "true")
    assert.Equal(t, header.Get("Vary"), "Origin")
    assert.Len(t, header, 2)
}

func TestCorsGenerateNormalHeadersForExposedHeaders(t *testing.T) {
    cors := NewCors()
    cors.ExposeHeaders = []string{"X-user", "xPassword"}
    header := cors.generateNormalHeaders()
    assert.Equal(t, header.Get("Access-Control-Expose-Headers"), "X-User,Xpassword")
    assert.Equal(t, header.Get("Vary"), "Origin")
    assert.Len(t, header, 2)
}

func TestCorsGeneratePreflightHeaders(t *testing.T) {
    cors := &Cors{}
    cors.AllowOrigins = nil
    header := cors.generatePreflightHeaders()
    assert.Equal(t, header.Get("Access-Control-Allow-Origin"), "")
    assert.Equal(t, header.Get("Vary"), "Origin")
    assert.Len(t, header, 1)

    cors.AllowOrigins = []string{"*"}
    cors.validateAllowOrigins()
    header = cors.generateNormalHeaders()
    assert.Equal(t, header.Get("Access-Control-Allow-Origin"), "*")
    assert.Equal(t, header.Get("Vary"), "")
    assert.Len(t, header, 1)
}

func TestCorsGeneratePreflightHeadersForAllowCredentials(t *testing.T) {
    cors := &Cors{}
    cors.AllowCredentials = true
    cors.AllowOrigins = nil
    header := cors.generatePreflightHeaders()
    assert.Equal(t, header.Get("Access-Control-Allow-Credentials"), "true")
    assert.Equal(t, header.Get("Vary"), "Origin")
    assert.Len(t, header, 2)
}

func TestCorsGeneratePreflightHeadersForAllowedMethods(t *testing.T) {
    cors := &Cors{}
    cors.AllowMethods = []string{"GET ", "post", "PUT", " put  "}
    header := cors.generatePreflightHeaders()
    assert.Equal(t, header.Get("Access-Control-Allow-Methods"), "GET,POST,PUT")
    assert.Equal(t, header.Get("Vary"), "Origin")
    assert.Len(t, header, 2)
}

func TestCorsGeneratePreflightHeadersForAllowedHeaders(t *testing.T) {
    cors := &Cors{}
    cors.AllowHeaders = []string{"X-user", "Content-Type"}
    header := cors.generatePreflightHeaders()
    assert.Equal(t, header.Get("Access-Control-Allow-Headers"), "X-User,Content-Type")
    assert.Equal(t, header.Get("Vary"), "Origin")
    assert.Len(t, header, 2)
}

func TestCorsGeneratePreflightHeadersForMaxAge(t *testing.T) {
    cors := &Cors{}
    cors.MaxAge = 12 * time.Hour
    header := cors.generatePreflightHeaders()
    assert.Equal(t, header.Get("Access-Control-Max-Age"), "43200") // 12*60*60
    assert.Equal(t, header.Get("Vary"), "Origin")
    assert.Len(t, header, 2)
}

func TestCorsValidateOrigin(t *testing.T) {
    cors := NewCors()
    cors.validateAllowOrigins()
    assert.True(t, cors.validateOrigin("http://google.com"))
    assert.True(t, cors.validateOrigin("https://google.com"))
    assert.True(t, cors.validateOrigin("example.com"))

    cors = NewCors()
    cors.AllowOrigins = []string{"https://google.com", "https://github.com"}
    cors.AllowOriginFunc = func(origin string) bool {
            return (origin == "http://news.ycombinator.com")
    }
    cors.validateAllowOrigins()

    assert.False(t, cors.validateOrigin("http://google.com"))
    assert.True(t, cors.validateOrigin("https://google.com"))
    assert.True(t, cors.validateOrigin("https://github.com"))
    assert.True(t, cors.validateOrigin("http://news.ycombinator.com"))
    assert.False(t, cors.validateOrigin("http://example.com"))
    assert.False(t, cors.validateOrigin("google.com"))
}

func TestCorsPassesAllowedOrigins(t *testing.T) {
    cors := NewCors()
    cors.AllowOrigins = []string{"http://google.com"}
    cors.AllowMethods =      []string{" GeT ", "get", "post", "PUT  ", "Head", "POST"}
    cors.AllowHeaders =     []string{"Content-type", "timeStamp "}
    cors.ExposeHeaders =   []string{"Data", "x-User"}
    cors.AllowCredentials = false
    cors.MaxAge =           12 * time.Hour
    cors.AllowOriginFunc = func(origin string) bool {
        return origin == "http://github.com"
    }

    router := newTestApp(cors)

    // no CORS request, origin == ""
    w := performRequest(router, "GET", "")
    assert.Equal(t, w.Body.String(), "get")
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"))
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))
    assert.Empty(t, w.Header().Get("Access-Control-Expose-Headers"))

    // allowed CORS request
    w = performRequest(router, "GET", "http://google.com")
    assert.Equal(t, w.Body.String(), "get")
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Origin"), "http://google.com")
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Credentials"), "")
    assert.Equal(t, w.Header().Get("Access-Control-Expose-Headers"), "Data,X-User")

    // deny CORS request
    w = performRequest(router, "GET", "https://google.com")
    assert.Equal(t, w.Code, 403)
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"))
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))
    assert.Empty(t, w.Header().Get("Access-Control-Expose-Headers"))

    // allowed CORS prefligh request
    w = performRequest(router, "OPTIONS", "http://github.com")
    assert.Equal(t, w.Code, 200)
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Origin"), "http://github.com")
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Credentials"), "")
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Methods"), "GET,POST,PUT,HEAD")
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Headers"), "Content-Type,Timestamp")
    assert.Equal(t, w.Header().Get("Access-Control-Max-Age"), "43200")

    // deny CORS prefligh request
    w = performRequest(router, "OPTIONS", "http://example.com")
    assert.Equal(t, w.Code, 403)
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"))
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Methods"))
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Headers"))
    assert.Empty(t, w.Header().Get("Access-Control-Max-Age"))
}

func TestCorsPassesAllowedAllOrigins(t *testing.T) {
    cors := NewCors()
    cors.AllowOrigins = []string{"*"}
    cors.AllowMethods =      []string{" Patch ", "get", "post", "POST"}
    cors.AllowHeaders =     []string{"Content-type", "  testheader "}
    cors.ExposeHeaders =   []string{"Data2", "x-User2"}
    cors.AllowCredentials = false
    cors.MaxAge =           10 * time.Hour
    router := newTestApp(cors)

    // no CORS request, origin == ""
    w := performRequest(router, "GET", "")
    assert.Equal(t, w.Body.String(), "get")
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"))
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))
    assert.Empty(t, w.Header().Get("Access-Control-Expose-Headers"))

    // allowed CORS request
    w = performRequest(router, "POST", "example.com")
    assert.Equal(t, w.Body.String(), "post")
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Origin"), "*")
    assert.Equal(t, w.Header().Get("Access-Control-Expose-Headers"), "Data2,X-User2")
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))

    // allowed CORS prefligh request
    w = performRequest(router, "OPTIONS", "https://facebook.com")
    assert.Equal(t, w.Code, 200)
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Origin"), "*")
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Methods"), "PATCH,GET,POST")
    assert.Equal(t, w.Header().Get("Access-Control-Allow-Headers"), "Content-Type,Testheader")
    assert.Equal(t, w.Header().Get("Access-Control-Max-Age"), "36000")
    assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))
}


text:
package uk.dangrew.nuts.graphics.selection.view;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyList;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.util.Arrays;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import uk.dangrew.nuts.food.FoodItem;
import uk.dangrew.nuts.food.FoodPortion;
import uk.dangrew.nuts.graphics.selection.model.FoodFilters;
import uk.dangrew.nuts.graphics.selection.model.FoodFilterModel;
import uk.dangrew.nuts.graphics.selection.model.FoodSelectionPaneManager;
import uk.dangrew.nuts.graphics.selection.model.FoodSelectionTypes;
import uk.dangrew.nuts.graphics.selection.view.UiFoodSelectionController;
import uk.dangrew.nuts.label.Label;
import uk.dangrew.nuts.nutrients.NutritionalUnit;
import uk.dangrew.nuts.stock.Stock;
import uk.dangrew.nuts.store.Database;
import uk.dangrew.nuts.template.Template;

public class UiFoodSelectionControllerTest {

   private Database database;
   private FoodItem chicken;
   private FoodItem beans;
   private FoodItem sausages;

   private Stock stock;
   private FoodFilterModel model;
   private Template liveSelection;
   @Mock private FoodSelectionPaneManager pane;

   private UiFoodSelectionController systemUnderTest;

   @Before public void initialiseSystemUnderTest() {
      MockitoAnnotations.initMocks( this );

      liveSelection = new Template( "Live Selection" );

      database = new Database();
      chicken = database.foodItems().createConcept( "Chicken" );
      chicken.foodAnalytics().of( NutritionalUnit.Protein ).set( 100.0 );
      beans = database.foodItems().createConcept( "Beans" );
      beans.foodAnalytics().of( NutritionalUnit.Protein ).set( 10.0 );
      sausages = database.foodItems().createConcept( "Sausages" );
      sausages.foodAnalytics().of( NutritionalUnit.Protein ).set( 20.0 );
      stock = database.stockLists().createConcept( "Stock" );
      stock.linkWithFoodItems( database.foodItems() );

      model = new FoodFilterModel( database );
      systemUnderTest = new UiFoodSelectionController( database, model, liveSelection );
      systemUnderTest.controlSelection( pane );
   }//End Method

   @Test public void shouldInvertSortingOnOptions(){
      verify( pane ).layoutTiles( Arrays.asList( beans, chicken, sausages ) );

      systemUnderTest.invertSort( true );
      verify( pane, times( 2 ) ).layoutTiles( Arrays.asList( sausages, chicken, beans ) );

      systemUnderTest.invertSort( false );
      verify( pane, times( 3 ) ).layoutTiles( Arrays.asList( beans, chicken, sausages ) );
   }//End Method

   @Test public void shouldFilterOptions(){
      verify( pane ).layoutTiles( Arrays.asList( beans, chicken, sausages ) );

      systemUnderTest.filterOptions( "chi" );
      verify( pane, times( 2 ) ).layoutTiles( Arrays.asList( chicken ) );

      systemUnderTest.filterOptions( "a" );
      verify( pane, times( 3 ) ).layoutTiles( Arrays.asList( beans, sausages ) );
   }//End Method

   @Test public void shouldChangeSelectionType(){
      verify( pane ).layoutTiles( Arrays.asList( beans, chicken, sausages ) );

      systemUnderTest.useSelectionType( FoodSelectionTypes.Protein );
      verify( pane, times( 2 ) ).layoutTiles( Arrays.asList( chicken, sausages, beans ) );

      systemUnderTest.useSelectionType( FoodSelectionTypes.All );
      verify( pane, times( 3 ) ).layoutTiles( Arrays.asList( beans, chicken, sausages ) );
   }//End Method

   @Test public void shouldDetectChangesInOptionsAndFeedThrough(){
      verify( pane ).layoutTiles( Arrays.asList( beans, chicken, sausages ) );

      FoodItem xyz = database.foodItems().createConcept( "xyz" );
      verify( pane, times( 2 ) ).layoutTiles( Arrays.asList( beans, chicken, sausages, xyz ) );

      database.foodItems().removeConcept( chicken );
      verify( pane, times( 3 ) ).layoutTiles( Arrays.asList( beans, sausages, xyz ) );
   }//End Method

   @Test public void shouldProvideSelection(){
      FoodPortion portion = new FoodPortion( chicken, 100 );
      assertThat( systemUnderTest.isSelected( portion ), is( false ) );
      assertThat( systemUnderTest.isSelected( chicken ), is( false ) );
      assertThat( liveSelection.portions().contains( portion ), is( false ) );

      systemUnderTest.select( portion );
      verify( pane ).setSelected( portion, true );
      assertThat( systemUnderTest.isSelected( portion ), is( true ) );
      assertThat( systemUnderTest.isSelected( chicken ), is( true ) );
      assertThat( liveSelection.portions().contains( portion ), is( true ) );

      systemUnderTest.deselect( portion );
      verify( pane ).setSelected( portion, false );
      assertThat( systemUnderTest.isSelected( portion ), is( false ) );
      assertThat( systemUnderTest.isSelected( chicken ), is( false ) );
      assertThat( liveSelection.portions().contains( portion ), is( false ) );
   }//End Method

   @Test public void shouldAvoidUnnecessaryPaneCalls(){
      FoodPortion portion = new FoodPortion();
      systemUnderTest.select( portion );
      systemUnderTest.select( portion );
      verify( pane, times( 1 ) ).setSelected( portion, true );

      systemUnderTest.deselect( portion );
      systemUnderTest.deselect( portion );
      verify( pane, times( 1 ) ).setSelected( portion, false );
   }//End Method

   @Test public void shouldGetAndClearSelection(){
      FoodPortion portion1 = new FoodPortion( chicken, 100 );
      FoodPortion portion2 = new FoodPortion( sausages, 125 );
      FoodPortion portion3 = new FoodPortion( beans, 75 );

      systemUnderTest.select( portion1 );
      systemUnderTest.select( portion2 );
      systemUnderTest.select( portion3 );

      Set< FoodPortion > selected = systemUnderTest.getAndClearSelection();
      assertThat( selected, contains( portion1, portion2, portion3 ) );
      assertThat( systemUnderTest.isSelected( portion1 ), is( false ) );
      assertThat( systemUnderTest.isSelected( portion2 ), is( false ) );
      assertThat( systemUnderTest.isSelected( portion3 ), is( false ) );
      assertThat( systemUnderTest.getAndClearSelection(), is( empty() ) );
   }//End Method

   @Test public void shouldApplyFilters(){
//      stock.portionFor( beans ).setPortion( 100 );
//      stock.portionFor( sausages ).setPortion( 200 );
//      systemUnderTest.select( new FoodPortion( chicken, 100 ) );
//      systemUnderTest.select( new FoodPortion( sausages, 100 ) );
//
//      systemUnderTest.applyFilters( Arrays.asList( FoodSelectionFilters.Selection, FoodSelectionFilters.Stock ) );
//      verify( pane, atLeastOnce() ).layoutTiles( Arrays.asList( sausages ) );

      FoodFilters filter1 = FoodFilters.Selection;
      FoodFilters filter2 = FoodFilters.Labels;
      systemUnderTest.applyFilters( Arrays.asList( filter1, filter2 ) );
      assertThat( model.filters(), contains( filter1, filter2 ) );

      FoodFilters filter3 = FoodFilters.Stock;
      systemUnderTest.applyFilters( Arrays.asList( filter3 ) );
      assertThat( model.filters(), contains( filter3 ) );

      verify( pane, times( 3 ) ).layoutTiles( anyList() );
   }//End Method

   @Test public void shouldApplyLabelsToModel(){
      Label label1 = database.labels().createConcept( "1" );
      Label label2 = database.labels().createConcept( "2" );
      systemUnderTest.applyLabels( Arrays.asList( label1, label2 ) );
      assertThat( model.labels(), contains( label1, label2 ) );

      Label label3 = database.labels().createConcept( "3" );
      systemUnderTest.applyLabels( Arrays.asList( label3 ) );
      assertThat( model.labels(), contains( label3 ) );

      verify( pane, times( 3 ) ).layoutTiles( anyList() );
   }//End Method

}//End Class