text:
#include <QActionGroup>
#include <QApplication>
#include <QColorDialog>
#include <QComboBox>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QFileInfo>
#include <QIcon>
#include <QKeySequence>
#include <QLabel>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QPrinter>
#include <QSettings>
#include <QSizeF>
#include <QStatusBar>
#include <QStringList>
#include <QToolBar>
#include "cognat.h"
#include "colorarchitecturesdialog.h"
#include "database.h"
#include "loadcolorschemedialog.h"
#include "mainwidget.h"
#include "searchgenesdialog.h"
#include "setradiusdialog.h"
//#include "setresolutiondialog.h"
#include "setvaluesdialog.h"
#include "specifydatabasedialog.h"

COGNAT::COGNAT()
{
    readSettings();
    createActions();
    createMenus();
    createToolBars();
    statusBar();
    setGeometry();
    setFocus();
    setFocusPolicy(Qt::StrongFocus);

    database = new Database(databasePath, MaxNeighborhoodRadius, this);
    mainWidget = NULL;

    //setWindowIcon(QIcon(":/images/icon.png"));
    //setCurrentFile("");
}

void COGNAT::createContextMenu(const QPoint &point)
{
    QMenu contextMenu(this);
    contextMenu.addAction(colorAction);
    contextMenu.addAction(decolorAction);
    contextMenu.exec(point);
}

void COGNAT::createColorDialog(const QString &architecture, const QColor &initial)
{
    QColor color = QColorDialog::getColor(initial, this, tr("Set Color"), QColorDialog::DontUseNativeDialog);
    if (color.isValid()) {
        writeColorToSettings(architecture, color);
        setColorGenesGroup(colorGenesComboBox->currentIndex());
    }
}

void COGNAT::closeEvent(QCloseEvent *event)
{
    if (okToContinue()) {
        writeSettings();
        event->accept();
    } else {
        event->ignore();
    }
}

/*void COGNAT::newFile()
{
    if (okToContinue()) {
        spreadsheet->clear();
        setCurrentFile("");
    }
}

void COGNAT::open()
{
    if (okToContinue()) {
        QString fileName = QFileDialog::getOpenFileName(this,
                                   tr("Open Spreadsheet"), ".",
                                   tr("Spreadsheet files (*.sp)"));
        if (!fileName.isEmpty())
            loadFile(fileName);
    }
}

bool COGNAT::save()
{
    if (curFile.isEmpty()) {
        return saveAs();
    } else {
        return saveFile(curFile);
    }
}

void COGNAT::openRecentFile()
{
    if (okToContinue()) {
        QAction *action = qobject_cast<QAction *>(sender());
        if (action)
            loadFile(action->data().toString());
    }
}

void COGNAT::updateStatusBar()
{
    locationLabel->setText(spreadsheet->currentLocation());
    formulaLabel->setText(spreadsheet->currentFormula());
}

void COGNAT::spreadsheetModified()
{
    setWindowModified(true);
    updateStatusBar();
}*/

void COGNAT::load() // 1.1
{
    if (okToContinue()) {
        if (database->isValid()) {
            if (loadPath.isEmpty()) {
                loadPath = QDir::homePath();
            }
            QString fileName = QFileDialog::getOpenFileName(this, tr("Load"), loadPath, tr("Text files (*.txt);;All files (*.*)"));
            fileName = QFileInfo(fileName).canonicalFilePath();
            if (!fileName.isEmpty()) {
                loadPath = QFileInfo(fileName).canonicalPath();
                QString extension = QFileInfo(fileName).suffix().toLower();
                if (extension == "ols") {
                    loadProject(fileName);
                } else {
                    loadTextFile(fileName);
                }
            }
        } else {
            /*QMessageBox::warning(this, tr("Warning"),
                                 tr("Could not load a text file or a project.\n\n"
                                    "Please, specify a path to a database\n"
                                    "using the Database menu."));*/
            QMessageBox::warning(this, tr("Warning"),
                                 tr("Could not load a text file.\n\n"
                                    "Please, specify a path to a database\n"
                                    "using the Database menu."));
        }
    }
}

void COGNAT::save() // 1.2 ###
{
    // TEMPORARY CODE !!!
    if (database->textFileWasLoaded()) {
        if (savePath.isEmpty()) {
            savePath = QDir::homePath();
        }
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save"), savePath, tr("PDF (*.pdf);;All files (*.*)"));
        if (!fileName.isEmpty()) {
            QString extension = QFileInfo(fileName).suffix().toLower();
            if (extension == "pdf") {
                savePdf(fileName);
            } else if (extension == "ols") {
                saveProject(fileName);
            }
        }
    }
    // TEMPORARY CODE !!!
}

void COGNAT::saveAs() // 1.3
{
    /*if (database->textFileWasLoaded()) {
        if (savePath.isEmpty()) {
            savePath = QDir::homePath();
        }
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save"), savePath, tr("PDF (*.pdf);;Text files (*.txt)"));
        if (!fileName.isEmpty()) {
            QString extension = QFileInfo(fileName).suffix().toLower();
            if (extension == "pdf") {
                savePdf(fileName);
            } else if (extension == "txt") {
                //saveTextFile(fileName);
            }
        }
    }*/
}

void COGNAT::loadRecentProject() {} // 1.4

void COGNAT::searchGenes() // 2.1 ###
{
    if (okToContinue()) {
        if (database->isValid()) {
            SearchGenesDialog dialog(this);
            if (dialog.exec()) {
                proteinDomain = dialog.specifiedDomain();
                if (database->textFileWasWritten(proteinDomain, minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, "./tmp.txt")) {
                    loadSearchedGenes("./tmp.txt");
                    QFile::remove("./tmp.txt");
                } else {
                    QMessageBox::warning(this, tr("Warning"),
                                         tr("%1.")
                                         .arg(database->errorString()));
                }
            }
        } else {
            QMessageBox::warning(this, tr("Warning"),
                                 tr("Could not search genes.\n\n"
                                    "Please, specify a path to a database\n"
                                    "using the Database menu."));
        }
    }
}

void COGNAT::specifyDatabase() // 2.2
{
    if (!database->exists()) {
        database->setPath(QString());
    }
    SpecifyDatabaseDialog dialog(database->canonicalPath(), this);
    if (dialog.exec()) {
        databasePath = dialog.specifiedPath();
        database->setPath(databasePath);
        statusBar()->showMessage(tr("A database '%1' was specified")
                                 .arg(database->canonicalPath()));
    }
}

void COGNAT::sortGenomesByTaxonomy(bool checked) // 3.1 ###
{
    if (database->textFileWasLoaded()) {
        if (checked) {
            mainWidget->setTreeTopWidget();
            statusBar()->showMessage(tr("Genomes were sorted by taxonomy"));
        } else {
            switch (inputType) {
            case Default:
                mainWidget->setTableTopWidget();
                statusBar()->showMessage(tr("Genomes were sorted by default"));
                break;
            case Search:
                mainWidget->setTableTopWidget();
                statusBar()->showMessage(tr("Genomes were sorted by a bit score"));
                break;
            case Phylogeny:
                mainWidget->setTextTopWidget();
                statusBar()->showMessage(tr("Genomes were sorted by a phylogenetic tree"));
                break;
            default:
                QMessageBox::warning(this, tr("Warning"),
                                     tr("Something bad happened.\n\n"
                                        "Please, reload a text file or a project."));
                break;
            }
        }
        mainWidget->setNeighborhoodRadius();
        showIntergenes(showIntergenesAction->isChecked());
        setColorGenesGroup(colorGenesComboBox->currentIndex());
        markGenesOfMembraneProteins(markGenesOfMembraneProteinsAction->isChecked());
    }
}

void COGNAT::markGenesOfMembraneProteins(bool checked) // 3.2 ###
{
    if (database->textFileWasLoaded()) {
        if (checked) {
            if (!database->annotationWasLoaded(Database::Membrane)) {
                if (!database->loadAnnotation(Database::Membrane)) {
                    QMessageBox::warning(this, tr("Warning"),
                                         tr("Could not load a membrane annotation.\n\n%1.")
                                         .arg(database->errorString()));
                } else {
                    mainWidget->markGenesOfMembraneProteins(true);
                    statusBar()->showMessage(tr("Genes of presumably membrane proteins were marked with hatching"));
                }
            } else {
                mainWidget->markGenesOfMembraneProteins(true);
                statusBar()->showMessage(tr("Genes of presumably membrane proteins were marked with hatching"));
            }
        } else if (database->annotationWasLoaded(Database::Membrane)) {
            mainWidget->markGenesOfMembraneProteins(false);
            statusBar()->showMessage(tr("Genes of presumably membrane proteins are not marked"));
        }
        setFocus();
    }
}

void COGNAT::examineOrthologsAndParalogs(bool checked) // 3.3
{
    if (database->textFileWasLoaded()) { // ??? Necessary?
        if (checked) {
            statusBar()->showMessage(tr("An examination of orthologs and paralogs was turned ON"));
        } else {
            statusBar()->showMessage(tr("An examination of orthologs and paralogs was turned OFF"));
        }
    }
}

void COGNAT::showIntergenes(bool checked) // 3.4 ###
{
    if (database->textFileWasLoaded()) {
        mainWidget->showIntergenes(checked);
        if (checked) {
            statusBar()->showMessage(tr("Intergenic spaces were shown as lines"));
        } else {
            statusBar()->showMessage(tr("Intergenic spaces are not shown"));
        }
        setFocus();
    }
}

void COGNAT::colorByDomainArchitectures() // 3.5.1
{
    if (database->textFileWasLoaded()) {
        if (!database->annotationWasLoaded(Database::Domains)) {
            if (!database->loadAnnotation(Database::Domains)) {
                QMessageBox::warning(this, tr("Warning"),
                                     tr("Could not load a domain annotation.\n\n%1.")
                                     .arg(database->errorString()));
            } else {
                database->updateAnchors(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, Database::Domains);
                mainWidget->deleteAnnotation();
                mainWidget->colorByDomainArchitectures();
                statusBar()->showMessage(tr("Genes were colored by protein domain architectures"));
            }
        } else {
            database->updateAnchors(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, Database::Domains);
            mainWidget->deleteAnnotation();
            mainWidget->colorByDomainArchitectures();
            statusBar()->showMessage(tr("Genes were colored by protein domain architectures"));
        }
        setFocus();
    }
}

void COGNAT::colorByCOGArchitectures() // 3.5.2
{
    if (database->textFileWasLoaded()) {
        if (!database->annotationWasLoaded(Database::COGs)) {
            if (!database->loadAnnotation(Database::COGs)) {
                QMessageBox::warning(this, tr("Warning"),
                                     tr("Could not load a COG annotation.\n\n%1.")
                                     .arg(database->errorString()));
            } else {
                database->updateAnchors(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, Database::COGs);
                mainWidget->deleteAnnotation();
                mainWidget->colorByCOGArchitectures();
                statusBar()->showMessage(tr("Genes were colored by protein COG architectures"));
            }
        } else {
            database->updateAnchors(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, Database::COGs);
            mainWidget->deleteAnnotation();
            mainWidget->colorByCOGArchitectures();
            statusBar()->showMessage(tr("Genes were colored by protein COG architectures"));
        }
        setFocus();
    }
}

