text:
package at.irian.ankor.fx.binding.value;

import at.irian.ankor.change.Change;
import at.irian.ankor.change.ChangeEventListener;
import at.irian.ankor.fx.binding.cache.FxCacheSupport;
import at.irian.ankor.ref.Ref;
import at.irian.ankor.ref.util.RefList;
import com.sun.javafx.collections.ListListenerHelper;
import javafx.beans.InvalidationListener;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.util.Callback;

import java.util.Arrays;
import java.util.Collection;

/**
 * A JavaFX ObservableList backed by a Ankor Ref that references a List.
 * The list items of this observable list are directly retrieved from the underlying "collection" Ref.
 * Listeners of this observable get notified whenever the referenced list's content changes.
 *
 * @author Manfred Geiler
 */
public class ObservableListRef<E> extends RefList<E> implements ObservableList<E> {
    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(ObservableListRef.class);

    private final FxListChangeHelper<E> changeHelper;
    private final ChangeEventListener changeEventListener;

    private ListListenerHelper<E> listenerHelper = null;

    protected ObservableListRef(Ref ref) {
        super(ref);
        this.changeHelper = new FxListChangeHelper<>(this);
        this.changeEventListener = new ObservableChangeEventListener(ref, this) {
            @Override
            protected void handleChange(Ref changedProperty, Change change) {
                if (changedProperty.equals(ObservableListRef.this.listRef)) {
                    switch (change.getType()) {
                        case value:
                            // list itself was replaced --> ignore here, handled by the wrapping ObservableValue
                            break;
                        case insert:
                        case delete:
                        case replace:
                            ListListenerHelper.fireValueChangedEvent(listenerHelper, changeHelper.toFxChange(change));
                            break;
                        default:
                            throw new IllegalArgumentException("Unknown change type " + change.getType());
                    }
                }
            }
        };
        this.listRef.context().modelSession().getEventListeners().add(this.changeEventListener);
    }

    public static <T> ObservableList<T> createObservableList(Ref ref) {
        return FxCacheSupport.getBindingCache(ref)
                             .getObservableList(ref, null, new Callback<Ref, ObservableList<T>>() {
                                 @Override
                                 public ObservableList<T> call(Ref ref) {
                                     LOG.debug("Creating ObservableList for {}", ref);
                                     return new ObservableListRef<>(ref);
                                 }
                             });
    }

    @Override
    public void addListener(InvalidationListener invalidationlistener) {
        listenerHelper = ListListenerHelper.addListener(listenerHelper, invalidationlistener);
    }

    @Override
    public void removeListener(InvalidationListener invalidationlistener) {
        listenerHelper = ListListenerHelper.removeListener(listenerHelper, invalidationlistener);
    }

    @Override
    public void addListener(ListChangeListener<? super E> listChangeListener) {
        listenerHelper = ListListenerHelper.addListener(listenerHelper, listChangeListener);
    }

    @Override
    public void removeListener(ListChangeListener<? super E> listChangeListener) {
        listenerHelper = ListListenerHelper.removeListener(listenerHelper, listChangeListener);
    }

    // ObservableList extensions

