text:
package org.elasticsearch.action.delete;

import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.CompositeIndicesRequest;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.support.replication.ReplicatedWriteRequest;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.shard.ShardId;

import java.io.IOException;

import static org.elasticsearch.action.ValidateActions.addValidationError;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;

/**
 * A request to delete a document from an index based on its type and id. Best created using
 * {@link org.elasticsearch.client.Requests#deleteRequest(String)}.
 * <p>
 * The operation requires the {@link #index()}, {@link #type(String)} and {@link #id(String)} to
 * be set.
 *
 * @see DeleteResponse
 * @see org.elasticsearch.client.Client#delete(DeleteRequest)
 * @see org.elasticsearch.client.Requests#deleteRequest(String)
 */
public class DeleteRequest extends ReplicatedWriteRequest<DeleteRequest>
        implements DocWriteRequest<DeleteRequest>, CompositeIndicesRequest {

    private String type;
    private String id;
    @Nullable
    private String routing;
    @Nullable
    private String parent;
    private long version = Versions.MATCH_ANY;
    private VersionType versionType = VersionType.INTERNAL;
    private long ifSeqNo = UNASSIGNED_SEQ_NO;
    private long ifPrimaryTerm = UNASSIGNED_PRIMARY_TERM;

    public DeleteRequest() {
    }

    /**
     * Constructs a new delete request against the specified index. The {@link #type(String)} and {@link #id(String)}
     * must be set.
     */
    public DeleteRequest(String index) {
        this.index = index;
    }

    /**
     * Constructs a new delete request against the specified index with the type and id.
     *
     * @param index The index to get the document from
     * @param type  The type of the document
     * @param id    The id of the document
     */
    public DeleteRequest(String index, String type, String id) {
        this.index = index;
        this.type = type;
        this.id = id;
    }

    @Override
    public ActionRequestValidationException validate() {
        ActionRequestValidationException validationException = super.validate();
        if (Strings.isEmpty(type)) {
            validationException = addValidationError("type is missing", validationException);
        }
        if (Strings.isEmpty(id)) {
            validationException = addValidationError("id is missing", validationException);
        }

        validationException = DocWriteRequest.validateSeqNoBasedCASParams(this, validationException);

        return validationException;
    }

    /**
     * The type of the document to delete.
     */
    @Override
    public String type() {
        return type;
    }

    /**
     * Sets the type of the document to delete.
     */
    @Override
    public DeleteRequest type(String type) {
        this.type = type;
        return this;
    }

    /**
     * The id of the document to delete.
     */
    @Override
    public String id() {
        return id;
    }

    /**
     * Sets the id of the document to delete.
     */
    public DeleteRequest id(String id) {
        this.id = id;
        return this;
    }

    /**
     * @return The parent for this request.
     */
    @Override
    public String parent() {
        return parent;
    }

    /**
     * Sets the parent id of this document.
     */
    public DeleteRequest parent(String parent) {
        this.parent = parent;
        return this;
    }

    /**
     * Controls the shard routing of the request. Using this value to hash the shard
     * and not the id.
     */
    @Override
    public DeleteRequest routing(String routing) {
        if (routing != null && routing.length() == 0) {
            this.routing = null;
        } else {
            this.routing = routing;
        }
        return this;
    }

    /**
     * Controls the shard routing of the delete request. Using this value to hash the shard
     * and not the id.
     */
    @Override
    public String routing() {
        return this.routing;
    }

    @Override
    public DeleteRequest version(long version) {
        this.version = version;
        return this;
    }

    @Override
    public long version() {
        return this.version;
    }

    @Override
    public DeleteRequest versionType(VersionType versionType) {
        this.versionType = versionType;
        return this;
    }

    /**
     * If set, only perform this delete request if the document was last modification was assigned this sequence number.
     * If the document last modification was assigned a different sequence number a
     * {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
     */
    public long ifSeqNo() {
        return ifSeqNo;
    }

    /**
     * If set, only perform this delete request if the document was last modification was assigned this primary term.
     *
     * If the document last modification was assigned a different term a
     * {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
     */
    public long ifPrimaryTerm() {
        return ifPrimaryTerm;
    }

    /**
     * only perform this delete request if the document was last modification was assigned the given
     * sequence number. Must be used in combination with {@link #setIfPrimaryTerm(long)}
     *
     * If the document last modification was assigned a different sequence number a
     * {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
     */
    public DeleteRequest setIfSeqNo(long seqNo) {
        if (seqNo < 0 && seqNo != UNASSIGNED_SEQ_NO) {
            throw new IllegalArgumentException("sequence numbers must be non negative. got [" +  seqNo + "].");
        }
        ifSeqNo = seqNo;
        return this;
    }

    /**
     * only perform this delete request if the document was last modification was assigned the given
     * primary term. Must be used in combination with {@link #setIfSeqNo(long)}
     *
     * If the document last modification was assigned a different primary term a
     * {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown.
     */
    public DeleteRequest setIfPrimaryTerm(long term) {
        if (term < 0) {
            throw new IllegalArgumentException("primary term must be non negative. got [" + term + "]");
        }
        ifPrimaryTerm = term;
        return this;
    }

    @Override
    public VersionType versionType() {
        return this.versionType;
    }

    @Override
    public OpType opType() {
        return OpType.DELETE;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        type = in.readString();
        id = in.readString();
        routing = in.readOptionalString();
        parent = in.readOptionalString();
        version = in.readLong();
        versionType = VersionType.fromValue(in.readByte());
        if (in.getVersion().onOrAfter(Version.V_6_6_0)) {
            ifSeqNo = in.readZLong();
            ifPrimaryTerm = in.readVLong();
        } else {
            ifSeqNo = UNASSIGNED_SEQ_NO;
            ifPrimaryTerm = UNASSIGNED_PRIMARY_TERM;
        }
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeString(type);
        out.writeString(id);
        out.writeOptionalString(routing());
        out.writeOptionalString(parent());
        out.writeLong(version);
        out.writeByte(versionType.getValue());
        if (out.getVersion().onOrAfter(Version.V_6_6_0)) {
            out.writeZLong(ifSeqNo);
            out.writeVLong(ifPrimaryTerm);
        } else if (ifSeqNo != UNASSIGNED_SEQ_NO || ifPrimaryTerm != UNASSIGNED_PRIMARY_TERM) {
            assert false : "ifSeqNo [" + ifSeqNo + "], ifPrimaryTerm [" + ifPrimaryTerm + "]";
            throw new IllegalStateException(
                "sequence number based compare and write is not supported until all nodes are on version 6.6.0 or higher. " +
                    "Stream version [" + out.getVersion() + "]");
        }
    }

    @Override
    public String toString() {
        return "delete {[" + index + "][" + type + "][" + id + "]}";
    }

    /**
     * Override this method from ReplicationAction, this is where we are storing our state in the request object (which we really shouldn't
     * do). Once the transport client goes away we can move away from making this available, but in the meantime this is dangerous to set or
     * use because the DeleteRequest object will always be wrapped in a bulk request envelope, which is where this *should* be set.
     */
    @Override
    public DeleteRequest setShardId(ShardId shardId) {
        throw new UnsupportedOperationException("shard id should never be set on DeleteRequest");
    }
}


text:
<!DOCTYPE HTML>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

   move mouse over this text

redpajama_set_name: RedPajamaGithub


text:
package net.snowflake.spark.snowflake.io

import java.sql.Connection

import net.snowflake.client.jdbc.SnowflakeResultSet
import net.snowflake.client.jdbc.internal.fasterxml.jackson.databind.ObjectMapper
import net.snowflake.client.jdbc.internal.fasterxml.jackson.databind.node.ObjectNode
import net.snowflake.spark.snowflake.Parameters.MergedParameters
import net.snowflake.spark.snowflake._
import net.snowflake.spark.snowflake.io.SupportedFormat.SupportedFormat
import net.snowflake.spark.snowflake.DefaultJDBCWrapper.DataBaseOperations
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SQLContext
import org.slf4j.{Logger, LoggerFactory}
import scala.language.postfixOps
import scala.util.Random

