text:
package com.midi_automator.view.windows.PreferencesDialog;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.midi_automator.guiautomator.GUIAutomation;
import com.midi_automator.model.MidiAutomatorProperties;
import com.midi_automator.presenter.Presenter;
import com.midi_automator.presenter.services.GUIAutomationsService;
import com.midi_automator.presenter.services.MidiItemChangeNotificationService;
import com.midi_automator.presenter.services.MidiLearnService;
import com.midi_automator.presenter.services.MidiService;
import com.midi_automator.presenter.services.PresenterService;
import com.midi_automator.utils.GUIUtils;
import com.midi_automator.utils.MidiUtils;
import com.midi_automator.view.windows.AbstractBasicDialog;
import com.midi_automator.view.windows.MainFrame.HTMLLabel;
import com.midi_automator.view.windows.PreferencesDialog.GUIAutomationPanel.AutomationIndexDoesNotExistException;
import com.midi_automator.view.windows.PreferencesDialog.GUIAutomationPanel.GUIAutomationPanel;
import com.midi_automator.view.windows.PreferencesDialog.GUIAutomationPanel.GUIAutomationTable.GUIAutomationTable;
import com.midi_automator.view.windows.PreferencesDialog.actions.SendNotificationAction;
import com.midi_automator.view.windows.PreferencesDialog.listener.PreferencesDialogCloseListener;

@org.springframework.stereotype.Component
public class PreferencesDialog extends AbstractBasicDialog {

	private static final long serialVersionUID = 1L;

	static Logger log = Logger.getLogger(PreferencesDialog.class.getName());

	private final String TITLE = "Preferences";
	private final String TITLE_PROGRAM_SETTINGS = "Program Settings";
	private final String LABEL_MIDI_IN_REMOTE_DEVICES = "Midi Remote IN:";
	private final String LABEL_MIDI_OUT_REMOTE_DEVICES = "Midi Master OUT:";
	private final String LABEL_MIDI_OUT_REMOTE_INFO = "Master open: ch 1 CC 102 <list entry - 1>";
	private final String LABEL_MIDI_OUT_SWITCH_NOTIFIER_DEVICES = "Midi Switch Notifier OUT:";
	private final String LABEL_MIDI_OUT_SWITCH_NOTIFIER_INFO = "Notifier: ch 1 CC 103 value 127";
	private final String LABEL_MIDI_OUT_SWITCH_ITEM_DEVICES = "Midi Switch List Entry OUT:";
	private final String LABEL_MIDI_OUT_SWITCH_ITEM_INFO = "Switch item: ch 16 CC [1 - 127] value 127";
	private final String LABEL_MIDI_IN_METRONOM_DEVICES = "Midi Metronom IN:";
	private final String LABEL_MINIMIZE_ON_CLOSE = "Minimize program on close";
	private final String LABEL_MIDI_IN_METRONOM_INFO = "1st click: ch 16 NOTE ON A4
"
			+ "Other clicks: ch 16 NOTE ON E4";
	private final String LABEL_GUI_AUTOMATION = "Automations";
	private final String BUTTON_SEND_NOTIFIER = "Send...";

	public static final String NAME = "preferences dialog";
	public static final String NAME_MIDI_IN_REMOTE_DEVICE_COMBO_BOX = "midiINRemoteDeviceComboBox";
	public static final String NAME_MIDI_OUT_REMOTE_DEVICE_COMBO_BOX = "midiOUTRemoteDeviceComboBox";
	public static final String NAME_MIDI_OUT_SWITCH_NOTIFIER_DEVICE_COMBO_BOX = "midiOUTSwitchNotifierDeviceComboBox";
	public static final String NAME_MIDI_OUT_SWITCH_ITEM_DEVICE_COMBO_BOX = "midiOUTSwitchItemDeviceComboBox";
	public static final String NAME_MIDI_IN_METRONROM_DEVICE_COMBO_BOX = "midiINMetronomDeviceComboBox";
	public static final String NAME_BUTTON_SEND_NOTIFIER = "buttonSendNotifier";
	public static final String NAME_CHECKBOX_MINIMIZE_ON_CLOSE = "checkcoxMinimizeOnClose";

	private JPanel topPanel;
	private JPanel middlePanel;
	private JPanel footerPanel;
	private JLabel midiINRemoteDevicesLabel;
	private JLabel midiOUTRemoteDevicesLabel;
	private JLabel midiOUTSwitchNotifierDevicesLabel;
	private JLabel midiOUTSwitchItemDevicesLabel;
	private JLabel labelHeader;
	private HTMLLabel midiOUTSwitchNotifierInfoLabel;
	private HTMLLabel midiOUTSwitchItemInfoLabel;
	private HTMLLabel midiINMetronomInfoLabel;
	private JComboBox<String> midiINRemoteDeviceComboBox;
	private JComboBox<String> midiOUTRemoteDeviceComboBox;
	private JComboBox<String> midiOUTSwitchNotifierDeviceComboBox;
	private JComboBox<String> midiINMetronomDeviceComboBox;
	private JComboBox<String> midiOUTSwitchItemDeviceComboBox;
	private JCheckBox minimizeOnCloseCheckBox;

	@Autowired
	private GUIAutomationPanel guiAutomationConfigurationPanel;

	private JButton buttonSendNotify;

	private final Insets INSETS_LABEL_HEADER = new Insets(0, 5, 0, 10);
	private final Insets INSETS_COMBO_BOX = new Insets(0, 0, 0, 10);
	private final Insets INSETS_LABEL_INFO = new Insets(0, 5, 0, 10);

	private int currentMiddleGridY = 0;
	private int currentTopGridY = 0;

	@Autowired
	private Presenter presenter;

	@Autowired
	private PresenterService presenterService;
	@Autowired
	private MidiLearnService midiLearnService;
	@Autowired
	private GUIAutomationsService guiAutomationsService;
	@Autowired
	private MidiService midiService;
	@Autowired
	private MidiItemChangeNotificationService midiNotificationService;

	@Autowired
	private PreferencesDialogCloseListener windowCloseListener;

	@Autowired
	private SendNotificationAction sendNotificationAction;

	/**
	 * Initializes the frame
	 */
	public void init() {
		super.init();

		log.debug("Initializing Preferences Dialog...");

		log.debug("Set Title: " + TITLE);
		setTitle(TITLE);

		log.debug("Set Name: " + NAME);
		setName(NAME);

		// set layout
		topPanel = new JPanel(new GridBagLayout());
		middlePanel = new JPanel(new GridBagLayout());
		footerPanel = new JPanel(new FlowLayout());

		TitledBorder titleBorder = BorderFactory.createTitledBorder(
				BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
				TITLE_PROGRAM_SETTINGS);
		Border topPadding = BorderFactory.createEmptyBorder(5, 0, 10, 0);
		CompoundBorder topBorder = BorderFactory.createCompoundBorder(
				titleBorder, topPadding);
		topPanel.setBorder(topBorder);

		createMinimizeOnCloseCheckbox();

		createRemoteMidiInDevices();
		createRemoteMidiOutDevices();
		createSwitchNotifierMidiOutDevices();
		currentMiddleGridY += 3;

		createSwitchItemOutDevices();
		createMetronomMidiInDevices();
		currentMiddleGridY += 3;

		// GUI Automation
		createGUIAutomation();
		guiAutomationsService.setGUIAutomatorsToActive(false);

		// Save
		footerPanel.add(buttonSave);

		// Cancel
		footerPanel.add(buttonCancel);

		add(topPanel, BorderLayout.PAGE_START);
		add(middlePanel, BorderLayout.CENTER);
		add(footerPanel, BorderLayout.PAGE_END);

		// load data
		reload();

		// action on close
		addWindowListener(windowCloseListener);

		log.debug("Preferences Dialog initialized.");
	}

	/**
	 * Creates the minimize on close check box
	 */
	private void createMinimizeOnCloseCheckbox() {

		log.debug("Creating Minimze On Close checkbox");

		minimizeOnCloseCheckBox = new JCheckBox(LABEL_MINIMIZE_ON_CLOSE);
		minimizeOnCloseCheckBox.setName(NAME_CHECKBOX_MINIMIZE_ON_CLOSE);

		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = 1.0;
		c.anchor = GridBagConstraints.WEST;
		c.gridx = 0;
		c.gridy = currentTopGridY;
		topPanel.add(minimizeOnCloseCheckBox, c);
	}

	/**
	 * Creates the midi in devices combo box for the remote switch with a label
	 */
	private void createRemoteMidiInDevices() {

		log.debug("Creating Remote Midi In Device combo box");

		GridBagConstraints c = new GridBagConstraints();
		midiINRemoteDevicesLabel = new JLabel(LABEL_MIDI_IN_REMOTE_DEVICES);
		c.insets = INSETS_LABEL_HEADER;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.gridy = currentMiddleGridY;
		middlePanel.add(midiINRemoteDevicesLabel, c);

		List<String> midiINDevices = MidiUtils.getMidiDeviceSignatures("IN");
		midiINDevices.add(0, MidiAutomatorProperties.VALUE_NULL);
		midiINRemoteDeviceComboBox = new JComboBox<String>(
				(String[]) midiINDevices.toArray(new String[0]));
		midiINRemoteDeviceComboBox
				.setName(NAME_MIDI_IN_REMOTE_DEVICE_COMBO_BOX);

		c = new GridBagConstraints();
		c.insets = INSETS_COMBO_BOX;
		c.fill = GridBagConstraints.NONE;
		c.anchor = GridBagConstraints.WEST;
		c.gridx = 0;
		c.gridy = currentMiddleGridY + 1;
		middlePanel.add(midiINRemoteDeviceComboBox, c);

	}

	/**
	 * Creates the midi out devices combo box for the remote switch with a label
	 */
	private void createRemoteMidiOutDevices() {

		log.debug("Creating Remote Midi Out Device combo box");

		GridBagConstraints c = new GridBagConstraints();
		midiOUTRemoteDevicesLabel = new JLabel(LABEL_MIDI_OUT_REMOTE_DEVICES);
		c.insets = INSETS_LABEL_HEADER;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = currentMiddleGridY;
		middlePanel.add(midiOUTRemoteDevicesLabel, c);

		List<String> midiOutDevices = MidiUtils.getMidiDeviceSignatures("OUT");
		midiOutDevices.add(0, MidiAutomatorProperties.VALUE_NULL);
		midiOUTRemoteDeviceComboBox = new JComboBox<String>(
				(String[]) midiOutDevices.toArray(new String[0]));
		midiOUTRemoteDeviceComboBox
				.setName(NAME_MIDI_OUT_REMOTE_DEVICE_COMBO_BOX);

		c = new GridBagConstraints();
		c.insets = INSETS_COMBO_BOX;
		c.fill = GridBagConstraints.NONE;
		c.anchor = GridBagConstraints.WEST;
		c.gridx = 1;
		c.gridy = currentMiddleGridY + 1;
		middlePanel.add(midiOUTRemoteDeviceComboBox, c);

		// Info label
		c = new GridBagConstraints();
		c.insets = INSETS_LABEL_INFO;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = currentMiddleGridY + 2;
		midiOUTSwitchNotifierInfoLabel = new HTMLLabel(
				""
						+ LABEL_MIDI_OUT_REMOTE_INFO + "");
		middlePanel.add(midiOUTSwitchNotifierInfoLabel, c);
	}