void COGNAT::colorByDomains() // 3.5.3
{
    if (database->textFileWasLoaded()) {
        if (!database->annotationWasLoaded(Database::Domains)) {
            if (!database->loadAnnotation(Database::Domains)) {
                QMessageBox::warning(this, tr("Warning"),
                                     tr("Could not load a domain annotation.\n\n%1.")
                                     .arg(database->errorString()));
            } else {
                database->updateAnchors(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, Database::Domains);
                mainWidget->deleteAnnotation();
                mainWidget->colorByDomains();
                markGenesOfMembraneProteins(markGenesOfMembraneProteinsAction->isChecked());
                statusBar()->showMessage(tr("Genes were colored by protein domains"));
            }
        } else {
            database->updateAnchors(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, Database::Domains);
            mainWidget->deleteAnnotation();
            mainWidget->colorByDomains();
            markGenesOfMembraneProteins(markGenesOfMembraneProteinsAction->isChecked());
            statusBar()->showMessage(tr("Genes were colored by protein domains"));
        }
        setFocus();
    }
}

void COGNAT::colorByCOGs() // 3.5.4
{
    if (database->textFileWasLoaded()) {
        if (!database->annotationWasLoaded(Database::COGs)) {
            if (!database->loadAnnotation(Database::COGs)) {
                QMessageBox::warning(this, tr("Warning"),
                                     tr("Could not load a COG annotation.\n\n%1.")
                                     .arg(database->errorString()));
            } else {
                database->updateAnchors(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, Database::COGs);
                mainWidget->deleteAnnotation();
                mainWidget->colorByCOGs();
                markGenesOfMembraneProteins(markGenesOfMembraneProteinsAction->isChecked());
                statusBar()->showMessage(tr("Genes were colored by protein COGs"));
            }
        } else {
            database->updateAnchors(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, Database::COGs);
            mainWidget->deleteAnnotation();
            mainWidget->colorByCOGs();
            markGenesOfMembraneProteins(markGenesOfMembraneProteinsAction->isChecked());
            statusBar()->showMessage(tr("Genes were colored by protein COGs"));
        }
        setFocus();
    }
}

void COGNAT::loadColorScheme() // 3.6
{
    LoadColorSchemeDialog dialog(this);
    if (dialog.exec()) {
        bool loaded = false;
        QString colorScheme = dialog.loadedScheme();
        QStringList list = colorScheme.split("\n");
        foreach (const QString &line, list) {
            QString architecture = line.section("\t", 0, 0).trimmed();
            QString name = line.section("\t", 1, 1).trimmed();
            QColor color(name);
            if (!architecture.isEmpty() && color.isValid()) {
                writeColorToSettings(architecture, color);
                loaded = true;
            } else {
                architecture = line.section("\t", 1, 1).trimmed();
                name = line.section("\t", 0, 0).trimmed();
                color = QColor(name);
                if (!architecture.isEmpty() && color.isValid()) {
                    writeColorToSettings(architecture, color);
                    loaded = true;
                }
            }
        }
        if (database->textFileWasLoaded()) {
            setColorGenesGroup(colorGenesComboBox->currentIndex());
        }
        if (loaded) {
            statusBar()->showMessage(tr("A color scheme was loaded"));
        } else {
            QMessageBox::warning(this, tr("Warning"),
                                 tr("Could not load a color scheme."));
        }
    }
}

void COGNAT::colorArchitectures() // 3.7
{
    ColorArchitecturesDialog dialog(this);
    if (dialog.exec()) {
        QString proteinArchitectures = dialog.loadedArchitectures();
        if (database->textFileWasLoaded()) {
            database->loadArchitectures(proteinArchitectures);
            setColorGenesGroup(colorGenesComboBox->currentIndex());
            statusBar()->showMessage(tr("Loaded protein architectures were colored"));
        } else {
            QMessageBox::warning(this, tr("Warning"),
                                 tr("Could not load protein architectures.\n\n"
                                    "There is nothing to color."));
        }
    }
}

/*void COGNAT::setPdfResolution() //
{
    SetResolutionDialog dialog(pdfWidth, pdfHeight, this);
    if (dialog.exec()) {
        pdfWidth = dialog.tunedWidth();
        pdfHeight = dialog.tunedHeight();
        statusBar()->showMessage(tr("Tuned resolution was saved"));
    }
}*/

void COGNAT::setNeighborhoodRadius() // 3.8
{
    setFocus();
    SetRadiusDialog dialog(neighborhoodRadius, MaxNeighborhoodRadius, this);
    if (dialog.exec()) {
        neighborhoodRadius = dialog.tunedRadius();
        neighborhoodRadiusComboBox->setCurrentIndex(neighborhoodRadius - 1);
        if (database->textFileWasLoaded()) {
            mainWidget->setRadius(neighborhoodRadius);
            mainWidget->setNeighborhoodRadius();
        }
        statusBar()->showMessage(tr("A number of genes in a neighborhood was tuned to %1 genes")
                                 .arg(neighborhoodRadius * 2 + 1));
    }
}

void COGNAT::setValues() // 3.9
{
    SetValuesDialog dialog(minimumBitScore, minimumRelativeLength, maximumOverlapping, trustworthyBitScore, this);
    if (dialog.exec()) {
        minimumBitScore = dialog.tunedMinimumScore();
        minimumRelativeLength = dialog.tunedMinimumLength();
        maximumOverlapping = dialog.tunedMaximumOverlapping();
        trustworthyBitScore = dialog.tunedTrustworthyScore();
        if (database->textFileWasLoaded()) {
            mainWidget->setMinimumScore(minimumBitScore);
            mainWidget->setMinimumLength(minimumRelativeLength);
            mainWidget->setMaximumOverlapping(maximumOverlapping);
            mainWidget->setTrustworthyScore(trustworthyBitScore);
            mainWidget->deleteAnnotation();
            setColorGenesGroup(colorGenesComboBox->currentIndex());
        }
        statusBar()->showMessage(tr("Tuned values were saved"));
    }
}

void COGNAT::reconstructTree() {} // 4.1

void COGNAT::setPhylumColor() {} // 4.2

void COGNAT::about() // 5.1
{
    QMessageBox::about(this, tr("About COGNAT"),
                       tr("
COGNAT
"
                          "
Comparative Gene Neighborhoods Analysis Tool
"
                          "
Copyright © 2017 Molecular Bioenergetics Group
"));
}

void COGNAT::setColorGenesComboBox(QAction *action) // 3.5
{
    colorGenesComboBox->setCurrentIndex(colorGenesComboBox->findText(action->text()));
}

void COGNAT::setColorGenesGroup(const int &index) // 3.5
{
    colorGenesGroup->actions()[index]->setChecked(true);
    colorGenesGroup->actions()[index]->trigger();
}

void COGNAT::modifyNeighborhoodRadius(const int &index) // 3.8
{
    neighborhoodRadius = index + 1;
    if (database->textFileWasLoaded()) {
        mainWidget->setRadius(neighborhoodRadius);
        mainWidget->setNeighborhoodRadius();
        showIntergenes(showIntergenesAction->isChecked());
        setColorGenesGroup(colorGenesComboBox->currentIndex());
    }
    statusBar()->showMessage(tr("A number of genes in a neighborhood was tuned to %1 genes")
                             .arg((index + 1) * 2 + 1));
    setFocus();
}

void COGNAT::color()
{
    QString gi = mainWidget->currentGi();
    QString architecture = mainWidget->currentArchitecture();
    database->insertAnchor(gi, architecture);
    if (architecture.isEmpty()) {
        if (mainWidget->mode == MainWidget::Domains || mainWidget->mode == MainWidget::DomainArchitectures) {
            QMessageBox::warning(this, tr("Warning"),
                                 tr("Could not color a selected gene.\n\n"
                                    "No significant Pfam-A matches."));
        } else if (mainWidget->mode == MainWidget::COGs || mainWidget->mode == MainWidget::COGArchitectures) {
            QMessageBox::warning(this, tr("Warning"),
                                 tr("Could not color a selected gene.\n\n"
                                    "No significant COGs matches."));
        }
    }
    setColorGenesGroup(colorGenesComboBox->currentIndex());
}

void COGNAT::decolor()
{
    QString architecture = mainWidget->currentArchitecture();
    database->removeAnchor(architecture);
    setColorGenesGroup(colorGenesComboBox->currentIndex());
}

void COGNAT::createActions()
{
    // 1.1
    loadAction = new QAction(tr("Load..."), this);
    //loadAction->setStatusTip(tr("Load a text file of protein GIs or IDs written under each other or load a project"));
    loadAction->setStatusTip(tr("Load a text file of protein GIs or IDs written under each other"));
    connect(loadAction, SIGNAL(triggered()), this, SLOT(load()));

    // 1.2 ###
    saveAction = new QAction(tr("Save"), this);
    saveAction->setIcon(QIcon(":/images/save.png"));
    saveAction->setShortcut(QKeySequence::Save);
    //saveAction->setStatusTip(tr("Save the project to a disk"));
    //saveAction->setToolTip(tr("Save the project to a disk"));
    saveAction->setStatusTip(tr("Save PDF"));
    saveAction->setToolTip(tr("Save PDF"));
    connect(saveAction, SIGNAL(triggered()), this, SLOT(save()));

    // 1.3
    saveAsAction = new QAction(tr("Save As..."), this);
    saveAsAction->setStatusTip(tr("Save under a new name or format"));
    connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveAs()));

    // 1.4
    for (int i = 0; i < MaxRecentProjects; ++i)
    {
        loadRecentProjectActions[i] = new QAction(this);
        loadRecentProjectActions[i]->setVisible(false);
        connect(loadRecentProjectActions[i], SIGNAL(triggered()), this, SLOT(loadRecentProject()));
    }

    // 1.5
    exitAction = new QAction(tr("Exit"), this);
    exitAction->setStatusTip(tr("Exit the application"));
    connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));

    // 2.1 ###
    searchGenesAction = new QAction(tr("Search Genes..."), this);
    searchGenesAction->setIcon(QIcon(":/images/search.png"));
    searchGenesAction->setStatusTip(tr("Search genes of proteins containing a given domain or COG"));
    searchGenesAction->setToolTip(tr("Search genes of proteins containing a given domain or COG"));
    connect(searchGenesAction, SIGNAL(triggered()), this, SLOT(searchGenes()));

    // 2.2
    specifyDatabaseAction = new QAction(tr("Specify Database..."), this);
    specifyDatabaseAction->setStatusTip(tr("Specify a path to a database"));
    connect(specifyDatabaseAction, SIGNAL(triggered()), this, SLOT(specifyDatabase()));

    // 3.1 ###
    sortGenomesByTaxonomyAction = new QAction(tr("Sort Genomes By Taxonomy"), this);
    sortGenomesByTaxonomyAction->setCheckable(true);
    sortGenomesByTaxonomyAction->setChecked(false);
    sortGenomesByTaxonomyAction->setIcon(QIcon(":/images/sort.png"));
    sortGenomesByTaxonomyAction->setStatusTip(tr("Sort genomes by taxonomy"));
    sortGenomesByTaxonomyAction->setToolTip(tr("Sort genomes by taxonomy"));
    connect(sortGenomesByTaxonomyAction, SIGNAL(toggled(bool)), this, SLOT(sortGenomesByTaxonomy(bool)));

    // 3.2 ###
    markGenesOfMembraneProteinsAction = new QAction(tr("Mark Genes Of Membrane Proteins"), this);
    markGenesOfMembraneProteinsAction->setCheckable(true);
    markGenesOfMembraneProteinsAction->setChecked(false);
    markGenesOfMembraneProteinsAction->setIcon(QIcon(":/images/mark.png"));
    markGenesOfMembraneProteinsAction->setStatusTip(tr("Mark genes of presumably membrane proteins with hatching"));
    markGenesOfMembraneProteinsAction->setToolTip(tr("Mark genes of presumably membrane proteins with hatching"));
    connect(markGenesOfMembraneProteinsAction, SIGNAL(toggled(bool)), this, SLOT(markGenesOfMembraneProteins(bool)));

    // 3.3
    examineOrthologsAndParalogsAction = new QAction(tr("Examine Orthologs And Paralogs"), this);
    examineOrthologsAndParalogsAction->setCheckable(true);
    examineOrthologsAndParalogsAction->setChecked(true);
    examineOrthologsAndParalogsAction->setStatusTip(tr("Color/decolor all genes, which products have the same architecture"));
    connect(examineOrthologsAndParalogsAction, SIGNAL(toggled(bool)), this, SLOT(examineOrthologsAndParalogs(bool)));

    // 3.4 ###
    showIntergenesAction = new QAction(tr("Show Intergenic Spaces"), this);
    showIntergenesAction->setCheckable(true);
    showIntergenesAction->setChecked(true);
    showIntergenesAction->setIcon(QIcon(":/images/show.png"));
    showIntergenesAction->setStatusTip(tr("Show intergenic spaces"));
    showIntergenesAction->setToolTip(tr("Show intergenic spaces"));
    connect(showIntergenesAction, SIGNAL(toggled(bool)), this, SLOT(showIntergenes(bool)));

    // 3.5.1
    colorByDomainArchitecturesAction = new QAction(tr("By Domain Architectures"), this);
    colorByDomainArchitecturesAction->setCheckable(true);
    colorByDomainArchitecturesAction->setStatusTip(tr("Each domain architecture is assigned to a specific color"));
    connect(colorByDomainArchitecturesAction, SIGNAL(triggered()), this, SLOT(colorByDomainArchitectures()));

    // 3.5.2
    colorByCOGArchitecturesAction = new QAction(tr("By COG Architectures"), this);
    colorByCOGArchitecturesAction->setCheckable(true);
    colorByCOGArchitecturesAction->setStatusTip(tr("Each COG architecture is assigned to a specific color"));
    connect(colorByCOGArchitecturesAction, SIGNAL(triggered()), this, SLOT(colorByCOGArchitectures()));

    // 3.5.3
    colorByDomainsAction = new QAction(tr("By Domains"), this);
    colorByDomainsAction->setCheckable(true);
    colorByDomainsAction->setStatusTip(tr("Each domain is assigned to a specific color"));
    connect(colorByDomainsAction, SIGNAL(triggered()), this, SLOT(colorByDomains()));

    // 3.5.4
    colorByCOGsAction = new QAction(tr("By COGs"), this);
    colorByCOGsAction->setCheckable(true);
    colorByCOGsAction->setStatusTip(tr("Each COG is assigned to a specific color"));
    connect(colorByCOGsAction, SIGNAL(triggered()), this, SLOT(colorByCOGs()));

    // 3.6
    loadColorSchemeAction = new QAction(tr("Load Color Scheme..."), this);
    loadColorSchemeAction->setStatusTip(tr("Load a color scheme in a simple text format"));
    connect(loadColorSchemeAction, SIGNAL(triggered()), this, SLOT(loadColorScheme()));

    // 3.7
    colorArchitecturesAction = new QAction(tr("Color Architectures..."), this);
    colorArchitecturesAction->setStatusTip(tr("Load protein architectures in a simple text format to be colored"));
    connect(colorArchitecturesAction, SIGNAL(triggered()), this, SLOT(colorArchitectures()));

    //
    /*setPdfResolutionAction = new QAction(tr("Set PDF Resolution..."), this);
    setPdfResolutionAction->setStatusTip(tr("Set a resolution of PDF in points"));
    connect(setPdfResolutionAction, SIGNAL(triggered()), this, SLOT(setPdfResolution()));*/

    // 3.8
    setNeighborhoodRadiusAction = new QAction(tr("Set Neighborhood..."), this);
    setNeighborhoodRadiusAction->setStatusTip(tr("Set a number of genes in a neighborhood"));
    connect(setNeighborhoodRadiusAction, SIGNAL(triggered()), this, SLOT(setNeighborhoodRadius()));

    // 3.9
    setValuesAction = new QAction(tr("Advanced Settings..."), this);
    setValuesAction->setStatusTip(tr("Advanced settings"));
    connect(setValuesAction, SIGNAL(triggered()), this, SLOT(setValues()));

    // 4.1
    reconstructTreeAction = new QAction(tr("Reconstruct Tree..."), this);
    reconstructTreeAction->setStatusTip(tr("Reconstruct a phylogenetic tree of selected proteins"));
    connect(reconstructTreeAction, SIGNAL(triggered()), this, SLOT(reconstructTree()));

    // 4.2
    setPhylumColorAction = new QAction(tr("Set Phylum Color..."), this);
    setPhylumColorAction->setStatusTip(tr("Assign each phylum to a specific color"));
    connect(setPhylumColorAction, SIGNAL(triggered()), this, SLOT(setPhylumColor()));

    // 5.1
    aboutAction = new QAction(tr("About"), this);
    aboutAction->setStatusTip(tr("Show the application's About box"));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));

    // 3.5
    colorGenesGroup = new QActionGroup(this);
    colorGenesGroup->addAction(colorByCOGsAction);
    colorGenesGroup->addAction(colorByDomainsAction);
    colorGenesGroup->addAction(colorByCOGArchitecturesAction);
    colorGenesGroup->addAction(colorByDomainArchitecturesAction);
    colorByCOGsAction->setChecked(true);

    colorAction = new QAction(tr("Color"), this);
    connect(colorAction, SIGNAL(triggered()), this, SLOT(color()));

    decolorAction = new QAction(tr("Decolor"), this);
    connect(decolorAction, SIGNAL(triggered()), this, SLOT(decolor()));
}