private[snowflake] object StageReader {

  private val mapper: ObjectMapper = new ObjectMapper()
  private val logger: Logger = LoggerFactory.getLogger(this.getClass)
  private val OUTPUT_BYTES = TelemetryFieldNames.OUTPUT_BYTES

  def readFromStage(sqlContext: SQLContext,
                    params: MergedParameters,
                    statement: SnowflakeSQLStatement,
                    format: SupportedFormat): RDD[String] = {
    val conn = DefaultJDBCWrapper.getConnector(params)
    val (storage, stage) =
      CloudStorageOperations.createStorageClient(params, conn)
    val compress = params.sfCompress
    val compressFormat = if (params.sfCompress) "gzip" else "none"

    Utils.genPrologueSql(params).foreach(x => x.execute(params.bindVariableEnabled)(conn))

    Utils.executePreActions(DefaultJDBCWrapper, conn, params, params.table)

    val prefix = Random.alphanumeric take 10 mkString ""

    val copyStatement = buildUnloadStatement(
      params,
      statement,
      s"@$stage/$prefix/",
      compressFormat,
      format
    )
    logger.info(s"Now executing below command to read from snowflake:\n${copyStatement.toString}")

    val startTime = System.currentTimeMillis()
    val res = try {
      if (params.isExecuteQueryWithSyncMode) {
        copyStatement.execute(params.bindVariableEnabled)(conn)
      } else {
        val asyncRs = copyStatement.executeAsync(bindVariableEnabled = false)(conn)
        val queryID = asyncRs.asInstanceOf[SnowflakeResultSet].getQueryID
        logger.info(s"The query ID for async reading from snowflake with COPY INTO LOCATION is: " +
          s"$queryID; The query ID URL is:\n${params.getQueryIDUrl(queryID)}")
        SparkConnectorContext.addRunningQuery(sqlContext.sparkContext, conn, queryID)
        // Call getMetaData() to wait fot the async query to be done
        // Note: do not call next() to wait for the query to be done because
        // it will change the ResultSet, so getCopyMissedFiles() doesn't work.
        asyncRs.getMetaData
        SparkConnectorContext.removeRunningQuery(sqlContext.sparkContext, conn, queryID)
        asyncRs
      }
    } catch {
      case th: Throwable => {
        // send telemetry message
        SnowflakeTelemetry.sendQueryStatus(
          conn,
          TelemetryConstValues.OPERATION_READ,
          copyStatement.getLastQueryID(),
          TelemetryConstValues.STATUS_FAIL,
          System.currentTimeMillis() - startTime,
          Some(th),
          "Hit exception when reading with COPY INTO LOCATION")
        // Re-throw the exception
        throw th
      }
    }

    // Verify it's the expected format
    val sch = res.getMetaData
    if (sch.getColumnCount >= 3) {
      // Format V1 for COPY INTO LOCATION. The result format is:
      // rows_unloaded    input_bytes    output_bytes
      // Format V2 for COPY INTO LOCATION. The result format is:
      // ROW_COUNT    FILE_NAME     FILE_SIZE
      val thirdColumnName = sch.getColumnName(3)
      val thirdColumnType = sch.getColumnTypeName(3)
      if (("output_bytes".equalsIgnoreCase(thirdColumnName)
        || "FILE_SIZE".equalsIgnoreCase(thirdColumnName))
        && "number".equalsIgnoreCase(thirdColumnType))
      {
        var dataSize: Long = 0
        while (res.next) {
          dataSize += res.getLong(3)
        }
        sendEgressUsage(dataSize, conn)
      } else {
        logger.warn(
          s"""The result format of COPY INTO LOCATION is not recognized.
             | $thirdColumnName $thirdColumnType""".stripMargin)
      }
    } else {
      logger.warn(
        s"""The result format of COPY INTO LOCATION is not recognized.
           | ${sch.getColumnCount}""".stripMargin)
    }

    Utils.executePostActions(DefaultJDBCWrapper, conn, params, params.table)

    SnowflakeTelemetry.send(conn.getTelemetry)

    val resultRDD = storage.download(
      sqlContext.sparkContext, format, compress, prefix)

    // The connection can't be closed before download because the spark driver
    // needs the connection to acquire the credential for distributed download.
    conn.close()

    resultRDD
  }

  private def buildUnloadStatement(
    params: MergedParameters,
    statement: SnowflakeSQLStatement,
    location: String,
    compression: String,
    format: SupportedFormat = SupportedFormat.CSV
  ): SnowflakeSQLStatement = {

    // Save the last SELECT so it can be inspected
    Utils.setLastSelect(statement.toString)

    val (formatStmt, queryStmt): (SnowflakeSQLStatement, SnowflakeSQLStatement) =
      format match {
        case SupportedFormat.CSV =>
          (
            ConstantString(s"""
                 |FILE_FORMAT = (
                 |    TYPE=CSV
                 |    COMPRESSION='$compression'
                 |    FIELD_DELIMITER='|'
                 |    FIELD_OPTIONALLY_ENCLOSED_BY='"'
                 |    ESCAPE_UNENCLOSED_FIELD = none
                 |    NULL_IF= ()
                 |  )
                 |  """.stripMargin) !,
            ConstantString("FROM (") + statement + ")"
          )
        case SupportedFormat.JSON =>
          (
            ConstantString(s"""
                 |FILE_FORMAT = (
                 |    TYPE=JSON
                 |    COMPRESSION='$compression'
                 |)
                 |""".stripMargin) !,
            ConstantString("FROM (SELECT object_construct(*) FROM (") + statement + "))"
          )
      }

    val result = ConstantString(s"COPY INTO '$location'") + queryStmt +
      formatStmt + "MAX_FILE_SIZE = " + params.s3maxfilesize

    Utils.setLastCopyUnload(result.toString)
    result

  }

  private[snowflake] def sendEgressUsage(bytes: Long, conn: Connection): Unit = {
    val metric: ObjectNode = mapper.createObjectNode()
    metric.put(OUTPUT_BYTES, bytes)

    SnowflakeTelemetry.addLog(
      (TelemetryTypes.SPARK_EGRESS, metric),
      System.currentTimeMillis()
    )
    SnowflakeTelemetry.send(conn.getTelemetry)
    logger.debug(s"Data Egress Usage: $bytes bytes".stripMargin)
  }
}


text:
namespace ui {

// A interface to observe changes in the IMEBridge.
class COMPONENT_EXPORT(UI_BASE_IME) IMEBridgeObserver
    : public base::CheckedObserver {
 public:
  // Called when requesting to switch the engine handler from ui::InputMethod.
  virtual void OnRequestSwitchEngine() = 0;

  // Called when the input context handler has changed, a signal of IME change.
  virtual void OnInputContextHandlerChanged() = 0;
};

}  // namespace ui

#endif  // UI_BASE_IME_IME_BRIDGE_OBSERVER_H_


text:
/* -*-C++-*-
******************************************************************************
*
* File:         MultiJoin.cpp
* Description:  MultiJoin Operator Methods
* Created:      03/03/03
* Language:     C++
*
*
******************************************************************************
*/

#include "MultiJoin.h"
#include "AppliedStatMan.h"
#include "RelJoin.h"

//
extern THREAD_P NAUnsigned              MJEnumRuleNumber;
extern THREAD_P NAUnsigned              MJStarJoinRuleNumber;
extern THREAD_P NAUnsigned              MJStarBDRuleNumber;
extern THREAD_P NAUnsigned              MJPrimeTableRuleNumber;
//extern NAUnsigned              MJPrimeTableRule2Number; Not needed
//

MultiJoin::MultiJoin(const JBBSubset & jbbSubset,
                     CollHeap *oHeap)
  : RelExpr(REL_MULTI_JOIN, NULL, NULL, oHeap)
  , jbbSubset_(jbbSubset)
  , childrenMap_(oHeap)
  , scheduledLSRs_(oHeap)
{
  // Need to initialize the childrenMap
  // This will set all children to NULL
  CANodeIdSet jbbcs = jbbSubset_.getJBBCs();
  Lng32 index = 0;

  for (CANodeId x= jbbcs.init();
       jbbcs.next(x);
       jbbcs.advance(x) )
  {
    JBBCExprGroupEntry* entry = new (oHeap)
      JBBCExprGroupEntry(x, (RelExpr*)NULL, oHeap);

    childrenMap_.insertAt(index, entry);
	index++;
  }

  lsrC_ = new (oHeap) LSRConfidence(oHeap);
#pragma warning (disable : 4018)  //warning elimination
  CMPASSERT (getArity() == jbbcs.entries());
#pragma warning (default : 4018)  //warning elimination
}

// LCOV_EXCL_START  - cnu
NABoolean MultiJoin::isSymmetricMultiJoin() const
{
  // now all are inners non semi
  return jbbSubset_.allJoinsInnerNonSemi();
}

void MultiJoin::pushdownCoveredExpr(const ValueIdSet & outputExpr,
                               const ValueIdSet & newExternalInputs,
                               ValueIdSet & predicatesOnParent,
			       const ValueIdSet * setOfValuesReqdByParent,
			       Lng32 childIndex
		              )
{
  CMPASSERT(0);
} // MultiJoin::pushdownCoveredExpr
// LCOV_EXCL_STOP

void MultiJoin::getPotentialOutputValues(ValueIdSet & outputValues) const
{
  outputValues.clear();

  CANodeIdSet jbbcs = jbbSubset_.getJBBCs();

  Int32 arity = getArity();

  for (Lng32 i = 0; i < arity; i++)
  {
	  JBBC * jbbci =
        child(i)->getGroupAnalysis()->getNodeAnalysis()->getJBBC();

	  if(jbbci->parentIsLeftJoin())
        outputValues.insertList(jbbci->nullInstantiatedOutput());
      else
        // Default implementation is good enough for innerNonSemi multi join
        outputValues += child(i).getGroupAttr()->getCharacteristicOutputs();
  }
} // MultiJoin::getPotentialOutputValues()

// LCOV_EXCL_START  - dpm
const NAString MultiJoin::getText() const
{
  return NAString("multi_join");
} // MultiJoin::getText()
// LCOV_EXCL_STOP

HashValue MultiJoin::topHash()
{
  selectionPred().clear();
  HashValue result = RelExpr::topHash();

  result ^= jbbSubset_.getJBBCs();
  result ^= CollIndex(jbbSubset_.getGB());

  return result;
}

NABoolean MultiJoin::duplicateMatch(const RelExpr & other) const
{
  // We need to compare the arity before RelExpr::duplicateMatch(...)
  // otherwise we may get out of array boundary exception when compaing
  // this multijoin to a RelExpr with different arity. This is different
  // than other RelExprs because the check for operator type does not
  // secure the same arity in this case.

  if (getArity() != other.getArity())
    return FALSE;

  ((RelExpr*)this)->selectionPred().clear();

  if (!RelExpr::duplicateMatch(other))
    return FALSE;

  MultiJoin &o = (MultiJoin &) other;

  if (jbbSubset_ != o.jbbSubset_)
    return FALSE;

  // At this point we will consider MJs with different LSRs to be different
  // This can change in the future, but would require updating the duplicate
  // MJ in the cascades memo to add the scheduledLSRs from the inserted one.
  if (scheduledLSRs_ != o.scheduledLSRs_)
    return FALSE;

  return TRUE;
}

RelExpr * MultiJoin::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap)
{
  MultiJoin *result;

  if (derivedNode == NULL)
    result = new (outHeap) MultiJoin(jbbSubset_,outHeap);
  else
    result = (MultiJoin *) derivedNode;

  // I added scheduledLSRs_ too to be consistent with duplicateMatch
  // Read comment on duplicateMatch
  result->scheduledLSRs_ = scheduledLSRs_;

  return RelExpr::copyTopNode(result, outHeap);
}