    @SuppressWarnings("unchecked")
    @Override
    public boolean addAll(E... es) {
        boolean added = false;
        for (E e : es) {
            added |= add(e);
        }
        return added;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean setAll(E... es) {
        return setAll(Arrays.asList(es));
    }

    @Override
    public boolean setAll(Collection<? extends E> ts) {
        // todo optimize
        clear();
        return addAll(ts);
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean removeAll(E... es) {
        boolean removed = false;
        for (E e : es) {
            removed |= remove(e);
        }
        return removed;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean retainAll(E... es) {
        return retainAll(Arrays.asList(es));
    }

    @Override
    public void remove(int from, int to) {
        // todo  test this
        for (int i = from, len = size(); i < to && i < len; i++) {
            remove(from);
        }
    }

    // misc

    protected void finalize() throws Throwable {
        this.listRef.context().modelSession().getEventListeners().remove(this.changeEventListener);
        super.finalize();
    }

}


text:
package sigmastate.helpers

import org.ergoplatform.SigmaConstants.ScriptCostLimit
import org.ergoplatform._
import org.ergoplatform.validation.ValidationRules.{CheckCalcFunc, CheckCostFunc, CheckSerializableTypeCode}
import org.ergoplatform.validation.{ValidationException, ValidationSpecification}
import org.scalacheck.Arbitrary.arbByte
import org.scalacheck.Gen
import org.scalatest.prop.{GeneratorDrivenPropertyChecks, PropertyChecks}
import org.scalatest.{Assertion, Matchers, PropSpec}
import scalan.util.BenchmarkUtil
import scalan.{RType, TestContexts, TestUtils}
import scorex.crypto.hash.Blake2b256
import sigma.types.IsPrimView
import sigmastate.Values.{Constant, ErgoTree, GroupElementConstant, SValue, SigmaBoolean, SigmaPropValue, Value}
import sigmastate.eval.{CompiletimeCosting, Evaluation, IRContext, _}
import sigmastate.helpers.TestingHelpers._
import sigmastate.interpreter.ContextExtension.VarBinding
import sigmastate.interpreter.CryptoConstants.EcPointType
import sigmastate.interpreter.ErgoTreeEvaluator.DefaultProfiler
import sigmastate.interpreter.Interpreter.{ScriptEnv, ScriptNameProp}
import sigmastate.interpreter.{CryptoConstants, Interpreter, _}
import sigmastate.lang.{CompilerSettings, SigmaCompiler, Terms}
import sigmastate.serialization.SigmaSerializer
import sigmastate.utils.Helpers._
import sigmastate.{JitCost, SGroupElement, SOption, SType, TestsBase}
import special.sigma

import scala.language.implicitConversions
import scala.reflect.ClassTag
import scala.util.DynamicVariable

trait SigmaTestingCommons extends PropSpec
  with PropertyChecks
  with GeneratorDrivenPropertyChecks
  with Matchers with TestUtils with TestContexts with ValidationSpecification
  with NegativeTesting
  with TestsBase {

  def fakeSelf: ErgoBox = createBox(0, TrueTree)

  def fakeContext: ErgoLikeContext =
    ErgoLikeContextTesting.dummy(fakeSelf, activatedVersionInTests)
        .withErgoTreeVersion(ergoTreeVersionInTests)

  //fake message, in a real-life a message is to be derived from a spending transaction
  val fakeMessage = Blake2b256("Hello World")

  implicit def grElemConvert(leafConstant: GroupElementConstant): EcPointType =
    SigmaDsl.toECPoint(leafConstant.value).asInstanceOf[EcPointType]

  implicit def grLeafConvert(elem: CryptoConstants.EcPointType): Value[SGroupElement.type] = GroupElementConstant(elem)

  class TestingIRContext extends TestContext with IRContext with CompiletimeCosting {
    override def onCostingResult[T](env: ScriptEnv, tree: SValue, res: RCostingResultEx[T]): Unit = {
      env.get(ScriptNameProp) match {
        case Some(name: String) if saveGraphsInFile =>
          emit(name, Pair(res.calcF, res.costF))
        case _ =>
      }
    }

    override def onEstimatedCost[T](env: ScriptEnv,
                                    tree: SValue,
                                    result: RCostingResultEx[T],
                                    ctx: special.sigma.Context,
                                    estimatedCost: Int): Unit = {
      if (outputEstimatedCost) {
        env.get(Interpreter.ScriptNameProp) match {
          case Some(name: String) =>
            println(s"Cost of $name = $estimatedCost")
          case _ =>
        }
      }
    }

    override private[sigmastate] def onResult[T](env: ScriptEnv,
                                     tree: SValue,
                                     result: RCostingResultEx[T],
                                     ctx: sigma.Context,
                                     estimatedCost: Int,
                                     calcCtx: sigma.Context,
                                     executedResult: sigma.SigmaProp,
                                     executionTime: Long): Unit = {
      if (outputComputedResults) {
        val name = env.get(Interpreter.ScriptNameProp).getOrElse("")
        println(s"ScriptName: $name, EstimatedCost: $estimatedCost, ExecutionTime: $executionTime")
      }
    }
  }

  private def fromPrimView[A](in: A) = {
    in match {
      case IsPrimView(v) => v
      case _ => in
    }
  }

  case class CompiledFunc[A,B]
    (script: String, bindings: Seq[VarBinding], expr: SValue, compiledTree: SValue, func: A => (B, CostDetails))
    (implicit val tA: RType[A], val tB: RType[B]) extends Function1[A, (B, CostDetails)] {
    override def apply(x: A): (B, CostDetails) = func(x)
  }

  /** The same operations are executed as part of Interpreter.verify() */
  def getCostingResult(env: ScriptEnv, exp: SValue)(implicit IR: IRContext): IR.RCostingResultEx[Any] = {
    val costingRes = IR.doCostingEx(env, exp, true)
    val costF = costingRes.costF
    CheckCostFunc(IR)(IR.asRep[Any => Int](costF))

    val calcF = costingRes.calcF
    CheckCalcFunc(IR)(calcF)
    costingRes
  }

  /** This value is used as Context.initCost value. The default value is used for most
    * test vectors.
    * Change this value using `withValue` method to test behavior with non-default
    * initial cost.
    */
  protected val initialCostInTests = new DynamicVariable[Long](0)

  def createContexts[A](in: A, bindings: Seq[VarBinding])(implicit tA: RType[A]) = {
    val x = fromPrimView(in)
    val tpeA = Evaluation.rtypeToSType(tA)
    in match {
      case ctx: CostingDataContext =>
        // the context is passed as function argument (this is for testing only)
        // This is to overcome non-functional semantics of context operations
        // (such as Inputs, Height, etc which don't have arguments and refer to the
        // context implicitly).
        // These context operations are introduced by buildTree frontend function
        // (ctx.HEIGHT method call compiled to Height IR node)
        // -------
        // We add ctx as it's own variable with id = 1
        val ctxVar = Extensions.toAnyValue[special.sigma.Context](ctx)(special.sigma.ContextRType)
        val newVars = if (ctx.vars.length < 2) {
          val vars = ctx.vars.toArray
          val buf = new Array[special.sigma.AnyValue](2)
          Array.copy(vars, 0, buf, 0, vars.length)
          buf(1) = ctxVar
          CostingSigmaDslBuilder.Colls.fromArray(buf)
        } else {
          ctx.vars.updated(1, ctxVar)
        }
        val calcCtx = ctx.copy(vars = newVars)
        val costCtx = calcCtx.copy(isCost = true)
        (costCtx, calcCtx)
      case _ =>
        val box = createBox(0, TrueTree)

        // make sure we are doing tests with the box with is actually serializable
        try roundTripTest(box)(ErgoBox.sigmaSerializer)
        catch {
          case ValidationException(_, r: CheckSerializableTypeCode.type, Seq(SOption.OptionTypeCode), _) =>
          // ignore the problem with Option serialization, but test all the other cases
        }

        val ergoCtx = ErgoLikeContextTesting.dummy(box, activatedVersionInTests)
          .withErgoTreeVersion(ergoTreeVersionInTests)
          .withBindings(1.toByte -> Constant[SType](x.asInstanceOf[SType#WrappedType], tpeA))
          .withBindings(bindings: _*)
        val calcCtx = ergoCtx.toSigmaContext(isCost = false).asInstanceOf[CostingDataContext]
        val costCtx = calcCtx.copy(isCost = true)
        (costCtx, calcCtx)
    }
  }

  def compileTestScript[A]
      (env: ScriptEnv, funcScript: String)
      (implicit tA: RType[A],
                IR: IRContext,
                compilerSettings: CompilerSettings): SValue = {
    val code =
      s"""{
        |  val func = $funcScript
        |  val res = func(getVar[${tA.name}](1).get)
        |  res
        |}
      """.stripMargin

    // The following ops are performed by frontend
    // typecheck, create graphs, compile to Tree
    // The resulting tree should be serializable
    val compiledTree = {
      val compiler = SigmaCompiler(compilerSettings)
      val internalProp = compiler.typecheck(env, code)
      val costingRes = getCostingResult(env, internalProp)
      val calcF = costingRes.calcF
      val tree = IR.buildTree(calcF)
      checkSerializationRoundTrip(tree)
      tree
    }
    compiledTree
  }

  /** Returns a Scala function which is equivalent to the given function script.
    * The script is embedded into valid ErgoScript which is then compiled to
    * [[sigmastate.Values.Value]] tree.
    * Limitations:
    * 1) DeserializeContext, ConstantPlaceholder is not supported
    * @param funcScript source code of the function
    * @param bindings additional context variables
    */
  def funcFromExpr[A: RType, B: RType]
      (funcScript: String, expr: SValue, bindings: VarBinding*)
      (implicit IR: IRContext,
                compilerSettings: CompilerSettings): CompiledFunc[A, B] = {
    import IR._
    import IR.Context._
    val tA = RType[A]
    val env = Interpreter.emptyEnv

    // The following is done as part of Interpreter.verify()
    val (costF, valueFun) = {
      val costingRes = getCostingResult(env, expr)
      val calcF = costingRes.calcF
      val tree = IR.buildTree(calcF)

      // sanity check that buildTree is reverse to buildGraph (see doCostingEx)
      if (tA != special.sigma.ContextRType) {
        if (tree != expr) {
          println(s"Result of buildTree:")
          val prettyTree = SigmaPPrint(tree, height = 150)
          println(prettyTree)

          println(s"compiledTree:")
          val prettyCompiledTree = SigmaPPrint(expr, height = 150)
          println(prettyCompiledTree)

          assert(prettyTree.plainText == prettyCompiledTree.plainText, "Failed sanity check that buildTree is reverse to buildGraph")
        }
      }

      val lA = Liftables.asLiftable[SContext, IR.Context](calcF.elem.eDom.liftable)
      val lB = Liftables.asLiftable[Any, Any](calcF.elem.eRange.liftable)
      val vf = IR.compile[SContext, Any, IR.Context, Any](IR.getDataEnv, calcF)(lA, lB)
      (costingRes.costF, vf)
    }

    val f = (in: A) => {
      implicit val cA: ClassTag[A] = tA.classTag
      val (costingCtx, sigmaCtx) = createContexts(in, bindings)

      val estimatedCost = IR.checkCostWithContext(costingCtx, costF, ScriptCostLimit.value, initialCostInTests.value).getOrThrow

      val (res, _) = valueFun(sigmaCtx)
      (res.asInstanceOf[B], GivenCost(JitCost(estimatedCost)))
    }
    val Terms.Apply(funcVal, _) = expr.asInstanceOf[SValue]
    CompiledFunc(funcScript, bindings, funcVal, expr, f)
  }

  /** Returns a Scala function which is equivalent to the given function script.
    * The script is embedded into valid ErgoScript which is then compiled to
    * [[sigmastate.Values.Value]] tree.
    * Limitations:
    * 1) DeserializeContext, ConstantPlaceholder is not supported
    * @param funcScript source code of the function
    * @param bindings additional context variables
    */
  def func[A: RType, B: RType]
      (funcScript: String, bindings: VarBinding*)
      (implicit IR: IRContext,
                compilerSettings: CompilerSettings): CompiledFunc[A, B] = {
    val env = Interpreter.emptyEnv
    val compiledTree = compileTestScript[A](env, funcScript)
    funcFromExpr[A, B](funcScript, compiledTree, bindings:_*)
  }

  def evalSettings = ErgoTreeEvaluator.DefaultEvalSettings

  def printCostDetails(script: String, details: CostDetails) = {
    val traceLines = SigmaPPrint(details, height = 550, width = 150)
    println(
      s"""------------------------
        |Script: $script
        |$traceLines
        |""".stripMargin)
  }

  def funcJitFromExpr[A: RType, B: RType]
      (funcScript: String, expr: SValue, bindings: VarBinding*)
      (implicit IR: IRContext,
                evalSettings: EvalSettings,
                compilerSettings: CompilerSettings): CompiledFunc[A, B] = {
    val tA = RType[A]
    val f = (in: A) => {
      implicit val cA: ClassTag[A] = tA.classTag
      val (_, sigmaCtx) = createContexts(in, bindings)
      val accumulator = new CostAccumulator(
        initialCost = JitCost(0),
        costLimit = Some(JitCost.fromBlockCost(ScriptCostLimit.value)))
      val evaluator = new ErgoTreeEvaluator(
        context = sigmaCtx,
        constants = ErgoTree.EmptyConstants,
        coster = accumulator, evalSettings.profilerOpt.getOrElse(DefaultProfiler), evalSettings)

      val (res, actualTime) = BenchmarkUtil.measureTimeNano(
        evaluator.evalWithCost[B](ErgoTreeEvaluator.EmptyDataEnv, expr))
      val costDetails = if (evalSettings.costTracingEnabled) {
        val trace: Seq[CostItem] = evaluator.getCostTrace()
        val costDetails = TracedCost(trace, Some(actualTime))
        assert(res.cost == costDetails.cost)
        costDetails
      } else
        GivenCost(res.cost, Some(actualTime))

      if (evalSettings.isMeasureScriptTime) {
        evaluator.profiler.addJitEstimation(funcScript, res.cost, actualTime)
      }

      if (evalSettings.isLogEnabled) {
        printCostDetails(funcScript, costDetails)
      }
      (res.value, costDetails)
    }
    val Terms.Apply(funcVal, _) = expr.asInstanceOf[SValue]
    CompiledFunc(funcScript, bindings, funcVal, expr, f)
  }

  def funcJit[A: RType, B: RType]
      (funcScript: String, bindings: VarBinding*)
      (implicit IR: IRContext,
                evalSettings: EvalSettings,
                compilerSettings: CompilerSettings): CompiledFunc[A, B] = {
    val compiledTree = compileTestScript[A](Interpreter.emptyEnv, funcScript)
    funcJitFromExpr(funcScript, compiledTree, bindings:_*)
  }

  /** Creates a specialized (faster) version which can be used to benchmark performance of
   * various scripts. */
  def funcJitFast[A: RType, B: RType]
      (funcScript: String, bindings: VarBinding*)
      (implicit IR: IRContext,
                evalSettings: EvalSettings,
                compilerSettings: CompilerSettings): CompiledFunc[A, B] = {
    val tA = RType[A]
    val compiledTree = compileTestScript[A](Interpreter.emptyEnv, funcScript)
    implicit val cA: ClassTag[A] = tA.classTag
    val tpeA = Evaluation.rtypeToSType(tA)
    val ergoCtxTemp = ErgoLikeContextTesting.dummy(
      createBox(0, TrueTree), activatedVersionInTests)
        .withErgoTreeVersion(ergoTreeVersionInTests)
        .withBindings(bindings: _*)

    val f = (in: A) => {
      val x = fromPrimView(in)
      val ergoCtx = ergoCtxTemp
          .withBindings(1.toByte -> Constant[SType](x.asInstanceOf[SType#WrappedType], tpeA))
      val sigmaCtx = ergoCtx.toSigmaContext(isCost = false).asInstanceOf[CostingDataContext]

      val accumulator = new CostAccumulator(
        initialCost = JitCost(0),
        costLimit = Some(JitCost.fromBlockCost(ScriptCostLimit.value)))
      val evaluator = new ErgoTreeEvaluator(
        context = sigmaCtx,
        constants = ErgoTree.EmptyConstants,
        coster = accumulator, DefaultProfiler, evalSettings)

      val (res, actualTime) = BenchmarkUtil.measureTimeNano(
        evaluator.evalWithCost[B](ErgoTreeEvaluator.EmptyDataEnv, compiledTree))
      (res.value, GivenCost(res.cost, Some(actualTime)))
    }
    val Terms.Apply(funcVal, _) = compiledTree.asInstanceOf[SValue]
    CompiledFunc(funcScript, bindings, funcVal, compiledTree, f)
  }

  protected def roundTripTest[T](v: T)(implicit serializer: SigmaSerializer[T, T]): Assertion = {
    // using default sigma reader/writer
    val bytes = serializer.toBytes(v)
    bytes.nonEmpty shouldBe true
    val r = SigmaSerializer.startReader(bytes)
    val positionLimitBefore = r.positionLimit
    serializer.parse(r) shouldBe v
    r.positionLimit shouldBe positionLimitBefore
  }

  protected def roundTripTestWithPos[T](v: T)(implicit serializer: SigmaSerializer[T, T]): Assertion = {
    val randomBytesCount = Gen.chooseNum(1, 20).sample.get
    val randomBytes = Gen.listOfN(randomBytesCount, arbByte.arbitrary).sample.get.toArray
    val bytes = serializer.toBytes(v)
    serializer.parse(SigmaSerializer.startReader(bytes)) shouldBe v
    serializer.parse(SigmaSerializer.startReader(randomBytes ++ bytes, randomBytesCount)) shouldBe v
  }

  def testReduce(I: Interpreter)(ctx: I.CTX, prop: SigmaPropValue): SigmaBoolean = {
    val ergoTree = ErgoTree.fromProposition(ergoTreeHeaderInTests, prop)
    I.fullReduction(ergoTree, ctx).value
  }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Choccybiccy\HumanApi;

use ArrayIterator;
use Countable;
use IteratorAggregate;
use Traversable;

/**
 * Class Collection
 * @package Choccybiccy\HumanApi
 */
class Collection implements Countable, IteratorAggregate
{

    /**
     * @var array
     */
    protected $data = array();

    /**
     * Add to collection
     *
     * @param Model $model
     */
    public function add(Model $model)
    {
        $this->data[] = $model;
    }

    /**
     * Collection count
     *
     * @return int|void
     */
    public function count()
    {
        return count($this->data);
    }

    /**
     * Get current
     *
     * @return Model
     */
    public function current()
    {
        return $this->getIterator()->current();
    }

    /**
     * Get iterator
     *
     * @return ArrayIterator|Traversable
     */
    public function getIterator()
    {
        return new ArrayIterator($this->data);
    }
}


text:
namespace Ui {
class Window;
}

class Window : public QWidget {
    Q_OBJECT

    public:
    explicit Window (QWidget* parent = 0);
    ~Window ();

    public slots:
    void loadButton_clicked ();
    void scaleSlider_valueChanged (int new_value);
    void posXSlider_valueChanged (int new_value);
    void posYSlider_valueChanged (int new_value);
    void rotXSlider_valueChanged (int new_value);
    void rotYSlider_valueChanged (int new_value);
    void rotZSlider_valueChanged (int new_value);

    protected:
    void keyPressEvent (QKeyEvent* event);

    private:
    void angle_to_matrix (float mat[16], float angle, float x, float y, float z);
    Ui::Window* ui;
};

#endif // WINDOW_H


text:
@interface ASFTableViewCell : UITableViewCell

@property (nonatomic, retain) NSObject *rowId;
@property (nonatomic, assign) NSUInteger minHeight;

- (void)setColumns:(NSArray *)aArr Options:(NSDictionary *)aOptions IsInnerRow:(BOOL)isInnerRow;

@end


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>GraphReaderIF (cloudsim 3.0.3 API)</title>
<meta name="date" content="2013-05-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.cloudbus.cloudsim.network

Interface GraphReaderIF

All Known Implementing Classes:

GraphReaderBrite

public interface GraphReaderIF

This interface abstracts an reader for different graph-file-formats

Since:

CloudSim Toolkit 1.0

Author:

Thomas Hohnstein

Method Summary

Methods

Modifier and Type
Method and Description

TopologicalGraph
readGraphFile(String filename)

this method just reads the file and creates an TopologicalGraph object

Method Detail

readGraphFile

TopologicalGraph readGraphFile(String filename)
                               throws IOException

this method just reads the file and creates an TopologicalGraph object

Parameters:

filename - name of the file to read

Returns:

created TopologicalGraph

Throws:

IOException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2013 The Cloud Computing and Distributed Systems (CLOUDS) Laboratory, The University of Melbourne. All Rights Reserved.


text:
namespace com { namespace amazonaws { namespace kinesis { namespace video {

class ProducerApiTest : public ProducerClientTestBase {
};

TEST_F(ProducerApiTest, fileLoggerCallbackApiTest)
{
    PClientCallbacks pClientCallbacks = NULL;
    PCHAR testLogDir = ((PCHAR) "/tmp");
    CHAR longPath[MAX_PATH_LEN + 2];

    MEMSET(longPath, 0x01, MAX_PATH_LEN + 2);
    longPath[MAX_PATH_LEN + 1] = '\0';
    EXPECT_EQ(STATUS_SUCCESS, createAbstractDefaultCallbacksProvider(TEST_DEFAULT_CHAIN_COUNT,
                                                                     API_CALL_CACHE_TYPE_NONE,
                                                                     TEST_CACHING_ENDPOINT_PERIOD,
                                                                     TEST_DEFAULT_REGION,
                                                                     TEST_CONTROL_PLANE_URI,
                                                                     EMPTY_STRING,
                                                                     NULL,
                                                                     TEST_USER_AGENT,
                                                                     &pClientCallbacks));

    EXPECT_EQ(STATUS_NULL_ARG, addFileLoggerPlatformCallbacksProvider(NULL, 10 * 1024, 10, testLogDir, FALSE));
    EXPECT_EQ(STATUS_INVALID_ARG, addFileLoggerPlatformCallbacksProvider(pClientCallbacks, MIN_FILE_LOGGER_STRING_BUFFER_SIZE - 1, 10, testLogDir, FALSE));
    EXPECT_EQ(STATUS_INVALID_ARG, addFileLoggerPlatformCallbacksProvider(pClientCallbacks, MAX_FILE_LOGGER_STRING_BUFFER_SIZE + 1, 10, testLogDir, FALSE));
    EXPECT_EQ(STATUS_INVALID_ARG, addFileLoggerPlatformCallbacksProvider(pClientCallbacks, MIN_FILE_LOGGER_STRING_BUFFER_SIZE, MAX_FILE_LOGGER_LOG_FILE_COUNT + 1, testLogDir, FALSE));
    EXPECT_EQ(STATUS_INVALID_ARG, addFileLoggerPlatformCallbacksProvider(pClientCallbacks, MIN_FILE_LOGGER_STRING_BUFFER_SIZE, 0, testLogDir, FALSE));
    EXPECT_EQ(STATUS_PATH_TOO_LONG, addFileLoggerPlatformCallbacksProvider(pClientCallbacks, MIN_FILE_LOGGER_STRING_BUFFER_SIZE, 10, longPath, FALSE));

    EXPECT_EQ(STATUS_SUCCESS, freeCallbacksProvider(&pClientCallbacks));
    EXPECT_EQ(STATUS_SUCCESS, freeCallbacksProvider(&pClientCallbacks)); // idempotent
}

TEST_F(ProducerApiTest, fileLoggerApiTest)
{
    PCHAR testLogDir = ((PCHAR) "/tmp");
    CHAR longPath[MAX_PATH_LEN + 2];

    MEMSET(longPath, 0x01, MAX_PATH_LEN + 2);
    longPath[MAX_PATH_LEN + 1] = '\0';

    EXPECT_EQ(STATUS_INVALID_ARG, createFileLogger(MIN_FILE_LOGGER_STRING_BUFFER_SIZE - 1, 10, testLogDir, FALSE, FALSE, NULL));
    EXPECT_EQ(STATUS_INVALID_ARG, createFileLogger(MAX_FILE_LOGGER_STRING_BUFFER_SIZE + 1, 10, testLogDir, FALSE, FALSE, NULL));
    EXPECT_EQ(STATUS_INVALID_ARG, createFileLogger(MIN_FILE_LOGGER_STRING_BUFFER_SIZE, MAX_FILE_LOGGER_LOG_FILE_COUNT + 1, testLogDir, FALSE, FALSE, NULL));
    EXPECT_EQ(STATUS_INVALID_ARG, createFileLogger(MIN_FILE_LOGGER_STRING_BUFFER_SIZE, 0, testLogDir, FALSE, FALSE, NULL));
    EXPECT_EQ(STATUS_PATH_TOO_LONG, createFileLogger(MIN_FILE_LOGGER_STRING_BUFFER_SIZE, 10, longPath, FALSE, FALSE, NULL));
}

}
}
}
}


text:
import java.io.*;
import java.util.*;

class UnsupportedFeatures {
  void m(String... args) throws Exception {
    for (String s : args) { System.out.println(s); }

    List<String> list =
      new ArrayList<error descr="Diamond types are not supported at language level '6'"><></error>();

    for (String s : list) {}
    Arrays.asList("");
    Boolean b = true;
    boolean b1 = Boolean.TRUE;

    try { Reader r = new FileReader("/dev/null"); }
    catch (<error descr="Multi-catches are not supported at language level '6'">FileNotFoundException | IOException e</error>) { e.printStackTrace(); }

    try <error descr="Try-with-resources are not supported at language level '6'">(Reader r = new FileReader("/dev/null"))</error> { }

    I i1 = <error descr="Method references are not supported at language level '6'">UnsupportedFeatures::m</error>;
    I i2 = <error descr="Lambda expressions are not supported at language level '6'">() -> { }</error>;

    switch (<error descr="Incompatible types. Found: 'java.lang.String', required: 'byte, char, short or int'">list.get(0)</error>) {
      case "foo": break;
    }

    switch (list.size()) {
      <error descr="Enhanced 'switch' blocks are not supported at language level '6'">case 0 -> throw new IllegalStateException("empty list");</error>
      default -> System.out.println("it's okay");
    }
  }

  void f(<error descr="Receiver parameters are not supported at language level '6'">Object this</error>) { }

  interface I {
    <error descr="Extension methods are not supported at language level '6'">default void m() { }</error>
    <error descr="Extension methods are not supported at language level '6'">static void m() { }</error>
  }
}


text:
package cz.cuni.mff.d3s.jdeeco.analysis.example.custom;

import cz.cuni.mff.d3s.deeco.analysis.def.Interval;
import cz.cuni.mff.d3s.deeco.analysis.interval.impl.StringInterval;

public class BooleanInterval extends Interval<Boolean> {

	public BooleanInterval(Boolean upperBound, Boolean lowerBound) {
		super(upperBound, lowerBound);
	}

	@Override
	public Interval<String> getStringInterval() {
		return new StringInterval(upperBound.toString(), lowerBound.toString());
	}

}


text:
#region Header
//////////////////////////////////////////////////////////////////////////////
//The MIT License (MIT)

//Copyright (c) 2013 Dirk Bretthauer

//Permission is hereby granted, free of charge, to any person obtaining a copy of
//this software and associated documentation files (the "Software"), to deal in
//the Software without restriction, including without limitation the rights to
//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//the Software, and to permit persons to whom the Software is furnished to do so,
//subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////
#endregion

using System;
using System.Linq;

namespace CChessCore.Pgn
{
    internal class TagSectionState : PgnParserState
    {
        private PgnGame _current;

        public TagSectionState(PgnParserStatemachine reader)
            : base(reader)
        {
        }

        public override void OnEnter(PgnMove currentMove)
        {
            base.OnEnter(currentMove);
        }

        public override void OnExit()
        {
            _current.AddTag(PgnTag.Parse(new string(_stateBuffer.ToArray())));
        }

        protected override PgnParseResult DoParse(char current, char next, PgnGame currentGame)
        {
            _current = currentGame;
            _stateBuffer.Add(current);

            return PgnParseResult.None;
        }
    }
}


text:
<?php

namespace PragmaRX\Tracker\Data\Repositories;

class EventLog extends Repository {

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="css/main.css">
  <title>JavaScript Basics</title>

Random Number Generator


text:
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;

using System;
using System.Threading.Tasks;
using Windows.Devices.Sensors;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.Globalization.DateTimeFormatting;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Windows.Globalization;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace PedometerCS
{
    /// <summary>
    /// History Page that gets loaded when 'History' scenario is selected.
    /// </summary>
    public sealed partial class Scenario2_History : Page
    {
        MainPage rootPage = MainPage.Current;

        public Scenario2_History()
        {
            this.InitializeComponent();
            historyRecords = new ObservableCollection<HistoryRecord>();
            historyRecordsList.DataContext = historyRecords;
            rootPage.NotifyUser("Choose time span for history", NotifyType.StatusMessage);
        }

        private void AllHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // Collapse SpanPicker - SpanPicker will not be created yet the first time the page is loading
            if (SpanPicker != null)
            {
                SpanPicker.Visibility = Visibility.Collapsed;
            }
            getAllHistory = true;
            rootPage.NotifyUser("This will retrieve all the step count history available on the system", NotifyType.StatusMessage);
        }

        private void SpecificHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            SpanPicker.Visibility = Visibility.Visible;
            getAllHistory = false;
            rootPage.NotifyUser("This will retrieve all the step count history for the selected time span", NotifyType.StatusMessage);
        }

        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            IReadOnlyList<PedometerReading> historyReadings = null;
            DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");

            // Disable subsequent history retrieval while the async operation is in progress
            GetHistory.IsEnabled = false;

            // clear previous content being displayed
            historyRecords.Clear();

            try
            {
                if (getAllHistory)
                {
                    DateTime dt = DateTime.FromFileTimeUtc(0);
                    DateTimeOffset fromBeginning = new DateTimeOffset(dt);
                    rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                    historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                }
                else
                {
                    String notificationString = "Retrieving history from: ";
                    Calendar calendar = new Calendar();
                    calendar.ChangeClock("24HourClock");

                    // DateTime picker will also include hour, minute and seconds from the the system time.
                    // Decrement the same to be able to correctly add TimePicker values.

                    calendar.SetDateTime(FromDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                    DateTimeOffset fromTime = calendar.GetDateTime();

                    calendar.SetDateTime(ToDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                    DateTimeOffset toTime = calendar.GetDateTime();

                    notificationString += timestampFormatter.Format(fromTime);
                    notificationString += " To ";
                    notificationString += timestampFormatter.Format(toTime);

                    if (toTime.ToFileTime() < fromTime.ToFileTime())
                    {
                        rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                        // Enable subsequent history retrieval while the async operation is in progress
                        GetHistory.IsEnabled = true;
                    }
                    else
                    {
                        TimeSpan span;
                        span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                        rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                        historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                    }
                }

                if (historyReadings != null)
                {
                    foreach(PedometerReading reading in historyReadings)
                    {
                        HistoryRecord record = new HistoryRecord(reading);
                        historyRecords.Add(record);
                    }

                    rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                }
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
            }

            // Finally, re-enable history retrieval
            GetHistory.IsEnabled = true;
        }

        private ObservableCollection<HistoryRecord> historyRecords;
        private bool getAllHistory = true;
    }

    /// <summary>
    /// Represents a history record object that gets binded to the ListView
    /// controller in the XAML
    /// </summary>
    public sealed class HistoryRecord
    {
        public String TimeStamp
        {
            get
            {
                DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
                return timestampFormatter.Format(recordTimestamp);
            }
        }

        public String StepKind
        {
            get
            {
                String stepString;
                switch (stepKind)
                {
                    case PedometerStepKind.Unknown:
                        stepString = "Unknown";
                        break;
                    case PedometerStepKind.Walking:
                        stepString = "Walking";
                        break;
                    case PedometerStepKind.Running:
                        stepString = "Running";
                        break;
                    default:
                        stepString = "Invalid Step Kind";
                        break;
                }
                return stepString;
            }
        }

        public Int32 StepsCount
        {
            get
            {
                return stepsCount;
            }
        }
        public double StepsDuration
        {
            get
            {
                // return Duration in ms
                return stepsDuration.TotalMilliseconds;
            }
        }

        public HistoryRecord(PedometerReading reading)
        {
            stepKind = reading.StepKind;
            stepsCount = reading.CumulativeSteps;
            recordTimestamp = reading.Timestamp;
        }

        private DateTimeOffset recordTimestamp;
        private PedometerStepKind stepKind;
        private Int32 stepsCount;
        private TimeSpan stepsDuration;
    }
}


text:
package org.elasticsearch.action.admin.indices.settings.get;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.ActionTestUtils;
import org.elasticsearch.action.support.replication.ClusterStateCreationUtils;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.index.Index;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.transport.CapturingTransport;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import org.junit.After;
import org.junit.Before;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static org.elasticsearch.test.ClusterServiceUtils.createClusterService;

public class GetSettingsActionTests extends ESTestCase {

    private TransportService transportService;
    private ClusterService clusterService;
    private ThreadPool threadPool;
    private SettingsFilter settingsFilter;
    private final String indexName = "test_index";

    private TestTransportGetSettingsAction getSettingsAction;

    class TestTransportGetSettingsAction extends TransportGetSettingsAction {
        TestTransportGetSettingsAction() {
            super(GetSettingsActionTests.this.transportService, GetSettingsActionTests.this.clusterService,
                GetSettingsActionTests.this.threadPool, settingsFilter, new ActionFilters(Collections.emptySet()),
                new Resolver(), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS);
        }
        @Override
        protected void masterOperation(Task task, GetSettingsRequest request, ClusterState state,
                                       ActionListener<GetSettingsResponse> listener) {
            ClusterState stateWithIndex = ClusterStateCreationUtils.state(indexName, 1, 1);
            super.masterOperation(task, request, stateWithIndex, listener);
        }
    }

    @Before
    public void setUp() throws Exception {
        super.setUp();

        settingsFilter = new SettingsModule(Settings.EMPTY, emptyList(), emptyList(), emptySet()).getSettingsFilter();
        threadPool = new TestThreadPool("GetSettingsActionTests");
        clusterService = createClusterService(threadPool);
        CapturingTransport capturingTransport = new CapturingTransport();
        transportService = capturingTransport.createTransportService(clusterService.getSettings(), threadPool,
            TransportService.NOOP_TRANSPORT_INTERCEPTOR,
            boundAddress -> clusterService.localNode(), null, Collections.emptySet());
        transportService.start();
        transportService.acceptIncomingRequests();
        getSettingsAction = new GetSettingsActionTests.TestTransportGetSettingsAction();
    }

    @After
    public void tearDown() throws Exception {
        ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS);
        threadPool = null;
        clusterService.close();
        super.tearDown();
    }

    public void testIncludeDefaults() {
        GetSettingsRequest noDefaultsRequest = new GetSettingsRequest().indices(indexName);
        ActionTestUtils.execute(getSettingsAction, null, noDefaultsRequest, ActionListener.wrap(noDefaultsResponse -> {
            assertNull("index.refresh_interval should be null as it was never set", noDefaultsResponse.getSetting(indexName,
                "index.refresh_interval"));
        }, exception -> {
            throw new AssertionError(exception);
        }));

        GetSettingsRequest defaultsRequest = new GetSettingsRequest().indices(indexName).includeDefaults(true);

        ActionTestUtils.execute(getSettingsAction, null, defaultsRequest, ActionListener.wrap(defaultsResponse -> {
            assertNotNull("index.refresh_interval should be set as we are including defaults", defaultsResponse.getSetting(indexName,
                "index.refresh_interval"));
        }, exception -> {
            throw new AssertionError(exception);
        }));

    }

    public void testIncludeDefaultsWithFiltering() {
        GetSettingsRequest defaultsRequest = new GetSettingsRequest().indices(indexName).includeDefaults(true)
            .names("index.refresh_interval");
        ActionTestUtils.execute(getSettingsAction, null, defaultsRequest, ActionListener.wrap(defaultsResponse -> {
            assertNotNull("index.refresh_interval should be set as we are including defaults", defaultsResponse.getSetting(indexName,
                "index.refresh_interval"));
            assertNull("index.number_of_shards should be null as this query is filtered",
                defaultsResponse.getSetting(indexName, "index.number_of_shards"));
            assertNull("index.warmer.enabled should be null as this query is filtered",
                defaultsResponse.getSetting(indexName, "index.warmer.enabled"));
        }, exception -> {
            throw new AssertionError(exception);
        }));
    }

    static class Resolver extends IndexNameExpressionResolver {
        Resolver() {
            super(new ThreadContext(Settings.EMPTY));
        }

        @Override
        public String[] concreteIndexNames(ClusterState state, IndicesRequest request) {
            return request.indices();
        }

        @Override
        public Index[] concreteIndices(ClusterState state, IndicesRequest request) {
            Index[] out = new Index[request.indices().length];
            for (int x = 0; x < out.length; x++) {
                out[x] = new Index(request.indices()[x], "_na_");
            }
            return out;
        }
    }
}


text:
namespace cyclus {
namespace toolkit {

/// Squash combines all products in ps and returns the resulting single
/// product.
Product::Ptr Squash(std::vector<Product::Ptr> ps);

/// Squash combines all materials in ms and returns the resulting single
/// material.
Material::Ptr Squash(std::vector<Material::Ptr> ms);

/// Squash combines all resources in rs and returns the resulting single
/// resource.
Resource::Ptr Squash(std::vector<Resource::Ptr> rs);

/// Casts a vector of Materials into a vector of Resources.
std::vector<Resource::Ptr> ResCast(std::vector<Material::Ptr> rs);

/// Casts a vector of Products into a vector of Resources.
std::vector<Resource::Ptr> ResCast(std::vector<Product::Ptr> rs);

/// Casts a vector of Resources into a vector of Resources.  This is actually
/// basically a no-op that enables ResBuf to work for plain Resource types.
std::vector<Resource::Ptr> ResCast(std::vector<Resource::Ptr> rs);

}  // namespace toolkit
}  // namespace cyclus

#endif  // CYCLUS_SRC_TOOLKIT_RES_MANIP_H_


text:
<?php

namespace Ems\Model\Eloquent;

use InvalidArgumentException;
use Ems\Contracts\Model\Relation\Tag\GlobalTaggingRepository as RepositoryContract;
use Ems\Contracts\Model\Relation\Tag\HoldsTags;
use Ems\Contracts\Model\Relation\Tag\Tag as TagContract;
use Ems\Contracts\Core\AppliesToResource;

class GlobalTaggingRepository implements RepositoryContract
{
    public $relationTable = 'tag_relations';

    public $tagIdKey = 'tag_id';

    public $foreignIdKey = 'foreign_id';

    public $resourceNameKey = 'resource';

    /**
     * @var \Ems\Model\Eloquent\Tag
     **/
    protected $model;

    /**
     * @var string
     **/
    protected $resourceName;

    public function __construct(Tag $tag = null, $resourceName = null)
    {
        $this->model = $tag;
        $this->resourceName = $resourceName;
    }

    /**
     * {@inheritdoc}
     *
     * @return \Traversable
     **/
    public function all()
    {
        $query = $this->model->newQuery()
                             ->select($this->model->getTable().'.*')
                             ->orderBy($this->model->getNameKey())
                             ->distinct();

        if ($this->resourceName) {
            $query->join($this->relationTable, $this->tagKeyName(), '=', $this->model->getTable().'.'.$this->model->getKeyName());
            $query->where($this->resourceNameKey, $this->resourceName);
        }

        return $query->get();
    }

    /**
     * {@inheritdoc}
     *
     * @param \Ems\Contracts\Model\Relation\HoldsTags|\Traversable $holders
     *
     * @return self
     **/
    public function attachTags(&$holders)
    {
        $tagHolders = $holders instanceof HoldsTags ? [$holders] : $holders;

        if (!$holder = $this->findFirst($tagHolders)) {
            return $this;
        }

        $resourceName = $holder->resourceName();

        if (!$tags = $this->tagsByForeignId($this->collectIds($tagHolders), $resourceName)) {
            return $this;
        }

        foreach ($tagHolders as $holder) {
            $foreignId = $holder->getKey();
            if (!isset($tags[$foreignId])) {
                continue;
            }
            foreach ($tags[$foreignId] as $tag) {
                $holder->attachTag($tag);
            }
        }
        return $this;
    }

    /**
     * {@inheritdoc}
     *
     * @param \Ems\Contracts\Model\Relation\HoldsTags $holder
     *
     * @return self
     **/
    public function syncTags(HoldsTags $holder)
    {
        $holderRelations = [];

        if (!$holder instanceof AppliesToResource) {
            throw new InvalidArgumentException('Holders have to be instanceof AppliesToResource for GlobalTaggingRepository');
        }

        $this->assureExistingTags($holder);

        $settedIds = $this->collectIds($holder->getTags());
        $storedIds = $this->collectIds($this->tagsByForeignId([$holder->getId()], $holder->resourceName(), true));

        list($attach, $unchanged, $detach) = $this->sortByDifference($storedIds, $settedIds);

        if ($detach) {
            $query = $this->newPivotQuery()
                          ->where($this->resourceNameKey, $holder->resourceName())
                          ->where($this->foreignIdKey, $holder->getKey())
                          ->whereIn($this->tagIdKey, $detach)
                          ->delete();
        }

        if ($attach) {
            $query = $this->newPivotQuery();
            $records = [];
            foreach ($attach as $attachId) {
                $records[] = $this->createPivotValues($holder, $attachId);
            }

            $query->insert($records);
        }
        return $this;
    }

    /**
     * {@inheritdoc}
     *
     * @param string $name
     *
     * @return \Ems\Contracts\Model\Relation\Tag
     **/
    public function make($name)
    {
        return $this->model->newInstance([$this->model->getNameKey() => $name]);
    }

    /**
     * {@inheritdoc}
     *
     * @param string $name
     *
     * @return \Ems\Contracts\Model\Relation\Tag
     **/
    public function create($name)
    {
        return $this->model->create([$this->model->getNameKey() => $name]);
    }

    /**
     * {@inheritdoc}
     *
     * @param string $name
     *
     * @return \Ems\Contracts\Model\Relation\Tag
     **/
    public function getByNameOrCreate($name)
    {
        if ($tag = $this->getByName($name)) {
            return $tag;
        }

        return $this->create($name);
    }

    /**
     * {@inheritdoc}
     *
     * @param int $id
     *
     * @return \Ems\Contracts\Model\Relation\Tag
     **/
    public function getOrFail($id)
    {
        return $this->model->findOrFail($id);
    }

    /**
     * {@inheritdoc}
     *
     * @param \Ems\Contracts\Model\Relation\Tag
     *
     * @return self
     **/
    public function delete(TagContract $tag)
    {
        $tag->delete();

        return $this;
    }

    /**
     * {@inheritdoc}
     *
     * @param string|\Ems\Contracts\Core\AppliesToResource $resource
     *
     * @return self
     **/
    public function by($resource)
    {
        $resourceName = $resource instanceof AppliesToResource ? $resource->resourceName() : $resource;

        return new static($this->model, $resourceName);
    }

    /**
     * {@inheritdoc}
     *
     * @return array
     **/
    public function resourceNames()
    {
        return $this->newPivotQuery()
                    ->select($this->resourceNameKey)
                    ->distinct()
                    ->lists($this->resourceNameKey);
    }

    protected function getByName($name)
    {
        $query = $this->model->newQuery()
                      ->where($this->model->getNameKey(), $name)
                      ->first();
    }

    protected function createPivotValues(HoldsTags $holder, $tagId)
    {
        return [
            $this->tagIdKey        => $tagId,
            $this->foreignIdKey    => $holder->getKey(),
            $this->resourceNameKey => $holder->resourceName(),
        ];
    }

    protected function assureExistingTags(HoldsTags $holder)
    {
        foreach ($holder->getTags() as $tag) {
            if (!$tag->exists) {
                $tag->save();
            }
        }
    }

    protected function collectIds($holders)
    {
        $ids = [];
        foreach ($holders as $holder) {
            $ids[] = $holder->getKey();
        }

        return $ids;
    }

    protected function newPivotQuery()
    {
        return $this->model->newQuery()->getQuery()->from($this->relationTable);
    }

    protected function tagsByForeignId(array $ids, $resourceName, $onlyFirst = false)
    {
        $query = $this->model->newQuery()
                      ->join($this->relationTable, $this->tagKeyName(), '=', $this->model->getTable().'.'.$this->model->getKeyName())
                      ->where("{$this->relationTable}.{$this->resourceNameKey}", $resourceName)
                      ->whereIn($this->foreignKeyName(), $ids);

        $byId = [];

        foreach ($query->get() as $tag) {
            $foreignId = $tag->getAttribute($this->foreignIdKey);
            if (!isset($byId[$foreignId])) {
                $byId[$foreignId] = [];
            }
            $byId[$foreignId][] = $tag;
        }
        if (!$onlyFirst || !count($byId)) {
            return $byId;
        }
        reset($byId);

        return $byId[key($byId)];
    }

    protected function sortByDifference(array $storedIds, array $passedIds)
    {
        $attached = [];
        $unchanged = [];
        $detached = [];

        foreach ($storedIds as $storedId) {
            if (!in_array($storedId, $passedIds)) {
                $detached[] = $storedId;
                continue;
            }
            $unchanged[] = $storedId;
        }

        foreach ($passedIds as $passedId) {
            if (!in_array($passedId, $storedIds)) {
                $attached[] = $passedId;
            }
        }

        return [$attached, $unchanged, $detached];
    }

    protected function tagKeyName()
    {
        return $this->relationTable.'.'.$this->tagIdKey;
    }

    protected function foreignKeyName()
    {
        return $this->relationTable.'.'.$this->foreignIdKey;
    }

    protected function findFirst($traversable)
    {
        foreach ($traversable as $item) {
            return $item;
        }
        return null;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Septoria podagrariae var. podagrariae

### Remarks
null


text:
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>

<!-- Google Analytics -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-36350691-1', 'auto');
  ga('send', 'pageview');

</script>


text:
package com.gaecompat.demo;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import com.gaecompat.repackaged.com.google.common.collect.ImmutableList;
import com.gaecompat.repackaged.com.google.common.collect.Lists;
import com.google.code.appengine.awt.Color;
import com.google.code.appengine.awt.image.BufferedImage;
import com.google.code.appengine.awt.image.ConvolveOp;
import com.google.code.appengine.awt.image.Kernel;
import com.google.code.appengine.awt.image.WritableRaster;

public interface SimpleFilter {

	BufferedImage filter(BufferedImage inputImage) throws IOException;

	public static abstract class InPlaceRasterFilter implements SimpleFilter {

		@Override
		public BufferedImage filter(BufferedImage inputImage)
				throws IOException {
			WritableRaster raster = inputImage.getRaster();
			filter(raster);
			return inputImage;
		}

		protected abstract void filter(WritableRaster raster) throws IOException;

	}

	public static abstract class PixelOpFilter extends InPlaceRasterFilter {

		@Override
		protected void filter(WritableRaster raster) throws IOException {
			final int w = raster.getWidth(), h = raster.getHeight();
			for (int y = 0; y < h; y++) {
				for (int x = 0; x < w; x++) {
					mutate(raster, x, y);
				}
			}
		}

		protected abstract void mutate(WritableRaster raster, int x, int y);
	}

	public static class ConvolvingFilter implements SimpleFilter {

		private ConvolveOp convolveOp;

		public ConvolvingFilter(ConvolveOp convolveOp) {
			super();
			this.convolveOp = convolveOp;
		}

		@Override
		public BufferedImage filter(BufferedImage inputImage)
				throws IOException {
			BufferedImage dest = convolveOp.filter(inputImage, null);
			return dest;
		}
	}

	/**
	 *
	 * @author http://www.cs.bham.ac.uk/~szh/teaching/graphics/sourcecode/RasterDataExample_ChangePixels.java
	 *
	 */
	public static class Convolutions {

		private Convolutions() {}

		// The last parameter of ConvolveOp is RenderingHints hints. Not imortant, you can
		// always use null.
		// Do sharpening
		public static ConvolveOp sharpen() {
			float data[] = { -1.0f, -1.0f, -1.0f,
							-1.0f,  9.0f,  -1.0f,
							-1.0f,  -1.0f, -1.0f };
			Kernel kernel = new Kernel(3, 3, data);
			ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,
					null);

			return convolve;
		}

		// Averaging or smoothing
		public static ConvolveOp smoothing() {
			float data[] = { 0.111f, 0.111f, 0.111f,
							0.111f,  0.111f,  0.111f,
							0.111f, 0.111f, 0.111f };
			Kernel kernel = new Kernel(3, 3, data);
			ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_ZERO_FILL,
					null);

			return convolve;
		}

		// Detect edges
		public static ConvolveOp edgeDetect() {
			float data[] = { 0.0f, 1.0f,  0.0f,
							 1.0f, -4.0f,  1.0f,
							 0.0f, 1.0f,  0.0f };

			Kernel kernel = new Kernel(3, 3, data);
			ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,
					null);

			return convolve;
		}

		// Embross a image
		public static ConvolveOp emboss() {
			float data[] = { -2.0f, -1.0f, 0.0f,
							 -1.0f, 1.0f,  1.0f,
							  0.0f,  1.0f, 2.0f };

			Kernel kernel = new Kernel(3, 3, data);
			ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,
					null);

			return convolve;
		}

		public static ConvolveOp motionblur() {
			float data[] = { 0.0f, 0.0f, 1.0f,
							 0.0f, 0.0f, 0.0f,
							 1.0f, 0.0f, 0.0f };

			Kernel kernel = new Kernel(3, 3, data);
			ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,
					null);

			return convolve;
		}

		// raise edges
		public static ConvolveOp emboss2() {
			float data[] = { 0.0f, 0.0f, -2.0f,
							 0.0f, 2.0f, 0.0f,
							 1.0f, 0.0f, 0.0f };

			Kernel kernel = new Kernel(3, 3, data);
			ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,
					null);

			return convolve;
		}

	}

	public static class ChannelFilter extends PixelOpFilter {

		private double[] channelFactors;

		public ChannelFilter(double factor0, double factor1, double factor2, double factor3) {
			channelFactors = new double[] { factor0, factor1, factor2, factor3 };
		}

		public ChannelFilter(double factor0, double factor1, double factor2) {
			channelFactors = new double[] { factor0, factor1, factor2};
		}

		@Override
		protected void mutate(WritableRaster raster, int x, int y) {
			int numBands = raster.getNumBands();
			int maxBand = Math.min(channelFactors.length, numBands);
			for (int b = 0; b < maxBand; b++) {
				int value = Colors.roundSample(channelFactors[b] * raster.getSample(x, y, b));
				raster.setSample(x, y, b, value);
			}
		}
	}

	public static class GrayFilter implements SimpleFilter {

				@Override
		public BufferedImage filter(BufferedImage image)
				throws IOException {
			final int w = image.getWidth(), h = image.getHeight();
			for (int y = 0; y < h; y++) {
				for (int x = 0; x < w; x++) {
					Color color = new Color(image.getRGB(x, y));
					int intensity = Colors.roundSample(color.getRed() * 0.3 + color.getGreen() * 0.59 + color.getBlue() * 0.11);
					Color gray = new Color(intensity, intensity, intensity);
					image.setRGB(x, y, gray.getRGB());
				}
			}
			return image;
		}

	}

	public static class IdentityFilter implements SimpleFilter {

		@Override
		public BufferedImage filter(BufferedImage inputImage)
				throws IOException {
			return inputImage;
		}

	}

	public static class Colors {

		private Colors() {}

		public static int clamp(int value, int minInclusive, int maxInclusive) {
			if (value < minInclusive) {
				return minInclusive;
			}
			if (value > maxInclusive) {
				return maxInclusive;
			}
			return value;
		}

		public static int clamp(int value) {
			return clamp(value, 0, 255);
		}

		public static int roundSample(double value) {
			return clamp(Math.round((float)value));
		}
	}

	public static class Examples {

		private static final Random random = new Random();
		private Examples() {}

		public static ImmutableList<SimpleFilter> allFilters() {
			return filters;
		}

		public static SimpleFilter random() {
			return filters.get(random.nextInt(filters.size()));
		}

		private static ImmutableList<SimpleFilter> filters = createFilters();

		private static ImmutableList<SimpleFilter> createFilters() {
			ChannelFilter red = newRedFilter(), green =newGreenFilter(), blue = newBlueFilter();
			List<SimpleFilter> filters = Lists.<SimpleFilter>newArrayList();
			filters.add(new IdentityFilter());
			filters.add(new ConvolvingFilter(Convolutions.edgeDetect()));
			filters.add(red);
			filters.add(new ConvolvingFilter(Convolutions.emboss()));
			filters.add(new ConvolvingFilter(Convolutions.emboss2()));
			filters.add(new GrayFilter());
			filters.add(blue);
			filters.add(new ConvolvingFilter(Convolutions.motionblur()));
			filters.add(new ConvolvingFilter(Convolutions.sharpen()));
			filters.add(green);
			filters.add(new ConvolvingFilter(Convolutions.smoothing()));
			return ImmutableList.copyOf(filters);
		}

		public static ChannelFilter newRedFilter() {
			return new ChannelFilter(1, 0, 0);
		}

		public static ChannelFilter newGreenFilter() {
			return new ChannelFilter(0, 1, 0);
		}

		public static ChannelFilter newBlueFilter() {
			return new ChannelFilter(0, 0, 1);
		}
	}

}


text:
<title>NotAFailureException.<init> - </title>
<link rel="stylesheet" href="../../style.css">

com.github.rs3vans.monadik / NotAFailureException / <init>

<init>

NotAFailureException()


text:
package parser

import (
	"bytes"
	"fmt"
	"go/ast"
	goparser "go/parser"
	gotoken "go/token"
	"io"
	"path/filepath"
	"strconv"
	"strings"
)

type parser struct {
	s                *scanner
	w                io.Writer
	packageName      string
	skipLineComments bool
	prefix           string
	forDepth         int
	switchDepth      int
	skipOutputDepth  int

	importsUseEmitted  bool
	packageNameEmitted bool
}

// Parse parses the contents of the supplied reader, writing generated code to
// the supplied writer. Uses filename as the source file for line comments, and
// pkg as the Go package name.
func Parse(w io.Writer, r io.Reader, filename, pkg string) error {
	return parse(w, r, filename, pkg, false)
}

// ParseNoLineComments is the same as Parse, but does not write line comments.
func ParseNoLineComments(w io.Writer, r io.Reader, filename, pkg string) error {
	return parse(w, r, filename, pkg, true)
}

func parse(w io.Writer, r io.Reader, filename, pkg string, skipLineComments bool) error {
	p := &parser{
		s:                newScanner(r, filename),
		w:                w,
		packageName:      pkg,
		skipLineComments: skipLineComments,
	}
	return p.parseTemplate()
}

func (p *parser) parseTemplate() error {
	s := p.s
	fmt.Fprintf(p.w, `// Code generated by qtc from %q. DO NOT EDIT.
// See https://github.com/valyala/quicktemplate for details.

`,
		filepath.Base(s.filePath))
	for s.Next() {
		t := s.Token()
		switch t.ID {
		case text:
			p.emitComment(t.Value)
		case tagName:
			switch string(t.Value) {
			case "package":
				if p.packageNameEmitted {
					return fmt.Errorf("package name must be at the top of the template. Found at %s", s.Context())
				}
				if err := p.parsePackageName(); err != nil {
					return err
				}
			case "import":
				p.emitPackageName()
				if p.importsUseEmitted {
					return fmt.Errorf("imports must be at the top of the template. Found at %s", s.Context())
				}
				if err := p.parseImport(); err != nil {
					return err
				}
			default:
				p.emitPackageName()
				p.emitImportsUse()
				switch string(t.Value) {
				case "interface", "iface":
					if err := p.parseInterface(); err != nil {
						return err
					}
				case "code":
					if err := p.parseTemplateCode(); err != nil {
						return err
					}
				case "func":
					if err := p.parseFunc(); err != nil {
						return err
					}
				default:
					return fmt.Errorf("unexpected tag found outside func: %q at %s", t.Value, s.Context())
				}
			}
		default:
			return fmt.Errorf("unexpected token found %s outside func at %s", t, s.Context())
		}
	}
	p.emitImportsUse()
	if err := s.LastError(); err != nil {
		return fmt.Errorf("cannot parse template: %s", err)
	}
	return nil
}

func (p *parser) emitPackageName() {
	if !p.packageNameEmitted {
		p.Printf("package %s\n", p.packageName)
		p.packageNameEmitted = true
	}
}

func (p *parser) emitComment(comment []byte) {
	isFirstNonemptyLine := false
	for len(comment) > 0 {
		n := bytes.IndexByte(comment, '\n')
		if n < 0 {
			n = len(comment)
		}
		line := stripTrailingSpace(comment[:n])
		if bytes.HasPrefix(line, []byte("//")) {
			line = line[2:]
			if len(line) > 0 && isSpace(line[0]) {
				line = line[1:]
			}
		}
		if len(line) == 0 {
			if isFirstNonemptyLine {
				fmt.Fprintf(p.w, "//\n")
			}
		} else {
			fmt.Fprintf(p.w, "// %s\n", line)
			isFirstNonemptyLine = true
		}

		if n < len(comment) {
			comment = comment[n+1:]
		} else {
			comment = comment[n:]
		}
	}
	fmt.Fprintf(p.w, "\n")
}

func (p *parser) emitImportsUse() {
	if p.importsUseEmitted {
		return
	}
	p.Printf(`import (
	qtio%s "io"

	qt%s "github.com/valyala/quicktemplate"
)
`, mangleSuffix, mangleSuffix)
	p.Printf(`var (
	_ = qtio%s.Copy
	_ = qt%s.AcquireByteBuffer
)
`, mangleSuffix, mangleSuffix)
	p.importsUseEmitted = true
}

func (p *parser) parseFunc() error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	funcStr := "func " + string(t.Value)
	f, err := parseFuncDef(t.Value)
	if err != nil {
		return fmt.Errorf("error in %q at %s: %s", funcStr, s.Context(), err)
	}
	p.emitFuncStart(f)
	for s.Next() {
		t := s.Token()
		switch t.ID {
		case text:
			p.emitText(t.Value)
		case tagName:
			ok, err := p.tryParseCommonTags(t.Value)
			if err != nil {
				return fmt.Errorf("error in %q: %s", funcStr, err)
			}
			if ok {
				continue
			}
			switch string(t.Value) {
			case "endfunc":
				if err = skipTagContents(s); err != nil {
					return err
				}
				p.emitFuncEnd(f)
				return nil
			default:
				return fmt.Errorf("unexpected tag found in %q: %q at %s", funcStr, t.Value, s.Context())
			}
		default:
			return fmt.Errorf("unexpected token found when parsing %q: %s at %s", funcStr, t, s.Context())
		}
	}
	if err := s.LastError(); err != nil {
		return fmt.Errorf("cannot parse %q: %s", funcStr, err)
	}
	return fmt.Errorf("cannot find endfunc tag for %q at %s", funcStr, s.Context())
}

func (p *parser) parseFor() error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	forStr := "for " + string(t.Value)
	if err = validateForStmt(t.Value); err != nil {
		return fmt.Errorf("invalid statement %q at %s: %s", forStr, s.Context(), err)
	}
	p.Printf("for %s {", t.Value)
	p.prefix += "\t"
	p.forDepth++
	for s.Next() {
		t := s.Token()
		switch t.ID {
		case text:
			p.emitText(t.Value)
		case tagName:
			ok, err := p.tryParseCommonTags(t.Value)
			if err != nil {
				return fmt.Errorf("error in %q: %s", forStr, err)
			}
			if ok {
				continue
			}
			switch string(t.Value) {
			case "endfor":
				if err = skipTagContents(s); err != nil {
					return err
				}
				p.forDepth--
				p.prefix = p.prefix[1:]
				p.Printf("}")
				return nil
			default:
				return fmt.Errorf("unexpected tag found in %q: %q at %s", forStr, t.Value, s.Context())
			}
		default:
			return fmt.Errorf("unexpected token found when parsing %q: %s at %s", forStr, t, s.Context())
		}
	}
	if err := s.LastError(); err != nil {
		return fmt.Errorf("cannot parse %q: %s", forStr, err)
	}
	return fmt.Errorf("cannot find endfor tag for %q at %s", forStr, s.Context())
}

func (p *parser) parseDefault() error {
	s := p.s
	if err := skipTagContents(s); err != nil {
		return err
	}
	stmtStr := "default"
	p.Printf("default:")
	p.prefix += "\t"
	for s.Next() {
		t := s.Token()
		switch t.ID {
		case text:
			p.emitText(t.Value)
		case tagName:
			ok, err := p.tryParseCommonTags(t.Value)
			if err != nil {
				return fmt.Errorf("error in %q: %s", stmtStr, err)
			}
			if !ok {
				s.Rewind()
				p.prefix = p.prefix[1:]
				return nil
			}
		default:
			return fmt.Errorf("unexpected token found when parsing %q: %s at %s", stmtStr, t, s.Context())
		}
	}
	if err := s.LastError(); err != nil {
		return fmt.Errorf("cannot parse %q: %s", stmtStr, err)
	}
	return fmt.Errorf("cannot find end of %q at %s", stmtStr, s.Context())
}

func (p *parser) parseCase(switchValue string) error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	caseStr := "case " + string(t.Value)
	if err = validateCaseStmt(switchValue, t.Value); err != nil {
		return fmt.Errorf("invalid statement %q at %s: %s", caseStr, s.Context(), err)
	}
	p.Printf("case %s:", t.Value)
	p.prefix += "\t"
	for s.Next() {
		t := s.Token()
		switch t.ID {
		case text:
			p.emitText(t.Value)
		case tagName:
			ok, err := p.tryParseCommonTags(t.Value)
			if err != nil {
				return fmt.Errorf("error in %q: %s", caseStr, err)
			}
			if !ok {
				s.Rewind()
				p.prefix = p.prefix[1:]
				return nil
			}
		default:
			return fmt.Errorf("unexpected token found when parsing %q: %s at %s", caseStr, t, s.Context())
		}
	}
	if err := s.LastError(); err != nil {
		return fmt.Errorf("cannot parse %q: %s", caseStr, err)
	}
	return fmt.Errorf("cannot find end of %q at %s", caseStr, s.Context())
}

func (p *parser) parseCat() error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	filename, err := strconv.Unquote(string(t.Value))
	if err != nil {
		return fmt.Errorf("invalid cat value %q at %s: %s", t.Value, s.Context(), err)
	}

	data, err := readFile(s.filePath, filename)
	if err != nil {
		return fmt.Errorf("cannot cat file %q at %s: %s", filename, s.Context(), err)
	}
	p.emitText(data)
	return nil
}

func (p *parser) parseSwitch() error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	switchStr := "switch " + string(t.Value)
	if err = validateSwitchStmt(t.Value); err != nil {
		return fmt.Errorf("invalid statement %q at %s: %s", switchStr, s.Context(), err)
	}
	p.Printf("switch %s {", t.Value)
	switchValue := string(t.Value)
	caseNum := 0
	defaultFound := false
	p.switchDepth++
	for s.Next() {
		t := s.Token()
		switch t.ID {
		case text:
			if caseNum == 0 {
				comment := stripLeadingSpace(t.Value)
				if len(comment) > 0 {
					p.emitComment(comment)
				}
			} else {
				p.emitText(t.Value)
			}
		case tagName:
			switch string(t.Value) {
			case "endswitch":
				if caseNum == 0 {
					return fmt.Errorf("empty statement %q found at %s", switchStr, s.Context())
				}
				if err = skipTagContents(s); err != nil {
					return err
				}
				p.switchDepth--
				p.Printf("}")
				return nil
			case "case":
				caseNum++
				if err = p.parseCase(switchValue); err != nil {
					return err
				}
			case "default":
				if defaultFound {
					return fmt.Errorf("duplicate default tag found in %q at %s", switchStr, s.Context())
				}
				defaultFound = true
				caseNum++
				if err = p.parseDefault(); err != nil {
					return err
				}
			default:
				return fmt.Errorf("unexpected tag found in %q: %q at %s", switchStr, t.Value, s.Context())
			}
		default:
			return fmt.Errorf("unexpected token found when parsing %q: %s at %s", switchStr, t, s.Context())
		}
	}
	if err := s.LastError(); err != nil {
		return fmt.Errorf("cannot parse %q: %s", switchStr, err)
	}
	return fmt.Errorf("cannot find endswitch tag for %q at %s", switchStr, s.Context())
}

