text:
package ml.dmlc.xgboost4j.scala.spark

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import ml.dmlc.xgboost4j.java.{IRabitTracker, Rabit, XGBoostError, DMatrix => JDMatrix, RabitTracker => PyRabitTracker}
import ml.dmlc.xgboost4j.scala.rabit.RabitTracker
import ml.dmlc.xgboost4j.scala.{XGBoost => SXGBoost, _}
import org.apache.commons.logging.LogFactory
import org.apache.hadoop.fs.{FSDataInputStream, Path}
import org.apache.spark.ml.feature.{LabeledPoint => MLLabeledPoint}
import org.apache.spark.ml.linalg.SparseVector
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.Dataset
import org.apache.spark.{SparkContext, TaskContext}

import scala.concurrent.duration.{Duration, MILLISECONDS}

object TrackerConf {
  def apply(): TrackerConf = TrackerConf(Duration.apply(0L, MILLISECONDS), "python")
}

/**
  * Rabit tracker configurations.
  * @param workerConnectionTimeout The timeout for all workers to connect to the tracker.
  *                                Set timeout length to zero to disable timeout.
  *                                Use a finite, non-zero timeout value to prevent tracker from
  *                                hanging indefinitely (supported by "scala" implementation only.)
  * @param trackerImpl Choice between "python" or "scala". The former utilizes the Java wrapper of
  *                    the Python Rabit tracker (in dmlc_core), whereas the latter is implemented
  *                    in Scala without Python components, and with full support of timeouts.
  *                    The Scala implementation is currently experimental, use at your own risk.
  */
case class TrackerConf(workerConnectionTimeout: Duration, trackerImpl: String)

object XGBoost extends Serializable {
  private val logger = LogFactory.getLog("XGBoostSpark")

  private def convertBoosterToXGBoostModel(booster: Booster, isClassification: Boolean):
      XGBoostModel = {
    if (!isClassification) {
      new XGBoostRegressionModel(booster)
    } else {
      new XGBoostClassificationModel(booster)
    }
  }

  private def fromDenseToSparseLabeledPoints(
      denseLabeledPoints: Iterator[MLLabeledPoint],
      missing: Float): Iterator[MLLabeledPoint] = {
    if (!missing.isNaN) {
      val sparseLabeledPoints = new ListBuffer[MLLabeledPoint]
      for (labelPoint <- denseLabeledPoints) {
        val dVector = labelPoint.features.toDense
        val indices = new ListBuffer[Int]
        val values = new ListBuffer[Double]
        for (i <- dVector.values.indices) {
          if (dVector.values(i) != missing) {
            indices += i
            values += dVector.values(i)
          }
        }
        val sparseVector = new SparseVector(dVector.values.length, indices.toArray,
          values.toArray)
        sparseLabeledPoints += MLLabeledPoint(labelPoint.label, sparseVector)
      }
      sparseLabeledPoints.iterator
    } else {
      denseLabeledPoints
    }
  }

  private def repartitionData(trainingData: RDD[MLLabeledPoint], numWorkers: Int):
      RDD[MLLabeledPoint] = {
    if (numWorkers != trainingData.partitions.length) {
      logger.info(s"repartitioning training set to $numWorkers partitions")
      trainingData.repartition(numWorkers)
    } else {
      trainingData
    }
  }

  private[spark] def buildDistributedBoosters(
      trainingSet: RDD[MLLabeledPoint],
      xgBoostConfMap: Map[String, Any],
      rabitEnv: java.util.Map[String, String],
      numWorkers: Int, round: Int, obj: ObjectiveTrait, eval: EvalTrait,
      useExternalMemory: Boolean, missing: Float = Float.NaN): RDD[Booster] = {
    import DataUtils._
    val partitionedTrainingSet = repartitionData(trainingSet, numWorkers)
    val appName = partitionedTrainingSet.context.appName
    // to workaround the empty partitions in training dataset,
    // this might not be the best efficient implementation, see
    // (https://github.com/dmlc/xgboost/issues/1277)
    partitionedTrainingSet.mapPartitions {
      trainingSamples =>
        rabitEnv.put("DMLC_TASK_ID", TaskContext.getPartitionId().toString)
        Rabit.init(rabitEnv)
        var booster: Booster = null
        if (trainingSamples.hasNext) {
          val cacheFileName: String = {
            if (useExternalMemory) {
              s"$appName-${TaskContext.get().stageId()}-" +
                s"dtrain_cache-${TaskContext.getPartitionId()}"
            } else {
              null
            }
          }
          val partitionItr = fromDenseToSparseLabeledPoints(trainingSamples, missing)
          val trainingSet = new DMatrix(new JDMatrix(partitionItr, cacheFileName))
          if (xgBoostConfMap.contains("groupData") && xgBoostConfMap("groupData") != null) {
            trainingSet.setGroup(xgBoostConfMap("groupData").asInstanceOf[Seq[Seq[Int]]](
                TaskContext.getPartitionId()).toArray)
          }
          booster = SXGBoost.train(trainingSet, xgBoostConfMap, round,
            watches = new mutable.HashMap[String, DMatrix] {
              put("train", trainingSet)
            }.toMap, obj, eval)
          Rabit.shutdown()
        } else {
          Rabit.shutdown()
          throw new XGBoostError(s"detect the empty partition in training dataset, partition ID:" +
            s" ${TaskContext.getPartitionId().toString}")
        }
        Iterator(booster)
    }.cache()
  }

  /**
   * train XGBoost model with the DataFrame-represented data
   * @param trainingData the trainingset represented as DataFrame
   * @param params Map containing the parameters to configure XGBoost
   * @param round the number of iterations
   * @param nWorkers the number of xgboost workers, 0 by default which means that the number of
   *                 workers equals to the partition number of trainingData RDD
   * @param obj the user-defined objective function, null by default
   * @param eval the user-defined evaluation function, null by default
   * @param useExternalMemory indicate whether to use external memory cache, by setting this flag as
   *                           true, the user may save the RAM cost for running XGBoost within Spark
   * @param missing the value represented the missing value in the dataset
   * @param featureCol the name of input column, "features" as default value
   * @param labelCol the name of output column, "label" as default value
   * @throws ml.dmlc.xgboost4j.java.XGBoostError when the model training is failed
   * @return XGBoostModel when successful training
   */
  @throws(classOf[XGBoostError])
  def trainWithDataFrame(
      trainingData: Dataset[_],
      params: Map[String, Any],
      round: Int,
      nWorkers: Int,
      obj: ObjectiveTrait = null,
      eval: EvalTrait = null,
      useExternalMemory: Boolean = false,
      missing: Float = Float.NaN,
      featureCol: String = "features",
      labelCol: String = "label"): XGBoostModel = {
    require(nWorkers > 0, "you must specify more than 0 workers")
    val estimator = new XGBoostEstimator(params)
    // assigning general parameters
    estimator.
      set(estimator.useExternalMemory, useExternalMemory).
      set(estimator.round, round).
      set(estimator.nWorkers, nWorkers).
      set(estimator.customObj, obj).
      set(estimator.customEval, eval).
      set(estimator.missing, missing).
      setFeaturesCol(featureCol).
      setLabelCol(labelCol).
      fit(trainingData)
  }

  private[spark] def isClassificationTask(paramsMap: Map[String, Any]): Boolean = {
    val objective = paramsMap.getOrElse("objective", paramsMap.getOrElse("obj_type", null))
    objective != null && {
      val objStr = objective.toString
      objStr == "classification" || (!objStr.startsWith("reg:") && objStr != "count:poisson" &&
        objStr != "rank:pairwise")
    }
  }

  /**
   * train XGBoost model with the RDD-represented data
   * @param trainingData the trainingset represented as RDD
   * @param params Map containing the configuration entries
   * @param round the number of iterations
   * @param nWorkers the number of xgboost workers, 0 by default which means that the number of
   *                 workers equals to the partition number of trainingData RDD
   * @param obj the user-defined objective function, null by default
   * @param eval the user-defined evaluation function, null by default
   * @param useExternalMemory indicate whether to use external memory cache, by setting this flag as
   *                           true, the user may save the RAM cost for running XGBoost within Spark
   * @param missing the value represented the missing value in the dataset
   * @throws ml.dmlc.xgboost4j.java.XGBoostError when the model training is failed
   * @return XGBoostModel when successful training
   */
  def train(
      trainingData: RDD[MLLabeledPoint], params: Map[String, Any], round: Int,
      nWorkers: Int, obj: ObjectiveTrait = null, eval: EvalTrait = null,
      useExternalMemory: Boolean = false, missing: Float = Float.NaN): XGBoostModel = {
    require(nWorkers > 0, "you must specify more than 0 workers")
    trainWithRDD(trainingData, params, round, nWorkers, obj, eval, useExternalMemory, missing)
  }

  private def overrideParamMapAccordingtoTaskCPUs(
      params: Map[String, Any],
      sc: SparkContext): Map[String, Any] = {
    val coresPerTask = sc.getConf.get("spark.task.cpus", "1").toInt
    var overridedParams = params
    if (overridedParams.contains("nthread")) {
      val nThread = overridedParams("nthread").toString.toInt
      require(nThread <= coresPerTask,
        s"the nthread configuration ($nThread) must be no larger than " +
          s"spark.task.cpus ($coresPerTask)")
    } else {
      overridedParams = params + ("nthread" -> coresPerTask)
    }
    overridedParams
  }

  private def startTracker(nWorkers: Int, trackerConf: TrackerConf): IRabitTracker = {
    val tracker: IRabitTracker = trackerConf.trackerImpl match {
      case "scala" => new RabitTracker(nWorkers)
      case "python" => new PyRabitTracker(nWorkers)
      case _ => new PyRabitTracker(nWorkers)
    }

    val connectionTimeout = if (trackerConf.workerConnectionTimeout.isFinite()) {
      trackerConf.workerConnectionTimeout.toMillis
    } else {
      // 0 == Duration.Inf
      0L
    }

    require(tracker.start(connectionTimeout), "FAULT: Failed to start tracker")
    tracker
  }

