text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Orleans;
using Orleans.AzureUtils;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;

namespace UnitTests.StorageTests
{
    internal static class SiloInstanceTableTestConstants
    {
        internal static readonly TimeSpan Timeout = TimeSpan.FromMinutes(1);

        internal static readonly bool DeleteEntriesAfterTest = true; // false; // Set to false for Debug mode

        internal static readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString();  //"Created";
        internal static readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString();    //"Active";
        internal static readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString();        //"Dead";
    }

    /// <summary>
    /// Tests for operation of Orleans SiloInstanceManager using AzureStore - Requires access to external Azure storage
    /// </summary>
    [TestClass]
    public class SiloInstanceTableManagerTests
    {
        public TestContext TestContext { get; set; }

        private string deploymentId;
        private int generation;
        private SiloAddress siloAddress;
        private SiloInstanceTableEntry myEntry;
        private OrleansSiloInstanceManager manager;
        private readonly TraceLogger logger;

        public SiloInstanceTableManagerTests()
        {
            logger = TraceLogger.GetLogger("SiloInstanceTableManagerTests", TraceLogger.LoggerType.Application);
        }

        // Use ClassInitialize to run code before running the first test in the class
        [ClassInitialize]
        public static void ClassInitialize(TestContext testContext)
        {
            TraceLogger.Initialize(new NodeConfiguration());

            //Starts the storage emulator if not started already and it exists (i.e. is installed).
            if(!StorageEmulator.TryStart())
            {
                Console.WriteLine("Azure Storage Emulator could not be started.");
            }
        }

        // Use TestInitialize to run code before running each test
        [TestInitialize]
        public void TestInitialize()
        {
            deploymentId = "test-" + Guid.NewGuid();
            generation = SiloAddress.AllocateNewGeneration();
            siloAddress = SiloAddress.NewLocalAddress(generation);

            logger.Info("DeploymentId={0} Generation={1}", deploymentId, generation);

            logger.Info("Initializing SiloInstanceManager");
            manager = OrleansSiloInstanceManager.GetManager(deploymentId, StorageTestConstants.DataConnectionString)
                .WaitForResultWithThrow(SiloInstanceTableTestConstants.Timeout);
        }