	/**
	 * Creates the midi out devices combo box for the switch notifier with a
	 * label
	 */
	private void createSwitchNotifierMidiOutDevices() {

		log.debug("Creating Switch Notifier Midi Out combo box");

		GridBagConstraints c = new GridBagConstraints();
		midiOUTSwitchNotifierDevicesLabel = new JLabel(
				LABEL_MIDI_OUT_SWITCH_NOTIFIER_DEVICES);
		c.insets = INSETS_LABEL_HEADER;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 2;
		c.gridy = currentMiddleGridY;
		middlePanel.add(midiOUTSwitchNotifierDevicesLabel, c);

		List<String> midiOutDevices = MidiUtils.getMidiDeviceSignatures("OUT");
		midiOutDevices.add(0, MidiAutomatorProperties.VALUE_NULL);
		midiOUTSwitchNotifierDeviceComboBox = new JComboBox<String>(
				(String[]) midiOutDevices.toArray(new String[0]));
		midiOUTSwitchNotifierDeviceComboBox
				.setName(NAME_MIDI_OUT_SWITCH_NOTIFIER_DEVICE_COMBO_BOX);

		c = new GridBagConstraints();
		c.insets = new Insets(0, 0, 0, 0);
		c.fill = GridBagConstraints.NONE;
		c.anchor = GridBagConstraints.WEST;
		c.gridx = 2;
		c.gridy = currentMiddleGridY + 1;
		middlePanel.add(midiOUTSwitchNotifierDeviceComboBox, c);

		// Button test notification
		c = new GridBagConstraints();
		c.fill = GridBagConstraints.NONE;
		c.anchor = GridBagConstraints.WEST;
		c.gridx = 3;
		c.gridy = currentMiddleGridY + 1;
		buttonSendNotify = new JButton(BUTTON_SEND_NOTIFIER);
		buttonSendNotify.setName(NAME_BUTTON_SEND_NOTIFIER);
		buttonSendNotify.addActionListener(sendNotificationAction);
		buttonSendNotify.setMaximumSize(new Dimension(7, 10));
		middlePanel.add(buttonSendNotify, c);

		// Info label
		c = new GridBagConstraints();
		c.insets = INSETS_LABEL_INFO;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 2;
		c.gridy = currentMiddleGridY + 2;
		midiOUTSwitchNotifierInfoLabel = new HTMLLabel(
				""
						+ LABEL_MIDI_OUT_SWITCH_NOTIFIER_INFO + "");
		middlePanel.add(midiOUTSwitchNotifierInfoLabel, c);
	}

	/**
	 * Creates the midi out devices combo box for item switch with a label.
	 */
	private void createSwitchItemOutDevices() {

		log.debug("Creating Switch Item Out combo box");

		GridBagConstraints c = new GridBagConstraints();
		midiOUTSwitchItemDevicesLabel = new JLabel(
				LABEL_MIDI_OUT_SWITCH_ITEM_DEVICES);
		c.insets = INSETS_LABEL_HEADER;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.gridy = currentMiddleGridY;
		middlePanel.add(midiOUTSwitchItemDevicesLabel, c);

		List<String> devices = MidiUtils.getMidiDeviceSignatures("OUT");
		devices.add(0, MidiAutomatorProperties.VALUE_NULL);
		midiOUTSwitchItemDeviceComboBox = new JComboBox<String>(
				(String[]) devices.toArray(new String[0]));
		midiOUTSwitchItemDeviceComboBox
				.setName(NAME_MIDI_OUT_SWITCH_ITEM_DEVICE_COMBO_BOX);

		c = new GridBagConstraints();
		c.insets = INSETS_COMBO_BOX;
		c.fill = GridBagConstraints.NONE;
		c.anchor = GridBagConstraints.WEST;
		c.gridx = 0;
		c.gridy = currentMiddleGridY + 1;
		middlePanel.add(midiOUTSwitchItemDeviceComboBox, c);

		// Info label
		c = new GridBagConstraints();
		c.insets = INSETS_LABEL_INFO;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.gridy = currentMiddleGridY + 2;
		midiOUTSwitchItemInfoLabel = new HTMLLabel(
				""
						+ this.LABEL_MIDI_OUT_SWITCH_ITEM_INFO + "");
		middlePanel.add(midiOUTSwitchItemInfoLabel, c);
	}

	/**
	 * Creates the midi in devices combo box for metronom with a label.
	 */
	private void createMetronomMidiInDevices() {

		log.debug("Creating Midi In combo box");

		GridBagConstraints c = new GridBagConstraints();
		labelHeader = new JLabel(LABEL_MIDI_IN_METRONOM_DEVICES);
		c.insets = INSETS_LABEL_HEADER;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = currentMiddleGridY;
		middlePanel.add(labelHeader, c);

		List<String> midiInDevices = MidiUtils.getMidiDeviceSignatures("IN");
		midiInDevices.add(0, MidiAutomatorProperties.VALUE_NULL);
		midiINMetronomDeviceComboBox = new JComboBox<String>(
				(String[]) midiInDevices.toArray(new String[0]));
		midiINMetronomDeviceComboBox
				.setName(NAME_MIDI_IN_METRONROM_DEVICE_COMBO_BOX);

		c = new GridBagConstraints();
		c.insets = INSETS_COMBO_BOX;
		c.fill = GridBagConstraints.NONE;
		c.anchor = GridBagConstraints.WEST;
		c.gridx = 1;
		c.gridy = currentMiddleGridY + 1;
		middlePanel.add(midiINMetronomDeviceComboBox, c);

		// Info label
		c = new GridBagConstraints();
		c.insets = INSETS_LABEL_INFO;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = currentMiddleGridY + 2;
		midiINMetronomInfoLabel = new HTMLLabel(
				""
						+ LABEL_MIDI_IN_METRONOM_INFO + "");
		middlePanel.add(midiINMetronomInfoLabel, c);
	}

	/**
	 * Creates the GUI automation configuration panel
	 */
	private void createGUIAutomation() {

		log.debug("Creating Gui Automation panel");

		GridBagConstraints c = new GridBagConstraints();

		guiAutomationConfigurationPanel.init();
		guiAutomationConfigurationPanel.setOpaque(true);
		Border loweredetched = BorderFactory
				.createEtchedBorder(EtchedBorder.LOWERED);
		guiAutomationConfigurationPanel.setBorder(BorderFactory
				.createTitledBorder(loweredetched, LABEL_GUI_AUTOMATION));
		c.gridx = 0;
		c.gridy = currentMiddleGridY;
		c.gridwidth = 4;
		middlePanel.add(guiAutomationConfigurationPanel, c);

	}

	/**
	 * Sets the learned midi signature for the selected GUI automation
	 *
	 * @param signature
	 *            The signature
	 */
	public void setAutomationMidiSignature(String signature) {

		// learning for automation list
		GUIAutomationTable table = guiAutomationConfigurationPanel
				.getGUIAutomationsTable();
		try {
			table.setMidiSignature(signature, table.getSelectedRow());
		} catch (AutomationIndexDoesNotExistException e) {
			log.error("The automation for the MIDI signature does not exist", e);
		}
	}

	/**
	 * Adds a learned key code for the selected GUI automation
	 *
	 * @param keyCode
	 *            The key code
	 */
	public void addKeyCodeToSelectedAutomation(int keyCode) {

		GUIAutomationTable table = guiAutomationConfigurationPanel
				.getGUIAutomationsTable();
		try {
			table.addKeyCode(keyCode, table.getSelectedRow());
		} catch (AutomationIndexDoesNotExistException e) {
			log.error("The automation for the key does not exist", e);
		}
	}

	/**
	 * Deletes a learned key code for the selected GUI automation
	 *
	 * @param keyCode
	 *            The key code
	 */
	public void deleteKeyCodeFromSelectedAutomation() {

		GUIAutomationTable table = guiAutomationConfigurationPanel
				.getGUIAutomationsTable();
		try {
			table.deleteKeys(table.getSelectedRow());
		} catch (AutomationIndexDoesNotExistException e) {
			log.error("The automation of the key does not exist", e);
		}
	}

	/**
	 * Reloads the data of the frame
	 */
	public void reload() {

		log.debug("Reloading settings...");

		// midi in remote opener
		String midiInRemoteDeviceName = midiService
				.getMidiDeviceName(MidiAutomatorProperties.KEY_MIDI_IN_REMOTE_DEVICE);

		if (midiInRemoteDeviceName != null) {
			midiINRemoteDeviceComboBox.setSelectedItem(midiInRemoteDeviceName);
		}

		// midi out remote opener
		String midiOUTRemoteDevice = midiService
				.getMidiDeviceName(MidiAutomatorProperties.KEY_MIDI_OUT_REMOTE_DEVICE);

		if (midiOUTRemoteDevice != null) {
			midiOUTRemoteDeviceComboBox.setSelectedItem(midiOUTRemoteDevice);
		}

		// midi in metronom
		String midiINMetronomDevice = midiService
				.getMidiDeviceName(MidiAutomatorProperties.KEY_MIDI_IN_METRONOM_DEVICE);

		if (midiINMetronomDevice != null) {
			midiINMetronomDeviceComboBox.setSelectedItem(midiINMetronomDevice);
		}

		// midi out switch notifier
		String midiOUTSwitchNotifierDevice = midiService
				.getMidiDeviceName(MidiAutomatorProperties.KEY_MIDI_OUT_SWITCH_NOTIFIER_DEVICE);

		if (midiOUTSwitchNotifierDevice != null) {
			midiOUTSwitchNotifierDeviceComboBox
					.setSelectedItem(midiOUTSwitchNotifierDevice);
		}

		// midi out item switch
		String midiOUTSwitchItemDevice = midiService
				.getMidiDeviceName(MidiAutomatorProperties.KEY_MIDI_OUT_SWITCH_ITEM_DEVICE);

		if (midiOUTSwitchItemDevice != null) {
			midiOUTSwitchItemDeviceComboBox
					.setSelectedItem(midiOUTSwitchItemDevice);
		}

		// minimize on close
		boolean minimizeOnClose = presenterService.isMinimizeOnClose();
		minimizeOnCloseCheckBox.setSelected(minimizeOnClose);

		// gui automations
		GUIAutomation[] guiAutomations = guiAutomationsService
				.getGuiAutomations();
		GUIAutomationTable table = guiAutomationConfigurationPanel
				.getGUIAutomationsTable();

		guiAutomationConfigurationPanel.setMinSimilarity(guiAutomationsService
				.getMinSimilarity());

		if (guiAutomations != null) {
			for (int i = 0; i < guiAutomations.length; i++) {
				table.setAutomation(guiAutomations[i].getImagePath(),
						guiAutomations[i].getType(),
						guiAutomations[i].getKeyCodes(),
						guiAutomations[i].getTrigger(),
						guiAutomations[i].getFocusedProgram(),
						guiAutomations[i].getMinDelay(),
						guiAutomations[i].getTimeout(),
						guiAutomations[i].getMidiSignature(),
						guiAutomations[i].getScanRate(),
						guiAutomations[i].isMovable(), i);
			}
		}
		validate();
	}

	/**
	 * Puts the frame to learn mode
	 */
	private void learnOn() {
		// disable inputs, except GUIAutomation table, so that it can listen for
		// keys
		GUIUtils.disEnableAllInputs(this, false, GUIAutomationTable.NAME);
	}

	/**
	 * Puts the frame to learn mode for the component
	 *
	 * @param learningComponent
	 *            The component to learn for
	 */
	private void learnOn(Component learningComponent) {

		learnOn();

		GUIAutomationTable table = guiAutomationConfigurationPanel
				.getGUIAutomationsTable();

		if (learningComponent.getName() != null) {
			if (learningComponent.getName().equals(GUIAutomationTable.NAME)) {

				GUIUtils.deHighlightTableRow(table, true);

				log.info("Learning for automation index: "
						+ table.getSelectedRow());

			}
		}
	}

