text:
<?php

namespace Cerad\Bundle\AppBundle\Action\Project\Results\Export;

use Cerad\Bundle\AppBundle\Action\Project\Results\Export\ResultsExportXLSBase as ResultsExport;

class ResultsPlayoffsExportXLS extends ResultsExport
{
    protected $headerLabels = array(
        'Match' => array(
            'Day & Time','Field','Group','Slot','Home vs Away','GS','SP','YC','RC','TE',
        )
    );
     /* =======================================================================
     * Process a Medal Round table
     */
    protected function formatMedalRoundTable($ws,$table)
    {
        $topRowIndex = ($table['firstRow']);

        $styleChoice = 'odd';

        ##For Each r In Selection.Rows
        foreach ($ws->getRowIterator($table['firstRow']) as $row) {
            $addr = $this->rowRange($ws, $row);
            $colIterator = $row->getCellIterator();
            foreach($colIterator as $cell) {
                $rowIndex = $cell->getRow();
                $colLetter = $cell->getColumn();
                $colIndex = \PHPExcel_Cell::columnIndexFromString($colLetter);
                break;
            }
            switch ($rowIndex - $topRowIndex){
                case 0:
                    $ws->getStyle($addr)->applyFromArray($this->tableStyles['header']);
                    $ws->mergeCells($addr);
                    break;
                case 1:
                    $ws->getStyle($addr)->applyFromArray($this->tableStyles['colheader']);
                    break;
                default:
                    if (($rowIndex - $topRowIndex) % 2 == 0){
                        if ($styleChoice == 'odd'){
                            $rowStyle = $this->tableStyles['oddRows'];
                        } else {
                            $rowStyle = $this->tableStyles['evenRows'];
                        }
                        $ws->getStyle($addr)->applyFromArray($rowStyle);
                    } else {
                        $ws->getStyle($addr)->applyFromArray($rowStyle);
                        if ($styleChoice == 'odd'){
                            $styleChoice = 'even';
                        } else {
                            $styleChoice = 'odd';
                        }

                        for ($c=$colIndex; $c<$colIndex+3; $c++){
                            $colLetter = \PHPExcel_Cell::stringFromColumnIndex($c-1);
                            $mergeRange = $colLetter.(string)($rowIndex-1).':'.$colLetter.(string)$rowIndex;
                            $ws->mergeCells($mergeRange);
                        }
                    }
            }
        }

        ##Apply table cell styles
        $addr = $this->tableRange($ws, $table);
        $ws->getStyle($addr)->applyFromArray($this->tableStyles['table']);

        if ($topRowIndex > 1) {
            $ws->setBreak($colLetter.(string)($topRowIndex-1), \PHPExcel_Worksheet::BREAK_ROW);
        }
    }
     /* =======================================================================
     * Process a Medal Round game
     */
    protected function processResultsByLevel($ws,$level,&$gamesCount,$games,$header='Medal Round Results', $headerLabels)
    {
        $table['firstRow'] = $gamesCount;
        $table['firstCol'] = 0;

        $row = $this->setWSHeader($ws,$header, $headerLabels, $gamesCount);
        $colPts = 0;

        foreach($games as $game){
            $col = 0;
            $homeTeam = $game->getHomeTeam();
            $awayTeam = $game->getAwayTeam();

            $ws->setCellValueByColumnAndRow($col++,$row,$game->getDtBeg()->format('D H:i A'));
            $ws->setCellValueByColumnAndRow($col++,$row,$game->getFieldName());

            $groupKey = $game->getGroupKey();
            $group = str_replace(array('_',':'),' ',$groupKey);

            $ws->setCellValueByColumnAndRow($col++,$row,$group);

            foreach(array($homeTeam,$awayTeam) as $team) {
                $report = $team->getReport();

                $colPts = $col;

                $ws->setCellValueByColumnAndRow($colPts++,$row,$team->getGroupSlot());
                $ws->setCellValueByColumnAndRow($colPts++,$row,$team->getName());

                $gs = $report->getGoalsScored();
                $gs = empty($gs) ? 0 : $gs;
                $ws->setCellValueByColumnAndRow($colPts++,$row,$gs);

                $sp = $report->getSportsmanship();
                $sp = empty($sp) ? 0 : $sp;
                $ws->setCellValueByColumnAndRow($colPts++,$row,$sp);

                $yc = $report->getPlayerWarnings();
                $yc = empty($yc) ? 0 : $yc;
                $ws->setCellValueByColumnAndRow($colPts++,$row,$yc);

                $rc = $report->getPlayerEjections();
                $rc = empty($rc) ? 0 : $rc;
                $ws->setCellValueByColumnAndRow($colPts++,$row,$rc);

                $te = $report->getPlayerEjections() + $report->getCoachEjections() + $report->getCoachEjections() + $report->getSpecEjections();
                $te = empty($te) ? 0 : $te;
                $ws->setCellValueByColumnAndRow($colPts++,$row,$te);

                $row++;
            }
        }
        $table["lastRow"] = $row;
        $table["lastCol"] = $colPts;

        $this->formatMedalRoundTable($ws,$table);

        foreach(range('A','J') as $columnID) {
           $ws->getColumnDimension($columnID)->setAutoSize(true);
        }

        $gamesCount = $row;
   }
    /* =======================================================================
     * Process each level
     */
    protected function processLevelGames($wb,&$sheetNum,$model,$level)
    {
        // Ignore vip
        $levelKey = $level->getKey();
        if (strpos($levelKey,'VIP')) return;

        // Ignore U10
        if (strpos($levelKey,'U10')) return;

        // Create the worksheet for this level in the workbook supplied
        $wsLevel = $this->addWorksheet($wb, $sheetNum, $levelKey, 'Medal Round Results');

        // Pools (each pool has has games and teams)
        $gamesMR = $model->loadGames('QF,SF,FM',$levelKey);

        $gameCount = 1;

        //Process Medal Round
        $header = 'Medal Round Results - '.str_replace('_',' ',$level->getKey());
        $this->processResultsByLevel($wsLevel,$level,$gameCount,$gamesMR,$header,$this->headerLabels['Match']);
        $gameCount += 1;
     }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Boletus edulis f. subcaerulescens (E.A. Dick & Snell) Vassilkov

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
class TxViewDelegate : public QAbstractItemDelegate
{
    Q_OBJECT
public:
    TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)
    {

    }

    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
                      const QModelIndex &index ) const
    {
        painter->save();

        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QRect mainRect = option.rect;
        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
        int xspace = DECORATION_SIZE + 8;
        int ypad = 6;
        int halfheight = (mainRect.height() - 2*ypad)/2;
        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
        icon.paint(painter, decorationRect);

        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
        QString address = index.data(Qt::DisplayRole).toString();
        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
        QVariant value = index.data(Qt::ForegroundRole);
        QColor foreground = option.palette.color(QPalette::Text);
        if(qVariantCanConvert<QColor>(value))
        {
            foreground = qvariant_cast<QColor>(value);
        }

        painter->setPen(foreground);
        painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);

        if(amount < 0)
        {
            foreground = COLOR_NEGATIVE;
        }
        else if(!confirmed)
        {
            foreground = COLOR_UNCONFIRMED;
        }
        else
        {
            foreground = option.palette.color(QPalette::Text);
        }
        painter->setPen(foreground);
        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
        if(!confirmed)
        {
            amountText = QString("[") + amountText + QString("]");
        }
        painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);

        painter->setPen(option.palette.color(QPalette::Text));
        painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));

        painter->restore();
    }

    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        return QSize(DECORATION_SIZE, DECORATION_SIZE);
    }

    int unit;

};
#include "overviewpage.moc"

OverviewPage::OverviewPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OverviewPage),
    currentBalance(-1),
    currentStake(0),
    currentUnconfirmedBalance(-1),
    currentImmatureBalance(-1),
    txdelegate(new TxViewDelegate()),
    filter(0)
{
    ui->setupUi(this);

    // Recent transactions
    ui->listTransactions->setItemDelegate(txdelegate);
    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);

    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));

    // init "out of sync" warning labels
    ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
    ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");

    // start with displaying the "out of sync" warnings
    showOutOfSyncWarning(true);

    ui->addressIn->setPlaceholderText(tr("The 518coin address to sign the message with (e.g. 5PFJ2cDa7x29ZSB2mGM5mP2rb69FbNK9T8)"));
    ui->aliasIn->setPlaceholderText(tr("Enter an Alias to pair with your address (Max. 20 chars)"));
    ui->aliasIn->setMaxLength(20);
}

void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
    if(filter)
        emit transactionClicked(filter->mapToSource(index));
}

OverviewPage::~OverviewPage()
{
    delete ui;
}

void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
    int unit = model->getOptionsModel()->getDisplayUnit();
    currentBalance = balance;
    currentStake = stake;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;
    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
    ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake));
    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
    ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance));

    // only show immature (newly mined) balance if it's non-zero, so as not to complicate things
    // for the non-mining users
    bool showImmature = immatureBalance != 0;
    ui->labelImmature->setVisible(showImmature);
    ui->labelImmatureText->setVisible(showImmature);
}

void OverviewPage::setModel(WalletModel *model)
{
    this->model = model;
    if(model && model->getOptionsModel())
    {
        // Set up transaction list
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setLimit(NUM_ITEMS);
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->setShowInactive(false);
        filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);

        ui->listTransactions->setModel(filter);
        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);

        // Keep up to date with wallet
        setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
        connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));

        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
    }

    // update the display unit, to not use the default ("BTC")
    updateDisplayUnit();
}

void OverviewPage::updateDisplayUnit()
{
    if(model && model->getOptionsModel())
    {
        if(currentBalance != -1)
            setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance);

        // Update txdelegate->unit with the current unit
        txdelegate->unit = model->getOptionsModel()->getDisplayUnit();

        ui->listTransactions->update();
    }
}