func (p *parser) parseIf() error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	if len(t.Value) == 0 {
		return fmt.Errorf("empty if condition at %s", s.Context())
	}
	ifStr := "if " + string(t.Value)
	if err = validateIfStmt(t.Value); err != nil {
		return fmt.Errorf("invalid statement %q at %s: %s", ifStr, s.Context(), err)
	}
	p.Printf("if %s {", t.Value)
	p.prefix += "\t"
	elseUsed := false
	for s.Next() {
		t := s.Token()
		switch t.ID {
		case text:
			p.emitText(t.Value)
		case tagName:
			ok, err := p.tryParseCommonTags(t.Value)
			if err != nil {
				return fmt.Errorf("error in %q: %s", ifStr, err)
			}
			if ok {
				continue
			}
			switch string(t.Value) {
			case "endif":
				if err = skipTagContents(s); err != nil {
					return err
				}
				p.prefix = p.prefix[1:]
				p.Printf("}")
				return nil
			case "else":
				if elseUsed {
					return fmt.Errorf("duplicate else branch found for %q at %s", ifStr, s.Context())
				}
				if err = skipTagContents(s); err != nil {
					return err
				}
				p.prefix = p.prefix[1:]
				p.Printf("} else {")
				p.prefix += "\t"
				elseUsed = true
			case "elseif":
				if elseUsed {
					return fmt.Errorf("unexpected elseif branch found after else branch for %q at %s",
						ifStr, s.Context())
				}
				t, err = expectTagContents(s)
				if err != nil {
					return err
				}
				p.prefix = p.prefix[1:]
				p.Printf("} else if %s {", t.Value)
				p.prefix += "\t"
			default:
				return fmt.Errorf("unexpected tag found in %q: %q at %s", ifStr, t.Value, s.Context())
			}
		default:
			return fmt.Errorf("unexpected token found when parsing %q: %s at %s", ifStr, t, s.Context())
		}
	}
	if err := s.LastError(); err != nil {
		return fmt.Errorf("cannot parse %q: %s", ifStr, err)
	}
	return fmt.Errorf("cannot find endif tag for %q at %s", ifStr, s.Context())
}