	/**
	 * Puts the frame to midi learn mode
	 */
	public void midiLearnOn() {

		learnOn();
		guiAutomationConfigurationPanel.getMidiLearnPopupMenu().midiLearnOn();

	}

	/**
	 * Puts the frame to midi learn mode for the given component key
	 *
	 * @param key
	 *            The key of the component to learn for
	 */
	public void midiLearnOn(String key) {

		learnOn(getLearningComponentFromKey(key));
		guiAutomationConfigurationPanel.getMidiLearnPopupMenu().midiLearnOn();

	}

	/**
	 * Gets the learning component for the key
	 *
	 * @param key
	 *            The learning component key
	 * @return The learning component
	 */
	private Component getLearningComponentFromKey(String key) {

		switch (midiLearnService.getKeyFromIndexedMidiLearnKey(key)) {
		case MidiLearnService.KEY_MIDI_LEARN_AUTOMATION_TRIGGER:
			return guiAutomationConfigurationPanel.getGUIAutomationsTable();
		}

		return null;
	}

	/**
	 * Puts the frame to key learn mode
	 *
	 * @param learningComponent
	 *            The component to learn for
	 */
	public void keyLearnOn(JComponent learningComponent) {

		learnOn(learningComponent);
		guiAutomationConfigurationPanel.getKeyLearnPopupMenu().keyLearnOn();

	}

	/**
	 * Puts the frame to normal mode.
	 */
	private void learnOff() {

		// enable inputs
		GUIUtils.disEnableAllInputs(this, true);

		GUIUtils.deHighlightTableRow(
				guiAutomationConfigurationPanel.getGUIAutomationsTable(), false);
	}

	/**
	 * Puts the frame to normal mode.
	 */
	public void midiLearnOff() {

		// change menu item
		guiAutomationConfigurationPanel.getMidiLearnPopupMenu().midiLearnOff();

		learnOff();
	}

	/**
	 * Puts the frame to normal mode.
	 */
	public void keyLearnOff() {

		// change menu item
		guiAutomationConfigurationPanel.getKeyLearnPopupMenu().keyLearnOff();

		learnOff();
	}

	public GUIAutomationPanel getGuiAutomationPanel() {
		return guiAutomationConfigurationPanel;
	}

	/**
	 * Gets the name of the switch notifier MIDI device.
	 *
	 * @return
	 */
	public String getSwitchNotifierMidiDeviceName() {
		return (String) midiOUTSwitchNotifierDeviceComboBox.getSelectedItem();
	}

	/**
	 * Closes the preferences window, saves and loads the configuration.
	 */
	protected void save() {

		String midiINRemoteDeviceName = (String) midiINRemoteDeviceComboBox
				.getSelectedItem();
		String midiOUTRemoteDeviceName = (String) midiOUTRemoteDeviceComboBox
				.getSelectedItem();
		String midiINMetronomDeviceName = (String) midiINMetronomDeviceComboBox
				.getSelectedItem();
		String midiOUTSwitchNotifierDeviceName = (String) midiOUTSwitchNotifierDeviceComboBox
				.getSelectedItem();
		String midiOUTSwitchItemDeviceName = (String) midiOUTSwitchItemDeviceComboBox
				.getSelectedItem();
		GUIAutomation[] guiAutomations = guiAutomationConfigurationPanel
				.getGUIAutomations();

		midiService.setMidiDeviceName(midiINRemoteDeviceName,
				MidiAutomatorProperties.KEY_MIDI_IN_REMOTE_DEVICE);
		midiService.setMidiDeviceName(midiINMetronomDeviceName,
				MidiAutomatorProperties.KEY_MIDI_IN_METRONOM_DEVICE);
		midiService.setMidiDeviceName(midiOUTRemoteDeviceName,
				MidiAutomatorProperties.KEY_MIDI_OUT_REMOTE_DEVICE);
		midiService.setMidiDeviceName(midiOUTSwitchNotifierDeviceName,
				MidiAutomatorProperties.KEY_MIDI_OUT_SWITCH_NOTIFIER_DEVICE);
		midiService.setMidiDeviceName(midiOUTSwitchItemDeviceName,
				MidiAutomatorProperties.KEY_MIDI_OUT_SWITCH_ITEM_DEVICE);
		guiAutomationsService.saveGUIAutomations(guiAutomations,
				guiAutomationConfigurationPanel.getMinSimilarity());
		presenterService.setMinimizeOnClose(minimizeOnCloseCheckBox
				.isSelected());

		close();
		presenter.loadProperties();
	}
}


text:
from lib2to3 import fixer_base, pytree, patcomp
from lib2to3.pgen2 import token
from lib2to3.fixer_util import Call, Name, Comma

"""
Fixes:
    b''.join(...)
into:
    b''.join(map(bytes, ...))
"""

class FixJoinbytes(fixer_base.BaseFix):
    PATTERN = """
        power< bytes=STRING trailer< '.' 'join' > trailer< '(' arg=any ')' > >
    """

    def transform(self, node, results):
        if results['bytes'].value.startswith('b'):
            results['arg'].replace(Call(Name('map'), [
                Name('bytes'),
                Comma(),
                results['arg'].clone(),
                ]))
        return node

redpajama_set_name: RedPajamaGithub


text:
namespace RiftDotNet
{
	/// <summary>
	/// MessageType identifies the structure of the Message class; based on the message,
	/// casting can be used to obtain the exact value.
	/// </summary>
	public enum MessageType
	{
		// Used for unassigned message types.
		None = 0,

		/// <summary>
		/// A new device is detected by manager.
		/// </summary>
		DeviceAdded,

		/// <summary>
		/// Existing device has been plugged/unplugged.
		/// </summary>
		DeviceRemoved,

		/// <summary>
		/// Emitted by sensor at regular intervals.
		/// </summary>
		BodyFrame,

		LatencyTestSamples,
		LatencyTestColorDetected,
		LatencyTestStarted,
		LatencyTestButton,
	};
}


text:
namespace drive {

TEST(ResourceEntryConversionTest, ConvertResourceEntryToDriveEntryProto_File) {
  scoped_ptr<base::Value> value =
      google_apis::test_util::LoadJSONFile("gdata/file_entry.json");
  ASSERT_TRUE(value.get());

  scoped_ptr<google_apis::ResourceEntry> resource_entry(
      google_apis::ResourceEntry::ExtractAndParse(*value));
  ASSERT_TRUE(resource_entry.get());

  DriveEntryProto entry_proto =
      ConvertResourceEntryToDriveEntryProto(*resource_entry);

  EXPECT_EQ("File 1.mp3",  entry_proto.title());
  EXPECT_EQ("File 1.mp3",  entry_proto.base_name());
  EXPECT_EQ("file:2_file_resource_id",  entry_proto.resource_id());
  EXPECT_EQ("https://file_content_url/",  entry_proto.content_url());
  EXPECT_EQ("https://file1_link_self/file:2_file_resource_id",
            entry_proto.edit_url());
  EXPECT_EQ("",  entry_proto.parent_resource_id());

  EXPECT_FALSE(entry_proto.deleted());
  EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entry_proto.kind());

  base::Time expected_creation_time;
  base::Time expected_modified_time;

  {
    // 2011-12-14T00:40:47.330Z
    base::Time::Exploded exploded;
    exploded.year = 2011;
    exploded.month = 12;
    exploded.day_of_month = 13;
    exploded.day_of_week = 2;  // Tuesday
    exploded.hour = 0;
    exploded.minute = 40;
    exploded.second = 47;
    exploded.millisecond = 330;
    expected_creation_time = base::Time::FromUTCExploded(exploded);
  }

  {
    // 2011-12-13T00:40:47.330Z
    base::Time::Exploded exploded;
    exploded.year = 2011;
    exploded.month = 12;
    exploded.day_of_month = 14;
    exploded.day_of_week = 3;  // Wednesday
    exploded.hour = 0;
    exploded.minute = 40;
    exploded.second = 47;
    exploded.millisecond = 330;
    expected_modified_time = base::Time::FromUTCExploded(exploded);
  }

  EXPECT_EQ(expected_modified_time.ToInternalValue(),
            entry_proto.file_info().last_modified());
  // Last accessed value equal to 0 means that the file has never been viewed.
  EXPECT_EQ(0, entry_proto.file_info().last_accessed());
  EXPECT_EQ(expected_creation_time.ToInternalValue(),
            entry_proto.file_info().creation_time());

  EXPECT_EQ("audio/mpeg",
            entry_proto.file_specific_info().content_mime_type());
  EXPECT_FALSE(entry_proto.file_specific_info().is_hosted_document());
  EXPECT_EQ("",
            entry_proto.file_specific_info().thumbnail_url());
  EXPECT_EQ("https://file_link_alternate/",
            entry_proto.file_specific_info().alternate_url());
  EXPECT_EQ("https://file_link_share/",
            entry_proto.file_specific_info().share_url());

  // Regular file specific fields.
  EXPECT_EQ(892721,  entry_proto.file_info().size());
  EXPECT_EQ("3b4382ebefec6e743578c76bbd0575ce",
            entry_proto.file_specific_info().file_md5());
  EXPECT_EQ("https://file_link_resumable_edit_media/",
            entry_proto.upload_url());
  EXPECT_FALSE(entry_proto.file_info().is_directory());
}

TEST(ResourceEntryConversionTest,
     ConvertResourceEntryToDriveEntryProto_HostedDocument) {
  scoped_ptr<base::Value> value =
      google_apis::test_util::LoadJSONFile("gdata/hosted_document_entry.json");
  ASSERT_TRUE(value.get());

  scoped_ptr<google_apis::ResourceEntry> resource_entry(
      google_apis::ResourceEntry::ExtractAndParse(*value));
  ASSERT_TRUE(resource_entry.get());

  DriveEntryProto entry_proto =
      ConvertResourceEntryToDriveEntryProto(*resource_entry);

  EXPECT_EQ("Document 1",  entry_proto.title());
  EXPECT_EQ("Document 1.gdoc",  entry_proto.base_name());  // The suffix added.
  EXPECT_EQ(".gdoc", entry_proto.file_specific_info().document_extension());
  EXPECT_EQ("document:5_document_resource_id",  entry_proto.resource_id());
  EXPECT_EQ("https://3_document_content/",  entry_proto.content_url());
  EXPECT_EQ("https://3_document_self_link/document:5_document_resource_id",
            entry_proto.edit_url());
  EXPECT_EQ("",  entry_proto.parent_resource_id());

  EXPECT_FALSE(entry_proto.deleted());
  EXPECT_EQ(google_apis::ENTRY_KIND_DOCUMENT, entry_proto.kind());

  // 2011-12-12T23:28:52.783Z
  base::Time::Exploded exploded;
  exploded.year = 2011;
  exploded.month = 12;
  exploded.day_of_month = 12;
  exploded.day_of_week = 1;  // Monday
  exploded.hour = 23;
  exploded.minute = 28;
  exploded.second = 52;
  exploded.millisecond = 783;
  const base::Time expected_last_modified_time =
      base::Time::FromUTCExploded(exploded);

  // 2011-12-12T23:28:46.686Z
  exploded.year = 2011;
  exploded.month = 12;
  exploded.day_of_month = 12;
  exploded.day_of_week = 1;  // Monday
  exploded.hour = 23;
  exploded.minute = 28;
  exploded.second = 46;
  exploded.millisecond = 686;
  const base::Time expected_creation_time =
      base::Time::FromUTCExploded(exploded);

  // 2011-12-13T02:12:18.527Z
  exploded.year = 2011;
  exploded.month = 12;
  exploded.day_of_month = 13;
  exploded.day_of_week = 2;  // Tuesday
  exploded.hour = 2;
  exploded.minute = 12;
  exploded.second = 18;
  exploded.millisecond = 527;
  const base::Time expected_last_accessed_time =
      base::Time::FromUTCExploded(exploded);

  EXPECT_EQ(expected_last_modified_time.ToInternalValue(),
            entry_proto.file_info().last_modified());
  EXPECT_EQ(expected_last_accessed_time.ToInternalValue(),
            entry_proto.file_info().last_accessed());
  EXPECT_EQ(expected_creation_time.ToInternalValue(),
            entry_proto.file_info().creation_time());

  EXPECT_EQ("text/html",
            entry_proto.file_specific_info().content_mime_type());
  EXPECT_TRUE(entry_proto.file_specific_info().is_hosted_document());
  EXPECT_EQ("https://3_document_thumbnail_link/",
            entry_proto.file_specific_info().thumbnail_url());
  EXPECT_EQ("https://3_document_alternate_link/",
            entry_proto.file_specific_info().alternate_url());
  EXPECT_EQ("https://3_document_share_link/",
            entry_proto.file_specific_info().share_url());

  // The size should be 0 for a hosted document.
  EXPECT_EQ(0,  entry_proto.file_info().size());
  EXPECT_FALSE(entry_proto.file_info().is_directory());
}

