text:
#ifndef http_parser_h
#define http_parser_h
#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>
#if defined(_WIN32) && !defined(__MINGW32__)
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;

typedef unsigned int size_t;
typedef int ssize_t;
#else
#include <stdint.h>
#endif

/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
 * faster
 */
#ifndef HTTP_PARSER_STRICT
# define HTTP_PARSER_STRICT 1
#else
# define HTTP_PARSER_STRICT 0
#endif

/* Maximium header size allowed */
#define HTTP_MAX_HEADER_SIZE (80*1024)

typedef struct http_parser http_parser;
typedef struct http_parser_settings http_parser_settings;

/* Callbacks should return non-zero to indicate an error. The parser will
 * then halt execution.
 *
 * The one exception is on_headers_complete. In a HTTP_RESPONSE parser
 * returning '1' from on_headers_complete will tell the parser that it
 * should not expect a body. This is used when receiving a response to a
 * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
 * chunked' headers that indicate the presence of a body.
 *
 * http_data_cb does not return data chunks. It will be call arbitrarally
 * many times for each string. E.G. you might get 10 callbacks for "on_path"
 * each providing just a few characters more data.
 */
typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
typedef int (*http_cb) (http_parser*);

/* Request Methods */
enum http_method
  { HTTP_DELETE    = 0
  , HTTP_GET
  , HTTP_HEAD
  , HTTP_POST
  , HTTP_PUT
  /* pathological */
  , HTTP_CONNECT
  , HTTP_OPTIONS
  , HTTP_TRACE
  /* webdav */
  , HTTP_COPY
  , HTTP_LOCK
  , HTTP_MKCOL
  , HTTP_MOVE
  , HTTP_PROPFIND
  , HTTP_PROPPATCH
  , HTTP_UNLOCK
  /* subversion */
  , HTTP_REPORT
  , HTTP_MKACTIVITY
  , HTTP_CHECKOUT
  , HTTP_MERGE
  /* upnp */
  , HTTP_MSEARCH
  , HTTP_NOTIFY
  , HTTP_SUBSCRIBE
  , HTTP_UNSUBSCRIBE
  };

enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };

struct http_parser {
  /** PRIVATE **/
  unsigned char type : 2;
  unsigned char flags : 6;
  unsigned char state;
  unsigned char header_state;
  unsigned char index;

  uint32_t nread;
  int64_t content_length;

  /** READ-ONLY **/
  unsigned short http_major;
  unsigned short http_minor;
  unsigned short status_code; /* responses only */
  unsigned char method;    /* requests only */
  const char *header_field_mark;
  const char *header_value_mark;
  const char *fragment_mark;
  const char *query_string_mark;
  const char *schema_mark;
  const char *host_mark;
  const char *port_mark;
  const char *path_mark;
  const char *url_mark;

  /* 1 = Upgrade header was present and the parser has exited because of that.
   * 0 = No upgrade header present.
   * Should be checked when http_parser_execute() returns in addition to
   * error checking.
   */
  char upgrade;

  /** PUBLIC **/
  void *data; /* A pointer to get hook to the "connection" or "socket" object */
};

struct http_parser_settings {
  http_cb      on_message_begin;
  http_data_cb on_schema;
  http_data_cb on_host;
  http_data_cb on_port;
  http_data_cb on_path;
  http_data_cb on_query_string;
  http_data_cb on_url;
  http_data_cb on_fragment;
  http_data_cb on_header_field;
  http_data_cb on_header_value;
  http_cb      on_headers_complete;
  http_data_cb on_body;
  http_cb      on_message_complete;
};

void http_parser_init(http_parser *parser, enum http_parser_type type);

size_t http_parser_execute(http_parser *parser,
                           const http_parser_settings *settings,
                           const char *data,
                           size_t len);

/* If http_should_keep_alive() in the on_headers_complete or
 * on_message_complete callback returns true, then this will be should be
 * the last message on the connection.
 * If you are the server, respond with the "Connection: close" header.
 * If you are the client, close the connection.
 */
int http_should_keep_alive(http_parser *parser);

/* Returns a string version of the HTTP method. */
const char *http_method_str(enum http_method);

#ifdef __cplusplus
}
#endif
#endif


text:
package org.apache.spark.sql.execution.adaptive

import java.util
import java.util.concurrent.LinkedBlockingQueue

import scala.collection.JavaConverters._
import scala.collection.concurrent.TrieMap
import scala.collection.mutable
import scala.concurrent.ExecutionContext
import scala.util.control.NonFatal

import org.apache.spark.broadcast
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, ReturnAnswer}
import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
import org.apache.spark.sql.catalyst.rules.{PlanChangeLogger, Rule}
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.catalyst.util.sideBySide
import org.apache.spark.sql.errors.QueryExecutionErrors
import org.apache.spark.sql.execution._
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanExec._
import org.apache.spark.sql.execution.bucketing.DisableUnnecessaryBucketedScan
import org.apache.spark.sql.execution.exchange._
import org.apache.spark.sql.execution.ui.{SparkListenerSQLAdaptiveExecutionUpdate, SparkListenerSQLAdaptiveSQLMetricUpdates, SQLPlanMetric}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.vectorized.ColumnarBatch
import org.apache.spark.util.{SparkFatalException, ThreadUtils}

/**
 * A root node to execute the query plan adaptively. It splits the query plan into independent
 * stages and executes them in order according to their dependencies. The query stage
 * materializes its output at the end. When one stage completes, the data statistics of the
 * materialized output will be used to optimize the remainder of the query.
 *
 * To create query stages, we traverse the query tree bottom up. When we hit an exchange node,
 * and if all the child query stages of this exchange node are materialized, we create a new
 * query stage for this exchange node. The new stage is then materialized asynchronously once it
 * is created.
 *
 * When one query stage finishes materialization, the rest query is re-optimized and planned based
 * on the latest statistics provided by all materialized stages. Then we traverse the query plan
 * again and create more stages if possible. After all stages have been materialized, we execute
 * the rest of the plan.
 */