void COGNAT::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("File")); // 1
    fileMenu->addAction(loadAction); // 1.1
    fileMenu->addAction(saveAction); // 1.2 ###
    //fileMenu->addAction(saveAsAction); // 1.3
    separatorAction = fileMenu->addSeparator();
    for (int i = 0; i < MaxRecentProjects; ++i)
        fileMenu->addAction(loadRecentProjectActions[i]); // 1.4
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction); // 1.5

    databaseMenu = menuBar()->addMenu(tr("Database")); // 2
    databaseMenu->addAction(searchGenesAction); // 2.1 ###
    databaseMenu->addSeparator();
    databaseMenu->addAction(specifyDatabaseAction); // 2.2

    optionsMenu = menuBar()->addMenu(tr("Options")); // 3
    optionsMenu->addAction(sortGenomesByTaxonomyAction); // 3.1 ###
    optionsMenu->addAction(markGenesOfMembraneProteinsAction); // 3.2 ###
    //optionsMenu->addAction(examineOrthologsAndParalogsAction); // 3.3
    optionsMenu->addAction(showIntergenesAction); // 3.4 ###
    colorGenesSubMenu = optionsMenu->addMenu(tr("Color Genes")); // 3.5
    colorGenesSubMenu->addAction(colorByCOGsAction); // 3.5.4
    colorGenesSubMenu->addAction(colorByDomainsAction); // 3.5.3
    colorGenesSubMenu->addAction(colorByCOGArchitecturesAction); // 3.5.2
    colorGenesSubMenu->addAction(colorByDomainArchitecturesAction); // 3.5.1
    optionsMenu->addSeparator();
    optionsMenu->addAction(loadColorSchemeAction); // 3.6
    optionsMenu->addAction(colorArchitecturesAction); // 3.7
    optionsMenu->addSeparator();
    //optionsMenu->addAction(setPdfResolutionAction); //
    optionsMenu->addAction(setNeighborhoodRadiusAction); // 3.8
    optionsMenu->addAction(setValuesAction); // 3.9

    //phylogenyMenu = menuBar()->addMenu(tr("Phylogeny")); // 4
    //phylogenyMenu->addAction(reconstructTreeAction); // 4.1
    //phylogenyMenu->addSeparator();
    //phylogenyMenu->addAction(setPhylumColorAction); // 4.2

    menuBar()->addSeparator();

    helpMenu = menuBar()->addMenu(tr("Help")); // 5
    helpMenu->addAction(aboutAction); // 5.1
}

void COGNAT::createToolBars()
{
    colorGenesLabel = new QLabel(tr("Color Genes:"), this); // 3.5

    colorGenesComboBox = new QComboBox(this); // 3.5
    colorGenesComboBox->addItem(tr("By COGs")); // 3.5.4
    colorGenesComboBox->addItem(tr("By Domains")); // 3.5.3
    colorGenesComboBox->addItem(tr("By COG Architectures")); // 3.5.2
    colorGenesComboBox->addItem(tr("By Domain Architectures")); // 3.5.1
    colorGenesComboBox->setItemData(0, tr("Each COG is assigned to a specific color"), Qt::StatusTipRole); // 3.5.4
    colorGenesComboBox->setItemData(0, tr("Each COG is assigned to a specific color"), Qt::ToolTipRole); // 3.5.4
    colorGenesComboBox->setItemData(1, tr("Each domain is assigned to a specific color"), Qt::StatusTipRole); // 3.5.3
    colorGenesComboBox->setItemData(1, tr("Each domain is assigned to a specific color"), Qt::ToolTipRole); // 3.5.3
    colorGenesComboBox->setItemData(2, tr("Each COG architecture is assigned to a specific color"), Qt::StatusTipRole); // 3.5.2
    colorGenesComboBox->setItemData(2, tr("Each COG architecture is assigned to a specific color"), Qt::ToolTipRole); // 3.5.2
    colorGenesComboBox->setItemData(3, tr("Each domain architecture is assigned to a specific color"), Qt::StatusTipRole); // 3.5.1
    colorGenesComboBox->setItemData(3, tr("Each domain architecture is assigned to a specific color"), Qt::ToolTipRole); // 3.5.1
    colorGenesComboBox->setFocusPolicy(Qt::NoFocus); // 3.5
    connect(colorGenesGroup, SIGNAL(triggered(QAction *)), this, SLOT(setColorGenesComboBox(QAction *))); // 3.5
    connect(colorGenesComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setColorGenesGroup(int))); // 3.5

    neighborhoodRadiusLabel = new QLabel(tr("Neighborhood:"), this); // 3.8
    neighborhoodRadiusLabel->setStatusTip(tr("Set a number of genes in a neighborhood")); // 3.8
    neighborhoodRadiusLabel->setToolTip(tr("Set a number of genes in a neighborhood")); // 3.8

    neighborhoodRadiusComboBox = new QComboBox(this); // 3.8
    for (int i = 1; i <= MaxNeighborhoodRadius; ++i) {
        if (i * 2 + 1 < 10) {
            neighborhoodRadiusComboBox->addItem(tr("%1 genes").arg(i * 2 + 1, 3));
        } else {
            neighborhoodRadiusComboBox->addItem(tr("%1 genes").arg(i * 2 + 1));
        }
    }
    neighborhoodRadiusComboBox->setCurrentIndex(neighborhoodRadius - 1); // 3.8
    neighborhoodRadiusComboBox->setFocusPolicy(Qt::NoFocus); // 3.8
    connect(neighborhoodRadiusComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(modifyNeighborhoodRadius(int))); // 3.8

    fileToolBar = addToolBar(tr("File")); // 1
    fileToolBar->addAction(saveAction); // 1.2 ###
    fileToolBar->addSeparator();
    fileToolBar->setMovable(false);

    databaseToolBar = addToolBar(tr("Database")); // 2
    databaseToolBar->addAction(searchGenesAction); // 2.1 ###
    databaseToolBar->addSeparator();
    databaseToolBar->setMovable(false);

    optionsToolBar = addToolBar(tr("Options")); // 3
    optionsToolBar->addAction(sortGenomesByTaxonomyAction); // 3.1 ###
    optionsToolBar->addAction(markGenesOfMembraneProteinsAction); // 3.2 ###
    optionsToolBar->addAction(showIntergenesAction); // 3.4 ###
    optionsToolBar->addSeparator();
    optionsToolBar->addWidget(colorGenesLabel); // 3.5
    optionsToolBar->addWidget(colorGenesComboBox); // 3.5
    optionsToolBar->addSeparator();
    optionsToolBar->addWidget(neighborhoodRadiusLabel); // 3.8
    optionsToolBar->addWidget(neighborhoodRadiusComboBox); // 3.8
    optionsToolBar->setMovable(false);
}