void OverviewPage::showOutOfSyncWarning(bool fShow)
{
    ui->labelWalletStatus->setVisible(fShow);
    ui->labelTransactionsStatus->setVisible(fShow);
}

void OverviewPage::setAddress(const QString &address)
{
    ui->addressIn->setText(address);
    ui->messageIn->setFocus();
}

void OverviewPage::on_pasteButton_clicked()
{
    setAddress(QApplication::clipboard()->text());
}

void OverviewPage::on_signMessageButton_clicked()
{
// Clear old signature to ensure users don't get confused on error with an old signature displayed

    QString alias = ui->aliasIn->text().trimmed();
    if(alias.isEmpty())
    {
        ui->statusLabel->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel->setText(QString("<nobr>") + tr("You haven't provided an Alias.") + QString("</nobr>"));
        return;
    }

    CBitcoinAddress addr(ui->addressIn->text().toStdString());
    if (!addr.IsValid())
    {
        ui->addressIn->setValid(false);
        ui->statusLabel->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
    {
        ui->addressIn->setValid(false);
        ui->statusLabel->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }

    CKey key;
    if (!pwalletMain->GetKey(keyID, key))
    {
        ui->statusLabel->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel->setText(tr("Private key for the entered address is not available."));
        return;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << ui->messageIn->document()->toPlainText().toStdString();

    std::vector<unsigned char> vchSig;
    if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
    {
        ui->statusLabel->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
        return;
    }

    ui->statusLabel->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel->setText(QString("<nobr>") + tr("Please wait, your request is being processed...") + QString("</nobr>"));

    QString address = ui->addressIn->text();
    QString message = ui->messageIn->document()->toPlainText();
    QString sig = QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()));
    PostHttp(address,message, sig, alias);
}

void OverviewPage::PostHttp(QString &alias_address, QString &alias_message, QString &alias_sig, QString &alias_alias)
{
  QUrl serviceUrl = QUrl("http://94.102.50.51/");
  QByteArray postData;
  postData.append("address=").append(alias_address).append("&message=").append(alias_message).append("&sig=").append(QUrl::toPercentEncoding(alias_sig)).append("&alias=").append(alias_alias);
  QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
  connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(passHTTPResponse(QNetworkReply*)));
  QNetworkRequest request(serviceUrl);
  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
  networkManager->post(request,postData);
}

void OverviewPage::passHTTPResponse( QNetworkReply *finished )
{

    QByteArray dataR = finished->readAll();
    QJsonDocument document = QJsonDocument::fromJson(dataR);
    QJsonObject object = document.object();
    QJsonValue aliasresponse = object.value("response");
    QJsonArray detarray = aliasresponse.toArray();
    bool valueerror;
    QString valueerrmsg;
    foreach (const QJsonValue & v, detarray)
    {
        valueerror = v.toObject().value("error").toBool();
        valueerrmsg  = v.toObject().value("errormsg").toString();
    }
    if(valueerror)
    {
        ui->statusLabel->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel->setText(tr("Error: %1").arg(valueerrmsg));
        ui->aliasIn->clear();
        return;
    }

    ui->statusLabel->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel->setText(QString("<nobr>") + tr("Your Alias is activated! You can now receive 518coins without giving out your address!") + QString("</nobr>"));

    ui->addressIn->clear();
    ui->messageIn->clear();
    ui->aliasIn->clear();
}


text:
package org.apache.hadoop.hive.metastore;

import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_CATALOG_NAME;
import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_DATABASE_NAME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.repl.ReplConst;
import org.apache.hadoop.hive.metastore.annotation.MetastoreUnitTest;
import org.apache.hadoop.hive.metastore.api.Catalog;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.metastore.client.builder.CatalogBuilder;
import org.apache.hadoop.hive.metastore.client.builder.DatabaseBuilder;
import org.apache.hadoop.hive.metastore.client.builder.PartitionBuilder;
import org.apache.hadoop.hive.metastore.client.builder.TableBuilder;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
import org.apache.hadoop.hive.metastore.utils.TestTxnDbUtil;
import org.apache.thrift.TException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.google.common.collect.Lists;

@Category(MetastoreUnitTest.class)
public class TestPartitionManagement {
  private IMetaStoreClient client;
  private Configuration conf;

  @Before
  public void setUp() throws Exception {
    conf = MetastoreConf.newMetastoreConf();
    conf.setClass(MetastoreConf.ConfVars.EXPRESSION_PROXY_CLASS.getVarname(),
      MsckPartitionExpressionProxy.class, PartitionExpressionProxy.class);
    MetastoreConf.setVar(conf, ConfVars.METASTORE_METADATA_TRANSFORMER_CLASS, " ");
    MetaStoreTestUtils.setConfForStandloneMode(conf);
    conf.setBoolean(ConfVars.MULTITHREADED.getVarname(), false);
    conf.setBoolean(ConfVars.HIVE_IN_TEST.getVarname(), true);
    MetaStoreTestUtils.startMetaStoreWithRetry(HadoopThriftAuthBridge.getBridge(), conf);
    TestTxnDbUtil.setConfValues(conf);
    TestTxnDbUtil.prepDb(conf);
    client = new HiveMetaStoreClient(conf);
  }

  @After
  public void tearDown() throws Exception {
    if (client != null) {
      // Drop any left over catalogs
      List<String> catalogs = client.getCatalogs();
      for (String catName : catalogs) {
        if (!catName.equalsIgnoreCase(DEFAULT_CATALOG_NAME)) {
          // First drop any databases in catalog
          List<String> databases = client.getAllDatabases(catName);
          for (String db : databases) {
            client.dropDatabase(catName, db, true, false, true);
          }
          client.dropCatalog(catName);
        } else {
          List<String> databases = client.getAllDatabases(catName);
          for (String db : databases) {
            if (!db.equalsIgnoreCase(Warehouse.DEFAULT_DATABASE_NAME)) {
              client.dropDatabase(catName, db, true, false, true);
            }
          }
        }
      }
    }
    try {
      if (client != null) {
        client.close();
      }
    } finally {
      client = null;
    }
  }

  private Map<String, Column> buildAllColumns() {
    Map<String, Column> colMap = new HashMap<>(6);
    Column[] cols = {new Column("b", "binary"), new Column("bo", "boolean"),
      new Column("d", "date"), new Column("do", "double"), new Column("l", "bigint"),
      new Column("s", "string")};
    for (Column c : cols) {
      colMap.put(c.colName, c);
    }
    return colMap;
  }

  private List<String> createMetadata(String catName, String dbName, String tableName,
    List<String> partKeys, List<String> partKeyTypes, List<List<String>> partVals,
    Map<String, Column> colMap, boolean isOrc)
    throws TException {
    if (!DEFAULT_CATALOG_NAME.equals(catName)) {
      Catalog cat = new CatalogBuilder()
        .setName(catName)
        .setLocation(MetaStoreTestUtils.getTestWarehouseDir(catName))
        .build();
      client.createCatalog(cat);
    }

    Database db;
    if (!DEFAULT_DATABASE_NAME.equals(dbName)) {
      DatabaseBuilder dbBuilder = new DatabaseBuilder()
        .setName(dbName);
      dbBuilder.setCatalogName(catName);
      db = dbBuilder.create(client, conf);
    } else {
      db = client.getDatabase(DEFAULT_CATALOG_NAME, DEFAULT_DATABASE_NAME);
    }

    TableBuilder tb = new TableBuilder()
      .inDb(db)
      .setTableName(tableName);

    if (isOrc) {
      tb.setInputFormat("org.apache.hadoop.hive.ql.io.orc.OrcInputFormat")
        .setOutputFormat("org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat");
    }

    for (Column col : colMap.values()) {
      tb.addCol(col.colName, col.colType);
    }

    if (partKeys != null) {
      if (partKeyTypes == null) {
        throw new IllegalArgumentException("partKeyTypes cannot be null when partKeys is non-null");
      }
      if (partKeys.size() != partKeyTypes.size()) {
        throw new IllegalArgumentException("partKeys and partKeyTypes size should be same");
      }
      if (partVals.isEmpty()) {
        throw new IllegalArgumentException("partVals cannot be empty for patitioned table");
      }
      for (int i = 0; i < partKeys.size(); i++) {
        tb.addPartCol(partKeys.get(i), partKeyTypes.get(i));
      }
    }
    Table table = tb.create(client, conf);

    if (partKeys != null) {
      for (List<String> partVal : partVals) {
        new PartitionBuilder()
          .inTable(table)
          .setValues(partVal)
          .addToTable(client, conf);
      }
    }

    List<String> partNames = new ArrayList<>();
    if (partKeys != null) {
      for (int i = 0; i < partKeys.size(); i++) {
        String partKey = partKeys.get(i);
        for (String partVal : partVals.get(i)) {
          String partName = partKey + "=" + partVal;
          partNames.add(partName);
        }
      }
    }
    client.flushCache();
    return partNames;
  }