case class AdaptiveSparkPlanExec(
    inputPlan: SparkPlan,
    @transient context: AdaptiveExecutionContext,
    @transient preprocessingRules: Seq[Rule[SparkPlan]],
    @transient isSubquery: Boolean,
    @transient override val supportsColumnar: Boolean = false)
  extends LeafExecNode {

  @transient private val lock = new Object()

  @transient private val logOnLevel: ( => String) => Unit = conf.adaptiveExecutionLogLevel match {
    case "TRACE" => logTrace(_)
    case "DEBUG" => logDebug(_)
    case "INFO" => logInfo(_)
    case "WARN" => logWarning(_)
    case "ERROR" => logError(_)
    case _ => logDebug(_)
  }

  @transient private val planChangeLogger = new PlanChangeLogger[SparkPlan]()

  // The logical plan optimizer for re-optimizing the current logical plan.
  @transient private val optimizer = new AQEOptimizer(conf,
    session.sessionState.adaptiveRulesHolder.runtimeOptimizerRules)

  // `EnsureRequirements` may remove user-specified repartition and assume the query plan won't
  // change its output partitioning. This assumption is not true in AQE. Here we check the
  // `inputPlan` which has not been processed by `EnsureRequirements` yet, to find out the
  // effective user-specified repartition. Later on, the AQE framework will make sure the final
  // output partitioning is not changed w.r.t the effective user-specified repartition.
  @transient private val requiredDistribution: Option[Distribution] = if (isSubquery) {
    // Subquery output does not need a specific output partitioning.
    Some(UnspecifiedDistribution)
  } else {
    AQEUtils.getRequiredDistribution(inputPlan)
  }

  @transient private val costEvaluator =
    conf.getConf(SQLConf.ADAPTIVE_CUSTOM_COST_EVALUATOR_CLASS) match {
      case Some(className) => CostEvaluator.instantiate(className, session.sparkContext.getConf)
      case _ => SimpleCostEvaluator(conf.getConf(SQLConf.ADAPTIVE_FORCE_OPTIMIZE_SKEWED_JOIN))
    }

  // A list of physical plan rules to be applied before creation of query stages. The physical
  // plan should reach a final status of query stages (i.e., no more addition or removal of
  // Exchange nodes) after running these rules.
  @transient private val queryStagePreparationRules: Seq[Rule[SparkPlan]] = {
    // For cases like `df.repartition(a, b).select(c)`, there is no distribution requirement for
    // the final plan, but we do need to respect the user-specified repartition. Here we ask
    // `EnsureRequirements` to not optimize out the user-specified repartition-by-col to work
    // around this case.
    val ensureRequirements =
      EnsureRequirements(requiredDistribution.isDefined, requiredDistribution)
    Seq(
      RemoveRedundantProjects,
      ensureRequirements,
      AdjustShuffleExchangePosition,
      ValidateSparkPlan,
      ReplaceHashWithSortAgg,
      RemoveRedundantSorts,
      DisableUnnecessaryBucketedScan,
      OptimizeSkewedJoin(ensureRequirements)
    ) ++ context.session.sessionState.adaptiveRulesHolder.queryStagePrepRules
  }

  // A list of physical optimizer rules to be applied to a new stage before its execution. These
  // optimizations should be stage-independent.
  @transient private val queryStageOptimizerRules: Seq[Rule[SparkPlan]] = Seq(
    PlanAdaptiveDynamicPruningFilters(this),
    ReuseAdaptiveSubquery(context.subqueryCache),
    OptimizeSkewInRebalancePartitions,
    CoalesceShufflePartitions(context.session),
    // `OptimizeShuffleWithLocalRead` needs to make use of 'AQEShuffleReadExec.partitionSpecs'
    // added by `CoalesceShufflePartitions`, and must be executed after it.
    OptimizeShuffleWithLocalRead
  )

  // This rule is stateful as it maintains the codegen stage ID. We can't create a fresh one every
  // time and need to keep it in a variable.
  @transient private val collapseCodegenStagesRule: Rule[SparkPlan] =
    CollapseCodegenStages()

  // A list of physical optimizer rules to be applied right after a new stage is created. The input
  // plan to these rules has exchange as its root node.
  private def postStageCreationRules(outputsColumnar: Boolean) = Seq(
    ApplyColumnarRulesAndInsertTransitions(
      context.session.sessionState.columnarRules, outputsColumnar),
    collapseCodegenStagesRule
  )

  private def optimizeQueryStage(plan: SparkPlan, isFinalStage: Boolean): SparkPlan = {
    val optimized = queryStageOptimizerRules.foldLeft(plan) { case (latestPlan, rule) =>
      val applied = rule.apply(latestPlan)
      val result = rule match {
        case _: AQEShuffleReadRule if !applied.fastEquals(latestPlan) =>
          val distribution = if (isFinalStage) {
            // If `requiredDistribution` is None, it means `EnsureRequirements` will not optimize
            // out the user-specified repartition, thus we don't have a distribution requirement
            // for the final plan.
            requiredDistribution.getOrElse(UnspecifiedDistribution)
          } else {
            UnspecifiedDistribution
          }
          if (ValidateRequirements.validate(applied, distribution)) {
            applied
          } else {
            logDebug(s"Rule ${rule.ruleName} is not applied as it breaks the " +
              "distribution requirement of the query plan.")
            latestPlan
          }
        case _ => applied
      }
      planChangeLogger.logRule(rule.ruleName, latestPlan, result)
      result
    }
    planChangeLogger.logBatch("AQE Query Stage Optimization", plan, optimized)
    optimized
  }

  @transient val initialPlan = context.session.withActive {
    applyPhysicalRules(
      inputPlan, queryStagePreparationRules, Some((planChangeLogger, "AQE Preparations")))
  }

  @volatile private var currentPhysicalPlan = initialPlan

  private var isFinalPlan = false

  private var currentStageId = 0

  /**
   * Return type for `createQueryStages`
   * @param newPlan the new plan with created query stages.
   * @param allChildStagesMaterialized whether all child stages have been materialized.
   * @param newStages the newly created query stages, including new reused query stages.
   */
  private case class CreateStageResult(
    newPlan: SparkPlan,
    allChildStagesMaterialized: Boolean,
    newStages: Seq[QueryStageExec])

  def executedPlan: SparkPlan = currentPhysicalPlan

  override def conf: SQLConf = context.session.sessionState.conf

  override def output: Seq[Attribute] = inputPlan.output

  override def doCanonicalize(): SparkPlan = inputPlan.canonicalized

  override def resetMetrics(): Unit = {
    metrics.valuesIterator.foreach(_.reset())
    executedPlan.resetMetrics()
  }

  private def getExecutionId: Option[Long] = {
    // If the `QueryExecution` does not match the current execution ID, it means the execution ID
    // belongs to another (parent) query, and we should not call update UI in this query.
    Option(context.session.sparkContext.getLocalProperty(SQLExecution.EXECUTION_ID_KEY))
      .map(_.toLong).filter(SQLExecution.getQueryExecution(_) eq context.qe)
  }

  private def getFinalPhysicalPlan(): SparkPlan = lock.synchronized {
    if (isFinalPlan) return currentPhysicalPlan

    // In case of this adaptive plan being executed out of `withActive` scoped functions, e.g.,
    // `plan.queryExecution.rdd`, we need to set active session here as new plan nodes can be
    // created in the middle of the execution.
    context.session.withActive {
      val executionId = getExecutionId
      // Use inputPlan logicalLink here in case some top level physical nodes may be removed
      // during `initialPlan`
      var currentLogicalPlan = inputPlan.logicalLink.get
      var result = createQueryStages(currentPhysicalPlan)
      val events = new LinkedBlockingQueue[StageMaterializationEvent]()
      val errors = new mutable.ArrayBuffer[Throwable]()
      var stagesToReplace = Seq.empty[QueryStageExec]
      while (!result.allChildStagesMaterialized) {
        currentPhysicalPlan = result.newPlan
        if (result.newStages.nonEmpty) {
          stagesToReplace = result.newStages ++ stagesToReplace
          executionId.foreach(onUpdatePlan(_, result.newStages.map(_.plan)))

          // SPARK-33933: we should submit tasks of broadcast stages first, to avoid waiting
          // for tasks to be scheduled and leading to broadcast timeout.
          // This partial fix only guarantees the start of materialization for BroadcastQueryStage
          // is prior to others, but because the submission of collect job for broadcasting is
          // running in another thread, the issue is not completely resolved.
          val reorderedNewStages = result.newStages
            .sortWith {
              case (_: BroadcastQueryStageExec, _: BroadcastQueryStageExec) => false
              case (_: BroadcastQueryStageExec, _) => true
              case _ => false
            }

          // Start materialization of all new stages and fail fast if any stages failed eagerly
          reorderedNewStages.foreach { stage =>
            try {
              stage.materialize().onComplete { res =>
                if (res.isSuccess) {
                  events.offer(StageSuccess(stage, res.get))
                } else {
                  events.offer(StageFailure(stage, res.failed.get))
                }
                // explicitly clean up the resources in this stage
                stage.cleanupResources()
              }(AdaptiveSparkPlanExec.executionContext)
            } catch {
              case e: Throwable =>
                cleanUpAndThrowException(Seq(e), Some(stage.id))
            }
          }
        }

        // Wait on the next completed stage, which indicates new stats are available and probably
        // new stages can be created. There might be other stages that finish at around the same
        // time, so we process those stages too in order to reduce re-planning.
        val nextMsg = events.take()
        val rem = new util.ArrayList[StageMaterializationEvent]()
        events.drainTo(rem)
        (Seq(nextMsg) ++ rem.asScala).foreach {
          case StageSuccess(stage, res) =>
            stage.resultOption.set(Some(res))
          case StageFailure(stage, ex) =>
            errors.append(ex)
        }

        // In case of errors, we cancel all running stages and throw exception.
        if (errors.nonEmpty) {
          cleanUpAndThrowException(errors.toSeq, None)
        }

        // Try re-optimizing and re-planning. Adopt the new plan if its cost is equal to or less
        // than that of the current plan; otherwise keep the current physical plan together with
        // the current logical plan since the physical plan's logical links point to the logical
        // plan it has originated from.
        // Meanwhile, we keep a list of the query stages that have been created since last plan
        // update, which stands for the "semantic gap" between the current logical and physical
        // plans. And each time before re-planning, we replace the corresponding nodes in the
        // current logical plan with logical query stages to make it semantically in sync with
        // the current physical plan. Once a new plan is adopted and both logical and physical
        // plans are updated, we can clear the query stage list because at this point the two plans
        // are semantically and physically in sync again.
        val logicalPlan = replaceWithQueryStagesInLogicalPlan(currentLogicalPlan, stagesToReplace)
        val afterReOptimize = reOptimize(logicalPlan)
        if (afterReOptimize.isDefined) {
          val (newPhysicalPlan, newLogicalPlan) = afterReOptimize.get
          val origCost = costEvaluator.evaluateCost(currentPhysicalPlan)
          val newCost = costEvaluator.evaluateCost(newPhysicalPlan)
          if (newCost < origCost ||
            (newCost == origCost && currentPhysicalPlan != newPhysicalPlan)) {
            logOnLevel("Plan changed:\n" +
              sideBySide(currentPhysicalPlan.treeString, newPhysicalPlan.treeString).mkString("\n"))
            cleanUpTempTags(newPhysicalPlan)
            currentPhysicalPlan = newPhysicalPlan
            currentLogicalPlan = newLogicalPlan
            stagesToReplace = Seq.empty[QueryStageExec]
          }
        }
        // Now that some stages have finished, we can try creating new stages.
        result = createQueryStages(currentPhysicalPlan)
      }

      // Run the final plan when there's no more unfinished stages.
      currentPhysicalPlan = applyPhysicalRules(
        optimizeQueryStage(result.newPlan, isFinalStage = true),
        postStageCreationRules(supportsColumnar),
        Some((planChangeLogger, "AQE Post Stage Creation")))
      isFinalPlan = true
      executionId.foreach(onUpdatePlan(_, Seq(currentPhysicalPlan)))
      currentPhysicalPlan
    }
  }

  // Use a lazy val to avoid this being called more than once.
  @transient private lazy val finalPlanUpdate: Unit = {
    // Subqueries that don't belong to any query stage of the main query will execute after the
    // last UI update in `getFinalPhysicalPlan`, so we need to update UI here again to make sure
    // the newly generated nodes of those subqueries are updated.
    if (!isSubquery && currentPhysicalPlan.exists(_.subqueries.nonEmpty)) {
      getExecutionId.foreach(onUpdatePlan(_, Seq.empty))
    }
    logOnLevel(s"Final plan:\n$currentPhysicalPlan")
  }

  override def executeCollect(): Array[InternalRow] = {
    withFinalPlanUpdate(_.executeCollect())
  }

  override def executeTake(n: Int): Array[InternalRow] = {
    withFinalPlanUpdate(_.executeTake(n))
  }

  override def executeTail(n: Int): Array[InternalRow] = {
    withFinalPlanUpdate(_.executeTail(n))
  }

  override def doExecute(): RDD[InternalRow] = {
    withFinalPlanUpdate(_.execute())
  }

  override def doExecuteColumnar(): RDD[ColumnarBatch] = {
    withFinalPlanUpdate(_.executeColumnar())
  }

  override def doExecuteBroadcast[T](): broadcast.Broadcast[T] = {
    withFinalPlanUpdate { finalPlan =>
      assert(finalPlan.isInstanceOf[BroadcastQueryStageExec])
      finalPlan.doExecuteBroadcast()
    }
  }

  private def withFinalPlanUpdate[T](fun: SparkPlan => T): T = {
    val plan = getFinalPhysicalPlan()
    val result = fun(plan)
    finalPlanUpdate
    result
  }

  protected override def stringArgs: Iterator[Any] = Iterator(s"isFinalPlan=$isFinalPlan")

  override def generateTreeString(
      depth: Int,
      lastChildren: Seq[Boolean],
      append: String => Unit,
      verbose: Boolean,
      prefix: String = "",
      addSuffix: Boolean = false,
      maxFields: Int,
      printNodeId: Boolean,
      indent: Int = 0): Unit = {
    super.generateTreeString(
      depth,
      lastChildren,
      append,
      verbose,
      prefix,
      addSuffix,
      maxFields,
      printNodeId,
      indent)
    if (currentPhysicalPlan.fastEquals(initialPlan)) {
      currentPhysicalPlan.generateTreeString(
        depth + 1,
        lastChildren :+ true,
        append,
        verbose,
        prefix = "",
        addSuffix = false,
        maxFields,
        printNodeId,
        indent)
    } else {
      generateTreeStringWithHeader(
        if (isFinalPlan) "Final Plan" else "Current Plan",
        currentPhysicalPlan,
        depth,
        append,
        verbose,
        maxFields,
        printNodeId)
      generateTreeStringWithHeader(
        "Initial Plan",
        initialPlan,
        depth,
        append,
        verbose,
        maxFields,
        printNodeId)
    }
  }

  private def generateTreeStringWithHeader(
      header: String,
      plan: SparkPlan,
      depth: Int,
      append: String => Unit,
      verbose: Boolean,
      maxFields: Int,
      printNodeId: Boolean): Unit = {
    append("   " * depth)
    append(s"+- == $header ==\n")
    plan.generateTreeString(
      0,
      Nil,
      append,
      verbose,
      prefix = "",
      addSuffix = false,
      maxFields,
      printNodeId,
      indent = depth + 1)
  }

  override def hashCode(): Int = inputPlan.hashCode()

  override def equals(obj: Any): Boolean = {
    if (!obj.isInstanceOf[AdaptiveSparkPlanExec]) {
      return false
    }

    this.inputPlan == obj.asInstanceOf[AdaptiveSparkPlanExec].inputPlan
  }

  /**
   * This method is called recursively to traverse the plan tree bottom-up and create a new query
   * stage or try reusing an existing stage if the current node is an [[Exchange]] node and all of
   * its child stages have been materialized.
   *
   * With each call, it returns:
   * 1) The new plan replaced with [[QueryStageExec]] nodes where new stages are created.
   * 2) Whether the child query stages (if any) of the current node have all been materialized.
   * 3) A list of the new query stages that have been created.
   */
  private def createQueryStages(plan: SparkPlan): CreateStageResult = plan match {
    case e: Exchange =>
      // First have a quick check in the `stageCache` without having to traverse down the node.
      context.stageCache.get(e.canonicalized) match {
        case Some(existingStage) if conf.exchangeReuseEnabled =>
          val stage = reuseQueryStage(existingStage, e)
          val isMaterialized = stage.isMaterialized
          CreateStageResult(
            newPlan = stage,
            allChildStagesMaterialized = isMaterialized,
            newStages = if (isMaterialized) Seq.empty else Seq(stage))

        case _ =>
          val result = createQueryStages(e.child)
          val newPlan = e.withNewChildren(Seq(result.newPlan)).asInstanceOf[Exchange]
          // Create a query stage only when all the child query stages are ready.
          if (result.allChildStagesMaterialized) {
            var newStage = newQueryStage(newPlan)
            if (conf.exchangeReuseEnabled) {
              // Check the `stageCache` again for reuse. If a match is found, ditch the new stage
              // and reuse the existing stage found in the `stageCache`, otherwise update the
              // `stageCache` with the new stage.
              val queryStage = context.stageCache.getOrElseUpdate(
                newStage.plan.canonicalized, newStage)
              if (queryStage.ne(newStage)) {
                newStage = reuseQueryStage(queryStage, e)
              }
            }
            val isMaterialized = newStage.isMaterialized
            CreateStageResult(
              newPlan = newStage,
              allChildStagesMaterialized = isMaterialized,
              newStages = if (isMaterialized) Seq.empty else Seq(newStage))
          } else {
            CreateStageResult(newPlan = newPlan,
              allChildStagesMaterialized = false, newStages = result.newStages)
          }
      }

    case q: QueryStageExec =>
      CreateStageResult(newPlan = q,
        allChildStagesMaterialized = q.isMaterialized, newStages = Seq.empty)

    case _ =>
      if (plan.children.isEmpty) {
        CreateStageResult(newPlan = plan, allChildStagesMaterialized = true, newStages = Seq.empty)
      } else {
        val results = plan.children.map(createQueryStages)
        CreateStageResult(
          newPlan = plan.withNewChildren(results.map(_.newPlan)),
          allChildStagesMaterialized = results.forall(_.allChildStagesMaterialized),
          newStages = results.flatMap(_.newStages))
      }
  }

  private def newQueryStage(e: Exchange): QueryStageExec = {
    val optimizedPlan = optimizeQueryStage(e.child, isFinalStage = false)
    val queryStage = e match {
      case s: ShuffleExchangeLike =>
        val newShuffle = applyPhysicalRules(
          s.withNewChildren(Seq(optimizedPlan)),
          postStageCreationRules(outputsColumnar = s.supportsColumnar),
          Some((planChangeLogger, "AQE Post Stage Creation")))
        if (!newShuffle.isInstanceOf[ShuffleExchangeLike]) {
          throw new IllegalStateException(
            "Custom columnar rules cannot transform shuffle node to something else.")
        }
        ShuffleQueryStageExec(currentStageId, newShuffle, s.canonicalized)
      case b: BroadcastExchangeLike =>
        val newBroadcast = applyPhysicalRules(
          b.withNewChildren(Seq(optimizedPlan)),
          postStageCreationRules(outputsColumnar = b.supportsColumnar),
          Some((planChangeLogger, "AQE Post Stage Creation")))
        if (!newBroadcast.isInstanceOf[BroadcastExchangeLike]) {
          throw new IllegalStateException(
            "Custom columnar rules cannot transform broadcast node to something else.")
        }
        BroadcastQueryStageExec(currentStageId, newBroadcast, b.canonicalized)
    }
    currentStageId += 1
    setLogicalLinkForNewQueryStage(queryStage, e)
    queryStage
  }

  private def reuseQueryStage(existing: QueryStageExec, exchange: Exchange): QueryStageExec = {
    val queryStage = existing.newReuseInstance(currentStageId, exchange.output)
    currentStageId += 1
    setLogicalLinkForNewQueryStage(queryStage, exchange)
    queryStage
  }

  /**
   * Set the logical node link of the `stage` as the corresponding logical node of the `plan` it
   * encloses. If an `plan` has been transformed from a `Repartition`, it should have `logicalLink`
   * available by itself; otherwise traverse down to find the first node that is not generated by
   * `EnsureRequirements`.
   */
  private def setLogicalLinkForNewQueryStage(stage: QueryStageExec, plan: SparkPlan): Unit = {
    val link = plan.getTagValue(TEMP_LOGICAL_PLAN_TAG).orElse(
      plan.logicalLink.orElse(plan.collectFirst {
        case p if p.getTagValue(TEMP_LOGICAL_PLAN_TAG).isDefined =>
          p.getTagValue(TEMP_LOGICAL_PLAN_TAG).get
        case p if p.logicalLink.isDefined => p.logicalLink.get
      }))
    assert(link.isDefined)
    stage.setLogicalLink(link.get)
  }

  /**
   * For each query stage in `stagesToReplace`, find their corresponding logical nodes in the
   * `logicalPlan` and replace them with new [[LogicalQueryStage]] nodes.
   * 1. If the query stage can be mapped to an integral logical sub-tree, replace the corresponding
   *    logical sub-tree with a leaf node [[LogicalQueryStage]] referencing this query stage. For
   *    example:
   *        Join                   SMJ                      SMJ
   *      /     \                /    \                   /    \
   *    r1      r2    =>    Xchg1     Xchg2    =>    Stage1     Stage2
   *                          |        |
   *                          r1       r2
   *    The updated plan node will be:
   *                               Join
   *                             /     \
   *    LogicalQueryStage1(Stage1)     LogicalQueryStage2(Stage2)
   *
   * 2. Otherwise (which means the query stage can only be mapped to part of a logical sub-tree),
   *    replace the corresponding logical sub-tree with a leaf node [[LogicalQueryStage]]
   *    referencing to the top physical node into which this logical node is transformed during
   *    physical planning. For example:
   *     Agg           HashAgg          HashAgg
   *      |               |                |
   *    child    =>     Xchg      =>     Stage1
   *                      |
   *                   HashAgg
   *                      |
   *                    child
   *    The updated plan node will be:
   *    LogicalQueryStage(HashAgg - Stage1)
   */
  private def replaceWithQueryStagesInLogicalPlan(
      plan: LogicalPlan,
      stagesToReplace: Seq[QueryStageExec]): LogicalPlan = {
    var logicalPlan = plan
    stagesToReplace.foreach {
      case stage if currentPhysicalPlan.exists(_.eq(stage)) =>
        val logicalNodeOpt = stage.getTagValue(TEMP_LOGICAL_PLAN_TAG).orElse(stage.logicalLink)
        assert(logicalNodeOpt.isDefined)
        val logicalNode = logicalNodeOpt.get
        val physicalNode = currentPhysicalPlan.collectFirst {
          case p if p.eq(stage) ||
            p.getTagValue(TEMP_LOGICAL_PLAN_TAG).exists(logicalNode.eq) ||
            p.logicalLink.exists(logicalNode.eq) => p
        }
        assert(physicalNode.isDefined)
        // Set the temp link for those nodes that are wrapped inside a `LogicalQueryStage` node for
        // they will be shared and reused by different physical plans and their usual logical links
        // can be overwritten through re-planning processes.
        setTempTagRecursive(physicalNode.get, logicalNode)
        // Replace the corresponding logical node with LogicalQueryStage
        val newLogicalNode = LogicalQueryStage(logicalNode, physicalNode.get)
        val newLogicalPlan = logicalPlan.transformDown {
          case p if p.eq(logicalNode) => newLogicalNode
        }
        logicalPlan = newLogicalPlan

      case _ => // Ignore those earlier stages that have been wrapped in later stages.
    }
    logicalPlan
  }

  /**
   * Re-optimize and run physical planning on the current logical plan based on the latest stats.
   */
  private def reOptimize(logicalPlan: LogicalPlan): Option[(SparkPlan, LogicalPlan)] = {
    try {
      logicalPlan.invalidateStatsCache()
      val optimized = optimizer.execute(logicalPlan)
      val sparkPlan = context.session.sessionState.planner.plan(ReturnAnswer(optimized)).next()
      val newPlan = applyPhysicalRules(
        sparkPlan,
        preprocessingRules ++ queryStagePreparationRules,
        Some((planChangeLogger, "AQE Replanning")))

      // When both enabling AQE and DPP, `PlanAdaptiveDynamicPruningFilters` rule will
      // add the `BroadcastExchangeExec` node manually in the DPP subquery,
      // not through `EnsureRequirements` rule. Therefore, when the DPP subquery is complicated
      // and need to be re-optimized, AQE also need to manually insert the `BroadcastExchangeExec`
      // node to prevent the loss of the `BroadcastExchangeExec` node in DPP subquery.
      // Here, we also need to avoid to insert the `BroadcastExchangeExec` node when the newPlan is
      // already the `BroadcastExchangeExec` plan after apply the `LogicalQueryStageStrategy` rule.
      val finalPlan = inputPlan match {
        case b: BroadcastExchangeLike
          if (!newPlan.isInstanceOf[BroadcastExchangeLike]) => b.withNewChildren(Seq(newPlan))
        case _ => newPlan
      }

      Some((finalPlan, optimized))
    } catch {
      case e: InvalidAQEPlanException[_] =>
        logOnLevel(s"Re-optimize - ${e.getMessage()}:\n${e.plan}")
        None
    }
  }

  /**
   * Recursively set `TEMP_LOGICAL_PLAN_TAG` for the current `plan` node.
   */
  private def setTempTagRecursive(plan: SparkPlan, logicalPlan: LogicalPlan): Unit = {
    plan.setTagValue(TEMP_LOGICAL_PLAN_TAG, logicalPlan)
    plan.children.foreach(c => setTempTagRecursive(c, logicalPlan))
  }

  /**
   * Unset all `TEMP_LOGICAL_PLAN_TAG` tags.
   */
  private def cleanUpTempTags(plan: SparkPlan): Unit = {
    plan.foreach {
      case plan: SparkPlan if plan.getTagValue(TEMP_LOGICAL_PLAN_TAG).isDefined =>
        plan.unsetTagValue(TEMP_LOGICAL_PLAN_TAG)
      case _ =>
    }
  }

  /**
   * Notify the listeners of the physical plan change.
   */
  private def onUpdatePlan(executionId: Long, newSubPlans: Seq[SparkPlan]): Unit = {
    if (isSubquery) {
      // When executing subqueries, we can't update the query plan in the UI as the
      // UI doesn't support partial update yet. However, the subquery may have been
      // optimized into a different plan and we must let the UI know the SQL metrics
      // of the new plan nodes, so that it can track the valid accumulator updates later
      // and display SQL metrics correctly.
      val newMetrics = newSubPlans.flatMap { p =>
        p.flatMap(_.metrics.values.map(m => SQLPlanMetric(m.name.get, m.id, m.metricType)))
      }
      context.session.sparkContext.listenerBus.post(SparkListenerSQLAdaptiveSQLMetricUpdates(
        executionId, newMetrics))
    } else {
      val planDescriptionMode = ExplainMode.fromString(conf.uiExplainMode)
      context.session.sparkContext.listenerBus.post(SparkListenerSQLAdaptiveExecutionUpdate(
        executionId,
        context.qe.explainString(planDescriptionMode),
        SparkPlanInfo.fromSparkPlan(context.qe.executedPlan)))
    }
  }

  /**
   * Cancel all running stages with best effort and throw an Exception containing all stage
   * materialization errors and stage cancellation errors.
   */
  private def cleanUpAndThrowException(
       errors: Seq[Throwable],
       earlyFailedStage: Option[Int]): Unit = {
    currentPhysicalPlan.foreach {
      // earlyFailedStage is the stage which failed before calling doMaterialize,
      // so we should avoid calling cancel on it to re-trigger the failure again.
      case s: QueryStageExec if !earlyFailedStage.contains(s.id) =>
        try {
          s.cancel()
        } catch {
          case NonFatal(t) =>
            logError(s"Exception in cancelling query stage: ${s.treeString}", t)
        }
      case _ =>
    }
    // Respect SparkFatalException which can be thrown by BroadcastExchangeExec
    val originalErrors = errors.map {
      case fatal: SparkFatalException => fatal.throwable
      case other => other
    }
    val e = if (originalErrors.size == 1) {
      originalErrors.head
    } else {
      val se = QueryExecutionErrors.multiFailuresInStageMaterializationError(originalErrors.head)
      originalErrors.tail.foreach(se.addSuppressed)
      se
    }
    throw e
  }
}