  /**
   * various of train()
   * @param trainingData the trainingset represented as RDD
   * @param params Map containing the configuration entries
   * @param round the number of iterations
   * @param nWorkers the number of xgboost workers, 0 by default which means that the number of
   *                 workers equals to the partition number of trainingData RDD
   * @param obj the user-defined objective function, null by default
   * @param eval the user-defined evaluation function, null by default
   * @param useExternalMemory indicate whether to use external memory cache, by setting this flag as
   *                          true, the user may save the RAM cost for running XGBoost within Spark
   * @param missing the value represented the missing value in the dataset
   * @throws ml.dmlc.xgboost4j.java.XGBoostError when the model training is failed
   * @return XGBoostModel when successful training
   */
  @throws(classOf[XGBoostError])
  def trainWithRDD(
      trainingData: RDD[MLLabeledPoint], params: Map[String, Any], round: Int,
      nWorkers: Int, obj: ObjectiveTrait = null, eval: EvalTrait = null,
      useExternalMemory: Boolean = false, missing: Float = Float.NaN): XGBoostModel = {
    require(nWorkers > 0, "you must specify more than 0 workers")
    if (obj != null) {
      require(params.get("obj_type").isDefined, "parameter \"obj_type\" is not defined," +
        " you have to specify the objective type as classification or regression with a" +
        " customized objective function")
    }
    val trackerConf = params.get("tracker_conf") match {
      case None => TrackerConf()
      case Some(conf: TrackerConf) => conf
      case _ => throw new IllegalArgumentException("parameter \"tracker_conf\" must be an " +
        "instance of TrackerConf.")
    }
    val tracker = startTracker(nWorkers, trackerConf)
    val overridedConfMap = overrideParamMapAccordingtoTaskCPUs(params, trainingData.sparkContext)
    val boosters = buildDistributedBoosters(trainingData, overridedConfMap,
      tracker.getWorkerEnvs, nWorkers, round, obj, eval, useExternalMemory, missing)
    val sparkJobThread = new Thread() {
      override def run() {
        // force the job
        boosters.foreachPartition(() => _)
      }
    }
    sparkJobThread.setUncaughtExceptionHandler(tracker)
    sparkJobThread.start()
    val isClsTask = isClassificationTask(params)
    val trackerReturnVal = tracker.waitFor(0L)
    logger.info(s"Rabit returns with exit code $trackerReturnVal")
    postTrackerReturnProcessing(trackerReturnVal, boosters, overridedConfMap, sparkJobThread,
      isClsTask)
  }

  private def postTrackerReturnProcessing(
      trackerReturnVal: Int, distributedBoosters: RDD[Booster],
      configMap: Map[String, Any], sparkJobThread: Thread, isClassificationTask: Boolean):
    XGBoostModel = {
    if (trackerReturnVal == 0) {
      val xgboostModel = convertBoosterToXGBoostModel(distributedBoosters.first(),
        isClassificationTask)
      distributedBoosters.unpersist(false)
      xgboostModel
    } else {
      try {
        if (sparkJobThread.isAlive) {
          sparkJobThread.interrupt()
        }
      } catch {
        case ie: InterruptedException =>
          logger.info("spark job thread is interrupted")
      }
      throw new XGBoostError("XGBoostModel training failed")
    }
  }

  private def loadGeneralModelParams(inputStream: FSDataInputStream): (String, String, String) = {
    val featureCol = inputStream.readUTF()
    val labelCol = inputStream.readUTF()
    val predictionCol = inputStream.readUTF()
    (featureCol, labelCol, predictionCol)
  }

  private def setGeneralModelParams(
      featureCol: String, labelCol: String, predCol: String, xgBoostModel: XGBoostModel):
      XGBoostModel = {
    xgBoostModel.setFeaturesCol(featureCol)
    xgBoostModel.setLabelCol(labelCol)
    xgBoostModel.setPredictionCol(predCol)
  }

  /**
   * Load XGBoost model from path in HDFS-compatible file system
   *
   * @param modelPath The path of the file representing the model
   * @return The loaded model
   */
  def loadModelFromHadoopFile(modelPath: String)(implicit sparkContext: SparkContext):
      XGBoostModel = {
    val path = new Path(modelPath)
    val dataInStream = path.getFileSystem(sparkContext.hadoopConfiguration).open(path)
    val modelType = dataInStream.readUTF()
    val (featureCol, labelCol, predictionCol) = loadGeneralModelParams(dataInStream)
    modelType match {
      case "_cls_" =>
        val rawPredictionCol = dataInStream.readUTF()
        val thresholdLength = dataInStream.readInt()
        var thresholds: Array[Double] = null
        if (thresholdLength != -1) {
          thresholds = new Array[Double](thresholdLength)
          for (i <- 0 until thresholdLength) {
            thresholds(i) = dataInStream.readDouble()
          }
        }
        val xgBoostModel = new XGBoostClassificationModel(SXGBoost.loadModel(dataInStream))
        setGeneralModelParams(featureCol, labelCol, predictionCol, xgBoostModel).
          asInstanceOf[XGBoostClassificationModel].setRawPredictionCol(rawPredictionCol)
        if (thresholdLength != -1) {
          xgBoostModel.setThresholds(thresholds)
        }
        xgBoostModel
      case "_reg_" =>
        val xgBoostModel = new XGBoostRegressionModel(SXGBoost.loadModel(dataInStream))
        setGeneralModelParams(featureCol, labelCol, predictionCol, xgBoostModel)
    }
  }
}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: org.apache.http.impl.client.DefaultRedirectHandler
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_IMPL_CLIENT_DEFAULTREDIRECTHANDLER_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_IMPL_CLIENT_DEFAULTREDIRECTHANDLER_HPP_DECL

namespace j2cpp { namespace org { namespace apache { namespace http { namespace client { class RedirectHandler; } } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { class HttpResponse; } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace protocol { class HttpContext; } } } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace net { class URI; } } }

#include <java/lang/Object.hpp>
#include <java/net/URI.hpp>
#include <org/apache/http/HttpResponse.hpp>
#include <org/apache/http/client/RedirectHandler.hpp>
#include <org/apache/http/protocol/HttpContext.hpp>

namespace j2cpp {

namespace org { namespace apache { namespace http { namespace impl { namespace client {

	class DefaultRedirectHandler;
	class DefaultRedirectHandler
		: public object<DefaultRedirectHandler>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)

		explicit DefaultRedirectHandler(jobject jobj)
		: object<DefaultRedirectHandler>(jobj)
		{
		}

		operator local_ref<org::apache::http::client::RedirectHandler>() const;
		operator local_ref<java::lang::Object>() const;

		DefaultRedirectHandler();
		jboolean isRedirectRequested(local_ref< org::apache::http::HttpResponse >  const&, local_ref< org::apache::http::protocol::HttpContext >  const&);
		local_ref< java::net::URI > getLocationURI(local_ref< org::apache::http::HttpResponse >  const&, local_ref< org::apache::http::protocol::HttpContext >  const&);
	}; //class DefaultRedirectHandler

} //namespace client
} //namespace impl
} //namespace http
} //namespace apache
} //namespace org

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_IMPL_CLIENT_DEFAULTREDIRECTHANDLER_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_IMPL_CLIENT_DEFAULTREDIRECTHANDLER_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_IMPL_CLIENT_DEFAULTREDIRECTHANDLER_HPP_IMPL

namespace j2cpp {

org::apache::http::impl::client::DefaultRedirectHandler::operator local_ref<org::apache::http::client::RedirectHandler>() const
{
	return local_ref<org::apache::http::client::RedirectHandler>(get_jobject());
}

org::apache::http::impl::client::DefaultRedirectHandler::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

org::apache::http::impl::client::DefaultRedirectHandler::DefaultRedirectHandler()
: object<org::apache::http::impl::client::DefaultRedirectHandler>(
	call_new_object<
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_CLASS_NAME,
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_METHOD_NAME(0),
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_METHOD_SIGNATURE(0)
	>()
)
{
}

jboolean org::apache::http::impl::client::DefaultRedirectHandler::isRedirectRequested(local_ref< org::apache::http::HttpResponse > const &a0, local_ref< org::apache::http::protocol::HttpContext > const &a1)
{
	return call_method<
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_CLASS_NAME,
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_METHOD_NAME(1),
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_METHOD_SIGNATURE(1),
		jboolean
	>(get_jobject(), a0, a1);
}

local_ref< java::net::URI > org::apache::http::impl::client::DefaultRedirectHandler::getLocationURI(local_ref< org::apache::http::HttpResponse > const &a0, local_ref< org::apache::http::protocol::HttpContext > const &a1)
{
	return call_method<
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_CLASS_NAME,
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_METHOD_NAME(2),
		org::apache::http::impl::client::DefaultRedirectHandler::J2CPP_METHOD_SIGNATURE(2),
		local_ref< java::net::URI >
	>(get_jobject(), a0, a1);
}

J2CPP_DEFINE_CLASS(org::apache::http::impl::client::DefaultRedirectHandler,"org/apache/http/impl/client/DefaultRedirectHandler")
J2CPP_DEFINE_METHOD(org::apache::http::impl::client::DefaultRedirectHandler,0,"<init>","()V")
J2CPP_DEFINE_METHOD(org::apache::http::impl::client::DefaultRedirectHandler,1,"isRedirectRequested","(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z")
J2CPP_DEFINE_METHOD(org::apache::http::impl::client::DefaultRedirectHandler,2,"getLocationURI","(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/net/URI;")

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_IMPL_CLIENT_DEFAULTREDIRECTHANDLER_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION

redpajama_set_name: RedPajamaGithub


text:
namespace _08.SMS_Typing
{
    using System;

    public class Program
    {
        public static void Main()
        {
            var number = int.Parse(Console.ReadLine());
            var counter = 1;
            string sms = null;

            while (counter <= number)
            {
                counter++;
                var digit = Console.ReadLine();
                var numberOfDigits = digit.Length;
                var mainDigit = int.Parse(digit[0].ToString());
                if (mainDigit == 0)
                {
                    sms += " ";
                }
                else
                {
                    var offset = (mainDigit - 2) * 3;

                    if (mainDigit == 8 || mainDigit == 9)
                    {
                        offset++;
                    }

                    var letterIndex = offset + numberOfDigits - 1;
                    sms += (char)(97 + letterIndex);
                }
            }

            Console.WriteLine(sms);
        }
    }
}


text:
<project name="BaseJavaTests" default="dist" basedir=".">
  <description>
    building base java tests source code with ant
  </description>
  <!-- Set global properties for this build -->
  <property name="src" location="src"/>
  <property name="dist" location="dist"/>
  <property name="out.dir" location="${PRODUCT_DIR}/lib.java"/>
  <!-- TODO(jrg): establish a standard for the intermediate java
       directories.  Settle on a standard once ant/jar build files
       like this are androidified -->
  <property name="dest.dir" location="${PRODUCT_DIR}/java/base_javatests"/>