void COGNAT::setGeometry()
{
    int x = qApp->desktop()->availableGeometry(qApp->desktop()->primaryScreen()).width() / 10;
    int y = qApp->desktop()->availableGeometry(qApp->desktop()->primaryScreen()).height() / 10;
    move(x, y);
    resize(x * 8, y * 8);
    setMinimumSize(sizeHint().width(), sizeHint().width() / 2);
}

void COGNAT::readSettings()
{
    /*QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFormat(QPrinter::PdfFormat);
    int width = printer.paperSize(QPrinter::Point).width();
    int height = printer.paperSize(QPrinter::Point).height();*/

    QSettings settings("Molecular Bioenergetics Group", "COGNAT");
    databasePath = settings.value("databasePath").toString();
    loadPath = settings.value("loadPath").toString();
    savePath = settings.value("savePath").toString();
    //pdfWidth = settings.value("pdfWidth", width).toInt();
    //pdfHeight = settings.value("pdfHeight", height).toInt();
    neighborhoodRadius = settings.value("neighborhoodRadius", 4).toInt();
    minimumBitScore = settings.value("minimumBitScore", 33).toInt();
    minimumRelativeLength = settings.value("minimumRelativeLength", 33).toInt();
    maximumOverlapping = settings.value("maximumOverlapping", 50).toInt();
    trustworthyBitScore = settings.value("trustworthyBitScore", 250).toInt();
    /*if (pdfWidth == 0) {
        pdfWidth = width;
    }
    if (pdfHeight == 0) {
        pdfHeight = height;
    }*/
    if (neighborhoodRadius == 0) {
        neighborhoodRadius = 4;
    }
    if (minimumBitScore == 0) {
        minimumBitScore = 33;
    }
    if (minimumRelativeLength == 0) {
        minimumRelativeLength = 33;
    }
    if (maximumOverlapping == 0) {
        maximumOverlapping = 50;
    }
    if (trustworthyBitScore == 0) {
        trustworthyBitScore = 250;
    }
    /*QSettings settings("Software Inc.", "Spreadsheet");

    restoreGeometry(settings.value("geometry").toByteArray());

    recentFiles = settings.value("recentFiles").toStringList();
    updateRecentFileActions();

    bool showGrid = settings.value("showGrid", true).toBool();
    showGridAction->setChecked(showGrid);

    bool autoRecalc = settings.value("autoRecalc", true).toBool();
    autoRecalcAction->setChecked(autoRecalc);*/
}

void COGNAT::writeSettings()
{
    QSettings settings("Molecular Bioenergetics Group", "COGNAT");
    settings.setValue("databasePath", databasePath);
    settings.setValue("loadPath", loadPath);
    settings.setValue("savePath", savePath);
    //settings.setValue("pdfWidth", pdfWidth);
    //settings.setValue("pdfHeight", pdfHeight);
    settings.setValue("neighborhoodRadius", neighborhoodRadius);
    settings.setValue("minimumBitScore", minimumBitScore);
    settings.setValue("minimumRelativeLength", minimumRelativeLength);
    settings.setValue("maximumOverlapping", maximumOverlapping);
    settings.setValue("trustworthyBitScore", trustworthyBitScore);
    /*QSettings settings("Software Inc.", "Spreadsheet");

    settings.setValue("geometry", saveGeometry());
    settings.setValue("recentFiles", recentFiles);
    settings.setValue("showGrid", showGridAction->isChecked());
    settings.setValue("autoRecalc", autoRecalcAction->isChecked());*/
}

void COGNAT::writeColorToSettings(const QString &architecture, const QColor &color)
{
    QSettings settings("Molecular Bioenergetics Group", "COGNAT");
    settings.setValue(architecture, color);
}

bool COGNAT::okToContinue()
{
    /*if (isWindowModified()) {
        int r = QMessageBox::warning(this, tr("Spreadsheet"),
                        tr("The document has been modified.\n"
                           "Do you want to save your changes?"),
                        QMessageBox::Yes | QMessageBox::No
                        | QMessageBox::Cancel);
        if (r == QMessageBox::Yes) {
            return save();
        } else if (r == QMessageBox::Cancel) {
            return false;
        }
    }*/
    return true;
}

void COGNAT::loadTextFile(const QString &fileName)
{
    inputType = Default;
    if (mainWidget != NULL) {
        delete mainWidget;
        mainWidget = NULL;
    }
    QString name = QFileInfo(fileName).fileName();
    if (database->loadTextFile(fileName)) { // The database was cleared.
        //setCurrentFile(fileName); ???
        statusBar()->showMessage(tr("A text file '%1' was loaded")
                                 .arg(name));
        mainWidget = new MainWidget(database, this); // Only a "skeleton" of an output window was created.
        mainWidget->setRadius(neighborhoodRadius);
        mainWidget->setMinimumScore(minimumBitScore);
        mainWidget->setMinimumLength(minimumRelativeLength);
        mainWidget->setMaximumOverlapping(maximumOverlapping);
        mainWidget->setTrustworthyScore(trustworthyBitScore);
        setCentralWidget(mainWidget);
        sortGenomesByTaxonomy(sortGenomesByTaxonomyAction->isChecked());
    } else {
        QMessageBox::warning(this, tr("Warning"),
                             tr("Could not load a text file '%1'.\n\n%2.")
                             .arg(name).arg(database->errorString()));
    }
}

void COGNAT::loadSearchedGenes(const QString &fileName)
{
    inputType = Default;
    if (mainWidget != NULL) {
        delete mainWidget;
        mainWidget = NULL;
    }
    QString name = QFileInfo(fileName).fileName();
    if (database->loadTextFile(fileName)) { // The database was cleared.
        //setCurrentFile(fileName); ???
        statusBar()->showMessage(tr("Searched genes were loaded"));
        mainWidget = new MainWidget(database, this); // Only a "skeleton" of an output window was created.
        mainWidget->setRadius(neighborhoodRadius);
        mainWidget->setMinimumScore(minimumBitScore);
        mainWidget->setMinimumLength(minimumRelativeLength);
        mainWidget->setMaximumOverlapping(maximumOverlapping);
        mainWidget->setTrustworthyScore(trustworthyBitScore);
        setCentralWidget(mainWidget);
        sortGenomesByTaxonomy(sortGenomesByTaxonomyAction->isChecked());
    } else {
        QMessageBox::warning(this, tr("Warning"),
                             tr("Could not search genes.\n\n%1.")
                             .arg(database->errorString()));
    }
}

void COGNAT::loadProject(const QString &fileName)
{
    //setCurrentFile(fileName); ???
    /*QString name = QFileInfo(fileName).fileName();
    statusBar()->showMessage(tr("A project '%1' was loaded")
                             .arg(name));*/
    //inputType = {one of 3} ???
    QMessageBox::warning(this, tr("Warning"),
                         tr("Sorry, this option is currently unavailable."));
}

void COGNAT::savePdf(const QString &fileName)
{
    QString name = QFileInfo(fileName).fileName();
    //QSizeF size(pdfWidth, pdfHeight);
    //if (mainWidget->savePdf(fileName, size)) {
    if (mainWidget->savePdf(fileName)) {
        savePath = QFileInfo(fileName).canonicalPath();
        //setCurrentFile(fileName); ???
        statusBar()->showMessage(tr("PDF '%1' was saved")
                                 .arg(name));
    } else {
        QMessageBox::warning(this, tr("Warning"),
                             tr("Could not save PDF '%1'.")
                             .arg(name));
    }
}

void COGNAT::saveProject(const QString &fileName)
{
    //setCurrentFile(fileName); ???
    /*QString name = QFileInfo(fileName).fileName();
    statusBar()->showMessage(tr("A project '%1' was saved")
                             .arg(name));*/
    QMessageBox::warning(this, tr("Warning"),
                         tr("Sorry, this option is currently unavailable."));
}

/*void COGNAT::setCurrentFile(const QString &fileName)
{
    curFile = fileName;
    setWindowModified(false);

    QString shownName = tr("Untitled");
    if (!curFile.isEmpty()) {
        shownName = strippedName(curFile);
        recentFiles.removeAll(curFile);
        recentFiles.prepend(curFile);
        updateRecentFileActions();
    }

    setWindowTitle(tr("%1[*] - %2").arg(shownName)
                                   .arg(tr("Spreadsheet")));
}

void COGNAT::updateRecentFileActions()
{
    QMutableStringListIterator i(recentFiles);
    while (i.hasNext()) {
        if (!QFile::exists(i.next()))
            i.remove();
    }

    for (int j = 0; j < MaxRecentFiles; ++j) {
        if (j < recentFiles.count()) {
            QString text = tr("&%1 %2")
                           .arg(j + 1)
                           .arg(strippedName(recentFiles[j]));
            recentFileActions[j]->setText(text);
            recentFileActions[j]->setData(recentFiles[j]);
            recentFileActions[j]->setVisible(true);
        } else {
            recentFileActions[j]->setVisible(false);
        }
    }
    separatorAction->setVisible(!recentFiles.isEmpty());
}*/


text:
package org.apache.solr.update.processor;

import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.io.FileUtils;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.schema.IndexSchema;
import org.junit.After;
import org.junit.Before;

/**
 * Tests for the field mutating update processors that parse Dates, Longs, Doubles, and Booleans.
 */
public class AddSchemaFieldsUpdateProcessorFactoryTest extends UpdateProcessorTestBase {
  private static final String SOLRCONFIG_XML =
      "solrconfig-add-schema-fields-update-processor-chains.xml";
  private static final String SCHEMA_XML = "schema-add-schema-fields-update-processor.xml";

  private static final String collection = "collection1";
  private static final String confDir = collection + "/conf";

  @Before
  public void initManagedSchemaCore() throws Exception {
    File tmpSolrHome = createTempDir().toFile();
    File tmpConfDir = new File(tmpSolrHome, confDir);
    File testHomeConfDir = new File(TEST_HOME(), confDir);
    FileUtils.copyFileToDirectory(new File(testHomeConfDir, SOLRCONFIG_XML), tmpConfDir);
    FileUtils.copyFileToDirectory(new File(testHomeConfDir, SCHEMA_XML), tmpConfDir);

    // initCore will trigger an upgrade to managed schema, since the solrconfig*.xml has
    // <schemaFactory class="ManagedIndexSchemaFactory" ... />
    initCore(SOLRCONFIG_XML, SCHEMA_XML, tmpSolrHome.getPath());
  }

  public void testEmptyValue() {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName = "newFieldABC";
    assertNull(schema.getFieldOrNull(fieldName));
    // UpdateProcessorTestBase#doc doesn't deal with nulls
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("id", "1");
    doc.addField(fieldName, null);

    expectThrows(AssertionError.class, () -> processAdd("add-fields-no-run-processor", doc));

    expectThrows(
        AssertionError.class,
        () -> processAdd("add-fields-no-run-processor", new SolrInputDocument(null, null)));
  }