object AdaptiveSparkPlanExec {
  private[adaptive] val executionContext = ExecutionContext.fromExecutorService(
    ThreadUtils.newDaemonCachedThreadPool("QueryStageCreator", 16))

  /**
   * The temporary [[LogicalPlan]] link for query stages.
   *
   * Physical nodes wrapped in a [[LogicalQueryStage]] can be shared among different physical plans
   * and thus their usual logical links can be overwritten during query planning, leading to
   * situations where those nodes point to a new logical plan and the rest point to the current
   * logical plan. In this case we use temp logical links to make sure we can always trace back to
   * the original logical links until a new physical plan is adopted, by which time we can clear up
   * the temp logical links.
   */
  val TEMP_LOGICAL_PLAN_TAG = TreeNodeTag[LogicalPlan]("temp_logical_plan")

  /**
   * Apply a list of physical operator rules on a [[SparkPlan]].
   */
  def applyPhysicalRules(
      plan: SparkPlan,
      rules: Seq[Rule[SparkPlan]],
      loggerAndBatchName: Option[(PlanChangeLogger[SparkPlan], String)] = None): SparkPlan = {
    if (loggerAndBatchName.isEmpty) {
      rules.foldLeft(plan) { case (sp, rule) => rule.apply(sp) }
    } else {
      val (logger, batchName) = loggerAndBatchName.get
      val newPlan = rules.foldLeft(plan) { case (sp, rule) =>
        val result = rule.apply(sp)
        logger.logRule(rule.ruleName, sp, result)
        result
      }
      logger.logBatch(batchName, plan, newPlan)
      newPlan
    }
  }
}