func (p *parser) tryParseCommonTags(tagBytes []byte) (bool, error) {
	tagNameStr, prec := splitTagNamePrec(string(tagBytes))
	switch tagNameStr {
	case "s", "v", "d", "dl", "dul", "f", "q", "z", "j", "u",
		"s=", "v=", "d=", "dl=", "dul=", "f=", "q=", "z=", "j=", "u=",
		"sz", "qz", "jz", "uz",
		"sz=", "qz=", "jz=", "uz=":
		if err := p.parseOutputTag(tagNameStr, prec); err != nil {
			return false, err
		}
	case "=", "=h", "=u", "=uh", "=q", "=qh", "=j", "=jh":
		if err := p.parseOutputFunc(tagNameStr); err != nil {
			return false, err
		}
	case "return":
		if err := p.skipAfterTag(tagNameStr); err != nil {
			return false, err
		}
	case "break":
		if p.forDepth <= 0 && p.switchDepth <= 0 {
			return false, fmt.Errorf("found break tag outside for loop and switch block")
		}
		if err := p.skipAfterTag(tagNameStr); err != nil {
			return false, err
		}
	case "continue":
		if p.forDepth <= 0 {
			return false, fmt.Errorf("found continue tag outside for loop")
		}
		if err := p.skipAfterTag(tagNameStr); err != nil {
			return false, err
		}
	case "code":
		if err := p.parseFuncCode(); err != nil {
			return false, err
		}
	case "for":
		if err := p.parseFor(); err != nil {
			return false, err
		}
	case "if":
		if err := p.parseIf(); err != nil {
			return false, err
		}
	case "switch":
		if err := p.parseSwitch(); err != nil {
			return false, err
		}
	case "cat":
		if err := p.parseCat(); err != nil {
			return false, err
		}
	default:
		return false, nil
	}
	return true, nil
}