TEST(ResourceEntryConversionTest,
     ConvertResourceEntryToDriveEntryProto_Directory) {
  scoped_ptr<base::Value> value =
      google_apis::test_util::LoadJSONFile("gdata/directory_entry.json");
  ASSERT_TRUE(value.get());

  scoped_ptr<google_apis::ResourceEntry> resource_entry(
      google_apis::ResourceEntry::ExtractAndParse(*value));
  ASSERT_TRUE(resource_entry.get());

  DriveEntryProto entry_proto =
      ConvertResourceEntryToDriveEntryProto(*resource_entry);

  EXPECT_EQ("Sub Directory Folder",  entry_proto.title());
  EXPECT_EQ("Sub Directory Folder",  entry_proto.base_name());
  EXPECT_EQ("folder:sub_dir_folder_resource_id",  entry_proto.resource_id());
  EXPECT_EQ("https://1_folder_content_url/",  entry_proto.content_url());
  EXPECT_EQ("https://dir2_sub_self_link/folder:sub_dir_folder_resource_id",
            entry_proto.edit_url());
  // The parent resource ID should be obtained as this is a sub directory
  // under a non-root directory.
  EXPECT_EQ("folder:1_folder_resource_id",  entry_proto.parent_resource_id());

  EXPECT_FALSE(entry_proto.deleted());
  EXPECT_EQ(google_apis::ENTRY_KIND_FOLDER, entry_proto.kind());

  // 2011-04-01T18:34:08.234Z
  base::Time::Exploded exploded;
  exploded.year = 2011;
  exploded.month = 04;
  exploded.day_of_month = 01;
  exploded.day_of_week = 5;  // Friday
  exploded.hour = 18;
  exploded.minute = 34;
  exploded.second = 8;
  exploded.millisecond = 234;
  const base::Time expected_last_modified_time =
      base::Time::FromUTCExploded(exploded);

  // 2010-11-07T05:03:54.719Z
  exploded.year = 2010;
  exploded.month = 11;
  exploded.day_of_month = 7;
  exploded.day_of_week = 0;  // Sunday
  exploded.hour = 5;
  exploded.minute = 3;
  exploded.second = 54;
  exploded.millisecond = 719;
  const base::Time expected_creation_time =
      base::Time::FromUTCExploded(exploded);

  // 2011-11-02T04:37:38.469Z
  exploded.year = 2011;
  exploded.month = 11;
  exploded.day_of_month = 2;
  exploded.day_of_week = 2;  // Tuesday
  exploded.hour = 4;
  exploded.minute = 37;
  exploded.second = 38;
  exploded.millisecond = 469;
  const base::Time expected_last_accessed_time =
      base::Time::FromUTCExploded(exploded);

  EXPECT_EQ(expected_last_modified_time.ToInternalValue(),
            entry_proto.file_info().last_modified());
  EXPECT_EQ(expected_last_accessed_time.ToInternalValue(),
            entry_proto.file_info().last_accessed());
  EXPECT_EQ(expected_creation_time.ToInternalValue(),
            entry_proto.file_info().creation_time());

  // Directory should have this.
  EXPECT_EQ("https://2_folder_resumable_create_media_link/",
            entry_proto.upload_url());

  EXPECT_TRUE(entry_proto.file_info().is_directory());
}

TEST(ResourceEntryConversionTest,
     ConvertResourceEntryToDriveEntryProto_DeletedHostedDocument) {
  scoped_ptr<base::Value> value =
      google_apis::test_util::LoadJSONFile(
          "gdata/deleted_hosted_document_entry.json");
  ASSERT_TRUE(value.get());

  scoped_ptr<google_apis::ResourceEntry> resource_entry(
      google_apis::ResourceEntry::ExtractAndParse(*value));
  ASSERT_TRUE(resource_entry.get());

  DriveEntryProto entry_proto =
      ConvertResourceEntryToDriveEntryProto(*resource_entry);

  EXPECT_EQ("Deleted document",  entry_proto.title());
  EXPECT_EQ("Deleted document.gdoc",  entry_proto.base_name());
  EXPECT_EQ("document:deleted_in_root_id",  entry_proto.resource_id());
  EXPECT_EQ("https://content_url/",  entry_proto.content_url());
  EXPECT_EQ("https://edit_url/document%3Adeleted_in_root_id",
            entry_proto.edit_url());
  EXPECT_EQ("",  entry_proto.parent_resource_id());

  EXPECT_TRUE(entry_proto.deleted());  // The document was deleted.
  EXPECT_EQ(google_apis::ENTRY_KIND_DOCUMENT, entry_proto.kind());

  // 2012-04-10T22:50:55.797Z
  base::Time::Exploded exploded;
  exploded.year = 2012;
  exploded.month = 04;
  exploded.day_of_month = 10;
  exploded.day_of_week = 2;  // Tuesday
  exploded.hour = 22;
  exploded.minute = 50;
  exploded.second = 55;
  exploded.millisecond = 797;
  const base::Time expected_last_modified_time =
      base::Time::FromUTCExploded(exploded);

  // 2012-04-10T22:50:53.237Z
  exploded.year = 2012;
  exploded.month = 04;
  exploded.day_of_month = 10;
  exploded.day_of_week = 2;  // Tuesday
  exploded.hour = 22;
  exploded.minute = 50;
  exploded.second = 53;
  exploded.millisecond = 237;
  const base::Time expected_creation_time =
      base::Time::FromUTCExploded(exploded);

  // 2012-04-10T22:50:55.797Z
  exploded.year = 2012;
  exploded.month = 04;
  exploded.day_of_month = 10;
  exploded.day_of_week = 2;  // Tuesday
  exploded.hour = 22;
  exploded.minute = 50;
  exploded.second = 55;
  exploded.millisecond = 797;
  const base::Time expected_last_accessed_time =
      base::Time::FromUTCExploded(exploded);

  EXPECT_EQ(expected_last_modified_time.ToInternalValue(),
            entry_proto.file_info().last_modified());
  EXPECT_EQ(expected_last_accessed_time.ToInternalValue(),
            entry_proto.file_info().last_accessed());
  EXPECT_EQ(expected_creation_time.ToInternalValue(),
            entry_proto.file_info().creation_time());

  EXPECT_EQ("text/html",
            entry_proto.file_specific_info().content_mime_type());
  EXPECT_TRUE(entry_proto.file_specific_info().is_hosted_document());
  EXPECT_EQ("",
            entry_proto.file_specific_info().thumbnail_url());
  EXPECT_EQ("https://alternate/document%3Adeleted_in_root_id/edit",
            entry_proto.file_specific_info().alternate_url());
  EXPECT_EQ("",
            entry_proto.file_specific_info().share_url());

  // The size should be 0 for a hosted document.
  EXPECT_EQ(0,  entry_proto.file_info().size());
}

}  // namespace drive


text:
from .__about__ import __version__
from .check import RethinkDBCheck

__all__ = ['__version__', 'RethinkDBCheck']


text:
module Mongoid #:nodoc:
  module Observable #:nodoc:
    extend ActiveSupport::Concern
    included do
      attr_reader :observers
    end

    # Add an observer to this object. This mimics the standard Ruby observable
    # library.
    #
    # Example:
    #
    # <tt>address.add_observer(person)</tt>
    def add_observer(object)
      @observers ||= []
      @observers.push(object)
    end

    # Notify all the objects observing this object of an update. All observers
    # need to respond to the update method in order to handle this.
    #
    # Example:
    #
    # <tt>document.notify_observers(self)</tt>
    def notify_observers(*args)
      @observers.dup.each { |observer| observer.observe(*args) } if @observers
    end
  end
end


text:
package ai.nitro.bot4j.middle.domain.receive.payload;

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

import ai.nitro.bot4j.middle.domain.receive.form.FormParam;

public class FormReceivePayload extends AbstractReceivePayload {

	protected List<FormParam> form = new ArrayList<FormParam>();

	protected String name;

	public FormReceivePayload() {
		super(Type.FORM);
	}

	public List<FormParam> getForm() {
		return form;
	}

	public String getFormParam(final String key) {
		String result = null;

		for (final FormParam formParam : form) {
			if (key.equals(formParam.getKey())) {
				result = formParam.getValue();
				break;
			}
		}

		return result;
	}

	public String getName() {
		return name;
	}

	public void setForm(final List<FormParam> form) {
		this.form = form;
	}

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

	@Override
	public String toString() {
		return "type=[" + type + "], name=[" + name + "], form=[" + form + "]";
	}
}


text:
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

# Dump of table groups
# ------------------------------------------------------------

DROP TABLE IF EXISTS `groups`;

CREATE TABLE `groups` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `description` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES `groups` WRITE;
/*!40000 ALTER TABLE `groups` DISABLE KEYS */;

INSERT INTO `groups` (`id`, `name`, `description`)
VALUES
	(1,'admin','Administrator'),
	(2,'members','General User');

/*!40000 ALTER TABLE `groups` ENABLE KEYS */;
UNLOCK TABLES;

# Dump of table login_attempts
# ------------------------------------------------------------

DROP TABLE IF EXISTS `login_attempts`;

CREATE TABLE `login_attempts` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `ip_address` varchar(15) NOT NULL,
  `login` varchar(100) NOT NULL,
  `time` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

# Dump of table sessions
# ------------------------------------------------------------

DROP TABLE IF EXISTS `sessions`;