  <target name="init">
    <!-- Create the time stamp -->
    <tstamp/>
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${out.dir}"/>
    <mkdir dir="${dest.dir}"/>
  </target>

  <target name="compile" depends="init"
          description="compile the source " >
    <!-- Compile the java code from ${src} into ${build} -->
    <!-- TODO(jrg): adapting this to a proper android antfile will
         remove warnings like this:
           base.xml:23: warning: 'includeantruntime' was not set,
           defaulting to build.sysclasspath=last;
           set to false for repeatable builds
      -->
    <javac srcdir="${src}" destdir="${dest.dir}" debug="true" includeantruntime="false">
      <classpath>
        <path location="${ANDROID_SDK}/android.jar"/>
      </classpath>
    </javac>
  </target>

  <target name="dist" depends="compile"
          description="generate the distribution" >
    <!-- Create the distribution directory -->
    <mkdir dir="${out.dir}"/>

    <jar jarfile="${out.dir}/chromium_base_javatests.jar" basedir="${dest.dir}"/>
  </target>

  <target name="clean"
          description="clean up" >
    <!-- Delete the appropriate directory trees -->
    <delete dir="${dest.dir}"/>
    <delete dir="${dist}"/>
  </target>
</project>


text:
namespace ipc_fuzzer {

extern MersenneTwister* g_mersenne_twister;

void InitRand();

inline uint32_t RandU32() {
  return g_mersenne_twister->genrand_int32();
}

inline uint64_t RandU64() {
  return (static_cast<uint64_t>(RandU32()) << 32) | RandU32();
}

inline double RandDouble() {
  uint64_t rand_u64 = RandU64();
  return *reinterpret_cast<double*>(&rand_u64);
}

inline uint32_t RandInRange(uint32_t range) {
  return RandU32() % range;
}

inline bool RandEvent(uint32_t frequency) {
  return RandInRange(frequency) == 0;
}

inline size_t RandElementCount() {
  return RandU32() % 10;
}

}  // namespace ipc_fuzzer

#endif  // TOOLS_IPC_FUZZER_MUTATE_RAND_UTIL_H_


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="miracode_stripe.subscriber.stripe_event"
                 class="Miracode\StripeBundle\EventListener\StripeEventSubscriber">
            <tag name="kernel.event_subscriber" />
            <argument type="service" id="miracode_stripe.model_manager" />
        </service>

    </services>

</container>


text:
package colt.nicity.performance.latent;

/**
 *
 */
public class LatentStack {

    private final LatentGraph latentGraph;
    private final Latent[] stack;
    private final String[] tracerIds;
    private final long[] enters;
    private int depth;

    public LatentStack(LatentGraph latentGraph, int maxDepth) {
        this.latentGraph = latentGraph;
        stack = new Latent[maxDepth];
        tracerIds = new String[maxDepth];
        enters = new long[maxDepth];
        depth = 0;
    }

    public void enter(Latent latent, String tracerId) {
        enters[depth] = System.nanoTime();
        stack[depth] = latent;
        tracerIds[depth] = tracerId;
        depth++;
    }

    public long exit(Latent latent, long latency) {
        depth--;
        latency = sample(latency, enters[depth]);
        latentGraph.record(stack, tracerIds, depth);
        if (stack[depth] == latent) {
            stack[depth] = null;
        } else {
            System.out.println("Should be impossible. Likely some one forgot to us try {} finally {}");
        }
        return latency;
    }

    public long failed(Latent latent, long latency) {
        return exit(latent, latency);
    }

    public long failed(Latent latent, long latency, Throwable t) {
        return exit(latent, latency);
    }

    private long sample(long latency, long entered) {
        if (latency > 0) {
            latency /= 2;
        } // decay
        long elapse = System.nanoTime() - entered;
        latency += elapse;
        return latency;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>javax.swing (Groovy JDK enhancements)</title>

    <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

Overview

Package

Class

Index

Package javax.swing

Interfaces

ListModel

MutableComboBoxModel

Classes

AbstractButton

ButtonGroup

DefaultComboBoxModel

DefaultListModel

JComboBox

JMenu

JMenuBar

JPopupMenu

JTabbedPane

JToolBar

Overview

Package

Class

Index


text:
class CustomFailureApp < Devise::FailureApp
  # test that sublclassing FailureApp works properly
  def respond
    super
    Rails.logger.info('Testing error flow')
  end
end


text:
A listing of CLI options can be found by passing the `help` command to the CLI.

```
 $ solidarity help

Solidarity
 Commands

  solidarity     Check environment against solidarity rules
  create (c)     Displays this help
  help (h)       Displays this help
  report (r)     Report solidarity info about the current machine
  snapshot (s)   Take a snapshot of the versions and store in solidarity file

 Flags

  --verbose		 (-a) Prints all detected info during solidarity check
  --moderate		 (-m) Prints failures in check or single success message
  --silent		 (-s) No output, just a return code of success/failure
  --solidarityFile	 (-f) Use given path to solidarity file for settings
  --module		 (-d) Search for a solidarity file in the given npm package
  --stack		 (-t) Use a known technology stack, and not the local file
  --fix		     Apply fixes to failing rules if fix is available on rule

Solidarity is open source - https://github.com/infinitered/solidarity
If you need additional help, join our Slack at http://community.infinite.red
```

Here we will go into detail on each option flag.

## verbose (-a)
Passing `--verbose` or `-a` flags will modify output to be verbose.

## moderate (-m)
Passing `--moderate` or `-m` flags will modify output to be moderate, meaning only failures exclusive or a single success will be printed.

## silent (-s)
Passing `--silent` or `-s` flags will modify output to be silent, meaning no output will occur.  You'll have to see if the command return is non-zero to see if it failed.

## solidarityFile (-f)
Passing `--solidarityFile` or `-f` flags will direct the file to use for the solidarity check.

> For example:  `solidarity -solidarityFile ./my/special/file.json` will run the designated file instead of looking for a local folder Solidarity file.

## module (-m)
Passing `--module` or `-m` flags will modify the designated solidarity file, to run a file found in the given `node_module` stack.

> For example:  `solidarity --module smoothReporter` will run the solidarity file in the root of the npm package `smoothReporter` instead of our own.

## stack (-t)
Passing `--stack` or `-t` flags will make our stack look to GitHub for a well known tech stack.

> For example: `solidarity --stack react-native` will check our machine if we are ready to run React Native projects, but not a specific React Native project.

Stacks are community managed and found here: https://github.com/infinitered/solidarity-stacks

## fix
Passing `--fix` flag will run fix scripts on any failing rules providing them.


text:
docker pull tobymccann/pelican:latest
docker run -t --name=pelican-run -v $(pwd):/site tobymccann/pelican
docker rm pelican-run


text:
var class__biggest__int__convertible_8js =
[
    [ "class_biggest_int_convertible", "class__biggest__int__convertible_8js.html#ad0af82f3ccf26d573b334c63b3aec07b", null ]
];


text:
#ifndef MONGOC_CURSOR_FILTER_PRIVATE_H
#define MONGOC_CURSOR_FILTER_PRIVATE_H

#if !defined (MONGOC_I_AM_A_DRIVER) && !defined (MONGOC_COMPILATION)
//#error "Only <mongoc.h> can be included directly."
#endif

#include <bson.h>

#include "mongoc-cursor-private.h"

BSON_BEGIN_DECLS

typedef enum
{
   MONGO_CURSOR_TRANSFORM_DROP,
   MONGO_CURSOR_TRANSFORM_PASS,
   MONGO_CURSOR_TRANSFORM_MUTATE,
} mongoc_cursor_transform_mode_t;

typedef mongoc_cursor_transform_mode_t
(*mongoc_cursor_transform_filter_t)(const bson_t *bson,
                                    void         *ctx);

typedef void (*mongoc_cursor_transform_mutate_t)(const bson_t *bson,
                                                 bson_t       *out,
                                                 void         *ctx);

typedef void (*mongoc_cursor_transform_dtor_t)(void *ctx);

void
_mongoc_cursor_transform_init (mongoc_cursor_t                 *cursor,
                               mongoc_cursor_transform_filter_t filter,
                               mongoc_cursor_transform_mutate_t mutate,
                               mongoc_cursor_transform_dtor_t   dtor,
                               void                            *ctx);

BSON_END_DECLS

#endif /* MONGOC_CURSOR_FILTER_PRIVATE_H */


text:
package io.opentelemetry.api.logs;

import static io.opentelemetry.api.internal.ValidationUtil.API_USAGE_LOGGER_NAME;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;

import io.opentelemetry.internal.testing.slf4j.SuppressLogger;
import org.junit.jupiter.api.Test;

class DefaultLoggerProviderTest {

  @Test
  @SuppressLogger(loggerName = API_USAGE_LOGGER_NAME)
  void noopLoggerProvider_doesNotThrow() {
    LoggerProvider provider = LoggerProvider.noop();

    assertThat(provider).isSameAs(DefaultLoggerProvider.getInstance());
    assertThatCode(() -> provider.get("scope-name")).doesNotThrowAnyException();
    assertThatCode(
            () ->
                provider
                    .loggerBuilder("scope-name")
                    .setInstrumentationVersion("1.0")
                    .setSchemaUrl("http://schema.com")
                    .build())
        .doesNotThrowAnyException();

    assertThatCode(() -> provider.loggerBuilder("scope-name").build().logRecordBuilder())
        .doesNotThrowAnyException();
    assertThatCode(() -> provider.loggerBuilder("scope-name").build().eventBuilder("event-name"))
        .doesNotThrowAnyException();
    assertThatCode(
            () ->
                provider
                    .loggerBuilder("scope-name")
                    .setEventDomain("event-domain")
                    .build()
                    .logRecordBuilder())
        .doesNotThrowAnyException();
    assertThatCode(
            () ->
                provider
                    .loggerBuilder("scope-name")
                    .setEventDomain("event-domain")
                    .build()
                    .eventBuilder("event-name"))
        .doesNotThrowAnyException();
  }
}


text:
/*	$NetBSD: inet_windowsize.c,v 1.1.1.1 2009/06/23 10:09:00 tron Exp $	*/

/*++
/* NAME
/*	inet_windowsize 3
/* SUMMARY
/*	TCP window scaling control
/* SYNOPSIS
/*	#include <iostuff.h>
/*
/*	int	inet_windowsize;
/*
/*	void	set_inet_windowsize(sock, windowsize)
/*	int	sock;
/*	int	windowsize;
/* DESCRIPTION
/*	set_inet_windowsize() overrides the default TCP window size
/*	with the specified value. When called before listen() or
/*	accept(), this works around broken infrastructure that
/*	mis-handles TCP window scaling options.
/*
/*	The global inet_windowsize variable is available for other
/*	routines to remember that they wish to override the default
/*	TCP window size. The variable is not accessed by the
/*	set_inet_windowsize() function itself.
/*
/*	Arguments:
/* .IP sock
/*	TCP communication endpoint, before the connect(2) or listen(2) call.
/* .IP windowsize
/*	The preferred TCP window size. This must be > 0.
/* DIAGNOSTICS
/*	Panic: interface violation.
/*	Warnings: some error return from setsockopt().
/* LICENSE
/* .ad
/* .fi
/*	The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/*	Wietse Venema
/*	IBM T.J. Watson Research
/*	P.O. Box 704
/*	Yorktown Heights, NY 10598, USA
/*--*/

/* System libraries. */

#include <sys_defs.h>
#include <sys/socket.h>

/* Utility library. */

#include <msg.h>
#include <iostuff.h>

/* Application storage. */

 /*
  * Tunable to work around broken routers.
  */
int     inet_windowsize = 0;

/* set_inet_windowsize - set TCP send/receive window size */

void    set_inet_windowsize(int sock, int windowsize)
{

    /*
     * Sanity check.
     */
    if (windowsize <= 0)
	msg_panic("inet_windowsize: bad window size %d", windowsize);

    /*
     * Generic implementation: set the send and receive buffer size before
     * listen() or connect().
     */
    if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *) &windowsize,
		   sizeof(windowsize)) < 0)
	msg_warn("setsockopt SO_SNDBUF %d: %m", windowsize);
    if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *) &windowsize,
		   sizeof(windowsize)) < 0)
	msg_warn("setsockopt SO_RCVBUF %d: %m", windowsize);
}