func splitTagNamePrec(tagName string) (string, int) {
	parts := strings.Split(tagName, ".")
	if len(parts) == 2 && parts[0] == "f" {
		p := parts[1]
		if strings.HasSuffix(p, "=") {
			p = p[:len(p)-1]
		}
		if len(p) == 0 {
			return "f", 0
		}
		prec, err := strconv.Atoi(p)
		if err == nil && prec >= 0 {
			return "f", prec
		}
	}
	return tagName, -1
}

func (p *parser) skipAfterTag(tagStr string) error {
	s := p.s
	if err := skipTagContents(s); err != nil {
		return err
	}
	p.Printf("%s", tagStr)
	p.skipOutputDepth++
	defer func() {
		p.skipOutputDepth--
	}()
	for s.Next() {
		t := s.Token()
		switch t.ID {
		case text:
			// skip text
		case tagName:
			ok, err := p.tryParseCommonTags(t.Value)
			if err != nil {
				return fmt.Errorf("error when parsing contents after %q: %s", tagStr, err)
			}
			if ok {
				continue
			}
			switch string(t.Value) {
			case "endfunc", "endfor", "endif", "else", "elseif", "case", "default", "endswitch":
				s.Rewind()
				return nil
			default:
				return fmt.Errorf("unexpected tag found after %q: %q at %s", tagStr, t.Value, s.Context())
			}
		default:
			return fmt.Errorf("unexpected token found when parsing contents after %q: %s at %s", tagStr, t, s.Context())
		}
	}
	if err := s.LastError(); err != nil {
		return fmt.Errorf("cannot parse contents after %q: %s", tagStr, err)
	}
	return fmt.Errorf("cannot find closing tag after %q at %s", tagStr, s.Context())
}