Join* MultiJoin::splitSubset(const JBBSubset & leftSet,
                             const JBBSubset & rightSet,
                             NABoolean reUseMJ) const
{
  // At this point assert that none of the subsets has a group by member
  CMPASSERT ( (jbbSubset_.getGB() == NULL_CA_ID) &&
              (leftSet.getGB() == NULL_CA_ID) &&
              (rightSet.getGB() == NULL_CA_ID) );
#ifndef NDEBUG
  // assert that left + right == subSet_
  // and left intersect right = phi

  CANodeIdSet unionSet(leftSet.getJBBCs());
  CANodeIdSet intersectSet(leftSet.getJBBCs());

  unionSet += rightSet.getJBBCs();
  intersectSet.intersectSet(rightSet.getJBBCs());

  CMPASSERT ( (unionSet == jbbSubset_.getJBBCs()) &&
              (intersectSet.entries() == 0 ));
#endif

  // Note: Joins including left, semi, anti semi are only created when
  // a single jbbc connected via one of them is split as a single right
  // child. InnerNonSemi joins can be created for any split i.e. any
  // number of jbbcs on the left and the right of the join, but special
  // joins (i.e. left, semi and anti semi joins) are only created when
  // there is a single right child i.e. the rightSet contains only one
  // jbbc that is connected via a special join. This is enforced as follows
  //
  // * The leftSet should be legal: This means that for every jbbc in the
  //   leftSet any predecessor jbbcs should be present in the leftSet.
  // * The rightSet is either a single jbbc or if the rightSet has more
  //   than one jbbc then it should be legal, note that a jbbc connected
  //   via a special join is not a legal set by itself but we allow
  //   creation of special joins assuming the predecessors are present
  //   in the leftSet.
  //
  // An implicit assumption here is that 'this' MultiJoin is legal, which
  // is fair since apart from the top level multijoin, rest of the multijoins
  // are produced by splitting the top level multijoin. This method should
  // not produce illegal multijoins, since we check both leftSet and rightSet
  // for legality. Only time we don't check for legality is when the rightChild
  // is a single jbbc, and a single jbbc does not result in a multijoin.

  if(!leftSet.legal())
    return NULL;

  if((rightSet.getJBBCs().entries() > 1) && (!rightSet.legal()))
    return NULL;

  // everything here goes to statement heap
  CollHeap* outHeap = CmpCommon::statementHeap();

  RelExpr* child0 = generateSubsetExpr(leftSet, reUseMJ);
  RelExpr* child1 = generateSubsetExpr(rightSet, reUseMJ);

  // Flag to remember to pass on the derivedFromRoutineJoin flag if needed.
  NABoolean derivedFromRoutineJoin(FALSE);

  // now form a JoinExpr with these left and right children.
  Join * result = NULL;

  // if the rightSet is a single jbbc, then it could be connected via
  // a special join. In such a case we have to create the appropriate
  // join operator
  if(rightSet.getJBBCs().entries() == 1){

    JBBC * rightChild = rightSet.getJBBCs().getFirst().getNodeAnalysis()
                         ->getJBBC();

    Join * rightChildParentJoin = rightChild->getOriginalParentJoin();

    // If rightChildParentJoin is NULL, then the child is the left
    // child of the left most join and is considered to be connected
    // via a InnerNonSemi join.
    if(rightChildParentJoin)
    {
      if(rightChildParentJoin->derivedFromRoutineJoin())
        derivedFromRoutineJoin = TRUE;

      if(rightChildParentJoin->isSemiJoin())
        result = new (outHeap) Join(child0, child1, REL_SEMIJOIN, NULL);

      if(rightChildParentJoin->isAntiSemiJoin())
        result = new (outHeap) Join(child0, child1, REL_ANTI_SEMIJOIN, NULL);

      if(rightChildParentJoin->isLeftJoin())
      {

        // left joins can have filter preds, i.e. predicates that
        // are applied as filters after applying the join predicate.
        // We need to set them here.
        result = new (outHeap) Join(child0, child1, REL_LEFT_JOIN, NULL);
        result->setSelectionPredicates(rightChild->getLeftJoinFilterPreds());
      }

      if(rightChildParentJoin->isRoutineJoin())
      {
        derivedFromRoutineJoin = TRUE;
        result = new (outHeap) Join(child0, child1, REL_ROUTINE_JOIN, NULL);
        ValueIdSet routineJoinFilterPreds = rightChild->getRoutineJoinFilterPreds();
        ValueIdSet predsToAddToRoutineJoin;

        // add covered filter preds
        for (ValueId filterPred= routineJoinFilterPreds.init();
             routineJoinFilterPreds.next(filterPred);
             routineJoinFilterPreds.advance(filterPred) )
        {
          if(jbbSubset_.coversExpr(filterPred))
            predsToAddToRoutineJoin += filterPred;
        }

        result->setSelectionPredicates(predsToAddToRoutineJoin);
      }

      if(result)
      {
        // set the join predicate for special joins, note predicates
        // for regular InnerNonSemi joins are set as selection predicates
        // in the join relexpr.
        result->setJoinPred(rightChild->getPredsWithPredecessors());

        result->nullInstantiatedOutput().insert(rightChild->
                                                  nullInstantiatedOutput());
      }
    }
  }

  // The join to be created is a regular InnerNonSemi join
  if (!result)
    result = new (outHeap) Join(child0, child1, REL_JOIN, NULL);

  // Make sure we carry the derivedFromRoutineJoin flag with us
  if (derivedFromRoutineJoin)
    result->setDerivedFromRoutineJoin();

  // Share my groupAttr with result
  result->setGroupAttr(getGroupAttr());

  // get inner join predicates
  ValueIdSet selPreds = rightSet.joinPredsWithOther(leftSet);

  // get left join filter preds if any
  selPreds += result->getSelectionPredicates();

  result->setSelectionPredicates(selPreds);

  result->findEquiJoinPredicates();

  // May be I could save a little if i pushdown only to the child(ren)
  // that are not already JBBCs, i.e. multijoins
  result->pushdownCoveredExpr
    (result->getGroupAttr()->getCharacteristicOutputs(),
     result->getGroupAttr()->getCharacteristicInputs(),
     result->selectionPred());

  // We used CutOp as children, to avoid pushing predicates to JBBCs.
  // Now put the actual expression back in case the child is a JBBCs
  if(leftSet.getJBBCs().entries() ==  1)
    result->setChild(0, getJBBCRelExpr(leftSet.getJBBCs().getFirst()));

  // We used CutOp as children, to avoid pushing predicates to JBBCs.
  // Now put the actual expression back in case the child is a JBBCs
  if(rightSet.getJBBCs().entries() ==  1)
    result->setChild(1, getJBBCRelExpr(rightSet.getJBBCs().getFirst()));

  // Temp fixup. We need to take the selectionPred out of MultiJoin
  // for now to prevent that pushed expr from being there. selectionPred
  // is not being used now in MultiJoin xxx.
  if (leftSet.getJBBCs().entries() > 1)
    result->child(0)->selectionPred().clear();
  if (rightSet.getJBBCs().entries() > 1)
    result->child(1)->selectionPred().clear();

  return result;
}

RelExpr* MultiJoin::generateSubsetExpr(const JBBSubset & subset, NABoolean reUseMJ) const
{
  RelExpr* result;

  if (subset.getJBBCs().entries() == 1)
    result = getJBBCCutOpExpr(subset.getJBBCs().getFirst());
  else
    result = createSubsetMultiJoin(subset, reUseMJ);

  return result;
}

// --------------------------------------------------------------------
// Create a MultiJoin that is joining a subset of this MultiJoin children.
// Note: We assume JBBCs are already primed before calling this method.
// THis is a fine assumption at the analysis and post analysis stage.
// --------------------------------------------------------------------
MultiJoin* MultiJoin::createSubsetMultiJoin(const JBBSubset & subset, NABoolean reUseMJ) const
{
  MultiJoin * result = NULL;

  if(reUseMJ)
    result = subset.getSubsetMJ();

  if(result)
    return result;

  CMPASSERT (subset.getGB() == NULL_CA_ID); // no GBs for now
  CMPASSERT (subset.getJBBCs().entries() > 1);

  // everything here goes to statement heap
  CollHeap* outHeap = CmpCommon::statementHeap();

  result = new (outHeap) MultiJoin(subset, outHeap);
  result->setChildren(childrenMap_);

  result->setGroupAttr(new (outHeap) GroupAttributes());

  // Assign my Characteristic Inputs to the newly created subset multi-join.
  result->getGroupAttr()->addCharacteristicInputs
    (getGroupAttr()->getCharacteristicInputs());

  // The following call primes the result Characteristic Outputs.
  // It ensures that the inputs are minimal and outputs are maximal.
  result->primeGroupAttributes();
  // Now compute the GroupAnalysis fields
  result->primeGroupAnalysis();

  return result;
}

// --------------------------------------------------------------------
// use the input JBBCExprGroupMap to set this MultiJoin childrenMap_
// --------------------------------------------------------------------
void MultiJoin::setChildren(const JBBCExprGroupMap & map)
{
  // everything here goes to statement heap
  CollHeap* outHeap = CmpCommon::statementHeap();

  CANodeIdSet jbbcs = jbbSubset_.getJBBCs();

  CMPASSERT (map.getJBBCs().contains(jbbcs));

  Lng32 index = 0;

  for (CANodeId x= jbbcs.init();
       jbbcs.next(x);
       jbbcs.advance(x) )
  {
    JBBCExprGroupEntry* entry = new (outHeap)
      JBBCExprGroupEntry(x, map.getExprGroupIdOfJBBC(x), outHeap);

    childrenMap_.insertAt(index, entry);
	index++;
  }

  return;
}

// --------------------------------------------------------------------
// use origExprs from NodeAnalysis to set this MultiJoin childrenMap_
// --------------------------------------------------------------------
void MultiJoin::setChildrenFromOrigExprs(QueryAnalysis * qa)
{
  CollHeap* outHeap = qa->outHeap();

  CANodeIdSet jbbcs = jbbSubset_.getJBBCs();

  CMPASSERT (qa->getJBBCs().contains(jbbcs));

  Lng32 index = 0;

  for (CANodeId x= jbbcs.init();
       jbbcs.next(x);
       jbbcs.advance(x) )
  {
    JBBCExprGroupEntry* entry = new (outHeap)
      JBBCExprGroupEntry(x, qa->getNodeAnalysis(x)->getOriginalExpr(), outHeap);

    childrenMap_.insertAt(index, entry);
	index++;
  }

  return;
}