/**
 * The execution context shared between the main query and all sub-queries.
 */
case class AdaptiveExecutionContext(session: SparkSession, qe: QueryExecution) {

  /**
   * The subquery-reuse map shared across the entire query.
   */
  val subqueryCache: TrieMap[SparkPlan, BaseSubqueryExec] =
    new TrieMap[SparkPlan, BaseSubqueryExec]()

  /**
   * The exchange-reuse map shared across the entire query, including sub-queries.
   */
  val stageCache: TrieMap[SparkPlan, QueryStageExec] =
    new TrieMap[SparkPlan, QueryStageExec]()
}

/**
 * The event type for stage materialization.
 */
sealed trait StageMaterializationEvent

/**
 * The materialization of a query stage completed with success.
 */
case class StageSuccess(stage: QueryStageExec, result: Any) extends StageMaterializationEvent

/**
 * The materialization of a query stage hit an error and failed.
 */
case class StageFailure(stage: QueryStageExec, error: Throwable) extends StageMaterializationEvent

redpajama_set_name: RedPajamaGithub


text:
typedef void (^DownloadCompleteCallback)(NSNumber*, NSNumber*);
typedef void (^ErrorCallback)(NSError*);
typedef void (^BeginCallback)(NSNumber*, NSNumber*, NSDictionary*);
typedef void (^ProgressCallback)(NSNumber*, NSNumber*);

@interface DownloadParams : NSObject

@property (copy) NSString* fromUrl;
@property (copy) NSString* toFile;
@property (copy) NSDictionary* headers;
@property (copy) DownloadCompleteCallback completeCallback;   // Download has finished (data written)
@property (copy) ErrorCallback errorCallback;                 // Something went wrong
@property (copy) BeginCallback beginCallback;                 // Download has started (headers received)
@property (copy) ProgressCallback progressCallback;           // Download is progressing
@property        bool background;                             // Whether to continue download when app is in background
@property (copy) NSNumber* progressDivider;

@end

@interface Downloader : NSObject <NSURLSessionDelegate, NSURLSessionDownloadDelegate>

- (void)downloadFile:(DownloadParams*)params;
- (void)stopDownload;

@end


text:
package com.houston.titles.commons;

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

/**
 * Created by bcast_000 on 23/06/2015.
 */
public class Methods {

    private static String TAG = "Methods";

    private static Context context;

    public Methods(){
        super();
    }

    public static Methods init(Context context){
        Methods.context = context;
        return new Methods();
    }
    public static int toPixels(int dpi){
        float d = context.getResources().getDisplayMetrics().density;
        int margin = (int)(dpi * d); // margin in pixels

        return margin;
    }