func (p *parser) parseInterface() error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}

	n := bytes.IndexByte(t.Value, '{')
	if n < 0 {
		return fmt.Errorf("missing '{' in interface at %s", s.Context())
	}
	ifname := string(stripTrailingSpace(t.Value[:n]))
	if len(ifname) == 0 {
		return fmt.Errorf("missing interface name at %s", s.Context())
	}
	p.Printf("type %s interface {", ifname)
	p.prefix = "\t"

	tail := t.Value[n:]
	exprStr := fmt.Sprintf("interface %s", tail)
	expr, err := goparser.ParseExpr(exprStr)
	if err != nil {
		return fmt.Errorf("error when parsing interface at %s: %s", s.Context(), err)
	}
	it, ok := expr.(*ast.InterfaceType)
	if !ok {
		return fmt.Errorf("unexpected interface type at %s: %T", s.Context(), expr)
	}
	methods := it.Methods.List
	if len(methods) == 0 {
		return fmt.Errorf("interface must contain at least one method at %s", s.Context())
	}

	for _, m := range it.Methods.List {
		methodStr := exprStr[m.Pos()-1 : m.End()-1]
		f, err := parseFuncDef([]byte(methodStr))
		if err != nil {
			return fmt.Errorf("when when parsing %q at %s: %s", methodStr, s.Context(), err)
		}
		p.Printf("%s string", methodStr)
		p.Printf("%s", f.DefStream("qw"+mangleSuffix))
		p.Printf("%s", f.DefWrite("qq"+mangleSuffix))
	}
	p.prefix = ""
	p.Printf("}")
	return nil
}