// -------------------------------------------------------------------
// This method returns the child as a RelExpr. If the child is
// a group it return a cut-op for that group.
// -------------------------------------------------------------------
RelExpr* MultiJoin::getJBBCRelExpr(CANodeId jbbc) const
{
  RelExpr* result = NULL;

  // everything here goes to statement heap
  CollHeap* outHeap = CmpCommon::statementHeap();

  ExprGroupId exprGroupId = childrenMap_.getExprGroupIdOfJBBC(jbbc);

  if (exprGroupId.getGroupId() == INVALID_GROUP_ID)
    result = exprGroupId.getPtr();
  else
  {
#pragma nowarn(1506)   // warning elimination
    result = new (outHeap) CutOp(exprGroupId.getGroupId(), outHeap);
#pragma warn(1506)  // warning elimination
    ((CutOp*)result)->setGroupIdAndAttr(exprGroupId.getGroupId());
    // may be we should re-use existing cut-op rather than creating
    // new one.
  }

  return result;
}

// -------------------------------------------------------------------
// This method returns the child as a cut-op.
// If the child is a group it return a cut-op for that group.
// If the child is a RelExpr it return a cut-op that shares its GA
// -------------------------------------------------------------------
CutOp* MultiJoin::getJBBCCutOpExpr(CANodeId jbbc) const
{
  // everything here goes to statement heap
  CollHeap* outHeap = CmpCommon::statementHeap();

  CutOp* result = new (outHeap) CutOp(0, outHeap); // we set index to 0 cuz it does not matter

  ExprGroupId exprGroupId = childrenMap_.getExprGroupIdOfJBBC(jbbc);

  if (exprGroupId.getGroupId() == INVALID_GROUP_ID)
    result->setExpr(exprGroupId.getPtr());
  else
    result->setGroupIdAndAttr(exprGroupId.getGroupId());

  return result;
}

// -----------------------------------------------------------------------
// MultJoin::recomputeOuterReferences()
// -----------------------------------------------------------------------
void MultiJoin::recomputeOuterReferences()
{
  // ---------------------------------------------------------------------
  // Delete all those input values that are no longer referenced on
  // this operator.
  // ---------------------------------------------------------------------
  if (NOT getGroupAttr()->getCharacteristicInputs().isEmpty())
  {
    ValueIdSet outerRefs = getGroupAttr()->getCharacteristicInputs();

    // Weed out those expressions not needed by my selectionPred and joinPred
    // xxx instead of taking this from getLocalJoinPreds, should I take it
    // from MultiJoin selectionPred??? refer to getLocalJoinPreds definition
    // and consider preds that referencing inputs!!!
    ValueIdSet exprSet = jbbSubset_.getLocalJoinPreds(); // from JbbSubsetAnalysis
    // Need to include LocalDependentPreds later when supported. Ok now for inner MultiJoins

    exprSet.weedOutUnreferenced(outerRefs);

    // Add back those expressiones needed by my children
    Int32 arity = getArity();

    // outputs produced by JBBCs in this MultiJoin
    ValueIdSet jbbcOutputs;
    for (Int32 i = 0; i < arity; i++)
    {
      outerRefs += child(i)->getGroupAttr()->getCharacteristicInputs();
      jbbcOutputs += child(i)->getGroupAttr()->getCharacteristicOutputs();
      // these inputs are provided by jbbcs in this MultiJoin
    }

    // account for TSJs i.e. values flowing from
    // one jbbc to another within this MultiJoin
    outerRefs -= jbbcOutputs;

    getGroupAttr()->setCharacteristicInputs(outerRefs);
  }
  return;
} // MultiJoin::recomputeOuterReferences()

// ------------------------------------------------------------------------
// Create a left linear subtree of joins from this MultiJoin
// ------------------------------------------------------------------------
Join* MultiJoin::leftLinearize(NABoolean fixJoinOrder, NABoolean createPriviledgedJoins) const
{
  // At this point assert that the subsets has no group by member.
  // If we want to allow GBs in this method in the future we should
  // remember to use computeJBBSubset() instead of the faster
  // jbbcsToJBBSubset() used currently in this method..
  CMPASSERT ( (jbbSubset_.getGB() == NULL_CA_ID));

  const CANodeIdSet & jbbcs = jbbSubset_.getJBBCs();
  // pick some child to make right child of join
  CANodeId jbbcRight(jbbcs.getFirst());

  CANodeIdSet right(jbbcRight);
  CANodeIdSet left(jbbcs);
  left -= jbbcRight;

  NABoolean nonExpander = (left.jbbcsToJBBSubset()->
    isGuaranteedNonExpandingJoin((*jbbcRight.getNodeAnalysis()->getJBBC())));

  Join* result = splitSubset(*(left.jbbcsToJBBSubset()),
                             *(right.jbbcsToJBBSubset()));

  if (fixJoinOrder)
  {
    // disallow left shift rule on the join
    result->contextInsensRules() += JoinLeftShiftRuleNumber;
    // disallow join commutativity on the join
    result->contextInsensRules() += JoinCommutativityRuleNumber;
  }

  if (createPriviledgedJoins)
  {
    result->setJoinFromPTRule();

    if ( CmpCommon::getDefault(COMP_BOOL_120) == DF_OFF)
    {
      result->updatePotential(-2);
    }
  }

  // If left subset is a multiJoin, then linearize it too.
  if (left.entries() > 1)
  {
    // left child must be multiJoin at this point. May be add assert.
    MultiJoin* leftChild = (MultiJoin*)(result->child(0).getPtr());
    result->child(0) = leftChild->leftLinearize(fixJoinOrder,createPriviledgedJoins);
  }

  return result;
} // MultiJoin::leftLinearize()

Join* MultiJoin::createLeftLinearJoinTree
                   (const NAList<CANodeIdSet> * const leftDeepJoinSequence,
                    NAList<MJJoinDirective *> * joinDirectives) const
{
  Join* result = NULL;

  Join* currentJoin=NULL;

  NABoolean reUseMultiJoins = FALSE;

  //Set of all JBBCs in this multi-join.
  //This set will be broken up to make the join tree
  //representing the substitue.
  //The loop below will construct the join tree,
  //starting from the top join.
  CANodeIdSet childSet = getJBBSubset().getJBBCs();

  // variables used in loop below
  MultiJoin * currentMJoin = (MultiJoin *) this;

  // in an iteration this is the parent join
  // e.g. when we are create JOIN3, this will
  // be JOIN2
  Join * parentJoin = NULL;

#ifdef _DEBUG
  if ( CmpCommon::getDefault( NSK_DBG ) == DF_ON  &&
       CmpCommon::getDefault( NSK_DBG_MJRULES_TRACKING ) == DF_ON )
  {
// LCOV_EXCL_START - dpm
    CURRCONTEXT_OPTDEBUG->stream() << "Following is left deep join sequence: " << endl;
    CURRCONTEXT_OPTDEBUG->stream() << endl;
// LCOV_EXCL_STOP
  }
#endif

  UInt32 numJoinChildren = leftDeepJoinSequence->entries();

  CANodeId currentTable = NULL_CA_ID;

  for (UInt32 i = 0; i < (numJoinChildren-1); i++)
  {
    //create JBBSubset representing a comprising component of the
    //leftDeepJoinSequence.
    JBBSubset * joinRightChild = ((*leftDeepJoinSequence)[i]).computeJBBSubset();

    MJJoinDirective * joinDirective = (*joinDirectives)[i];

    //remove all tables that will become right side of join
    childSet.remove((*leftDeepJoinSequence)[i]);

#ifdef _DEBUG
    //print the right child of the current join
    if ( CmpCommon::getDefault( NSK_DBG ) == DF_ON  &&
       CmpCommon::getDefault( NSK_DBG_MJRULES_TRACKING ) == DF_ON )
    {
      CURRCONTEXT_OPTDEBUG->stream() << ((*leftDeepJoinSequence)[i]).getText() << endl; // LCOV_EXCL_LINE - dpm
    }
#endif
    //Get JBBSubset for left side of join
    JBBSubset * joinLeftChild = childSet.computeJBBSubset();

    //create the join by doing a split of the multi-join
    currentJoin = currentMJoin->splitSubset(*joinLeftChild, *joinRightChild, reUseMultiJoins);

    joinDirective->setupJoin(currentJoin);

    if ( CmpCommon::getDefault(COMP_BOOL_120) == DF_OFF)
      currentJoin->updatePotential(-3);

    // if this is the first iteration
    // set the result to be the top join
    if (i == 0)
      result = currentJoin;

    //set the current multi-join to the left child of the
    //join just created
    //change getChild to child().getPointer
    currentMJoin = (MultiJoin*) currentJoin->getChild(0);

    //if there was a parent join, set the left child to
    //point to the new join we just created i.e. currentJoin.
    if (parentJoin)
      parentJoin->setChild(0,currentJoin);

    //set currentJoin to be the parent for the next iteration
    parentJoin = currentJoin;

  }

#ifdef _DEBUG
  //print the left most child
  if ( CmpCommon::getDefault( NSK_DBG ) == DF_ON  &&
       CmpCommon::getDefault( NSK_DBG_MJRULES_TRACKING ) == DF_ON )
  {
// LCOV_EXCL_START  - dpm
    CURRCONTEXT_OPTDEBUG->stream() << ((*leftDeepJoinSequence)[(numJoinChildren-1)]).getText() << endl;
    CURRCONTEXT_OPTDEBUG->stream() << endl;
// LCOV_EXCL_STOP
  }
#endif

  // end - construct the join tree

  // synth the join
  result->synthLogProp();

  //if the right child of the top-most join is a multi-Join,
  //synthesize_it
  if(result->child(1))
    if(result->child(1)->getOperatorType()==REL_MULTI_JOIN)
      result->child(1)->synthLogProp();

  // synth the left child too
  result->child(0)->synthLogProp();

  return result;

} // MultiJoin::createLeftLinearJoinTree()

// ----------------------------------------------------------------
// method for testing purpose right now.
// Uses left linearize for expanding
// ----------------------------------------------------------------
// LCOV_EXCL_START - cnu
RelExpr* MultiJoin::expandMultiJoinSubtree()
{
  // Use default implementation to invoke call on children
  RelExpr::expandMultiJoinSubtree();

  // Now do this operator
  Join* result = leftLinearize();
  return result;
}
// LCOV_EXCL_STOP

// Methods for class MJJoinDirective
MJJoinDirective::MJJoinDirective(CollHeap *outHeap):
leftScheduledLSRs_(outHeap),
rightScheduledLSRs_(outHeap),
heap_(outHeap),
skipNestedJoin_(FALSE),
skipMergeJoin_(FALSE),
skipHashJoin_(FALSE),
skipJoinLeftShift_(FALSE),
skipJoinCommutativity_(FALSE),
joinSource_(Join::GENERAL),
joinFromPTRule_(FALSE)
{
}