  public void testSingleField() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName = "newfield1";
    assertNull(schema.getFieldOrNull(fieldName));
    Date date = Date.from(Instant.now());
    SolrInputDocument d =
        processAdd("add-fields-no-run-processor", doc(f("id", "1"), f(fieldName, date)));
    assertNotNull(d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName));
    assertEquals("pdates", schema.getFieldType(fieldName).getTypeName());
  }

  public void testSingleFieldRoundTrip() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName = "newfield2";
    assertNull(schema.getFieldOrNull(fieldName));
    Float floatValue = -13258.992f;
    SolrInputDocument d = processAdd("add-fields", doc(f("id", "2"), f(fieldName, floatValue)));
    assertNotNull(d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName));
    assertEquals("pfloats", schema.getFieldType(fieldName).getTypeName());
    assertU(commit());
    assertQ(req("id:2"), "//arr[@name='" + fieldName + "']/float[.='" + floatValue + "']");
  }

  public void testSingleFieldMixedFieldTypesRoundTrip() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName = "newfield3";
    assertNull(schema.getFieldOrNull(fieldName));
    Float fieldValue1 = -13258.0f;
    Double fieldValue2 = 8.4828800808E10;
    SolrInputDocument d =
        processAdd("add-fields", doc(f("id", "3"), f(fieldName, fieldValue1, fieldValue2)));
    assertNotNull(d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName));
    assertEquals("pdoubles", schema.getFieldType(fieldName).getTypeName());
    assertU(commit());
    assertQ(
        req("id:3"),
        "//arr[@name='" + fieldName + "']/double[.='" + fieldValue1 + "']",
        "//arr[@name='" + fieldName + "']/double[.='" + fieldValue2 + "']");
  }

  public void testSingleFieldDefaultFieldTypeRoundTrip() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName = "newfield4";
    assertNull(schema.getFieldOrNull(fieldName));
    Float fieldValue1 = -13258.0f;
    Double fieldValue2 = 8.4828800808E10;
    String fieldValue3 = "blah blah";
    SolrInputDocument d =
        processAdd(
            "add-fields", doc(f("id", "4"), f(fieldName, fieldValue1, fieldValue2, fieldValue3)));
    assertNotNull(d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName));
    assertEquals("text", schema.getFieldType(fieldName).getTypeName());
    assertEquals(
        0, schema.getCopyFieldProperties(true, Collections.singleton(fieldName), null).size());
    assertU(commit());
    assertQ(
        req("id:4"),
        "//arr[@name='" + fieldName + "']/str[.='" + fieldValue1 + "']",
        "//arr[@name='" + fieldName + "']/str[.='" + fieldValue2 + "']",
        "//arr[@name='" + fieldName + "']/str[.='" + fieldValue3 + "']");
  }

  public void testSingleFieldDefaultTypeMappingRoundTrip() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName = "newfield4";
    assertNull(schema.getFieldOrNull(fieldName));
    Float fieldValue1 = -13258.0f;
    Double fieldValue2 = 8.4828800808E10;
    String fieldValue3 = "blah blah";
    SolrInputDocument d =
        processAdd(
            "add-fields-default-mapping",
            doc(f("id", "4"), f(fieldName, fieldValue1, fieldValue2, fieldValue3)));
    assertNotNull(d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName));
    assertEquals("text", schema.getFieldType(fieldName).getTypeName());
    assertEquals(
        1, schema.getCopyFieldProperties(true, Collections.singleton(fieldName), null).size());
    assertU(commit());
    assertQ(
        req("id:4"),
        "//arr[@name='" + fieldName + "']/str[.='" + fieldValue1 + "']",
        "//arr[@name='" + fieldName + "']/str[.='" + fieldValue2 + "']",
        "//arr[@name='" + fieldName + "']/str[.='" + fieldValue3 + "']");
  }

  public void testMultipleFieldsRoundTrip() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName1 = "newfield5";
    final String fieldName2 = "newfield6";
    assertNull(schema.getFieldOrNull(fieldName1));
    assertNull(schema.getFieldOrNull(fieldName2));
    Float field1Value1 = -13258.0f;
    Double field1Value2 = 8.4828800808E10;
    Long field1Value3 = 999L;
    Integer field2Value1 = 55123;
    Long field2Value2 = 1234567890123456789L;
    SolrInputDocument d =
        processAdd(
            "add-fields",
            doc(
                f("id", "5"),
                f(fieldName1, field1Value1, field1Value2, field1Value3),
                f(fieldName2, field2Value1, field2Value2)));
    assertNotNull(d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName1));
    assertNotNull(schema.getFieldOrNull(fieldName2));
    assertEquals("pdoubles", schema.getFieldType(fieldName1).getTypeName());
    assertEquals("plongs", schema.getFieldType(fieldName2).getTypeName());
    assertU(commit());
    assertQ(
        req("id:5"),
        "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value1 + "']",
        "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value2 + "']",
        "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value3.doubleValue() + "']",
        "//arr[@name='" + fieldName2 + "']/long[.='" + field2Value1 + "']",
        "//arr[@name='" + fieldName2 + "']/long[.='" + field2Value2 + "']");
  }

  public void testParseAndAddMultipleFieldsRoundTrip() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName1 = "newfield7";
    final String fieldName2 = "newfield8";
    final String fieldName3 = "newfield9";
    final String fieldName4 = "newfield10";
    assertNull(schema.getFieldOrNull(fieldName1));
    assertNull(schema.getFieldOrNull(fieldName2));
    assertNull(schema.getFieldOrNull(fieldName3));
    assertNull(schema.getFieldOrNull(fieldName4));
    String field1String1 = "-13,258.0";
    Float field1Value1 = -13258.0f;
    String field1String2 = "84,828,800,808.0";
    Double field1Value2 = 8.4828800808E10;
    String field1String3 = "999";
    Long field1Value3 = 999L;
    String field2String1 = "55,123";
    Integer field2Value1 = 55123;
    String field2String2 = "1,234,567,890,123,456,789";
    Long field2Value2 = 1234567890123456789L;
    String field3String1 = "blah-blah";
    String field3String2 = "-5.28E-3";
    String field4String1 = "1999-04-17 17:42";
    DateTimeFormatter dateTimeFormatter =
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ROOT).withZone(ZoneOffset.UTC);
    LocalDateTime dateTime = LocalDateTime.parse(field4String1, dateTimeFormatter);
    DateTimeFormatter dateTimeFormatter2 =
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT).withZone(ZoneOffset.UTC);
    String field4Value1String = dateTime.format(dateTimeFormatter2) + "Z";

    SolrInputDocument d =
        processAdd(
            "parse-and-add-fields",
            doc(
                f("id", "6"),
                f(fieldName1, field1String1, field1String2, field1String3),
                f(fieldName2, field2String1, field2String2),
                f(fieldName3, field3String1, field3String2),
                f(fieldName4, field4String1)));
    assertNotNull(d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName1));
    assertNotNull(schema.getFieldOrNull(fieldName2));
    assertNotNull(schema.getFieldOrNull(fieldName3));
    assertNotNull(schema.getFieldOrNull(fieldName4));
    assertEquals("pdoubles", schema.getFieldType(fieldName1).getTypeName());
    assertEquals("plongs", schema.getFieldType(fieldName2).getTypeName());
    assertEquals("text", schema.getFieldType(fieldName3).getTypeName());
    assertEquals("pdates", schema.getFieldType(fieldName4).getTypeName());
    assertU(commit());
    assertQ(
        req("id:6"),
        "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value1 + "']",
        "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value2 + "']",
        "//arr[@name='" + fieldName1 + "']/double[.='" + field1Value3.doubleValue() + "']",
        "//arr[@name='" + fieldName2 + "']/long[.='" + field2Value1 + "']",
        "//arr[@name='" + fieldName2 + "']/long[.='" + field2Value2 + "']",
        "//arr[@name='" + fieldName3 + "']/str[.='" + field3String1 + "']",
        "//arr[@name='" + fieldName3 + "']/str[.='" + field3String2 + "']",
        "//arr[@name='" + fieldName4 + "']/date[.='" + field4Value1String + "']");
  }

  public void testStringWithCopyField() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName = "stringField";
    final String strFieldName = fieldName + "_str";
    assertNull(schema.getFieldOrNull(fieldName));
    String content = "This is a text that should be copied to a string field but not be cutoff";
    SolrInputDocument d = processAdd("add-fields", doc(f("id", "1"), f(fieldName, content)));
    assertNotNull(d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName));
    assertNotNull(schema.getFieldOrNull(strFieldName));
    assertEquals("text", schema.getFieldType(fieldName).getTypeName());
    assertEquals(
        1,
        schema
            .getCopyFieldProperties(
                true, Collections.singleton(fieldName), Collections.singleton(strFieldName))
            .size());
  }

  public void testStringWithCopyFieldAndMaxChars() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    final String fieldName = "stringField";
    final String strFieldName = fieldName + "_str";
    assertNull(schema.getFieldOrNull(fieldName));
    String content =
        "This is a text that should be copied to a string field and cutoff at 10 characters";
    SolrInputDocument d =
        processAdd("add-fields-maxchars", doc(f("id", "1"), f(fieldName, content)));
    assertNotNull(d);
    System.out.println("Document is " + d);
    schema = h.getCore().getLatestSchema();
    assertNotNull(schema.getFieldOrNull(fieldName));
    assertNotNull(schema.getFieldOrNull(strFieldName));
    assertEquals("text", schema.getFieldType(fieldName).getTypeName());
    // We have three copyFields, one with maxChars 10 and two with maxChars 20
    assertEquals(
        3, schema.getCopyFieldProperties(true, Collections.singleton(fieldName), null).size());
    assertEquals(
        "The configured maxChars cutoff does not exist on the copyField",
        10,
        schema
            .getCopyFieldProperties(
                true, Collections.singleton(fieldName), Collections.singleton(strFieldName))
            .get(0)
            .get("maxChars"));
    assertEquals(
        "The configured maxChars cutoff does not exist on the copyField",
        20,
        schema
            .getCopyFieldProperties(
                true, Collections.singleton(fieldName), Collections.singleton(fieldName + "_t"))
            .get(0)
            .get("maxChars"));
    assertEquals(
        "The configured maxChars cutoff does not exist on the copyField",
        20,
        schema
            .getCopyFieldProperties(
                true, Collections.singleton(fieldName), Collections.singleton(fieldName + "2_t"))
            .get(0)
            .get("maxChars"));
  }

  public void testCopyFieldByIndexing() throws Exception {
    String content =
        "This is a text that should be copied to a string field and cutoff at 10 characters";
    SolrInputDocument d =
        processAdd("add-fields-default-mapping", doc(f("id", "1"), f("mynewfield", content)));
    assertU(commit());

    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*").add("facet", "true").add("facet.field", "mynewfield_str");
    assertQ(
        req(params),
        "*[count(//doc)=1]",
        "//lst[@name='mynewfield_str']/int[@name='This is a '][.='1']");
  }

  @After
  public void deleteCoreAndTempSolrHomeDirectory() {
    deleteCore();
  }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'
#include Carrot::Facebook::ViewHelpers
#include ActionView::Helpers::TagHelper

#require 'action_view'
#require 'active_support'

include Carrot::Facebook::ViewHelpers
#include ActionView::Helpers
#include ActionView::Helpers::TagHelper