text:
// Package pathmap provides utilities for matching and generating paths
// based on a pattern string.
package pathmap

import (
	"fmt"
	"net/url"
	"path/filepath"
	"regexp"
	"strings"
)

// Mapper provides path parsing and generating with named segments
// See NewMapper for details on construction
type Mapper struct {
	// Regexp used for parsing strings to variables
	re *regexp.Regexp
	// Array of segments used for generating strings from variables
	seg []segment
}

// This regex searches for named path segments of the form :mySeg or :mySeg*
var namedSeg = regexp.MustCompile("(^|/):([^*/]*)(\\*?)")

// NewMapper produces a Mapper object from a pattern string.
// Patterns strings are paths that have named segments that are extracted during
// parsing and populated during generation.
// Example:
// 		m := NewMapper("/dir/:segment/home/:rest*")
//  	s, err := m.Parse("/dir/foo/home/hello/world")	// {"segment": "foo", "rest": "hello/world"}, nil
//		p := m.Generate(s) 								// /dir/foo/home/hello/world
func NewMapper(pat string) (*Mapper, error) {
	// All handling below assumes unix-style '/' separated paths
	pat = filepath.ToSlash(pat)

	// This is a sanity check to ensure that the path is not malformed.
	// By prepending the / we stop url from getting confused if there's
	// a leading colon
	u, err := url.Parse("/" + pat)
	if err != nil {
		return nil, fmt.Errorf("pattern (%s) is not a valid path: '%v'", pat, err)
	}
	if u.EscapedPath() != u.Path {
		return nil, fmt.Errorf("pattern (%s) is requires escaping", pat)
	}

	var (
		segments []segment
		patReg   = "^"
	)

	for i, seg := range strings.Split(pat, "/") {
		// A slash must precede any segment after the first
		if i != 0 {
			patReg += "/"
			segments = append(segments, staticsegment("/"))
		}

		// If the segment is empty there's nothing else to do
		if seg == "" {
			continue
		}

		// If the segment starts with a ':' then it is a named segment
		if seg[0] == ':' {
			var segname string
			if seg[len(seg)-1] == '*' {
				segname = seg[1 : len(seg)-1]
				patReg += fmt.Sprintf("(?P<%s>(?:[^/]+/)*(?:[^/]+))", segname)
			} else {
				segname = seg[1:]
				patReg += fmt.Sprintf("(?P<%s>(?:[^/]+))", segname)
			}
			segments = append(segments, varsegment(segname))
		} else {
			segments = append(segments, staticsegment(seg))
			patReg += regexp.QuoteMeta(seg)
		}
	}
	patReg += "$"

	re, err := regexp.Compile(patReg)
	if err != nil {
		return nil, fmt.Errorf("error compiling regex for pattern (%s):\nRegex: %s\nError: %v", pat, patReg, err)
	}

	return &Mapper{
		re:  re,
		seg: segments,
	}, nil
}

// Parse extracts named segments from the path provided
// All segments must appear in the path
func (m Mapper) Parse(path string) (map[string]string, error) {
	// The regex is based on unix-style paths so we need to convert
	path = filepath.ToSlash(path)

	match := m.re.FindStringSubmatch(path)
	if len(match) == 0 {
		return nil, fmt.Errorf("path (%s) did not match regex (%v)", path, m.re)
	}

	out := make(map[string]string)
	// The first SubexpName is "" so we skip it
	for i, v := range m.re.SubexpNames()[1:] {
		// The first match is the full string so add 1
		out[v] = match[i+1]
	}
	return out, nil
}

// Generate produces a path from a map of segment values.
// All required values must be present
func (m Mapper) Generate(vars map[string]string) (string, error) {
	var gen string
	for _, s := range m.seg {
		seg, err := s.str(vars)
		if err != nil {
			return "", err
		}
		gen += seg
	}
	// Convert back to local path format at the end
	return filepath.FromSlash(gen), nil
}

type segment interface {
	str(map[string]string) (string, error)
}

type staticsegment string

func (s staticsegment) str(map[string]string) (string, error) {
	return string(s), nil
}

type varsegment string

func (v varsegment) str(p map[string]string) (string, error) {
	if s, ok := p[string(v)]; ok {
		return s, nil
	}
	return "", fmt.Errorf("path generation failure. Missing key: %s", v)
}


text:
package org.consumersunion.stories.server.persistence;

import java.util.List;

import javax.inject.Inject;

import org.consumersunion.stories.SpringTestCase;
import org.consumersunion.stories.common.shared.model.NotificationTrigger;
import org.consumersunion.stories.common.shared.model.Subscription;

import static org.consumersunion.stories.common.shared.model.NotificationTrigger.STORY_ADDED;

public class SubscriptionPersisterTest extends SpringTestCase {
    private static final int ALREAD_EXISTING_TARGET = 960;
    private static final int PROFILE = 1001;

    @Inject
    SubscriptionPersister subscriptionPersister;

    private final Subscription preExistingSubscription = Subscription.builder()
            .withProfile(PROFILE)
            .withTarget(ALREAD_EXISTING_TARGET)
            .withType(STORY_ADDED)
            .build();

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        subscriptionPersister.deleteAll();
        subscriptionPersister.create(preExistingSubscription);
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();

        subscriptionPersister.deleteAll();
    }

    public void test_get() {
        List<Subscription> subscriptions = subscriptionPersister.getSubscriptions(ALREAD_EXISTING_TARGET, STORY_ADDED);

        assertEquals(1, subscriptions.size());
    }

    public void test_create() {
        int target = 961;
        NotificationTrigger type = STORY_ADDED;

        subscriptionPersister.create(Subscription.builder()
                .withProfile(PROFILE)
                .withTarget(target)
                .withType(type)
                .build());

        List<Subscription> subscriptions = subscriptionPersister.getSubscriptions(target, type);
        assertEquals(1, subscriptions.size());
    }

    public void test_delete() {
        int target = 962;
        NotificationTrigger type = STORY_ADDED;
        Subscription subscription = Subscription.builder()
                .withProfile(PROFILE)
                .withTarget(target)
                .withType(type)
                .build();

        subscriptionPersister.create(subscription);

        subscriptionPersister.setInactive(subscription);

        List<Subscription> subscriptions = subscriptionPersister.getSubscriptions(target, type);
        assertFalse(subscriptions.get(0).isActive());
    }
}


text:
package org.displaytag.decorator;

/**
 * Test decorator used in tests.
 *
 * @author Fabrizio Giustina
 *
 * @version $Revision: 1081 $ ($Author: fgiust $)
 */
public class TableDecoratorThree extends TableDecorator {

    /**
     * Setter for simple.
     *
     * @param simple
     *            The simple property to set.
     */
    public void setSimple(final String simple) {
        //
    }

    /**
     * setter for a mapped property.
     *
     * @param key
     *            property name
     */
    public void setMapped(final String key) {
        //
    }

    /**
     * setter for an indexed property.
     *
     * @param key
     *            property index
     */
    public void setIndexed(final int key) {
        //
    }

}


text:
package org.ofbiz.widget.html;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javolution.util.FastMap;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.control.RequestHandler;
import org.ofbiz.webapp.taglib.ContentUrlTag;
import org.ofbiz.widget.ModelWidget;
import org.ofbiz.widget.WidgetContentWorker;
import org.ofbiz.widget.WidgetDataResourceWorker;
import org.ofbiz.widget.WidgetWorker;
import org.ofbiz.widget.form.FormStringRenderer;
import org.ofbiz.widget.form.ModelForm;
import org.ofbiz.widget.menu.MenuStringRenderer;
import org.ofbiz.widget.menu.ModelMenu;
import org.ofbiz.widget.screen.ModelScreenWidget;
import org.ofbiz.widget.screen.ScreenStringRenderer;
import org.ofbiz.widget.screen.ModelScreenWidget.ColumnContainer;

/**
 * Widget Library - HTML Form Renderer implementation
 * @deprecated Use MacroScreenRenderer.
 */
public class HtmlScreenRenderer extends HtmlWidgetRenderer implements ScreenStringRenderer {

    public static final String module = HtmlScreenRenderer.class.getName();
    protected int elementId = 999;

    public HtmlScreenRenderer() {}

    protected String getNextElementId() {
        elementId++;
        return "hsr" + elementId;
    }

    public String getRendererName() {
        return "html";
    }

    public void renderScreenBegin(Appendable writer, Map<String, Object> context) throws IOException {
        writer.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        appendWhitespace(writer);
    }

    public void renderScreenEnd(Appendable writer, Map<String, Object> context) throws IOException {
    }