void MJJoinDirective::setupJoin(Join * join)
{
  if(skipNestedJoin_)
    join->contextInsensRules() += JoinToTSJRuleNumber;

  if(skipMergeJoin_)
    join->contextInsensRules() += MergeJoinRuleNumber;

  if(skipHashJoin_)
    join->contextInsensRules() += HashJoinRuleNumber;

  if(skipJoinLeftShift_)
    join->contextInsensRules() += JoinLeftShiftRuleNumber;

  if(skipJoinCommutativity_)
    join->contextInsensRules() += JoinCommutativityRuleNumber;

  join->setSource(joinSource_);

  if(rightScheduledLSRs_.entries())
    ((MultiJoin*) (join->getChild(1)))->scheduledLSRs() += rightScheduledLSRs_;

  if(leftScheduledLSRs_.entries())
    ((MultiJoin*) (join->getChild(0)))->scheduledLSRs() += leftScheduledLSRs_;

  if(joinFromPTRule_)
    join->setJoinFromPTRule();

};

// xxx make this private
const ExprGroupId &
  JBBCExprGroupMap::getExprGroupIdOfJBBC(CANodeId jbbc) const
{

#pragma nowarn(1506)   // warning elimination
  Int32 entries = array_.entries();
#pragma warn(1506)  // warning elimination
  for (Int32 i = 0; i < entries; i++)
  {
    CMPASSERT(array_.used(i));
    if (array_[i]->getJBBCId() == jbbc)
    {
      return array_[i]->getExprGroupId();
    }
  }
  // LCOV_EXCL_START
  // Assert on invalid request
  CMPASSERT(FALSE);
  ExprGroupId* dummyResult = new(CmpCommon::statementHeap()) ExprGroupId;
  return *dummyResult;
  // LCOV_EXCL_STOP
}

// ---------------------------------------------------------------
// Compute the Group Analysis for this multi join based on its
// children. Verify its consistent with its jbbSubset_
// ---------------------------------------------------------------
void MultiJoin::primeGroupAnalysis()
{
  // Analysis must have passed now that we have a MultiJoin. Otherwise
  // we must have cleanup problem.
  CMPASSERT (QueryAnalysis::Instance()->isAnalysisON());

  // no GB in multi-joins for now
  CMPASSERT (jbbSubset_.getGB() == NULL_CA_ID);

  GroupAnalysis* groupAnalysis = getGroupAnalysis();

  // recursively call the children appending their subtreeTables
  // and parentJBBViews
  JBBSubset* localView =
    new (groupAnalysis->outHeap()) JBBSubset(groupAnalysis->outHeap());
  CANodeIdSet allSubtreeTables;
  Int32 arity = getArity();
  for (Lng32 i = 0; i < arity; i++)
  {
    GroupAnalysis* childAnalysis = child(i).getPtr()->getGroupAnalysis();
	// use children parentViews to build this join local view
    localView->addSubset(*(childAnalysis->getParentJBBView()));
    allSubtreeTables += childAnalysis->getAllSubtreeTables();
  }
  groupAnalysis->setLocalJBBView(localView);
  groupAnalysis->setSubtreeTables(allSubtreeTables);

  // The computed localJBBView should be the same as the MultiJoin subset.
  CMPASSERT (jbbSubset_ == *localView);

  return;
}

// this method is temp
CostScalar MultiJoin::getChildrenDataFlow() const
{
  CostScalar childrenDataFlow(0);

  UInt32 minRecordLength = (ActiveSchemaDB()->getDefaults())\
                                       .getAsLong(COMP_INT_50);
  Int32 arity = getArity();
  for (Int32 i = 0; i < arity; i++)
  {
    childrenDataFlow +=
      child(i)->getGroupAttr()->getResultCardinalityForEmptyInput() *
      MAXOF(child(i)->getGroupAttr()->getRecordLength(), minRecordLength);
  }

  return childrenDataFlow;
}

// ----------------------------------------------------------------
// SynthLogProp for multi join requires setting numJoinedTables
// ----------------------------------------------------------------
/*
void MultiJoin::synthLogProp()
{
  // Check to see whether this GA has already been associated
  // with a logExpr for synthesis.  If so, no need to resynthesize
  // for this equivalent log. expression.
  if (getGroupAttr()->existsLogExprForSynthesis()) return;

  CMPASSERT ( (jbbSubset_.getGB() == NULL_CA_ID));

  const CANodeIdSet & jbbcs = jbbSubset_.getJBBCs();
  CANodeId jbbcRight(jbbcs.getFirst());

  CANodeIdSet right(jbbcRight);
  CANodeIdSet left(jbbcs);
  left -= jbbcRight;

  Join* join = splitSubset(*(left.jbbcsToJBBSubset()),
                             *(right.jbbcsToJBBSubset()));

  join->synthLogProp();

  CMPASSERT ( getGroupAttr()->getNumJoinedTables() == getArity());
}
*/

Join * MultiJoin::getPreferredJoin()
{
  if(!getGroupAttr()->existsLogExprForSynthesis())
    synthLogProp();

  return (Join*) getGroupAttr()->getLogExprForSynthesis();
}

void MultiJoin::synthLogProp(NormWA * normWAPtr)
{
  // Check to see whether this GA has already been associated
  // with a logExpr for synthesis.  If so, no need to resynthesize
  // for this equivalent log. expression.
  if (getGroupAttr()->existsLogExprForSynthesis()) return;

  CMPASSERT ( (jbbSubset_.getGB() == NULL_CA_ID));

  const CANodeIdSet & jbbcs = jbbSubset_.getJBBCs();

  // Instead of always picking the first JBBC as the right child
  // pick the one with minimum JBBC connections. This will avoid
  // all unnecessary crossproducts

  CANodeId jbbcRight;

  jbbcRight = jbbcs.getJBBCwithMinConnectionsToThisJBBSubset();

  CANodeIdSet right(jbbcRight);
  CANodeIdSet left(jbbcs);
  left -= jbbcRight;

  Join* join = splitSubset(*(left.jbbcsToJBBSubset()),
                             *(right.jbbcsToJBBSubset()));

  join->synthLogProp(normWAPtr);

  getGroupAttr()->setLogExprForSynthesis(join);

  join->setJoinFromMJSynthLogProp();

  jbbSubset_.setSubsetMJ(this);

  CASortedList * synthLogPropPath =
    new (CmpCommon::statementHeap())
    CASortedList(CmpCommon::statementHeap(), jbbcs.entries());

  synthLogPropPath->insert((*(left.jbbcsToJBBSubset()->getSynthLogPropPath())));
  synthLogPropPath->insert(right.getFirst());
  jbbSubset_.setSynthLogPropPath(synthLogPropPath);

  CMPASSERT ( getGroupAttr()->getNumJoinedTables() >= getArity());
}

void MultiJoin::synthLogPropWithMJReuse(NormWA * normWAPtr)
{
  // Check to see whether this GA has already been associated
  // with a logExpr for synthesis.  If so, no need to resynthesize
  // for this equivalent log. expression.
  if (getGroupAttr()->existsLogExprForSynthesis())
  {
    Join * joinExprForSynth =
      (Join *) getGroupAttr()->getLogExprForSynthesis();

    if(joinExprForSynth->isJoinFromMJSynthLogProp())
      return;
  }

  NABoolean reUseMJ = TRUE;

  CMPASSERT ( (jbbSubset_.getGB() == NULL_CA_ID));

  const CANodeIdSet & jbbcs = jbbSubset_.getJBBCs();

  // Instead of always picking the first JBBC as the right child
  // pick the one with minimum JBBC connections. This will avoid
  // all unnecessary crossproducts

  CANodeId jbbcRight;

  jbbcRight = jbbcs.getJBBCwithMinConnectionsToThisJBBSubset();

  CANodeIdSet right(jbbcRight);
  CANodeIdSet left(jbbcs);
  left -= jbbcRight;

  Join* join = splitSubset(*(left.jbbcsToJBBSubset()),
                             *(right.jbbcsToJBBSubset()),
                           reUseMJ);

  //if the left is a MultiJoin, synthesize it using reUse
  //this has to be done before join->synthLogProp to avoid
  //calling MultiJoin::synthLogProp on the left MultiJoin
  //because that does not reUse
  if(left.entries() > 1)
  {
    RelExpr * leftRelExpr = join->child(0)->castToRelExpr();
    if(leftRelExpr &&
       leftRelExpr->getOperator() == REL_MULTI_JOIN)
      ((MultiJoin *) leftRelExpr)->synthLogPropWithMJReuse(normWAPtr);
  }

  join->synthLogProp(normWAPtr);

  join->setJoinFromMJSynthLogProp();

  getGroupAttr()->setLogExprForSynthesis(join);

  jbbSubset_.setSubsetMJ(this);

  CMPASSERT ( getGroupAttr()->getNumJoinedTables() >= getArity());
}

// -----------------------------------------------------------------------
// synthEstLogProp
// -----------------------------------------------------------------------

// LCOV_EXCL_START
// Used for other RelExpr but not MultiJoin
void MultiJoin::synthEstLogProp(const EstLogPropSharedPtr& inputEstLogProp)
{
  CMPASSERT(inputEstLogProp->getNodeSet());

  Join * preferredJoin = jbbSubset_.getPreferredJoin();

  CMPASSERT(preferredJoin->isJoinFromMJSynthLogProp());

  EstLogPropSharedPtr myEstLogProp =
    preferredJoin->getGroupAttr()->outputLogProp(inputEstLogProp);

  getGroupAttr()->addInputOutputLogProp (inputEstLogProp, myEstLogProp, NULL);
} // MultiJoin::synthEstLogProp
// LCOV_EXCL_STOP

void MultiJoin::addLocalExpr(LIST(ExprNode *) &xlist,
			    LIST(NAString) &llist) const
{
  xlist.insert(jbbSubset_.getLocalJoinPreds().rebuildExprTree());
  llist.insert("local_multi_join_predicates");

  xlist.insert(jbbSubset_.getJoinPreds().rebuildExprTree());
  llist.insert("join_predicates_with_others");

  xlist.insert(jbbSubset_.getPredsWithPredecessors().rebuildExprTree());
  llist.insert("join_predicates_with_predecessors");

  xlist.insert(jbbSubset_.getPredsWithSuccessors().rebuildExprTree());
  llist.insert("join_predicates_with_successors");

  RelExpr::addLocalExpr(xlist,llist);
}