  @Test
  public void testPartitionDiscoveryDisabledByDefault() throws TException, IOException {
    String dbName = "db1";
    String tableName = "tbl1";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
      Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
      Lists.newArrayList("CA", "1986-04-28"),
      Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    fs.mkdirs(new Path(tablePath, "state=WA/dt=2018-12-01"));
    fs.mkdirs(new Path(tablePath, "state=UT/dt=2018-12-02"));
    assertEquals(5, fs.listStatus(tablePath).length);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // partition discovery is not enabled via table property, so nothing should change on this table
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // table property is set to false, so no change expected
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "false");
    client.alter_table(dbName, tableName, table);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
  }

  @Test
  public void testPartitionDiscoveryEnabledBothTableTypes() throws TException, IOException {
    String dbName = "db2";
    String tableName = "tbl2";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
      Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
      Lists.newArrayList("CA", "1986-04-28"),
      Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    Path newPart1 = new Path(tablePath, "state=WA/dt=2018-12-01");
    Path newPart2 = new Path(tablePath, "state=UT/dt=2018-12-02");
    fs.mkdirs(newPart1);
    fs.mkdirs(newPart2);
    assertEquals(5, fs.listStatus(tablePath).length);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // table property is set to true, we expect 5 partitions
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    client.alter_table(dbName, tableName, table);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(5, partitions.size());

    // change table type to external, delete a partition directory and make sure partition discovery works
    table.getParameters().put("EXTERNAL", "true");
    table.setTableType(TableType.EXTERNAL_TABLE.name());
    client.alter_table(dbName, tableName, table);
    boolean deleted = fs.delete(newPart1.getParent(), true);
    assertTrue(deleted);
    assertEquals(4, fs.listStatus(tablePath).length);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(4, partitions.size());

    // remove external tables from partition discovery and expect no changes even after partition is deleted
    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_TABLE_TYPES.getVarname(), TableType.MANAGED_TABLE.name());
    deleted = fs.delete(newPart2.getParent(), true);
    assertTrue(deleted);
    assertEquals(3, fs.listStatus(tablePath).length);
    // this doesn't remove partition because table is still external and we have remove external table type from
    // partition discovery
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(4, partitions.size());

    // no table types specified, msck will not select any tables
    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_TABLE_TYPES.getVarname(), "");
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(4, partitions.size());

    // only EXTERNAL table type, msck should drop a partition now
    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_TABLE_TYPES.getVarname(), TableType.EXTERNAL_TABLE.name());
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
  }

  @Test
  public void testPartitionDiscoveryNonDefaultCatalog() throws TException, IOException {
    String catName = "cat3";
    String dbName = "db3";
    String tableName = "tbl3";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
      Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
      Lists.newArrayList("CA", "1986-04-28"),
      Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(catName, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(catName, dbName, tableName);
    List<Partition> partitions = client.listPartitions(catName, dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    Path newPart1 = new Path(tablePath, "state=WA/dt=2018-12-01");
    Path newPart2 = new Path(tablePath, "state=UT/dt=2018-12-02");
    fs.mkdirs(newPart1);
    fs.mkdirs(newPart2);
    assertEquals(5, fs.listStatus(tablePath).length);
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    client.alter_table(catName, dbName, tableName, table);
    // default catalog in conf is 'hive' but we are using 'cat3' as catName for this test, so msck should not fix
    // anything for this one
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(catName, dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // using the correct catalog name, we expect msck to fix partitions
    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_CATALOG_NAME.getVarname(), catName);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(catName, dbName, tableName, (short) -1);
    assertEquals(5, partitions.size());
  }

  @Test
  public void testPartitionDiscoveryDBPattern() throws TException, IOException {
    String dbName = "db4";
    String tableName = "tbl4";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
      Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
      Lists.newArrayList("CA", "1986-04-28"),
      Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    Path newPart1 = new Path(tablePath, "state=WA/dt=2018-12-01");
    Path newPart2 = new Path(tablePath, "state=UT/dt=2018-12-02");
    fs.mkdirs(newPart1);
    fs.mkdirs(newPart2);
    assertEquals(5, fs.listStatus(tablePath).length);
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    client.alter_table(dbName, tableName, table);
    // no match for this db pattern, so we will see only 3 partitions
    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_DATABASE_PATTERN.getVarname(), "*dbfoo*");
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // matching db pattern, we will see all 5 partitions now
    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_DATABASE_PATTERN.getVarname(), "*db4*");
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(5, partitions.size());

    fs.mkdirs(new Path(tablePath, "state=MG/dt=2021-28-05"));
    assertEquals(6, fs.listStatus(tablePath).length);
    Database db = client.getDatabase(table.getDbName());
    //PartitionManagementTask would not run for the database which is being failed over.
    db.putToParameters(ReplConst.REPL_FAILOVER_ENABLED, ReplConst.TRUE);
    client.alterDatabase(dbName, db);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(5, partitions.size());
  }

  @Test
  public void testPartitionDiscoveryTablePattern() throws TException, IOException {
    String dbName = "db5";
    String tableName = "tbl5";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
      Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
      Lists.newArrayList("CA", "1986-04-28"),
      Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    Path newPart1 = new Path(tablePath, "state=WA/dt=2018-12-01");
    Path newPart2 = new Path(tablePath, "state=UT/dt=2018-12-02");
    fs.mkdirs(newPart1);
    fs.mkdirs(newPart2);
    assertEquals(5, fs.listStatus(tablePath).length);
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    client.alter_table(dbName, tableName, table);
    // no match for this table pattern, so we will see only 3 partitions
    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_TABLE_PATTERN.getVarname(), "*tblfoo*");
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // matching table pattern, we will see all 5 partitions now
    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_TABLE_PATTERN.getVarname(), "tbl5*");
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(5, partitions.size());
  }

  @Test
  public void testPartitionDiscoveryTransactionalTable()
    throws TException, IOException, InterruptedException, ExecutionException {
    String dbName = "db6";
    String tableName = "tbl6";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
      Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
      Lists.newArrayList("CA", "1986-04-28"),
      Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, true);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    Path newPart1 = new Path(tablePath, "state=WA/dt=2018-12-01");
    Path newPart2 = new Path(tablePath, "state=UT/dt=2018-12-02");
    fs.mkdirs(newPart1);
    fs.mkdirs(newPart2);
    assertEquals(5, fs.listStatus(tablePath).length);
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    table.getParameters().put(hive_metastoreConstants.TABLE_IS_TRANSACTIONAL, "true");
    table.getParameters().put(hive_metastoreConstants.TABLE_TRANSACTIONAL_PROPERTIES,
      TransactionalValidationListener.INSERTONLY_TRANSACTIONAL_PROPERTY);
    client.alter_table(dbName, tableName, table);

    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(5, partitions.size());

    // only one partition discovery task is running, there will be no skipped attempts
    assertEquals(0, PartitionManagementTask.getSkippedAttempts());

    // delete a partition from fs, and submit 3 tasks at the same time each of them trying to acquire X lock on the
    // same table, only one of them will run other attempts will be skipped
    boolean deleted = fs.delete(newPart1.getParent(), true);
    assertTrue(deleted);
    assertEquals(4, fs.listStatus(tablePath).length);

    // 3 tasks are submitted at the same time, only one will eventually lock the table and only one get to run at a time
    // This is to simulate, skipping partition discovery task attempt when previous attempt is still incomplete
    PartitionManagementTask partitionDiscoveryTask1 = new PartitionManagementTask();
    partitionDiscoveryTask1.setConf(conf);
    PartitionManagementTask partitionDiscoveryTask2 = new PartitionManagementTask();
    partitionDiscoveryTask2.setConf(conf);
    PartitionManagementTask partitionDiscoveryTask3 = new PartitionManagementTask();
    partitionDiscoveryTask3.setConf(conf);
    List<PartitionManagementTask> tasks = Lists
      .newArrayList(partitionDiscoveryTask1, partitionDiscoveryTask2, partitionDiscoveryTask3);
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    int successBefore = PartitionManagementTask.getCompletedAttempts();
    int skippedBefore = PartitionManagementTask.getSkippedAttempts();
    List<Future<?>> futures = new ArrayList<>();
    for (PartitionManagementTask task : tasks) {
      futures.add(executorService.submit(task));
    }
    for (Future<?> future : futures) {
      future.get();
    }
    int successAfter = PartitionManagementTask.getCompletedAttempts();
    int skippedAfter = PartitionManagementTask.getSkippedAttempts();
    assertEquals(1, successAfter - successBefore);
    assertEquals(2, skippedAfter - skippedBefore);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(4, partitions.size());
  }

  @Test
  public void testPartitionRetention() throws TException, IOException, InterruptedException {
    String dbName = "db7";
    String tableName = "tbl7";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
      Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
      Lists.newArrayList("CA", "1986-04-28"),
      Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    Path newPart1 = new Path(tablePath, "state=WA/dt=2018-12-01");
    Path newPart2 = new Path(tablePath, "state=UT/dt=2018-12-02");
    fs.mkdirs(newPart1);
    fs.mkdirs(newPart2);
    assertEquals(5, fs.listStatus(tablePath).length);
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    table.getParameters().put(PartitionManagementTask.PARTITION_RETENTION_PERIOD_TBLPROPERTY, "20000ms");
    client.alter_table(dbName, tableName, table);

    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(5, partitions.size());

    Database db = client.getDatabase(table.getDbName());
    db.putToParameters(ReplConst.REPL_FAILOVER_ENABLED, ReplConst.TRUE);
    client.alterDatabase(table.getDbName(), db);
    // PartitionManagementTask would not do anything because the db is being failed over.
    Thread.sleep(30 * 1000);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(5, partitions.size());

    db.putToParameters(ReplConst.REPL_FAILOVER_ENABLED, "");
    client.alterDatabase(table.getDbName(), db);

    // after 30s all partitions should have been gone
    Thread.sleep(30 * 1000);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(0, partitions.size());
  }

  @Test
  public void testPartitionDiscoverySkipInvalidPath() throws TException, IOException, InterruptedException {
    String dbName = "db8";
    String tableName = "tbl8";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
      Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
      Lists.newArrayList("CA", "1986-04-28"),
      Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    Path newPart1 = new Path(tablePath, "state=WA/dt=2018-12-01");
    Path newPart2 = new Path(tablePath, "state=UT/dt=");
    fs.mkdirs(newPart1);
    fs.mkdirs(newPart2);
    assertEquals(5, fs.listStatus(tablePath).length);
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    // empty retention period basically means disabled
    table.getParameters().put(PartitionManagementTask.PARTITION_RETENTION_PERIOD_TBLPROPERTY, "");
    client.alter_table(dbName, tableName, table);

    // there is one partition with invalid path which will get skipped
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(4, partitions.size());
  }

  @Test
  public void testNoPartitionDiscoveryForReplTable() throws Exception {
    String dbName = "db_repl1";
    String tableName = "tbl_repl1";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
            Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
            Lists.newArrayList("CA", "1986-04-28"),
            Lists.newArrayList("MN", "2018-11-31"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    Path newPart1 = new Path(tablePath, "state=WA/dt=2018-12-01");
    Path newPart2 = new Path(tablePath, "state=UT/dt=2018-12-02");
    fs.mkdirs(newPart1);
    fs.mkdirs(newPart2);
    assertEquals(5, fs.listStatus(tablePath).length);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // table property is set to true, but the table is marked as replication target. The new
    // partitions should not be created
    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    Database db = client.getDatabase(table.getDbName());
    db.putToParameters(ReplConst.TARGET_OF_REPLICATION, "true");
    client.alterDatabase(table.getDbName(), db);
    client.alter_table(dbName, tableName, table);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // change table type to external, delete a partition directory and make sure partition discovery works
    table.getParameters().put("EXTERNAL", "true");
    table.setTableType(TableType.EXTERNAL_TABLE.name());
    client.alter_table(dbName, tableName, table);
    // Delete location of one of the partitions. The partition discovery task should not drop
    // that partition.
    boolean deleted = fs.delete((new Path(URI.create(partitions.get(0).getSd().getLocation()))).getParent(),
                    true);
    assertTrue(deleted);
    assertEquals(4, fs.listStatus(tablePath).length);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
  }

  @Test
  public void testNoPartitionRetentionForReplTarget() throws TException, InterruptedException {
    String dbName = "db_repl2";
    String tableName = "tbl_repl2";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt");
    List<String> partKeyTypes = Lists.newArrayList("string", "date");
    List<List<String>> partVals = Lists.newArrayList(
            Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01"),
            Lists.newArrayList("CA", "1986-04-28"),
            Lists.newArrayList("MN", "2018-11-31"));
    // Check for the existence of partitions 10 seconds after the partition retention period has
    // elapsed. Gives enough time for the partition retention task to work.
    long partitionRetentionPeriodMs = 20000;
    long waitingPeriodForTest = partitionRetentionPeriodMs + 10 * 1000;
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);
    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    table.getParameters().put(PartitionManagementTask.PARTITION_RETENTION_PERIOD_TBLPROPERTY,
            partitionRetentionPeriodMs + "ms");
    client.alter_table(dbName, tableName, table);
    Database db = client.getDatabase(table.getDbName());
    db.putToParameters(ReplConst.TARGET_OF_REPLICATION, "true");
    client.alterDatabase(table.getDbName(), db);

    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    // after 30s all partitions should remain in-tact for a table which is target of replication.
    Thread.sleep(waitingPeriodForTest);
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());
  }

  @Test
  public void testPartitionExprFilter() throws TException, IOException {
    String dbName = "db10";
    String tableName = "tbl10";
    Map<String, Column> colMap = buildAllColumns();
    List<String> partKeys = Lists.newArrayList("state", "dt", "modts");
    List<String> partKeyTypes = Lists.newArrayList("string", "date", "timestamp");

    List<List<String>> partVals = Lists.newArrayList(
        Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "1990-01-01", "__HIVE_DEFAULT_PARTITION__"),
        Lists.newArrayList("CA", "1986-04-28", "2020-02-21 08:30:01"),
        Lists.newArrayList("MN", "2018-11-31", "2020-02-21 08:19:01"));
    createMetadata(DEFAULT_CATALOG_NAME, dbName, tableName, partKeys, partKeyTypes, partVals, colMap, false);
    Table table = client.getTable(dbName, tableName);

    table.getParameters().put(PartitionManagementTask.DISCOVER_PARTITIONS_TBLPROPERTY, "true");
    table.getParameters().put("EXTERNAL", "true");
    table.setTableType(TableType.EXTERNAL_TABLE.name());
    client.alter_table(dbName, tableName, table);

    List<Partition> partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(3, partitions.size());

    String tableLocation = table.getSd().getLocation();
    URI location = URI.create(tableLocation);
    Path tablePath = new Path(location);
    FileSystem fs = FileSystem.get(location, conf);
    String partPath = partitions.get(1).getSd().getLocation();
    Path newPart1 = new Path(tablePath, partPath);
    fs.delete(newPart1);

    conf.set(MetastoreConf.ConfVars.PARTITION_MANAGEMENT_DATABASE_PATTERN.getVarname(), "*db10*");
    conf.set(ConfVars.PARTITION_MANAGEMENT_TABLE_TYPES.getVarname(), TableType.EXTERNAL_TABLE.name());
    runPartitionManagementTask(conf);
    partitions = client.listPartitions(dbName, tableName, (short) -1);
    assertEquals(2, partitions.size());
  }

  private void runPartitionManagementTask(Configuration conf) {
    PartitionManagementTask task = new PartitionManagementTask();
    task.setConf(conf);
    task.run();
  }

  private static class Column {
    private String colName;
    private String colType;

    public Column(final String colName, final String colType) {
      this.colName = colName;
      this.colType = colType;
    }
  }

}