func (p *parser) parsePackageName() error {
	t, err := expectTagContents(p.s)
	if err != nil {
		return err
	}
	if len(t.Value) == 0 {
		return fmt.Errorf("empty package name found at %s", p.s.Context())
	}
	if err = validatePackageName(t.Value); err != nil {
		return fmt.Errorf("invalid package name found at %s: %s", p.s.Context(), err)
	}
	p.packageName = string(t.Value)
	p.emitPackageName()
	return nil
}

func (p *parser) parseImport() error {
	t, err := expectTagContents(p.s)
	if err != nil {
		return err
	}
	if len(t.Value) == 0 {
		return fmt.Errorf("empty import found at %s", p.s.Context())
	}
	if err = validateImport(t.Value); err != nil {
		return fmt.Errorf("invalid import found at %s: %s", p.s.Context(), err)
	}
	p.Printf("import %s\n", t.Value)
	return nil
}

func (p *parser) parseTemplateCode() error {
	t, err := expectTagContents(p.s)
	if err != nil {
		return err
	}
	if err = validateTemplateCode(t.Value); err != nil {
		return fmt.Errorf("invalid code at %s: %s", p.s.Context(), err)
	}
	p.Printf("%s\n", t.Value)
	return nil
}

func (p *parser) parseFuncCode() error {
	t, err := expectTagContents(p.s)
	if err != nil {
		return err
	}
	if err = validateFuncCode(t.Value); err != nil {
		return fmt.Errorf("invalid code at %s: %s", p.s.Context(), err)
	}
	p.Printf("%s\n", t.Value)
	return nil
}

func (p *parser) parseOutputTag(tagNameStr string, prec int) error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	if err = validateOutputTagValue(t.Value); err != nil {
		return fmt.Errorf("invalid output tag value at %s: %s", s.Context(), err)
	}
	filter := "N"
	switch tagNameStr {
	case "s", "v", "q", "z", "j", "sz", "qz", "jz":
		filter = "E"
	}
	if strings.HasSuffix(tagNameStr, "=") {
		tagNameStr = tagNameStr[:len(tagNameStr)-1]
	}
	if tagNameStr == "f" && prec >= 0 {
		p.Printf("qw%s.N().FPrec(%s, %d)", mangleSuffix, t.Value, prec)
	} else {
		tagNameStr = strings.ToUpper(tagNameStr)
		p.Printf("qw%s.%s().%s(%s)", mangleSuffix, filter, tagNameStr, t.Value)
	}

	return nil
}

func (p *parser) parseOutputFunc(tagNameStr string) error {
	s := p.s
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	f, err := parseFuncCall(t.Value)
	if err != nil {
		return fmt.Errorf("error at %s: %s", s.Context(), err)
	}
	filter := "N"
	tagNameStr = tagNameStr[1:]
	if strings.HasSuffix(tagNameStr, "h") {
		tagNameStr = tagNameStr[:len(tagNameStr)-1]
		switch tagNameStr {
		case "", "q", "j":
			filter = "E"
		}
	}

	if len(tagNameStr) > 0 || filter == "E" {
		tagNameStr = strings.ToUpper(tagNameStr)
		p.Printf("{")
		p.Printf("qb%s := qt%s.AcquireByteBuffer()", mangleSuffix, mangleSuffix)
		p.Printf("%s", f.CallWrite("qb"+mangleSuffix))
		p.Printf("qw%s.%s().%sZ(qb%s.B)", mangleSuffix, filter, tagNameStr, mangleSuffix)
		p.Printf("qt%s.ReleaseByteBuffer(qb%s)", mangleSuffix, mangleSuffix)
		p.Printf("}")
	} else {
		p.Printf("%s", f.CallStream("qw"+mangleSuffix))
	}

	return nil
}

func (p *parser) emitText(text []byte) {
	for len(text) > 0 {
		n := bytes.IndexByte(text, '`')
		if n < 0 {
			p.Printf("qw%s.N().S(`%s`)", mangleSuffix, text)
			return
		}
		p.Printf("qw%s.N().S(`%s`)", mangleSuffix, text[:n])
		p.Printf("qw%s.N().S(\"`\")", mangleSuffix)
		text = text[n+1:]
	}
}

func (p *parser) emitFuncStart(f *funcType) {
	p.Printf("func %s {", f.DefStream("qw"+mangleSuffix))
	p.prefix = "\t"
}

func (p *parser) emitFuncEnd(f *funcType) {
	p.prefix = ""
	p.Printf("}\n")

	p.Printf("func %s {", f.DefWrite("qq"+mangleSuffix))
	p.prefix = "\t"
	p.Printf("qw%s := qt%s.AcquireWriter(qq%s)", mangleSuffix, mangleSuffix, mangleSuffix)
	p.Printf("%s", f.CallStream("qw"+mangleSuffix))
	p.Printf("qt%s.ReleaseWriter(qw%s)", mangleSuffix, mangleSuffix)
	p.prefix = ""
	p.Printf("}\n")

	p.Printf("func %s {", f.DefString())
	p.prefix = "\t"
	p.Printf("qb%s := qt%s.AcquireByteBuffer()", mangleSuffix, mangleSuffix)
	p.Printf("%s", f.CallWrite("qb"+mangleSuffix))
	p.Printf("qs%s := string(qb%s.B)", mangleSuffix, mangleSuffix)
	p.Printf("qt%s.ReleaseByteBuffer(qb%s)", mangleSuffix, mangleSuffix)
	p.Printf("return qs%s", mangleSuffix)
	p.prefix = ""
	p.Printf("}\n")
}

func (p *parser) Printf(format string, args ...interface{}) {
	if p.skipOutputDepth > 0 {
		return
	}
	w := p.w
	if !p.skipLineComments {
		// line comments are required to start at the beginning of the line
		p.s.WriteLineComment(w)
	}
	fmt.Fprintf(w, "%s", p.prefix)
	fmt.Fprintf(w, format, args...)
	fmt.Fprintf(w, "\n")
}

func skipTagContents(s *scanner) error {
	tagName := string(s.Token().Value)
	t, err := expectTagContents(s)
	if err != nil {
		return err
	}
	if len(t.Value) > 0 {
		return fmt.Errorf("unexpected extra value after %s: %q at %s", tagName, t.Value, s.Context())
	}
	return err
}

func expectTagContents(s *scanner) (*token, error) {
	return expectToken(s, tagContents)
}

func expectToken(s *scanner, id int) (*token, error) {
	if !s.Next() {
		return nil, fmt.Errorf("cannot find token %s: %v", tokenIDToStr(id), s.LastError())
	}
	t := s.Token()
	if t.ID != id {
		return nil, fmt.Errorf("unexpected token found %s. Expecting %s at %s", t, tokenIDToStr(id), s.Context())
	}
	return t, nil
}

func validateOutputTagValue(stmt []byte) error {
	exprStr := string(stmt)
	_, err := goparser.ParseExpr(exprStr)
	return err
}

func validateForStmt(stmt []byte) error {
	exprStr := fmt.Sprintf("func () { for %s {} }", stmt)
	_, err := goparser.ParseExpr(exprStr)
	return err
}