    public static void showSoftKeyboard(View view) {
        if (view.requestFocus()) {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    public static void hideSoftKeyboard(View view) {
        view.clearFocus();
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static Drawable setTint(int mipmap, int color){

        Drawable drawable = context.getResources().getDrawable(mipmap);

        if(Build.VERSION.SDK_INT >= 21){
            drawable.setTint(context.getResources().getColor(color));
        }else{
            drawable.setColorFilter(context.getResources().getColor(color), PorterDuff.Mode.SRC_ATOP);
        }

        return drawable;
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.01.09 at 03:44:44 PM CET
//

package com.bitplan.mediawiki.japi.api;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="images">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="im" maxOccurs="unbounded">
 *                     <complexType>
 *                       <complexContent>
 *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                           <attribute name="ns" type="{http://www.w3.org/2001/XMLSchema}int" />
 *                           <attribute name="title" type="{http://www.w3.org/2001/XMLSchema}string" />
 *                         </restriction>
 *                       </complexContent>
 *                     </complexType>
 *                   </element>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *       <attribute name="pageid" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="ns" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="title" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "images"
})
public class Page {

    @XmlElement(required = true)
    protected Images images;
    @XmlAttribute(name = "pageid")
    protected Integer pageid;
    @XmlAttribute(name = "ns")
    protected Integer ns;
    @XmlAttribute(name = "title")
    protected String title;

    /**
     * Gets the value of the images property.
     *
     * @return
     *     possible object is
     *     {@link Images }
     *
     */
    public Images getImages() {
        return images;
    }

    /**
     * Sets the value of the images property.
     *
     * @param value
     *     allowed object is
     *     {@link Images }
     *
     */
    public void setImages(Images value) {
        this.images = value;
    }

    /**
     * Gets the value of the pageid property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getPageid() {
        return pageid;
    }

    /**
     * Sets the value of the pageid property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setPageid(Integer value) {
        this.pageid = value;
    }

    /**
     * Gets the value of the ns property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getNs() {
        return ns;
    }

    /**
     * Sets the value of the ns property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setNs(Integer value) {
        this.ns = value;
    }

    /**
     * Gets the value of the title property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTitle() {
        return title;
    }

    /**
     * Sets the value of the title property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTitle(String value) {
        this.title = value;
    }

}


text:
using namespace std;

#if !defined(MSGPACK_USE_CPP03)
#include <iterator>

// C++11

constexpr unsigned int VECTOR_SIZE = 100;
constexpr unsigned int MAP_SIZE    = 100;

TEST(iterator, vector)
{
    using vec_type = vector<unsigned int>;
    vec_type vec;
    vec.reserve(VECTOR_SIZE);
    for (unsigned int i = 0; i < VECTOR_SIZE; i++) {
        vec.push_back(rand());
    }
    msgpack::sbuffer sbuf;
    msgpack::pack(sbuf, vec);

    msgpack::unpacked ret;
    msgpack::unpack(ret, sbuf.data(), sbuf.size());

    auto const& msgarr = ret.get().via.array;
    auto dist = std::distance(begin(msgarr), end(msgarr));
    auto vecSize = vec.size();
    EXPECT_EQ(dist, vecSize);

    vec_type::const_iterator correct = std::begin(vec);
    for (auto const& obj : msgarr) {
        auto u64 = *correct;
        EXPECT_EQ(obj.as<unsigned int>(), u64);
        ++correct;
    }
}

TEST(iterator, map)
{
    using map_type = map<unsigned int, unsigned int>;
    map_type map;
    for (unsigned int i = 0; i < MAP_SIZE; i++) {
        map[rand()] = rand();
    }
    msgpack::sbuffer sbuf;
    msgpack::pack(sbuf, map);

    msgpack::unpacked ret;
    msgpack::unpack(ret, sbuf.data(), sbuf.size());

    auto const& msgmap = ret.get().via.map;
    auto dist = std::distance(begin(msgmap), end(msgmap));
    auto mapSize = map.size();
    EXPECT_EQ(dist, mapSize);

    for (auto const& kv : msgmap) {
        auto key = kv.key.as<unsigned int>();
        auto val = kv.val.as<unsigned int>();
        auto correct = map[key];
        EXPECT_EQ(val, correct);
    }
}

#endif // !defined(MSGPACK_USE_CPP03


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gablarski.Audio;
using NUnit.Framework;

namespace Gablarski.Tests
{
	[TestFixture]
	public class AudioFormatTests
	{
		[Test]
		public void Equals()
		{
			var one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000);
			var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000);

			Assert.IsTrue (one.Equals (two));
		}

		[Test]
		public void DoesNotEqual()
		{
			var one = new AudioFormat (WaveFormatEncoding.Unknown, 2, 16, 48000);
			var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000);
			Assert.IsFalse (one.Equals (two));

			one = new AudioFormat (WaveFormatEncoding.LPCM, 1, 16, 48000);
			Assert.IsFalse (one.Equals (two));

			one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 8, 48000);
			Assert.IsFalse (one.Equals (two));

			one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 44100);
			Assert.IsFalse (one.Equals (two));
		}

		[Test]
		public void GetHashCodeTest()
		{
			var one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000);
			var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000);

			Assert.AreEqual (one.GetHashCode(), two.GetHashCode());
		}

		[Test]
		public void GetHashCodeNotMatching()
		{
			var one = new AudioFormat (WaveFormatEncoding.Unknown, 2, 16, 48000);
			var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000);
			Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode());

			one = new AudioFormat (WaveFormatEncoding.LPCM, 1, 16, 48000);
			Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode());

			one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 8, 48000);
			Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode());

			one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 44100);
			Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode());
		}
	}
}


text:
package org.apache.hadoop.hdfs.server.namenode;

import io.hops.exception.LockUpgradeException;
import io.hops.transaction.lock.TransactionLockTypes;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.*;
import org.junit.Test;

import java.io.IOException;

import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY;
import static org.junit.Assert.fail;

public class TestLockUpgradeInFileRead {

  //
  // writes specified bytes to file.
  //
  public static void writeFile(FSDataOutputStream stm, int size)
          throws IOException {
    byte[] buffer = AppendTestUtil.randomBytes(0, size);
    stm.write(buffer, 0, size);
  }
  @Test
  public void TestFileReadLockUpgrade() throws IOException {
    MiniDFSCluster cluster = null;
    try {
      Configuration conf = new HdfsConfiguration();
      final int BLOCK_SIZE = 1024;
      conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE); // 4 byte
      //update the access time every time
      conf.setLong(DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, 10000); // update
      // the access time after every 5 sec
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
      cluster.waitActive();

      DistributedFileSystem dfs = cluster.getFileSystem();
      Path file = new Path("/file.txt");
      FSDataOutputStream out = dfs.create(file, (short)3);
      writeFile(out, 1024);
      out.close();

      FSNamesystem ns = cluster.getNamesystem();
      try{
        Thread.sleep(10000);       // 5 seconds has passed and the access time should be updated
                                  // Should get a LockUpgradeException while trying to update the timestamp
                                  // while holding the read lock
        ns.getBlockLocationsWithLock("client", file.toString(), 0, 1024, TransactionLockTypes.INodeLockType.READ);
        fail("The operation was expected to fail");
      }catch(LockUpgradeException | InterruptedException e){
      }

      try{
        // should succeed while holding the appropriate write lock
        ns.getBlockLocationsWithLock("client", file.toString(), 0, 1024, TransactionLockTypes.INodeLockType.WRITE);
      }catch(Exception e){
        fail("No exception was expected. Got "+e);
        e.printStackTrace();
      }

      try{
        // Now reading the file again with read lock should work
        ns.getBlockLocationsWithLock("client", file.toString(), 0, 1024, TransactionLockTypes.INodeLockType.READ);
      }catch(Exception e){
        fail("No exception was expected. Got "+e);
        e.printStackTrace();
      }

      try{
        Thread.sleep(10000);
        FSDataInputStream in = dfs.open(file);
        in.read();
        in.close();
      }catch(Exception e){
        fail("No exception was expected. Got "+e);
        e.printStackTrace();
      }
    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }
}


text:
<?php

namespace App\Controller;

use SkankyDev\Auth;
use SkankyDev\Utilities\Session;
use SkankyDev\MasterController;
use SkankyDev\MasterModel;

class JeTestController extends MasterController{

	//public $collection = 'Task';

	private function index(){

		$model = MasterModel::load('Task');
		$result= $model->find();

		if($this->request->isPost()){
			debug($this->request->data);
			$doc = $model->createDocument($this->request->data);
			if ($model->isValid($doc)) {
				$model->save($doc);
				$this->Flash->set('valide',['class' => 'success']);
			}else{
				$this->request->data = $doc;
				$this->Flash->set('pas valide',['class' => 'error']);
			}
		}
		$this->view->set(['result'=>$result]);
	}

}


text:
import unittest
import codec

import random as rnd

MAXITER = 200
REQUEST_KEYS = codec.REQUEST_KEYS + ['value']
REPLY_KEYS   = codec.REPLY_KEYS   + ['value']

class CodecTestCase(unittest.TestCase):

    def _gen_byte(self, min_i=0, max_i=256):
        return rnd.randint(min_i, max_i-1)

    def _gen_bytes(self, length=5):
        return [self._gen_byte() for _ in xrange(length)]

    def _gen_pos_bytes(self, length=5):
        return [self._gen_byte(max_i=128)] + self._gen_bytes(length-1)

    def _gen_neg_bytes(self, length=5):
        return [self._gen_byte(min_i=128)] + self._gen_bytes(length-1)

    def _gen_number(self, length=None):
        if length is None:
            length = rnd.randint(1, 9)
        value = [rnd.randint(0, 9) for _ in xrange(length)]
        value = (str(s) for s in value)
        value = "".join(value)
        return int(value)

    def _gen_cmd_string(self, length=8):
        values = [rnd.randint(0, 9) for _ in xrange(length)]
        chksum = sum(values)
        values.append(chksum)
        string = "".join(chr(v) for v in values)
        return string

    def test_byte(self):
        for i in xrange(MAXITER):
            self.assertIn(codec.byte(i), range(256))

    def test_checksum(self):
        for i in xrange(MAXITER):
            self.assertEqual(codec.checksum(i*[i]), codec.byte(i*i))

    def test_encodeBytes(self):
        value = 123456789

        bytes = codec.encodeBytes(value)
        self.assertEqual([7, 91, 205, 21], bytes)

        new_value = codec.decodeBytes(bytes)
        self.assertEqual(value, new_value)

    def test_decodeBytes(self):
        bytes = [1, 2, 3, 4]

        value = codec.decodeBytes(bytes)
        self.assertEqual(16909060, value)

        new_bytes = codec.encodeBytes(value)
        self.assertEqual(bytes, new_bytes)

    def test_encdecBytes(self):
        for _ in xrange(MAXITER):
            value = self._gen_number()
            bytes = codec.encodeBytes(value)
            new_value = codec.decodeBytes(bytes)

            self.assertEqual(value, new_value)

    def test_decencBytes(self):
        for _ in xrange(MAXITER):
            bytes = self._gen_bytes(length=4)
            value = codec.decodeBytes(bytes)
            new_bytes = codec.encodeBytes(value)

            self.assertEqual(bytes, new_bytes)

    def test_decencNegBytes(self):
        for _ in xrange(MAXITER):
            bytes = self._gen_neg_bytes(length=4)
            value = codec.decodeBytes(bytes)
            new_bytes = codec.encodeBytes(value)

            self.assertEqual(bytes, new_bytes)

    def test_decencPosBytes(self):
        for _ in xrange(MAXITER):
            bytes = self._gen_pos_bytes(length=4)
            value = codec.decodeBytes(bytes)
            new_bytes = codec.encodeBytes(value)

            self.assertEqual(bytes, new_bytes)

    def _help_test_encodeReAllCommand(self, encoder, decoder, keys):
        string = "ABCD\x00\x00\x00EO"
        values = [ord(s) for s in string]

        result = encoder(values[0], values[1], values[2], values[3], sum(values[4:8]))
        self.assertEqual(string, result)

    def _help_test_decodeReAllCommand(self, encoder, decoder, keys):
        string = "ABCD\x00\x00\x00EO"
        result = decoder(string)

        for i, k in enumerate(keys[:4]):
            self.assertEqual(ord(string[i]), result[k])

        values = sum(ord(s) for s in string[4:8])
        self.assertEqual(values, result['value'])

        self.assertEqual(ord(string[7]), result['value'])
        self.assertEqual(ord(string[8]), result['checksum'])

    def test_encodeRequestCommand(self):
        self._help_test_encodeReAllCommand(codec.encodeRequestCommand, codec.decodeRequestCommand, REQUEST_KEYS)

    def test_decodeRequestCommand(self):
        self._help_test_decodeReAllCommand(codec.encodeRequestCommand, codec.decodeRequestCommand, REQUEST_KEYS)

    def test_encodeReplyCommand(self):
        self._help_test_encodeReAllCommand(codec.encodeReplyCommand, codec.decodeReplyCommand, REPLY_KEYS)

    def test_decodeReplyCommand(self):
        self._help_test_decodeReAllCommand(codec.encodeReplyCommand, codec.decodeReplyCommand, REPLY_KEYS)

    def _help_test_encdecReAllCommand(self, encoder, decoder, keys):
        for _ in xrange(MAXITER):
            values = self._gen_bytes(length=len(keys))
            string = encoder(*values)
            result = decoder(string)

            for i, k in enumerate(keys):
                self.assertEqual(values[i], result[k])

            self.assertEqual(sum(values) % 256, result['checksum'])

    def _help_test_decencReALLCommand(self, encoder, decoder, keys):
        for _ in xrange(MAXITER):
            string = self._gen_cmd_string()
            values = decoder(string)

            unpacked = (values[k] for k in keys)
            new_string = encoder(*unpacked)

            self.assertEqual(string, new_string)

    def test_encdecRequestCommand(self):
        self._help_test_encdecReAllCommand(codec.encodeRequestCommand, codec.decodeRequestCommand, REQUEST_KEYS)

    def test_decencRequestCommand(self):
        self._help_test_decencReALLCommand(codec.encodeRequestCommand, codec.decodeRequestCommand, REQUEST_KEYS)

    def test_encdecReplyCommand(self):
        self._help_test_encdecReAllCommand(codec.encodeReplyCommand, codec.decodeReplyCommand, REPLY_KEYS)

    def test_decencReplyCommand(self):
        self._help_test_decencReALLCommand(codec.encodeReplyCommand, codec.decodeReplyCommand, REPLY_KEYS)

    def test_encodeCommand(self):
        string = "ABCD\x00\x00\x00EO"
        params = [ord(s) for s in string[:4]]
        values = ord(string[7])
#        values = sum(ord(s) for s in string[4:8])

        new_string = codec.encodeCommand(params, values)
        self.assertEqual(string, new_string)

    def test_decodeCommand(self):
        keys = range(4)
        string = "ABCD\x00\x00\x00EO"

        result = codec.decodeCommand(string, keys)

        for i, k in enumerate(keys):
            self.assertEqual(ord(string[i]), result[k])

        values = sum(ord(s) for s in string[4:8])
        self.assertEqual(values, result['value'])

        self.assertEqual(ord(string[7]), result['value'])
        self.assertEqual(ord(string[8]), result['checksum'])

    def test_encdecCommand(self):
        keys = range(4)
        for _ in xrange(MAXITER):
            params = self._gen_bytes(length=4)
            values = self._gen_byte()
            chksum = sum(params, values) % 256

            string = codec.encodeCommand(params, values)
            result = codec.decodeCommand(string, keys)

            for i, k in enumerate(keys):
                self.assertEqual(params[i], result[k])

            self.assertEqual(values, result['value'])
            self.assertEqual(chksum, result['checksum'])

    def test_decencCommand(self):
        keys = range(4)
        for _ in xrange(MAXITER):
            string = self._gen_cmd_string()

            decoded = codec.decodeCommand(string, keys)
            params = [decoded[k] for k in keys]
            values = decoded['value']
            new_string = codec.encodeCommand(params, values)

            self.assertEqual(string[:4],  new_string[:4])  # parameter part
            self.assertEqual(string[4:8], new_string[4:8]) # value part
            self.assertEqual(string[8],   new_string[8])   # checksum part
            self.assertEqual(string,      new_string)

if __name__ == '__main__':
    unittest.main()


text:
Misc.
=====

.. currentmodule:: aioconsul.typing

Typing
------

Most of call are polymorphic and most of the types in documentation are just hints.
Here is the full list of types:

.. class:: aioconsul.typing.ObjectIndex

    Used by polymorphic functions that accept any ``str`` or ``dict`` that
    have an **Index** key.

    For example these two objects are equivalent::

        a = { "Index": "1234-43-6789" }
        b = "1234-43-6789"

.. class:: aioconsul.typing.ObjectID

    Used by polymorphic functions that accept any ``str`` or ``dict`` that
    have an **ID** key.

    These two objects are equivalent::

        a = { "ID": "1234-43-6789" }
        b = "1234-43-6789"

.. class:: aioconsul.typing.Object

    Represents a ``dict`` where keys are ``str`` and values can be any type.

    For example::

        {
          "ID": "1234-43-6789",
          "Name": "foo",
          "Value": "bar"
        }

    Depending of the endpoint, **ID** may be required or not.

.. class:: aioconsul.typing.Collection

    Represents a ``list`` where values are :class:`Object`.

    For example::

        [{"ID": "1234"}, {"ID": "5678"}]

.. class:: aioconsul.typing.Mapping

    Represents a ``dict`` where keys are ``id`` and values are :class:`Object`.

    For example::

        {"service1": {"ID": "service1"}}

.. class:: aioconsul.typing.Meta

    Represents a ``dict`` that is associated to Response.
    These keys should be presents:

    * **Index** — a unique identifier representing the current state
      of the requested resource
    * **KnownLeader** — indicates if there is a known leader
    * **LastContact** — Contains the time in milliseconds that a server was
      last contacted by the leader node

    Meta can be used for blocking / watch mode.

.. class:: aioconsul.typing.CollectionMeta

    A tuple where first value is a :class:`Collection` and
    second value is :class:`Meta`.

.. class:: aioconsul.typing.ObjectMeta

    A tuple where first value is an :class:`Object` and
    second value is :class:`Meta`.

.. class:: aioconsul.typing.Filter

    Regular expression to filter by.

    It accepts a ``re.Pattern`` or a ``str``.
    These two objects are equivalent::

        a = re.compile("node-\d+")
        b = "node-\d+"

.. class:: aioconsul.typing.Consistency

    Most of the read query endpoints support multiple levels of consistency.
    Since no policy will suit all clients' needs, these consistency modes
    allow the user to have the ultimate say in how to balance the trade-offs
    inherent in a distributed system. The three read modes are:

    **default** — If not specified, the default is strongly consistent in
    almost all cases. However, there is a small window in which a new leader
    may be elected during which the old leader may service stale values. The
    trade-off is fast reads but potentially stale values. The condition
    resulting in stale reads is hard to trigger, and most clients should not
    need to worry about this case. Also, note that this race condition only
    applies to reads, not writes.

    **consistent** — This mode is strongly consistent without caveats.
    It requires that a leader verify with a quorum of peers that it is still
    leader. This introduces an additional round-trip to all server nodes.
    The trade-off is increased latency due to an extra round trip. Most
    clients should not use this unless they cannot tolerate a stale read.

    **stale** — This mode allows any server to service the read regardless
    of whether it is the leader. This means reads can be arbitrarily stale;
    however, results are generally consistent to within 50 milliseconds of
    the leader. The trade-off is very fast and scalable reads with a higher
    likelihood of stale values. Since this mode allows reads without a
    leader, a cluster that is unavailable will still be able to respond to
    queries.

.. class:: aioconsul.typing.Duration

    Defines a duration. Can be specified in the form of "10s" or "5m" or
    a ``datetime.timedelta``.

    For example, these objects are equivalent::

        timedelta(seconds=150)
        "2m30s"

.. class:: aioconsul.typing.Blocking

    Defines a blocking query.

    It must be a :class:`~aioconsul.typing.ObjectIndex` or better a tuple where
    second value is a :class:`~aioconsul.typing.Duration`.

    For example these values are equivalent::

        a = {"Index": 1}
        b = 1
        c = ({"Index": 1}, None)

    For adding a wait, just set the second value of tuple.

.. class:: aioconsul.typing.Payload

    Currently only ``bytes`` and ``bytearray`` are allowed.
    It may vary on **Flags** value in the futur.

    Internally, Payload will be base64 encoded/decoded when the
    endpoint requires it. End user does not have to do it.

    The :class:`~aioconsul.client.KVEndpoint` is build on top of:

    * ``PUT /v1/kv/(key)`` - **Body** will be encoded
    * ``GET /v1/kv/(key)`` - **Value** will be decoded

    For example::

        PAYLOAD = b"bar"
        await client.kv.set("foo", PAYLOAD)
        response, _ = await client.kv.get("foo")
        assert response["Value"] == PAYLOAD

    The :class:`~aioconsul.client.EventEndpoint` is build on top of:

    * ``PUT /v1/event/fire/(name)`` - **Payload** will be kept as is
    * ``GET /v1/event/list`` - **Payload** will be base64 encoded

    For example::

        PAYLOAD = b"qux"
        response = await client.event.fire("baz", PAYLOAD)
        assert response["Payload"] == PAYLOAD
        responses, _ = await client.kv.items("baz")
        assert responses[0]["Payload"] == PAYLOAD


text:
/* MagicMirror² Test config sample ipWhitelist
 *
 * By Rodrigo Ramírez Norambuena https://rodrigoramirez.com
 * MIT Licensed.
 */
let config = require(process.cwd() + "/tests/configs/default.js").configFactory({
	ipWhitelist: []
});

/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
	module.exports = config;
}


text:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");

var t = async_test("setTransform() with Infinity/NaN is ignored");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
    throw reason;
});
t.step(function() {

var canvas = new OffscreenCanvas(100, 50);
var ctx = canvas.getContext('2d');

ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
ctx.translate(100, 10);
ctx.setTransform(Infinity, 0, 0, 0, 0, 0);
ctx.setTransform(-Infinity, 0, 0, 0, 0, 0);
ctx.setTransform(NaN, 0, 0, 0, 0, 0);
ctx.setTransform(0, Infinity, 0, 0, 0, 0);
ctx.setTransform(0, -Infinity, 0, 0, 0, 0);
ctx.setTransform(0, NaN, 0, 0, 0, 0);
ctx.setTransform(0, 0, Infinity, 0, 0, 0);
ctx.setTransform(0, 0, -Infinity, 0, 0, 0);
ctx.setTransform(0, 0, NaN, 0, 0, 0);
ctx.setTransform(0, 0, 0, Infinity, 0, 0);
ctx.setTransform(0, 0, 0, -Infinity, 0, 0);
ctx.setTransform(0, 0, 0, NaN, 0, 0);
ctx.setTransform(0, 0, 0, 0, Infinity, 0);
ctx.setTransform(0, 0, 0, 0, -Infinity, 0);
ctx.setTransform(0, 0, 0, 0, NaN, 0);
ctx.setTransform(0, 0, 0, 0, 0, Infinity);
ctx.setTransform(0, 0, 0, 0, 0, -Infinity);
ctx.setTransform(0, 0, 0, 0, 0, NaN);
ctx.setTransform(Infinity, Infinity, 0, 0, 0, 0);
ctx.setTransform(Infinity, Infinity, Infinity, 0, 0, 0);
ctx.setTransform(Infinity, Infinity, Infinity, Infinity, 0, 0);
ctx.setTransform(Infinity, Infinity, Infinity, Infinity, Infinity, 0);
ctx.setTransform(Infinity, Infinity, Infinity, Infinity, Infinity, Infinity);
ctx.setTransform(Infinity, Infinity, Infinity, Infinity, 0, Infinity);
ctx.setTransform(Infinity, Infinity, Infinity, 0, Infinity, 0);
ctx.setTransform(Infinity, Infinity, Infinity, 0, Infinity, Infinity);
ctx.setTransform(Infinity, Infinity, Infinity, 0, 0, Infinity);
ctx.setTransform(Infinity, Infinity, 0, Infinity, 0, 0);
ctx.setTransform(Infinity, Infinity, 0, Infinity, Infinity, 0);
ctx.setTransform(Infinity, Infinity, 0, Infinity, Infinity, Infinity);
ctx.setTransform(Infinity, Infinity, 0, Infinity, 0, Infinity);
ctx.setTransform(Infinity, Infinity, 0, 0, Infinity, 0);
ctx.setTransform(Infinity, Infinity, 0, 0, Infinity, Infinity);
ctx.setTransform(Infinity, Infinity, 0, 0, 0, Infinity);
ctx.setTransform(Infinity, 0, Infinity, 0, 0, 0);
ctx.setTransform(Infinity, 0, Infinity, Infinity, 0, 0);
ctx.setTransform(Infinity, 0, Infinity, Infinity, Infinity, 0);
ctx.setTransform(Infinity, 0, Infinity, Infinity, Infinity, Infinity);
ctx.setTransform(Infinity, 0, Infinity, Infinity, 0, Infinity);
ctx.setTransform(Infinity, 0, Infinity, 0, Infinity, 0);
ctx.setTransform(Infinity, 0, Infinity, 0, Infinity, Infinity);
ctx.setTransform(Infinity, 0, Infinity, 0, 0, Infinity);
ctx.setTransform(Infinity, 0, 0, Infinity, 0, 0);
ctx.setTransform(Infinity, 0, 0, Infinity, Infinity, 0);
ctx.setTransform(Infinity, 0, 0, Infinity, Infinity, Infinity);
ctx.setTransform(Infinity, 0, 0, Infinity, 0, Infinity);
ctx.setTransform(Infinity, 0, 0, 0, Infinity, 0);
ctx.setTransform(Infinity, 0, 0, 0, Infinity, Infinity);
ctx.setTransform(Infinity, 0, 0, 0, 0, Infinity);
ctx.setTransform(0, Infinity, Infinity, 0, 0, 0);
ctx.setTransform(0, Infinity, Infinity, Infinity, 0, 0);
ctx.setTransform(0, Infinity, Infinity, Infinity, Infinity, 0);
ctx.setTransform(0, Infinity, Infinity, Infinity, Infinity, Infinity);
ctx.setTransform(0, Infinity, Infinity, Infinity, 0, Infinity);
ctx.setTransform(0, Infinity, Infinity, 0, Infinity, 0);
ctx.setTransform(0, Infinity, Infinity, 0, Infinity, Infinity);
ctx.setTransform(0, Infinity, Infinity, 0, 0, Infinity);
ctx.setTransform(0, Infinity, 0, Infinity, 0, 0);
ctx.setTransform(0, Infinity, 0, Infinity, Infinity, 0);
ctx.setTransform(0, Infinity, 0, Infinity, Infinity, Infinity);
ctx.setTransform(0, Infinity, 0, Infinity, 0, Infinity);
ctx.setTransform(0, Infinity, 0, 0, Infinity, 0);
ctx.setTransform(0, Infinity, 0, 0, Infinity, Infinity);
ctx.setTransform(0, Infinity, 0, 0, 0, Infinity);
ctx.setTransform(0, 0, Infinity, Infinity, 0, 0);
ctx.setTransform(0, 0, Infinity, Infinity, Infinity, 0);
ctx.setTransform(0, 0, Infinity, Infinity, Infinity, Infinity);
ctx.setTransform(0, 0, Infinity, Infinity, 0, Infinity);
ctx.setTransform(0, 0, Infinity, 0, Infinity, 0);
ctx.setTransform(0, 0, Infinity, 0, Infinity, Infinity);
ctx.setTransform(0, 0, Infinity, 0, 0, Infinity);
ctx.setTransform(0, 0, 0, Infinity, Infinity, 0);
ctx.setTransform(0, 0, 0, Infinity, Infinity, Infinity);
ctx.setTransform(0, 0, 0, Infinity, 0, Infinity);
ctx.setTransform(0, 0, 0, 0, Infinity, Infinity);
ctx.fillStyle = '#0f0';
ctx.fillRect(-100, -10, 100, 50);
_assertPixel(canvas, 50,25, 0,255,0,255);
t.done();

});
done();


text:
//-----------------------------------------------------------------------
// <copyright file="HoconConfigurationElement.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
#if CONFIGURATION
using System.Configuration;

namespace Akka.Configuration.Hocon
{
    ///
    /// This class represents a custom HOCON (Human-Optimized Config Object Notation)
    /// node within a configuration file.
    ///
    /// <![CDATA[
    /// <?xml version="1.0" encoding="utf-8" ?>
    /// <configuration>
    ///   <configSections>
    ///