describe Carrot::Facebook::ViewHelpers, :type => :helper do
  let(:helper) { Carrot::Facebook::ViewHelpers }

  context "#fb_avatar" do
    it "should output a default URL with a 'square' format" do
      output = helper.fb_avatar('tmilewski')
      expect(output).to match /\?type=square\z/
    end

    it "should output a URL for a 'large' format" do
      output = helper.fb_avatar('tmilewski', :large)
      expect(output).to match /\?type=large\z/
    end

    it "should accept a Facebook ID as an Integer and output a formatted URL" do
      output = helper.fb_avatar(8201087)
      expect(output).to match /.com\/8201087\//
    end

    it "should accept a Facebook ID as a String and output a formatted URL" do
      output = helper.fb_avatar('tmilewski')
      expect(output).to match /.com\/tmilewski\//
    end

    it "should not raise an error if a Facebook ID isn't provided" do
      expect(helper.fb_avatar).to_not raise_error(ArgumentError)
    end

    it "should return nil if a Facebook ID isn't provided" do
      expect(helper.fb_avatar).to be_nil
    end
  end

  context "#fb_avatar_tag" do
    it "should output the URL within an image tag" do
      output = helper.fb_avatar_tag('tmilewski')
      expect(output.to_str).to eq '<img alt="Facebook Avatar for User tmilewski" src="//graph.facebook.com/tmilewski/picture?type=square" />'
    end

    it "should not raise an error if a Facebook ID isn't provided" do
      expect(helper.fb_avatar_tag).to_not raise_error(ArgumentError)
    end

    it "should return nil if a Facebook ID isn't provided" do
      expect(helper.fb_avatar_tag).to be_nil
    end
  end

  context "#fb_js" do
    it "should output the correct JS using ENV variables" do
      ENV.stub(:[]).with("FACEBOOK_APP_ID").and_return("asdf")
      output = helper.fbjs
      expect(output).to match /appId: 'asdf'/
      expect(output).to match /xfbml: 'true'/
    end

    it "should allow an override of the ENV variable" do
      ENV.stub(:[]).with("FACEBOOK_APP_ID").and_return("asdf")
      output = helper.fbjs(:app_id => "qwerty")
      expect(output).to match /appId: 'qwerty'/
    end

    it "should allow a user to disable XFBML rendering" do
      output = helper.fbjs(:app_id => "qwerty", :xfbml => false)
      expect(output).to match /appId: 'qwerty'/
      expect(output).to match /xfbml: 'false'/
    end
  end

  context "#facepile" do
    it "should raise error if url is not provided" do
      expect { helper.facepile }.to raise_error
    end

    it "should not raise error if ENV variable is provided" do
      ENV.stub(:[]).with("FACEBOOK_APP_URL").and_return("asdf")
      expect { helper.facepile }.to_not raise_error
    end

    it "should not raise error if :href parameter is provided" do
      expect { helper.facepile(href: "http://carrotcreative.com/") }.to_not raise_error
    end

    it "should correctly set output HTML" do
      ENV.stub(:[]).with("FACEBOOK_APP_URL").and_return("http://carrotcreative.com/")
      expect(helper.facepile).to match /data-href="http:\/\/carrotcreative.com\//
      expect(helper.facepile(max_rows: 2)).to match /data-max-rows="2"/
      expect(helper.facepile(width: 400)).to match /data-width="400"/
      expect(helper.facepile(show_count: false)).to match /data-show-count="false"/
    end
  end
end


text:
"""
QQTools command-line runner.
"""

from __future__ import print_function

import sys
import os
import re

from os import path
from .common import instantiate_command, QQBadInvocation, is_debug

def usage():
    """
    Print application usage and exit.
    """

    print(
        'QQTools script runner\n'
        'Usage: qq <command> [arguments]\n'
        '\n'
        'Execute a command from the QQTools command directory.\n'
    )
    exit(1)

def main():
    if len(sys.argv) < 2:
        usage()
    command_name = sys.argv[1]

    try:
        inst = instantiate_command(command_name)
    except Exception as e:
        print('Failed to instantiate command: ' + command_name)
        print(e)
        if is_debug():
            raise
    if not inst:
        print('Command not found: ' + command_name)
        exit(1)
    try:
        inst.execute(*sys.argv[2:])
    except Exception as e:
        if isinstance(e, QQBadInvocation):
            print(inst.help())
            exit(1)
        # Kind of a hack (could catch arity errors that propagate from inside command)
        # but good enough
        if isinstance(e, TypeError) and re.match(r'.*takes (exactly|at least|at most) \d+ argument.*', str(e)):
            print(inst.help())
            exit(1)
        print('Unexpected failure in command: ' + command_name)
        print(e)
        if is_debug():
            raise

    except Exception as e:
        print('Unexpected error in command: ' + command_name)
        print('')
        print(e)
        if is_debug():
            raise

if __name__ == '__main__':
    main()


text:
require 'chef/knife'
require 'chef/cookbook_uploader'
require 'chef/cookbook_site_streaming_uploader'

class Chef
  class Knife
    class CookbookSiteShare < Knife

      banner "knife cookbook site share COOKBOOK CATEGORY (options)"
      category "cookbook site"

      option :cookbook_path,
        :short => "-o PATH:PATH",
        :long => "--cookbook-path PATH:PATH",
        :description => "A colon-separated path to look for cookbooks in",
        :proc => lambda { |o| Chef::Config.cookbook_path = o.split(":") }

      def run
        if @name_args.length < 2
          show_usage
          Chef::Log.fatal("You must specify the cookbook name and the category you want to share this cookbook to.")
          exit 1
        end

        cookbook_name = @name_args[0]
        category = @name_args[1]
        cl = Chef::CookbookLoader.new
        if cl.cookbook_exists?(cookbook_name)
          cookbook = cl[cookbook_name]
          Chef::CookbookUploader.validate_cookbook(cookbook)
          tmp_cookbook_dir = Chef::CookbookSiteStreamingUploader.create_build_dir(cookbook)
          begin
            Chef::Log.debug("temp cookbook directory is #{tmp_cookbook_dir.inspect}")
            Chef::Log.info("Making tarball #{cookbook_name}.tgz")
            Chef::Mixin::Command.run_command(:command => "tar -czf #{cookbook_name}.tgz #{cookbook_name}", :cwd => tmp_cookbook_dir)
          rescue => e
            Chef::Log.error("Error making tarball #{cookbook_name}.tgz: #{e.message}. Set log level to debug (-l debug) for more information.")
            Chef::Log.debug("\n#{e.backtrace.join("\n")}")
            exit(1)
          end

          begin
            do_upload("#{tmp_cookbook_dir}/#{cookbook_name}.tgz", category, Chef::Config[:node_name], Chef::Config[:client_key])
            Chef::Log.info("Upload complete!")
            Chef::Log.debug("Removing local staging directory at #{tmp_cookbook_dir}")
            FileUtils.rm_rf tmp_cookbook_dir
          rescue => e
            Chef::Log.error("Error uploading cookbook #{cookbook_name} to the Opscode Cookbook Site: #{e.message}. Set log level to debug (-l debug) for more information.")
            Chef::Log.debug("\n#{e.backtrace.join("\n")}")
            exit(1)
          end

        else
          Chef::Log.error("Could not find cookbook #{cookbook_name} in your cookbook path.")
          exit(1)
        end

      end

      def do_upload(cookbook_filename, cookbook_category, user_id, user_secret_filename)
         uri = "http://cookbooks.opscode.com/api/v1/cookbooks"

         category_string = { 'category'=>cookbook_category }.to_json

         http_resp = Chef::CookbookSiteStreamingUploader.post(uri, user_id, user_secret_filename, {
           :tarball => File.open(cookbook_filename),
           :cookbook => category_string
         })

         res = Chef::JSONCompat.from_json(http_resp.body)
         if http_resp.code.to_i != 201
           if res['error_messages']
             if res['error_messages'][0] =~ /Version already exists/
               Chef::Log.error "The same version of this cookbook already exists on the Opscode Cookbook Site."
               exit(1)
             else
               Chef::Log.error "#{res['error_messages'][0]}"
               exit(1)
             end
           else
             Chef::Log.error "Unknown error while sharing cookbook"
             Chef::Log.error "Server response: #{http_resp.body}"
             exit(1)
           end
         end
         res
       end
    end

  end
end


text:
loaded = [] instanceof Array;
// globals = global
required = require('./fixture');

const {
  Plugin,
  Function,
  Autocmd,
  Command,
} = require('../../../../../../lib/plugin');

@Plugin
class Test {
  @Command('JSHostTestCmd', { sync: true, range: '', nargs: '*' })
  hostTest(args, range) {
    if (args[0] === 'canhazresponse?') {
      throw new Error('no >:(');
    }

    this.nvim.setLine('A line, for your troubles');

    return true;
  }

  @Autocmd('BufEnter', {
    sync: true,
    pattern: '*.test',
    eval: 'expand("<afile>")',
  })
  onBufEnter(filename) {
    return new Promise((resolve, reject) => {
      console.log('This is an annoying function ' + filename);
      resolve(filename);
    });
  }

  @Function('Func', { sync: true })
  func(args) {
    return 'Funcy ' + args;
  }
}

module.exports = Test;
module.exports.default = module.exports;


text:
package org.keycloak.models.map.common.delegate;

import org.keycloak.models.map.common.EntityField;
import org.keycloak.models.map.common.UpdatableEntity;

/**
 *
 * @author hmlnarik
 */
public class SimpleDelegateProvider<T extends UpdatableEntity> implements DelegateProvider<T> {

    private final T delegate;

    public SimpleDelegateProvider(T delegate) {
        this.delegate = delegate;
    }

    @Override
    public T getDelegate(boolean isRead, Enum<? extends EntityField<T>> field, Object... parameters) {
        return this.delegate;
    }

    @Override
    public boolean isUpdated() {
        return this.delegate.isUpdated();
    }
}


text:
class Thing < ActiveRecord::Base

  attr_accessor :version
  acts_as_versioned

end


text:
package com.soundbite.gcharts.jackson;

import com.fasterxml.jackson.annotation.JsonValue;

public interface ColumnTypeMixin {
	@JsonValue String getValue();
}


text:
package instance

import (
	"time"

	"github.com/deckarep/golang-set"
	logutil "github.com/docker/infrakit/pkg/log"
	"github.com/docker/infrakit/pkg/spi/event"
	"github.com/docker/infrakit/pkg/spi/instance"
	"github.com/docker/infrakit/pkg/types"
)

var log = logutil.New("module", "util/event/instance")

const (
	eventType = event.Type("tracker")
)

// NewTracker returns an event plugin implementation that can generate events based on resources it trackers
func NewTracker(name string, plugin instance.Plugin, tick <-chan time.Time, tags map[string]string) *Tracker {
	m := &Tracker{
		poll:   tick,
		Plugin: plugin,
		Name:   name,
		tags:   tags,
	}
	return m.init()
}

// Tracker implements the event spi -- just just calls the Describe to get a
// list of known instances, and report anything it hasn't seen before, or
// if anything that disappeared.
type Tracker struct {
	stop   chan struct{}
	topics map[string]interface{}

	tags map[string]string

	// poll is the ticker for polling
	poll <-chan time.Time

	// Plugin is the instance plugin to use
	Plugin instance.Plugin

	// Name is the name of the plugin
	Name string
}

func (m *Tracker) getEndpoint() interface{} {
	return "redirect to endpoint (not implemented)"
}

// Init initializes the event plugin and starts working
func (m *Tracker) init() *Tracker {
	m.topics = map[string]interface{}{}
	m.stop = make(chan struct{})

	if m.poll == nil {
		m.poll = time.Tick(3 * time.Second)
	}

	for _, topic := range types.PathFromStrings(
		"found",
		"lost",
		"error",
	) {
		types.Put(topic, m.getEndpoint, m.topics)
	}
	return m
}

// Stop stops the Tracker
func (m *Tracker) Stop() {
	if m.stop != nil {
		close(m.stop)
	}
}

// List returns the nodes under the given topic
func (m *Tracker) List(topic types.Path) ([]string, error) {
	return types.List(topic, m.topics), nil
}