CREATE TABLE `sessions` (
  `session_id` varchar(40) NOT NULL DEFAULT '0',
  `ip_address` varchar(45) NOT NULL DEFAULT '0',
  `user_agent` varchar(120) NOT NULL,
  `last_activity` int(10) unsigned NOT NULL DEFAULT '0',
  `user_data` text NOT NULL,
  PRIMARY KEY (`session_id`,`ip_address`,`user_agent`),
  KEY `last_activity_idx` (`last_activity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

# Dump of table users
# ------------------------------------------------------------

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `ip_address` varchar(15) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  `salt` varchar(255) DEFAULT NULL,
  `email` varchar(100) NOT NULL,
  `activation_code` varchar(40) DEFAULT NULL,
  `forgotten_password_code` varchar(40) DEFAULT NULL,
  `forgotten_password_time` int(11) unsigned DEFAULT NULL,
  `remember_code` varchar(40) DEFAULT NULL,
  `created_on` int(11) unsigned NOT NULL,
  `last_login` int(11) unsigned DEFAULT NULL,
  `active` tinyint(1) unsigned DEFAULT NULL,
  `first_name` varchar(50) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `company` varchar(100) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;

INSERT INTO `users` (`id`, `ip_address`, `username`, `password`, `salt`, `email`, `activation_code`, `forgotten_password_code`, `forgotten_password_time`, `remember_code`, `created_on`, `last_login`, `active`, `first_name`, `last_name`, `company`, `phone`)
VALUES
	(1,'127.0.0.1','administrator','$2y$08$dxM6uLEKd5yIyBWVKNvOMOZmTqJt.yxQCmhHMfoA56zeXO41prBKK','','test@menteer.ca','',NULL,NULL,NULL,1268889823,1417970057,1,'Admin','istrator','ADMIN','0');

/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;

# Dump of table users_groups
# ------------------------------------------------------------

DROP TABLE IF EXISTS `users_groups`;

CREATE TABLE `users_groups` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `group_id` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uc_users_groups` (`user_id`,`group_id`),
  KEY `fk_users_groups_users1_idx` (`user_id`),
  KEY `fk_users_groups_groups1_idx` (`group_id`),
  CONSTRAINT `fk_users_groups_groups1` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `fk_users_groups_users1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES `users_groups` WRITE;
/*!40000 ALTER TABLE `users_groups` DISABLE KEYS */;

INSERT INTO `users_groups` (`id`, `user_id`, `group_id`)
VALUES
	(1,1,1),
	(2,1,2);

/*!40000 ALTER TABLE `users_groups` ENABLE KEYS */;
UNLOCK TABLES;

/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
require 'rails_helper'

RSpec.describe "prescriptions/index", type: :view do
  before(:each) do
    @patient = assign(:patient, Patient.create!(
      first_name: 'Mark',
      last_name: 'Harris',
      date_of_birth: '10/11/1971',
      state: 'OH'
    ))
    @pharmacy = assign(:pharmacy, Pharmacy.create!(
      name: 'cvs',
      street: '123 Easy St.'
    ))
    assign(:prescriptions, [
      Prescription.create!(
        drug_number: "12345",
        drug_name: 'Drug Name',
        quantity: 1,
        frequency: "qD",
        refills: 2,
        dispense_as_written: false,
        patient: @patient,
        pharmacy: @pharmacy
      ),
      Prescription.create!(
        drug_number: "12345",
        drug_name: 'Drug Name',
        quantity: 1,
        frequency: "qD",
        refills: 2,
        dispense_as_written: false,
        patient: @patient,
        pharmacy: @pharmacy
      )
    ])
  end

  it "renders a list of prescriptions" do
    render
    assert_select "tr>td", text: "Drug Name", count: 2
    assert_select "tr>td", text: 1.to_s, count: 2
    assert_select "tr>td", text: "qD", count: 2
    assert_select "tr>td", text: 2.to_s, count: 2
    assert_select "tr>td", text: false.to_s, count: 2
  end

  it "renders the patient's name" do
    render
    assert_select "h1", text: "Prescriptions for Mark Harris (10/11/1971)", count: 1
  end

end


text:
#ifndef __BK_LOGGER_H__
#define __BK_LOGGER_H__

// blackhart headers.
#include "foundation\BkExport.h"

// ~~~~~ Dcl(PUBLIC) ~~~~~

/*! \brief Logs a message to the log file.
 *
 * \param str The message to log.
 */
extern BK_API void	BkLog(char const* str);

// ~~~~~ Dcl(INTERNAL) ~~~~~

/*! \brief Initializes the logger.
*/
extern void	_BkLogger_Initialize(void);

/*! \brief Uninitializes the logger.
*/
extern void	_BkLogger_Uninitialize(void);

#endif


text:
/*************************************************************************/
/*  core_string_names.cpp                                                */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "core_string_names.h"

CoreStringNames *CoreStringNames::singleton = NULL;

CoreStringNames::CoreStringNames() {

	_free = StaticCString::create("free");
	changed = StaticCString::create("changed");
	_meta = StaticCString::create("__meta__");
	_script = StaticCString::create("script");
	script_changed = StaticCString::create("script_changed");
	___pdcdata = StaticCString::create("___pdcdata");
	__getvar = StaticCString::create("__getvar");
	_iter_init = StaticCString::create("_iter_init");
	_iter_next = StaticCString::create("_iter_next");
	_iter_get = StaticCString::create("_iter_get");
	get_rid = StaticCString::create("get_rid");
}


text:
package app

import "github.com/jaegertracing/jaeger/model"

// ProcessSpan processes a Domain Model Span
type ProcessSpan func(span *model.Span)

// ProcessSpans processes a batch of Domain Model Spans
type ProcessSpans func(spans []*model.Span)

// FilterSpan decides whether to allow or disallow a span
type FilterSpan func(span *model.Span) bool

// ChainedProcessSpan chains spanProcessors as a single ProcessSpan call
func ChainedProcessSpan(spanProcessors ...ProcessSpan) ProcessSpan {
	return func(span *model.Span) {
		for _, processor := range spanProcessors {
			processor(span)
		}
	}
}


text:
long smg$end_pasteboard_update(
	smg_pasteboard_id &pasteboard)		//! Display to update
{
	update_panels();
	doupdate();
	return 1;
}


text:
package com.appleframework.qos.server.statistics.service;

import com.appleframework.exception.ServiceException;
import com.appleframework.model.page.Pagination;
import com.appleframework.qos.server.core.entity.AppInfo;

public interface AppInfoService {

	public AppInfo get(Long id);

	public void update(AppInfo appInfo) throws ServiceException;

	public boolean isUniqueByCode(String oldCode, String newCode);

	public boolean isExistByCode(String code);

	public Pagination findPage(Pagination page, String keyword);
}


text:
var expect = require('chai').expect;
var adhere = require('../../lib/adhere');

describe('additionalItems', function () {

  it('by default, should validate arrays that have as many or more elements than items schemas', function () {
    var schema = {
      type: 'array',
      items: [{type: 'number'}, {type: 'string'}, {type: 'null'}],
    };

    var values = [[1, 'a', null], [1, 'a', null, 'test']];
    values.forEach(function (val) {
      var result = adhere.validate(val, schema);
      expect(result.valid).to.eql(true);
    });
  });

  describe('if enabled', function () {
    it('should validate arrays that have as many or more elements than items schemas', function () {
      var schema = {
        type: 'array',
        items: [{type: 'number'}, {type: 'string'}, {type: 'null'}],
        additionalItems: true
      };

      var values = [[1, 'a', null], [1, 'a', null, 'test']];
      values.forEach(function (val) {
        var result = adhere.validate(val, schema);
        expect(result.valid).to.eql(true);
      });
    });

    it('should invalidate arrays that have less elements than items schemas', function () {
      var schema = {
        type: 'array',
        items: [{type: 'number'}, {type: 'string'}, {type: 'null'}],
        additionalItems: true
      };

      var val = [1, 'a'];
      var result = adhere.validate(val, schema);
      expect(result.valid).to.eql(false);
    });
  });

  describe('if disabled', function () {
    it('should invalidate arrays that have more elements than items schemas', function () {
      var schema = {
        type: 'array',
        items: [{type: 'number'}, {type: 'string'}, {type: 'null'}],
        additionalItems: false
      };

      var val = [1, 'a', null, 'test'];
      var result = adhere.validate(val, schema);
      expect(result.valid).to.eql(false);
    });

    it('should validate arrays that have as many elements as items schemas', function () {
      var schema = {
        type: 'array',
        items: [{type: 'number'}, {type: 'string'}, {type: 'null'}],
        additionalItems: false
      };

      var val = [1, 'a', null];
      var result = adhere.validate(val, schema);
      expect(result.valid).to.eql(true);
    });
  });

});


text:
@(email:String)
<!DOCTYPE HTML>

    <link href="/public/style/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
        <link href="/public/style/demos.css" rel="stylesheet"/>
        <link href="/public/style/userDemoIndex.css" rel="stylesheet"/>


text:
package com.example.android.notepad;

import com.example.android.notepad.NotePad;

import android.app.ListActivity;
import android.content.ClipboardManager;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

/**
 * Displays a list of notes. Will display notes from the {@link Uri}
 * provided in the incoming Intent if there is one, otherwise it defaults to displaying the
 * contents of the {@link NotePadProvider}.
 *
 * NOTE: Notice that the provider operations in this Activity are taking place on the UI thread.
 * This is not a good practice. It is only done here to make the code more readable. A real
 * application should use the {@link android.content.AsyncQueryHandler} or
 * {@link android.os.AsyncTask} object to perform operations asynchronously on a separate thread.
 */
public class NotesList extends ListActivity {

    // For logging and debugging
    private static final String TAG = "NotesList";

    /**
     * The columns needed by the cursor adapter
     */
    private static final String[] PROJECTION = new String[] {
            NotePad.Notes._ID, // 0
            NotePad.Notes.COLUMN_NAME_TITLE, // 1
    };

    /** The index of the title column */
    private static final int COLUMN_INDEX_TITLE = 1;

    /**
     * onCreate is called when Android starts this Activity from scratch.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // The user does not need to hold down the key to use menu shortcuts.
        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

        /* If no data is given in the Intent that started this Activity, then this Activity
         * was started when the intent filter matched a MAIN action. We should use the default
         * provider URI.
         */
        // Gets the intent that started this Activity.
        Intent intent = getIntent();

        // If there is no data associated with the Intent, sets the data to the default URI, which
        // accesses a list of notes.
        if (intent.getData() == null) {
            intent.setData(NotePad.Notes.CONTENT_URI);
        }

        /*
         * Sets the callback for context menu activation for the ListView. The listener is set
         * to be this Activity. The effect is that context menus are enabled for items in the
         * ListView, and the context menu is handled by a method in NotesList.
         */
        getListView().setOnCreateContextMenuListener(this);

        /* Performs a managed query. The Activity handles closing and requerying the cursor
         * when needed.
         *
         * Please see the introductory note about performing provider operations on the UI thread.
         */
        Cursor cursor = managedQuery(
            getIntent().getData(),            // Use the default content URI for the provider.
            PROJECTION,                       // Return the note ID and title for each note.
            null,                             // No where clause, return all records.
            null,                             // No where clause, therefore no where column values.
            NotePad.Notes.DEFAULT_SORT_ORDER  // Use the default sort order.
        );

        /*
         * The following two arrays create a "map" between columns in the cursor and view IDs
         * for items in the ListView. Each element in the dataColumns array represents
         * a column name; each element in the viewID array represents the ID of a View.
         * The SimpleCursorAdapter maps them in ascending order to determine where each column
         * value will appear in the ListView.
         */

        // The names of the cursor columns to display in the view, initialized to the title column
        String[] dataColumns = { NotePad.Notes.COLUMN_NAME_TITLE } ;

        // The view IDs that will display the cursor columns, initialized to the TextView in
        // noteslist_item.xml
        int[] viewIDs = { android.R.id.text1 };

        // Creates the backing adapter for the ListView.
        SimpleCursorAdapter adapter
            = new SimpleCursorAdapter(
                      this,                             // The Context for the ListView
                      R.layout.noteslist_item,          // Points to the XML for a list item
                      cursor,                           // The cursor to get items from
                      dataColumns,
                      viewIDs
              );

        // Sets the ListView's adapter to be the cursor adapter that was just created.
        setListAdapter(adapter);
    }

    /**
     * Called when the user clicks the device's Menu button the first time for
     * this Activity. Android passes in a Menu object that is populated with items.
     *
     * Sets up a menu that provides the Insert option plus a list of alternative actions for
     * this Activity. Other applications that want to handle notes can "register" themselves in
     * Android by providing an intent filter that includes the category ALTERNATIVE and the
     * mimeTYpe NotePad.Notes.CONTENT_TYPE. If they do this, the code in onCreateOptionsMenu()
     * will add the Activity that contains the intent filter to its list of options. In effect,
     * the menu will offer the user other applications that can handle notes.
     * @param menu A Menu object, to which menu items should be added.
     * @return True, always. The menu should be displayed.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate menu from XML resource
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_options_menu, menu);

        // Generate any additional actions that can be performed on the
        // overall list.  In a normal install, there are no additional
        // actions found here, but this allows other applications to extend
        // our menu with their own actions.
        Intent intent = new Intent(null, getIntent().getData());
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
                new ComponentName(this, NotesList.class), null, intent, 0, null);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        // The paste menu item is enabled if there is data on the clipboard.
        ClipboardManager clipboard = (ClipboardManager)
                getSystemService(Context.CLIPBOARD_SERVICE);

        MenuItem mPasteItem = menu.findItem(R.id.menu_paste);

        // If the clipboard contains an item, enables the Paste option on the menu.
        if (clipboard.hasPrimaryClip()) {
            mPasteItem.setEnabled(true);
        } else {
            // If the clipboard is empty, disables the menu's Paste option.
            mPasteItem.setEnabled(false);
        }

        // Gets the number of notes currently being displayed.
        final boolean haveItems = getListAdapter().getCount() > 0;

        // If there are any notes in the list (which implies that one of
        // them is selected), then we need to generate the actions that
        // can be performed on the current selection.  This will be a combination
        // of our own specific actions along with any extensions that can be
        // found.
        if (haveItems) {

            // This is the selected item.
            Uri uri = ContentUris.withAppendedId(getIntent().getData(), getSelectedItemId());

            // Creates an array of Intents with one element. This will be used to send an Intent
            // based on the selected menu item.
            Intent[] specifics = new Intent[1];

            // Sets the Intent in the array to be an EDIT action on the URI of the selected note.
            specifics[0] = new Intent(Intent.ACTION_EDIT, uri);

            // Creates an array of menu items with one element. This will contain the EDIT option.
            MenuItem[] items = new MenuItem[1];

            // Creates an Intent with no specific action, using the URI of the selected note.
            Intent intent = new Intent(null, uri);

            /* Adds the category ALTERNATIVE to the Intent, with the note ID URI as its
             * data. This prepares the Intent as a place to group alternative options in the
             * menu.
             */
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);

            /*
             * Add alternatives to the menu
             */
            menu.addIntentOptions(
                Menu.CATEGORY_ALTERNATIVE,  // Add the Intents as options in the alternatives group.
                Menu.NONE,                  // A unique item ID is not required.
                Menu.NONE,                  // The alternatives don't need to be in order.
                null,                       // The caller's name is not excluded from the group.
                specifics,                  // These specific options must appear first.
                intent,                     // These Intent objects map to the options in specifics.
                Menu.NONE,                  // No flags are required.
                items                       // The menu items generated from the specifics-to-
                                            // Intents mapping
            );
                // If the Edit menu item exists, adds shortcuts for it.
                if (items[0] != null) {

                    // Sets the Edit menu item shortcut to numeric "1", letter "e"
                    items[0].setShortcut('1', 'e');
                }
            } else {
                // If the list is empty, removes any existing alternative actions from the menu
                menu.removeGroup(Menu.CATEGORY_ALTERNATIVE);
            }

        // Displays the menu
        return true;
    }

    /**
     * This method is called when the user selects an option from the menu, but no item
     * in the list is selected. If the option was INSERT, then a new Intent is sent out with action
     * ACTION_INSERT. The data from the incoming Intent is put into the new Intent. In effect,
     * this triggers the NoteEditor activity in the NotePad application.
     *
     * If the item was not INSERT, then most likely it was an alternative option from another
     * application. The parent method is called to process the item.
     * @param item The menu item that was selected by the user
     * @return True, if the INSERT menu item was selected; otherwise, the result of calling
     * the parent method.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_add:
          /*
           * Launches a new Activity using an Intent. The intent filter for the Activity
           * has to have action ACTION_INSERT. No category is set, so DEFAULT is assumed.
           * In effect, this starts the NoteEditor Activity in NotePad.
           */
           startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
           return true;
        case R.id.menu_paste:
          /*
           * Launches a new Activity using an Intent. The intent filter for the Activity
           * has to have action ACTION_PASTE. No category is set, so DEFAULT is assumed.
           * In effect, this starts the NoteEditor Activity in NotePad.
           */
          startActivity(new Intent(Intent.ACTION_PASTE, getIntent().getData()));
          return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * This method is called when the user context-clicks a note in the list. NotesList registers
     * itself as the handler for context menus in its ListView (this is done in onCreate()).
     *
     * The only available options are COPY and DELETE.
     *
     * Context-click is equivalent to long-press.
     *
     * @param menu A ContexMenu object to which items should be added.
     * @param view The View for which the context menu is being constructed.
     * @param menuInfo Data associated with view.
     * @throws ClassCastException
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {

        // The data from the menu item.
        AdapterView.AdapterContextMenuInfo info;

        // Tries to get the position of the item in the ListView that was long-pressed.
        try {
            // Casts the incoming data object into the type for AdapterView objects.
            info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            // If the menu object can't be cast, logs an error.
            Log.e(TAG, "bad menuInfo", e);
            return;
        }

        /*
         * Gets the data associated with the item at the selected position. getItem() returns
         * whatever the backing adapter of the ListView has associated with the item. In NotesList,
         * the adapter associated all of the data for a note with its list item. As a result,
         * getItem() returns that data as a Cursor.
         */
        Cursor cursor = (Cursor) getListAdapter().getItem(info.position);

        // If the cursor is empty, then for some reason the adapter can't get the data from the
        // provider, so returns null to the caller.
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }

        // Inflate menu from XML resource
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_context_menu, menu);

        // Sets the menu header to be the title of the selected note.
        menu.setHeaderTitle(cursor.getString(COLUMN_INDEX_TITLE));

        // Append to the
        // menu items for any other activities that can do stuff with it
        // as well.  This does a query on the system for any activities that
        // implement the ALTERNATIVE_ACTION for our data, adding a menu item
        // for each one that is found.
        Intent intent = new Intent(null, Uri.withAppendedPath(getIntent().getData(),
                                        Integer.toString((int) info.id) ));
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
                new ComponentName(this, NotesList.class), null, intent, 0, null);
    }

    /**
     * This method is called when the user selects an item from the context menu
     * (see onCreateContextMenu()). The only menu items that are actually handled are DELETE and
     * COPY. Anything else is an alternative option, for which default handling should be done.
     *
     * @param item The selected menu item
     * @return True if the menu item was DELETE, and no default processing is need, otherwise false,
     * which triggers the default handling of the item.
     * @throws ClassCastException
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // The data from the menu item.
        AdapterView.AdapterContextMenuInfo info;

        /*
         * Gets the extra info from the menu item. When an note in the Notes list is long-pressed, a
         * context menu appears. The menu items for the menu automatically get the data
         * associated with the note that was long-pressed. The data comes from the provider that
         * backs the list.
         *
         * The note's data is passed to the context menu creation routine in a ContextMenuInfo
         * object.
         *
         * When one of the context menu items is clicked, the same data is passed, along with the
         * note ID, to onContextItemSelected() via the item parameter.
         */
        try {
            // Casts the data object in the item into the type for AdapterView objects.
            info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {

            // If the object can't be cast, logs an error
            Log.e(TAG, "bad menuInfo", e);

            // Triggers default processing of the menu item.
            return false;
        }
        // Appends the selected note's ID to the URI sent with the incoming Intent.
        Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), info.id);

        /*
         * Gets the menu item's ID and compares it to known actions.
         */
        switch (item.getItemId()) {
        case R.id.context_open:
            // Launch activity to view/edit the currently selected item
            startActivity(new Intent(Intent.ACTION_EDIT, noteUri));
            return true;
//BEGIN_INCLUDE(copy)
        case R.id.context_copy:
            // Gets a handle to the clipboard service.
            ClipboardManager clipboard = (ClipboardManager)
                    getSystemService(Context.CLIPBOARD_SERVICE);

            // Copies the notes URI to the clipboard. In effect, this copies the note itself
            clipboard.setPrimaryClip(ClipData.newUri(   // new clipboard item holding a URI
                    getContentResolver(),               // resolver to retrieve URI info
                    "Note",                             // label for the clip
                    noteUri)                            // the URI
            );

            // Returns to the caller and skips further processing.
            return true;
//END_INCLUDE(copy)
        case R.id.context_delete:

            // Deletes the note from the provider by passing in a URI in note ID format.
            // Please see the introductory note about performing provider operations on the
            // UI thread.
            getContentResolver().delete(
                noteUri,  // The URI of the provider
                null,     // No where clause is needed, since only a single note ID is being
                          // passed in.
                null      // No where clause is used, so no where arguments are needed.
            );

            // Returns to the caller and skips further processing.
            return true;
        default:
            return super.onContextItemSelected(item);
        }
    }

    /**
     * This method is called when the user clicks a note in the displayed list.
     *
     * This method handles incoming actions of either PICK (get data from the provider) or
     * GET_CONTENT (get or create data). If the incoming action is EDIT, this method sends a
     * new Intent to start NoteEditor.
     * @param l The ListView that contains the clicked item
     * @param v The View of the individual item
     * @param position The position of v in the displayed list
     * @param id The row ID of the clicked item
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        // Constructs a new URI from the incoming URI and the row ID
        Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);

        // Gets the action from the incoming Intent
        String action = getIntent().getAction();

        // Handles requests for note data
        if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {

            // Sets the result to return to the component that called this Activity. The
            // result contains the new URI
            setResult(RESULT_OK, new Intent().setData(uri));
        } else {

            // Sends out an Intent to start an Activity that can handle ACTION_EDIT. The
            // Intent's data is the note ID URI. The effect is to call NoteEdit.
            startActivity(new Intent(Intent.ACTION_EDIT, uri));
        }
    }
}


text:
#import "RCTJSStackFrame.h"
#import "RCTLog.h"
#import "RCTUtils.h"

static NSRegularExpression *RCTJSStackFrameRegex()
{
  static dispatch_once_t onceToken;
  static NSRegularExpression *_regex;
  dispatch_once(&onceToken, ^{
    NSError *regexError;
    _regex = [NSRegularExpression regularExpressionWithPattern:@"^([^@]+)@(.*):(\\d+):(\\d+)$" options:0 error:&regexError];
    if (regexError) {
      RCTLogError(@"Failed to build regex: %@", [regexError localizedDescription]);
    }
  });
  return _regex;
}

@implementation RCTJSStackFrame

- (instancetype)initWithMethodName:(NSString *)methodName file:(NSString *)file lineNumber:(NSInteger)lineNumber column:(NSInteger)column
{
  if (self = [super init]) {
    _methodName = methodName;
    _file = file;
    _lineNumber = lineNumber;
    _column = column;
  }
  return self;
}

- (NSDictionary *)toDictionary
{
  return @{
     @"methodName": RCTNullIfNil(self.methodName),
     @"file": RCTNullIfNil(self.file),
     @"lineNumber": @(self.lineNumber),
     @"column": @(self.column)
  };
}

+ (instancetype)stackFrameWithLine:(NSString *)line
{
  NSTextCheckingResult *match = [RCTJSStackFrameRegex() firstMatchInString:line options:0 range:NSMakeRange(0, line.length)];
  if (!match) {
    return nil;
  }

  NSString *methodName = [line substringWithRange:[match rangeAtIndex:1]];
  NSString *file = [line substringWithRange:[match rangeAtIndex:2]];
  NSString *lineNumber = [line substringWithRange:[match rangeAtIndex:3]];
  NSString *column = [line substringWithRange:[match rangeAtIndex:4]];

  return [[self alloc] initWithMethodName:methodName
                                     file:file
                               lineNumber:[lineNumber integerValue]
                                   column:[column integerValue]];
}

+ (instancetype)stackFrameWithDictionary:(NSDictionary *)dict
{
  return [[self alloc] initWithMethodName:dict[@"methodName"]
                                     file:dict[@"file"]
                               lineNumber:[RCTNilIfNull(dict[@"lineNumber"]) integerValue]
                                   column:[RCTNilIfNull(dict[@"column"]) integerValue]];
}

+ (NSArray<RCTJSStackFrame *> *)stackFramesWithLines:(NSString *)lines
{
  NSMutableArray *stack = [NSMutableArray new];
  for (NSString *line in [lines componentsSeparatedByString:@"\n"]) {
    RCTJSStackFrame *frame = [self stackFrameWithLine:line];
    if (frame) {
      [stack addObject:frame];
    }
  }
  return stack;
}

+ (NSArray<RCTJSStackFrame *> *)stackFramesWithDictionaries:(NSArray<NSDictionary *> *)dicts
{
  NSMutableArray *stack = [NSMutableArray new];
  for (NSDictionary *dict in dicts) {
    RCTJSStackFrame *frame = [self stackFrameWithDictionary:dict];
    if (frame) {
      [stack addObject:frame];
    }
  }
  return stack;
}

@end


text:
static CGFloat const kTriangleHeight = 10.f;
static CGFloat const kMargin = 10.f;

@interface HRPopupMenuView () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, weak) id <HRPopupMenuViewDelegate> delegate;
@property (nonatomic, assign) CGPoint startPoint;
@end

@implementation HRPopupMenuView

- (instancetype)initWithResponseView:(UIView *)view delegate:(id<HRPopupMenuViewDelegate>)delegate {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        self.delegate = delegate;
        CGFloat menuWidth = 130;
        if (self.delegate && [self.delegate respondsToSelector:@selector(hr_widthOfPopupMenuView:)]) {
            menuWidth = [self.delegate hr_widthOfPopupMenuView:self];
        }
        NSInteger itemCount = 1;
        if (self.delegate && [self.delegate respondsToSelector:@selector(hr_itemCountInPopupMenuView:)]) {
            itemCount =  [self.delegate hr_itemCountInPopupMenuView:self];
        }
        CGFloat itemHeight = 50;
        if (self.delegate && [self.delegate respondsToSelector:@selector(hr_itemHeightInPopupMenuView:)]) {
            itemHeight = [self.delegate hr_itemHeightInPopupMenuView:self];
        }

        CGPoint centerPoint = CGPointMake(view.screenXValue+view.widthValue/2.f, view.screenYValue+view.heightValue/2.f);
        CGFloat tableViewY = view.screenYValue + view.heightValue + kTriangleHeight;
        CGFloat tableViewX = centerPoint.x - menuWidth * 0.5;
        if (tableViewX + menuWidth + kMargin > kScreenWidth) {
            tableViewX = kScreenWidth - kMargin - menuWidth;
        } else if (tableViewX < kMargin) {
            tableViewX = kMargin;
        }
        _startPoint = CGPointMake(centerPoint.x, view.screenYValue + view.heightValue + 3);

        self.tableView.frame = CGRectMake(tableViewX, tableViewY, menuWidth, itemHeight*itemCount);
        self.tableView.transform = CGAffineTransformMakeScale(0.001, 0.001);
        [self addSubview:self.tableView];

        [self drawTriangleLayer];
    }
    return self;
}

- (void)drawTriangleLayer {
    CGFloat triangleLength = kTriangleHeight * 2.0 / 1.732;
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:_startPoint];
    [path addLineToPoint:CGPointMake(_startPoint.x - triangleLength * 0.5, _startPoint.y + kTriangleHeight)];
    [path addLineToPoint:CGPointMake(_startPoint.x + triangleLength * 0.5, _startPoint.y + kTriangleHeight)];
    CAShapeLayer *triangleLayer = [CAShapeLayer layer];
    triangleLayer.path = path.CGPath;
    triangleLayer.fillColor = self.tableView.backgroundColor.CGColor;
    triangleLayer.strokeColor = self.tableView.backgroundColor.CGColor;
    self.triangleLayer = triangleLayer;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.layer addSublayer:triangleLayer];

    });
}

#pragma mark - response action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [HRPopupMenuManager dismiss];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.delegate && [self.delegate respondsToSelector:@selector(hr_itemCountInPopupMenuView:)]) {
        return [self.delegate hr_itemCountInPopupMenuView:self];
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.delegate && [self.delegate respondsToSelector:@selector(hr_itemHeightInPopupMenuView:)]) {
        return [self.delegate hr_itemHeightInPopupMenuView:self];
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HRPopupMenuCell *cell = [HRPopupMenuCell createCellWithTableView:tableView];
    if (self.delegate && [self.delegate respondsToSelector:@selector(hr_datasourceInPopupMenuView:at:)]) {
        HRPopupMenuModel *model = [self.delegate hr_datasourceInPopupMenuView:self at:indexPath.row];
        [cell configCellWithTitle:model.title image:model.imageName];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.delegate && [self.delegate respondsToSelector:@selector(hr_selectItemInPopupMenuView:at:)]) {
        [self.delegate hr_selectItemInPopupMenuView:self at:indexPath.row];
        [HRPopupMenuManager dismiss];
    }
}

#pragma mark - getter
- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.layer.masksToBounds = YES;
        _tableView.layer.cornerRadius = 2;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.bounces = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

@end


text:
package com.headstartech.citrine.core;

import com.headstartech.citrine.*;
import com.headstartech.citrine.jobstore.JobStore;
import com.headstartech.citrine.jobstore.TriggeredJob;
import com.headstartech.citrine.jobstore.TriggeredJobCompleteAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by per on 3/7/15.
 */
public class JobRunShell implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(JobRunShell.class);

    private final JobStore jobStore;
    private final JobExecutionContext jobExecutionContext;
    private final TriggeredJob triggeredJob;
    private final Job job;
    private final Scheduler scheduler;

    JobRunShell(TriggeredJob triggeredJob, JobStore jobStore, Scheduler scheduler) throws SchedulerException {
        this.jobStore = jobStore;
        this.triggeredJob = triggeredJob;
        this.job = createJobInstance(triggeredJob.getJobDetail());
        this.scheduler = scheduler;
        jobExecutionContext = new JobExecutionContextImpl(triggeredJob, scheduler);
    }

    @Override
    public void run() {
        JobDetail jobDetail = jobExecutionContext.getTriggeredJob().getJobDetail();
        JobKey jobKey = jobDetail.getJobKey();

        notifyJobListeners();
        try {
            logger.debug("Calling execute on job: jobKey={} ", jobKey);
            job.execute(jobExecutionContext);
        } catch(Throwable t) {
            logger.error(String.format("Job threw unhandled exception: jobKey=%s", jobKey), t);
        }

        jobStore.triggeredJobComplete(triggeredJob, TriggeredJobCompleteAction.DELETE_OR_RESCHEDULE_JOB);
    }

    private void notifyJobListeners() {
        List<JobListener> jobListeners = scheduler.getListenerRegistry().getJobListeners();
        for(JobListener jl: jobListeners) {
            try {
                jl.jobToBeExecuted(jobExecutionContext);
            } catch (Exception e) {
                logger.warn(String.format("JobListener threw exception: jobListener=%s", jl), e);
            }
        }
    }

    private Job createJobInstance(JobDetail jobDetail) throws SchedulerException {
        Class<? extends Job> jobClass = jobDetail.getJobClass();
        try {
            logger.debug("Creating instance of Job: jobKey={}, class={}", jobDetail.getJobKey().getKey(), jobClass.getName());
            return jobClass.newInstance();
        } catch (Exception e) {
            SchedulerException se = new SchedulerException("Failed to instantiate class '" + jobClass.getName() + "'", e);
            throw se;
        }
    }
}


text:
package com.twitter.intellij.pants.quickfix;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileNameMatcher;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.util.IncorrectOperationException;
import com.twitter.intellij.pants.PantsBundle;
import org.jetbrains.annotations.NotNull;

public class TypeAssociationFix extends PantsQuickFix {
  @NotNull
  @Override
  public String getName() {
    return PantsBundle.message("quick.fix.add.build.file.treatment");
  }

  @Override
  public boolean startInWriteAction() {
    return true;
  }

  @NotNull
  @Override
  public String getText() {
    return PantsBundle.message("quick.fix.add.build.file.treatment");
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    return true;
  }

  @Override
  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    invoke(project, null, descriptor.getPsiElement().getContainingFile());
  }

  @Override
  public void invoke(@NotNull final Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException {
    FileTypeManager manager = FileTypeManager.getInstance();
    FileType type = manager.getFileTypeByFileName(psiFile.getName());
    // Remove the BUILD file matcher from the wrong type then add it to PythonFileType
    for (FileNameMatcher matcher : manager.getAssociations(type)) {
      if (matcher.acceptsCharSequence(psiFile.getName())) {
        manager.removeAssociation(type, matcher);
      }
    }
  }
}


text:
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\BaseController;
use Auth;
use Illuminate\Http\Request;

/**
 * This controller is responsible for handling password creation,
 * modification and deletion requests for authenticated users.
 */
class ChangePasswordController extends BaseController
{
    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/mship/manage/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        $this->middleware('auth_full_group');
    }

    protected function validateOld(Request $request)
    {
        $this->validate($request, [
            'old_password' => 'required|string|password',
        ]);
    }

    protected function validateNew(Request $request)
    {
        $this->validate($request, [
            'new_password' => 'required|string|confirmed|min:8|upperchars:1|lowerchars:1|numbers:1',
        ]);
    }

    protected function validateBoth(Request $request)
    {
        $this->validateOld($request);
        $this->validateNew($request);

        $this->validate($request, [
            'new_password' => 'different:old_password',
        ]);
    }

    public function showCreateForm()
    {
        $this->authorize('create', 'password');

        return $this->viewMake('auth.passwords.create');
    }

    public function create(Request $request)
    {
        $this->authorize('create', 'password');
        $this->validateNew($request);

        Auth::user()->setPassword($request->input('new_password'));

        return redirect($this->redirectPath())->withSuccess('Password set successfully.');
    }

    public function showChangeForm()
    {
        $this->authorize('change', 'password');

        return $this->viewMake('auth.passwords.change');
    }

    public function change(Request $request)
    {
        $this->authorize('change', 'password');
        $this->validateBoth($request);

        Auth::user()->setPassword($request->input('new_password'));

        return redirect($this->redirectPath())->withSuccess('Password reset successfully.');
    }

    public function showDeleteForm()
    {
        $this->authorize('delete', 'password');

        return $this->viewMake('auth.passwords.delete');
    }

    public function delete(Request $request)
    {
        $this->authorize('delete', 'password');
        $this->validateOld($request);

        $this->account->removePassword();

        return redirect($this->redirectPath())->withSuccess('Password deleted successfully.');
    }
}


text:
All of the files in this folder are auto-generated. The only exception is
JavaScriptBaseLexer.py which was translated from Java and is needed to run one
of the auto generated files (JavaScriptLexer). As a result, the code is not
up to linting standards, but cannot be changed. Do not place any hand written
code in this dir, it will not be linted.


text:
module Logical::Validators
  class UrlFormat
    def self.valid?(url)
      uri = URI(url)
      uri.scheme.present? && uri.host.present?
    end
  end
end


text:
/*! \addtogroup PTHREAD
 * @{
 *
 * \details This is the interface for POSIX threads.  Here is an example of creating a new thread:
 *
 * \code
 * #include <pthread.h>
 *
 * void * thread_function(void * args);
 *
 * pthread_t t;
 * pthread_attr_t attr;
 *
 * if ( pthread_attr_init(&attr) < 0 ){
 * 	perror("failed to initialize attr");
 * 	return -1;
 * }
 *
 * if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) < 0 ){
 * 	perror("failed to set detach state");
 * 	return -1;
 * }
 *
 * if ( pthread_attr_setstacksize(&attr, 4096) < 0 ){
 * 	perror("failed to set stack size");
 * 	return -1;
 * }
 *
 * if ( pthread_create(&t, &attr, thread_function, NULL) ){
 * 	perror("failed to create thread");
 * 	return -1;
 * }
 *
 * \endcode
 *
 */

/*! \file */

#include "config.h"

#include <pthread.h>
#include <errno.h>

#include "../sched/sched_flags.h"

static void priv_join_thread(void * args);

/*! \details This function creates a new thread.
 * \return Zero on success or -1 with \a errno (see \ref ERRNO) set to:
 * - ENOMEM: error allocating memory for the thread
 * - EAGAIN: insufficient system resources to create a new thread
 *
 *
 */
int pthread_create(pthread_t * thread /*! If not null, the thread id is written here */,
		const pthread_attr_t * attr /*! Sets the thread attributes (defaults are used if this is NULL) */,
		void *(*start_routine)(void *) /*! A pointer to the start routine */,
		void *arg /*! A pointer to the start routine's single argument */){

	int id;
	pthread_attr_t attrs;

	if ( attr == NULL ){

		if ( pthread_attr_init(&attrs) < 0 ){
			//Errno is set by pthread_attr_init()
			return -1;
		}
	} else {
		memcpy(&attrs, attr, sizeof(pthread_attr_t));
	}

	id = sched_new_thread(start_routine,
			arg,
			attrs.stackaddr,
			attrs.stacksize,
			&attrs);

	if ( id ){
		if ( thread ){
			*thread = id;
		}
		return 0;
	} else {
		if ( attr == NULL ){
			pthread_attr_destroy(&attrs);
		}
		errno = EAGAIN;
		return -1;
	}
}

/*! \details This function blocks the calling thread until \a thread terminates.
 * \return Zero on success or -1 with \a errno (see \ref ERRNO) set to:
 * - ESRCH: \a thread does not exist
 * - EDEADLK: a deadlock has been detected or \a thread refers to the calling thread
 * - EINVAL: \a thread does not refer to a joinable thread.
 */
int pthread_join(pthread_t thread, void ** value_ptr){

	if( (thread < task_get_total()) && (thread >= 0) ){
		if ( task_enabled(thread) ){
			//now see if the thread is joinable
			if ( PTHREAD_ATTR_GET_DETACH_STATE( (&(sched_table[thread].attr))) != PTHREAD_CREATE_JOINABLE ){
				errno = EINVAL;
				return -1;
			}

			//See if the thread is joined to this thread
			if ( (sched_table[thread].block_object == (void*)&sched_table[task_get_current()]) ||
					(thread == task_get_current()) ){
				errno = EDEADLK;
				return -1;
			}

			do {
				hwpl_core_privcall(priv_join_thread, &thread);
				if ( thread < 0 ){
					errno = ESRCH;
					return -1;
				}
			} while( sched_get_unblock_type(task_get_current()) != SCHED_UNBLOCK_PTHREAD_JOINED_THREAD_COMPLETE);

			if ( value_ptr != NULL ){
				//When the thread terminates, it puts the exit value in this threads scheduler table entry
				*value_ptr = (void*)(sched_table[ task_get_current() ].exit_status);
			}

			return 0;
		}
	}
	errno = ESRCH;
	return -1;
}

void priv_join_thread(void * args){
	int * p = (int*)args;
	int id = *p;

	if ( task_enabled(id) ){
		sched_table[task_get_current()].block_object = (void*)&sched_table[id]; //block on the thread to be joined
		//If the thread is waiting to be joined, it needs to be activated
		if ( sched_table[id].block_object == (void*)&sched_table[id].block_object ){
			sched_priv_assert_active(id, SCHED_UNBLOCK_PTHREAD_JOINED);
		}
		sched_priv_update_on_sleep();
	} else {
		*p = -1;
	}
}

/*! @} */


text:
<?php
/**
 * @author  MyBB Group
 * @version 2.0.0
 * @package mybb/core
 * @license http://www.mybb.com/licenses/bsd3 BSD-3
 */

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;

class CreateProfileFieldsTable extends Migration
{

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		if (Schema::hasTable('profile_fields')) {
			return;
		}

		Schema::create('profile_fields', function (Blueprint $table) {
			$table->increments('id')->unsigned();
			$table->integer('profile_field_group_id')->unsigned()->nullable()->index();
			$table->string('type');
			$table->string('name');
			$table->string('description');
			$table->string('validation_rules')->nullable();
			$table->integer('display_order')->unsigned();
			$table->nullableTimestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		if (Schema::hasTable('profile_field_options')) {
			Schema::table('profile_field_options', function (Blueprint $table) {
				$table->dropForeign('profile_field_id_foreign');
			});
		}

		if (Schema::hasTable('user_profile_fields')) {
			Schema::table('user_profile_fields', function (Blueprint $table) {
				$table->dropForeign('profile_field_id_foreign');
			});
		}

		Schema::drop('profile_fields');
	}
}


text:
import * as numbers from './schema-number';
import { SchemaText } from './schema-text';
import { SchemaBool } from './schema-bool';
import { SchemaDate } from './schema-date';
import { SchemaTextArray } from './schema-text-array';
import { SchemaJSON } from './schema-json';
import { SchemaIdArray } from './schema-id-array';
import { SchemaNumArray } from './schema-num-array';
import { SchemaId } from './schema-id';
import { SchemaHtml } from './schema-html';
import { SchemaForeignKey } from './schema-foreign-key';

export const NumberType = numbers.NumberType;
export const num = numbers.SchemaNumber;
export const text = SchemaText;
export const textArray = SchemaTextArray;
export const json = SchemaJSON;
export const idArray = SchemaIdArray;
export const numArray = SchemaNumArray;
export const date = SchemaDate;
export const bool = SchemaBool;
export const id = SchemaId;
export const html = SchemaHtml;
export const foreignKey = SchemaForeignKey;


text:
package org.basex.gui.layout;

import static org.basex.util.Token.*;

import java.util.*;

import javax.swing.tree.*;

import org.basex.core.*;
import org.basex.data.*;
import org.basex.util.*;
import org.basex.util.hash.*;
import org.basex.util.list.*;

/**
 * JTree node which represents a folder.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Lukas Kircher
 */
public class TreeFolder extends TreeNode {
  /** Children of node have been loaded. */
  private boolean loaded;
  /** Maximum number of displayed/processed children for a node. */
  public static final int MAXC = 10000;

  /**
   * Constructor.
   * @param nm displayed node name
   * @param pth folder path
   * @param t tree reference
   * @param d data reference
   */
  public TreeFolder(final byte[] nm, final byte[] pth, final BaseXTree t, final Data d) {
    super(nm, pth, t, d);
  }

  @Override
  void load() {
    if(loaded || updating) return;

    updating = true;
    int cmax = MAXC;
    // add folders
    final byte[] sub = subfolder();
    final TokenSet set = data.resources.children(subfolder(), true);
    for(final byte[] f : new TokenList(set).sort(Prop.CASE)) {
      add(new TreeFolder(f, sub, tree, data));
      if(--cmax == 0) break;
    }
    // add leaves
    cmax = addLeaves(EMPTY, cmax, this);
    // add dummy node if not all nodes are displayed
    if(cmax <= 0)
      add(new TreeLeaf(token(Text.DOTS), sub, false, true, tree, data));

    loaded = true;
    ((DefaultTreeModel) tree.getModel()).nodeStructureChanged(this);
    updating = false;
  }

  /**
   * Filters child nodes by the given filter expression and adds the remaining children
   * to the given node.
   * @param filter filter expression
   * @param cmax counter for the maximum number of children to add
   * @param target node to append filtered nodes
   * @return number of remaining nodes that can be added
   */
  public int addLeaves(final byte[] filter, final int cmax, final TreeFolder target) {
    final TokenBoolMap tbm = data.resources.children(subfolder(), false);
    final List<byte[]> keys = new ArrayList<>(tbm.size());

    // get desired leaves, depending on the given filter
    for(final byte[] b : tbm) {
      if(filter.length == 0 || eq(b, filter)) keys.add(b);
    }
    Collections.sort(keys, new Comparator<byte[]>() {
      @Override
      public int compare(final byte[] o1, final byte[] o2) {
        return Prop.CASE ? diff(o1, o2) : diff(lc(o1), lc(o2));
      }
    });

    // finally add the necessary leaves
    final byte[] sub = subfolder();
    int k = 0, m = cmax;
    final int ks = keys.size();
    while(k < ks && m-- > 0) {
      final byte[] nm = keys.get(k++);
      target.add(new TreeLeaf(nm, sub, tbm.get(nm), false, tree, data));
    }

    return m;
  }

  /**
   * Returns the path for a child node of this folder.
   * @return sub folder path
   */
  byte[] subfolder() {
    return path.length > 1 ? concat(concat(path, SLASH), name) :
      concat(path, name);
  }

  /**
   * Extracts the file/document/folder name from the given path.
   * @param path path
   * @return name
   */
  public static byte[] name(final byte[] path) {
    final byte[][] s = split(path, '/');
    if(s.length == 0) return EMPTY;
    return s[s.length - 1];
  }

  /**
   * Returns the path without folder/file name for the given path.
   * @param path path
   * @return path without file/folder name
   */
  public static byte[] path(final byte[] path) {
    if(path.length == 0) return path;
    final byte[] r = substring(path, 0, lastIndexOf(path, '/'));
    return r.length == 0 ? SLASH : r;
  }

  /**
   * Removes all children from this node.
   */
  public void removeChildren() {
    removeAllChildren();
    loaded = false;
  }

  /**
   * Reloads this node without repainting the tree.
   */
  public void reload() {
    removeChildren();
    load();
  }

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


text:
package com.github.gobbisanches.ubisoldiers.mechanics;

import java.io.Serializable;

/**
 * Created by Sanches on 29/06/2014.
 */
public class Unit implements Serializable {
    private static final long serialVersionUID = 1L;
    Soldier soldier;
    Weapon weapon;
    Armor armor;

    public Unit(Soldier soldier, Weapon weapon, Armor armor) {
        this.soldier = soldier;
        this.weapon = weapon;
        this.armor = armor;
    }

    public Unit(Unit other) {
        this(other.getSoldier(), other.getWeapon(), other.getArmor());
    }

    public Soldier getSoldier() {
        return soldier;
    }

    public void setSoldier(Soldier soldier) {
        this.soldier = soldier;
    }

    public Weapon getWeapon() {
        return weapon;
    }

    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }

    public Armor getArmor() {
        return armor;
    }

    public void setArmor(Armor armor) {
        this.armor = armor;
    }

    @Override
    public String toString() {
        return "Unit{" +
                "soldier=" + soldier +
                ", weapon=" + weapon +
                ", armor=" + armor +
                '}';
    }

    public double getAttack() {
        return soldier.getAttack() + weapon.getAttack();
    }

    public double getDefense() {
        return soldier.getDefense() + armor.getDefense();
    }
}