func validateIfStmt(stmt []byte) error {
	exprStr := fmt.Sprintf("func () { if %s {} }", stmt)
	_, err := goparser.ParseExpr(exprStr)
	return err
}

func validateSwitchStmt(stmt []byte) error {
	exprStr := fmt.Sprintf("func () { switch %s {} }", stmt)
	_, err := goparser.ParseExpr(exprStr)
	return err
}

func validateCaseStmt(switchValue string, stmt []byte) error {
	exprStr := fmt.Sprintf("func () { switch %s {case %s:} }", switchValue, stmt)
	_, err := goparser.ParseExpr(exprStr)
	return err
}

func validateFuncCode(code []byte) error {
	exprStr := fmt.Sprintf("func () { for { %s\n } }", code)
	_, err := goparser.ParseExpr(exprStr)
	return err
}

func validateTemplateCode(code []byte) error {
	codeStr := fmt.Sprintf("package foo\nvar _ = a\n%s", code)
	fset := gotoken.NewFileSet()
	_, err := goparser.ParseFile(fset, "", codeStr, 0)
	return err
}

func validatePackageName(code []byte) error {
	codeStr := fmt.Sprintf("package %s", code)
	fset := gotoken.NewFileSet()
	_, err := goparser.ParseFile(fset, "", codeStr, 0)
	return err
}

func validateImport(code []byte) error {
	codeStr := fmt.Sprintf("package foo\nimport %s", code)
	fset := gotoken.NewFileSet()
	f, err := goparser.ParseFile(fset, "", codeStr, 0)
	if err != nil {
		return err
	}
	for _, d := range f.Decls {
		gd, ok := d.(*ast.GenDecl)
		if !ok {
			return fmt.Errorf("unexpected code found: %T. Expecting ast.GenDecl", d)
		}
		for _, s := range gd.Specs {
			if _, ok := s.(*ast.ImportSpec); !ok {
				return fmt.Errorf("unexpected code found: %T. Expecting ast.ImportSpec", s)
			}
		}
	}
	return nil
}


text:
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { grey300,grey900,blue500, blue200 } from 'material-ui/styles/colors';
const darkGray = grey900;
const theme = getMuiTheme({
  fontFamily:'Lato',
  palette: {
    primary1Color:darkGray,
    primary2Color:blue500
  },
  appBar: {
    height: 50,
    color: darkGray
  },
  tabs: {
    backgroundColor: darkGray,
    textColor: 'white',
    selectedTextColor: blue200,
  }
});
export default theme;


text:
package net.i2p.client.streaming;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import net.i2p.I2PAppContext;
import net.i2p.client.I2PClientFactory;
import net.i2p.data.Destination;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;

/**
 * Sit around on a destination, receiving lots of data and sending lots of
 * data to whomever talks to us.
 *
 * Usage: TestSwarm myKeyFile [peerDestFile ]*
 *
 */
public class TestSwarm {
    private I2PAppContext _context;
    private Log _log;
    private String _destFile;
    private String _peerDestFiles[];
    private I2PSocketManager _manager;
    private String _conOptions; // unused? used elsewhere?
    private boolean _dead; // unused? used elsewhere?

    public static void main(String args[]) {
        if (args.length < 1) {
            System.err.println("Usage: TestSwarm myDestFile [peerDestFile ]*");
            return;
        }
        I2PAppContext ctx = new I2PAppContext();
        String files[] = new String[args.length - 1];
        System.arraycopy(args, 1, files, 0, files.length);
        TestSwarm swarm = new TestSwarm(ctx, args[0], files);
        swarm.startup();
    }

    public TestSwarm(I2PAppContext ctx, String destFile, String peerDestFiles[]) {
        _context = ctx;
        _log = ctx.logManager().getLog(TestSwarm.class);
        _dead = false;
        _destFile = destFile;
        _peerDestFiles = peerDestFiles;
        _conOptions = "";
    }

    public void startup() {
        _log.debug("Starting up");
        File keys = new File(_destFile);
        if (!keys.exists()) {
            try {
                I2PClientFactory.createClient().createDestination(new FileOutputStream(keys));
            } catch (Exception e) {
                _log.error("Error creating a new destination on " + keys, e);
                return;
            }
        }
        try {
            _manager = I2PSocketManagerFactory.createManager(new FileInputStream(_destFile), null, -1, null);
        } catch (Exception e) {
            _log.error("Error creatign the manager", e);
            return;
        }

        I2PThread listener = new I2PThread(new Listener(), "Listener");
        listener.start();

        connectWithPeers();
    }

    private void connectWithPeers() {
        if (_peerDestFiles != null) {
            for (int i = 0; i < _peerDestFiles.length; i++) {
                try {
                    FileInputStream fin = new FileInputStream(_peerDestFiles[i]);
                    Destination dest = new Destination();
                    dest.readBytes(fin);

                    I2PThread flooder = new I2PThread(new Flooder(dest), "Flooder+" + dest.calculateHash().toBase64().substring(0,4));
                    flooder.start();
                } catch (Exception e) {
                    _log.error("Unable to read the peer from " + _peerDestFiles[i], e);
                }
            }
        }
    }

    private class Listener implements Runnable {
        public void run() {
            try {
                I2PServerSocket ss = _manager.getServerSocket();
                I2PSocket s = null;
                while ( (s = ss.accept()) != null) {
                    I2PThread flooder = new I2PThread(new Flooder(s), "Flooder-" + s.getPeerDestination().calculateHash().toBase64().substring(0,4));
                    flooder.start();
                }
            } catch (Exception e) {
                _log.error("Error listening", e);
            }
        }
    }

    private static volatile long __conId = 0;
    private class Flooder implements Runnable {
        private Destination _remoteDestination;
        private I2PSocket _socket;
        private boolean _closed;
        private long _started;
        private long _totalSent;
        private long _totalReceived;
        private long _lastReceived;
        private long _lastReceivedOn;
        private long _connectionId;

        public Flooder(Destination dest) {
            _socket = null;
            _remoteDestination = dest;
            _connectionId = ++__conId;
            _closed = false;
            _lastReceived = -1;
            _lastReceivedOn = _context.clock().now();
            _context.statManager().createRateStat("swarm." + _connectionId + ".totalReceived", "Data size received", "swarm", new long[] { 30*1000, 60*1000, 5*60*1000 });
            _context.statManager().createRateStat("swarm." + _connectionId + ".totalSent", "Data size sent", "swarm", new long[] { 30*1000, 60*1000, 5*60*1000 });
            _context.statManager().createRateStat("swarm." + _connectionId + ".started", "When we start", "swarm", new long[] { 5*60*1000 });
            _context.statManager().createRateStat("swarm." + _connectionId + ".lifetime", "How long we talk to a peer", "swarm", new long[] { 5*60*1000 });
        }

        public Flooder(I2PSocket socket) {
            _socket = socket;
            _remoteDestination = socket.getPeerDestination();
            _connectionId = ++__conId;
            _closed = false;
            _lastReceived = -1;
            _lastReceivedOn = _context.clock().now();
            _context.statManager().createRateStat("swarm." + _connectionId + ".totalReceived", "Data size received", "swarm", new long[] { 30*1000, 60*1000, 5*60*1000 });
            _context.statManager().createRateStat("swarm." + _connectionId + ".totalSent", "Data size sent", "swarm", new long[] { 30*1000, 60*1000, 5*60*1000 });
            _context.statManager().createRateStat("swarm." + _connectionId + ".started", "When we start", "swarm", new long[] { 5*60*1000 });
            _context.statManager().createRateStat("swarm." + _connectionId + ".lifetime", "How long we talk to a peer", "swarm", new long[] { 5*60*1000 });
        }

        public long getConnectionId() { return _connectionId; }
        public Destination getDestination() { return _remoteDestination; }

        public void run() {
            _started = _context.clock().now();
            _context.statManager().addRateData("swarm." + _connectionId + ".started", 1, 0);
            byte data[] = new byte[4*1024];
            _context.random().nextBytes(data);
            long value = 0;
            long lastSend = _context.clock().now();
            if (_socket == null) {
                try {
                    _socket = _manager.connect(_remoteDestination);
                } catch (Exception e) {
                    _log.error("Error connecting to " + _remoteDestination.calculateHash().toBase64().substring(0,4));
                    return;
                }
            }

            I2PThread floodListener = new I2PThread(new FloodListener(), "FloodListener" + _connectionId);
            floodListener.start();

            try {
                OutputStream out = _socket.getOutputStream();
                while (!_closed) {
                    if (shouldSend()) {
                        out.write(data);
                        // out.flush();
                        _totalSent += data.length;
                        _context.statManager().addRateData("swarm." + _connectionId + ".totalSent", _totalSent, 0);
                        //try { Thread.sleep(100); } catch (InterruptedException ie) {}
                        long now = _context.clock().now();
                        //_log.debug("Sending " + _connectionId + " after " + (now-lastSend));
                        lastSend = now;
                        //try { Thread.sleep(20); } catch (InterruptedException ie) {}
                    } else {
                        try { Thread.sleep(5000); } catch (InterruptedException ie) {}
                    }
                }
            } catch (Exception e) {
                _log.error("Error sending", e);
            }
        }

        private class FloodListener implements Runnable {
            public void run() {
                long lastRead = System.currentTimeMillis();
                long now = lastRead;
                try {
                    InputStream in = _socket.getInputStream();
                    byte buf[] = new byte[8*1024];
                    int read = 0;
                    while ( (read = in.read(buf)) != -1) {
                        now = System.currentTimeMillis();
                        _totalReceived += read;
                        _context.statManager().addRateData("swarm." + getConnectionId() + ".totalReceived", _totalReceived, 0);
                        //_log.debug("Receiving " + _connectionId + " with " + read + " after " + (now-lastRead));
                        lastRead = now;
                    }
                } catch (Exception e) {
                    _log.error("Error listening to the flood", e);
                }
            }
        }
    }

    private boolean shouldSend() {
        return Boolean.valueOf(_context.getProperty("shouldSend", "false")).booleanValue();
    }
}


text:
// Test automatically retrieved. Do not edit manually
const { render, json } = require('server/reply');
const { get, post } = require('server/router');
const { modern } = require('server').utils;
const run = require('server/test/run');
const fs = require('mz/fs');
const path = require('path');

describe('Automatic test from content 3', () => {
  it('works', async () => {
    // START
    const options = {
      public: 'public'
    };

    /* test */
    const same = ctx => ({ public: ctx.options.public });
    const res = await run(options, same).get('/');
    expect(res.body.public).toBe(path.join(process.cwd() + '/public'));
    // END
  });
});


text:
'use strict';

const _ = require('lodash');
const serialize = require('simple-serialization');
const defaultRegistry = serialize.registry;

function noop() {}
function trueF() { return true; }
function falseF() { return false; }

class Visitor {
  static get noop() { return noop; }
  static get trueF() { return trueF; }
  static get falseF() { return falseF; }

  constructor(opts) {
    this.init(opts || {});
  }

  init(opts) {
    this.shouldVisitNode = opts.shouldVisitNode || falseF;
    this.shouldVisitTree = opts.shouldVisitTree || falseF;
    this.visit = opts.visit || noop;
    this.registry = opts.registry || defaultRegistry;
  }

  visitNode(node) {
    if (!this.shouldVisitNode(node)) return;
    this.visit(node);
  }

  visitTree(root) {
    if (!this.shouldVisitTree(root)) return;
    this.visitNode(root);
    _.forOwn(root, node => this.visitTree(node));
  }
}

module.exports = Visitor;


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context="cz.jenda.pidifrky.ui.GpsLogActivity" android:padding="5dp">

    <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/scrollView" android:fillViewport="true">
        <TextView
                android:text=""
                android:layout_width="match_parent"
                android:layout_height="match_parent" android:id="@+id/gpslog" android:nestedScrollingEnabled="true"/>
    </ScrollView>

</RelativeLayout>