        // Use TestCleanup to run code after each test has run
        [TestCleanup]
        public void TestCleanup()
        {
            if(manager != null && SiloInstanceTableTestConstants.DeleteEntriesAfterTest)
            {
                TimeSpan timeout = SiloInstanceTableTestConstants.Timeout;

                logger.Info("TestCleanup Timeout={0}", timeout);

                manager.DeleteTableEntries(deploymentId).WaitWithThrow(timeout);

                logger.Info("TestCleanup -  Finished");
                manager = null;
            }
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public void SiloInstanceTable_Op_RegisterSiloInstance()
        {
            RegisterSiloInstance();
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public void SiloInstanceTable_Op_ActivateSiloInstance()
        {
            RegisterSiloInstance();

            manager.ActivateSiloInstance(myEntry);
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public void SiloInstanceTable_Op_UnregisterSiloInstance()
        {
            RegisterSiloInstance();

            manager.UnregisterSiloInstance(myEntry);
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public async Task SiloInstanceTable_Op_CreateSiloEntryConditionally()
        {
            bool didInsert = await manager.TryCreateTableVersionEntryAsync()
                .WithTimeout(AzureTableDefaultPolicies.TableOperationTimeout);

            Assert.IsTrue(didInsert, "Did insert");
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public async Task SiloInstanceTable_Register_CheckData()
        {
            const string testName = "SiloInstanceTable_Register_CheckData";
            logger.Info("Start {0}", testName);

            RegisterSiloInstance();

            var data = await FindSiloEntry(siloAddress);
            SiloInstanceTableEntry siloEntry = data.Item1;
            string eTag = data.Item2;

            Assert.IsNotNull(eTag, "ETag should not be null");
            Assert.IsNotNull(siloEntry, "SiloInstanceTableEntry should not be null");

            Assert.AreEqual(SiloInstanceTableTestConstants.INSTANCE_STATUS_CREATED, siloEntry.Status);

            CheckSiloInstanceTableEntry(myEntry, siloEntry);
            logger.Info("End {0}", testName);
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public async Task SiloInstanceTable_Activate_CheckData()
        {
            RegisterSiloInstance();

            manager.ActivateSiloInstance(myEntry);

            var data = await FindSiloEntry(siloAddress);
            Assert.IsNotNull(data, "Data returned should not be null");

            SiloInstanceTableEntry siloEntry = data.Item1;
            string eTag = data.Item2;

            Assert.IsNotNull(eTag, "ETag should not be null");
            Assert.IsNotNull(siloEntry, "SiloInstanceTableEntry should not be null");

            Assert.AreEqual(SiloInstanceTableTestConstants.INSTANCE_STATUS_ACTIVE, siloEntry.Status);

            CheckSiloInstanceTableEntry(myEntry, siloEntry);
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public async Task SiloInstanceTable_Unregister_CheckData()
        {
            RegisterSiloInstance();

            manager.UnregisterSiloInstance(myEntry);

            var data = await FindSiloEntry(siloAddress);
            SiloInstanceTableEntry siloEntry = data.Item1;
            string eTag = data.Item2;

            Assert.IsNotNull(eTag, "ETag should not be null");
            Assert.IsNotNull(siloEntry, "SiloInstanceTableEntry should not be null");

            Assert.AreEqual(SiloInstanceTableTestConstants.INSTANCE_STATUS_DEAD, siloEntry.Status);

            CheckSiloInstanceTableEntry(myEntry, siloEntry);
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public void SiloInstanceTable_FindAllGatewayProxyEndpoints()
        {
            RegisterSiloInstance();

            var gateways = manager.FindAllGatewayProxyEndpoints();
            Assert.AreEqual(0, gateways.Count, "Number of gateways before Silo.Activate");

            manager.ActivateSiloInstance(myEntry);

            gateways = manager.FindAllGatewayProxyEndpoints();
            Assert.AreEqual(1, gateways.Count, "Number of gateways after Silo.Activate");

            Uri myGateway = gateways.First();
            Assert.AreEqual(myEntry.Address, myGateway.Host.ToString(), "Gateway address");
            Assert.AreEqual(myEntry.ProxyPort, myGateway.Port.ToString(CultureInfo.InvariantCulture), "Gateway port");
        }

        [TestMethod, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
        public void SiloAddress_ToFrom_RowKey()
        {
            string ipAddress = "1.2.3.4";
            int port = 5555;
            int generation = 6666;

            IPAddress address = IPAddress.Parse(ipAddress);
            IPEndPoint endpoint = new IPEndPoint(address, port);
            SiloAddress siloAddress = SiloAddress.New(endpoint, generation);

            string MembershipRowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);

            Console.WriteLine("SiloAddress = {0} Row Key string = {1}", siloAddress, MembershipRowKey);

            SiloAddress fromRowKey = SiloInstanceTableEntry.UnpackRowKey(MembershipRowKey);

            Console.WriteLine("SiloAddress result = {0} From Row Key string = {1}", fromRowKey, MembershipRowKey);

            Assert.AreEqual(siloAddress, fromRowKey, "Compare SiloAddress");
            Assert.AreEqual(SiloInstanceTableEntry.ConstructRowKey(siloAddress), SiloInstanceTableEntry.ConstructRowKey(fromRowKey), "SiloInstanceTableEntry.ConstructRowKey");
        }

        private void RegisterSiloInstance()
        {
            string partitionKey = deploymentId;
            string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);

            IPEndPoint myEndpoint = siloAddress.Endpoint;

            myEntry = new SiloInstanceTableEntry
            {
                PartitionKey = partitionKey,
                RowKey = rowKey,

                DeploymentId = deploymentId,
                Address = myEndpoint.Address.ToString(),
                Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
                Generation = generation.ToString(CultureInfo.InvariantCulture),

                HostName = myEndpoint.Address.ToString(),
                ProxyPort = "30000",

                RoleName = "MyRole",
                InstanceName = "MyInstance",
                UpdateZone = "0",
                FaultZone = "0",
                StartTime = TraceLogger.PrintDate(DateTime.UtcNow),
            };

            logger.Info("MyEntry={0}", myEntry);

            manager.RegisterSiloInstance(myEntry);
        }

        private async Task<Tuple<SiloInstanceTableEntry, string>> FindSiloEntry(SiloAddress siloAddr)
        {
            string partitionKey = deploymentId;
            string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddr);

            logger.Info("FindSiloEntry for SiloAddress={0} PartitionKey={1} RowKey={2}", siloAddr, partitionKey, rowKey);

            Tuple<SiloInstanceTableEntry, string> data = await manager.ReadSingleTableEntryAsync(partitionKey, rowKey);

            logger.Info("FindSiloEntry returning Data={0}", data);
            return data;
        }

        private void CheckSiloInstanceTableEntry(SiloInstanceTableEntry referenceEntry, SiloInstanceTableEntry entry)
        {
            Assert.AreEqual(referenceEntry.DeploymentId, entry.DeploymentId, "DeploymentId");
            Assert.AreEqual(referenceEntry.Address, entry.Address, "Address");
            Assert.AreEqual(referenceEntry.Port, entry.Port, "Port");
            Assert.AreEqual(referenceEntry.Generation, entry.Generation, "Generation");
            Assert.AreEqual(referenceEntry.HostName, entry.HostName, "HostName");
            //Assert.AreEqual(referenceEntry.Status, entry.Status, "Status");
            Assert.AreEqual(referenceEntry.ProxyPort, entry.ProxyPort, "ProxyPort");
            Assert.AreEqual(referenceEntry.RoleName, entry.RoleName, "RoleName");
            Assert.AreEqual(referenceEntry.InstanceName, entry.InstanceName, "InstanceName");
            Assert.AreEqual(referenceEntry.UpdateZone, entry.UpdateZone, "UpdateZone");
            Assert.AreEqual(referenceEntry.FaultZone, entry.FaultZone, "FaultZone");
            Assert.AreEqual(referenceEntry.StartTime, entry.StartTime, "StartTime");
            Assert.AreEqual(referenceEntry.IAmAliveTime, entry.IAmAliveTime, "IAmAliveTime");
            Assert.AreEqual(referenceEntry.MembershipVersion, entry.MembershipVersion, "MembershipVersion");

            Assert.AreEqual(referenceEntry.SuspectingTimes, entry.SuspectingTimes, "SuspectingTimes");
            Assert.AreEqual(referenceEntry.SuspectingSilos, entry.SuspectingSilos, "SuspectingSilos");
        }
    }
}


text:
package org.jabref.gui;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import org.jabref.Globals;
import org.jabref.JabRefExecutorService;
import org.jabref.JabRefGUI;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.importer.EntryFromFileCreator;
import org.jabref.gui.importer.EntryFromFileCreatorManager;
import org.jabref.gui.importer.UnlinkedFilesCrawler;
import org.jabref.gui.importer.UnlinkedPDFFileFilter;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.EntryTypes;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibtexEntryType;
import org.jabref.model.entry.EntryType;
import org.jabref.model.entry.FieldName;
import org.jabref.preferences.JabRefPreferences;

import com.jgoodies.forms.builder.ButtonBarBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * GUI Dialog for the feature "Find unlinked files".
 */
public class FindUnlinkedFilesDialog extends JabRefDialog {

    /**
     * Keys to be used for referencing this Action.
     */
    public static final String ACTION_COMMAND = "findUnlinkedFiles";
    public static final String ACTION_MENU_TITLE = Localization.menuTitle("Find unlinked files...");

    public static final String ACTION_SHORT_DESCRIPTION = Localization
            .lang("Searches for unlinked PDF files on the file system");

    private static final Log LOGGER = LogFactory.getLog(FindUnlinkedFilesDialog.class);
    private static final String GLOBAL_PREFS_WORKING_DIRECTORY_KEY = "findUnlinkedFilesWD";

    private static final String GLOBAL_PREFS_DIALOG_SIZE_KEY = "findUnlinkedFilesDialogSize";
    private final JabRefFrame frame;
    private final BibDatabaseContext databaseContext;
    private final EntryFromFileCreatorManager creatorManager;

    private final UnlinkedFilesCrawler crawler;
    private Path lastSelectedDirectory;

    private TreeModel treeModel;
    /* PANELS */
    private JPanel panelDirectory;
    private JPanel panelSearchArea;
    private JPanel panelFiles;
    private JPanel panelOptions;
    private JPanel panelButtons;
    private JPanel panelEntryTypesSelection;

    private JPanel panelImportArea;
    private JButton buttonBrowse;
    private JButton buttonScan;
    private JButton buttonApply;

    private JButton buttonClose;
    /* Options for the TreeView */
    private JButton buttonOptionSelectAll;
    private JButton buttonOptionDeselectAll;
    private JButton buttonOptionExpandAll;
    private JButton buttonOptionCollapseAll;

    private JCheckBox checkboxCreateKeywords;
    private JTextField textfieldDirectoryPath;
    private JLabel labelDirectoryDescription;
    private JLabel labelFileTypesDescription;
    private JLabel labelFilesDescription;
    private JLabel labelEntryTypeDescription;
    private JLabel labelSearchingDirectoryInfo;

    private JLabel labelImportingInfo;
    private JTree tree;
    private JScrollPane scrollpaneTree;
    private JComboBox<FileFilter> comboBoxFileTypeSelection;

    private JComboBox<BibtexEntryTypeWrapper> comboBoxEntryTypeSelection;
    private JProgressBar progressBarSearching;
    private JProgressBar progressBarImporting;

    private MouseListener treeMouseListener;
    private Action actionSelectAll;
    private Action actionUnselectAll;
    private Action actionExpandTree;

    private Action actionCollapseTree;

    private ComponentListener dialogPositionListener;
    private final AtomicBoolean threadState = new AtomicBoolean();

    private boolean checkBoxWhyIsThereNoGetSelectedStupidSwing;

    public FindUnlinkedFilesDialog(Frame owner, JabRefFrame frame, BasePanel panel) {
        super(owner, Localization.lang("Find unlinked files"), true, FindUnlinkedFilesDialog.class);
        this.frame = frame;

        restoreSizeOfDialog();

        databaseContext = panel.getDatabaseContext();
        creatorManager = new EntryFromFileCreatorManager();
        crawler = new UnlinkedFilesCrawler(databaseContext);

        lastSelectedDirectory = loadLastSelectedDirectory();

        initialize();
        buttonApply.setEnabled(false);
    }

    /**
     * Close dialog when pressing escape
     */
    @Override
    protected JRootPane createRootPane() {
        ActionListener actionListener = actionEvent -> setVisible(false);
        JRootPane rPane = new JRootPane();
        KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        rPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return rPane;
    }

    /**
     * Stores the current size of this dialog persistently.
     */
    private void storeSizeOfDialog() {
        Dimension dim = getSize();
        String store = dim.width + ";" + dim.height;
        Globals.prefs.put(FindUnlinkedFilesDialog.GLOBAL_PREFS_DIALOG_SIZE_KEY, store);
    }

    /**
     * Restores the location and size of this dialog from the persistent storage.
     */
    private void restoreSizeOfDialog() {

        String store = Globals.prefs.get(FindUnlinkedFilesDialog.GLOBAL_PREFS_DIALOG_SIZE_KEY);

        Dimension dimension = null;

        if (store != null) {
            try {
                String[] dim = store.split(";");
                dimension = new Dimension(Integer.valueOf(dim[0]), Integer.valueOf(dim[1]));
            } catch (NumberFormatException ignoredEx) {
                LOGGER.debug("RestoreSizeDialog Exception ", ignoredEx);
            }
        }
        if (dimension != null) {
            setPreferredSize(dimension);
        }
    }

    /**
     * Initializes the components, the layout, the data structure and the
     * actions in this dialog.
     */
    private void initialize() {

        initializeActions();
        initComponents();
        createTree();
        createFileTypesCombobox();
        createEntryTypesCombobox();
        initLayout();
        setupActions();
        pack();
    }

    /**
     * Initializes action objects.

     * Does not assign actions to components yet!
     */
    private void initializeActions() {

        actionSelectAll = new AbstractAction(Localization.lang("Select all")) {

            @Override
            public void actionPerformed(ActionEvent e) {
                CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot();
                rootNode.setSelected(true);
                tree.invalidate();
                tree.repaint();
            }
        };

        actionUnselectAll = new AbstractAction(Localization.lang("Unselect all")) {

            @Override
            public void actionPerformed(ActionEvent e) {
                CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot();
                rootNode.setSelected(false);
                tree.invalidate();
                tree.repaint();
            }
        };

        actionExpandTree = new AbstractAction(Localization.lang("Expand all")) {

            @Override
            public void actionPerformed(ActionEvent e) {
                CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot();
                expandTree(tree, new TreePath(rootNode), true);
            }
        };

        actionCollapseTree = new AbstractAction(Localization.lang("Collapse all")) {

            @Override
            public void actionPerformed(ActionEvent e) {
                CheckableTreeNode rootNode = (CheckableTreeNode) tree.getModel().getRoot();
                expandTree(tree, new TreePath(rootNode), false);
            }
        };

        dialogPositionListener = new ComponentAdapter() {

            /* (non-Javadoc)
             * @see java.awt.event.ComponentAdapter#componentResized(java.awt.event.ComponentEvent)
             */
            @Override
            public void componentResized(ComponentEvent e) {
                storeSizeOfDialog();
            }

            /* (non-Javadoc)
             * @see java.awt.event.ComponentAdapter#componentMoved(java.awt.event.ComponentEvent)
             */
            @Override
            public void componentMoved(ComponentEvent e) {
                storeSizeOfDialog();
            }
        };

    }

    /**
     * Stores the working directory path for this view in the global
     * preferences.
     *
     * @param lastSelectedDir
     *            directory that is used as the working directory in this view.
     */
    private void storeLastSelectedDirectory(Path lastSelectedDir) {
        lastSelectedDirectory = lastSelectedDir;
        if (lastSelectedDirectory != null) {
            Globals.prefs.put(FindUnlinkedFilesDialog.GLOBAL_PREFS_WORKING_DIRECTORY_KEY,
                    lastSelectedDirectory.toAbsolutePath().toString());
        }
    }

    /**
     * Loads the working directory path which is persistantly stored for this
     * view and returns it as a {@link File}-Object.

     *

     * If there is no working directory path stored, the general working
     * directory will be consulted.
     *
     * @return The persistently stored working directory path for this view.
     */
    private Path loadLastSelectedDirectory() {
        String workingDirectory = Globals.prefs.get(FindUnlinkedFilesDialog.GLOBAL_PREFS_WORKING_DIRECTORY_KEY);
        if (workingDirectory == null) {
            workingDirectory = Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY);
        }
        lastSelectedDirectory = Paths.get(workingDirectory);

        return lastSelectedDirectory;
    }

    /**
     * Disables or enables all visible Elements in this Dialog.

     *

     * This also removes the {@link MouseListener} from the Tree-View to prevent
     * it from receiving mouse events when in disabled-state.
     *
     * @param enable
     *            true when the elements shall get enabled,
     *            false when they shall get disabled.
     */
    private void disOrEnableDialog(boolean enable) {

        if (enable) {
            tree.addMouseListener(treeMouseListener);
        } else {
            tree.removeMouseListener(treeMouseListener);
        }
        disOrEnableAllElements(FindUnlinkedFilesDialog.this, enable);
    }

    /**
     * Recursively disables or enables all swing and awt components in this
     * dialog, starting with but not including the container
     * startContainer.
     *
     * @param startContainer
     *            The GUI Element to start with.
     * @param enable
     *            true, if all elements will get enabled,
     *            false if all elements will get disabled.
     */
    private void disOrEnableAllElements(Container startContainer, boolean enable) {
        Component[] children = startContainer.getComponents();
        for (Component child : children) {
            if (child instanceof Container) {
                disOrEnableAllElements((Container) child, enable);
            }
            child.setEnabled(enable);
        }
    }

    /**
     * Expands or collapses the specified tree according to the
     * expand-parameter.
     */
    private void expandTree(JTree currentTree, TreePath parent, boolean expand) {
        TreeNode node = (TreeNode) parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration<TreeNode> e = node.children(); e.hasMoreElements();) {
                TreePath path = parent.pathByAddingChild(e.nextElement());
                expandTree(currentTree, path, expand);
            }
        }
        if (expand) {
            currentTree.expandPath(parent);
        } else {
            currentTree.collapsePath(parent);
        }
    }

    /**
     * Starts the search of unlinked files according to the current dialog
     * state.

     *

     * This state is made of:

     *
The value of the "directory"-input-textfield and
The file type
     * selection.

     * The search will process in a seperate thread and the progress bar behind
     * the "search" button will be displayed.

     *

     * When the search has completed, the
     * {@link #searchFinishedHandler(CheckableTreeNode)} handler method is
     * invoked.
     */
    private void startSearch() {

        Path directory = Paths.get(textfieldDirectoryPath.getText());
        if (Files.notExists(directory)) {
            directory = Paths.get(System.getProperty("user.dir"));
        }
        if (!Files.isDirectory(directory)) {
            directory = directory.getParent();
        }

        //this addtional statement is needed because for the lamdba the variable must be effetively final
        Path dir = directory;

        storeLastSelectedDirectory(directory);

        progressBarSearching.setMinimumSize(
                new Dimension(buttonScan.getSize().width, progressBarSearching.getMinimumSize().height));
        progressBarSearching.setVisible(true);
        progressBarSearching.setString("");

        labelSearchingDirectoryInfo.setVisible(true);
        buttonScan.setVisible(false);

        disOrEnableDialog(false);
        labelSearchingDirectoryInfo.setEnabled(true);

        final FileFilter selectedFileFilter = (FileFilter) comboBoxFileTypeSelection.getSelectedItem();

        threadState.set(true);
        JabRefExecutorService.INSTANCE.execute(() -> {
            UnlinkedPDFFileFilter unlinkedPDFFileFilter = new UnlinkedPDFFileFilter(selectedFileFilter,
                    databaseContext);
            CheckableTreeNode rootNode = crawler.searchDirectory(dir.toFile(), unlinkedPDFFileFilter, threadState,
                    new ChangeListener() {

                        int counter;

                        @Override
                        public void stateChanged(ChangeEvent e) {
                            counter++;
                            String message;
                            if (counter == 1) {
                                message = Localization.lang("One file found");
                            } else {
                                message = Localization.lang("%0 files found", Integer.toString(counter));
                            }
                            progressBarSearching.setString(message);
                        }
                    });
            searchFinishedHandler(rootNode);
        });

    }

    /**
     * This will start the import of all file of all selected nodes in this
     * dialogs tree view.

     *

     * The import itself will run in a seperate thread, whilst this dialog will
     * be showing a progress bar, until the thread has finished its work.

     *

     * When the import has finished, the {@link #importFinishedHandler(java.util.List)} is
     * invoked.
     */
    private void startImport() {

        if (treeModel == null) {
            return;
        }
        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

        CheckableTreeNode root = (CheckableTreeNode) treeModel.getRoot();

        final List<File> fileList = getFileListFromNode(root);

        if ((fileList == null) || fileList.isEmpty()) {
            return;
        }

        progressBarImporting.setVisible(true);
        labelImportingInfo.setVisible(true);
        buttonApply.setVisible(false);
        buttonClose.setVisible(false);
        disOrEnableDialog(false);

        labelImportingInfo.setEnabled(true);

        progressBarImporting.setMinimum(0);
        progressBarImporting.setMaximum(fileList.size());
        progressBarImporting.setValue(0);
        progressBarImporting.setString("");

        final EntryType entryType = ((BibtexEntryTypeWrapper) comboBoxEntryTypeSelection.getSelectedItem())
                .getEntryType();

        threadState.set(true);
        JabRefExecutorService.INSTANCE.execute(() -> {
            List<String> errors = new LinkedList<>();
            creatorManager.addEntriesFromFiles(fileList, databaseContext.getDatabase(), frame.getCurrentBasePanel(),
                    entryType, checkBoxWhyIsThereNoGetSelectedStupidSwing, new ChangeListener() {

                        int counter;

                        @Override
                        public void stateChanged(ChangeEvent e) {
                            counter++;
                            progressBarImporting.setValue(counter);
                            progressBarImporting.setString(Localization.lang("%0 of %1", Integer.toString(counter),
                                    Integer.toString(progressBarImporting.getMaximum())));
                        }
                    }, errors);
            importFinishedHandler(errors);
        });
    }

    /**
     *
     * @param errors
     */
    private void importFinishedHandler(List<String> errors) {

        if ((errors != null) && !errors.isEmpty()) {
            String message;
            if (errors.size() == 1) {
                message = Localization.lang("There was one file that could not be imported.");
            } else {
                message = Localization.lang("There were %0 files which could not be imported.",
                        Integer.toString(errors.size()));
            }
            JOptionPane.showMessageDialog(this,
                    Localization.lang("The import finished with warnings:") + "\n" + message,
                    Localization.lang("Warning"), JOptionPane.WARNING_MESSAGE);
        }

        progressBarImporting.setVisible(false);
        labelImportingInfo.setVisible(false);
        buttonApply.setVisible(true);
        buttonClose.setVisible(true);
        disOrEnableDialog(true);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.getCurrentBasePanel().markBaseChanged();
    }

    /**
     * Will be called from the Thread in which the "unlinked files search" is
     * processed. As the result of the search, the root node of the determined
     * file structure is passed.
     *
     * @param rootNode
     *            The root of the file structure as the result of the search.
     */
    private void searchFinishedHandler(CheckableTreeNode rootNode) {
        treeModel = new DefaultTreeModel(rootNode);
        tree.setModel(treeModel);
        tree.setRootVisible(rootNode.getChildCount() > 0);

        tree.invalidate();
        tree.repaint();

        progressBarSearching.setVisible(false);
        labelSearchingDirectoryInfo.setVisible(false);
        buttonScan.setVisible(true);
        actionSelectAll.actionPerformed(null);

        disOrEnableDialog(true);
        buttonApply.setEnabled(true);
    }

    /**
     * Sets up the actions for the components.
     */
    private void setupActions() {

        DirectoryDialogConfiguration directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder()
                .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build();
        DialogService ds = new FXDialogService();
        /**
         * Stores the selected directory.
         */
        buttonBrowse.addActionListener(e -> {
            Optional<Path> selectedDirectory = DefaultTaskExecutor
                    .runInJavaFXThread(() -> ds.showDirectorySelectionDialog(directoryDialogConfiguration));
            selectedDirectory.ifPresent(d -> {
                textfieldDirectoryPath.setText(d.toAbsolutePath().toString());
                storeLastSelectedDirectory(d);
            });
        });

        buttonScan.addActionListener(e -> startSearch());

        /**
         * Action for the button "Import...".

         *

         * Actions on this button will start the import of all file of all
         * selected nodes in this dialogs tree view.

         */
        ActionListener actionListenerImportEntrys = e -> startImport();
        buttonApply.addActionListener(actionListenerImportEntrys);
        buttonClose.addActionListener(e -> dispose());
    }

    /**
     * Creates a list of {@link File}s for all leaf nodes in the tree structure
     * node, which have been marked as selected.

     *

     * Selected nodes correspond to those entries in the tree,
     * whose checkbox is checked.
     *
     * SIDE EFFECT: The checked nodes are removed from the tree.
     *
     * @param node
     *            The root node representing a tree structure.
     * @return A list of files of all checked leaf nodes.
     */
    private List<File> getFileListFromNode(CheckableTreeNode node) {
        List<File> filesList = new ArrayList<>();
        Enumeration<CheckableTreeNode> children = node.depthFirstEnumeration();
        List<CheckableTreeNode> nodesToRemove = new ArrayList<>();
        for (CheckableTreeNode child : Collections.list(children)) {
            if (child.isLeaf() && child.isSelected()) {
                File nodeFile = ((FileNodeWrapper) child.getUserObject()).file;
                if ((nodeFile != null) && nodeFile.isFile()) {
                    filesList.add(nodeFile);
                    nodesToRemove.add(child);
                }
            }
        }

        // remove imported files from tree
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        for (CheckableTreeNode nodeToRemove : nodesToRemove) {
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) nodeToRemove.getParent();
            model.removeNodeFromParent(nodeToRemove);

            // remove empty parent node
            while ((parent != null) && parent.isLeaf()) {
                DefaultMutableTreeNode pp = (DefaultMutableTreeNode) parent.getParent();
                if (pp != null) {
                    model.removeNodeFromParent(parent);
                }
                parent = pp;
            }
            // TODO: update counter / see: getTreeCellRendererComponent for label generation
        }
        tree.invalidate();
        tree.repaint();

        return filesList;
    }

    /**
     * Initializes the visible components in this dialog.
     */
    private void initComponents() {

        this.addComponentListener(dialogPositionListener);
        /* Interrupts the searchThread by setting the State-Array to 0 */
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                threadState.set(false);
            }
        });