// -----------------------------------------------------------------------
// This method is used by the CQS re-write which re-arranged jbbcs
// in the join tree based on CQS tree.
// -----------------------------------------------------------------------
Join* MultiJoin::splitByTables(const CANodeIdSet & leftTableSet,
                               const CANodeIdSet & rightTableSet,
                               NABoolean reUseMJ) const
{
  // At this point assert that my subset has no group by member
  CMPASSERT ( jbbSubset_.getGB() == NULL_CA_ID );

#ifndef NDEBUG
  // assert that left + right == subSet_
  // and left intersect right = phi

  CANodeIdSet tables = jbbSubset_.getSubtreeTables();
  //CMPASSERT (tables == getGroupAnalysis()->getAllSubtreeTables());

  CANodeIdSet unionSet(leftTableSet);
  CANodeIdSet intersectSet(leftTableSet);

  unionSet += rightTableSet;
  intersectSet.intersectSet(rightTableSet);

  CMPASSERT ( (unionSet == tables) &&
              (intersectSet.entries() == 0 ));
#endif

  CANodeIdSet currentTables;
  JBBSubset leftJBBCs;
  JBBSubset rightJBBCs;

  const CANodeIdSet & jbbcs = jbbSubset_.getJBBCs();
  for (CANodeId x= jbbcs.init();  jbbcs.next(x); jbbcs.advance(x) )
  {
    currentTables = x.getNodeAnalysis()->getJBBC()->getSubtreeTables();
    if (leftTableSet.contains(currentTables))
    {
      // This child belong on the left
      leftJBBCs.addJBBC(x);
    }
	else if (rightTableSet.contains(currentTables))
    {
      // This child belong on the right
      rightJBBCs.addJBBC(x);
    }
    else
    {
      // not left, not right, this is illegal split request.
      return NULL;
    }
  }

  return splitSubset(leftJBBCs, rightJBBCs, reUseMJ);
} // MultiJoin::splitByTables()

// -----------------------------------------------------------------------
// analyzeInitialPlan
// -----------------------------------------------------------------------

void MultiJoin::analyzeInitialPlan()
{
  // get the subset analysis for this MultiJoin
  JBBSubsetAnalysis * subsetAnalysis = getJBBSubset().getJBBSubsetAnalysis();
  subsetAnalysis->analyzeInitialPlan(this);

  // analyzeInitialPlan for each child of the MultiJoin
  RelExpr::analyzeInitialPlan();
}

// ---------------------------------------------------------------------
// MultiJoinTester methods
// ---------------------------------------------------------------------
// LCOV_EXCL_START - cnu
NABoolean MultiJoinTester::Test1(RelExpr* originalNonMultiJoinTree, RelExpr* treeConvertedToMultiJoin)
{
  RelExpr* treeCopy = treeConvertedToMultiJoin->copyRelExprTree(CmpCommon::statementHeap());
  treeCopy->synthLogProp();
  treeCopy->expandMultiJoinSubtree();
  treeCopy->synthLogProp();
  // Now assert both trees are the same
  CMPASSERT(originalNonMultiJoinTree->duplicateMatch(*treeCopy));
  return TRUE;
}
// LCOV_EXCL_STOP


text:
<?php

namespace Okatea\Admin\Controller\Config;

use Okatea\Admin\Controller;
use Okatea\Tao\Users\Groups;

class Permissions extends Controller
{
	public function page()
	{
		if (!$this->okt['visitor']->checkPerm('permissions')) {
			return $this->serve401();
		}

		# locales
		$this->okt['l10n']->loadFile($this->okt['locales_path'] . '/%s/admin/permissions');

		$aGroups = [];
		$aPerms = [];

		$aParams = [
			'language' => $this->okt['visitor']->language,
			'group_id_not' => [
				Groups::SUPERADMIN,
				Groups::GUEST
			]
		];

		if (!$this->okt['visitor']->is_superadmin) {
			$aParams['group_id_not'][] = Groups::ADMIN;
		}

		foreach ($this->okt['groups']->getGroups($aParams) as $aGroup)
		{
			$aGroups[$aGroup['group_id']] = $aGroup['title'];

			$aPerms[$aGroup['group_id']] = $aGroup['perms'] ? json_decode($aGroup['perms']) : [];
		}

		if ($this->okt['request']->request->has('sended_form'))
		{
			$perms = $this->okt['request']->request->get('perms');

			foreach ($aGroups as $group_id => $group_title)
			{
				$group_perms = !empty($perms[$group_id]) ? array_keys($perms[$group_id]) : [];

				$this->okt['groups']->updGroupPerms($group_id, $group_perms);
			}

			$this->okt['flashMessages']->success(__('c_a_config_permissions_updated'));

			return $this->redirect($this->generateUrl('config_permissions'));
		}

		return $this->render('Config/Permissions', [
			'aGroups'        => $aGroups,
			'aPerms'         => $aPerms,
			'aPermissions'   => $this->okt['permissions']->getPermsForDisplay()
		]);
	}
}


text:
var exec = require('child_process').exec;

module.exports = {
  childProcess: function(command, arguments, cb) {
    console.log('running command: ' + command + ' ' + arguments.join(' '));
    exec(command + ' ' + arguments.join(' '), cb);
  }
};


text:
package com.intellij.openapi.diff.impl.util;

import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import org.jetbrains.annotations.NotNull;

public class DocumentUtil {

  public static String getText(RangeMarker range) {
    return range.getDocument().getText().substring(range.getStartOffset(), range.getEndOffset());
  }

  public static boolean isEmpty(@NotNull RangeMarker rangeMarker) {
    return rangeMarker.getStartOffset() == rangeMarker.getEndOffset();
  }

  public static int getStartLine(RangeMarker range) {
    final Document doc = range.getDocument();
    if (doc.getTextLength() == 0) return 0;

    return doc.getLineNumber(range.getStartOffset());
  }

  public static int getEndLine(RangeMarker range) {
    Document document = range.getDocument();
    int endOffset = range.getEndOffset();

    int endLine = document.getLineNumber(endOffset);
    if (document.getTextLength() == endOffset && lastLineIsNotEmpty(document, endLine)) {
      return document.getLineCount();
    }
    return endLine;
  }

  private static boolean lastLineIsNotEmpty(Document document, int line) {
    return document.getTextLength() != document.getLineStartOffset(line);
  }

  public static int getLength(RangeMarker rangeMarker) {
    return rangeMarker.getEndOffset() - rangeMarker.getStartOffset();
  }
}


text:
package org.protobee.gnutella.extension;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.protobee.gnutella.util.NameValue;
import org.protobee.util.ByteUtils;

import com.google.common.base.Preconditions;

/**
 * A mutable GGEP extension block. A GGEP block can be thought of as a collection of key/value
 * pairs. A key (extension header) cannot be greater than 15 bytes. The value (extension data) can
 * be 0 to 2^24-1 bytes. Values can be formatted as a number, boolean, or generic blob of binary
 * data. If necessary (e.g., for query replies), GGEP will COBS-encode values to remove null bytes.
 * The order of the extensions is immaterial. Extensions supported by LimeWire have keys specified
 * in this class (prefixed by GGEP_HEADER...)
 */
public class GGEP {

  /** The maximum size of a extension header (key). */
  public static final int MAX_KEY_SIZE_IN_BYTES = 15;

  /** The maximum size of a extension data (value). */
  public static final int MAX_VALUE_SIZE_IN_BYTES = 262143;

  /**
   * The GGEP prefix. A GGEP block will start with this byte value.
   */
  public static final byte GGEP_PREFIX_MAGIC_NUMBER = (byte) 0xC3;

  /**
   * The collection of key/value pairs. Rep. rationale: arrays of bytes are convenient for values
   * since they're easy to convert to numbers or strings. But strings are conventient for keys since
   * they define hashCode and equals.
   */
  private final Map<String, Object> properties = new TreeMap<String, Object>();

  /**
   * Cached hash code value to avoid calculating the hash code from the map each time.
   */
  private volatile int hashCode = 0;

  // ////////////////// Encoding/Decoding (Map <==> byte[]) ///////////////////

  public GGEP() {}

  public GGEP(Map<String, Object> properties) {
    Preconditions.checkNotNull(properties);
    this.properties.putAll(properties);
  }

  public GGEP(GGEP other) {
    Preconditions.checkNotNull(other);
    this.properties.putAll(other.properties);
    this.hashCode = other.hashCode;
  }

  /**
   * Merges the other's GGEP with this' GGEP.
   */
  public void merge(GGEP other) {
    Preconditions.checkNotNull(other);
    properties.putAll(other.properties);
  }

  public int getNumKeys() {
    return properties.size();
  }

  /**
   * Returns the amount of overhead that will be added when the following key/value pair is written.
   *
   * This does *NOT* work for non-ASCII headers, or compressed data.
   */
  public int getHeaderOverhead(String key) {
    byte[] data = get(key);
    Preconditions.checkNotNull(data, "no data for key " + key);

    return 1 + // flags
        key.length() + // header
        data.length + // data
        1 + // required data length
        (data.length > 0x3F ? 1 : 0) + // optional data
        (data.length > 0xFFF ? 1 : 0); // more option data
  }

  // //////////////////////// Key/Value Mutators and Accessors ////////////////

  /**
   * Adds all the specified key/value pairs. TODO: Allow a value to be compressed.
   */
  public void putAll(List<? extends NameValue<?>> fields) throws IllegalArgumentException {
    for (NameValue<?> next : fields) {
      String key = next.getName();
      Object value = next.getValue();
      if (value == null)
        put(key);
      else if (value instanceof byte[])
        put(key, (byte[]) value);
      else if (value instanceof String)
        put(key, (String) value);
      else if (value instanceof Integer)
        put(key, ((Integer) value).intValue());
      else if (value instanceof Long)
        put(key, ((Long) value).longValue());
      else if (value instanceof Byte)
        put(key, ((Byte) value).byteValue());
      else
        throw new IllegalArgumentException("Unknown value: " + value);
    }
  }