    ///   </configSections>
    ///   <akka>
    ///     <hocon>
    ///     ...
    ///     </hocon>
    ///   </akka>
    /// </configuration>
    /// ]]>
    ///
    ///
    public class HoconConfigurationElement : CDataConfigurationElement
    {
        ///
        /// Gets or sets the HOCON configuration string contained in the hocon node.
        ///
        [ConfigurationProperty(ContentPropertyName, IsRequired = true, IsKey = true)]
        public string Content
        {
            get { return (string) base[ContentPropertyName]; }
            set { base[ContentPropertyName] = value; }
        }
    }
}
#endif


text:
import {getUid} from '../../../../../src/ol/util.js';
import Feature from '../../../../../src/ol/Feature.js';
import Map from '../../../../../src/ol/Map.js';
import View from '../../../../../src/ol/View.js';
import Point from '../../../../../src/ol/geom/Point.js';
import TileLayer from '../../../../../src/ol/layer/Tile.js';
import VectorLayer from '../../../../../src/ol/layer/Vector.js';
import CanvasLayerRenderer from '../../../../../src/ol/renderer/canvas/Layer.js';
import CanvasMapRenderer from '../../../../../src/ol/renderer/canvas/Map.js';
import VectorSource from '../../../../../src/ol/source/Vector.js';
import Icon from '../../../../../src/ol/style/Icon.js';
import Style from '../../../../../src/ol/style/Style.js';

describe('ol.renderer.canvas.Map', function() {

  describe('constructor', function() {

    it('creates a new instance', function() {
      const map = new Map({
        target: document.createElement('div')
      });
      const renderer = new CanvasMapRenderer(map);
      expect(renderer).to.be.a(CanvasMapRenderer);
    });

  });

  describe('#forEachFeatureAtCoordinate', function() {

    let layer, map, target;

    beforeEach(function(done) {
      target = document.createElement('div');
      target.style.width = '100px';
      target.style.height = '100px';
      document.body.appendChild(target);
      map = new Map({
        pixelRatio: 1,
        target: target,
        view: new View({
          center: [0, 0],
          zoom: 0
        })
      });

      // 1 x 1 pixel black icon
      const img = document.createElement('img');
      img.onload = function() {
        done();
      };
      img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==';

      layer = new VectorLayer({
        source: new VectorSource({
          features: [
            new Feature({
              geometry: new Point([0, 0])
            })
          ]
        }),
        style: new Style({
          image: new Icon({
            img: img,
            imgSize: [1, 1]
          })
        })
      });
    });

    afterEach(function() {
      map.setTarget(null);
      document.body.removeChild(target);
    });

    it('calls callback with layer for managed layers', function() {
      map.addLayer(layer);
      map.renderSync();
      const cb = sinon.spy();
      map.forEachFeatureAtPixel(map.getPixelFromCoordinate([0, 0]), cb);
      expect(cb).to.be.called();
      expect(cb.firstCall.args[1]).to.be(layer);
    });

    it('calls callback with null for unmanaged layers', function() {
      layer.setMap(map);
      map.renderSync();
      const cb = sinon.spy();
      map.forEachFeatureAtPixel(map.getPixelFromCoordinate([0, 0]), cb);
      expect(cb).to.be.called();
      expect(cb.firstCall.args[1]).to.be(null);
    });

    it('calls callback with main layer when skipped feature on unmanaged layer', function() {
      const feature = layer.getSource().getFeatures()[0];
      const managedLayer = new VectorLayer({
        source: new VectorSource({
          features: [feature]
        })
      });
      map.addLayer(managedLayer);
      map.skipFeature(feature);
      layer.setMap(map);
      map.renderSync();
      const cb = sinon.spy();
      map.forEachFeatureAtPixel(map.getPixelFromCoordinate([0, 0]), cb);
      expect(cb.callCount).to.be(1);
      expect(cb.firstCall.args[1]).to.be(managedLayer);
    });

    it('filters managed layers', function() {
      map.addLayer(layer);
      map.renderSync();
      const cb = sinon.spy();
      map.forEachFeatureAtPixel(map.getPixelFromCoordinate([0, 0]), cb, {
        layerFilter: function() {
          return false;
        }
      });
      expect(cb).to.not.be.called();
    });

    it('doesn\'t fail with layer with no source', function() {
      map.addLayer(new TileLayer());
      map.renderSync();
      expect(function() {
        map.forEachFeatureAtPixel(map.getPixelFromCoordinate([0, 0]),
          function() {});
      }).to.not.throwException();
    });

    it('calls callback for clicks inside of the hitTolerance', function() {
      map.addLayer(layer);
      map.renderSync();
      const cb1 = sinon.spy();
      const cb2 = sinon.spy();

      const pixel = map.getPixelFromCoordinate([0, 0]);

      const pixelsInside = [
        [pixel[0] + 9, pixel[1]],
        [pixel[0] - 9, pixel[1]],
        [pixel[0], pixel[1] + 9],
        [pixel[0], pixel[1] - 9]
      ];

      const pixelsOutside = [
        [pixel[0] + 9, pixel[1] + 9],
        [pixel[0] - 9, pixel[1] + 9],
        [pixel[0] + 9, pixel[1] - 9],
        [pixel[0] - 9, pixel[1] - 9]
      ];

      for (let i = 0; i < 4; i++) {
        map.forEachFeatureAtPixel(pixelsInside[i], cb1, {hitTolerance: 10});
      }
      expect(cb1.callCount).to.be(4);
      expect(cb1.firstCall.args[1]).to.be(layer);

      for (let j = 0; j < 4; j++) {
        map.forEachFeatureAtPixel(pixelsOutside[j], cb2, {hitTolerance: 10});
      }
      expect(cb2).not.to.be.called();
    });
  });

  describe('#forEachLayerAtCoordinate', function() {

    let layer, map, target;

    beforeEach(function(done) {
      target = document.createElement('div');
      target.style.width = '100px';
      target.style.height = '100px';
      document.body.appendChild(target);
      map = new Map({
        pixelRatio: 1,
        target: target,
        view: new View({
          center: [0, 0],
          zoom: 0
        })
      });

      // 1 x 1 pixel black icon
      const img = document.createElement('img');
      img.onload = function() {
        done();
      };
      img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==';

      layer = new VectorLayer({
        source: new VectorSource({
          features: [
            new Feature({
              geometry: new Point([0, 0])
            })
          ]
        }),
        style: new Style({
          image: new Icon({
            img: img,
            imgSize: [1, 1]
          })
        })
      });
    });

    afterEach(function() {
      map.setTarget(null);
      document.body.removeChild(target);
    });

    it('calls callback for clicks inside of the hitTolerance', function() {
      map.addLayer(layer);
      map.renderSync();
      const cb1 = sinon.spy();
      const cb2 = sinon.spy();

      const pixel = map.getPixelFromCoordinate([0, 0]);

      const pixelsInside = [
        [pixel[0] + 9, pixel[1]],
        [pixel[0] - 9, pixel[1]],
        [pixel[0], pixel[1] + 9],
        [pixel[0], pixel[1] - 9]
      ];

      const pixelsOutside = [
        [pixel[0] + 9, pixel[1] + 9],
        [pixel[0] - 9, pixel[1] + 9],
        [pixel[0] + 9, pixel[1] - 9],
        [pixel[0] - 9, pixel[1] - 9]
      ];

      for (let i = 0; i < 4; i++) {
        map.forEachLayerAtPixel(pixelsInside[i], cb1, {hitTolerance: 10});
      }
      expect(cb1.callCount).to.be(4);
      expect(cb1.firstCall.args[0]).to.be(layer);

      for (let j = 0; j < 4; j++) {
        map.forEachLayerAtPixel(pixelsOutside[j], cb2, {hitTolerance: 10});
      }
      expect(cb2).not.to.be.called();
    });
  });

  describe('#renderFrame()', function() {
    let layer, map, renderer;

    beforeEach(function() {
      map = new Map({});
      map.on('postcompose', function() {});
      layer = new VectorLayer({
        source: new VectorSource({wrapX: true})
      });
      renderer = map.getRenderer();
      renderer.layerRenderers_ = {};
      const layerRenderer = new CanvasLayerRenderer(layer);
      layerRenderer.prepareFrame = function() {
        return true;
      };
      layerRenderer.getImage = function() {
        return null;
      };
      renderer.layerRenderers_[getUid(layer)] = layerRenderer;
    });

  });

});


text:
$(document).ready(function() {
    $('#form_FacturaManual').bootstrapValidator({
        feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
        },
        excluded: ':disabled',
        fields: {
            newNumFac: {
                validators: {
                    notEmpty: {
                        message: 'Establesca número de Factura'
                    },
                    numeric: {
                        message: 'Debe ser de tipo Numérico'
                    }
                }
            },
            newFechaFac: {
                validators: {
                    notEmpty: {
                        message: 'Establesca fecha de Factura'
                    },
                    date: {
                        format: 'YYYY-MM-DD',
                        message: 'La fecha no es valida Ej: 2019-01-31 (año-mes-dia)'
                    }
                }
            },
        }
        }).on('success.form.bv', function(e) {
            e.preventDefault();
            let formData = new FormData($('#form_FacturaManual')[0]);
        $.ajax({
                url: base_url("index.php/Facturas/updateFacturaManual"),
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (returndata) {
                    console.log(formData);
                    if (returndata == 'true') {
                        limpiarModal()
                        resetForm('#form_FacturaManual')
                        swal({
                            title: 'Se corrigió la factura exitosamente',
                            type: 'success',
                            showCancelButton: false,
                            allowOutsideClick: false,
                        })
                        $('#modalFacturaManual').modal('hide')
                        limpiarModal()
                        retFacturasManuales()
                    } else {
                        swal(
                            'Error',
                            returndata,
                            'error'
                        )
                    }
                },
                error : function (returndata) {
                    swal(
                        'Error',
                        'El numero de Factura ya existe o no se tiene tipo de cambio para la fecha, corrobore los datos',
                        'error'
                    )
                    //limpiarModal()
                    //console.log(returndata);
                },
            });
        });
});
$(document).on("click", "#refresh", function () {
    retFacturasManuales();
})
function retFacturasManuales()
{
    agregarcargando();
    alm=$("#almacen_filtro").val()
    lote=$("#lote_filtro").val()
    $.ajax({
        type:"POST",
        url: base_url('index.php/Facturas/showFactuasManuales'),
        dataType: "json",
        data: {alm:alm,lote:lote},
    }).done(function(res){
         quitarcargando();
        //datosselect= restornardatosSelect(res)

        $("#facturasManuales").bootstrapTable('destroy');
        $('#facturasManuales').bootstrapTable({

            data:res,
            striped:true,
            //pagination:false,
            pageSize:"100",
            search:true,
            stickyHeader: true,
            stickyHeaderOffsetY: '50px',
            filter:true,
            showColumns:true,
            strictSearch: true,
            showToggle:true,
            columns: [
            {
                field: 'idFactura',
                title: 'ID',
                visible:false,
                searchable: false,
            },
            {
                field: 'lote',
                title: 'Lote',
                visible:false,
                searchable: false,
            },
            {
                field:'nFactura',
                title:"N° Fac",
                sortable:true,
                align: 'center',
            },
            {
                field:'fechaFac',
                title:"Fecha",
                align:'center',
                sortable:true,
                formatter: formato_fecha_corta,
                searchable: false,
            },
            {
                field:'ClienteNit',
                title:"N° Cliente",
                sortable:true,
                visible:false,
                searchable: false,
            },
            {
                field:'ClienteFactura',
                title:"Cliente",
                sortable:true,
                /*filter: {
                    type: "select",
                    data: datosselect[0]
                }*/
            },
            {
                field:'moneda',
                title:'Moneda',
                visible:false,
                /*filter: {
                            type: 'select',
                            data: datosselect[3]
                        }*/
            },
            {
                field:'total',
                title:"Total",
                sortable:true,
                align: 'right',
                searchable: false,
                width:'100px',
                formatter:operateFormatter3,
            },
            {
                field:'autor',
                title:"Emitido por:",
                align: 'center',
                visible:false,
            },
            {
                field:'fecha',
                title:"Fecha",
                align:'center',
                sortable:true,
                visible:false,
                searchable: false,
            },
            {
                title: 'Modificar',
                align: 'center',
                width: '10%',
                width:'150px',
                searchable: false,
                events: eventosBotones,
                formatter: formatoBotones
            }]

        });
    }).fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Request Failed: " + err );
    });
}
function operateFormatter3(value, row, index)
    {
        num=Math.round(value * 100) / 100
        num=num.toFixed(2);
        return (formatNumber.new(num));
}
function formatoBotones(value, row, index)
{
        return [
        '<button type="button" class="btn btn-default update"  aria-label="Right Align" data-toggle="tooltip" title="Modificar">',
        '</button>',
        ].join('');
}
window.eventosBotones = {
    'click .update': function (e, value, row, index) {
        showModal(row)
    },
};
function showModal(row)
{
    nFacAnt = row.nFactura
    fechaFacAnt = formato_fecha_corta(row.fechaFac)
    nomCliente = row.ClienteFactura
    $("#id").val(row.idFactura)
    $("#alm").val(row.almacen)
    $("#fechaLimite").val(row.fechaLimite)
    $("#desde").val(row.desde)
    $("#hasta").val(row.hasta)
    $("#msjeBeforeUpdate").html(`Se modificará la factura de <b>${nomCliente}</b>, número  <b>${nFacAnt}</b> del  <b>${fechaFacAnt}</b> por:`)
    $('#modalFacturaManual').modal('show');

}
$(document).on("click",".botoncerrarmodal",function(){
    limpiarModal()
})