// PublishOn sets the channel to publish on
func (m *Tracker) PublishOn(events chan<- *event.Event) {
	go func() {

		c := events

		defer func() {
			if c != nil {
				close(c)
			}
		}()

		log.Info("Start trackering instances", "name", m.Name)

		instances := map[instance.ID]instance.Description{}
		last := mapset.NewSet()

	poll:
		for {
			select {
			case <-m.stop:
				m.stop = nil
				return

			case <-m.poll:

				described, err := m.Plugin.DescribeInstances(m.tags, false)
				if err != nil {
					log.Warn("Error describing instances", "name", m.Name, "err", err)
					c <- event.Event{
						Type: eventType,
						ID:   "error",
					}.Init().Now().WithTopic("error").WithDataMust(err)

					// Done here. skip to the next poll
					continue poll
				}

				current := mapset.NewSet()
				for _, f := range described {
					current.Add(f.ID)
					instances[f.ID] = f
				}

				lost := last.Difference(current)
				found := current.Difference(last)

				log.Debug("found", "list", found)
				log.Debug("lost", "list", lost)

				for v := range lost.Iter() {
					id := v.(instance.ID)
					c <- event.Event{
						Type: eventType,
						ID:   string(id),
					}.Init().Now().WithTopic("lost").WithDataMust(instances[id])

					log.Debug("sent lost", "id", id)
				}
				for v := range found.Iter() {
					id := v.(instance.ID)
					c <- event.Event{
						Type: eventType,
						ID:   string(id),
					}.Init().Now().WithTopic("found").WithDataMust(instances[id])

					log.Debug("sent found", "id", id)
				}

				log.Debug("current", "list", current)

				last = current

			}
		}
	}()
}


text:
package com.blazebit.persistence.integration.hibernate;

import com.blazebit.persistence.spi.DbmsDialect;
import com.blazebit.persistence.spi.DbmsLimitHandler;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.engine.spi.RowSelection;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Christian Beikov
 * @since 1.2.0
 */
public class Hibernate43LimitHandler implements LimitHandler {

    private final DbmsLimitHandler limitHandler;
    private final String sql;
    private final Integer limit;
    private final Integer offset;

    public Hibernate43LimitHandler(Dialect dialect, DbmsDialect dbmsDialect, String sql, RowSelection selection) {
        this.limitHandler = dbmsDialect.createLimitHandler();
        this.sql = sql;

        if (selection == null || selection.getMaxRows() == null || selection.getMaxRows().intValue() == Integer.MAX_VALUE) {
            this.limit = null;
        } else {
            this.limit = selection.getMaxRows();
        }
        if (selection == null || selection.getFirstRow() == null || selection.getFirstRow().intValue() < 1) {
            this.offset = null;
        } else {
            this.offset = selection.getFirstRow();
        }
    }

    @Override
    public boolean supportsLimit() {
        return limitHandler.supportsLimit();
    }

    @Override
    public boolean supportsLimitOffset() {
        return limitHandler.supportsLimitOffset();
    }

    @Override
    public String getProcessedSql() {
        return limitHandler.applySql(sql, false, limit, offset);
    }

    @Override
    public int bindLimitParametersAtStartOfQuery(PreparedStatement statement, int index) throws SQLException {
        return limitHandler.bindLimitParametersAtStartOfQuery(limit, offset, statement, index);
    }

    @Override
    public int bindLimitParametersAtEndOfQuery(PreparedStatement statement, int index) throws SQLException {
        return limitHandler.bindLimitParametersAtEndOfQuery(limit, offset, statement, index);
    }

    @Override
    public void setMaxRows(PreparedStatement statement) throws SQLException {
        limitHandler.setMaxRows(limit, offset, statement);
    }

}


text:
package org.terasology.network.internal;

import com.google.common.collect.Sets;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.config.Config;
import org.terasology.engine.EngineTime;
import org.terasology.engine.TerasologyConstants;
import org.terasology.engine.Time;
import org.terasology.engine.module.ModuleManager;
import org.terasology.engine.paths.PathManager;
import org.terasology.module.ModuleLoader;
import org.terasology.naming.Name;
import org.terasology.naming.Version;
import org.terasology.network.JoinStatus;
import org.terasology.protobuf.NetData;
import org.terasology.registry.CoreRegistry;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Locale;
import java.util.Set;

/**
 * @author Immortius
 */
public class ClientConnectionHandler extends SimpleChannelUpstreamHandler {

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

    private final JoinStatusImpl joinStatus;
    private NetworkSystemImpl networkSystem;
    private ServerImpl server;
    private ModuleManager moduleManager;

    private Set<String> missingModules = Sets.newHashSet();
    private NetData.ModuleDataHeader receivingModule;
    private Path tempModuleLocation;
    private BufferedOutputStream downloadingModule;
    private long lengthReceived;

    public ClientConnectionHandler(JoinStatusImpl joinStatus, NetworkSystemImpl networkSystem) {
        this.networkSystem = networkSystem;
        this.joinStatus = joinStatus;
        this.moduleManager = CoreRegistry.get(ModuleManager.class);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        NetData.NetMessage message = (NetData.NetMessage) e.getMessage();
        if (message.hasServerInfo()) {
            receivedServerInfo(ctx, message.getServerInfo());
        } else if (message.hasModuleDataHeader()) {
            receiveModuleStart(ctx, message.getModuleDataHeader());
        } else if (message.hasModuleData()) {
            receiveModule(ctx, message.getModuleData());
        } else if (message.hasJoinComplete()) {
            completeJoin(ctx, message.getJoinComplete());
        } else {
            logger.error("Received unexpected message");
        }
    }

    private void receiveModuleStart(ChannelHandlerContext channelHandlerContext, NetData.ModuleDataHeader moduleDataHeader) {
        if (receivingModule != null) {
            joinStatus.setErrorMessage("Module download error");
            channelHandlerContext.getChannel().close();
            return;
        }
        String moduleId = moduleDataHeader.getId();
        if (missingModules.remove(moduleId.toLowerCase(Locale.ENGLISH))) {
            if (moduleDataHeader.hasError()) {
                joinStatus.setErrorMessage("Module download error: " + moduleDataHeader.getError());
                channelHandlerContext.getChannel().close();
            } else {
                String sizeString = getSizeString(moduleDataHeader.getSize());
                joinStatus.setCurrentActivity("Downloading " + moduleDataHeader.getId() + ":" + moduleDataHeader.getVersion() + " (" + sizeString + ")");
                receivingModule = moduleDataHeader;
                lengthReceived = 0;
                try {
                    tempModuleLocation = Files.createTempFile("terasologyDownload", ".tmp");
                    tempModuleLocation.toFile().deleteOnExit();
                    downloadingModule = new BufferedOutputStream(Files.newOutputStream(tempModuleLocation, StandardOpenOption.WRITE));
                } catch (IOException e) {
                    logger.error("Failed to write received module", e);
                    joinStatus.setErrorMessage("Module download error");
                    channelHandlerContext.getChannel().close();
                }
            }
        } else {
            logger.error("Received unwanted module {}:{} from server", moduleDataHeader.getId(), moduleDataHeader.getVersion());
            joinStatus.setErrorMessage("Module download error");
            channelHandlerContext.getChannel().close();
        }
    }

    private String getSizeString(long size) {
        if (size < 1024) {
            return size + " bytes";
        } else if (size < 1048576) {
            return String.format("%.2f KB", (float) size / 1024);
        } else {
            return String.format("%.2f MB", (float) size / 1048576);
        }
    }

    private void receiveModule(ChannelHandlerContext channelHandlerContext, NetData.ModuleData moduleData) {
        if (receivingModule == null) {
            joinStatus.setErrorMessage("Module download error");
            channelHandlerContext.getChannel().close();
            return;
        }

        try {
            downloadingModule.write(moduleData.getModule().toByteArray());
            lengthReceived += moduleData.getModule().size();
            joinStatus.setCurrentProgress((float) lengthReceived / receivingModule.getSize());
            if (lengthReceived == receivingModule.getSize()) {
                // finished
                downloadingModule.close();
                String moduleName = String.format("%s-%s.jar", receivingModule.getId(), receivingModule.getVersion());
                Path finalPath = PathManager.getInstance().getHomeModPath().normalize().resolve(moduleName);
                if (finalPath.normalize().startsWith(PathManager.getInstance().getHomeModPath())) {
                    if (Files.exists(finalPath)) {
                        logger.error("File already exists at {}", finalPath);
                        joinStatus.setErrorMessage("Module download error");
                        channelHandlerContext.getChannel().close();
                        return;
                    }

                    Files.copy(tempModuleLocation, finalPath);
                    ModuleLoader loader = new ModuleLoader(moduleManager.getModuleMetadataReader());
                    loader.setModuleInfoPath(TerasologyConstants.MODULE_INFO_FILENAME);

                    moduleManager.getRegistry().add(loader.load(finalPath));
                    receivingModule = null;

                    if (missingModules.isEmpty()) {
                        sendJoin(channelHandlerContext);
                    }
                } else {
                    logger.error("Module rejected");
                    joinStatus.setErrorMessage("Module download error");
                    channelHandlerContext.getChannel().close();
                }
            }
        } catch (IOException e) {
            logger.error("Error saving module", e);
            joinStatus.setErrorMessage("Module download error");
            channelHandlerContext.getChannel().close();
        }
    }

    private void completeJoin(ChannelHandlerContext channelHandlerContext, NetData.JoinCompleteMessage joinComplete) {
        logger.info("Join complete received");
        server.setClientId(joinComplete.getClientId());

        channelHandlerContext.getPipeline().remove(this);
        channelHandlerContext.getPipeline().get(ClientHandler.class).joinComplete(server);
        joinStatus.setComplete();
    }

    private void receivedServerInfo(ChannelHandlerContext channelHandlerContext, NetData.ServerInfoMessage message) {
        logger.info("Received server info");
        ((EngineTime) CoreRegistry.get(Time.class)).setGameTime(message.getTime());
        this.server = new ServerImpl(networkSystem, channelHandlerContext.getChannel());
        server.setServerInfo(message);

        // Request missing modules
        for (NetData.ModuleInfo info : message.getModuleList()) {
            if (null == moduleManager.getRegistry().getModule(new Name(info.getModuleId()), new Version(info.getModuleVersion()))) {
                missingModules.add(info.getModuleId().toLowerCase(Locale.ENGLISH));
            }
        }

        if (missingModules.isEmpty()) {
            joinStatus.setCurrentActivity("Finalizing join");
            sendJoin(channelHandlerContext);
        } else {
            joinStatus.setCurrentActivity("Requesting missing modules");
            NetData.NetMessage.Builder builder = NetData.NetMessage.newBuilder();
            for (String module : missingModules) {
                builder.addModuleRequest(NetData.ModuleRequest.newBuilder().setModuleId(module));
            }
            channelHandlerContext.getChannel().write(builder.build());
        }
    }

    private void sendJoin(ChannelHandlerContext channelHandlerContext) {
        Config config = CoreRegistry.get(Config.class);
        NetData.JoinMessage.Builder bldr = NetData.JoinMessage.newBuilder();
        NetData.Color.Builder clrbldr = NetData.Color.newBuilder();

        bldr.setName(config.getPlayer().getName());
        bldr.setViewDistanceLevel(config.getRendering().getViewDistance().getIndex());
        bldr.setColor(clrbldr.setRgba(config.getPlayer().getColor().rgba()).build());

        channelHandlerContext.getChannel().write(NetData.NetMessage.newBuilder().setJoin(bldr).build());
    }

    public JoinStatus getJoinStatus() {
        return joinStatus;
    }
}


text:
//
//  EGBasicViewController.m
//  Widgets
//
//  Created by EG on 2017/8/4.
//  Copyright © 2017年 EGMade. All rights reserved.
//

#import "EGBasicViewController.h"

@interface EGBasicViewController ()

@end