        panelDirectory = new JPanel();
        panelSearchArea = new JPanel();
        panelFiles = new JPanel();
        panelOptions = new JPanel();
        panelEntryTypesSelection = new JPanel();
        panelButtons = new JPanel();
        panelImportArea = new JPanel();

        buttonBrowse = new JButton(Localization.lang("Browse"));
        buttonBrowse.setMnemonic('B');
        buttonBrowse.setToolTipText(Localization.lang("Opens the file browser."));
        buttonScan = new JButton(Localization.lang("Scan directory"));
        buttonScan.setMnemonic('S');
        buttonScan.setToolTipText(Localization.lang("Searches the selected directory for unlinked files."));
        buttonApply = new JButton(Localization.lang("Apply"));
        buttonApply.setMnemonic('I');
        buttonApply.setToolTipText(Localization.lang("Starts the import of BibTeX entries."));
        buttonClose = new JButton(Localization.lang("Close"));
        buttonClose.setToolTipText(Localization.lang("Leave this dialog."));
        buttonClose.setMnemonic('C');

        /* Options for the TreeView */
        buttonOptionSelectAll = new JButton();
        buttonOptionSelectAll.setMnemonic('A');
        buttonOptionSelectAll.setAction(actionSelectAll);
        buttonOptionDeselectAll = new JButton();
        buttonOptionDeselectAll.setMnemonic('U');
        buttonOptionDeselectAll.setAction(actionUnselectAll);
        buttonOptionExpandAll = new JButton();
        buttonOptionExpandAll.setMnemonic('E');
        buttonOptionExpandAll.setAction(actionExpandTree);
        buttonOptionCollapseAll = new JButton();
        buttonOptionCollapseAll.setMnemonic('L');
        buttonOptionCollapseAll.setAction(actionCollapseTree);

        checkboxCreateKeywords = new JCheckBox(Localization.lang("Create directory based keywords"));
        checkboxCreateKeywords
                .setToolTipText(Localization.lang("Creates keywords in created entrys with directory pathnames"));
        checkboxCreateKeywords.setSelected(checkBoxWhyIsThereNoGetSelectedStupidSwing);
        checkboxCreateKeywords.addItemListener(
                e -> checkBoxWhyIsThereNoGetSelectedStupidSwing = !checkBoxWhyIsThereNoGetSelectedStupidSwing);

        textfieldDirectoryPath = new JTextField();
        textfieldDirectoryPath
                .setText(lastSelectedDirectory == null ? "" : lastSelectedDirectory.toAbsolutePath().toString());

        labelDirectoryDescription = new JLabel(Localization.lang("Select a directory where the search shall start."));
        labelFileTypesDescription = new JLabel(Localization.lang("Select file type:"));
        labelFilesDescription = new JLabel(Localization.lang("These files are not linked in the active library."));
        labelEntryTypeDescription = new JLabel(Localization.lang("Entry type to be created:"));
        labelSearchingDirectoryInfo = new JLabel(Localization.lang("Searching file system..."));
        labelSearchingDirectoryInfo.setHorizontalAlignment(SwingConstants.CENTER);
        labelSearchingDirectoryInfo.setVisible(false);
        labelImportingInfo = new JLabel(Localization.lang("Importing into Library..."));
        labelImportingInfo.setHorizontalAlignment(SwingConstants.CENTER);
        labelImportingInfo.setVisible(false);

        tree = new JTree();

        scrollpaneTree = new JScrollPane(tree);
        scrollpaneTree.setWheelScrollingEnabled(true);