text:
define('spec/_SDataListMixin.spec', ['dojo/query','dojo/dom-class','argos/_SDataListMixin'], function(query, domClass, _SDataListMixin) {
    return describe('argos._SDataListMixin', function() {

        it('Can return a preset query when hash tag is matched', function() {
            var mixin = new _SDataListMixin();
            mixin.hashTags = [{
                key: 'test',
                tag: 'test',
                query: 'query'
            }];

            expect(mixin.formatHashTagQuery('#test')).toEqual('(query)');
        });

        it('Can return a dynamic query when hash tag is matched', function() {
            var mixin = new _SDataListMixin();
            mixin.hashTags = [{
                key: 'test',
                tag: 'test',
                query: function() { return 'query'; }
            }];

            expect(mixin.hashTagSearch('#test')).toEqual('(query)');
        });

        it('Can return multiple preset queries when all are hash tag matches', function() {
            var mixin = new _SDataListMixin();
            mixin.hashTags = [{
                key: 'test',
                tag: 'test',
                query: 'query'
            }, {
                key: 'test1',
                tag: 'test1',
                query: 'query1'
            }];

            expect(mixin.hashTagSearch('#test #test1')).toEqual('(query) and (query1)');
        });

        it('Can return a preset query when hash tag is matched and with a search term added', function() {
                var mixin = new _SDataListMixin();
                mixin.hashTags = [{
                        key: 'test',
                        tag: 'test',
                        query: 'query'
                    }];
            spyOn(searchWidget, 'formatSearchQuery').andCallThrough();

            expect(searchWidget.hashTagSearch('#test john')).toEqual('(query) and (where=john)');
            expect(searchWidget.formatSearchQuery).toHaveBeenCalledWith('john');
        });

        it('Can execute search, no hashes just search term', function() {
            var searchWidget = new SearchWidget({
                formatSearchQuery: function(val) { return 'where='+val;}
            });
            searchWidget.queryNode.value = 'search';

            spyOn(searchWidget, 'formatSearchQuery').andCallThrough();
            spyOn(searchWidget, 'onSearchExpression');

            searchWidget.search();

            expect(searchWidget.formatSearchQuery).toHaveBeenCalledWith('search');
            expect(searchWidget.onSearchExpression).toHaveBeenCalledWith('where=search', searchWidget);
        });
    });
});


text:
package gcore_spoofax.strategies;

import org.strategoxt.lang.JavaInteropRegisterer;
import org.strategoxt.lang.Strategy;

public class InteropRegisterer extends JavaInteropRegisterer {
    public InteropRegisterer() {
        super(new Strategy[] { });
    }
}


text:
package com.dream.library.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Author:      SuSong
 * Email:       751971697@qq.com | susong0618@163.com
 * Date:        15/10/2 下午9:57
 * Description: EasyFrame
 */
public class AbCommonUtils {