function limpiarModal(fia)
{
    resetForm('#form_FacturaManual')
     $("#msjeBeforeUpdate").val('')
    $("#id").val('')
    $("#newNumFac").val('')
    $("#newFechaFac").val('')

}


text:
layout: error_401
css_filename: flatly.css
---


text:
namespace ReadAloud.Web.Controllers
{
    using System.Text.RegularExpressions;
    using System.Web.Mvc;

    public class HomeController : Controller
    {
        public ActionResult Index(string text)
        {
            // Simple validation for text, if invalid just skip
            string model = this.Server.UrlDecode(text) ?? string.Empty;

            if (model.Length > 50)
            {
                model = model.Substring(0, 50);
            }

            if (!Regex.IsMatch(model, @"[\w\s\!\?.,ÄäÖöÅå]+"))
            {
                model = string.Empty;
            }

            // Use slightly unconventional ASP.NET MVC syntax due to stripped
            // down route format causing problems in View discovery.
            var viewData = new ViewDataDictionary<string> { Model = model };

            return new ViewResult
                {
                    ViewData = viewData,
                    ViewName = "Index"
                };
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sinensia, Shanghai 4(12): 368 (1934)

#### Original name
Nitschkia macrospora Teng, 1934

### Remarks
null


text:
import os

from core import path_util
from core import perf_benchmark

from telemetry import benchmark
from telemetry import page as page_module
from telemetry.page import legacy_page_test
from telemetry.page import shared_page_state
from telemetry import story
from telemetry.value import list_of_scalar_values

from benchmarks import pywebsocket_server
from page_sets import webgl_supported_shared_state

BLINK_PERF_BASE_DIR = os.path.join(path_util.GetChromiumSrcDir(),
                                   'third_party', 'WebKit', 'PerformanceTests')
SKIPPED_FILE = os.path.join(BLINK_PERF_BASE_DIR, 'Skipped')

def CreateStorySetFromPath(path, skipped_file,
                           shared_page_state_class=(
                               shared_page_state.SharedPageState)):
  assert os.path.exists(path)

  page_urls = []
  serving_dirs = set()

  def _AddPage(path):
    if not path.endswith('.html'):
      return
    if '../' in open(path, 'r').read():
      # If the page looks like it references its parent dir, include it.
      serving_dirs.add(os.path.dirname(os.path.dirname(path)))
    page_urls.append('file://' + path.replace('\\', '/'))

  def _AddDir(dir_path, skipped):
    for candidate_path in os.listdir(dir_path):
      if candidate_path == 'resources':
        continue
      candidate_path = os.path.join(dir_path, candidate_path)
      if candidate_path.startswith(skipped):
        continue
      if os.path.isdir(candidate_path):
        _AddDir(candidate_path, skipped)
      else:
        _AddPage(candidate_path)

  if os.path.isdir(path):
    skipped = []
    if os.path.exists(skipped_file):
      for line in open(skipped_file, 'r').readlines():
        line = line.strip()
        if line and not line.startswith('#'):
          skipped_path = os.path.join(os.path.dirname(skipped_file), line)
          skipped.append(skipped_path.replace('/', os.sep))
    _AddDir(path, tuple(skipped))
  else:
    _AddPage(path)
  ps = story.StorySet(base_dir=os.getcwd() + os.sep,
                      serving_dirs=serving_dirs)
  for url in page_urls:
    ps.AddStory(page_module.Page(
        url, ps, ps.base_dir,
        shared_page_state_class=shared_page_state_class))
  return ps

class _BlinkPerfMeasurement(legacy_page_test.LegacyPageTest):
  """Tuns a blink performance test and reports the results."""

  def __init__(self):
    super(_BlinkPerfMeasurement, self).__init__()
    with open(os.path.join(os.path.dirname(__file__),
                           'blink_perf.js'), 'r') as f:
      self._blink_perf_js = f.read()

  def WillNavigateToPage(self, page, tab):
    del tab  # unused
    page.script_to_evaluate_on_commit = self._blink_perf_js

  def CustomizeBrowserOptions(self, options):
    options.AppendExtraBrowserArgs([
        '--js-flags=--expose_gc',
        '--enable-experimental-web-platform-features',
        '--disable-gesture-requirement-for-media-playback',
        '--enable-experimental-canvas-features',
        # TODO(qinmin): After fixing crbug.com/592017, remove this command line.
        '--reduce-security-for-testing'
    ])
    if 'content-shell' in options.browser_type:
      options.AppendExtraBrowserArgs('--expose-internals-for-testing')

  def ValidateAndMeasurePage(self, page, tab, results):
    tab.WaitForJavaScriptExpression('testRunner.isDone', 600)

    log = tab.EvaluateJavaScript('document.getElementById("log").innerHTML')

    for line in log.splitlines():
      if line.startswith("FATAL: "):
        print line
        continue
      if not line.startswith('values '):
        continue
      parts = line.split()
      values = [float(v.replace(',', '')) for v in parts[1:-1]]
      units = parts[-1]
      metric = page.display_name.split('.')[0].replace('/', '_')
      results.AddValue(list_of_scalar_values.ListOfScalarValues(
          results.current_page, metric, units, values))

      break

    print log

class _SharedPywebsocketPageState(shared_page_state.SharedPageState):
  """Runs a pywebsocket server."""

  def __init__(self, test, finder_options, user_story_set):
    super(_SharedPywebsocketPageState, self).__init__(
        test, finder_options, user_story_set)
    self.platform.StartLocalServer(pywebsocket_server.PywebsocketServer())

class BlinkPerfBindings(perf_benchmark.PerfBenchmark):
  tag = 'bindings'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.bindings'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'Bindings')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

  @classmethod
  def ShouldDisable(cls, possible_browser):
    return cls.IsSvelte(possible_browser)  # http://crbug.com/563979

@benchmark.Enabled('content-shell')
class BlinkPerfBlinkGC(perf_benchmark.PerfBenchmark):
  tag = 'blink_gc'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.blink_gc'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'BlinkGC')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

class BlinkPerfCSS(perf_benchmark.PerfBenchmark):
  tag = 'css'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.css'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'CSS')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

@benchmark.Disabled('android-webview', # http://crbug.com/593200
                    'reference')  # http://crbug.com/576779
class BlinkPerfCanvas(perf_benchmark.PerfBenchmark):
  tag = 'canvas'
  test = _BlinkPerfMeasurement

  @classmethod
  def ShouldDisable(cls, possible_browser):
    return cls.IsSvelte(possible_browser)  # http://crbug.com/593973.

  @classmethod
  def Name(cls):
    return 'blink_perf.canvas'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'Canvas')
    story_set = CreateStorySetFromPath(
        path, SKIPPED_FILE,
        shared_page_state_class=(
            webgl_supported_shared_state.WebGLSupportedSharedState))
    # WebGLSupportedSharedState requires the skipped_gpus property to
    # be set on each page.
    for page in story_set:
      page.skipped_gpus = []
    return story_set

class BlinkPerfDOM(perf_benchmark.PerfBenchmark):
  tag = 'dom'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.dom'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'DOM')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

@benchmark.Disabled('win')  # http://crbug.com/588819
class BlinkPerfEvents(perf_benchmark.PerfBenchmark):
  tag = 'events'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.events'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'Events')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

@benchmark.Disabled('win8')  # http://crbug.com/462350
class BlinkPerfLayout(perf_benchmark.PerfBenchmark):
  tag = 'layout'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.layout'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'Layout')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