    public void renderSectionBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Section section) throws IOException {
        if (section.isMainSection) {
            this.widgetCommentsEnabled = ModelWidget.widgetBoundaryCommentsEnabled(context);
        }
        renderBeginningBoundaryComment(writer, section.isMainSection?"Screen":"Section Widget", section);
    }

    public void renderSectionEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Section section) throws IOException {
        renderEndingBoundaryComment(writer, section.isMainSection?"Screen":"Section Widget", section);
    }

    public void renderContainerBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Container container) throws IOException {
        String containerId = container.getId(context);
        String autoUpdateTarget = container.getAutoUpdateTargetExdr(context);
        HttpServletRequest request = (HttpServletRequest) context.get("request");
        if (UtilValidate.isNotEmpty(autoUpdateTarget) && UtilHttp.isJavaScriptEnabled(request)) {
            if (UtilValidate.isEmpty(containerId)) {
                containerId = getNextElementId();
            }
            HttpServletResponse response = (HttpServletResponse) context.get("response");
            ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
            RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");

            writer.append("");
            appendWhitespace(writer);
        }
        writer.append("
");
        appendWhitespace(writer);
    }
    public void renderContainerEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Container container) throws IOException {
        writer.append("
");
        appendWhitespace(writer);
    }

    public void renderHorizontalSeparator(Appendable writer, Map<String, Object> context, ModelScreenWidget.HorizontalSeparator separator) throws IOException {
        writer.append("
");
        appendWhitespace(writer);
    }

    public void renderScreenletBegin(Appendable writer, Map<String, Object> context, boolean collapsed, ModelScreenWidget.Screenlet screenlet) throws IOException {
        HttpServletRequest request = (HttpServletRequest) context.get("request");
        HttpServletResponse response = (HttpServletResponse) context.get("response");
        boolean javaScriptEnabled = UtilHttp.isJavaScriptEnabled(request);
        ModelScreenWidget.Menu tabMenu = screenlet.getTabMenu();
        if (tabMenu != null) {
            tabMenu.renderWidgetString(writer, context, this);
        }
        writer.append("
");
        appendWhitespace(writer);

        String title = screenlet.getTitle(context);
        ModelScreenWidget.Menu navMenu = screenlet.getNavigationMenu();
        ModelScreenWidget.Form navForm = screenlet.getNavigationForm();
        String collapsibleAreaId = null;
        if (UtilValidate.isNotEmpty(title) || navMenu != null || navForm != null || screenlet.collapsible()) {
            writer.append("
");
            appendWhitespace(writer);
            writer.append("
");
            appendWhitespace(writer);
            if (UtilValidate.isNotEmpty(title)) {
                writer.append("
");
                writer.append(title);
                writer.append("
");
                appendWhitespace(writer);
            }
            if (screenlet.collapsible()) {
                collapsibleAreaId = this.getNextElementId();
                String expandToolTip = null;
                String collapseToolTip = null;
                Map<String, Object> uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap"));
                Map<String, Object> paramMap = UtilGenerics.checkMap(context.get("requestParameters"));
                Map<String, Object> requestParameters = new HashMap<String, Object>(paramMap);
                if (uiLabelMap != null) {
                    expandToolTip = (String) uiLabelMap.get("CommonExpand");
                    collapseToolTip = (String) uiLabelMap.get("CommonCollapse");
                }
                writer.append("
<a ");
                    if (javaScriptEnabled) {
                        writer.append("onclick=\"javascript:toggleScreenlet(this, '").append(collapsibleAreaId).append("', '").append(expandToolTip).append("', '").append(collapseToolTip).append("');\"");
                    } else {
                        requestParameters.put(screenlet.getPreferenceKey(context) + "_collapsed", "false");
                        String queryString = UtilHttp.urlEncodeArgs(requestParameters);
                        writer.append("href=\"").append(request.getRequestURI()).append("?").append(queryString).append("\"");
                    }
                    if (UtilValidate.isNotEmpty(expandToolTip)) {
                        writer.append(" title=\"").append(expandToolTip).append("\"");
                    }
                } else {
                    writer.append("expanded\"><a ");
                    if (javaScriptEnabled) {
                        writer.append("onclick=\"javascript:toggleScreenlet(this, '").append(collapsibleAreaId).append("', '").append(expandToolTip).append("', '").append(collapseToolTip).append("');\"");
                    } else {
                        requestParameters.put(screenlet.getPreferenceKey(context) + "_collapsed", "true");
                        String queryString = UtilHttp.urlEncodeArgs(requestParameters);
                        writer.append("href=\"").append(request.getRequestURI()).append("?").append(queryString).append("\"");
                    }
                    if (UtilValidate.isNotEmpty(collapseToolTip)) {
                        writer.append(" title=\"").append(collapseToolTip).append("\"");
                    }
                }
                writer.append(">&nbsp
");
                appendWhitespace(writer);
            }
            if (!collapsed) {
                if (navMenu != null) {
                    MenuStringRenderer savedRenderer = (MenuStringRenderer) context.get("menuStringRenderer");
                    MenuStringRenderer renderer = new ScreenletMenuRenderer(request, response);
                    context.put("menuStringRenderer", renderer);
                    navMenu.renderWidgetString(writer, context, this);
                    context.put("menuStringRenderer", savedRenderer);
                } else if (navForm != null) {
                    renderScreenletPaginateMenu(writer, context, navForm);
                }
            }
            writer.append("
");
            appendWhitespace(writer);
            writer.append("
");
            appendWhitespace(writer);
            writer.append("
");
            appendWhitespace(writer);
            writer.append("
");
            appendWhitespace(writer);
        }
    }

    protected void renderScreenletPaginateMenu(Appendable writer, Map<String, Object> context, ModelScreenWidget.Form form) throws IOException {
        HttpServletResponse response = (HttpServletResponse) context.get("response");
        HttpServletRequest request = (HttpServletRequest) context.get("request");
        ModelForm modelForm = form.getModelForm(context);
        modelForm.runFormActions(context);
        modelForm.preparePager(context);
        String targetService = modelForm.getPaginateTarget(context);
        if (targetService == null) {
            targetService = "${targetService}";
        }

        // get the parametrized pagination index and size fields
        int paginatorNumber = WidgetWorker.getPaginatorNumber(context);
        String viewIndexParam = modelForm.getMultiPaginateIndexField(context);
        String viewSizeParam = modelForm.getMultiPaginateSizeField(context);

        int viewIndex = modelForm.getViewIndex(context);
        int viewSize = modelForm.getViewSize(context);
        int listSize = modelForm.getListSize(context);

        int lowIndex = modelForm.getLowIndex(context);
        int highIndex = modelForm.getHighIndex(context);
        int actualPageSize = modelForm.getActualPageSize(context);

        // if this is all there seems to be (if listSize < 0, then size is unknown)
        if (actualPageSize >= listSize && listSize >= 0) return;

        // needed for the "Page" and "rows" labels
        Map<String, String> uiLabelMap = UtilGenerics.cast(context.get("uiLabelMap"));
        String ofLabel = "";
        if (uiLabelMap == null) {
            Debug.logWarning("Could not find uiLabelMap in context", module);
        } else {
            ofLabel = uiLabelMap.get("CommonOf");
            ofLabel = ofLabel.toLowerCase();
        }

        // for legacy support, the viewSizeParam is VIEW_SIZE and viewIndexParam is VIEW_INDEX when the fields are "viewSize" and "viewIndex"
        if (viewIndexParam.equals("viewIndex" + "_" + paginatorNumber)) viewIndexParam = "VIEW_INDEX" + "_" + paginatorNumber;
        if (viewSizeParam.equals("viewSize" + "_" + paginatorNumber)) viewSizeParam = "VIEW_SIZE" + "_" + paginatorNumber;

        ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
        RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");

        Map<String, Object> inputFields = UtilGenerics.toMap(context.get("requestParameters"));
        // strip out any multi form fields if the form is of type multi
        if (modelForm.getType().equals("multi")) {
            inputFields = UtilHttp.removeMultiFormParameters(inputFields);
        }
        String queryString = UtilHttp.urlEncodeArgs(inputFields);
        // strip legacy viewIndex/viewSize params from the query string
        queryString = UtilHttp.stripViewParamsFromQueryString(queryString, "" + paginatorNumber);
        // strip parametrized index/size params from the query string
        HashSet<String> paramNames = new HashSet<String>();
        paramNames.add(viewIndexParam);
        paramNames.add(viewSizeParam);
        queryString = UtilHttp.stripNamedParamsFromQueryString(queryString, paramNames);

        String anchor = "";
        String paginateAnchor = modelForm.getPaginateTargetAnchor();
        if (paginateAnchor != null) anchor = "#" + paginateAnchor;

        // preparing the link text, so that later in the code we can reuse this and just add the viewIndex
        StringBuilder prepLinkTextBuffer = new StringBuilder(targetService);
        if (prepLinkTextBuffer.indexOf("?") < 0) {
            prepLinkTextBuffer.append("?");
        } else if (prepLinkTextBuffer.indexOf("?", prepLinkTextBuffer.length() - 1) > 0) {
            prepLinkTextBuffer.append("&");
        }
        if (!UtilValidate.isEmpty(queryString) && !queryString.equals("null")) {
            prepLinkTextBuffer.append(queryString).append("&");
        }
        prepLinkTextBuffer.append(viewSizeParam).append("=").append(viewSize).append("&").append(viewIndexParam).append("=");
        String prepLinkText = prepLinkTextBuffer.toString();

        String linkText;

        appendWhitespace(writer);
        // The current screenlet title bar navigation syling requires rendering
        // these links in reverse order
        // Last button
        writer.append("<li class=\"").append(modelForm.getPaginateLastStyle());
        if (highIndex < listSize) {
            writer.append("\">").append(modelForm.getPaginateLastLabel(context)).append("");
        } else {
            // disabled button
            writer.append(" disabled\">").append(modelForm.getPaginateLastLabel(context));
        }
        writer.append("
");
        appendWhitespace(writer);
        // Next button
        writer.append("<li class=\"").append(modelForm.getPaginateNextStyle());
        if (highIndex < listSize) {
            writer.append("\">").append(modelForm.getPaginateNextLabel(context)).append("");
        } else {
            // disabled button
            writer.append(" disabled\">").append(modelForm.getPaginateNextLabel(context));
        }
        writer.append("
");
        appendWhitespace(writer);
        if (listSize > 0) {
            writer.append("
");
            writer.append(Integer.toString(lowIndex + 1)).append(" - ").append(Integer.toString(lowIndex + actualPageSize)).append(" ").append(ofLabel).append(" ").append(Integer.toString(listSize));
            writer.append("
");
            appendWhitespace(writer);
        }
        // Previous button
        writer.append("
 0) {
            writer.append("\">").append(modelForm.getPaginatePreviousLabel(context)).append("");
        } else {
            // disabled button
            writer.append(" disabled\">").append(modelForm.getPaginatePreviousLabel(context));
        }
        writer.append("
");
        appendWhitespace(writer);
        // First button
        writer.append("
 0) {
            writer.append("\">").append(modelForm.getPaginateFirstLabel(context)).append("");
        } else {
            writer.append(" disabled\">").append(modelForm.getPaginateFirstLabel(context));
        }
        writer.append("
");
        appendWhitespace(writer);
    }

    public void renderScreenletSubWidget(Appendable writer, Map<String, Object> context, ModelScreenWidget subWidget, ModelScreenWidget.Screenlet screenlet) throws GeneralException, IOException {
        if (subWidget.equals(screenlet.getNavigationForm())) {
            HttpServletRequest request = (HttpServletRequest) context.get("request");
            HttpServletResponse response = (HttpServletResponse) context.get("response");
            if (request != null && response != null) {
                Map<String, Object> globalCtx = UtilGenerics.checkMap(context.get("globalContext"));
                globalCtx.put("NO_PAGINATOR", true);
                FormStringRenderer savedRenderer = (FormStringRenderer) context.get("formStringRenderer");
                HtmlFormRenderer renderer = new HtmlFormRenderer(request, response);
                renderer.setRenderPagination(false);
                context.put("formStringRenderer", renderer);
                subWidget.renderWidgetString(writer, context, this);
                context.put("formStringRenderer", savedRenderer);
            }
        } else {
            subWidget.renderWidgetString(writer, context, this);
        }
    }

    public void renderScreenletEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Screenlet screenlet) throws IOException {
        writer.append("
");
        appendWhitespace(writer);
        writer.append("
");
        appendWhitespace(writer);
    }

    public static class ScreenletMenuRenderer extends HtmlMenuRenderer {
        public ScreenletMenuRenderer(HttpServletRequest request, HttpServletResponse response) {
            super(request, response);
        }
        @Override
        public void renderMenuOpen(Appendable writer, Map<String, Object> context, ModelMenu modelMenu) {}
        @Override
        public void renderMenuClose(Appendable writer, Map<String, Object> context, ModelMenu modelMenu) {}
    }

    public void renderLabel(Appendable writer, Map<String, Object> context, ModelScreenWidget.Label label) throws IOException {
        String labelText = label.getText(context);
        if (UtilValidate.isEmpty(labelText)) {
            // nothing to render
            return;
        }
        // open tag
        String style = label.getStyle(context);
        String id = label.getId(context);
        if (UtilValidate.isNotEmpty(style) || UtilValidate.isNotEmpty(id)) {
               writer.append("");

            // the text
            writer.append(labelText);

            // close tag
               writer.append("");

        } else {
            writer.append(labelText);
        }

        appendWhitespace(writer);
    }

    public void renderLink(Appendable writer, Map<String, Object> context, ModelScreenWidget.Link link) throws IOException {
        HttpServletResponse response = (HttpServletResponse) context.get("response");
        HttpServletRequest request = (HttpServletRequest) context.get("request");

        String targetWindow = link.getTargetWindow(context);
        String target = link.getTarget(context);

        String uniqueItemName = link.getModelScreen().getName() + "_LF_" + UtilMisc.<String>addToBigDecimalInMap(context, "screenUniqueItemIndex", BigDecimal.ONE);

        String linkType = WidgetWorker.determineAutoLinkType(link.getLinkType(), target, link.getUrlMode(), request);
        if ("hidden-form".equals(linkType)) {
            writer.append("<form method=\"post\"");
            writer.append(" action=\"");
            // note that this passes null for the parameterList on purpose so they won't be put into the URL
            WidgetWorker.buildHyperlinkUrl(writer, target, link.getUrlMode(), null, link.getPrefix(context),
                    link.getFullPath(), link.getSecure(), link.getEncode(), request, response, context);
            writer.append("\"");

            if (UtilValidate.isNotEmpty(targetWindow)) {
                writer.append(" target=\"");
                writer.append(targetWindow);
                writer.append("\"");
            }

            writer.append(" onsubmit=\"javascript:submitFormDisableSubmits(this)\"");

            writer.append(" name=\"");
            writer.append(uniqueItemName);
            writer.append("\">");

            for (Map.Entry<String, String> parameter: link.getParameterMap(context).entrySet()) {
                writer.append("<input name=\"");
                writer.append(parameter.getKey());
                writer.append("\" value=\"");
                writer.append(parameter.getValue());
                writer.append("\" type=\"hidden\"/>");
            }

            writer.append("</form>");
        }

        writer.append("<a");
        String id = link.getId(context);
        if (UtilValidate.isNotEmpty(id)) {
            writer.append(" id=\"");
            writer.append(id);
            writer.append("\"");
        }
        String style = link.getStyle(context);
        if (UtilValidate.isNotEmpty(style)) {
            writer.append(" class=\"");
            writer.append(style);
            writer.append("\"");
        }
        String name = link.getName(context);
        if (UtilValidate.isNotEmpty(name)) {
            writer.append(" name=\"");
            writer.append(name);
            writer.append("\"");
        }
        if (UtilValidate.isNotEmpty(targetWindow)) {
            writer.append(" target=\"");
            writer.append(targetWindow);
            writer.append("\"");
        }
        if (UtilValidate.isNotEmpty(target)) {
            writer.append(" href=\"");
            if ("hidden-form".equals(linkType)) {
                writer.append("javascript:document.");
                writer.append(uniqueItemName);
                writer.append(".submit()");
            } else {
                WidgetWorker.buildHyperlinkUrl(writer, target, link.getUrlMode(), link.getParameterMap(context), link.getPrefix(context),
                        link.getFullPath(), link.getSecure(), link.getEncode(), request, response, context);
            }
            writer.append("\"");
        }
        writer.append(">");

        // the text
        ModelScreenWidget.Image img = link.getImage();
        if (img == null) {
            writer.append(link.getText(context));
        } else {
            renderImage(writer, context, img);
        }

        // close tag
        writer.append("");

        appendWhitespace(writer);
    }

    public void renderImage(Appendable writer, Map<String, Object> context, ModelScreenWidget.Image image) throws IOException {
        // open tag
        String src = image.getSrc(context);
        if (UtilValidate.isEmpty(src)) {
            return;
        }
        writer.append("<img ");
        String id = image.getId(context);
        if (UtilValidate.isNotEmpty(id)) {
            writer.append(" id=\"");
            writer.append(id);
            writer.append("\"");
        }
        String style = image.getStyle(context);
        if (UtilValidate.isNotEmpty(style)) {
            writer.append(" class=\"");
            writer.append(style);
            writer.append("\"");
        }
        String wid = image.getWidth(context);
        if (UtilValidate.isNotEmpty(wid)) {
            writer.append(" width=\"");
            writer.append(wid);
            writer.append("\"");
        }
        String hgt = image.getHeight(context);
        if (UtilValidate.isNotEmpty(hgt)) {
            writer.append(" height=\"");
            writer.append(hgt);
            writer.append("\"");
        }
        String border = image.getBorder(context);
        if (UtilValidate.isNotEmpty(border)) {
            writer.append(" border=\"");
            writer.append(border);
            writer.append("\"");
        }
        String alt = image.getAlt(context);
        if (UtilValidate.isNotEmpty(alt)) {
            writer.append(" alt=\"");
            writer.append(alt);
            writer.append("\"");
        }

        writer.append(" src=\"");
        String urlMode = image.getUrlMode();
        boolean fullPath = false;
        boolean secure = false;
        boolean encode = false;
        HttpServletResponse response = (HttpServletResponse) context.get("response");
        HttpServletRequest request = (HttpServletRequest) context.get("request");
        if (urlMode != null && urlMode.equalsIgnoreCase("intra-app")) {
            if (request != null && response != null) {
                ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
                RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
                String urlString = rh.makeLink(request, response, src, fullPath, secure, encode);
                writer.append(urlString);
            } else {
                writer.append(src);
            }
        } else  if (urlMode != null && urlMode.equalsIgnoreCase("content")) {
            if (request != null && response != null) {
                StringBuilder newURL = new StringBuilder();
                ContentUrlTag.appendContentPrefix(request, newURL);
                newURL.append(src);
                writer.append(newURL.toString());
            }
        } else {
            writer.append(src);
        }

        writer.append("\"/>");

        appendWhitespace(writer);
    }

    public void renderContentBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException {
        String editRequest = content.getEditRequest(context);
        String editContainerStyle = content.getEditContainerStyle(context);
        String enableEditName = content.getEnableEditName(context);
        String enableEditValue = (String)context.get(enableEditName);

        if (Debug.verboseOn()) Debug.logVerbose("directEditRequest:" + editRequest, module);

        if (UtilValidate.isNotEmpty(editRequest) && "true".equals(enableEditValue)) {
            writer.append("
 ");
            appendWhitespace(writer);
        }
    }

    public void renderContentBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException {
        Locale locale = UtilMisc.ensureLocale(context.get("locale"));
        //Boolean nullThruDatesOnly = Boolean.valueOf(false);
        String mimeTypeId = "text/html";
        String expandedContentId = content.getContentId(context);
        String expandedDataResourceId = content.getDataResourceId(context);
        String renderedContent = null;
        LocalDispatcher dispatcher = (LocalDispatcher) context.get("dispatcher");
        Delegator delegator = (Delegator) context.get("delegator");

        // make a new map for content rendering; so our current map does not get clobbered
        Map<String, Object> contentContext = FastMap.newInstance();
        contentContext.putAll(context);
        String dataResourceId = (String)contentContext.get("dataResourceId");
        if (Debug.verboseOn()) Debug.logVerbose("expandedContentId:" + expandedContentId, module);

        try {
            if (UtilValidate.isNotEmpty(dataResourceId)) {
                if (WidgetDataResourceWorker.dataresourceWorker != null) {
                    renderedContent = WidgetDataResourceWorker.dataresourceWorker.renderDataResourceAsTextExt(delegator, dataResourceId, contentContext, locale, mimeTypeId, false);
                } else {
                    Debug.logError("Not rendering content, WidgetDataResourceWorker.dataresourceWorker not found.", module);
                }
            } else if (UtilValidate.isNotEmpty(expandedContentId)) {
                if (WidgetContentWorker.contentWorker != null) {
                    renderedContent = WidgetContentWorker.contentWorker.renderContentAsTextExt(dispatcher, delegator, expandedContentId, contentContext, locale, mimeTypeId, true);
                } else {
                    Debug.logError("Not rendering content, WidgetContentWorker.contentWorker not found.", module);
                }
            } else if (UtilValidate.isNotEmpty(expandedDataResourceId)) {
                if (WidgetDataResourceWorker.dataresourceWorker != null) {
                    renderedContent = WidgetDataResourceWorker.dataresourceWorker.renderDataResourceAsTextExt(delegator, expandedDataResourceId, contentContext, locale, mimeTypeId, false);
                } else {
                    Debug.logError("Not rendering content, WidgetDataResourceWorker.dataresourceWorker not found.", module);
                }
            }
            if (UtilValidate.isEmpty(renderedContent)) {
                String editRequest = content.getEditRequest(context);
                if (UtilValidate.isNotEmpty(editRequest)) {
                    if (WidgetContentWorker.contentWorker != null) {
                        WidgetContentWorker.contentWorker.renderContentAsTextExt(dispatcher, delegator, "NOCONTENTFOUND", writer, contentContext, locale, mimeTypeId, true);
                    } else {
                        Debug.logError("Not rendering content, WidgetContentWorker.contentWorker not found.", module);
                    }
                }
            } else {
                if (content.xmlEscape()) {
                    renderedContent = UtilFormatOut.encodeXmlValue(renderedContent);
                }

                writer.append(renderedContent);
            }

        } catch (GeneralException e) {
            String errMsg = "Error rendering included content with id [" + expandedContentId + "] : " + e.toString();
            Debug.logError(e, errMsg, module);
            //throw new RuntimeException(errMsg);
        } catch (IOException e2) {
            String errMsg = "Error rendering included content with id [" + expandedContentId + "] : " + e2.toString();
            Debug.logError(e2, errMsg, module);
            //throw new RuntimeException(errMsg);
        }
    }

    public void renderContentEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException {

                //Debug.logInfo("renderContentEnd, context:" + context, module);
        String expandedContentId = content.getContentId(context);
        String editMode = "Edit";
        String editRequest = content.getEditRequest(context);
        String editContainerStyle = content.getEditContainerStyle(context);
        String enableEditName = content.getEnableEditName(context);
        String enableEditValue = (String)context.get(enableEditName);
        if (editRequest != null && editRequest.toUpperCase().indexOf("IMAGE") > 0) {
            editMode += " Image";
        }
        //String editRequestWithParams = editRequest + "?contentId=${currentValue.contentId}&drDataResourceId=${currentValue.drDataResourceId}&directEditRequest=${directEditRequest}&indirectEditRequest=${indirectEditRequest}&caContentIdTo=${currentValue.caContentIdTo}&caFromDate=${currentValue.caFromDate}&caContentAssocTypeId=${currentValue.caContentAssocTypeId}";

        if (UtilValidate.isNotEmpty(editRequest) && "true".equals(enableEditValue)) {
            HttpServletResponse response = (HttpServletResponse) context.get("response");
            HttpServletRequest request = (HttpServletRequest) context.get("request");
            if (request != null && response != null) {
                if (editRequest.indexOf("?") < 0)  editRequest += "?";
                else editRequest += "&";
                editRequest += "contentId=" + expandedContentId;
                ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
                RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
                writer.append("").append(editMode).append("");
            }
            if (UtilValidate.isNotEmpty(editContainerStyle)) {
                writer.append("
");
            }
            appendWhitespace(writer);
        }
    }

    public void renderContentFrame(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException {

        HttpServletRequest request = (HttpServletRequest) context.get("request");
        HttpServletResponse response = (HttpServletResponse) context.get("response");
        if (request != null && response != null) {
            ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
            RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
            String dataResourceId = content.getDataResourceId(context);
//          String urlString = "/content/control/ViewSimpleContent?dataResourceId=" + dataResourceId;
            String urlString = "/ViewSimpleContent?dataResourceId=" + dataResourceId;

            writer.append("");
        }

    }

    public void renderSubContentBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException {

        String editRequest = content.getEditRequest(context);
        String editContainerStyle = content.getEditContainerStyle(context);
        String enableEditName = content.getEnableEditName(context);
        String enableEditValue = (String)context.get(enableEditName);
        if (UtilValidate.isNotEmpty(editRequest) && "true".equals(enableEditValue)) {
            writer.append("
 ");

            appendWhitespace(writer);
        }
    }

    public void renderSubContentBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException {
            Locale locale = Locale.getDefault();
            String mimeTypeId = "text/html";
            String expandedContentId = content.getContentId(context);
            String expandedMapKey = content.getMapKey(context);
            String renderedContent = null;
            LocalDispatcher dispatcher = (LocalDispatcher) context.get("dispatcher");
            Delegator delegator = (Delegator) context.get("delegator");

            // create a new map for the content rendering; so our current context does not get overwritten!
            Map<String, Object> contentContext = FastMap.newInstance();
            contentContext.putAll(context);

            try {
                if (WidgetContentWorker.contentWorker != null) {
                    renderedContent = WidgetContentWorker.contentWorker.renderSubContentAsTextExt(dispatcher, delegator, expandedContentId, expandedMapKey, contentContext, locale, mimeTypeId, true);
                    //Debug.logInfo("renderedContent=" + renderedContent, module);
                } else {
                    Debug.logError("Not rendering content, WidgetContentWorker.contentWorker not found.", module);
                }
                if (UtilValidate.isEmpty(renderedContent)) {
                    String editRequest = content.getEditRequest(context);
                    if (UtilValidate.isNotEmpty(editRequest)) {
                        if (WidgetContentWorker.contentWorker != null) {
                            WidgetContentWorker.contentWorker.renderContentAsTextExt(dispatcher, delegator, "NOCONTENTFOUND", writer, contentContext, locale, mimeTypeId, true);
                        } else {
                            Debug.logError("Not rendering content, WidgetContentWorker.contentWorker not found.", module);
                        }
                    }
                } else {
                    if (content.xmlEscape()) {
                        renderedContent = UtilFormatOut.encodeXmlValue(renderedContent);
                    }

                    writer.append(renderedContent);
                }

            } catch (GeneralException e) {
                String errMsg = "Error rendering included content with id [" + expandedContentId + "] : " + e.toString();
                Debug.logError(e, errMsg, module);
                //throw new RuntimeException(errMsg);
            } catch (IOException e2) {
                String errMsg = "Error rendering included content with id [" + expandedContentId + "] : " + e2.toString();
                Debug.logError(e2, errMsg, module);
                //throw new RuntimeException(errMsg);
            }
    }

    public void renderSubContentEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.SubContent content) throws IOException {

        String editMode = "Edit";
        String editRequest = content.getEditRequest(context);
        String editContainerStyle = content.getEditContainerStyle(context);
        String enableEditName = content.getEnableEditName(context);
        String enableEditValue = (String)context.get(enableEditName);
        String expandedContentId = content.getContentId(context);
        String expandedMapKey = content.getMapKey(context);
        if (editRequest != null && editRequest.toUpperCase().indexOf("IMAGE") > 0) {
            editMode += " Image";
        }
        if (UtilValidate.isNotEmpty(editRequest) && "true".equals(enableEditValue)) {
            HttpServletResponse response = (HttpServletResponse) context.get("response");
            HttpServletRequest request = (HttpServletRequest) context.get("request");
            if (request != null && response != null) {
                if (editRequest.indexOf("?") < 0)  editRequest += "?";
                else editRequest += "&";
                editRequest += "contentId=" + expandedContentId;
                if (UtilValidate.isNotEmpty(expandedMapKey)) {
                    editRequest += "&mapKey=" + expandedMapKey;
                }
                //HttpSession session = request.getSession();
                //GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
                /* don't know why this is here. might come to me later. -amb
                Delegator delegator = (Delegator)request.getAttribute("delegator");
                String contentIdTo = content.getContentId(context);
                String mapKey = content.getAssocName(context);
                GenericValue view = null;
                try {
                    view = ContentWorker.getSubContentCache(delegator, contentIdTo, mapKey, userLogin, null, UtilDateTime.nowTimestamp(), Boolean.valueOf(false), null);
                } catch (GenericEntityException e) {
                    throw new IOException("Originally a GenericEntityException. " + e.getMessage());
                }
                */
                ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
                RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
                writer.append("").append(editMode).append("");
            }
            if (UtilValidate.isNotEmpty(editContainerStyle)) {
                writer.append("
");
            }
            appendWhitespace(writer);
        }
    }

    public void renderPortalPageBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage) throws GeneralException, IOException {
        // TODO: not implemented
    }
    public void renderPortalPageEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage) throws GeneralException, IOException {
        // TODO: not implemented
    }
    public void renderPortalPageColumnBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPageColumn) throws GeneralException, IOException {
        // TODO: not implemented
    }
    public void renderPortalPageColumnEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPageColumn) throws GeneralException, IOException {
        // TODO: not implemented
    }
    public void renderPortalPagePortletBegin(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException {
        // TODO: not implemented
    }
    public void renderPortalPagePortletEnd(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException {
        // TODO: not implemented
    }
    public void renderPortalPagePortletBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException {
        // TODO: not implemented
    }

    @Override
    public void renderColumnContainer(Appendable writer, Map<String, Object> context, ColumnContainer columnContainer) throws IOException {
        // TODO: not implemented
    }
}


text:
<?php get_header(); ?>

	<?php /* Start loop */ ?>
	<?php while (have_posts()) : the_post(); ?>
		<article <?php post_class() ?> id="post-<?php the_ID(); ?>">

			<?php

				$orient = 'none';

				if ( has_post_thumbnail() ) {
					$post_thumbnail_id = get_post_thumbnail_id( $get_the_ID );
					$imgmeta = wp_get_attachment_metadata( $post_thumbnail_id );
					if ($imgmeta['width'] > $imgmeta['height']) {
						$orient = 'horizontal';
					} else {
						$orient = 'vertical';
					}
				}
			?>

			<header class="<?php echo $orient; ?>">
				<?php if ( has_post_thumbnail() ) { echo '
'; the_post_thumbnail('fd-lrg'); echo '
'; } ?>

<?php the_title(); ?>

<?php reverie_entry_meta(); ?>

						<?php the_content(); ?>

						<?php wp_link_pages(array('before' => '
' . __('Pages:', 'reverie'), 'after' => '
' )); ?>

<?php the_tags(); ?>

						<?php edit_post_link('Edit this Post'); ?>

						<?php echo get_avatar( get_the_author_meta('user_email'), 95 ); ?>

<?php the_author_posts_link(); ?>

<?php the_author_meta('description'); ?>

			<?php comments_template(); ?>

	<?php endwhile; // End the loop ?>

<! -- fixthis -->


text:
Responsive, privately hostable chat and IM software on node.js and mysql

* Private instant messaging
* Group chat rooms
* Profile images
* Image uploads / inline media in chats
* Full sized image views on click
* User presence status for when a user is active vs not on the app
* **Pluggable Identity** for easier integration with existing communities

Layout created with bootstrap.

Live demo at https://chat.peachat.io

Created and maintained by SlideWave, LLC - https://www.slidewave.com

![Screenshot](/screenshot.png?raw=true)
![Screenshot](/screenshot2.png?raw=true)

## Typical setup:

* Have a MySQL instance handy
* git clone https://github.com/SlideWave/peaChat.git
* npm install
* Go to the pchat directory and edit config.js for your environment specifying your mysql credentials
and if necessary the full local path to the upload directory (required when using certain init scripts)
* Run "node app.js setup" to initialize the database
* Start the app using an init script or "node bin/www"

## Plans:

* CDN Image support


text:
'use strict';

var util = require('util');
var stream = require('stream');

module.exports.createReadStream = function (object, options) {
  return new MultiStream (object, options);
};

var MultiStream = function (object, options) {
  if (object instanceof Buffer || typeof object === 'string') {
    options = options || {};
    stream.Readable.call(this, {
      highWaterMark: options.highWaterMark,
      encoding: options.encoding
    });
  } else {
    stream.Readable.call(this, { objectMode: true });
  }
  this._object = object;
};

util.inherits(MultiStream, stream.Readable);

MultiStream.prototype._read = function () {
  this.push(this._object);
  this._object = null;
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<SageTVPlugin>
	<Name>JavaFFmpegLibrary Windows x64</Name>
	<Identifier>JavaFFmpegLibraryWinx64</Identifier>
	<Description>JNI Wrapper library around FFmpeg library for 64 bit SageTV</Description>
	<Author>jvl711</Author>
	<OS>Windows</OS>
	<CreationDate>2020.05.01</CreationDate>
	<ModificationDate>2022.10.18</ModificationDate>
	<Version>0.6</Version>
	<PluginType>Library</PluginType>
	<Desktop>false</Desktop>
	<Webpage>https://github.com/jvl711/JavaFFmpegLibrary</Webpage>
	<Package>
        <PackageType>System</PackageType>
        <Location>https://github.com/jvl711/JavaFFmpegLibrary/releases/download/v0.6/JavaFFmpegLibraryWin64_v0.6.zip</Location>
        <MD5>bf20feb47afd08bbd2bdd7c01b0d7ad5</MD5>
    </Package>
</SageTVPlugin>


text:
"""
Defines two classes to support domain objects. Domain objects allow you to
model meta data in a more compact way.

Domain objects should always be inherited from C{DomainObject}. Then the required
properties should be defined on class level using C{DomainProperty}.

Here an example:
>>> class Author(DomainObject):
...    name = DomainProperty(StringType(), None, "Name", "This is the author name.")
...
...    @name.setValidate
...    def _validateName(self):
...        if self.name is None or len(self.name) == 0:
...            raise ValueError("Name should not be empty.")
...
... author = Author()
... author.name = "Pierre"
"""

import inspect

__version__ = "$Revision-Id:$"

class DomainProperty(property):
    """ Describes a property of a domain object.

    Properties defined in this way are persisted and can be further described by a
    documentation string, display name, and a default value. You can also provide a
    custom validation function using C{setValidate). The existing property types
    L{property_type<datafinder.core.configuration.properties.property_type>} can
    be used.
    """

    def __init__(self, type_, defaultValue=None, displayName="", docString=""):
        property.__init__(self, self._getter, self._setter)

        self.type = type_
        self.__doc__ = docString
        self.defaultValue = defaultValue
        self.displayName = displayName
        self._values = dict()
        self._validate = lambda _: None

    def validate(self, instance):
        """ Validates the given object.
        @raise ValueError: Indicates an invalid object.
        """

        self.type.validate(self._getter(instance))
        self._validate(instance)

    def setValidate(self, function):
        """ This method is intended to be used as method decorator.
        >>> @name.setValidate
        ... def _validateName(self):
        ...     pass

        The decorated method should just expect the domain
        property instance as argument. Invalid values should be
        indicated using C{ValueError}. The default validation method
        does nothing.
        """

        self._validate = function

    def _getter(self, instance):
        if id(instance) in self._values:
            return self._values[id(instance)]
        else:
            return self.defaultValue

    def _setter(self, instance, value):
        self._values[id(instance)] = value

    def __repr__(self):
        return "%s: %s\n%s" % (self.displayName, self.type.name, self.__doc__)

class DomainObject(object):
    """ Base class for all domain objects.
    @note: Domain object should be created using an empty constructor.
    """

    def validate(self):
        """ Indicates validation errors using C{ValueError}. """

        for instance, _, propertyDescriptor, value in self.walk():
            propertyDescriptor.validate(instance)
            if isinstance(value, DomainObject):
                value.validate()

    def walk(self, recursively=False):
        """ Returns a generator which allows walking through
        all defined domain properties.

        For every property the following information is returned:
        - The instance on which the property is defined.
        - The attribute name to which the property is bound.
        - The property descriptor.
        - The current value of the property.

        @param recursively: Indicates whether sub domain
            objects are processed as well. Default: C{False}
        @type recursively: C{bool}
        """

        processLater = list()
        for name, propertyDescriptor in inspect.getmembers(self.__class__):
            if isinstance(propertyDescriptor, DomainProperty):
                value = getattr(self, name)
                yield self, name, propertyDescriptor, value
                if isinstance(value, DomainObject) and recursively:
                    processLater.append(value)
        for theProperty in processLater:
            for propertyInfo in theProperty.walk(recursively):
                yield propertyInfo

    def __cmp__(self, other):
        """ Two instances are equal if all domain properties are equal. """

        for _, name, __, value in self.walk():
            try:
                if cmp(getattr(other, name), value) != 0:
                    return 1
            except AttributeError:
                return 1
        return 0

    def __hash__(self):
        hashValue = list()
        for _, __, ___, value in self.walk():
            hashValue.append(value)
        return hash(tuple(hashValue))

    def __repr__(self):
        result = ""
        for _, name, __, value in self.walk():
            result += "%s: '%s' " % (name, str(value))
        return result.strip()


text:
package org.dspace.versioning;

import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.*;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.event.Consumer;
import org.dspace.event.Event;
import org.dspace.identifier.DOIIdentifierProvider;
import org.dspace.identifier.IdentifierException;
import org.dspace.identifier.IdentifierService;
import org.dspace.utils.DSpace;

import java.sql.SQLException;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: fabio.bolognesi
 * Date: Jun 16, 2011
 * Time: 1:26:40 PM
 * To change this template use File | Settings | File Templates.
 */
public class VersioningConsumer implements Consumer {
    /**
     * log4j logger
     */
    private static Logger log = Logger.getLogger(VersioningConsumer.class);

    // collect Items, Collections, Communities that need indexing
    private Set<DSpaceObject> objectsToUpdate = null;

    // handles to delete since IDs are not useful by now.
    private Set<String> handlesToDelete = null;

    public void initialize() throws Exception {
        // No-op

    }

    public void finish(Context ctx) throws Exception {
        // No-op
    }

    public void end(Context ctx) throws Exception {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    //public void update(Context ctx, Event event) throws Exception{

    public void consume(Context ctx, Event event) throws Exception {
        int st = event.getSubjectType();
        int et = event.getEventType();

        try {
            ctx = new Context();
            ctx.turnOffAuthorisationSystem();

            switch (st) {

                case Constants.ITEM: {
                    Item item = (Item) event.getSubject(ctx);
                    VersionHistory history = retrieveVersionHistory(ctx, item);

                    if(history!=null && history.size()>0){
                        if (et == Event.INSTALL) {
                            moveCanonicalToPointToTheNewVersion(ctx, item);
                            setArhcivedFalsePreviousVersion(ctx, item, history);
                        }
                        break;
                    }
                }

                case Constants.BUNDLE: {
                    if (et == Event.ADD || et == Event.REMOVE) {
                        Bundle b = (Bundle) event.getSubject(ctx);
                        Item item = (Item) b.getParentObject();
                        if(item.isArchived()){
                            upgradeDOIDataFile(ctx, item);
                        }
                    }
                }
                break;
            }
            ctx.complete();
        }
        catch (Exception e) {
            ctx.abort();
        }
    }

    private void upgradeDOIDataFile(Context ctx, Item item) throws AuthorizeException, SQLException, IdentifierException
    {
        IdentifierService identifierService = new DSpace().getSingletonService(IdentifierService.class);
        identifierService.register(ctx, item);
    }

    private void setArhcivedFalsePreviousVersion(Context ctx, Item item, VersionHistory history) throws AuthorizeException, SQLException
    {
        setArchivedFalse(ctx, item, history);
        Item[] items = org.dspace.workflow.DryadWorkflowUtils.getDataFiles(ctx, item);
        for (Item datafile : items) {
            setArchivedFalse(ctx, datafile, history);
        }
    }

    private void moveCanonicalToPointToTheNewVersion(Context ctx, Item item) throws IdentifierException
    {
        DOIIdentifierProvider dis = new DSpace().getSingletonService(DOIIdentifierProvider.class);
        dis.moveCanonical(ctx, item);
    }

    private static org.dspace.versioning.VersionHistory retrieveVersionHistory(Context c, Item item) {
        VersioningService versioningService = new DSpace().getSingletonService(VersioningService.class);
        org.dspace.versioning.VersionHistory history = versioningService.findVersionHistory(c, item.getID());

        return history;
    }

    private void setArchivedFalse(Context ctx, Item item, VersionHistory history) throws AuthorizeException, SQLException {

        if (history != null) {
            Version latest = history.getLatestVersion();
            Version previous = history.getPrevious(latest);
            previous.getItem().setArchived(false);
            previous.getItem().update();
        }
    }

}