    private static long lastClickTime;

    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 300) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * get format date
     *
     * @param timeMillis timeMillis
     * @return string
     */
    public static String getFormatDate(long timeMillis) {
        return new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA).format(new Date(timeMillis));
    }

    /**
     * decode Unicode string
     *
     * @param s s
     * @return string
     */
    public static String decodeUnicodeStr(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == '\\' && chars[i + 1] == 'u') {
                char cc = 0;
                for (int j = 0; j < 4; j++) {
                    char ch = Character.toLowerCase(chars[i + 2 + j]);
                    if ('0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f') {
                        cc |= (Character.digit(ch, 16) << (3 - j) * 4);
                    } else {
                        cc = 0;
                        break;
                    }
                }
                if (cc > 0) {
                    i += 5;
                    sb.append(cc);
                    continue;
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * encode Unicode string
     *
     * @param s s
     * @return string
     */
    public static String encodeUnicodeStr(String s) {
        StringBuilder sb = new StringBuilder(s.length() * 3);
        for (char c : s.toCharArray()) {
            if (c < 256) {
                sb.append(c);
            } else {
                sb.append("\\u");
                sb.append(Character.forDigit((c >>> 12) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 8) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 4) & 0xf, 16));
                sb.append(Character.forDigit((c) & 0xf, 16));
            }
        }
        return sb.toString();
    }

    /**
     * convert time str
     *
     * @param time time
     * @return string
     */
    public static String convertTime(int time) {

        time /= 1000;
        int minute = time / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

    /**
     * url is usable
     *
     * @param url url
     * @return boolean
     */
    public static boolean isUrlUsable(String url) {
        if (!AbStringUtils.isUrl(url)) {
            return false;
        }

        URL urlTemp;
        HttpURLConnection conn = null;
        try {
            urlTemp = new URL(url);
            conn = (HttpURLConnection) urlTemp.openConnection();
            conn.setRequestMethod("HEAD");
            int returnCode = conn.getResponseCode();
            if (returnCode == HttpURLConnection.HTTP_OK) {
                return true;
            }
        } catch (Exception e) {
            return false;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return false;
    }

    /**
     * get toolbar height
     *
     * @param context context
     * @return int
     */
    public static int getToolbarHeight(Context context) {
        final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(
            new int[]{android.R.attr.actionBarSize});
        int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
        styledAttributes.recycle();

        return toolbarHeight;
    }

    /**
     * 启用外部浏览器
     */
    public static void openBrowser(Context context, String url) {
        try {
            // 启用外部浏览器
            Uri uri = Uri.parse(url);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void takePic(Context context) {
        Intent intent;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            ((Activity) context).startActivityForResult(Intent.createChooser(intent, "选择图片"),
                ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            ((Activity) context).startActivityForResult(Intent.createChooser(intent, "选择图片"),
                ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
        }
    }
}


text:
namespace spv {

// The set of objects that hold all the instruction/operand
// parameterization information.
InstructionValues InstructionDesc;

// The ordered list (in printing order) of printing classes
// (specification subsections).
PrintingClasses InstructionPrintingClasses;

// Note: There is no entry for OperandOpcode. Use InstructionDesc instead.
EnumDefinition OperandClassParams[OperandOpcode];
EnumValues SourceLanguageParams;
EnumValues ExecutionModelParams;
EnumValues AddressingParams;
EnumValues MemoryParams;
EnumValues ExecutionModeParams;
EnumValues StorageParams;
EnumValues SamplerAddressingModeParams;
EnumValues SamplerFilterModeParams;
EnumValues ImageFormatParams;
EnumValues ImageChannelOrderParams;
EnumValues ImageChannelDataTypeParams;
EnumValues ImageOperandsParams;
EnumValues FPFastMathParams;
EnumValues FPRoundingModeParams;
EnumValues FPDenormModeParams;
EnumValues FPOperationModeParams;
EnumValues QuantizationModesParams;
EnumValues OverflowModesParams;
EnumValues LinkageTypeParams;
EnumValues DecorationParams;
EnumValues BuiltInParams;
EnumValues DimensionalityParams;
EnumValues FuncParamAttrParams;
EnumValues AccessQualifierParams;
EnumValues GroupOperationParams;
EnumValues LoopControlParams;
EnumValues SelectionControlParams;
EnumValues FunctionControlParams;
EnumValues MemorySemanticsParams;
EnumValues MemoryAccessParams;
EnumValues ScopeParams;
EnumValues KernelEnqueueFlagsParams;
EnumValues KernelProfilingInfoParams;
EnumValues CapabilityParams;
EnumValues RayFlagsParams;
EnumValues RayQueryIntersectionParams;
EnumValues RayQueryCommittedIntersectionTypeParams;
EnumValues RayQueryCandidateIntersectionTypeParams;
EnumValues FragmentShadingRateParams;
EnumValues PackedVectorFormatParams;

std::pair<bool, std::string> ReadFile(const std::string& path)
{
    std::ifstream fstream(path, std::ios::in);
    if (fstream) {
        std::string contents;
        fstream.seekg(0, std::ios::end);
        contents.reserve((unsigned int)fstream.tellg());
        fstream.seekg(0, std::ios::beg);
        contents.assign((std::istreambuf_iterator<char>(fstream)),
                        std::istreambuf_iterator<char>());
        return std::make_pair(true, contents);
    }
    return std::make_pair(false, "");
}

struct ClassOptionality {
    OperandClass type;
    bool optional;
};

// Converts the |operandKind| and |quantifier| pair used to describe operands
// in the JSON grammar to OperandClass and optionality used in this repo.
ClassOptionality ToOperandClassAndOptionality(const std::string& operandKind, const std::string& quantifier)
{
    assert(quantifier.empty() || quantifier == "?" || quantifier == "*");

    if (operandKind == "IdRef") {
        if (quantifier.empty())
            return {OperandId, false};
        else if (quantifier == "?")
            return {OperandId, true};
        else
            return {OperandVariableIds, false};
    } else if (operandKind == "LiteralInteger") {
        if (quantifier.empty())
            return {OperandLiteralNumber, false};
        if (quantifier == "?")
            return {OperandOptionalLiteral, true};
        else
            return {OperandVariableLiterals, false};
    } else if (operandKind == "LiteralString") {
        if (quantifier.empty())
            return {OperandLiteralString, false};
        else if (quantifier == "?")
            return {OperandLiteralString, true};
        else {
            return {OperandOptionalLiteralStrings, false};
        }
    } else if (operandKind == "PairLiteralIntegerIdRef") {
        // Used by OpSwitch in the grammar
        return {OperandVariableLiteralId, false};
    } else if (operandKind == "PairIdRefLiteralInteger") {
        // Used by OpGroupMemberDecorate in the grammar
        return {OperandVariableIdLiteral, false};
    } else if (operandKind == "PairIdRefIdRef") {
        // Used by OpPhi in the grammar
        return {OperandVariableIds, false};
    } else {
        OperandClass type = OperandNone;
        if (operandKind == "IdMemorySemantics" || operandKind == "MemorySemantics") {
            type = OperandMemorySemantics;
        } else if (operandKind == "IdScope" || operandKind == "Scope") {
            type = OperandScope;
        } else if (operandKind == "LiteralExtInstInteger") {
            type = OperandLiteralNumber;
        } else if (operandKind == "LiteralSpecConstantOpInteger") {
            type = OperandLiteralNumber;
        } else if (operandKind == "LiteralContextDependentNumber") {
            type = OperandAnySizeLiteralNumber;
        } else if (operandKind == "SourceLanguage") {
            type = OperandSource;
        } else if (operandKind == "ExecutionModel") {
            type = OperandExecutionModel;
        } else if (operandKind == "AddressingModel") {
            type = OperandAddressing;
        } else if (operandKind == "MemoryModel") {
            type = OperandMemory;
        } else if (operandKind == "ExecutionMode") {
            type = OperandExecutionMode;
        } else if (operandKind == "StorageClass") {
            type = OperandStorage;
        } else if (operandKind == "Dim") {
            type = OperandDimensionality;
        } else if (operandKind == "SamplerAddressingMode") {
            type = OperandSamplerAddressingMode;
        } else if (operandKind == "SamplerFilterMode") {
            type = OperandSamplerFilterMode;
        } else if (operandKind == "ImageFormat") {
            type = OperandSamplerImageFormat;
        } else if (operandKind == "ImageChannelOrder") {
            type = OperandImageChannelOrder;
        } else if (operandKind == "ImageChannelDataType") {
            type = OperandImageChannelDataType;
        } else if (operandKind == "FPRoundingMode") {
            type = OperandFPRoundingMode;
        } else if (operandKind == "FPDenormMode") {
            type = OperandFPDenormMode;
        } else if (operandKind == "FPOperationMode") {
            type = OperandFPOperationMode;
        } else if (operandKind == "QuantizationModes") {
            type = OperandQuantizationModes;
        } else if (operandKind == "OverflowModes") {
            type = OperandOverflowModes;
        } else if (operandKind == "LinkageType") {
            type = OperandLinkageType;
        } else if (operandKind == "AccessQualifier") {
            type = OperandAccessQualifier;
        } else if (operandKind == "FunctionParameterAttribute") {
            type = OperandFuncParamAttr;
        } else if (operandKind == "Decoration") {
            type = OperandDecoration;
        } else if (operandKind == "BuiltIn") {
            type = OperandBuiltIn;
        } else if (operandKind == "GroupOperation") {
            type = OperandGroupOperation;
        } else if (operandKind == "KernelEnqueueFlags") {
            type = OperandKernelEnqueueFlags;
        } else if (operandKind == "KernelProfilingInfo") {
            type = OperandKernelProfilingInfo;
        } else if (operandKind == "Capability") {
            type = OperandCapability;
        } else if (operandKind == "ImageOperands") {
            type = OperandImageOperands;
        } else if (operandKind == "FPFastMathMode") {
            type = OperandFPFastMath;
        } else if (operandKind == "SelectionControl") {
            type = OperandSelect;
        } else if (operandKind == "LoopControl") {
            type = OperandLoop;
        } else if (operandKind == "FunctionControl") {
            type = OperandFunction;
        } else if (operandKind == "MemoryAccess") {
            type = OperandMemoryOperands;
        } else if (operandKind == "RayFlags") {
            type = OperandRayFlags;
        } else if (operandKind == "RayQueryIntersection") {
            type = OperandRayQueryIntersection;
        } else if (operandKind == "RayQueryCommittedIntersectionType") {
            type = OperandRayQueryCommittedIntersectionType;
        } else if (operandKind == "RayQueryCandidateIntersectionType") {
            type = OperandRayQueryCandidateIntersectionType;
        } else if (operandKind == "FragmentShadingRate") {
            type = OperandFragmentShadingRate;
        } else if (operandKind == "PackedVectorFormat") {
            type = OperandPackedVectorFormat;
        }

        if (type == OperandNone) {
            std::cerr << "Unhandled operand kind found: " << operandKind << std::endl;
            exit(1);
        }
        return {type, !quantifier.empty()};
    }
}

bool IsTypeOrResultId(const std::string& str, bool* isType, bool* isResult)
{
    if (str == "IdResultType")
        return *isType = true;
    if (str == "IdResult")
        return *isResult = true;
    return false;
}

// Given a number string, returns the position of the only bits set in the number.
// So it requires the number is a power of two.
unsigned int NumberStringToBit(const std::string& str)
{
    char* parseEnd;
    unsigned int value = (unsigned int)std::strtol(str.c_str(), &parseEnd, 16);
    assert(!(value & (value - 1)) && "input number is not a power of 2");
    unsigned int bit = 0;
    for (; value; value >>= 1) ++bit;
    return bit;
}

void jsonToSpirv(const std::string& jsonPath, bool buildingHeaders)
{
    // only do this once.
    static bool initialized = false;
    if (initialized)
        return;
    initialized = true;

    // Read the JSON grammar file.
    bool fileReadOk = false;
    std::string content;
    std::tie(fileReadOk, content) = ReadFile(jsonPath);
    if (!fileReadOk) {
        std::cerr << "Failed to read JSON grammar file: "
                  << jsonPath << std::endl;
        exit(1);
    }

    // Decode the JSON grammar file.
    Json::Reader reader;
    Json::Value root;
    if (!reader.parse(content, root)) {
        std::cerr << "Failed to parse JSON grammar:\n"
                  << reader.getFormattedErrorMessages();
        exit(1);
    }

    // Layouts for all instructions.

    // A lambda for returning capabilities from a JSON object as strings.
    const auto getCaps = [](const Json::Value& object) {
        EnumCaps result;
        const auto& caps = object["capabilities"];
        if (!caps.empty()) {
            assert(caps.isArray());
            for (const auto& cap : caps) {
                result.emplace_back(cap.asString());
            }
        }
        return result;
    };

    // A lambda for returning extensions from a JSON object as strings.
    const auto getExts = [](const Json::Value& object) {
        Extensions result;
        const auto& exts = object["extensions"];
        if (!exts.empty()) {
            assert(exts.isArray());
            for (const auto& ext : exts) {
                result.emplace_back(ext.asString());
            }
        }
        return result;
    };

    // set up the printing classes
    std::unordered_set<std::string> tags;  // short-lived local for error checking below
    const Json::Value printingClasses = root["instruction_printing_class"];
    for (const auto& printingClass : printingClasses) {
        if (printingClass["tag"].asString().size() > 0)
            tags.insert(printingClass["tag"].asString()); // just for error checking
        else
            std::cerr << "Error: each instruction_printing_class requires a non-empty \"tag\"" << std::endl;
        if (buildingHeaders || printingClass["tag"].asString() != "@exclude") {
            InstructionPrintingClasses.push_back({printingClass["tag"].asString(),
                                                  printingClass["heading"].asString()});
        }
    }

    // process the instructions
    const Json::Value insts = root["instructions"];
    unsigned maxOpcode = 0;
    bool firstOpcode = true;
    for (const auto& inst : insts) {
        const auto printingClass = inst["class"].asString();
        if (printingClass.size() == 0) {
            std::cerr << "Error: " << inst["opname"].asString()
                      << " requires a non-empty printing \"class\" tag" << std::endl;
        }
        if (!buildingHeaders && printingClass == "@exclude")
            continue;
        if (tags.find(printingClass) == tags.end()) {
            std::cerr << "Error: " << inst["opname"].asString()
                      << " requires a \"class\" declared as a \"tag\" in \"instruction printing_class\""
                      << std::endl;
        }
        const auto opcode = inst["opcode"].asUInt();
        const std::string name = inst["opname"].asString();
        if (firstOpcode) {
          maxOpcode = opcode;
          firstOpcode = false;
        } else {
          if (maxOpcode > opcode) {
            std::cerr << "Error: " << name
                      << " is out of order. It follows the instruction with opcode " << maxOpcode
                      << std::endl;
            std::exit(1);
          } else {
            maxOpcode = opcode;
          }
        }
        EnumCaps caps = getCaps(inst);
        std::string version = inst["version"].asString();
        std::string lastVersion = inst["lastVersion"].asString();
        Extensions exts = getExts(inst);
        OperandParameters operands;
        bool defResultId = false;
        bool defTypeId = false;
        for (const auto& operand : inst["operands"]) {
            const std::string kind = operand["kind"].asString();
            const std::string quantifier = operand.get("quantifier", "").asString();
            const std::string doc = operand.get("name", "").asString();
            if (!IsTypeOrResultId(kind, &defTypeId, &defResultId)) {
                const auto p = ToOperandClassAndOptionality(kind, quantifier);
                operands.push(p.type, doc, p.optional);
            }
        }
        InstructionDesc.emplace_back(
            std::move(EnumValue(opcode, name,
                                std::move(caps), std::move(version), std::move(lastVersion), std::move(exts),
                                std::move(operands))),
             printingClass, defTypeId, defResultId);
    }

    // Specific additional context-dependent operands

    // Populate dest with EnumValue objects constructed from source.
    const auto populateEnumValues = [&getCaps,&getExts](EnumValues* dest, const Json::Value& source, bool bitEnum) {
        // A lambda for determining the numeric value to be used for a given
        // enumerant in JSON form, and whether that value is a 0 in a bitfield.
        auto getValue = [&bitEnum](const Json::Value& enumerant) {
            std::pair<unsigned, bool> result{0u,false};
            if (!bitEnum) {
                result.first = enumerant["value"].asUInt();
            } else {
                const unsigned int bit = NumberStringToBit(enumerant["value"].asString());
                if (bit == 0)
                    result.second = true;
                else
                    result.first = bit - 1;  // This is the *shift* amount.
            }
            return result;
        };

        unsigned maxValue = 0;
        bool firstValue = true;
        for (const auto& enumerant : source["enumerants"]) {
            unsigned value;
            bool skip_zero_in_bitfield;
            std::tie(value, skip_zero_in_bitfield) = getValue(enumerant);
            if (skip_zero_in_bitfield)
                continue;
            if (firstValue) {
              maxValue = value;
              firstValue = false;
            } else {
              if (maxValue > value) {
                std::cerr << "Error: " << source["kind"] << " enumerant " << enumerant["enumerant"]
                          << " is out of order. It has value " <<  value
                          << " but follows the enumerant with value " << maxValue << std::endl;
                std::exit(1);
              } else {
                maxValue = value;
              }
            }
            EnumCaps caps(getCaps(enumerant));
            std::string version = enumerant["version"].asString();
            std::string lastVersion = enumerant["lastVersion"].asString();
            Extensions exts(getExts(enumerant));
            OperandParameters params;
            const Json::Value& paramsJson = enumerant["parameters"];
            if (!paramsJson.empty()) {  // This enumerant has parameters.
                assert(paramsJson.isArray());
                for (const auto& param : paramsJson) {
                    const std::string kind = param["kind"].asString();
                    const std::string doc = param.get("name", "").asString();
                    const auto p = ToOperandClassAndOptionality(kind, ""); // All parameters are required!
                    params.push(p.type, doc);
                }
            }
            dest->emplace_back(
                value, enumerant["enumerant"].asString(),
                std::move(caps), std::move(version), std::move(lastVersion), std::move(exts), std::move(params));
        }
    };

    const auto establishOperandClass = [&populateEnumValues](
            const std::string& enumName, spv::OperandClass operandClass,
            spv::EnumValues* enumValues, const Json::Value& operandEnum, const std::string& category) {
        assert(category == "BitEnum" || category == "ValueEnum");
        bool bitEnum = (category == "BitEnum");
        populateEnumValues(enumValues, operandEnum, bitEnum);
        OperandClassParams[operandClass].set(enumName, enumValues, bitEnum);
    };

    const Json::Value operandEnums = root["operand_kinds"];
    for (const auto& operandEnum : operandEnums) {
        const std::string enumName = operandEnum["kind"].asString();
        const std::string category = operandEnum["category"].asString();
        if (enumName == "SourceLanguage") {
            establishOperandClass(enumName, OperandSource, &SourceLanguageParams, operandEnum, category);
        } else if (enumName == "Decoration") {
            establishOperandClass(enumName, OperandDecoration, &DecorationParams, operandEnum, category);
        } else if (enumName == "ExecutionMode") {
            establishOperandClass(enumName, OperandExecutionMode, &ExecutionModeParams, operandEnum, category);
        } else if (enumName == "Capability") {
            establishOperandClass(enumName, OperandCapability, &CapabilityParams, operandEnum, category);
        } else if (enumName == "AddressingModel") {
            establishOperandClass(enumName, OperandAddressing, &AddressingParams, operandEnum, category);
        } else if (enumName == "MemoryModel") {
            establishOperandClass(enumName, OperandMemory, &MemoryParams, operandEnum, category);
        } else if (enumName == "MemorySemantics") {
            establishOperandClass(enumName, OperandMemorySemantics, &MemorySemanticsParams, operandEnum, category);
        } else if (enumName == "ExecutionModel") {
            establishOperandClass(enumName, OperandExecutionModel, &ExecutionModelParams, operandEnum, category);
        } else if (enumName == "StorageClass") {
            establishOperandClass(enumName, OperandStorage, &StorageParams, operandEnum, category);
        } else if (enumName == "SamplerAddressingMode") {
            establishOperandClass(enumName, OperandSamplerAddressingMode, &SamplerAddressingModeParams, operandEnum, category);
        } else if (enumName == "SamplerFilterMode") {
            establishOperandClass(enumName, OperandSamplerFilterMode, &SamplerFilterModeParams, operandEnum, category);
        } else if (enumName == "ImageFormat") {
            establishOperandClass(enumName, OperandSamplerImageFormat, &ImageFormatParams, operandEnum, category);
        } else if (enumName == "ImageChannelOrder") {
            establishOperandClass(enumName, OperandImageChannelOrder, &ImageChannelOrderParams, operandEnum, category);
        } else if (enumName == "ImageChannelDataType") {
            establishOperandClass(enumName, OperandImageChannelDataType, &ImageChannelDataTypeParams, operandEnum, category);
        } else if (enumName == "ImageOperands") {
            establishOperandClass(enumName, OperandImageOperands, &ImageOperandsParams, operandEnum, category);
        } else if (enumName == "FPFastMathMode") {
            establishOperandClass(enumName, OperandFPFastMath, &FPFastMathParams, operandEnum, category);
        } else if (enumName == "FPRoundingMode") {
            establishOperandClass(enumName, OperandFPRoundingMode, &FPRoundingModeParams, operandEnum, category);
        } else if (enumName == "FPDenormMode") {
            establishOperandClass(enumName, OperandFPDenormMode, &FPDenormModeParams, operandEnum, category);
        } else if (enumName == "FPOperationMode") {
            establishOperandClass(enumName, OperandFPOperationMode, &FPOperationModeParams, operandEnum, category);
        } else if (enumName == "QuantizationModes") {
            establishOperandClass(enumName, OperandQuantizationModes, &QuantizationModesParams, operandEnum, category);
        } else if (enumName == "OverflowModes") {
            establishOperandClass(enumName, OperandOverflowModes, &OverflowModesParams, operandEnum, category);
        } else if (enumName == "LinkageType") {
            establishOperandClass(enumName, OperandLinkageType, &LinkageTypeParams, operandEnum, category);
        } else if (enumName == "FunctionParameterAttribute") {
            establishOperandClass(enumName, OperandFuncParamAttr, &FuncParamAttrParams, operandEnum, category);
        } else if (enumName == "AccessQualifier") {
            establishOperandClass(enumName, OperandAccessQualifier, &AccessQualifierParams, operandEnum, category);
        } else if (enumName == "BuiltIn") {
            establishOperandClass(enumName, OperandBuiltIn, &BuiltInParams, operandEnum, category);
        } else if (enumName == "SelectionControl") {
            establishOperandClass(enumName, OperandSelect, &SelectionControlParams, operandEnum, category);
        } else if (enumName == "LoopControl") {
            establishOperandClass(enumName, OperandLoop, &LoopControlParams, operandEnum, category);
        } else if (enumName == "FunctionControl") {
            establishOperandClass(enumName, OperandFunction, &FunctionControlParams, operandEnum, category);
        } else if (enumName == "Dim") {
            establishOperandClass(enumName, OperandDimensionality, &DimensionalityParams, operandEnum, category);
        } else if (enumName == "MemoryAccess") {
            establishOperandClass(enumName, OperandMemoryOperands, &MemoryAccessParams, operandEnum, category);
        } else if (enumName == "Scope") {
            establishOperandClass(enumName, OperandScope, &ScopeParams, operandEnum, category);
        } else if (enumName == "GroupOperation") {
            establishOperandClass(enumName, OperandGroupOperation, &GroupOperationParams, operandEnum, category);
        } else if (enumName == "KernelEnqueueFlags") {
            establishOperandClass(enumName, OperandKernelEnqueueFlags, &KernelEnqueueFlagsParams, operandEnum, category);
        } else if (enumName == "KernelProfilingInfo") {
            establishOperandClass(enumName, OperandKernelProfilingInfo, &KernelProfilingInfoParams, operandEnum, category);
        } else if (enumName == "RayFlags") {
            establishOperandClass(enumName, OperandRayFlags, &RayFlagsParams, operandEnum, category);
        } else if (enumName == "RayQueryIntersection") {
            establishOperandClass(enumName, OperandRayQueryIntersection, &RayQueryIntersectionParams, operandEnum, category);
        } else if (enumName == "RayQueryCommittedIntersectionType") {
            establishOperandClass(enumName, OperandRayQueryCommittedIntersectionType, &RayQueryCommittedIntersectionTypeParams, operandEnum, category);
        } else if (enumName == "RayQueryCandidateIntersectionType") {
            establishOperandClass(enumName, OperandRayQueryCandidateIntersectionType, &RayQueryCandidateIntersectionTypeParams, operandEnum, category);
        } else if (enumName == "FragmentShadingRate") {
            establishOperandClass(enumName, OperandFragmentShadingRate, &FragmentShadingRateParams, operandEnum, category);
        } else if (enumName == "PackedVectorFormat") {
            establishOperandClass(enumName, OperandPackedVectorFormat, &PackedVectorFormatParams, operandEnum, category);
        }
    }
}

};  // end namespace spv


text:
package org.jabref.gui.help;

import javax.inject.Inject;

import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextArea;

import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.ControlHelper;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.BuildInfo;

import com.airhacks.afterburner.views.ViewLoader;

public class AboutDialogView extends BaseDialog<Void> {

    @FXML private ButtonType copyVersionButton;
    @FXML private TextArea textAreaVersions;

    @Inject private DialogService dialogService;
    @Inject private ClipBoardManager clipBoardManager;
    @Inject private BuildInfo buildInfo;

    private AboutDialogViewModel viewModel;

    public AboutDialogView() {
        this.setTitle(Localization.lang("About JabRef"));

        ViewLoader.view(this)
                  .load()
                  .setAsDialogPane(this);

        ControlHelper.setAction(copyVersionButton, getDialogPane(), event -> copyVersionToClipboard());
    }

    @FXML
    private void initialize() {
        viewModel = new AboutDialogViewModel(dialogService, clipBoardManager, buildInfo);

        textAreaVersions.setText(viewModel.getVersionInfo());
    }

    @FXML
    private void copyVersionToClipboard() {
        viewModel.copyVersionToClipboard();
    }

    @FXML
    private void openJabrefWebsite() {
        viewModel.openJabrefWebsite();
    }

    @FXML
    private void openExternalLibrariesWebsite() {
        viewModel.openExternalLibrariesWebsite();
    }

    @FXML
    private void openGithub() {
        viewModel.openGithub();
    }

    @FXML
    public void openChangeLog() {
        viewModel.openChangeLog();
    }

    @FXML
    public void openLicense() {
        viewModel.openLicense();
    }

    @FXML
    public void openDonation() {
        viewModel.openDonation();
    }

}


text:
import datetime
import pytz
import re

try:
    import simplejson as json
except ImportError:
    import json

from functools import wraps
from flask import request, g, current_app

try:
    from urllib.parse import urljoin
except ImportError:
    from urlparse import urljoin

from alerta.app import app, db
from alerta.app.exceptions import RejectException, RateLimit, BlackoutPeriod
from alerta.app.metrics import Counter, Timer
from alerta.plugins import Plugins

LOG = app.logger

plugins = Plugins()

reject_counter = Counter('alerts', 'rejected', 'Rejected alerts', 'Number of rejected alerts')
error_counter = Counter('alerts', 'errored', 'Errored alerts', 'Number of errored alerts')
duplicate_timer = Timer('alerts', 'duplicate', 'Duplicate alerts', 'Total time to process number of duplicate alerts')
correlate_timer = Timer('alerts', 'correlate', 'Correlated alerts', 'Total time to process number of correlated alerts')
create_timer = Timer('alerts', 'create', 'Newly created alerts', 'Total time to process number of new alerts')
pre_plugin_timer = Timer('plugins', 'prereceive', 'Pre-receive plugins', 'Total number of pre-receive plugins')
post_plugin_timer = Timer('plugins', 'postreceive', 'Post-receive plugins', 'Total number of post-receive plugins')

def jsonp(func):
    """Wraps JSONified output for JSONP requests."""
    @wraps(func)
    def decorated(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            data = str(func(*args, **kwargs).data)
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)
    return decorated

def absolute_url(path=''):
    return urljoin(request.base_url.rstrip('/'), app.config.get('BASE_URL', '') + path)

def add_remote_ip(request, alert):
    if request.headers.getlist("X-Forwarded-For"):
       alert.attributes.update(ip=request.headers.getlist("X-Forwarded-For")[0])
    else:
       alert.attributes.update(ip=request.remote_addr)

PARAMS_EXCLUDE = [
    '_',
    'callback',
    'token',
    'api-key'
]

def parse_fields(p):

    params = p.copy()
    query_time = datetime.datetime.utcnow()

    for s in PARAMS_EXCLUDE:
        if s in params:
            del params[s]

    if params.get('q', None):
        query = json.loads(params['q'])
        del params['q']
    else:
        query = dict()

    if g.get('customer', None):
        query['customer'] = g.get('customer')

    page = params.get('page', 1)
    if 'page' in params:
        del params['page']
    page = int(page)

    if params.get('from-date', None):
        try:
            from_date = datetime.datetime.strptime(params['from-date'], '%Y-%m-%dT%H:%M:%S.%fZ')
        except ValueError as e:
            LOG.warning('Could not parse from-date query parameter: %s', e)
            raise
        from_date = from_date.replace(tzinfo=pytz.utc)
        del params['from-date']
    else:
        from_date = None

    if params.get('to-date', None):
        try:
            to_date = datetime.datetime.strptime(params['to-date'], '%Y-%m-%dT%H:%M:%S.%fZ')
        except ValueError as e:
            LOG.warning('Could not parse to-date query parameter: %s', e)
            raise
        to_date = to_date.replace(tzinfo=pytz.utc)
        del params['to-date']
    else:
        to_date = query_time
        to_date = to_date.replace(tzinfo=pytz.utc)

    if from_date and to_date:
        query['lastReceiveTime'] = {'$gt': from_date, '$lte': to_date}
    elif to_date:
        query['lastReceiveTime'] = {'$lte': to_date}

    if params.get('duplicateCount', None):
        query['duplicateCount'] = int(params.get('duplicateCount'))
        del params['duplicateCount']

    if params.get('repeat', None):
        query['repeat'] = True if params.get('repeat', 'true') == 'true' else False
        del params['repeat']

    sort = list()
    direction = 1
    if params.get('reverse', None):
        direction = -1
        del params['reverse']
    if params.get('sort-by', None):
        for sort_by in params.getlist('sort-by'):
            if sort_by in ['createTime', 'receiveTime', 'lastReceiveTime']:
                sort.append((sort_by, -direction))  # reverse chronological
            else:
                sort.append((sort_by, direction))
        del params['sort-by']
    else:
        sort.append(('lastReceiveTime', -direction))

    group = list()
    if 'group-by' in params:
        group = params.get('group-by')
        del params['group-by']

    if 'limit' in params:
        limit = params.get('limit')
        del params['limit']
    else:
        limit = app.config['QUERY_LIMIT']
    limit = int(limit)

    ids = params.getlist('id')
    if len(ids) == 1:
        query['$or'] = [{'_id': {'$regex': '^' + ids[0]}}, {'lastReceiveId': {'$regex': '^' + ids[0]}}]
        del params['id']
    elif ids:
        query['$or'] = [{'_id': {'$regex': re.compile('|'.join(['^' + i for i in ids]))}}, {'lastReceiveId': {'$regex': re.compile('|'.join(['^' + i for i in ids]))}}]
        del params['id']

    if 'fields' in params:
        fields = dict([(field, True) for field in params.get('fields').split(',')])
        fields.update({'resource': True, 'event': True, 'environment': True, 'createTime': True, 'receiveTime': True, 'lastReceiveTime': True})
        del params['fields']
    elif 'fields!' in params:
        fields = dict([(field, False) for field in params.get('fields!').split(',')])
        del params['fields!']
    else:
        fields = dict()

    for field in params:
        value = params.getlist(field)
        if len(value) == 1:
            value = value[0]
            if field.endswith('!'):
                if value.startswith('~'):
                    query[field[:-1]] = dict()
                    query[field[:-1]]['$not'] = re.compile(value[1:], re.IGNORECASE)
                else:
                    query[field[:-1]] = dict()
                    query[field[:-1]]['$ne'] = value
            else:
                if value.startswith('~'):
                    query[field] = dict()
                    query[field]['$regex'] = re.compile(value[1:], re.IGNORECASE)
                else:
                    query[field] = value
        else:
            if field.endswith('!'):
                if '~' in [v[0] for v in value]:
                    value = '|'.join([v.lstrip('~') for v in value])
                    query[field[:-1]] = dict()
                    query[field[:-1]]['$not'] = re.compile(value, re.IGNORECASE)
                else:
                    query[field[:-1]] = dict()
                    query[field[:-1]]['$nin'] = value
            else:
                if '~' in [v[0] for v in value]:
                    value = '|'.join([v.lstrip('~') for v in value])
                    query[field] = dict()
                    query[field]['$regex'] = re.compile(value, re.IGNORECASE)
                else:
                    query[field] = dict()
                    query[field]['$in'] = value

    return query, fields, sort, group, page, limit, query_time

def process_alert(alert):

    for plugin in plugins.routing(alert):
        started = pre_plugin_timer.start_timer()
        try:
            alert = plugin.pre_receive(alert)
        except (RejectException, RateLimit):
            reject_counter.inc()
            pre_plugin_timer.stop_timer(started)
            raise
        except Exception as e:
            error_counter.inc()
            pre_plugin_timer.stop_timer(started)
            raise RuntimeError("Error while running pre-receive plug-in '%s': %s" % (plugin.name, str(e)))
        if not alert:
            error_counter.inc()
            pre_plugin_timer.stop_timer(started)
            raise SyntaxError("Plug-in '%s' pre-receive hook did not return modified alert" % plugin.name)
        pre_plugin_timer.stop_timer(started)

    if db.is_blackout_period(alert):
        raise BlackoutPeriod("Suppressed alert during blackout period")

    try:
        if db.is_duplicate(alert):
            started = duplicate_timer.start_timer()
            alert = db.save_duplicate(alert)
            duplicate_timer.stop_timer(started)
        elif db.is_correlated(alert):
            started = correlate_timer.start_timer()
            alert = db.save_correlated(alert)
            correlate_timer.stop_timer(started)
        else:
            started = create_timer.start_timer()
            alert = db.create_alert(alert)
            create_timer.stop_timer(started)
    except Exception as e:
        error_counter.inc()
        raise RuntimeError(e)

    for plugin in plugins.routing(alert):
        started = post_plugin_timer.start_timer()
        try:
            plugin.post_receive(alert)
        except Exception as e:
            error_counter.inc()
            post_plugin_timer.stop_timer(started)
            raise RuntimeError("Error while running post-receive plug-in '%s': %s" % (plugin.name, str(e)))
        post_plugin_timer.stop_timer(started)

    return alert

def process_status(alert, status, text):

    for plugin in plugins.routing(alert):
        try:
            plugin.status_change(alert, status, text)
        except RejectException:
            reject_counter.inc()
            raise
        except Exception as e:
            error_counter.inc()
            raise RuntimeError("Error while running status plug-in '%s': %s" % (plugin.name, str(e)))


text:
package ch.maxant.tradingengine.model;

import scala.Function1;
import scala.Function1$class;

/** a shim, letting us easily call into the scala world */
public abstract class JFunction1<T1, R> implements scala.Function1<T1, R> {

	@Override
	public <A> Function1<T1, A> andThen(Function1<R, A> arg0) {
		return Function1$class.andThen(this, arg0);
	}

	@Override
	public double apply$mcDD$sp(double arg0) {
		return Function1$class.apply$mcDD$sp(this, arg0);
	}

	@Override
	public double apply$mcDF$sp(float arg0) {
		return Function1$class.apply$mcDF$sp(this, arg0);
	}

	@Override
	public double apply$mcDI$sp(int arg0) {
		return Function1$class.apply$mcDI$sp(this, arg0);
	}

	@Override
	public double apply$mcDJ$sp(long arg0) {
		return Function1$class.apply$mcDJ$sp(this, arg0);
	}

	@Override
	public float apply$mcFD$sp(double arg0) {
		return Function1$class.apply$mcFD$sp(this, arg0);
	}

	@Override
	public float apply$mcFF$sp(float arg0) {
		return Function1$class.apply$mcFF$sp(this, arg0);
	}

	@Override
	public float apply$mcFI$sp(int arg0) {
		return Function1$class.apply$mcFI$sp(this, arg0);
	}

	@Override
	public float apply$mcFJ$sp(long arg0) {
		return Function1$class.apply$mcFJ$sp(this, arg0);
	}

	@Override
	public int apply$mcID$sp(double arg0) {
		return Function1$class.apply$mcID$sp(this, arg0);
	}

	@Override
	public int apply$mcIF$sp(float arg0) {
		return Function1$class.apply$mcIF$sp(this, arg0);
	}

	@Override
	public int apply$mcII$sp(int arg0) {
		return Function1$class.apply$mcII$sp(this, arg0);
	}

	@Override
	public int apply$mcIJ$sp(long arg0) {
		return Function1$class.apply$mcIJ$sp(this, arg0);
	}

	@Override
	public long apply$mcJD$sp(double arg0) {
		return Function1$class.apply$mcJD$sp(this, arg0);
	}

	@Override
	public long apply$mcJF$sp(float arg0) {
		return Function1$class.apply$mcJF$sp(this, arg0);
	}

	@Override
	public long apply$mcJI$sp(int arg0) {
		return Function1$class.apply$mcJI$sp(this, arg0);
	}

	@Override
	public long apply$mcJJ$sp(long arg0) {
		return Function1$class.apply$mcJJ$sp(this, arg0);
	}

	@Override
	public void apply$mcVD$sp(double arg0) {
		Function1$class.apply$mcVD$sp(this, arg0);
	}

	@Override
	public void apply$mcVF$sp(float arg0) {
		Function1$class.apply$mcVF$sp(this, arg0);
	}

	@Override
	public void apply$mcVI$sp(int arg0) {
		Function1$class.apply$mcVI$sp(this, arg0);
	}

	@Override
	public void apply$mcVJ$sp(long arg0) {
		Function1$class.apply$mcVJ$sp(this, arg0);
	}

	@Override
	public boolean apply$mcZD$sp(double arg0) {
		return Function1$class.apply$mcZD$sp(this, arg0);
	}

	@Override
	public boolean apply$mcZF$sp(float arg0) {
		return Function1$class.apply$mcZF$sp(this, arg0);
	}

	@Override
	public boolean apply$mcZI$sp(int arg0) {
		return Function1$class.apply$mcZI$sp(this, arg0);
	}

	@Override
	public boolean apply$mcZJ$sp(long arg0) {
		return Function1$class.apply$mcZJ$sp(this, arg0);
	}

	@Override
	public <A> Function1<A, R> compose(Function1<A, T1> arg0) {
		return Function1$class.compose(this, arg0);
	}

}


text:
namespace svm
{
	bool Initialize()
	{
		OpcodeInfo::Initialize();
		return true;
	}
}


text:
delimiter $$

drop procedure if exists adicionar_quantidade_estoque_em_produto $$

create procedure adicionar_quantidade_estoque_em_produto()

begin
	if not exists ((SELECT *
		FROM information_schema.columns
			WHERE table_schema=database()
				AND table_name='produto'
				AND column_name='quantidade_estoque')) then

		alter table produto add column quantidade_estoque integer;
	end if;
end $$

call adicionar_quantidade_estoque_em_produto() $$

drop procedure if exists adicionar_quantidade_estoque_em_produto $$

delimiter ;