  /**
   * Adds a key with data that should be compressed.
   */
  public void putCompressed(String key, byte[] value) throws IllegalArgumentException {
    validateKey(key);
    Preconditions.checkNotNull(value, "Null value for key " + key);
    // validateValue(value); // done when writing. TODO: do here?
    properties.put(key, new NeedsCompression(value));
  }

  /**
   * Adds a key with byte value.
   *
   * @param key the name of the GGEP extension, whose length should be between 1 and 15, inclusive
   * @param value the GGEP extension data.
   */
  public void put(String key, byte value) throws IllegalArgumentException {
    put(key, new byte[] {value});
  }

  /**
   * Adds a key with raw byte value.
   *
   * @param key the name of the GGEP extension, whose length should be between 1 and 15, inclusive
   * @param value the GGEP extension data
   * @exception IllegalArgumentException key is of an illegal length or if value is null.
   */
  public void put(String key, byte[] value) throws IllegalArgumentException {
    validateKey(key);
    validateValue(value, key);
    properties.put(key, value);
  }

  /**
   * Adds a key with string value, using the default character encoding.
   *
   * @param key the name of the GGEP extension, whose length should be between 1 and 15, inclusive
   * @param value the GGEP extension data
   * @exception IllegalArgumentException key is of an illegal length or if value is null
   */
  public void put(String key, String value) throws IllegalArgumentException {
    put(key, value == null ? null : value.getBytes());
  }

  /**
   * Adds a key with integer value.
   *
   * @param key the name of the GGEP extension, whose length should be between 1 and 15, inclusive
   * @param value the GGEP extension data, which should be an unsigned integer
   * @exception IllegalArgumentException key is of an illegal length or if value is negative
   */
  public void put(String key, int value) throws IllegalArgumentException {
    if (value < 0) // int2minLeb doesn't work on negative values
      throw new IllegalArgumentException("Negative value: " + value + " for key: " + key);
    put(key, ByteUtils.int2minLeb(value));
  }

  /**
   * Adds a key with long value.
   *
   * @param key the name of the GGEP extension, whose length should be between 1 and 15, inclusive
   * @param value the GGEP extension data, which should be an unsigned long
   * @exception IllegalArgumentException key is of an illegal length of ir value is negative
   */
  public void put(String key, long value) throws IllegalArgumentException {
    if (value < 0) // long2minLeb doesn't work on negative values
      throw new IllegalArgumentException("Negative value: " + value + " for key: " + key);
    put(key, ByteUtils.long2minLeb(value));
  }

  /**
   * Adds a key without any value.
   *
   * @param key the name of the GGEP extension, whose length should be between 1 and 15, inclusive
   * @exception IllegalArgumentException key is of an illegal length.
   */
  public void put(String key) throws IllegalArgumentException {
    validateKey(key);
    properties.put(key, null);
  }

  /**
   * Returns the value for a key, as raw bytes.
   *
   * @param key the name of the GGEP extension
   * @return the GGEP extension data associated with the key
   * @exception BadGGEPPropertyException extension not found, was corrupt, or has no associated
   *            data. Note that BadGGEPPropertyException is is always thrown for extensions with no
   *            data; use hasKey instead.
   */
  public byte[] getBytes(String key) throws BadGGEPPropertyException {
    byte[] ret = get(key);
    if (ret == null) throw new BadGGEPPropertyException();
    return ret;
  }

  /**
   * Returns the value for a key, as a string.
   *
   * @param key the name of the GGEP extension
   * @return the GGEP extension data associated with the key
   * @exception BadGGEPPropertyException extension not found, was corrupt, or has no associated
   *            data. Note that BadGGEPPropertyException is is always thrown for extensions with no
   *            data; use hasKey instead.
   */
  public String getString(String key) throws BadGGEPPropertyException {
    return new String(getBytes(key));
  }

  /**
   * Returns the value for a key, as an integer
   *
   * @param key the name of the GGEP extension
   * @return the GGEP extension data associated with the key
   * @exception BadGGEPPropertyException extension not found, was corrupt, or has no associated
   *            data. Note that BadGGEPPropertyException is is always thrown for extensions with no
   *            data; use hasKey instead.
   */
  public int getInt(String key) throws BadGGEPPropertyException {
    byte[] bytes = getBytes(key);
    if (bytes.length < 1) throw new BadGGEPPropertyException("No bytes");
    if (bytes.length > 4) throw new BadGGEPPropertyException("Integer too big");
    return ByteUtils.leb2int(bytes, 0, bytes.length);
  }

  /**
   * Returns the value for a key as a long.
   *
   * @param key the name of the GGEP extension
   * @return the GGEP extension data associated with the key
   * @exception BadGGEPPropertyException extension not found, was corrupt, or has no associated
   *            data. Note that BadGGEPPropertyException is is always thrown for extensions with no
   *            data; use hasKey instead.
   */
  public long getLong(String key) throws BadGGEPPropertyException {
    byte[] bytes = getBytes(key);
    if (bytes.length < 1) throw new BadGGEPPropertyException("No bytes");
    if (bytes.length > 8) throw new BadGGEPPropertyException("Integer too big");
    return ByteUtils.leb2long(bytes, 0, bytes.length);
  }

  /**
   * Returns whether this has the given key.
   *
   * @param key the name of the GGEP extension
   * @return true if this has a key
   */
  public boolean hasKey(String key) {
    return properties.containsKey(key);
  }

  /**
   * Returns the set of keys.
   *
   * @return a set of all the GGEP extension header name in this, each as a String.
   */
  public Set<String> getHeaders() {
    return properties.keySet();
  }

  /**
   * Returns whether this GGEP is empty or not.
   */
  public boolean isEmpty() {
    return properties.isEmpty();
  }

  /**
   * Gets the byte[] data from props.
   */
  public byte[] get(String key) {
    Object value = properties.get(key);
    if (value instanceof NeedsCompression)
      return ((NeedsCompression) value).data;
    else
      return (byte[]) value;
  }

  public boolean isCompressed(String key) {
    return properties.get(key) instanceof NeedsCompression;
  }

  private void validateKey(String key) throws IllegalArgumentException {
    byte[] bytes = key.getBytes();
    if (key.equals("") || (bytes.length > MAX_KEY_SIZE_IN_BYTES) || containsNull(bytes))
      throw new IllegalArgumentException();
  }

  private void validateValue(byte[] value, String key) throws IllegalArgumentException {
    if (value == null) throw new IllegalArgumentException("null value for key: " + key);
    if (value.length > MAX_VALUE_SIZE_IN_BYTES)
      throw new IllegalArgumentException("value (" + value + ") too large for key: " + key);
  }

  private boolean containsNull(byte[] bytes) {
    if (bytes != null) {
      for (int i = 0; i < bytes.length; i++)
        if (bytes[i] == 0x0) return true;
    }
    return false;
  }

  // ////////////////////////////// Miscellany ///////////////////////////////

  /**
   * @return True if the two Maps that represent header/data pairs are equivalent.
   */
  @Override
  public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof GGEP)) return false;
    // This is O(n lg n) time with n keys. It would be great if we could
    // just check that the trees are isomorphic. I don't think this code is
    // really used anywhere, however.
    return this.subset((GGEP) o) && ((GGEP) o).subset(this);
  }

  /**
   * Returns true if this is a subset of other, e.g., all of this' keys can be found in OTHER with
   * the same value.
   */
  private boolean subset(GGEP other) {
    for (String key : properties.keySet()) {
      byte[] v1 = this.get(key);
      byte[] v2 = other.get(key);
      // Remember that v1 and v2 can be null.
      if ((v1 == null) != (v2 == null)) return false;
      if (v1 != null && !Arrays.equals(v1, v2)) return false;
    }
    return true;
  }

  // overrides Object.hashCode to be consistent with equals
  @Override
  public int hashCode() {
    if (hashCode == 0) {
      hashCode = 37 * properties.hashCode();
    }
    return hashCode;
  }

  /**
   * Marker class that wraps a byte[] value, if that value is going to require compression upon
   * write. TODO: don't use this, and instead keep a set of keys that are flagged for compression
   */
  public static class NeedsCompression {
    final byte[] data;

    public NeedsCompression(byte[] data) {
      this.data = data;
    }
  }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Etusivu extends CI_Controller {

public function index () {
	$data['sivun_sisalto']='etusivu/index';
	$this->load->view('menu/sisalto',$data);
}

}


text:
<?php
//## NextScripts Facebook Connection Class
$nxs_snapAPINts[] = array('code'=>'BG', 'lcode'=>'bg', 'name'=>'Blogger');