        progressBarSearching = new JProgressBar();
        progressBarSearching.setIndeterminate(true);
        progressBarSearching.setVisible(false);
        progressBarSearching.setStringPainted(true);

        progressBarImporting = new JProgressBar();
        progressBarImporting.setIndeterminate(false);
        progressBarImporting.setVisible(false);
        progressBarImporting.setStringPainted(true);

    }

    /**
     * Initializes the layout for the visible components in this menu. A
     * {@link GridBagLayout} is used.
     */
    private void initLayout() {

        GridBagLayout gbl = new GridBagLayout();

        panelDirectory.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
                Localization.lang("Select directory")));
        panelFiles.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
                Localization.lang("Select files")));
        panelEntryTypesSelection.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
                Localization.lang("BibTeX entry creation")));

        Insets basicInsets = new Insets(6, 6, 6, 6);
        Insets smallInsets = new Insets(3, 2, 3, 1);
        Insets noInsets = new Insets(0, 0, 0, 0);

        // 		x, y, w, h, wx,wy,ix,iy
        FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, buttonScan, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.EAST, noInsets, 0, 1, 1, 1, 1, 1, 40, 10);
        FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, labelSearchingDirectoryInfo,
                GridBagConstraints.HORIZONTAL, GridBagConstraints.EAST, noInsets, 0, 2, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelSearchArea, progressBarSearching, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.EAST, noInsets, 0, 3, 1, 1, 0, 0, 0, 0);

        FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, labelDirectoryDescription, null,
                GridBagConstraints.WEST, new Insets(6, 6, 0, 6), 0, 0, 3, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, textfieldDirectoryPath, GridBagConstraints.HORIZONTAL,
                null, basicInsets, 0, 1, 2, 1, 1, 1, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, buttonBrowse, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.EAST, basicInsets, 2, 1, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, labelFileTypesDescription, GridBagConstraints.NONE,
                GridBagConstraints.WEST, new Insets(18, 6, 18, 3), 0, 3, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, comboBoxFileTypeSelection,
                GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, new Insets(18, 3, 18, 6), 1, 3, 1, 1, 1, 0, 0,
                0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelDirectory, panelSearchArea, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.EAST, new Insets(18, 6, 18, 6), 2, 3, 1, 1, 0, 0, 0, 0);

        FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, labelFilesDescription, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.WEST, new Insets(6, 6, 0, 6), 0, 0, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, scrollpaneTree, GridBagConstraints.BOTH,
                GridBagConstraints.CENTER, basicInsets, 0, 1, 1, 1, 1, 1, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelFiles, panelOptions, GridBagConstraints.NONE,
                GridBagConstraints.NORTHEAST, basicInsets, 1, 1, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionSelectAll, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.NORTH, noInsets, 0, 0, 1, 1, 1, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionDeselectAll, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.NORTH, noInsets, 0, 1, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionExpandAll, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.NORTH, new Insets(6, 0, 0, 0), 0, 2, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelOptions, buttonOptionCollapseAll, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.NORTH, noInsets, 0, 3, 1, 1, 0, 0, 0, 0);

        FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, labelEntryTypeDescription,
                GridBagConstraints.NONE, GridBagConstraints.WEST, basicInsets, 0, 0, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, comboBoxEntryTypeSelection,
                GridBagConstraints.NONE, GridBagConstraints.WEST, basicInsets, 1, 0, 1, 1, 1, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelEntryTypesSelection, checkboxCreateKeywords,
                GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, basicInsets, 0, 1, 2, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelImportArea, labelImportingInfo, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.CENTER, new Insets(6, 6, 0, 6), 0, 1, 1, 1, 1, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelImportArea, progressBarImporting, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.CENTER, new Insets(0, 6, 6, 6), 0, 2, 1, 1, 1, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, panelButtons, panelImportArea, GridBagConstraints.NONE,
                GridBagConstraints.EAST, smallInsets, 1, 0, 1, 1, 0, 0, 0, 0);

        FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelDirectory, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.CENTER, basicInsets, 0, 0, 1, 1, 0, 0, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelFiles, GridBagConstraints.BOTH,
                GridBagConstraints.NORTHWEST, new Insets(12, 6, 2, 2), 0, 1, 1, 1, 1, 1, 0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelEntryTypesSelection,
                GridBagConstraints.HORIZONTAL, GridBagConstraints.SOUTHWEST, new Insets(12, 6, 2, 2), 0, 2, 1, 1, 0, 0,
                0, 0);
        FindUnlinkedFilesDialog.addComponent(gbl, getContentPane(), panelButtons, GridBagConstraints.HORIZONTAL,
                GridBagConstraints.CENTER, new Insets(10, 6, 10, 6), 0, 3, 1, 1, 0, 0, 0, 0);

        ButtonBarBuilder bb = new ButtonBarBuilder();
        bb.addGlue();
        bb.addButton(buttonApply);
        bb.addButton(buttonClose);
        bb.addGlue();

        bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        panelImportArea.add(bb.getPanel(), GridBagConstraints.NONE);
        pack();

    }

    /**
     * Adds a component to a container, using the specified gridbag-layout and
     * the supplied parameters.

     *

     * This method is simply used to ged rid of thousands of lines of code,
     * which inevitably rise when layouts such as the gridbag-layout is being
     * used.
     *
     * @param layout
     *            The layout to be used.
     * @param container
     *            The {@link Container}, to which the component will be added.
     * @param component
     *            An AWT {@link Component}, that will be added to the container.
     * @param fill
     *            A constant describing the fill behaviour (see
     *            {@link GridBagConstraints}). Can be null, if no
     *            filling wants to be specified.
     * @param anchor
     *            A constant describing the anchor of the element in its parent
     *            container (see {@link GridBagConstraints}). Can be
     *            null, if no specification is needed.
     * @param gridX
     *            The relative grid-X coordinate.
     * @param gridY
     *            The relative grid-Y coordinate.
     * @param width
     *            The relative width of the component.
     * @param height
     *            The relative height of the component.
     * @param weightX
     *            A value for the horizontal weight.
     * @param weightY
     *            A value for the vertical weight.
     * @param insets
     *            Insets of the component. Can be null.
     */
    private static void addComponent(GridBagLayout layout, Container container, Component component, Integer fill,
            Integer anchor, Insets insets, int gridX, int gridY, int width, int height, double weightX, double weightY,
            int ipadX, int ipadY) {
        container.setLayout(layout);
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = gridX;
        constraints.gridy = gridY;
        constraints.gridwidth = width;
        constraints.gridheight = height;
        constraints.weightx = weightX;
        constraints.weighty = weightY;
        constraints.ipadx = ipadX;
        constraints.ipady = ipadY;
        if (fill != null) {
            constraints.fill = fill;
        }
        if (insets != null) {
            constraints.insets = insets;
        }
        if (anchor != null) {
            constraints.anchor = anchor;
        }
        layout.setConstraints(component, constraints);
        container.add(component);
    }

    /**
     * Creates the tree view, that holds the data structure.

     *

     * Initially, the root node is not visible, so that the tree appears empty at the beginning.
     */
    private void createTree() {

        /**
         * Mouse listener to listen for mouse events on the tree.

         * This will mark the selected tree entry as "selected" or "unselected",
         * which will cause this nodes checkbox to appear as either "checked" or
         * "unchecked".
         */
        treeMouseListener = new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();

                int row = tree.getRowForLocation(x, y);

                TreePath path = tree.getPathForRow(row);
                if (path != null) {
                    CheckableTreeNode node = (CheckableTreeNode) path.getLastPathComponent();
                    if (e.getClickCount() == 2) {
                        Object userObject = node.getUserObject();
                        if ((userObject instanceof FileNodeWrapper) && node.isLeaf()) {
                            FileNodeWrapper fnw = (FileNodeWrapper) userObject;
                            try {
                                JabRefDesktop.openExternalViewer(
                                        JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext(),
                                        fnw.file.getAbsolutePath(), FieldName.PDF);
                            } catch (IOException e1) {
                                LOGGER.info("Error opening file", e1);
                            }
                        }
                    } else {
                        node.check();
                        tree.invalidate();
                        tree.repaint();
                    }
                }
            }

        };

        CheckableTreeNode startNode = new CheckableTreeNode("ROOT");
        DefaultTreeModel model = new DefaultTreeModel(startNode);

        tree.setModel(model);
        tree.setRootVisible(false);

        DefaultTreeCellRenderer renderer = new CheckboxTreeCellRenderer();
        tree.setCellRenderer(renderer);

        tree.addMouseListener(treeMouseListener);

    }

    /**
     * Initialises the combobox that contains the available file types which
     * bibtex entries can be created of.
     */
    private void createFileTypesCombobox() {

        List<FileFilter> fileFilterList = creatorManager.getFileFilterList();

        comboBoxFileTypeSelection = new JComboBox<>(fileFilterList.toArray(new FileFilter[fileFilterList.size()]));

        comboBoxFileTypeSelection.setRenderer(new DefaultListCellRenderer() {

            /* (non-Javadoc)
             * @see javax.swing.DefaultListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
             */
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
                    boolean cellHasFocus) {
                JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,
                        cellHasFocus);
                if (value instanceof EntryFromFileCreator) {
                    EntryFromFileCreator creator = (EntryFromFileCreator) value;
                    if (creator.getExternalFileType() != null) {
                        label.setIcon(creator.getExternalFileType().getIcon());
                    }
                }
                return label;
            }
        });

    }

    /**
     * Creates the ComboBox-View for the Listbox that holds the Bibtex entry
     * types.
     */
    private void createEntryTypesCombobox() {

        Iterator<EntryType> iterator = EntryTypes
                .getAllValues(frame.getCurrentBasePanel().getBibDatabaseContext().getMode()).iterator();
        List<BibtexEntryTypeWrapper> list = new ArrayList<>();
        list.add(
                new BibtexEntryTypeWrapper(null));
        while (iterator.hasNext()) {
            list.add(new BibtexEntryTypeWrapper(iterator.next()));
        }
        comboBoxEntryTypeSelection = new JComboBox<>(list.toArray(new BibtexEntryTypeWrapper[list.size()]));
    }

    /**
     * Wrapper for displaying the Type {@link BibtexEntryType} in a Combobox.
     *
     * @author Nosh&Dan
     * @version 12.11.2008 | 01:02:30
     *
     */
    private static class BibtexEntryTypeWrapper {

        private final EntryType entryType;

        BibtexEntryTypeWrapper(EntryType bibtexType) {
            this.entryType = bibtexType;
        }

        @Override
        public String toString() {
            if (entryType == null) {
                return Localization.lang("<No selection>");
            }
            return entryType.getName();
        }

        public EntryType getEntryType() {
            return entryType;
        }
    }

    public static class CheckableTreeNode extends DefaultMutableTreeNode {

        private boolean isSelected;
        private final JCheckBox checkbox;

        public CheckableTreeNode(Object userObject) {
            super(userObject);
            checkbox = new JCheckBox();
        }

        /**
         * @return the checkbox
         */
        public JCheckBox getCheckbox() {
            return checkbox;
        }

        public void check() {
            setSelected(!isSelected);
        }

        public void setSelected(boolean bSelected) {
            isSelected = bSelected;
            Enumeration<CheckableTreeNode> tmpChildren = this.children();
            for (CheckableTreeNode child : Collections.list(tmpChildren)) {
                child.setSelected(bSelected);
            }

        }

        public boolean isSelected() {
            return isSelected;
        }

    }

    private static class CheckboxTreeCellRenderer extends DefaultTreeCellRenderer {

        private final FileSystemView fsv = FileSystemView.getFileSystemView();

        @Override
        public Component getTreeCellRendererComponent(final JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {

            Component nodeComponent = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row,
                    hasFocus);
            CheckableTreeNode node = (CheckableTreeNode) value;

            FileNodeWrapper userObject = (FileNodeWrapper) node.getUserObject();

            JPanel newPanel = new JPanel();

            JCheckBox checkbox = node.getCheckbox();
            checkbox.setSelected(node.isSelected());

            try {
                setIcon(fsv.getSystemIcon(userObject.file));
            } catch (Exception ignored) {
                // Ignored
            }

            newPanel.setBackground(nodeComponent.getBackground());
            checkbox.setBackground(nodeComponent.getBackground());

            GridBagLayout gbl = new GridBagLayout();
            FindUnlinkedFilesDialog.addComponent(gbl, newPanel, checkbox, null, null, null, 0, 0, 1, 1, 0, 0, 0, 0);
            FindUnlinkedFilesDialog.addComponent(gbl, newPanel, nodeComponent, GridBagConstraints.HORIZONTAL, null,
                    new Insets(1, 2, 0, 0), 1, 0, 1, 1, 1, 0, 0, 0);

            if (userObject.fileCount > 0) {
                JLabel label = new JLabel(
                        "(" + userObject.fileCount + " file" + (userObject.fileCount > 1 ? "s" : "") + ")");
                FindUnlinkedFilesDialog.addComponent(gbl, newPanel, label, null, null, new Insets(1, 2, 0, 0), 2, 0, 1,
                        1, 0, 0, 0, 0);
            }
            return newPanel;
        }

    }

    public static class FileNodeWrapper {

        public final File file;
        public final int fileCount;

        public FileNodeWrapper(File aFile) {
            this(aFile, 0);
        }

        /**
         * @param aDirectory
         * @param fileCount
         */
        public FileNodeWrapper(File aDirectory, int fileCount) {
            this.file = aDirectory;
            this.fileCount = fileCount;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.lang.Object#toString()
         */
        @Override
        public String toString() {
            return file.getName();
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
using Dufry.Comissoes.Data.Context;
using Dufry.Comissoes.Data.Context.Interfaces;
using Ninject.Modules;

namespace Dufry.Comissoes.CrossCutting.InversionOfControl.Modules
{
    public class InfrastructureNinjectModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IDbContext>().To<ComissoesContext>();
            Bind<IDbContext>().To<BIVendasContext>();
            Bind(typeof (IContextManager<>)).To(typeof (ContextManager<>));
            Bind(typeof(IUnitOfWork<>)).To((typeof(UnitOfWork<>)));
        }
    }
}


text:
FOUNDATION_EXPORT double CuckooGeneratorFrameworkVersionNumber;

//! Project version string for CuckooGeneratorFramework.
FOUNDATION_EXPORT const unsigned char CuckooGeneratorFrameworkVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <CuckooGeneratorFramework/PublicHeader.h>


text:
package com.khorn.terraincontrol.generator.biome.layers;

import com.khorn.terraincontrol.generator.biome.ArraysCache;

/**
 * Layer is the abstract base class for the entire layering system.
 * This system works on the principle that given an array of integers
 * representing a given space on a Minecraft map, that each column of
 * blocks is represented by a single array index/location. At each location
 * a sequence of operations is performed such that the end result is a
 * full description of what should be created upon generation with
 * respect to biome information.
 *

 * Each subclass will need to implement getInts() which is responsible
 * to acting upon the array of ints in it's own unique way. As previously
 * mentioned, each array index is associated with a column of blocks in
 * Minecraft. Each array index is acted upon using a bit masking system.
 *

 * The bit masking system works by marking locations with specific properties
 * or data such as: Land, Island, Ice, River, Biome, and BiomeGroup.
 * For example, the first part of the system starts by assigning MainLayer
 * to LayerEmpty. This layer simply initializes the array of ints with zeros.
 * Next MainLayer is assigned to LayerZoom which has the job of increasing
 * the resolution of the array of ints. Notice how each new layer assigned
 * to MainLayer passes the previous MainLayer into the constructor. Next we
 * see MainLayer assigned to LayerLand. LayerLand randomly marks indices with
 * a Land flag. This flag is then used by the next layers, LayerLandRandom
 * and LayerBiomeGroup, to act upon the map in land specific ways. This process
 * continues for @generationDepth times and is then finished with a set of
 * layers that clean up after the layer system and get it ready for generation
 *

 * It is important to note that getInts should, in most cases, call
 * this.child.getInts() which will follow the trail all the way back to the
 * initial `LayerEmpty` call and produce all modifications to the array as
 * it climbs back up the chain of getInts() calls.
 */
public abstract class Layer
{

    /**
     * The base seed set during layer construction, all other seeds are based
     * upon this one.
     */
    protected long baseSeed;

    /**
     * A general seed kept for use in world generation
     *

     * @see initWorldGenSeed
     */
    protected long worldGenSeed;

    /**
     * This seed is used for general random number generation within the Layers
     * system. It is based off of both the worldGenSeed and baseSeed.
     *

     * @see initWorldGenSeed
     * @see initChunkSeed
     */
    private long chunkSeed;

    /**
     * This seed is used for generating random numbers for biome groups
     *

     * @see initGroupSeed
     */
    private long groupSeed;

    /**
     * The layer to process before this one. getInts() should call
     * child.getInts() before doing any processing -- in most cases.
     */
    protected Layer child;

    /**
     * This helps our random numbers be a little more random
     */
    protected static final int entropy = 10000;

    /*
     * LayerIsland - chance to big land
     * LayerLandRandom - a(3) - chance to increase big land
     * GenLayerIcePlains - chance to ice
     * GenLayerMushroomIsland - chance to mushroom island
     *
     * biome:
     * 1) is island
     * 2) size
     * 3) chance
     * 4) is shore
     * 5) color
     * 6) temperature
     * 7) downfall
     * 8) is snow biome
     * 9) Have rivers
     *
     * world
     * 1) chance to lands
     * 2) size of big lands
     * 3) chance to increase lands
     * 4) Chance for ice area
     * 5) Ice area size
     * 6) Rivers
     * 7) Rivers size
     */
    // [ Biome Data ]
    protected static final int BiomeBits = 1023;            //>>	1st-10th Bits           // 255 63

    // [ Flags ]
    protected static final int LandBit = (1 << 10);         //>>	11th Bit, 1024          // 256 64
    protected static final int IslandBit = (1 << 11);       //>>	12th Bit, 2048          // 4096 1024
    protected static final int IceBit = (1 << 12);          //>>	13th Bit, 4096

    // [ Biome Group Data ]
    protected static final int BiomeGroupShift = 13;        //>>	Shift amount for biome group data
    protected static final int BiomeGroupBits = (127 << BiomeGroupShift);   //>>	14th-20th Bits, 1040384

    // [ River Data ]
    protected static final int RiverShift = 20;
    protected static final int RiverBits = (3 << RiverShift);               //>>	21st-22nd Bits, 3145728  //3072 768
    protected static final int RiverBitOne = (1 << RiverShift);             //>>	21st Bit, 1048576
    protected static final int RiverBitTwo = (1 << (RiverShift + 1));       //>>	22nd Bit, 2097152

    /**
     * In a single step, checks for land and when present returns biome data
     * @param selection The location to be checked
     * @return Biome Data or 0 when not on land
     */
    protected static int getBiomeFromLayer(int selection)
    {
        return (selection & LandBit) != 0 ? (selection & BiomeBits) : 0;
    }

    protected Layer(long seed)
    {
        this.baseSeed = seed;
        this.baseSeed *= (this.baseSeed * 6364136223846793005L + 1442695040888963407L);
        this.baseSeed += seed;
        this.baseSeed *= (this.baseSeed * 6364136223846793005L + 1442695040888963407L);
        this.baseSeed += seed;
        this.baseSeed *= (this.baseSeed * 6364136223846793005L + 1442695040888963407L);
        this.baseSeed += seed;
    }

    public Layer()
    {
    }

    public void initWorldGenSeed(long seed)
    {
        this.worldGenSeed = seed;
        if (this.child != null)
            this.child.initWorldGenSeed(seed);
        this.worldGenSeed *= (this.worldGenSeed * 6364136223846793005L + 1442695040888963407L);
        this.worldGenSeed += this.baseSeed;
        this.worldGenSeed *= (this.worldGenSeed * 6364136223846793005L + 1442695040888963407L);
        this.worldGenSeed += this.baseSeed;
        this.worldGenSeed *= (this.worldGenSeed * 6364136223846793005L + 1442695040888963407L);
        this.worldGenSeed += this.baseSeed;
    }

    protected void initChunkSeed(long x, long z)
    {
        this.chunkSeed = this.worldGenSeed;
        this.chunkSeed *= (this.chunkSeed * 6364136223846793005L + 1442695040888963407L);
        this.chunkSeed += x;
        this.chunkSeed *= (this.chunkSeed * 6364136223846793005L + 1442695040888963407L);
        this.chunkSeed += z;
        this.chunkSeed *= (this.chunkSeed * 6364136223846793005L + 1442695040888963407L);
        this.chunkSeed += x;
        this.chunkSeed *= (this.chunkSeed * 6364136223846793005L + 1442695040888963407L);
        this.chunkSeed += z;
    }

    protected void initGroupSeed(long x, long z)
    {
        this.groupSeed = this.chunkSeed;
        this.groupSeed *= (this.groupSeed * 6364136223846793005L + 1442695040888963407L);
        this.groupSeed += x;
        this.groupSeed *= (this.groupSeed * 6364136223846793005L + 1442695040888963407L);
        this.groupSeed += z;
        this.groupSeed *= (this.groupSeed * 6364136223846793005L + 1442695040888963407L);
        this.groupSeed += x;
        this.groupSeed *= (this.groupSeed * 6364136223846793005L + 1442695040888963407L);
        this.groupSeed += z;
    }

    protected int nextInt(int x)
    {
        int i = (int) ((this.chunkSeed >> 24) % x);
        if (i < 0)
            i += x;
        this.chunkSeed *= (this.chunkSeed * 6364136223846793005L + 1442695040888963407L);
        this.chunkSeed += this.worldGenSeed;
        return i;
    }

    protected int nextGroupInt(int x)
    {
        int i = (int) ((this.groupSeed >> 24) % x);
        if (i < 0)
            i += x;
        this.groupSeed *= (this.groupSeed * 6364136223846793005L + 1442695040888963407L);
        this.groupSeed += this.chunkSeed;
        return i;
    }

    public abstract int[] getInts(ArraysCache cache, int x, int z, int xSize, int zSize);

    protected int getRandomInArray(int... biomes)
    {
        return biomes[this.nextInt(biomes.length)];
    }

    protected int getRandomOf4(int a, int b, int c, int d)
    {
        return b == c && c == d
               ? b
               : (a == b && a == c
                  ? a
                  : (a == b && a == d
                     ? a
                     : (a == c && a == d
                        ? a
                        : (a == b && c != d
                           ? a
                           : (a == c && b != d
                              ? a
                              : (a == d && b != c
                                 ? a
                                 : (b == c && a != d
                                    ? b
                                    : (b == d && a != c
                                       ? b
                                       : (c == d && a != b
                                          ? c
                                          : this.getRandomInArray(new int[]
                                          {
                                              a, b, c, d
        }))))))))));
    }

}


text:
require "spec_helper"

describe ::Linr::Client do
  subject      { ::Linr::Client.new(config) }
  let(:config) do
    { port: port, logger: logger }
  end
  let(:logger) do
    ::Logger.new(output).tap { |l| l.level = Logger::DEBUG }
  end
  let(:output) { StringIO.new }
  let(:socket) { UDPSocket.new }
  let(:port)   { 44_001 }

  before do
    socket.bind("127.0.0.1", port)
  end

  after do
    socket.close
  end

  it "holds a config" do
    subject.config.logger.must_equal logger
  end

  it "writes a single series to socket" do
    subject.write(measurement: "m", fields: { a: 1.0 })
    socket.recvfrom(60).first.must_equal "m a=1.0"
  end

  it "writes multiple series to socket" do
    serie1 = { measurement: "m", fields: { a: 1.0 } }
    serie2 = { measurement: "n", fields: { b: true }, timestamp: 1_234_567 }
    subject.write(serie1, serie2)

    socket.recvfrom(80).first.must_equal "m a=1.0\nn b=true 1234567"
  end

  it "logs payloads" do
    subject.write(measurement: "m", fields: { a: 1.0 })
    lines = output.string.split("\n")
    lines.size.must_equal 2
    lines.shift.must_match(/Connected to 127\.0\.0\.1:44001/)
    lines.shift.must_match("m a=1")
  end
end


text:
<?php

/**
 * Library Library
 *
 * The Library library is designed to only allow one instance of any library
 * that extends it to exist per application or module.
 *
 * @category	Eventing
 * @package		Libraries
 * @subpackage	Library
 * @see			/index.php
 */

	namespace Eventing\Library;

	if(!defined('E_FRAMEWORK')) {
		headers_sent() || header('HTTP/1.1 404 Not Found', true, 404);
		exit('Direct script access is disallowed.');
	}

	/**
	 * Library Base Class
	 *
	 * This is the Eventing Framework implementation of the Singleton pattern,
	 * instances of classes can be returned with the getInstance() method, whilst
	 * new instances are forbidden.
	 */
	abstract class library {

		/**
		 * Constructor Function
		 *
		 * Every library class must have a constructor function that is defined
		 * using the protected access availability.
		 *
		 * @abstract
		 * @access protected
		 */
		abstract protected function __construct();

		/**
		 * Disallow Cloning
		 *
		 * No point using the singleton pattern if the object can be cloned into a
		 * new instance.
		 *
		 * @access public
		 * @return fatalerror
		 */
		final public function __clone() {
			trigger_error('Cannot clone framework library.', E_USER_ERROR);
		}

		/**
		 * Get Instance
		 *
		 * @final
		 * @static
		 * @access public
		 * @return object|false
		 */
		final public static function &getInstance() {
			static $objects = array();
			$class = get_called_class();
			if(isset($objects[$class]) && is_object($objects[$class])) {
				return $objects[$class];
			}
			if(!class_exists($class)) {
				return false;
			}
			$objects[$class] = isset($class::$_instance) && is_a($class::$_instance, $class)
				? $class::$_instance
				: new $class;
			return $objects[$class];
		}

	}


text:
/* Includes ------------------------------------------------------------------*/
#include <stdint.h>

#include "usbd_core.h"
#include "usbd_desc.h"
#include "usbd_req.h"
#include "usbd_conf.h"
#include "usb_regs.h"

/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
  * @{
  */

/** @defgroup USBD_DESC
  * @brief USBD descriptors module
  * @{
  */

/** @defgroup USBD_DESC_Private_TypesDefinitions
  * @{
  */
/**
  * @}
  */

/** @defgroup USBD_DESC_Private_Defines
  * @{
  */
//#undef WBF_IDS
#ifdef WBF_IDS
//#define USBD_VID						0x0483
//#define USBD_PID						0x5741
#define USBD_VID                        0x236E
#define USBD_PID                        0x0183

#define USBD_LANGID_STRING              0x409
#define USBD_MANUFACTURER_STRING        "IDEX ASA"

#define USBD_PRODUCT_HS_STRING          "idx-serial high-speed"
#define USBD_SERIALNUMBER_HS_STRING     "00000000050B"

#define USBD_PRODUCT_FS_STRING          "idx-serial full-speed"
#define USBD_SERIALNUMBER_FS_STRING     "00000000050C"

#define USBD_CONFIGURATION_FS_STRING    "idx-serial config"
#define USBD_INTERFACE_FS_STRING        "idx-serial interface"
#else

#define USBD_VID						0x0483
#define USBD_PID						0x5740

#define USBD_LANGID_STRING				0x409
#define USBD_MANUFACTURER_STRING		L"STMicroelectronics"

#define USBD_PRODUCT_HS_STRING          L"STM32 Virtual ComPort in HS mode"
#define USBD_SERIALNUMBER_HS_STRING     L"00000000050B"

#define USBD_PRODUCT_FS_STRING          L"STM32 Virtual ComPort in FS Mode"
#define USBD_SERIALNUMBER_FS_STRING     L"00000000050C"

#define USBD_CONFIGURATION_FS_STRING    L"VCP Config"
#define USBD_INTERFACE_FS_STRING        L"VCP Interface"

#endif

const USBD_DEVICE USR_desc =
{
  USBD_USR_DeviceDescriptor,
  USBD_USR_LangIDStrDescriptor,
  USBD_USR_ManufacturerStrDescriptor,
  USBD_USR_ProductStrDescriptor,
  USBD_USR_SerialStrDescriptor,
  USBD_USR_ConfigStrDescriptor,
  USBD_USR_InterfaceStrDescriptor,

};

#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED
  #if defined ( __ICCARM__ ) /*!< IAR Compiler */
    #pragma data_alignment=4
  #endif
#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */
/* USB Standard Device Descriptor */
const __ALIGN_BEGIN uint8_t USBD_DeviceDesc[USB_SIZ_DEVICE_DESC] __ALIGN_END =
  {
    0x12,                       /*bLength */
    USB_DEVICE_DESCRIPTOR_TYPE, /*bDescriptorType*/
    0x00,                       /*bcdUSB */
    0x02,
    0x02,                       /*bDeviceClass*/
    0x00,                       /*bDeviceSubClass*/
    0x00,                       /*bDeviceProtocol*/
    USB_OTG_MAX_EP0_SIZE,      /*bMaxPacketSize*/
    LOBYTE(USBD_VID),           /*idVendor*/
    HIBYTE(USBD_VID),           /*idVendor*/
    LOBYTE(USBD_PID),           /*idVendor*/
    HIBYTE(USBD_PID),           /*idVendor*/
    0x00,                       /*bcdDevice rel. 2.00*/
    0x02,
    USBD_IDX_MFC_STR,           /*Index of manufacturer  string*/
    USBD_IDX_PRODUCT_STR,       /*Index of product string*/
    USBD_IDX_SERIAL_STR,        /*Index of serial number string*/
    USBD_CFG_MAX_NUM            /*bNumConfigurations*/
  } ; /* USB_DeviceDescriptor */

#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED
  #if defined ( __ICCARM__ ) /*!< IAR Compiler */
    #pragma data_alignment=4
  #endif
#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */
/* USB Standard Device Descriptor */
__ALIGN_BEGIN uint8_t USBD_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =
{
  USB_LEN_DEV_QUALIFIER_DESC,
  USB_DESC_TYPE_DEVICE_QUALIFIER,
  0x00,
  0x02,
  0x00,
  0x00,
  0x00,
  0x40,
  0x01,
  0x00,
};

#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED
  #if defined ( __ICCARM__ ) /*!< IAR Compiler */
    #pragma data_alignment=4
  #endif
#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */
/* USB Standard Device Descriptor */
__ALIGN_BEGIN const uint8_t USBD_LangIDDesc[USB_SIZ_STRING_LANGID] __ALIGN_END =
{
     USB_SIZ_STRING_LANGID,
     USB_DESC_TYPE_STRING,
     LOBYTE(USBD_LANGID_STRING),
     HIBYTE(USBD_LANGID_STRING),
};

/**
* @brief  USBD_USR_DeviceDescriptor
*         return the device descriptor
* @param  speed : current device speed
* @param  length : pointer to data length variable
* @retval pointer to descriptor buffer
*/
uint8_t *  USBD_USR_DeviceDescriptor( uint8_t speed , uint16_t *length)
{
  *length = sizeof(USBD_DeviceDesc);
  return (uint8_t *)USBD_DeviceDesc;
}

/**
* @brief  USBD_USR_LangIDStrDescriptor
*         return the LangID string descriptor
* @param  speed : current device speed
* @param  length : pointer to data length variable
* @retval pointer to descriptor buffer
*/
uint8_t *  USBD_USR_LangIDStrDescriptor( uint8_t speed , uint16_t *length)
{
  *length =  sizeof(USBD_LangIDDesc);
  return (uint8_t *)USBD_LangIDDesc;
}

/**
* @brief  USBD_USR_ProductStrDescriptor
*         return the product string descriptor
* @param  speed : current device speed
* @param  length : pointer to data length variable
* @retval pointer to descriptor buffer
*/
uint8_t *  USBD_USR_ProductStrDescriptor( uint8_t speed , uint16_t *length)
{
	uint8_t *ret ;

	ret = (speed  == 0) ? (uint8_t *)USBD_PRODUCT_HS_STRING : (uint8_t *)USBD_PRODUCT_FS_STRING ;

	return ret ;
}

/**
* @brief  USBD_USR_ManufacturerStrDescriptor
*         return the manufacturer string descriptor
* @param  speed : current device speed
* @param  length : pointer to data length variable
* @retval pointer to descriptor buffer
*/
uint8_t *  USBD_USR_ManufacturerStrDescriptor( uint8_t speed , uint16_t *length)
{
	return (uint8_t *)USBD_MANUFACTURER_STRING ;

}

/**
* @brief  USBD_USR_SerialStrDescriptor
*         return the serial number string descriptor
* @param  speed : current device speed
* @param  length : pointer to data length variable
* @retval pointer to descriptor buffer
*/
uint8_t *  USBD_USR_SerialStrDescriptor( uint8_t speed , uint16_t *length)
{
	uint8_t *ret ;

	ret = (speed  == USB_OTG_SPEED_HIGH) ? (uint8_t *)USBD_SERIALNUMBER_HS_STRING : (uint8_t *)USBD_SERIALNUMBER_FS_STRING ;

	return ret ;
}

/**
* @brief  USBD_USR_ConfigStrDescriptor
*         return the configuration string descriptor
* @param  speed : current device speed
* @param  length : pointer to data length variable
* @retval pointer to descriptor buffer
*/
uint8_t *  USBD_USR_ConfigStrDescriptor( uint8_t speed , uint16_t *length)
{
	return (uint8_t *)USBD_CONFIGURATION_FS_STRING ;
}

/**
* @brief  USBD_USR_InterfaceStrDescriptor
*         return the interface string descriptor
* @param  speed : current device speed
* @param  length : pointer to data length variable
* @retval pointer to descriptor buffer
*/
uint8_t *  USBD_USR_InterfaceStrDescriptor( uint8_t speed , uint16_t *length)
{
	return (uint8_t *)USBD_INTERFACE_FS_STRING ;
}


text:
package de.pfabulist.kleinod.frex;

public class Single extends CharacterClass {
    Single( char direct ) {
        super( fromSingle( direct ) );
    }

    Single( int ch ) {
        super( fromSingleDigit( ch ));
    }

    private static String fromSingleDigit( int singleDigit ) {
        switch( singleDigit ) {
            case 0: return "0";
            case 1: return "1";
            case 2: return "2";
            case 3: return "3";
            case 4: return "4";
            case 5: return "5";
            case 6: return "6";
            case 7: return "7";
            case 8: return "8";
            case 9: return "9";
            default:
                throw new IllegalArgumentException( "single digit, i.e 0 <= x <= 9 expected not: " + singleDigit  );
        }
    }

    private static String fromSingle( char ch ) {
        switch( ch ) {
            case '\\':
            case '.':
            case '(':
            case ')':
            case ']':
            case '[':
            case '$':
            case '<':
            case '>':
            case '*':
            case '?':
            case '|':
            case '{':
            case '}':
            case '+':
            case '^':
            case '-':
            case ',':
            case ':':
            case '!':
            case '=':
                return "\\" + ch;
            default:
                return "" + ch;
        }
    }

    public CharacterClass through( Single to ) {
        return new CharacterClass( withoutBrackets + "-" + to.withoutBrackets );
    }

    public CharacterClass through( char to ) {
        return through( new Single( to ) );
    }

    public CharacterClass through( int to ) {
        return new CharacterClass( withoutBrackets + "-" + Frex.txt( to ).withoutBrackets );
    }

    @Override
    public Frex then( Frex next ) {
        return new Frex( withoutBrackets + ( next instanceof Single ? ( (Single) next ).withoutBrackets : next.pat ));
    }

}


text:
'use strict';

const partTypes = require('../../partTypes'),
      arrayUtilities = require('../../../utilities/array'),
      NonTerminalPart = require('../../part/nonTerminal');

const { allButFirstAndLast } = arrayUtilities,
      { GroupOfPartsPartType } = partTypes;

class GroupOfPartsPart extends NonTerminalPart {
  constructor(parts) {
    const type = GroupOfPartsPartType; ///

    super(type);

    this.parts = parts;
  }

  getParts() {
    return this.parts;
  }

  parse(configuration) {
    let nodes = [];

    const savedIndex = configuration.getSavedIndex(),
          parsed = this.parts.every(function(part) {
            const partNodeOrNodes = part.parse(configuration);

            if (partNodeOrNodes !== null) {
              nodes = nodes.concat(partNodeOrNodes);

              return true;
            }
          });

    if (!parsed) {
      configuration.backtrack(savedIndex);

      nodes = null;
    }

    return nodes;
  }

  asString() {
    const partsString = this.parts.reduce(function(partsString, part) {
            const partString = part.asString();

            if (partsString === null) {
              partsString = partString;
            } else {
              partsString = `${partsString} ${partString}`;
            }

            return partsString;
          }, null),
          string = `( ${partsString} )`;

    return string;
  }

  clone() { return super.clone(GroupOfPartsPart, this.parts); }

  static fromNodes(nodes) {
    const allButFirstAndLastNodes = allButFirstAndLast(nodes);

    nodes = allButFirstAndLastNodes;  ///

    const noWhitespace = false,
          lookAhead = false,
          parts = nodes.map(function(node) {
            const part = node.generatePart(noWhitespace, lookAhead);

            return part;
          }),
          groupOfPartsPart = new GroupOfPartsPart(parts);

    return groupOfPartsPart;
  }
}

module.exports = GroupOfPartsPart;


text: export { default as TileViewButton } from './TileViewButton';


text:
package object

import (
	"bytes"
	"fmt"
	"hash/fnv"
	"strconv"
	"strings"

	"github.com/skatsuta/monkey-interpreter/ast"
)

// Type is a type of objects.
type Type string

const (
	// IntegerType represents a type of integers.
	IntegerType Type = "Integer"
	// FloatType represents a type of floating point numbers.
	FloatType = "Float"
	// BooleanType represents a type of booleans.
	BooleanType = "Boolean"
	// NilType represents a type of nil.
	NilType = "Nil"
	// ReturnValueType represents a type of return values.
	ReturnValueType = "ReturnValue"
	// ErrorType represents a type of errors.
	ErrorType = "Error"
	// FunctionType represents a type of functions.
	FunctionType = "Function"
	// StringType represents a type of strings.
	StringType = "String"
	// BuiltinType represents a type of builtin functions.
	BuiltinType = "Builtin"
	// ArrayType represents a type of arrays.
	ArrayType = "Array"
	// HashType represents a type of hashes.
	HashType = "Hash"
	// QuoteType represents a type of quotes used for macros.
	QuoteType = "Quote"
	// MacroType represents a type of macros.
	MacroType = "Macro"
)

// Object represents an object of Monkey language.
type Object interface {
	Type() Type
	Inspect() string
}

// HashKey represents a key of a hash.
type HashKey struct {
	Type  Type
	Value uint64
}

// Hashable is the interface that is able to become a hash key.
type Hashable interface {
	HashKey() HashKey
}

// Integer represents an integer.
type Integer struct {
	Value int64
}

// Type returns the type of the Integer.
func (i *Integer) Type() Type {
	return IntegerType
}

// Inspect returns a string representation of the Integer.
func (i *Integer) Inspect() string {
	return strconv.FormatInt(i.Value, 10)
}

// HashKey returns a hash key object for i.
func (i *Integer) HashKey() HashKey {
	return HashKey{
		Type:  i.Type(),
		Value: uint64(i.Value),
	}
}

// Float represents an integer.
type Float struct {
	Value float64
}

// Type returns the type of f.
func (f *Float) Type() Type {
	return FloatType
}

// Inspect returns a string representation of f.
func (f *Float) Inspect() string {
	return strconv.FormatFloat(f.Value, 'f', -1, 64)
}

// HashKey returns a hash key object for f.
func (f *Float) HashKey() HashKey {
	s := strconv.FormatFloat(f.Value, 'f', -1, 64)
	h := fnv.New64a()
	h.Write([]byte(s))

	return HashKey{
		Type:  f.Type(),
		Value: h.Sum64(),
	}
}

// Boolean represents a boolean.
type Boolean struct {
	Value bool
}

// Type returns the type of the Boolean.
func (b *Boolean) Type() Type {
	return BooleanType
}

// Inspect returns a string representation of the Boolean.
func (b *Boolean) Inspect() string {
	return strconv.FormatBool(b.Value)
}

// HashKey returns a hash key object for b.
func (b *Boolean) HashKey() HashKey {
	key := HashKey{Type: b.Type()}
	if b.Value {
		key.Value = 1
	}
	return key
}

// Nil represents the absence of any value.
type Nil struct{}

// Type returns the type of the Nil.
func (n *Nil) Type() Type {
	return NilType
}

// Inspect returns a string representation of the Nil.
func (n *Nil) Inspect() string {
	return "nil"
}

// ReturnValue represents a return value.
type ReturnValue struct {
	Value Object
}

// Type returns the type of the ReturnValue.
func (rv *ReturnValue) Type() Type {
	return ReturnValueType
}

// Inspect returns a string representation of the ReturnValue.
func (rv *ReturnValue) Inspect() string {
	return rv.Value.Inspect()
}

// Error represents an error.
type Error struct {
	Message string
}

// Type returns the type of the Error.
func (e *Error) Type() Type {
	return ErrorType
}

// Inspect returns a string representation of the Error.
func (e *Error) Inspect() string {
	return "Error: " + e.Message
}

// Function represents a function.
type Function struct {
	Parameters []*ast.Ident
	Body       *ast.BlockStatement
	Env        Environment
}

// Type returns the type of the Function.
func (f *Function) Type() Type {
	return FunctionType
}

// Inspect returns a string representation of the Function.
func (f *Function) Inspect() string {
	var out bytes.Buffer

	params := make([]string, 0, len(f.Parameters))
	for _, p := range f.Parameters {
		params = append(params, p.String())
	}

	out.WriteString("fn(")
	out.WriteString(strings.Join(params, ", "))
	out.WriteString(") {\n")
	out.WriteString(f.Body.String())
	out.WriteString("\n}")

	return out.String()
}

// String represents a string.
type String struct {
	Value string
}

// Type returns the type of the String.
func (s *String) Type() Type {
	return StringType
}

// Inspect returns a string representation of the String.
func (s *String) Inspect() string {
	return s.Value
}

// HashKey returns a hash key object for s.
func (s *String) HashKey() HashKey {
	h := fnv.New64a()
	h.Write([]byte(s.Value))

	return HashKey{
		Type:  s.Type(),
		Value: h.Sum64(),
	}
}

// BuiltinFunction represents a function signature of builtin functions.
type BuiltinFunction func(args ...Object) Object

// Builtin represents a builtin function.
type Builtin struct {
	Fn BuiltinFunction
}

// Type returns the type of the Builtin.
func (b *Builtin) Type() Type {
	return BuiltinType
}

// Inspect returns a string representation of the Builtin.
func (b *Builtin) Inspect() string {
	return "builtin function"
}

// Array represents an array.
type Array struct {
	Elements []Object
}

// Type returns the type of the Array.
func (*Array) Type() Type {
	return ArrayType
}

// Inspect returns a string representation of the Array.
func (a *Array) Inspect() string {
	if a == nil {
		return ""
	}

	elements := make([]string, 0, len(a.Elements))
	for _, e := range a.Elements {
		elements = append(elements, e.Inspect())
	}

	var out bytes.Buffer
	out.WriteString("[")
	out.WriteString(strings.Join(elements, ", "))
	out.WriteString("]")
	return out.String()
}

// HashPair represents a key-value pair in a hash.
type HashPair struct {
	Key   Object
	Value Object
}

// Hash represents a hash.
type Hash struct {
	Pairs map[HashKey]HashPair
}

// Type returns the type of the Hash.
func (*Hash) Type() Type {
	return HashType
}

// Inspect returns a string representation of the Hash.
func (h *Hash) Inspect() string {
	if h == nil {
		return ""
	}

	pairs := make([]string, 0, len(h.Pairs))
	for _, pair := range h.Pairs {
		pairs = append(pairs, pair.Key.Inspect()+": "+pair.Value.Inspect())
	}

	var out bytes.Buffer
	out.WriteString("{")
	out.WriteString(strings.Join(pairs, ", "))
	out.WriteString("}")
	return out.String()
}

// Quote represents a quote, i.e. an unevaluated expression.
type Quote struct {
	ast.Node
}

// Type returns the type of `q`.
func (q *Quote) Type() Type {
	return QuoteType
}

// Inspect returns a string representation of `q`.
func (q *Quote) Inspect() string {
	return fmt.Sprintf("%s(%s)", QuoteType, q.Node.String())
}

// Macro represents a macro.
type Macro struct {
	Parameters []*ast.Ident
	Body       *ast.BlockStatement
	Env        Environment
}

// Type returns the type of `m`.
func (m *Macro) Type() Type {
	return MacroType
}

// Inspect returns a string representation of `m`.
func (m *Macro) Inspect() string {
	var out bytes.Buffer

	params := make([]string, 0, len(m.Parameters))
	for _, p := range m.Parameters {
		params = append(params, p.String())
	}

	out.WriteString("macro(")
	out.WriteString(strings.Join(params, ", "))
	out.WriteString(") {\n")
	out.WriteString(m.Body.String())
	out.WriteString("\n}")

	return out.String()
}


text:
package org.basinmc.maven.plugins.minecraft.patch;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Provides a Mojo capable of re-generating patches based on the unmodified module code base.
 *
 * @author Johannes Donath
 */
@Mojo(
        name = "generate-patches",
        requiresProject = false,
        threadSafe = true,
        defaultPhase = LifecyclePhase.GENERATE_RESOURCES
)
public class GeneratePatchesMojo extends AbstractGitCommandMojo {

    /**
     * {@inheritDoc}
     */
    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        super.execute();

        this.getLog().info("Purging previous patch files");

        try {
            Files.walk(this.getPatchDirectory().toPath())
                    .filter((p) -> p.getFileName().toString().endsWith(".patch"))
                    .forEach((p) -> {
                        try {
                            Files.delete(p);
                        } catch (IOException ex) {
                            throw new WrappedException(ex);
                        }
                    });
        } catch (IOException ex) {
            throw new MojoFailureException("Failed to access patch directory: " + ex.getMessage(), ex);
        } catch (WrappedException ex) {
            if (ex.getCause() instanceof IOException) {
                throw new MojoFailureException("Failed to delete patch file: " + ex.getMessage(), ex);
            }

            throw new MojoFailureException("Caught unexpected exception: " + ex.getMessage(), ex);
        }

        try {
            Repository repository = new FileRepositoryBuilder()
                    .setWorkTree(this.getSourceDirectory())
                    .setMustExist(true)
                    .build();

            Git git = new Git(repository);

            if (!git.status().call().isClean()) {
                this.getLog().warn("One or more uncommited changes present within source directory\n");
                this.getLog().warn("Only commited changes will be considered in patch generation");
            }
        } catch (GitAPIException ex) {
            throw new MojoFailureException("Failed to invoke git: " + ex.getMessage(), ex);
        } catch (IOException ex) {
            throw new MojoFailureException("Could not access module repository: " + ex.getMessage(), ex);
        }

        Path workingDirectory = this.getSourceDirectory().toPath().toAbsolutePath();
        Path relativePatchDirectory = workingDirectory.relativize(this.getPatchDirectory().toPath());

        try {
            if (this.execute(new ProcessBuilder().command("git", "format-patch", "--minimal", "--no-stat", "-N", "-o", relativePatchDirectory.toString(), "upstream").directory(this.getSourceDirectory().getAbsoluteFile())) != 0) {
                throw new MojoFailureException("Git reported an unexpected error");
            }
        } catch (InterruptedException ex) {
            throw new MojoFailureException("Interrupted while awaiting git result: " + ex.getMessage(), ex);
        } catch (IOException ex) {
            throw new MojoFailureException("Failed to invoke git: " + ex.getMessage(), ex);
        }
    }

    private static class WrappedException extends RuntimeException {
        public WrappedException(Throwable throwable) {
            super(throwable);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/arrow_button_small_pressed" /> <!-- pressed -->
     <item android:drawable="@drawable/arrow_button_small_normal" /> <!-- default -->
 </selector>


text:
from-plain-text
===============

Markdown... no, not anymore
---------------------------

In one s-expression:

	> (html<-text-string
		(mkstr "Header 1"
			   #\Newline
			   "========"
			   #\Newline
			   #\Newline
			   "Header 2"
			   #\Newline
			   "--------"
			   #\Newline
			   "One small paragraph here."
			   #\Newline
			   #\Newline
			   "Another small paragraph there."))

	((:h1 (:noescape "Header 1"))
	 (:h2 (:noescape "Header 2"))
	 (:p (:noescape "One small paragraph here."))
	 (:p (:noescape "Another small paragraph there.")))

And that's all there is. Of course, you do not use it like that. The text would be written verbatim as:

	Header 1
	========

	Header 2
	--------
	One small paragraph here.

	Another small paragraph there.

Nice typography on characters
-----------------------------

Some characters make texts nicer to read but they are quite a pain to use in pure HTML. The action html<-text-string insert them without mandating to memorize tedious things like ’ or –. And in the very spirit of Markdown, you do not fill your text with such lengthy and inelegant tokens.

Here are the character or sequence of characters that are special:

'
A single quote will yield a proper opening simple quote. If a word is written in quotes, the second will be replaced by a closing simple quote.

"
Same thing here as with single quotes.

\-
A hyphen will be replaced by a non-breaking hyphen.

\-\-
Two hyphens will be replaced by a small dash, as needed when writing ranges like from page 330 to page 339 that you may want to shorten to 330--39.

\-\-\-
Three hyphens will be replaced by a long dash, as needed to break visually a sentence with a remark.

...
Three dots in a row will be replaced by an ellipsis.

(
An opening parenthesis will trigger HTML insertion. You do not write classical, verbose HTML but Lisp-like HTML as in:

	(:p :class "title" "Here's a list of things")

How to escape
-------------

The escape character is the colon :. So if you really want a single quote or two hyphens or an opening parenthesis, you would write:

:'
:\-:\-
:(

Note that since the colon character is never used at the beginning of a word, you can just type a colon character when you actually need one (contrary to the backslash character commonly used in programming languages that you need to write twice to get one).

Special symbols and characters
------------------------------

You write special HTML characters as :char rather than writing them with the syntax &char;. It is visually less invasive and trigger on reading the same reaction as with escaping: "ah! There's something special here."

Here they are:

*:para*
The symbol for a paragraph. A non-breaking space is always included after it.

*:sect*
The symbol for a section. A non-breaking space is always included after it.

*:trade*
The trademark symbol.

*:reg*
The registered symbol.

*:copy*
The copyright symbol. A non-breaking space is always included after it.

*:nbsp*
Insert a non-breaking space manually.

*:br*
Insert a hard line break manually.


text:
package at.irian.ankor.switching.connector.local;

import at.irian.ankor.session.ModelSession;
import at.irian.ankor.switching.routing.ModelAddress;

import java.io.Serializable;

/**
 * @author Manfred Geiler
 */
public class StatefulSessionModelAddress implements ModelAddress, Serializable {
    //private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(StatefulSessionModelAddress.class);

    private final String modelSessionId;
    private final String modelName;
    private final int hashCode;
    private final String consistentHashKey;

    public StatefulSessionModelAddress(ModelSession modelSession, String modelName) {
        this(modelSession.getId(), modelName);
    }

    public StatefulSessionModelAddress(String modelSessionId, String modelName) {
        this.modelSessionId = modelSessionId;
        this.modelName = modelName;
        this.hashCode = 31 * modelSessionId.hashCode() + modelName.hashCode();
        this.consistentHashKey = modelSessionId + modelName;
    }

    public String getModelSessionId() {
        return modelSessionId;
    }

    @Override
    public String getModelName() {
        return modelName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        StatefulSessionModelAddress that = (StatefulSessionModelAddress) o;

        return modelName.equals(that.modelName) && modelSessionId.equals(that.modelSessionId);
    }

    @Override
    public int hashCode() {
        return hashCode;
    }

    @Override
    public String consistentHashKey() {
        return consistentHashKey;
    }

    @Override
    public String toString() {
        return "StatefulSessionModelAddress{" +
               "modelSessionId='" + modelSessionId + '\'' +
               ", modelName='" + modelName + '\'' +
               '}';
    }

}


text:
package monitor

import (
	"context"

	"github.com/google/gapid/test/robot/job/worker"
	"github.com/google/gapid/test/robot/report"
)

// Report is the in memory representation/wrapper for a report.Action
type Report struct {
	report.Action
}

// Reports is the type that manages a set of Report objects.
type Reports struct {
	entries []*Report
}

// All returns the complete set of Report objects we have seen so far.
func (r *Reports) All() []*Report {
	return r.entries
}

func (o *DataOwner) updateReport(ctx context.Context, action *report.Action) error {
	o.Write(func(data *Data) {
		entry, _ := data.Reports.FindOrCreate(ctx, action)
		entry.Action = *action
	})
	return nil
}

// Find searches the reports for the one that matches the supplied action.
// See worker.EquivalentAction for more information about how actions are compared.
func (r *Reports) Find(ctx context.Context, action *report.Action) *Report {
	for _, entry := range r.entries {
		if worker.EquivalentAction(&entry.Action, action) {
			return entry
		}
	}
	return nil
}

// FindOrCreate returns the report that matches the supplied aciton if it exists, if not
// it creates a new report object, and returns it.
// It does not register the newly created report object for you, that will happen only if
// a call is made to trigger the action on the report service.
func (r *Reports) FindOrCreate(ctx context.Context, action *report.Action) (*Report, bool) {
	entry := r.Find(ctx, action)
	if entry != nil {
		return entry, true
	}
	entry = &Report{Action: *action}
	r.entries = append(r.entries, entry)
	return entry, false
}