@implementation EGBasicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.title == nil) {
        self.title = NSStringFromClass(self.class);
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package acceptance

import (
	gosql "database/sql"
	"errors"
	"fmt"
	"math/rand"

	"golang.org/x/net/context"

	"github.com/cockroachdb/cockroach/pkg/acceptance/cluster"
	"github.com/cockroachdb/cockroach/pkg/base"
	"github.com/cockroachdb/cockroach/pkg/testutils"
	"github.com/cockroachdb/cockroach/pkg/util/log"
	"github.com/cockroachdb/cockroach/pkg/util/stop"
	"github.com/cockroachdb/cockroach/pkg/util/syncutil"
)

// dynamicClient should be used in acceptance tests when connecting to a
// cluster that may lose and gain nodes as the test proceeds.
type dynamicClient struct {
	cluster cluster.Cluster
	stopper *stop.Stopper

	mu struct {
		syncutil.Mutex
		// clients is a map from node indexes used by methods passed to the
		// cluster `c` to db clients.
		clients map[int]*gosql.DB
	}
}

// newDyanmicClient creates a dynamic client. `close()` must be called after
// the dynamic client is no longer needed.
func newDynamicClient(cluster cluster.Cluster, stopper *stop.Stopper) *dynamicClient {
	dc := &dynamicClient{
		cluster: cluster,
		stopper: stopper,
	}
	dc.mu.clients = make(map[int]*gosql.DB)
	return dc
}

// Close closes all connected database clients. Close implements the Closer
// interface.
func (dc *dynamicClient) Close() {
	dc.mu.Lock()
	defer dc.mu.Unlock()
	for i, client := range dc.mu.clients {
		log.Infof(context.TODO(), "closing connection to %s", dc.cluster.Addr(i, base.DefaultPort))
		client.Close()
		delete(dc.mu.clients, i)
	}
}

var errTestFinished = errors.New("test is shutting down")

// exec calls exec on a client using a preexisting or new connection.
func (dc *dynamicClient) exec(query string, args ...interface{}) (gosql.Result, error) {
	for dc.isRunning() {
		client, err := dc.getClient()
		if err != nil {
			return nil, err
		}
		if result, err := client.Exec(
			query, args...,
		); err == nil || !testutils.IsSQLRetryError(err) {
			return result, err
		}
	}
	return nil, errTestFinished
}

// queryRowScan performs first a QueryRow and follows that up with a Scan using
// a preexisting or new connection.
func (dc *dynamicClient) queryRowScan(query string, queryArgs, destArgs []interface{}) error {
	for dc.isRunning() {
		client, err := dc.getClient()
		if err != nil {
			return err
		}
		if err := client.QueryRow(
			query, queryArgs...,
		).Scan(destArgs...); err == nil || !testutils.IsSQLRetryError(err) {
			return err
		}
	}
	return errTestFinished
}

// getClient returns open client to a random node from the cluster.
func (dc *dynamicClient) getClient() (*gosql.DB, error) {
	dc.mu.Lock()
	defer dc.mu.Unlock()

	indexes := rand.Perm(dc.cluster.NumNodes())
	for _, index := range indexes {
		if client, ok := dc.mu.clients[index]; ok {
			return client, nil
		}
		client, err := gosql.Open("postgres", dc.cluster.PGUrl(index))
		if err != nil {
			log.Infof(context.TODO(), "could not establish connection to %s: %s", dc.cluster.Addr(index, base.DefaultPort), err)
			continue
		}
		log.Infof(context.TODO(), "connection established to %s",
			dc.cluster.Addr(index, base.DefaultPort))
		dc.mu.clients[index] = client
		return client, nil
	}

	// If we find that we end up having no connections often, consider putting
	// in a retry loop for this whole function.
	return nil, fmt.Errorf("there are no available connections to the cluster")
}

// isRunning returns true as long as the stopper is still running.
func (dc *dynamicClient) isRunning() bool {
	select {
	case <-dc.stopper.ShouldStop():
		return false
	default:
	}
	return true
}


text:
package org.apache.sling.resourceresolver.impl.providers;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.runtime.RuntimeService;
import org.apache.sling.api.resource.runtime.dto.RuntimeDTO;

@Component
@Service(value = RuntimeService.class)
public class RuntimeServiceImpl implements RuntimeService {

    @Reference
    private ResourceProviderTracker tracker;

    @Override
    public RuntimeDTO getRuntimeDTO() {
        final RuntimeDTO dto = new RuntimeDTO();
        tracker.fill(dto);
        return dto;
    }
}


text:
package servicebroker

import (
	"fmt"

	"k8s.io/apimachinery/pkg/util/validation/field"

	templatevalidation "github.com/openshift/origin/pkg/template/apis/template/validation"
	"github.com/openshift/origin/pkg/templateservicebroker/openservicebroker/api"
)

// ValidateProvisionRequest ensures that a ProvisionRequest is valid, beyond
// the validation carried out by the service broker framework itself.
func ValidateProvisionRequest(preq *api.ProvisionRequest) field.ErrorList {
	var allErrs field.ErrorList

	for key := range preq.Parameters {
		if !templatevalidation.ParameterNameRegexp.MatchString(key) {
			allErrs = append(allErrs, field.Invalid(field.NewPath("parameters", key), key, fmt.Sprintf("does not match %v", templatevalidation.ParameterNameRegexp)))
		}
	}

	return allErrs
}

// ValidateBindRequest ensures that a BindRequest is valid, beyond the
// validation carried out by the service broker framework itself.
func ValidateBindRequest(breq *api.BindRequest) field.ErrorList {
	var allErrs field.ErrorList

	for key := range breq.Parameters {
		if !templatevalidation.ParameterNameRegexp.MatchString(key) {
			allErrs = append(allErrs, field.Invalid(field.NewPath("parameters."+key), key, fmt.Sprintf("does not match %v", templatevalidation.ParameterNameRegexp)))
		}
	}

	return allErrs
}


text:
import json
import abc

import jsonschema
import requests

from rest_tester.setting import ParameterSet, TestMethod, UnsupportedMethodError
from rest_tester.utils import convert_to_list

class TestFunction(object):
    """Contains test function and its name"""
    def __init__(self, name, test_function):
        self._name = name
        self._test_function = test_function

    @property
    def name(self):
        return self._name

    @property
    def test_function(self):
        return self._test_function

class TestFunctionBuilderFactory(object):
    @staticmethod
    def get_builder(setting):
        if setting.has_multiple_targets():
            from .multiple import MultipleTargetsTestFunctionBuilder
            return MultipleTargetsTestFunctionBuilder(setting)

        else:
            from .single import SingleTargetTestFunctionBuilder
            return SingleTargetTestFunctionBuilder(setting)

class TestFunctionBuilder(object):
    """Build test functions"""
    __metaclass__ = abc.ABCMeta

    @staticmethod
    def _run_tests(self, tests, response):
        if tests.status_code:
            self.assertIn(
                    response.status_code,
                    convert_to_list(tests.status_code),
                    'Unexpected status code.'
            )

        if tests.json_schema:
            jsonschema.validate(
                    response.json(),
                    tests.json_schema
            )

    def _build_test_function(self, name, api, tests):
        def test_function(test_self):
            param_set_list = ParameterSet.generate(api.params)
            for param_set in param_set_list:
                timeout = tests.timeout
                response = self._get_response(api, param_set, timeout)

                response_time = response.elapsed.total_seconds()
                print(name + ' takes ' + str(round(response_time, 4)) + ' seconds.')

                self._run_tests(test_self, tests, response)

        return test_function

    def _get_response(self, api, params, timeout):
        settings = {
            'timeout': timeout,
            'auth': api.auth,
            'verify': not api.insecure,
            'headers': {'Content-Type': 'application/json'},
        }

        data = json.dumps(api.data) if api.data else None

        return self._send_request(method=api.method, url=api.url, params=params, data=data, **settings)

    @staticmethod
    def _send_request(method, url, params, data, **settings):
        if method == TestMethod.GET:
            return requests.get(url=url, params=params, **settings)
        elif method == TestMethod.PUT:
            return requests.put(url=url, data=data, **settings)
        elif method == TestMethod.POST:
            return requests.post(url=url, data=data, **settings)
        elif method == TestMethod.PATCH:
            return requests.patch(url=url, data=data, **settings)
        elif method == TestMethod.DELETE:
            return requests.delete(url=url, **settings)
        else:
            raise UnsupportedMethodError('Unsupported method: %s' % method)

    @staticmethod
    def _generate_name(api):
        """Test function name should start with 'test' since we use unit test."""
        param_str = '&'.join([key + "=" + str(value) for key, value in api.params.items()])
        if param_str != '':
            param_str = '?' + param_str

        return 'test_%s%s' % (api.url, param_str)

    @abc.abstractmethod
    def build(self):
        raise NotImplementedError


text:
package gosnowflake

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"
	"strings"
)

type localUtil struct {
}

func (util *localUtil) createClient(_ *execResponseStageInfo, _ bool) (cloudClient, error) {
	return nil, nil
}

func (util *localUtil) uploadOneFileWithRetry(meta *fileMetadata) error {
	var frd *bufio.Reader
	if meta.srcStream != nil {
		b := meta.srcStream
		if meta.realSrcStream != nil {
			b = meta.realSrcStream
		}
		frd = bufio.NewReader(b)
	} else {
		f, err := os.Open(meta.realSrcFileName)
		if err != nil {
			return err
		}
		defer f.Close()
		frd = bufio.NewReader(f)
	}

	user, err := expandUser(meta.stageInfo.Location)
	if err != nil {
		return err
	}
	if !meta.overwrite {
		if _, err := os.Stat(filepath.Join(user, meta.dstFileName)); err == nil {
			meta.dstFileSize = 0
			meta.resStatus = skipped
			return nil
		}
	}
	output, err := os.OpenFile(filepath.Join(user, meta.dstFileName), os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		return err
	}
	defer output.Close()
	data := make([]byte, meta.uploadSize)
	for {
		n, err := frd.Read(data)
		if err != nil && err != io.EOF {
			return err
		}
		if n == 0 {
			break
		}

		if _, err = output.Write(data); err != nil {
			return err
		}
	}
	meta.dstFileSize = meta.uploadSize
	meta.resStatus = uploaded
	return nil
}

func (util *localUtil) downloadOneFile(meta *fileMetadata) error {
	srcFileName := meta.srcFileName
	if strings.HasPrefix(meta.srcFileName, fmt.Sprintf("%b", os.PathSeparator)) {
		srcFileName = srcFileName[1:]
	}
	user, err := expandUser(meta.stageInfo.Location)
	if err != nil {
		return err
	}
	fullSrcFileName := path.Join(user, srcFileName)
	user, err = expandUser(meta.localLocation)
	if err != nil {
		return err
	}
	fullDstFileName := path.Join(user, baseName(meta.dstFileName))
	baseDir, err := getDirectory()
	if err != nil {
		return err
	}
	if _, err = os.Stat(baseDir); os.IsNotExist(err) {
		if err = os.MkdirAll(baseDir, os.ModePerm); err != nil {
			return err
		}
	}

	data, err := os.ReadFile(fullSrcFileName)
	if err != nil {
		return err
	}
	if err = os.WriteFile(fullDstFileName, data, os.ModePerm); err != nil {
		return err
	}
	fi, err := os.Stat(fullDstFileName)
	if err != nil {
		return err
	}
	meta.dstFileSize = fi.Size()
	meta.resStatus = downloaded
	return nil
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DocLinkButton.cs" company="Exit Games GmbH">
//   Part of: Pun demos
// </copyright>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------

using Photon.Pun.Demo.Shared;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Photon.Pun.Demo.Cockpit
{
    /// <summary>
    /// Open an Url on Pointer Click.
    /// </summary>
    public class DocLinkButton : MonoBehaviour, IPointerClickHandler
    {
		public DocLinks.DocTypes Type = DocLinks.DocTypes.Doc;

        public string Reference = "getting-started/pun-intro";

		// Just so that Unity expose the enable Check Box inside the Component Inspector Header.
		public void Start(){}

        //Detect if a click occurs
        public void OnPointerClick(PointerEventData pointerEventData)
        {
			Application.OpenURL(DocLinks.GetLink(Type,Reference));
        }
    }
}