if (!class_exists("nxs_class_SNAP_BG")) { class nxs_class_SNAP_BG {

    var $ntCode = 'BG';
    var $ntLCode = 'bg';

    function doPost($options, $message){ if (!is_array($options)) return false;
      foreach ($options as $ii=>$ntOpts) $out[$ii] = $this->doPostToNT($ntOpts, $message);
      return $out;
    }

    function doPostToNT($options, $message){ $badOut = array('pgID'=>'', 'isPosted'=>0, 'pDate'=>date('Y-m-d H:i:s'), 'Error'=>''); // prr($message);  prr($options);
      //## Check API Lib
      //if (!function_exists('doConnectToBlogger')) if (file_exists('apis/postToGooglePlus.php')) require_once ('apis/postToGooglePlus.php'); elseif (file_exists('/home/_shared/deSrc.php')) require_once ('/home/_shared/deSrc.php');
      //## Check settings
      if (!is_array($options)) { $badOut['Error'] = 'No Options'; return $badOut; }
      if ( (!isset($options['bgUName']) || empty($options['bgPass'])) && empty($options['AccessToken'])) { $badOut['Error'] = 'Not Configured'; return $badOut; }
      //## Format
      if (!empty($message['pText'])) $msg = $message['pText']; else $msg = nxs_doFormatMsg($options['bgMsgFormat'], $message);
      if (!empty($message['pTitle'])) $msgT = $message['pTitle']; else $msgT = nxs_doFormatMsg($options['bgMsgTFormat'], $message);
      if ($options['bgInclTags']=='1') $tags = nsTrnc($message['tags'], 195, ',', ''); else $tags = '';
      //## Check/Fix HTML
      if (class_exists('DOMDocument')) {$doc = new DOMDocument();  @$doc->loadHTML('<?xml encoding="UTF-8">' .$msg); $doc->encoding = 'UTF-8'; $msg = $doc->saveHTML(); $msg = CutFromTo($msg, '', '');
        $msg = preg_replace('/
/','
',$msg);   $msg = preg_replace('//','',$msg);
        require ('apis/htmlNumTable.php');  if (is_array($HTML401NamedToNumeric)) { $msg = strtr($msg, $HTML401NamedToNumeric); $msgT = strtr($msgT, $HTML401NamedToNumeric); }
      }
      $msg = preg_replace('/


text:
package io.youi.net

case class IPv4(part1: Int = 127, part2: Int = 0, part3: Int = 0, part4: Int = 1) extends IP {
  lazy val address = Array(part1, part2, part3, part4)
  lazy val addressString = s"$part1.$part2.$part3.$part4"
}


text:
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
//     ResourceLib Original Code from http://resourcelib.codeplex.com
//     Original Copyright (c) 2008-2009 Vestris Inc.
//     Changes Copyright (c) 2011 Garrett Serack . All rights reserved.
// </copyright>
// <license>
// MIT License
// You may freely use and distribute this software under the terms of the following license agreement.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
// </license>
//-----------------------------------------------------------------------

namespace ClrPlus.Windows.PeBinary.ResourceLib {
    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    using Api.Structures;

    /// <summary>
    ///     A font directory entry.
    /// </summary>
    public class FontDirectoryEntry {
        private string _deviceName;
        private string _faceName;
        private FontDirEntry _font;
        private UInt16 _fontOrdinal;

        /// <summary>
        ///     Font ordinal.
        /// </summary>
        public UInt16 FontOrdinal {
            get {
                return _fontOrdinal;
            }
            set {
                _fontOrdinal = value;
            }
        }

        /// <summary>
        ///     Typeface name of the font.
        /// </summary>
        public string FaceName {
            get {
                return _faceName;
            }
            set {
                _faceName = value;
            }
        }

        /// <summary>
        ///     Specifies the name of the device if this font file is designated for a specific device.
        /// </summary>
        public string DeviceName {
            get {
                return _deviceName;
            }
            set {
                _deviceName = value;
            }
        }

        /// <summary>
        ///     Font information.
        /// </summary>
        public FontDirEntry Font {
            get {
                return _font;
            }
            set {
                _font = value;
            }
        }

        /// <summary>
        ///     Read the font directory entry.
        /// </summary>
        /// <param name="lpRes">Pointer in memory.</param>
        /// <returns>Pointer to the end of the font directory entry.</returns>
        internal IntPtr Read(IntPtr lpRes) {
            var lpHead = lpRes;

            _fontOrdinal = (UInt16)Marshal.ReadInt16(lpRes);
            lpRes = new IntPtr(lpRes.ToInt32() + 2);

            _font = (FontDirEntry)Marshal.PtrToStructure(lpRes, typeof (FontDirEntry));

            lpRes = new IntPtr(lpRes.ToInt32() + Marshal.SizeOf(_font));

            _deviceName = Marshal.PtrToStringAnsi(lpRes);
            lpRes = new IntPtr(lpRes.ToInt32() + _deviceName.Length + 1);

            _faceName = Marshal.PtrToStringAnsi(lpRes);
            lpRes = new IntPtr(lpRes.ToInt32() + _faceName.Length + 1);

            return lpRes;
        }

        /// <summary>
        ///     Write the font directory entry to a binary stream.
        /// </summary>
        /// <param name="w">Binary stream.</param>
        public void Write(BinaryWriter w) {
            w.Write(_fontOrdinal);
            w.Write(ResourceUtil.GetBytes(_font));

            // device name
            if (string.IsNullOrEmpty(_deviceName)) {
                w.Write((byte)0);
            } else {
                w.Write(Encoding.ASCII.GetBytes(_deviceName));
            }

            // face name
            if (string.IsNullOrEmpty(_faceName)) {
                w.Write((byte)0);
            } else {
                w.Write(Encoding.ASCII.GetBytes(_faceName));
            }
        }
    }
}


text:
from django.conf.urls import url, patterns
from .views import box

urlpatterns = patterns('',
    url(r'(?P<label>[\w-]+)/$', box, name='box'),
)


text:
package com.llf.basemodel.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.DisplayMetrics;
import android.view.WindowManager;

/**
 * Created by llf on 2017/3/2.
 * 设置一些基础的东西(1.dp,sp,px转化2.获取手机宽高3.缓存)
 */

public class SettingUtil {
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     * context.getResources().getDisplayMetrics().density 1dp对应多少px,加0.5是为了四舍五入
     */
    public static int dip2px(Context context, float dpValue) {
        //这个得到的不应该叫做密度,应该是密度的一个比例,在160dpi手机上这个值是1,dpi屏幕像素密度(是基准)
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int sp2px(Context context, float spValue) {
        //scaledDensity为字体缩放比例
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 缓存相关
     */
    public static void setTagString(Context context, String tag, String value) {
        SharedPreferences.Editor editor = context.getSharedPreferences("cache", Context.MODE_PRIVATE).edit();
        editor.putString(tag, value);
        editor.commit();
    }

    public static String getTagString(Context context, String tag) {
        SharedPreferences sp = context.getSharedPreferences("cache", Context.MODE_PRIVATE);
        return sp.getString(tag, "");
    }

    /**
     * 默认的缓存文件
     */
    public static void setTagString(Activity activity, String tag, String value) {
        SharedPreferences.Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit();
        editor.putString(tag, value);
        editor.commit();
    }

    public static String getTagString(Activity activity, String tag) {
        SharedPreferences sp = activity.getPreferences(Context.MODE_PRIVATE);
        return sp.getString(tag, "");
    }
}


text:
require 'osx/cocoa'
require 'yaml'
require 'fileutils'
require File.expand_path('../passenger_pane_config', __FILE__) unless ENV['TESTING_PASSENGER_PREF']

class String
  def bypass_safe_level_1
    str = dup
    str.untaint
    str
  end
end

class ConfigInstaller
  attr_reader :data

  def initialize(yaml_data, extra_command = nil)
    @data = YAML.load(yaml_data)
    @extra_command = extra_command
  end

  def add_to_hosts(index)
    server_name = @data[index]['host']
    [server_name, *@data[index]['aliases'].split(' ')].each do |host|
      OSX::NSLog("Will add host: #{host}")
      system "/usr/bin/dscl localhost -create /Local/Default/Hosts/#{host.bypass_safe_level_1} IPAddress 127.0.0.1"
    end
  end

  def verify_vhost_conf
    unless File.exist? PassengerPaneConfig::PASSENGER_APPS_DIR
      OSX::NSLog("Will create directory: #{PassengerPaneConfig::PASSENGER_APPS_DIR}")
      FileUtils.mkdir_p PassengerPaneConfig::PASSENGER_APPS_DIR
    end
  end

  def verify_httpd_conf
	unless File.exist?(PassengerPaneConfig::PASSENGER_PANE_VHOST_CONF)
      OSX::NSLog("Will write passenger pane vhosts conf to: #{PassengerPaneConfig::PASSENGER_APPS_DIR}")
	  File.open(PassengerPaneConfig::PASSENGER_PANE_VHOST_CONF, 'w') do |f|
        f << %{
# Added by the Passenger preference pane
# Make sure to include the Passenger configuration
# (the LoadModule, PassengerRoot, and PassengerRuby directives)
# before this section.

<IfModule passenger_module>
  NameVirtualHost *:80
  <VirtualHost *:80>
    ServerName _default_
  </VirtualHost>
  Include #{PassengerPaneConfig::PASSENGER_APPS_DIR}/*.conf
</IfModule>}
      end
    end
  end

  def create_vhost_conf(index)
    app = @data[index]
    public_dir = File.join(app['path'], 'public')
    vhost = [
      "<VirtualHost #{app['vhostname']}>",
      "  ServerName #{app['host']}",
      ("  ServerAlias #{app['aliases']}" unless app['aliases'].empty?),
      "  DocumentRoot \"#{public_dir}\"",
      "  #{app['app_type'].capitalize}Env #{app['environment']}",
      (app['user_defined_data'] unless app['user_defined_data'].empty?),
      "</VirtualHost>"
    ].compact.join("\n")

    OSX::NSLog("Will write vhost file: #{app['config_path']}\nData: #{vhost}")
    File.open(app['config_path'].bypass_safe_level_1, 'w') { |f| f << vhost }
  end

  def restart_apache!
    system PassengerPaneConfig::APACHE_RESTART_COMMAND
  end

  def install!
    verify_vhost_conf
    verify_httpd_conf

    (0..(@data.length - 1)).each do |index|
      add_to_hosts index
      create_vhost_conf index
    end

    restart_apache!
  end
end

if $0 == __FILE__
  OSX::NSLog("Will try to write config(s).")
  ConfigInstaller.new(*ARGV).install!
end


text:
<!DOCTYPE html>

  <title>LocaleManager - API Documentation</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <meta name="fragment" content="!">

  <link rel="shortcut icon" type="image/ico" href="favicon.ico" />
  <link rel="stylesheet" href="resources/css/app-0f2069573328c567a9a80772dbcb26f1.css" type="text/css" />
  <link rel="stylesheet" href="styles-8a82b1f65a21ab5f376f2bd2dfac7715.css" type="text/css" />

LocaleManager - API Documentation

LocaleManager API Documentation

nineam

localization

nineam.localization.LocaleManager

nineam.localization.LocalePlugin

nineam.localization.delegate.LocaleDelegate

nineam.localization.event.LocaleEvent

nineam.localization.model.ClientModel

nineam.localization.model.LocaleModel

nineam.localization.store.LocalesStore

nineam.localization.util.Persistence

Generated on Thu 25 Jul 2013 10:06:37 by JSDuck 5.0.0.beta2.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

    <bean id="cool" class="org.apache.camel.spring.issues.CoolService"/>

    <camelContext trace="true" xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="direct:start"/>
            <to uri="log:foo"/>
            <split>
                <method ref="cool" method="split"/>
                <transform><simple>Hello ${body}</simple></transform>
                <to uri="mock:split"/>
            </split>
        </route>
    </camelContext>

</beans>


text:
package org.terasology.rendering.dag;

/**
 * TODO: Add javadocs
 */
public interface RenderPipelineTask {
    void execute();
}