  @classmethod
  def ShouldDisable(cls, possible_browser):
    return cls.IsSvelte(possible_browser)  # http://crbug.com/551950

class BlinkPerfPaint(perf_benchmark.PerfBenchmark):
  tag = 'paint'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.paint'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'Paint')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

  @classmethod
  def ShouldDisable(cls, possible_browser):
    return cls.IsSvelte(possible_browser)  # http://crbug.com/574483

@benchmark.Disabled('win')  # crbug.com/488493
class BlinkPerfParser(perf_benchmark.PerfBenchmark):
  tag = 'parser'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.parser'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'Parser')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

class BlinkPerfSVG(perf_benchmark.PerfBenchmark):
  tag = 'svg'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.svg'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'SVG')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

class BlinkPerfShadowDOM(perf_benchmark.PerfBenchmark):
  tag = 'shadow_dom'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.shadow_dom'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'ShadowDOM')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

# This benchmark is for local testing, doesn't need to run on bots.
@benchmark.Disabled('all')
class BlinkPerfXMLHttpRequest(perf_benchmark.PerfBenchmark):
  tag = 'xml_http_request'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.xml_http_request'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'XMLHttpRequest')
    return CreateStorySetFromPath(path, SKIPPED_FILE)

# Disabled on Windows and ChromeOS due to https://crbug.com/521887
@benchmark.Disabled('win', 'chromeos')
class BlinkPerfPywebsocket(perf_benchmark.PerfBenchmark):
  """The blink_perf.pywebsocket tests measure turn-around-time of 10MB
  send/receive for XHR, Fetch API and WebSocket. We might ignore < 10%
  regressions, because the tests are noisy and such regressions are
  often unreproducible (https://crbug.com/549017).
  """
  tag = 'pywebsocket'
  test = _BlinkPerfMeasurement

  @classmethod
  def Name(cls):
    return 'blink_perf.pywebsocket'

  def CreateStorySet(self, options):
    path = os.path.join(BLINK_PERF_BASE_DIR, 'Pywebsocket')
    return CreateStorySetFromPath(
        path, SKIPPED_FILE,
        shared_page_state_class=_SharedPywebsocketPageState)

  @classmethod
  def ShouldDisable(cls, possible_browser):
    return cls.IsSvelte(possible_browser)  # http://crbug.com/551950