text:
"""Tests for tf.cond in XLA."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.compiler.tests import xla_test
from tensorflow.python.eager import function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.platform import test

@test_util.with_control_flow_v2
class CondTest(xla_test.XLATestCase):

  def testCondAndTensorArrayInDefun(self):
    with self.cached_session(), self.test_scope():
      xla_context = control_flow_ops.XLAControlFlowContext()
      xla_context.Enter()

      @function.defun
      def f():
        ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=1)
        output = control_flow_ops.cond(
            constant_op.constant(
                True), lambda: ta.write(0, 5.), lambda: ta.write(0, 10.))

        return output.stack()

      output_t = f()
      self.assertAllEqual(self.evaluate(output_t), [5.])

      xla_context.Exit()

  def testCondConstPropagation(self):
    with self.cached_session() as sess, self.test_scope():
      xla_context = control_flow_ops.XLAControlFlowContext()
      xla_context.Enter()

      x = array_ops.placeholder(dtypes.float32)
      p = array_ops.placeholder(dtypes.int32)

      # TODO(b/129021699): Wrapping this in a tf.function does not work.
      def if_true():
        # This emits a StridedSlice op which expects the index to be a
        # compile-time const.
        return x[p]

      def if_false():
        return 5.

      output = control_flow_ops.cond(
          constant_op.constant(True), if_true, if_false)

      self.assertAllEqual(
          sess.run(output, feed_dict={
              x: [0., 1., 2.],
              p: 1
          }), 1.)

      xla_context.Exit()

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


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 485 (1898)

#### Original name
Pezizella elaeina (Pass. & Beltr.) Sacc.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package com.kevelbreh.steamchat.fragment;

import android.os.Bundle;
import android.preference.PreferenceFragment;

import com.kevelbreh.steamchat.R;

/**
 * Stock settings fragment for our shared preferences interface.
 */
public class SettingsFragment extends PreferenceFragment {

    /**
     * Preference key returned boolean value of whether the hide offline contacts or not.
     */
    public static final String PREF_FRIENDS_HIDE_OFFLINE = "pref_friends_hide_offline";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace RenderingLibrary.Graphics
{
    public enum VerticalAlignment
    {
        Top,
        Center,
        Bottom,
        TextBaseline
    }

}


text: alter table query_tv_info convert to character set utf8;


text:
package org.insightech.er.editor.view.tool;

import org.eclipse.gef.tools.ConnectionCreationTool;
import org.insightech.er.Activator;
import org.insightech.er.editor.controller.command.diagram_contents.element.connection.relation.CreateRelationCommand;
import org.insightech.er.editor.model.diagram_contents.element.node.table.ERTable;
import org.insightech.er.editor.model.diagram_contents.element.node.table.TableView;

public class RelationCreationTool extends ConnectionCreationTool {

	@Override
	protected boolean handleCreateConnection() {
		CreateRelationCommand command = (CreateRelationCommand) this
				.getCommand();

		if (command == null) {
			return false;
		}

		TableView source = (TableView) command.getSourceModel();
		TableView target = (TableView) command.getTargetModel();

		if (ERTable.isRecursive(source, target)) {
			Activator.showErrorDialog("error.recursive.relation");

			this.eraseSourceFeedback();

			return false;
		}

		return super.handleCreateConnection();
	}

}


text:
package org.apache.jackrabbit.oak.segment;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static org.apache.jackrabbit.oak.commons.PathUtils.elements;
import static org.apache.jackrabbit.oak.commons.PathUtils.getName;
import static org.apache.jackrabbit.oak.commons.PathUtils.getParentPath;
import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.google.common.base.Supplier;
import org.apache.jackrabbit.oak.segment.file.GCNodeWriteMonitor;
import org.apache.jackrabbit.oak.spi.blob.BlobStore;
import org.apache.jackrabbit.oak.spi.gc.GCMonitor;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;

/**
 * This compactor implementation is aware of the checkpoints in the repository.
 * It uses this information to further optimise the compaction result by
 *

 *
Rebasing the checkpoints and subsequently the root on top of each other
 *     in chronological order. This results minimises the deltas that need to be
 *     processed and stored.

 *
Caching the compacted checkpoints and root states for deduplication should
 *     the same checkpoint or root state occur again in a later compaction retry cycle.

 *

 */
public class CheckpointCompactor {
    @Nonnull
    private final GCMonitor gcListener;

    @Nonnull
    private final Map<NodeState, NodeState> cpCache = newHashMap();

    @Nonnull
    private final Compactor compactor;

    @Nonnull
    private final NodeWriter nodeWriter;

    private interface NodeWriter {
        @Nonnull
        SegmentNodeState writeNode(@Nonnull NodeState node, @Nullable ByteBuffer stableId) throws IOException;
    }

    /**
     * Create a new instance based on the passed arguments.
     * @param reader     segment reader used to read from the segments
     * @param writer     segment writer used to serialise to segments
     * @param blobStore  the blob store or {@code null} if none
     * @param cancel     a flag that can be used to cancel the compaction process
     * @param compactionMonitor   notification call back for each compacted nodes,
     *                            properties, and binaries
     */
    public CheckpointCompactor(
            @Nonnull GCMonitor gcListener,
            @Nonnull SegmentReader reader,
            @Nonnull SegmentWriter writer,
            @Nullable BlobStore blobStore,
            @Nonnull Supplier<Boolean> cancel,
            @Nonnull GCNodeWriteMonitor compactionMonitor) {
        this.gcListener = gcListener;
        this.compactor = new Compactor(reader, writer, blobStore, cancel, compactionMonitor);
        this.nodeWriter = (node, stableId) -> {
            RecordId nodeId = writer.writeNode(node, stableId);
            return new SegmentNodeState(reader, writer, blobStore, nodeId);
        };
    }

    /**
     * Compact {@code uncompacted} on top of an optional {@code base}.
     * @param base         the base state to compact against
     * @param uncompacted  the uncompacted state to compact
     * @param onto         the state onto which to compact the change between {@code base} and
     *                     {@code uncompacted}
     * @return  compacted clone of {@code uncompacted} or {@code null} if cancelled.
     * @throws IOException
     */
    @CheckForNull
    public SegmentNodeState compact(
            @Nonnull NodeState base,
            @Nonnull NodeState uncompacted,
            @Nonnull NodeState onto)
    throws IOException {
        // Collect a chronologically ordered list of roots for the uncompacted
        // state. This list consists of all checkpoints followed by the root.
        LinkedHashMap<String, NodeState> uncompactedRoots = collectRoots(uncompacted);

        // Compact the list of uncompacted roots to a list of compacted roots.
        LinkedHashMap<String, NodeState> compactedRoots = compact(
                getRoot(base), uncompactedRoots, getRoot(onto));
        if (compactedRoots == null) {
            return null;
        }

        // Build a compacted super root by replacing the uncompacted roots with
        // the compacted ones in the original node.
        NodeBuilder builder = uncompacted.builder();
        for (Entry<String, NodeState> compactedRoot : compactedRoots.entrySet()) {
            String path = compactedRoot.getKey();
            NodeState state = compactedRoot.getValue();
            NodeBuilder childBuilder = getChild(builder, getParentPath(path));
            childBuilder.setChildNode(getName(path), state);
        }

        return nodeWriter.writeNode(builder.getNodeState(), getStableIdBytes(uncompacted));
    }

    @CheckForNull
    private static ByteBuffer getStableIdBytes(@Nonnull NodeState node) {
        return node instanceof SegmentNodeState
            ? ((SegmentNodeState) node).getStableIdBytes()
            : null;
    }

    @Nonnull
    private static NodeState getRoot(@Nonnull NodeState node) {
        return node.hasChildNode("root")
            ? node.getChildNode("root")
            : EMPTY_NODE;
    }

    /**
     * Compact a list of uncompacted roots on top of base roots of the same key or
     * an empty node if none.
     */
    @CheckForNull
    private LinkedHashMap<String, NodeState> compact(
            @Nonnull NodeState base,
            @Nonnull LinkedHashMap<String, NodeState> uncompactedRoots,
            @Nonnull NodeState onto)
    throws IOException {
        LinkedHashMap<String, NodeState> compactedRoots = newLinkedHashMap();
        for (Entry<String, NodeState> uncompactedRoot : uncompactedRoots.entrySet()) {
            String path = uncompactedRoot.getKey();
            NodeState uncompacted = uncompactedRoot.getValue();
            Result result = compactWithCache(base, uncompacted, onto, path);
            if (result == null) {
                return null;
            }
            base = result.nextBefore;
            onto = result.nextOnto;
            compactedRoots.put(path, result.compacted);
        }
        return compactedRoots;
    }

    /**
     * Collect a chronologically ordered list of roots for the base and the uncompacted
     * state from a {@code superRoot}. This list consists of all checkpoints followed by
     * the root.
     */
    @Nonnull
    private LinkedHashMap<String, NodeState> collectRoots(@Nullable NodeState superRoot) {
        LinkedHashMap<String, NodeState> roots = newLinkedHashMap();
        if (superRoot != null) {
            List<ChildNodeEntry> checkpoints = newArrayList(
                    superRoot.getChildNode("checkpoints").getChildNodeEntries());

            checkpoints.sort((cne1, cne2) -> {
                long c1 = cne1.getNodeState().getLong("created");
                long c2 = cne2.getNodeState().getLong("created");
                return Long.compare(c1, c2);
            });

            for (ChildNodeEntry checkpoint : checkpoints) {
                String name = checkpoint.getName();
                NodeState node = checkpoint.getNodeState();
                gcListener.info("found checkpoint {} created at {}.",
                    name, new Date(node.getLong("created")));
                roots.put("checkpoints/" + name + "/root", node.getChildNode("root"));
            }
            roots.put("root", superRoot.getChildNode("root"));
        }
        return roots;
    }

    @Nonnull
    private static NodeBuilder getChild(NodeBuilder builder, String path) {
        for (String name : elements(path)) {
            builder = builder.getChildNode(name);
        }
        return builder;
    }

    private static class Result {
            final NodeState compacted;
            final NodeState nextBefore;
            final NodeState nextOnto;

            Result(@Nonnull NodeState compacted, @Nonnull NodeState nextBefore, @Nonnull NodeState nextOnto) {
                this.compacted = compacted;
                this.nextBefore = nextBefore;
                this.nextOnto = nextOnto;
            }
        }

    /**
     * Compact {@code after} against {@code before} on top of {@code onto} unless
     * {@code after} has been compacted before and is found in the cache. In this
     * case the cached version of the previously compacted {@code before} is returned.
     */
    @CheckForNull
    private Result compactWithCache(
            @Nonnull NodeState before,
            @Nonnull NodeState after,
            @Nonnull NodeState onto,
            @Nonnull String path)
    throws IOException {
        gcListener.info("compacting {}.", path);
        NodeState compacted = cpCache.get(after);
        if (compacted == null) {
            compacted = compactor.compact(before, after, onto);
            if (compacted == null) {
                return null;
            } else {
                cpCache.put(after, compacted);
                return new Result(compacted, after, compacted);
            }
        } else {
            gcListener.info("found {} in cache.", path);
            return new Result(compacted, before, onto);
        }
    }

}


text:
package frameless
package functions

import frameless.{TypedAggregate, TypedColumn}
import frameless.functions.aggregate._
import org.apache.spark.sql.{Column, Encoder}
import org.scalacheck.{Gen, Prop}
import org.scalacheck.Prop._

class AggregateFunctionsTests extends TypedDatasetSuite {
  def sparkSchema[A: TypedEncoder, U](f: TypedColumn[X1[A], A] => TypedAggregate[X1[A], U]): Prop = {
    val df = TypedDataset.create[X1[A]](Nil)
    val col = f(df.col('a))

    val sumDf = df.agg(col)

    TypedExpressionEncoder.targetStructType(sumDf.encoder) ?= sumDf.dataset.schema
  }

  test("sum") {
    case class Sum4Tests[A, B](sum: Seq[A] => B)

    def prop[A: TypedEncoder, Out: TypedEncoder : Numeric](xs: List[A])(
      implicit
      summable: CatalystSummable[A, Out],
      summer: Sum4Tests[A, Out]
    ): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)

      val datasetSum: List[Out] = dataset.agg(sum(A)).collect().run().toList

      datasetSum match {
        case x :: Nil => approximatelyEqual(summer.sum(xs), x)
        case other => falsified
      }
    }

    // Replicate Spark's behaviour : Ints and Shorts are cast to Long
    // https://github.com/apache/spark/blob/7eb2ca8/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L37
    implicit def summerDecimal = Sum4Tests[BigDecimal, BigDecimal](_.sum)
    implicit def summerDouble = Sum4Tests[Double, Double](_.sum)
    implicit def summerLong = Sum4Tests[Long, Long](_.sum)
    implicit def summerInt = Sum4Tests[Int, Long](_.map(_.toLong).sum)
    implicit def summerShort = Sum4Tests[Short, Long](_.map(_.toLong).sum)

    check(forAll(prop[BigDecimal, BigDecimal] _))
    check(forAll(prop[Long, Long] _))
    check(forAll(prop[Double, Double] _))
    check(forAll(prop[Int, Long] _))
    check(forAll(prop[Short, Long] _))

    check(sparkSchema[BigDecimal, BigDecimal](sum))
    check(sparkSchema[Long, Long](sum))
    check(sparkSchema[Int, Long](sum))
    check(sparkSchema[Double, Double](sum))
    check(sparkSchema[Short, Long](sum))
  }

  test("sumDistinct") {
    case class Sum4Tests[A, B](sum: Seq[A] => B)

    def prop[A: TypedEncoder, Out: TypedEncoder : Numeric](xs: List[A])(
      implicit
      summable: CatalystSummable[A, Out],
      summer: Sum4Tests[A, Out]
    ): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)

      val datasetSum: List[Out] = dataset.agg(sumDistinct(A)).collect().run().toList

      datasetSum match {
        case x :: Nil => approximatelyEqual(summer.sum(xs), x)
        case other => falsified
      }
    }

    // Replicate Spark's behaviour : Ints and Shorts are cast to Long
    // https://github.com/apache/spark/blob/7eb2ca8/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L37
    implicit def summerLong = Sum4Tests[Long, Long](_.toSet.sum)
    implicit def summerInt = Sum4Tests[Int, Long]( x => x.toSet.map((_:Int).toLong).sum)
    implicit def summerShort = Sum4Tests[Short, Long](x => x.toSet.map((_:Short).toLong).sum)

    check(forAll(prop[Long, Long] _))
    check(forAll(prop[Int, Long] _))
    check(forAll(prop[Short, Long] _))

    check(sparkSchema[Long, Long](sum))
    check(sparkSchema[Int, Long](sum))
    check(sparkSchema[Short, Long](sum))
  }

  test("avg") {
    case class Averager4Tests[A, B](avg: Seq[A] => B)

    def prop[A: TypedEncoder, Out: TypedEncoder : Numeric](xs: List[A])(
      implicit
      averageable: CatalystAverageable[A, Out],
      averager: Averager4Tests[A, Out]
    ): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)

      val datasetAvg: Vector[Out] = dataset.agg(avg(A)).collect().run().toVector

      if (datasetAvg.size > 2) falsified
      else xs match {
        case Nil => datasetAvg ?= Vector()
        case _ :: _ => datasetAvg.headOption match {
          case Some(x) => approximatelyEqual(averager.avg(xs), x)
          case None => falsified
        }
      }
    }

    // Replicate Spark's behaviour : If the datatype isn't BigDecimal cast type to Double
    // https://github.com/apache/spark/blob/7eb2ca8/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Average.scala#L50
    implicit def averageDecimal = Averager4Tests[BigDecimal, BigDecimal](as => as.sum/as.size)
    implicit def averageDouble = Averager4Tests[Double, Double](as => as.sum/as.size)
    implicit def averageLong = Averager4Tests[Long, Double](as => as.map(_.toDouble).sum/as.size)
    implicit def averageInt = Averager4Tests[Int, Double](as => as.map(_.toDouble).sum/as.size)
    implicit def averageShort = Averager4Tests[Short, Double](as => as.map(_.toDouble).sum/as.size)

    check(forAll(prop[BigDecimal, BigDecimal] _))
    check(forAll(prop[Double, Double] _))
    check(forAll(prop[Long, Double] _))
    check(forAll(prop[Int, Double] _))
    check(forAll(prop[Short, Double] _))
  }

  test("stddev and variance") {
    def prop[A: TypedEncoder : CatalystVariance : Numeric](xs: List[A]): Prop = {
      val numeric = implicitly[Numeric[A]]
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)

      val datasetStdOpt = dataset.agg(stddev(A)).collect().run().toVector.headOption
      val datasetVarOpt = dataset.agg(variance(A)).collect().run().toVector.headOption

      val std = sc.parallelize(xs.map(implicitly[Numeric[A]].toDouble)).sampleStdev()
      val `var` = sc.parallelize(xs.map(implicitly[Numeric[A]].toDouble)).sampleVariance()

      (datasetStdOpt, datasetVarOpt) match {
        case (Some(datasetStd), Some(datasetVar)) =>
          approximatelyEqual(datasetStd, std) && approximatelyEqual(datasetVar, `var`)
        case _ => proved
      }
    }

    check(forAll(prop[Short] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Long] _))
    check(forAll(prop[BigDecimal] _))
    check(forAll(prop[Double] _))
  }

  test("litAggr") {
    def prop[A: TypedEncoder, B: TypedEncoder, C: TypedEncoder](xs: List[A], b: B, c: C): Prop = {
      val dataset = TypedDataset.create(xs)
      val (r1, rb, rc, rcount) = dataset.agg(count().lit(1), litAggr(b), litAggr(c), count()).collect().run().head
      (rcount ?= xs.size.toLong) && (r1 ?= 1) && (rb ?= b) && (rc ?= c)
    }

    check(forAll(prop[Boolean, Int, String] _))
    check(forAll(prop[Option[Boolean], Vector[Option[Vector[Char]]], Long] _))
  }

  test("count") {
    def prop[A: TypedEncoder](xs: List[A]): Prop = {
      val dataset = TypedDataset.create(xs)
      val Vector(datasetCount) = dataset.agg(count()).collect().run().toVector

      datasetCount ?= xs.size.toLong
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[Byte] _))
  }

  test("count('a)") {
    def prop[A: TypedEncoder](xs: List[A]): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)
      val datasetCount = dataset.agg(count(A)).collect().run()

      datasetCount ?= List(xs.size.toLong)
    }

    check(forAll(prop[Int] _))
    check(forAll(prop[Byte] _))
  }

  test("max") {
    def prop[A: TypedEncoder: CatalystOrdered](xs: List[A])(implicit o: Ordering[A]): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)
      val datasetMax = dataset.agg(max(A)).collect().run().toList

      datasetMax ?= xs.reduceOption(o.max).toList
    }

    check(forAll(prop[Long] _))
    check(forAll(prop[Double] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[Byte] _))
    check(forAll(prop[String] _))
  }

  test("max with follow up multiplication") {
    def prop(xs: List[Long]): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[Long]('a)
      val datasetMax = dataset.agg(max(A) * 2).collect().run().headOption

      datasetMax ?= (if(xs.isEmpty) None else Some(xs.max * 2))
    }

    check(forAll(prop _))
  }

  test("min") {
    def prop[A: TypedEncoder: CatalystOrdered](xs: List[A])(implicit o: Ordering[A]): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)

      val datasetMin = dataset.agg(min(A)).collect().run().toList

      datasetMin ?= xs.reduceOption(o.min).toList
    }

    check(forAll(prop[Long] _))
    check(forAll(prop[Double] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[Byte] _))
    check(forAll(prop[String] _))
  }

  test("first") {
    def prop[A: TypedEncoder](xs: List[A]): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)

      val datasetFirst = dataset.agg(first(A)).collect().run().toList

      datasetFirst ?= xs.headOption.toList
    }

    check(forAll(prop[BigDecimal] _))
    check(forAll(prop[Long] _))
    check(forAll(prop[Double] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[Byte] _))
    check(forAll(prop[String] _))
  }

  test("last") {
    def prop[A: TypedEncoder](xs: List[A]): Prop = {
      val dataset = TypedDataset.create(xs.map(X1(_)))
      val A = dataset.col[A]('a)

      val datasetLast = dataset.agg(last(A)).collect().run().toList

      datasetLast ?= xs.lastOption.toList
    }

    check(forAll(prop[BigDecimal] _))
    check(forAll(prop[Long] _))
    check(forAll(prop[Double] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[Byte] _))
    check(forAll(prop[String] _))
  }

  // Generator for simplified and focused aggregation examples
  def getLowCardinalityKVPairs: Gen[Vector[(Int, Int)]] = {
    val kvPairGen: Gen[(Int, Int)] = for {
      k <- Gen.const(1) // key
      v <- Gen.choose(10, 100) // values
    } yield (k, v)

    Gen.listOfN(200, kvPairGen).map(_.toVector)
  }

  test("countDistinct") {
    check {
      forAll(getLowCardinalityKVPairs) { xs: Vector[(Int, Int)] =>
        val tds = TypedDataset.create(xs)
        val tdsRes: Seq[(Int, Long)] = tds.groupBy(tds('_1)).agg(countDistinct(tds('_2))).collect().run()
        tdsRes.toMap ?= xs.groupBy(_._1).mapValues(_.map(_._2).distinct.size.toLong).toSeq.toMap
      }
    }
  }

  test("approxCountDistinct") {
    // Simple version of #approximatelyEqual()
    // Default maximum estimation error of HyperLogLog in Spark is 5%
    def approxEqual(actual: Long, estimated: Long, allowedDeviationPercentile: Double = 0.05): Boolean = {
      val delta: Long = Math.abs(actual - estimated)
      delta / actual.toDouble < allowedDeviationPercentile * 2
    }

    check {
      forAll(getLowCardinalityKVPairs) { xs: Vector[(Int, Int)] =>
        val tds = TypedDataset.create(xs)
        val tdsRes: Seq[(Int, Long, Long)] =
          tds.groupBy(tds('_1)).agg(countDistinct(tds('_2)), approxCountDistinct(tds('_2))).collect().run()
        tdsRes.forall { case (_, v1, v2) => approxEqual(v1, v2) }
      }
    }

    check {
      forAll(getLowCardinalityKVPairs) { xs: Vector[(Int, Int)] =>
        val tds = TypedDataset.create(xs)
        val allowedError = 0.1 // 10%
        val tdsRes: Seq[(Int, Long, Long)] =
          tds.groupBy(tds('_1)).agg(countDistinct(tds('_2)), approxCountDistinct(tds('_2), allowedError)).collect().run()
        tdsRes.forall { case (_, v1, v2) => approxEqual(v1, v2, allowedError) }
      }
    }
  }

  test("collectList") {
    def prop[A: TypedEncoder : Ordering](xs: List[X2[A, A]]): Prop = {
      val tds = TypedDataset.create(xs)
      val tdsRes: Seq[(A, Vector[A])] = tds.groupBy(tds('a)).agg(collectList(tds('b))).collect().run()

      tdsRes.toMap.mapValues(_.sorted) ?= xs.groupBy(_.a).mapValues(_.map(_.b).toVector.sorted)
    }

    check(forAll(prop[Long] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Byte] _))
    check(forAll(prop[String] _))
  }

  test("collectSet") {
    def prop[A: TypedEncoder : Ordering](xs: List[X2[A, A]]): Prop = {
      val tds = TypedDataset.create(xs)
      val tdsRes: Seq[(A, Vector[A])] = tds.groupBy(tds('a)).agg(collectSet(tds('b))).collect().run()

      tdsRes.toMap.mapValues(_.toSet) ?= xs.groupBy(_.a).mapValues(_.map(_.b).toSet)
    }

    check(forAll(prop[Long] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Byte] _))
    check(forAll(prop[String] _))
  }

  test("lit") {
    def prop[A: TypedEncoder](xs: List[X1[A]], l: A): Prop = {
      val tds = TypedDataset.create(xs)
      tds.select(tds('a), lit(l)).collect().run() ?= xs.map(x => (x.a, l))
    }

    check(forAll(prop[Long] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Vector[Vector[Int]]] _))
    check(forAll(prop[Byte] _))
    check(forAll(prop[Vector[Byte]] _))
    check(forAll(prop[String] _))
    check(forAll(prop[Vector[Long]] _))
    check(forAll(prop[BigDecimal] _))
  }

  def bivariatePropTemplate[A: TypedEncoder, B: TypedEncoder]
  (
    xs: List[X3[Int, A, B]]
  )
  (
    framelessFun: (TypedColumn[X3[Int, A, B], A], TypedColumn[X3[Int, A, B], B]) => TypedAggregate[X3[Int, A, B], Option[Double]],
    sparkFun: (Column, Column) => Column
  )
  (
    implicit
    encEv: Encoder[(Int, A, B)],
    encEv2: Encoder[(Int,Option[Double])],
    evCanBeDoubleA: CatalystCast[A, Double],
    evCanBeDoubleB: CatalystCast[B, Double]
  ): Prop = {

    val tds = TypedDataset.create(xs)
    // Typed implementation of bivar stats function
    val tdBivar = tds.groupBy(tds('a)).agg(framelessFun(tds('b), tds('c))).deserialized.map(kv =>
      (kv._1, kv._2.flatMap(DoubleBehaviourUtils.nanNullHandler))
    ).collect().run()

    val cDF = session.createDataset(xs.map(x => (x.a, x.b, x.c)))
    // Comparison implementation of bivar stats functions
    val compBivar = cDF
      .groupBy(cDF("_1"))
      .agg(sparkFun(cDF("_2"), cDF("_3")))
      .map(
        row => {
          val grp = row.getInt(0)
          (grp, DoubleBehaviourUtils.nanNullHandler(row.get(1)))
        }
      )

    // Should be the same
    tdBivar.toMap ?= compBivar.collect().toMap
  }

  def univariatePropTemplate[A: TypedEncoder]
  (
    xs: List[X2[Int, A]]
  )
  (
    framelessFun: (TypedColumn[X2[Int, A], A]) => TypedAggregate[X2[Int, A], Option[Double]],
    sparkFun: (Column) => Column
  )
  (
    implicit
    encEv: Encoder[(Int, A)],
    encEv2: Encoder[(Int,Option[Double])],
    evCanBeDoubleA: CatalystCast[A, Double]
  ): Prop = {

    val tds = TypedDataset.create(xs)
    //typed implementation of univariate stats function
    val tdUnivar = tds.groupBy(tds('a)).agg(framelessFun(tds('b))).deserialized.map(kv =>
      (kv._1, kv._2.flatMap(DoubleBehaviourUtils.nanNullHandler))
    ).collect().run()

    val cDF = session.createDataset(xs.map(x => (x.a, x.b)))
    // Comparison implementation of bivar stats functions
    val compUnivar = cDF
      .groupBy(cDF("_1"))
      .agg(sparkFun(cDF("_2")))
      .map(
        row => {
          val grp = row.getInt(0)
          (grp, DoubleBehaviourUtils.nanNullHandler(row.get(1)))
        }
      )

    // Should be the same
    tdUnivar.toMap ?= compUnivar.collect().toMap
  }

  test("corr") {
    val spark = session
    import spark.implicits._

    def prop[A: TypedEncoder, B: TypedEncoder](xs: List[X3[Int, A, B]])(
      implicit
      encEv: Encoder[(Int, A, B)],
      evCanBeDoubleA: CatalystCast[A, Double],
      evCanBeDoubleB: CatalystCast[B, Double]
    ): Prop = bivariatePropTemplate(xs)(corr[A,B,X3[Int, A, B]],org.apache.spark.sql.functions.corr)

    check(forAll(prop[Double, Double] _))
    check(forAll(prop[Double, Int] _))
    check(forAll(prop[Int, Int] _))
    check(forAll(prop[Short, Int] _))
    check(forAll(prop[BigDecimal, Byte] _))
  }

  test("covar_pop") {
    val spark = session
    import spark.implicits._

    def prop[A: TypedEncoder, B: TypedEncoder](xs: List[X3[Int, A, B]])(
      implicit
      encEv: Encoder[(Int, A, B)],
      evCanBeDoubleA: CatalystCast[A, Double],
      evCanBeDoubleB: CatalystCast[B, Double]
    ): Prop = bivariatePropTemplate(xs)(
      covarPop[A, B, X3[Int, A, B]],
      org.apache.spark.sql.functions.covar_pop
    )

    check(forAll(prop[Double, Double] _))
    check(forAll(prop[Double, Int] _))
    check(forAll(prop[Int, Int] _))
    check(forAll(prop[Short, Int] _))
    check(forAll(prop[BigDecimal, Byte] _))
  }

  test("covar_samp") {
    val spark = session
    import spark.implicits._

    def prop[A: TypedEncoder, B: TypedEncoder](xs: List[X3[Int, A, B]])(
      implicit
      encEv: Encoder[(Int, A, B)],
      evCanBeDoubleA: CatalystCast[A, Double],
      evCanBeDoubleB: CatalystCast[B, Double]
    ): Prop = bivariatePropTemplate(xs)(
      covarSamp[A, B, X3[Int, A, B]],
      org.apache.spark.sql.functions.covar_samp
    )

    check(forAll(prop[Double, Double] _))
    check(forAll(prop[Double, Int] _))
    check(forAll(prop[Int, Int] _))
    check(forAll(prop[Short, Int] _))
    check(forAll(prop[BigDecimal, Byte] _))
  }

  test("kurtosis") {
    val spark = session
    import spark.implicits._

    def prop[A: TypedEncoder](xs: List[X2[Int, A]])(
      implicit
      encEv: Encoder[(Int, A)],
      evCanBeDoubleA: CatalystCast[A, Double]
    ): Prop = univariatePropTemplate(xs)(
      kurtosis[A, X2[Int, A]],
      org.apache.spark.sql.functions.kurtosis
    )

    check(forAll(prop[Double] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[BigDecimal] _))
    check(forAll(prop[Byte] _))
  }

  test("skewness") {
    val spark = session
    import spark.implicits._

    def prop[A: TypedEncoder](xs: List[X2[Int, A]])(
      implicit
      encEv: Encoder[(Int, A)],
      evCanBeDoubleA: CatalystCast[A, Double]
    ): Prop = univariatePropTemplate(xs)(
      skewness[A, X2[Int, A]],
      org.apache.spark.sql.functions.skewness
    )

    check(forAll(prop[Double] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[BigDecimal] _))
    check(forAll(prop[Byte] _))
  }

  test("stddev_pop") {
    val spark = session
    import spark.implicits._

    def prop[A: TypedEncoder](xs: List[X2[Int, A]])(
      implicit
      encEv: Encoder[(Int, A)],
      evCanBeDoubleA: CatalystCast[A, Double]
    ): Prop = univariatePropTemplate(xs)(
      stddevPop[A, X2[Int, A]],
      org.apache.spark.sql.functions.stddev_pop
    )

    check(forAll(prop[Double] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[BigDecimal] _))
    check(forAll(prop[Byte] _))
  }

  test("stddev_samp") {
    val spark = session
    import spark.implicits._

    def prop[A: TypedEncoder](xs: List[X2[Int, A]])(
      implicit
      encEv: Encoder[(Int, A)],
      evCanBeDoubleA: CatalystCast[A, Double]
    ): Prop = univariatePropTemplate(xs)(
      stddevSamp[A, X2[Int, A]],
      org.apache.spark.sql.functions.stddev_samp
    )
    check(forAll(prop[Double] _))
    check(forAll(prop[Int] _))
    check(forAll(prop[Short] _))
    check(forAll(prop[BigDecimal] _))
    check(forAll(prop[Byte] _))
  }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

          <title>AppendedClues - ScalaTest 2.1.5 - org.scalatest.AppendedClues</title>
          <meta name="description" content="AppendedClues - ScalaTest 2.1.5 - org.scalatest.AppendedClues" />
          <meta name="keywords" content="AppendedClues ScalaTest 2.1.5 org.scalatest.AppendedClues" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

org.scalatest

AppendedClues

        trait

        AppendedClues extends AnyRef

Trait providing an implicit conversion that allows clues to be placed after a block of code.

You can use the withClue construct provided by Assertions, which is
extended by every style trait in ScalaTest, to add extra information to reports of failed or canceled tests.
The withClue from Assertions places the "clue string" at the front, both
in the code and in the resulting message:

withClue("This is a prepended clue;") {
  1 + 1 should equal (3)
}

The above expression will yield the failure message:

This is a prepended clue; 2 did not equal 3

If you mix in this trait, or import its members via its companion object, you can alternatively place
the clue string at the end, like this:

{ 1 + 1 should equal (3) } withClue "now the clue comes after"

The above expression will yield the failure message:

2 did not equal 3 now the clue comes after

If no space is already present, either at the beginning of the clue string or at the end
of the current message, a space will be placed between the two, unless the clue string
starts with one of the punctuation characters: comma (,), period (.),
or semicolon (;). For example, the failure message in the above example
includes an extra space inserted between 3 and now.

By contrast this code, which has a clue string starting with comma:

{ 1 + 1 should equal (3) } withClue ", now the clue comes after"

Will yield a failure message with no extra inserted space:

2 did not equal 3, now the clue comes after

The withClue method will only append the clue string to the detail
message of exception types that mix in the ModifiableMessage trait.
See the documentation for ModifiableMessage for more
information.

Note: the reason this functionality is not provided by Assertions directly, like the
prepended withClue construct, is because appended clues require an implicit conversion.
ScalaTest only gives you one implicit conversion by default in any test class to minimize the
potential for conflicts with other implicit conversions you may be using. All other implicit conversions,
including the one provided by this trait, you must explicitly invite into your code through inheritance
or an import.

Source

AppendedClues.scala

          Linear Supertypes

AnyRef, Any

          Known Subclasses

AppendedClues

<input id="mbrsel-input" type="text" accesskey="/" />

              Ordering

Alphabetic

By inheritance

                Inherited

AppendedClues

AnyRef

Any

Hide All

Show all

            Learn more about member selection

            Visibility

Public

All

Type Members

        class

        Clueful[T] extends AnyRef

Class that provides a withClue method that appends clue strings to any
ModifiableMessage exception
thrown by the passed by-name parameter.

Value Members

        final
        def

        !=(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

Any

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        final
        def

        ==(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

Any

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws()

        implicit
        def

        convertToClueful[T](fun: ⇒ T): Clueful[T]

Implicit conversion that allows clues to be place after a block of code.

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        def

        toString(): String

Definition Classes

AnyRef → Any

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws()

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws()

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
<?php

namespace FlowrouteMessagingLib\Controllers;

use FlowrouteMessagingLib\APIException;
use FlowrouteMessagingLib\APIHelper;
use FlowrouteMessagingLib\Configuration;
use Unirest\Unirest;

class MessagesController {

    /* private fields for configuration */

    /**
     * Tech Prefix
     * @var string
     */
    private $username;

    /**
     * API Secret Key
     * @var string
     */
    private $password;

    /**
     * Constructor with authentication and configuration parameters
     */
    function __construct($username=null, $password=null)
    {
        $this->username = $username ? $username : Configuration::$username;
        $this->password = $password ? $password : Configuration::$password;
    }

    /**
     * Send a message
     * @param  Message     $message     Required parameter: Message Object to send.
     * @return string response from the API call
     * @throws APIException
     **/
    function createMessage($message)
    {
        //the base uri for api requests
        $queryBuilder = Configuration::$BASEURI;

        //prepare query string for API call
        $queryBuilder = $queryBuilder.'/messages';

        //validate and preprocess url
        $queryUrl = APIHelper::cleanUrl($queryBuilder);

        //prepare headers
        $headers = array (
            'user-agent'    => 'Flowroute Messaging SDK 1.0',
            'content-type'  => 'application/json; charset=utf-8'
        );

        //prepare API request
        $request = Unirest::post($queryUrl, $headers, json_encode($message), $this->username, $this->password);

        //and invoke the API call request to fetch the response
        $response = Unirest::getResponse($request);

        //Error handling using HTTP status codes
        if ($response->code == 401) {
            throw new APIException('UNAUTHORIZED', 401, $response->body);
        }

        else if ($response->code == 403) {
            throw new APIException('FORBIDDEN', 403, $response->body);
        }

        else if (($response->code < 200) || ($response->code > 206)) { //[200,206] = HTTP OK
            throw new APIException("HTTP Response Not OK", $response->code, $response->body);
        }

        return $response->body;
    }

    /**
     * Lookup a Message by MDR
     * @param  string     $recordId      Required parameter: Unique MDR ID
     * @return string response from the API call
     * @throws APIException
     **/
    function getMessageLookup($recordId)
    {
        //the base uri for api requests
        $queryBuilder = Configuration::$BASEURI;

        //prepare query string for API call
        $queryBuilder = $queryBuilder.'/messages/{record_id}';

        //process optional query parameters
        APIHelper::appendUrlWithTemplateParameters($queryBuilder, array (
            'record_id' => $recordId,
        ));

        //validate and preprocess url
        $queryUrl = APIHelper::cleanUrl($queryBuilder);

        //prepare headers
        $headers = array (
            'user-agent' => 'Flowroute Messaging SDK 1.0'
        );

        //prepare API request
        $request = Unirest::get($queryUrl, $headers, NULL, $this->username, $this->password);

        //and invoke the API call request to fetch the response
        $response = Unirest::getResponse($request);

        //Error handling using HTTP status codes
        if (($response->code < 200) || ($response->code > 206)) { //[200,206] = HTTP OK
            throw new APIException("HTTP Response Not OK", $response->code, $response->body);
        }

        return $response->body;
    }

}


text:
namespace llvm {
  class Type;
  class SMDiagnostic;
  class SourceMgr;
  class LLVMContext;

  class LLLexer {
    const char *CurPtr;
    StringRef CurBuf;
    SMDiagnostic &ErrorInfo;
    SourceMgr &SM;
    LLVMContext &Context;

    // Information about the current token.
    const char *TokStart;
    lltok::Kind CurKind;
    std::string StrVal;
    unsigned UIntVal;
    Type *TyVal;
    APFloat APFloatVal;
    APSInt  APSIntVal;

    // When false (default), an identifier ending in ':' is a label token.
    // When true, the ':' is treated as a separate token.
    bool IgnoreColonInIdentifiers;

  public:
    explicit LLLexer(StringRef StartBuf, SourceMgr &SM, SMDiagnostic &,
                     LLVMContext &C);

    lltok::Kind Lex() {
      return CurKind = LexToken();
    }

    typedef SMLoc LocTy;
    LocTy getLoc() const { return SMLoc::getFromPointer(TokStart); }
    lltok::Kind getKind() const { return CurKind; }
    const std::string &getStrVal() const { return StrVal; }
    Type *getTyVal() const { return TyVal; }
    unsigned getUIntVal() const { return UIntVal; }
    const APSInt &getAPSIntVal() const { return APSIntVal; }
    const APFloat &getAPFloatVal() const { return APFloatVal; }

    void setIgnoreColonInIdentifiers(bool val) {
      IgnoreColonInIdentifiers = val;
    }

    bool Error(LocTy ErrorLoc, const Twine &Msg) const;
    bool Error(const Twine &Msg) const { return Error(getLoc(), Msg); }

    void Warning(LocTy WarningLoc, const Twine &Msg) const;
    void Warning(const Twine &Msg) const { return Warning(getLoc(), Msg); }

  private:
    lltok::Kind LexToken();

    int getNextChar();
    void SkipLineComment();
    lltok::Kind ReadString(lltok::Kind kind);
    bool ReadVarName();

    lltok::Kind LexIdentifier();
    lltok::Kind LexDigitOrNegative();
    lltok::Kind LexPositive();
    lltok::Kind LexAt();
    lltok::Kind LexDollar();
    lltok::Kind LexExclaim();
    lltok::Kind LexPercent();
    lltok::Kind LexUIntID(lltok::Kind Token);
    lltok::Kind LexVar(lltok::Kind Var, lltok::Kind VarID);
    lltok::Kind LexQuote();
    lltok::Kind Lex0x();
    lltok::Kind LexHash();
    lltok::Kind LexCaret();

    uint64_t atoull(const char *Buffer, const char *End);
    uint64_t HexIntToVal(const char *Buffer, const char *End);
    void HexToIntPair(const char *Buffer, const char *End, uint64_t Pair[2]);
    void FP80HexToIntPair(const char *Buffer, const char *End, uint64_t Pair[2]);
  };
} // end namespace llvm

#endif


text:
<?php

namespace Graze\UnicontrollerClient\Parser\Parser;

use Graze\UnicontrollerClient\Parser\Parser\AbstractParser;
use Graze\UnicontrollerClient\Parser\Parser\ParserInterface;
use Graze\UnicontrollerClient\Entity\Entity\EntityVarPrompt;

class ParserVarPrompt extends AbstractParser implements ParserInterface
{
    /**
     * @return []
     */
    protected function getProperties()
    {
        return [
            'name',
            'prompt',
            'length',
            'inputType',
            'jumpSpecial',
            'cPadding',
            'mask'
        ];
    }

    /**
     * @return EntityVarPrompt
     */
    protected function getEntity()
    {
        return new EntityVarPrompt();
    }
}


text:
import { PropertyPath } from '../../fluent';
import { Command } from '../Command';
import { CommandType } from '../CommandType';

export class SelectCommand extends Command {
  columns: PropertyPath[];
  mentions: PropertyPath[];
  expression: (expression: any) => any;

  constructor() {
    super(CommandType.Select);
  }
}


text:
static void   simple_pointer_test()
{
   struct mulle_buffer   *buffer;
   void                  *pointer;

   buffer = mulle_buffer_create( NULL);

   mulle_sprintf( buffer, "%p", (void *) 0x12345678); // some pointer
   mulle_buffer_add_byte( buffer, 0);
   sscanf( mulle_buffer_get_bytes( buffer), "%p", &pointer);
   mulle_buffer_reset( buffer);

   if( pointer != (void *) 0x12345678)
      printf( "pointer mismatch\n");

   mulle_buffer_destroy( buffer);
}

int  main()
{
   mulle_testallocator_set_tracelevel( 1);
   mulle_testallocator_initialize();

   mulle_default_allocator = mulle_testallocator;

   simple_pointer_test();

   mulle_sprintf_free_storage();
   mulle_testallocator_reset();

   return( 0);
}


text:
Originally published: 2011-06-21 09:11:18
Last updated: 2011-06-21 09:11:19
Author: Filippo Squillace

From the previous recipe http://code.activestate.com/recipes/577764-combinations-of-a-sequence-without-replacement-usi/ we can easily build a generator that return all the K-combinations without replacement.


text:
/**
     * Stacked Bar Chart Graph Directive
     * @memberOf innoApp
     * @ngdoc directive
     * @scope filters
     * @format HTML  - <stackedbar-chart ></stackedbar-chart>
     * @format DATA - { title: 'Title', data: [ dataPoints: [ {indexLabel: 'label', 'y': point} ] ] }
     * @author Akshay Kasliwal
     */

    innoApp.directive('groupedStackedbargraph', function($compile, $timeout) {
      return {

        restrict: 'E',
        scope: {
          data: '='
        },

        link: function(scope, oElement, attrs) {
          var graphname = attrs.graphname;

          if(graphname === 'salesfigures'){
            groupslegend = false;
            chartwidth=36;
          }else{
            groupslegend = ['Cash Discount (LY)', 'Ac Returns (LY)','Discounts (LY)','Mand. Discounts (LY)','Adjustments (LY)'];
            chartwidth=24;
          }

          if(graphname === 'salesfigures'){
            scope.salesfiguredata = scope.$parent.salesfigureData.chart;
            var salesfigureGraphdata = [];
            var categories  = [];
            var colorPatern = [];
            var groups = [];
            var bindId = attrs.id;
            document.getElementById(bindId).value = JSON.stringify(scope.$parent.salesfigureData.tooltip);
           $compile(oElement.contents())(scope.$new());

              salesfigureGraphdata = scope.salesfiguredata;

              var graphdata = new Array(salesfigureGraphdata.data.length);
              for(var i = 0 ; i< salesfigureGraphdata.data.length; i++){
                graphdata[i]= new Array(salesfigureGraphdata.data[i].data.length+1);
              }

              for(var i = 0; i< salesfigureGraphdata.data.length; i++){
                 graphdata[i][0] = salesfigureGraphdata.data[i].title;
                 for(var j=1; j<=salesfigureGraphdata.data[i].data.length; j++){
                   graphdata[i][j] = salesfigureGraphdata.data[i].data[j-1];
                 }
              }
              categories = salesfigureGraphdata.categories;
              colorPatern = ["#B2B3B3", "#CFD0D0", "#0066B3", "#1dbecf"];
              groups = [
                ['Net Sales(LY)', 'Discounts & Returns (LY)'],
                ['Net Sales', 'Discounts & Returns']
              ];
              groups1 = [
                'Net Sales(LY)', 'Discounts & Returns (LY)','Net Sales', 'Discounts & Returns'
              ];
          }else if(graphname === 'breakupofdiscounts'){
            scope.breakupdiscdata = scope.$parent.breakupofdiscountsdata.data.chart;
            var breakupGraphdata = [];
            var categories  = [];
            var colorPatern = [];
            var groups = [];
            var bindId = attrs.id;
            document.getElementById(bindId).value = JSON.stringify(scope.$parent.salesfigureData.tooltip);
            $compile(oElement.contents())(scope.$new());

              breakupGraphdata = scope.breakupdiscdata;

              var graphdata = new Array(breakupGraphdata.data.length);
              for(var i = 0 ; i< breakupGraphdata.data.length; i++){
                graphdata[i]= new Array(breakupGraphdata.data[i].data.length+1);
              }

              for(var i = 0; i< breakupGraphdata.data.length; i++){
                 graphdata[i][0] = breakupGraphdata.data[i].title;
                 for(var j=1; j<=breakupGraphdata.data[i].data.length; j++){
                   graphdata[i][j] = breakupGraphdata.data[i].data[j-1];
                 }
              }
              categories = breakupGraphdata.categories;
              colorPatern = ['#A1A2A2','#C3C4C4','#D8D9D9','#E4E5E5','#eaebeb','#522f91','#ee3897','#009a5b','#ffcb08','#ed1a3b'];
              groups = [
                ['Cash Discount (LY)', 'Ac Returns (LY)','Discounts (LY)','Mand. Discounts (LY)','Adjustments (LY)'],
                ['Cash Discount', 'Ac Returns','Discounts','Mand. Discounts','Adjustments']
              ];
              groups1 = [
                'Cash Discount', 'Ac Returns','Discounts','Mand. Discounts','Adjustments'
              ];
          }

          var chart = c3.generate({
            bindto:'#'+bindId,
            data: {
              columns: graphdata,
              type: 'bar',
              groups: groups,
              order: 'asc'
            },
            bar: {
              width: chartwidth
            },
            legend: {
              show: false
              //or hide: 'data1'
              //or hide: ['data1', 'data2']
            },
            color: {
              pattern: colorPatern
            },
            axis: {
              x: {
                type: 'category',
                categories : categories,
                // padding: {
                //   left: 40,
                //   right: 40,
                // }

              //  categories: ['Nov\'14', 'Dec\'14', 'Jan\'15', 'Feb\'15', 'Mar\'15', 'Apr\'15', 'May\'15', 'June\'15', 'Jul\'15', 'Aug\'15', 'Sept\'15', 'Oct\'15']
              },
              y:{
                show:false
              }
            },
            tooltip: {
             format: {
                 title: function (d) {
                     var format = d3.time.format('%d/%m/%Y');
                     return format(d)
                 }
             },
            grouped: true,
            position: function (data, width, height, element) {
              // var chartOffsetX = document.querySelector("#breakupgraph").getBoundingClientRect().left,
              // graphOffsetX = document.querySelector("#breakupgraph g.c3-axis-y").getBoundingClientRect().right,
              // tooltipWidth = document.getElementById('tooltip').parentNode.clientWidth,
              // x = (parseInt(element.getAttribute('cx')) ) + graphOffsetX - chartOffsetX - Math.floor(tooltipWidth/2),
              // y = element.getAttribute('cy');
               tmptooltip=document.getElementById('tooltip'),
              tooltipWidth = $(tmptooltip).width(),
              x =(parseInt(element.getAttribute('x')) )
              y = 0;
              var dt =$(element).closest('svg').next().children();
              var offset=Number(element.getBoundingClientRect().left.toFixed(0));
               if(window.innerWidth < (offset+$(dt).width()+10) ){
                 x = x - ((x + tooltipWidth) - $(element).closest('svg').width());
                 $(element).closest('svg').next().children().addClass('arrow-right');
               }
              return {top: y, left: x}
            },
           contents: function (data, defaultTitleFormat, defaultValueFormat, color) {
             var cal =this.api.categories();
             var text, i, value;
             var $$ = this, config = $$.config,
             titleFormat = defaultTitleFormat,
             title=titleFormat(data[0].x),
             tmptooltip = JSON.parse($(this.config.bindto).val()),
             optarget = tmptooltip.OPTarget,
             performancetotarget = tmptooltip.PerformanceToTarget,
             grosssalesharetotal,grosssalesply,netsalesharetotal,netsalesply,
             currentpos =cal.indexOf(title);
             $.each(tmptooltip.data,function(ind,obj){
               if(obj.title == "Gross Sales"){
                 grosssalesharetotal=obj.data.shareOfTotal[currentpos];
                 grosssalesply=obj.data.vsSply[currentpos];
               }else if(obj.title == "Net Sales"){
                 netsalesharetotal=obj.data.shareOfTotal[currentpos];
                 netsalesply=obj.data.vsSply[currentpos];
               }
             });

             var text = "
"
                         +"
"
                         +"
"
                         +"
"
                         +"
OP Traget
"
                         +"
Performance to Target
"
                         +"
"
                         +"
"
                         + "
$ " +optarget+"
"
                         + "
"+performancetotarget+"
"
                         +"
"
                         +"

"
                         +"
"
                           +"
"
                             +"
"
                               +"

"
                               +"
Gross Sales
"
                               +"
Net Sales
"
                             +"
"
                             +"
"
                               +"
% Share of Total
"
                               +"
"+grosssalesharetotal+"%
"
                               +"
"+netsalesharetotal+"%
"
                             +"
"
                             +"
"
                               +"
vs SPLY
"
                               +"
"+grosssalesply+"%
"
                               +"
"+netsalesply+"%
"
                             +"
"
                           +"
"
                         +"
"
              text += "
";
             return text;
            }
            }

          });
        function toggle(id) {
            chart.toggle(id);
        }

      d3.select('#'+bindId).insert('div', '.chart').attr('class', 'legend').selectAll('span')
        .data(groups1)
      .enter().append('div').attr('class','legend-item').append('span')
        .attr('data-id', function (id) { return id; })
        .html(function (id) { return id; })
        .each(function (id) {
            var data  = d3.select(this)[0][0];
            var newItem = document.createElement("label");
             newItem.style.backgroundColor =chart.color(id);
            data.parentElement.insertBefore(newItem,data);

            //d3.select(this).style('background-color', chart.color(id));
        })
        .on('mouseover', function (id) {
            chart.focus(id);
        })
        .on('mouseout', function (id) {
            chart.revert();
        })
        .on('click', function (id) {
            $(this).parent().toggleClass('disabled');
            chart.toggle(id);
        });
        }
      };
    });


text:
package vnmr.util;

import javax.swing.*;
import java.awt.*;
import java.beans.*;
import java.awt.event.*;

/**********************************************************

 * Summary: Modal Entry Dialog Base Class with OK, Cancel & Help
 *
 *   What it this:
 *	This is a generic Modal Dialog Base Class which has Three buttons
 *	across the bottom as standard fixtures. They are left to right
 *	OK, Cancel and Help.  It also has a message and an input text area.
 *	This Class extends JDialog and thus is treated much like
 *	any JDialog with the exception of the standard buttons and the
 *	fact that it is fixed as modal.
 *
 *	The user can navigate from button to button using the 'tab' key
 *	and then hitting a 'return' will activate that button.
 *	The focus is set up such that typing anyplace, anytime in the
 *	dialog will direct focus to the text item.
 *	If tab has not been clicked to move the focus, 'return' will
 *	activate the 'OK' button.
 *	If the 'ESC' key is hit it activates the 'Cancel' button.
 *   How to use it:
 *	Create one of these Like the following:
 *		ModalEntryDialog med = new ModalEntryDialog(
 *					   "My Dialog Title",
 *					   "My Question for the User");
 *	Then call the following command to get the results:
 *		String results = med.showDialogAndGetValue(Button_clicked);
 *
 *	Where Button_clicked is the component which activated this
 *	entry dialog.  This will place the dialog on top of this
 *	component so the user does not have to move the mouse to find it.
 *
 *	Then dispose of this dialog when you are finished with:
 *		med.dispose();
 *	OR
 *	Create a single instance of this dialog box, and just call
 *	showDialogAndGetValue() each time you need to display it.
 *
 *	If the user clicks Cancel, results = null
 *	If the user clicks Help,   results = null
 *	If the user clicks OK,	   results = the contents of the text field
 *
 *

 **********************************************************/
public class ModalEntryDialog extends ModalDialog implements ActionListener,
                                         PropertyChangeListener,
                                         KeyListener {
    /** Text input Field */
    protected JTextField inputText;
    /** Text from User */
    protected String userText=null;
    /* Panel to hold the three standard buttons. */
    protected JPanel panelForText;
    /* Message */
    protected JLabel messageText;

    /**************************************************

     * Summary: Constructor, Add label and text fields to dialog box
     *

 **************************************************/
    public ModalEntryDialog(String title, String message)
    {
        this(title, message, "");
    }

    public ModalEntryDialog(String title, String message, String helpFile) {
        super(title);
        m_strHelpFile = helpFile;

        // Make a panel for the text items
        GridLayoutCol mgr = new GridLayoutCol(0, 1, 10, 10);
        panelForText = new JPanel(mgr);
        // It looks better with a border
        panelForText.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

        // Create the two items.
        messageText = new JLabel (message);
        inputText = new JTextField (20);

        // Add items to panel
        panelForText.add(messageText);
        panelForText.add(inputText);

        // Add the panel top of the dialog.
        getContentPane().add(panelForText, BorderLayout.NORTH);

        // Set the buttons and the text item up with Listeners
        okButton.addActionListener(this);
        okButton.setActionCommand("ok");
        cancelButton.setActionCommand("cancel");
        cancelButton.addActionListener(this);
        helpButton.setActionCommand("help");
        helpButton.addActionListener(this);
        inputText.setActionCommand("text");
        inputText.addActionListener(this);
        inputText.addKeyListener(this);

        // Start OK disabled until something has been entered.
        okButton.setEnabled(false);

        setBgColor(Util.getBgColor());
        DisplayOptions.addChangeListener(this);

        // Make the frame fit its contents.
        pack();
    }

    public void propertyChange(PropertyChangeEvent evt)
    {
	setBgColor(Util.getBgColor());
    }

    protected void setBgColor(Color bgColor)
    {
	setBackgroundColor(bgColor);

	panelForText.setBackground(bgColor);
	messageText.setBackground(bgColor);
	inputText.setBackground(bgColor);
	messageText.setBackground(bgColor);
    }

    /**************************************************

     * Summary: Listener for all buttons and the text field.
     *
     *

 **************************************************/
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        // OK
        if(cmd.equals("ok")) {
            userText =inputText.getText();
            setVisible(false);
        }
        // Cancel
        else if(cmd.equals("cancel")) {
            userText = null;
            setVisible(false);
        }
        // Help
        else if(cmd.equals("help")) {
	    // Do not call setVisible(false);  That will cause
	    // the Block to release and the code which create
	    // this object will try to use userText.  This way
	    // the panel stays up and the Block stays in effect.
            userText = null;
            //Messages.postError("Help Not Implemented Yet");
            displayHelp();
        }
        // Text Field
        else if(cmd.equals("text")) {
            // Have a return do the same as clicking ok.
            okButton.doClick();
        }
    }

    /**************************************************

     * Summary: Catch any key pressed.
     *
     *    Since we extend ModalDialog and ModalDialog implements KeyListener,
     *	  ModalEntryDialog is a KeyListener.  ModalDialog has already
     *    called addKeyListener(), so we do not want to call it again,
     *    else we add the listener twice.  Here we just override ModalDialog's
     *	  keyPressed.  So, we need to call super.keyPressed() so ModalDialog
     *    can do its thing.

 **************************************************/
    public void keyPressed(KeyEvent e) {

	// default focus to text item if any key.
	if(!inputText.hasFocus())
	    inputText.grabFocus();

	// Enable OK as soon as something is typed.
	if(!okButton.isEnabled())
	    okButton.setEnabled(true);

	// ModalDialog will take care of ESC and anything else that
	// is standard, so call its keyPressed method.
	super.keyPressed(e);
    }

    /**************************************************

     * Summary: Show the dialog, wait for results, get and return results.
     *
     *	    The Dialog will be positioned over the component passed in.
     *	    This way, the cursor will not need to be moved.
     *	    If null is passed in, the dialog will be positioned in the
     *	    center of the screen.
     *

 **************************************************/
    public String showDialogAndGetValue(Component comp) {
	// Set this dialog on top of the component passed in.
	setLocationRelativeTo(comp);

	// Show the dialog and wait for the results. (Blocking call)
	setVisible(true);

	// If I don't do this, and the user hits a 'return' on the keyboard
	// the dialog comes visible again.
	transferFocus();

	// Pass on the results.	 'null' for Cancel or Help button.
	return(userText);
    }
}


text:
import {PlatformLocation} from '@angular/common';
import {analyzeAppProvidersForDeprecatedConfiguration, platformCoreDynamic} from '@angular/compiler';
import {ApplicationRef, ComponentRef, NgModule, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER, PlatformRef, Type, createPlatformFactory, platformCore} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {Console, ReflectionCapabilities, reflector, wtfInit} from '../core_private';

import {Parse5DomAdapter} from './parse5_adapter';

function notSupported(feature: string): Error {
  throw new Error(`platform-server does not support '${feature}'.`);
}

class ServerPlatformLocation extends PlatformLocation {
  getBaseHrefFromDOM(): string { throw notSupported('getBaseHrefFromDOM'); };
  onPopState(fn: any): void { notSupported('onPopState'); };
  onHashChange(fn: any): void { notSupported('onHashChange'); };
  get pathname(): string { throw notSupported('pathname'); }
  get search(): string { throw notSupported('search'); }
  get hash(): string { throw notSupported('hash'); }
  replaceState(state: any, title: string, url: string): void { notSupported('replaceState'); };
  pushState(state: any, title: string, url: string): void { notSupported('pushState'); };
  forward(): void { notSupported('forward'); };
  back(): void { notSupported('back'); };
}

export const INTERNAL_SERVER_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> = [
  {provide: PLATFORM_INITIALIZER, useValue: initParse5Adapter, multi: true},
  {provide: PlatformLocation, useClass: ServerPlatformLocation},
];

/**
 * A set of providers to initialize the Angular platform in a server.
 *
 * Used automatically by `serverBootstrap`, or can be passed to `platform`.
 * @deprecated Use `platformServer()` or create a custom platform factory via
 * `createPlatformFactory(platformServer, ...)`
 */
export const SERVER_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> =
    [PLATFORM_COMMON_PROVIDERS, INTERNAL_SERVER_PLATFORM_PROVIDERS];

function initParse5Adapter() {
  Parse5DomAdapter.makeCurrent();
  wtfInit();
}

/**
 * @experimental
 */
export const platformServer =
    createPlatformFactory(platformCore, 'server', INTERNAL_SERVER_PLATFORM_PROVIDERS);

/**
 * @deprecated Use {@link platformServer} instead
 */
export const serverPlatform = platformServer;

/**
 * The server platform that supports the runtime compiler.
 *
 * @experimental
 */
export const platformDynamicServer =
    createPlatformFactory(platformCoreDynamic, 'serverDynamic', INTERNAL_SERVER_PLATFORM_PROVIDERS);

/**
 * @deprecated Use {@link platformDynamicServer} instead
 */
export const serverDynamicPlatform = platformDynamicServer;

/**
 * Used to bootstrap Angular in server environment (such as node).
 *
 * This version of bootstrap only creates platform injector and does not define anything for
 * application injector. It is expected that application providers are imported from other
 * packages such as `@angular/platform-browser` or `@angular/platform-browser-dynamic`.
 *
 * ```
 * import {BROWSER_APP_PROVIDERS} from '@angular/platform-browser';
 * import {BROWSER_APP_COMPILER_PROVIDERS} from '@angular/platform-browser-dynamic';
 *
 * serverBootstrap(..., [BROWSER_APP_PROVIDERS, BROWSER_APP_COMPILER_PROVIDERS])
 * ```
 *
 * @deprecated create an {@link NgModule} and use {@link bootstrapModule} with the {@link
 * serverDynamicPlatform}()
 * instead.
 */
export function serverBootstrap<T>(
    appComponentType: Type<T>,
    customProviders: Array<any /*Type | Provider | any[]*/>): Promise<ComponentRef<T>> {
  console.warn(
      'serverBootstrap is deprecated. Create an @NgModule and use `bootstrapModule` with the `serverDynamicPlatform()` instead.');
  reflector.reflectionCapabilities = new ReflectionCapabilities();

  const deprecatedConfiguration = analyzeAppProvidersForDeprecatedConfiguration(customProviders);
  const declarations = [deprecatedConfiguration.moduleDeclarations.concat([appComponentType])];

  @NgModule({
    providers: customProviders,
    declarations: declarations,
    imports: [BrowserModule],
    bootstrap: [appComponentType]
  })
  class DynamicModule {
  }

  return platformDynamicServer()
      .bootstrapModule(DynamicModule, deprecatedConfiguration.compilerOptions)
      .then((moduleRef) => {
        const console = moduleRef.injector.get(Console);
        deprecatedConfiguration.deprecationMessages.forEach((msg) => console.warn(msg));
        const appRef: ApplicationRef = moduleRef.injector.get(ApplicationRef);
        return appRef.components[0];
      });
}


text:
TODO for Whiskey:
 * Better memory management? Safer memory management.
 * Add better test cases for the core pass classes


text:
using System;

namespace Okra
{
    public interface IOkraBootstrapper
    {
        IServiceProvider ApplicationServices { get; }
        void Initialize();
    }
}


text:
.App {
    text-align: center;
}

.App-logo {
    animation: App-logo-spin infinite 20s linear;
    height: 80px;
}

.App-header {
    background-color: #222;
    height: 150px;
    color: white;
}

.App-intro {
    font-size: large;
}

@keyframes App-logo-spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}


text:
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AlgorithmInterface = require('./AlgorithmInterface');
var Algorithm = require('./Algorithm');
var Queue = require('../common/VictimsStructures/Queue');

cocktail.use(Logger);

cocktail.mix({
	'@exports': module,
	'@as': 'class',
	'@extends': Algorithm,
	'@traits': [AlgorithmInterface],
	'@logger' : [console, "Algorithm Nru:"],

	constructor: function() {
		this.callSuper("constructor");
		this._instant = 0;
		this._victims = new Queue();
		this._orderedVictims = {};
		this.log("Created.");
	},

	initialize: function(requirements) {
		this.callSuper("initialize", requirements);
		this._instant = 0;
	  this._victims = new Queue();
		this._orderedVictims = {};
		this._orderVictims();
		this.log("Initialized.");
	},

	addPage: function(requirement) {
  	// this._victims.add(requirement.asPage().clearAll());
	},

	getPage: function(page) {
	  // return this._victims.pageOf(page);
	},

	update: function(requirement) {

		this._instant++;
		var highestLesser = {};

		for (key in this._orderedVictims) {
			this._orderedVictims[key].forEach(function(instant) {
			  if (instant < this._instant) {
					highestLesser[key] = instant;
			  }
			}, this);
		}

		var sortable = [];
		for (var page in highestLesser) {
	      sortable.push([page, highestLesser[page]]);
			}

		sortable.sort(function(a, b) {return a[1] - b[1]});
		sortable.forEach(function(elem) {
			this._victims.add(this._requirements[elem[1]].asPage());
		}, this);

	},

	_orderVictims: function() {
	  var reqs = this._requirements;
		reqs.forEach(function(elem, index) {
			var key = elem.getProcess() + elem.getPageNumber();
			if (!this._orderedVictims[key]) {
				this._orderedVictims[key] = [];
			}
			this._orderedVictims[key].push(index)
		}, this);
		this.log(this._orderedVictims);
	}

});


text: CPU Message Trader


text:
#ifndef __SUPPORT_CGPOINTEXTENSION_H__
#define __SUPPORT_CGPOINTEXTENSION_H__

/**
 @file
 CCPoint extensions based on Chipmunk's cpVect file.
 These extensions work both with CCPoint and cpVect.

 The "ccp" prefix means: "CoCos2d Point"

 Examples:
  - ccpAdd( ccp(1,1), ccp(2,2) ); // preferred cocos2d way
  - ccpAdd( CCPointMake(1,1), CCPointMake(2,2) ); // also ok but more verbose

  - cpvadd( cpv(1,1), cpv(2,2) ); // way of the chipmunk
  - ccpAdd( cpv(1,1), cpv(2,2) ); // mixing chipmunk and cocos2d (avoid)
  - cpvadd( CCPointMake(1,1), CCPointMake(2,2) ); // mixing chipmunk and CG (avoid)
 */

#include "CCGeometry.h"

#include <math.h>
namespace   cocos2d {

/** Helper macro that creates a CCPoint
 @return CCPoint
 @since v0.7.2
 */
#define ccp(__X__,__Y__) cocos2d::CCPointMake((float)(__X__), (float)(__Y__))

/** Returns opposite of point.
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpNeg(const CCPoint& v)
{
	return ccp(-v.x, -v.y);
}

/** Calculates sum of two points.
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpAdd(const CCPoint& v1, const CCPoint& v2)
{
	return ccp(v1.x + v2.x, v1.y + v2.y);
}

/** Calculates difference of two points.
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpSub(const CCPoint& v1, const CCPoint& v2)
{
	return ccp(v1.x - v2.x, v1.y - v2.y);
}

/** Returns point multiplied by given factor.
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpMult(const CCPoint& v, const CGFloat s)
{
	return ccp(v.x*s, v.y*s);
}

/** Calculates midpoint between two points.
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpMidpoint(const CCPoint& v1, const CCPoint& v2)
{
	return ccpMult(ccpAdd(v1, v2), 0.5f);
}

/** Calculates dot product of two points.
 @return CGFloat
 @since v0.7.2
 */
static inline CGFloat
ccpDot(const CCPoint& v1, const CCPoint& v2)
{
	return v1.x*v2.x + v1.y*v2.y;
}

/** Calculates cross product of two points.
 @return CGFloat
 @since v0.7.2
 */
static inline CGFloat
ccpCross(const CCPoint& v1, const CCPoint& v2)
{
	return v1.x*v2.y - v1.y*v2.x;
}

/** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpPerp(const CCPoint& v)
{
	return ccp(-v.y, v.x);
}

/** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpRPerp(const CCPoint& v)
{
	return ccp(v.y, -v.x);
}

/** Calculates the projection of v1 over v2.
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpProject(const CCPoint& v1, const CCPoint& v2)
{
	return ccpMult(v2, ccpDot(v1, v2)/ccpDot(v2, v2));
}

/** Rotates two points.
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpRotate(const CCPoint& v1, const CCPoint& v2)
{
	return ccp(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x);
}

/** Unrotates two points.
 @return CCPoint
 @since v0.7.2
 */
static inline CCPoint
ccpUnrotate(const CCPoint& v1, const CCPoint& v2)
{
	return ccp(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y);
}

/** Calculates the square length of a CCPoint (not calling sqrt() )
 @return CGFloat
 @since v0.7.2
 */
static inline CGFloat
ccpLengthSQ(const CCPoint& v)
{
	return ccpDot(v, v);
}

/** Calculates distance between point an origin
 @return CGFloat
 @since v0.7.2
 */
CGFloat CC_DLL ccpLength(const CCPoint& v);

/** Calculates the distance between two points
 @return CGFloat
 @since v0.7.2
 */
CGFloat CC_DLL ccpDistance(const CCPoint& v1, const CCPoint& v2);

/** Returns point multiplied to a length of 1.
 @return CCPoint
 @since v0.7.2
 */
CCPoint CC_DLL ccpNormalize(const CCPoint& v);

/** Converts radians to a normalized vector.
 @return CCPoint
 @since v0.7.2
 */
CCPoint CC_DLL ccpForAngle(const CGFloat a);

/** Converts a vector to radians.
 @return CGFloat
 @since v0.7.2
 */
CGFloat CC_DLL ccpToAngle(const CCPoint& v);

/** Clamp a value between from and to.
 @since v0.99.1
 */
float CC_DLL clampf(float value, float min_inclusive, float max_inclusive);

/** Clamp a point between from and to.
 @since v0.99.1
 */
CCPoint CC_DLL ccpClamp(const CCPoint& p, const CCPoint& from, const CCPoint& to);

/** Quickly convert CCSize to a CCPoint
 @since v0.99.1
 */
CCPoint CC_DLL ccpFromSize(const CCSize& s);

/** Run a math operation function on each point component
 * absf, fllorf, ceilf, roundf
 * any function that has the signature: float func(float);
 * For example: let's try to take the floor of x,y
 * ccpCompOp(p,floorf);
 @since v0.99.1
 */
CCPoint CC_DLL ccpCompOp(const CCPoint& p, float (*opFunc)(float));

/** Linear Interpolation between two points a and b
 @returns
	alpha == 0 ? a
	alpha == 1 ? b
	otherwise a value between a..b
 @since v0.99.1
 */
CCPoint CC_DLL ccpLerp(const CCPoint& a, const CCPoint& b, float alpha);

/** @returns if points have fuzzy equality which means equal with some degree of variance.
 @since v0.99.1
 */
bool CC_DLL ccpFuzzyEqual(const CCPoint& a, const CCPoint& b, float variance);

/** Multiplies a nd b components, a.x*b.x, a.y*b.y
 @returns a component-wise multiplication
 @since v0.99.1
 */
CCPoint CC_DLL ccpCompMult(const CCPoint& a, const CCPoint& b);

/** @returns the signed angle in radians between two vector directions
 @since v0.99.1
 */
float CC_DLL ccpAngleSigned(const CCPoint& a, const CCPoint& b);

/** @returns the angle in radians between two vector directions
 @since v0.99.1
*/
float CC_DLL ccpAngle(const CCPoint& a, const CCPoint& b);

/** Rotates a point counter clockwise by the angle around a pivot
 @param v is the point to rotate
 @param pivot is the pivot, naturally
 @param angle is the angle of rotation cw in radians
 @returns the rotated point
 @since v0.99.1
 */
CCPoint CC_DLL ccpRotateByAngle(const CCPoint& v, const CCPoint& pivot, float angle);

/** A general line-line intersection test
 @param p1
	is the startpoint for the first line P1 = (p1 - p2)
 @param p2
	is the endpoint for the first line P1 = (p1 - p2)
 @param p3
	is the startpoint for the second line P2 = (p3 - p4)
 @param p4
	is the endpoint for the second line P2 = (p3 - p4)
 @param s
	is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1))
 @param t
	is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3))
 @return bool
	indicating successful intersection of a line
	note that to truly test intersection for segments we have to make
	sure that s & t lie within [0..1] and for rays, make sure s & t > 0
	the hit point is		p3 + t * (p4 - p3);
	the hit point also is	p1 + s * (p2 - p1);
 @since v0.99.1
 */
bool CC_DLL ccpLineIntersect(const CCPoint& p1, const CCPoint& p2,
					  const CCPoint& p3, const CCPoint& p4,
					  float *s, float *t);

/*
ccpSegmentIntersect returns YES if Segment A-B intersects with segment C-D
@since v1.0.0
*/
bool CC_DLL ccpSegmentIntersect(const CCPoint& A, const CCPoint& B, const CCPoint& C, const CCPoint& D);

/*
ccpIntersectPoint returns the intersection point of line A-B, C-D
@since v1.0.0
*/
CCPoint CC_DLL ccpIntersectPoint(const CCPoint& A, const CCPoint& B, const CCPoint& C, const CCPoint& D);

}//namespace   cocos2d

#endif // __SUPPORT_CGPOINTEXTENSION_H__


text:
package protobuf

import (
	"bytes"
	"fmt"
	"io"
	"reflect"

	"github.com/gogo/protobuf/proto"

	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/framer"
)

var (
	// protoEncodingPrefix serves as a magic number for an encoded protobuf message on this serializer. All
	// proto messages serialized by this schema will be preceded by the bytes 0x6b 0x38 0x73, with the fourth
	// byte being reserved for the encoding style. The only encoding style defined is 0x00, which means that
	// the rest of the byte stream is a message of type k8s.io.kubernetes.pkg.runtime.Unknown (proto2).
	//
	// See k8s.io/kubernetes/pkg/runtime/generated.proto for details of the runtime.Unknown message.
	//
	// This encoding scheme is experimental, and is subject to change at any time.
	protoEncodingPrefix = []byte{0x6b, 0x38, 0x73, 0x00}
)

type errNotMarshalable struct {
	t reflect.Type
}

func (e errNotMarshalable) Error() string {
	return fmt.Sprintf("object %v does not implement the protobuf marshalling interface and cannot be encoded to a protobuf message", e.t)
}

func IsNotMarshalable(err error) bool {
	_, ok := err.(errNotMarshalable)
	return err != nil && ok
}

// NewSerializer creates a Protobuf serializer that handles encoding versioned objects into the proper wire form. If a typer
// is passed, the encoded object will have group, version, and kind fields set. If typer is nil, the objects will be written
// as-is (any type info passed with the object will be used).
//
// This encoding scheme is experimental, and is subject to change at any time.
func NewSerializer(creater runtime.ObjectCreater, typer runtime.Typer, defaultContentType string) *Serializer {
	return &Serializer{
		prefix:      protoEncodingPrefix,
		creater:     creater,
		typer:       typer,
		contentType: defaultContentType,
	}
}

type Serializer struct {
	prefix      []byte
	creater     runtime.ObjectCreater
	typer       runtime.Typer
	contentType string
}

var _ runtime.Serializer = &Serializer{}

// Decode attempts to convert the provided data into a protobuf message, extract the stored schema kind, apply the provided default
// gvk, and then load that data into an object matching the desired schema kind or the provided into. If into is *runtime.Unknown,
// the raw data will be extracted and no decoding will be performed. If into is not registered with the typer, then the object will
// be straight decoded using normal protobuf unmarshalling (the MarshalTo interface). If into is provided and the original data is
// not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk. On success or most
// errors, the method will return the calculated schema kind.
func (s *Serializer) Decode(originalData []byte, gvk *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) {
	if versioned, ok := into.(*runtime.VersionedObjects); ok {
		into = versioned.Last()
		obj, actual, err := s.Decode(originalData, gvk, into)
		if err != nil {
			return nil, actual, err
		}
		// the last item in versioned becomes into, so if versioned was not originally empty we reset the object
		// array so the first position is the decoded object and the second position is the outermost object.
		// if there were no objects in the versioned list passed to us, only add ourselves.
		if into != nil && into != obj {
			versioned.Objects = []runtime.Object{obj, into}
		} else {
			versioned.Objects = []runtime.Object{obj}
		}
		return versioned, actual, err
	}

	prefixLen := len(s.prefix)
	switch {
	case len(originalData) == 0:
		// TODO: treat like decoding {} from JSON with defaulting
		return nil, nil, fmt.Errorf("empty data")
	case len(originalData) < prefixLen || !bytes.Equal(s.prefix, originalData[:prefixLen]):
		return nil, nil, fmt.Errorf("provided data does not appear to be a protobuf message, expected prefix %v", s.prefix)
	case len(originalData) == prefixLen:
		// TODO: treat like decoding {} from JSON with defaulting
		return nil, nil, fmt.Errorf("empty body")
	}

	data := originalData[prefixLen:]
	unk := runtime.Unknown{}
	if err := unk.Unmarshal(data); err != nil {
		return nil, nil, err
	}

	actual := unk.GroupVersionKind()
	copyKindDefaults(&actual, gvk)

	if intoUnknown, ok := into.(*runtime.Unknown); ok && intoUnknown != nil {
		*intoUnknown = unk
		if len(intoUnknown.ContentType) == 0 {
			intoUnknown.ContentType = s.contentType
		}
		return intoUnknown, &actual, nil
	}

	if into != nil {
		typed, _, err := s.typer.ObjectKind(into)
		switch {
		case runtime.IsNotRegisteredError(err):
			pb, ok := into.(proto.Message)
			if !ok {
				return nil, &actual, errNotMarshalable{reflect.TypeOf(into)}
			}
			if err := proto.Unmarshal(unk.Raw, pb); err != nil {
				return nil, &actual, err
			}
			return into, &actual, nil
		case err != nil:
			return nil, &actual, err
		default:
			copyKindDefaults(&actual, typed)
			// if the result of defaulting did not set a version or group, ensure that at least group is set
			// (copyKindDefaults will not assign Group if version is already set). This guarantees that the group
			// of into is set if there is no better information from the caller or object.
			if len(actual.Version) == 0 && len(actual.Group) == 0 {
				actual.Group = typed.Group
			}
		}
	}

	if len(actual.Kind) == 0 {
		return nil, &actual, runtime.NewMissingKindErr(fmt.Sprintf("%#v", unk.TypeMeta))
	}
	if len(actual.Version) == 0 {
		return nil, &actual, runtime.NewMissingVersionErr(fmt.Sprintf("%#v", unk.TypeMeta))
	}

	return unmarshalToObject(s.typer, s.creater, &actual, into, unk.Raw)
}

// EncodeToStream serializes the provided object to the given writer. Overrides is ignored.
func (s *Serializer) EncodeToStream(obj runtime.Object, w io.Writer, overrides ...unversioned.GroupVersion) error {
	var unk runtime.Unknown
	kind := obj.GetObjectKind().GroupVersionKind()
	unk = runtime.Unknown{
		TypeMeta: runtime.TypeMeta{
			Kind:       kind.Kind,
			APIVersion: kind.GroupVersion().String(),
		},
	}

	prefixSize := uint64(len(s.prefix))

	switch t := obj.(type) {
	case bufferedMarshaller:
		// this path performs a single allocation during write but requires the caller to implement
		// the more efficient Size and MarshalTo methods
		encodedSize := uint64(t.Size())
		estimatedSize := prefixSize + estimateUnknownSize(&unk, encodedSize)
		data := make([]byte, estimatedSize)

		i, err := unk.NestedMarshalTo(data[prefixSize:], t, encodedSize)
		if err != nil {
			return err
		}

		copy(data, s.prefix)

		_, err = w.Write(data[:prefixSize+uint64(i)])
		return err

	case proto.Marshaler:
		// this path performs extra allocations
		data, err := t.Marshal()
		if err != nil {
			return err
		}
		unk.Raw = data

		estimatedSize := prefixSize + uint64(unk.Size())
		data = make([]byte, estimatedSize)

		i, err := unk.MarshalTo(data[prefixSize:])
		if err != nil {
			return err
		}

		copy(data, s.prefix)

		_, err = w.Write(data[:prefixSize+uint64(i)])
		return err

	default:
		// TODO: marshal with a different content type and serializer (JSON for third party objects)
		return errNotMarshalable{reflect.TypeOf(obj)}
	}
}

// RecognizesData implements the RecognizingDecoder interface.
func (s *Serializer) RecognizesData(peek io.Reader) (bool, error) {
	prefix := make([]byte, 4)
	n, err := peek.Read(prefix)
	if err != nil {
		if err == io.EOF {
			return false, nil
		}
		return false, err
	}
	if n != 4 {
		return false, nil
	}
	return bytes.Equal(s.prefix, prefix), nil
}

// copyKindDefaults defaults dst to the value in src if dst does not have a value set.
func copyKindDefaults(dst, src *unversioned.GroupVersionKind) {
	if src == nil {
		return
	}
	// apply kind and version defaulting from provided default
	if len(dst.Kind) == 0 {
		dst.Kind = src.Kind
	}
	if len(dst.Version) == 0 && len(src.Version) > 0 {
		dst.Group = src.Group
		dst.Version = src.Version
	}
}

// bufferedMarshaller describes a more efficient marshalling interface that can avoid allocating multiple
// byte buffers by pre-calculating the size of the final buffer needed.
type bufferedMarshaller interface {
	proto.Sizer
	runtime.ProtobufMarshaller
}

// estimateUnknownSize returns the expected bytes consumed by a given runtime.Unknown
// object with a nil RawJSON struct and the expected size of the provided buffer. The
// returned size will not be correct if RawJSOn is set on unk.
func estimateUnknownSize(unk *runtime.Unknown, byteSize uint64) uint64 {
	size := uint64(unk.Size())
	// protobuf uses 1 byte for the tag, a varint for the length of the array (at most 8 bytes - uint64 - here),
	// and the size of the array.
	size += 1 + 8 + byteSize
	return size
}

// NewRawSerializer creates a Protobuf serializer that handles encoding versioned objects into the proper wire form. If typer
// is not nil, the object has the group, version, and kind fields set. This serializer does not provide type information for the
// encoded object, and thus is not self describing (callers must know what type is being described in order to decode).
//
// This encoding scheme is experimental, and is subject to change at any time.
func NewRawSerializer(creater runtime.ObjectCreater, typer runtime.Typer, defaultContentType string) *RawSerializer {
	return &RawSerializer{
		creater:     creater,
		typer:       typer,
		contentType: defaultContentType,
	}
}

// RawSerializer encodes and decodes objects without adding a runtime.Unknown wrapper (objects are encoded without identifying
// type).
type RawSerializer struct {
	creater     runtime.ObjectCreater
	typer       runtime.Typer
	contentType string
}

var _ runtime.Serializer = &RawSerializer{}

// Decode attempts to convert the provided data into a protobuf message, extract the stored schema kind, apply the provided default
// gvk, and then load that data into an object matching the desired schema kind or the provided into. If into is *runtime.Unknown,
// the raw data will be extracted and no decoding will be performed. If into is not registered with the typer, then the object will
// be straight decoded using normal protobuf unmarshalling (the MarshalTo interface). If into is provided and the original data is
// not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk. On success or most
// errors, the method will return the calculated schema kind.
func (s *RawSerializer) Decode(originalData []byte, gvk *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) {
	if into == nil {
		return nil, nil, fmt.Errorf("this serializer requires an object to decode into: %#v", s)
	}

	if versioned, ok := into.(*runtime.VersionedObjects); ok {
		into = versioned.Last()
		obj, actual, err := s.Decode(originalData, gvk, into)
		if err != nil {
			return nil, actual, err
		}
		if into != nil && into != obj {
			versioned.Objects = []runtime.Object{obj, into}
		} else {
			versioned.Objects = []runtime.Object{obj}
		}
		return versioned, actual, err
	}

	if len(originalData) == 0 {
		// TODO: treat like decoding {} from JSON with defaulting
		return nil, nil, fmt.Errorf("empty data")
	}
	data := originalData

	actual := &unversioned.GroupVersionKind{}
	copyKindDefaults(actual, gvk)

	if intoUnknown, ok := into.(*runtime.Unknown); ok && intoUnknown != nil {
		intoUnknown.Raw = data
		intoUnknown.ContentEncoding = ""
		intoUnknown.ContentType = s.contentType
		intoUnknown.SetGroupVersionKind(*actual)
		return intoUnknown, actual, nil
	}

	typed, _, err := s.typer.ObjectKind(into)
	switch {
	case runtime.IsNotRegisteredError(err):
		pb, ok := into.(proto.Message)
		if !ok {
			return nil, actual, errNotMarshalable{reflect.TypeOf(into)}
		}
		if err := proto.Unmarshal(data, pb); err != nil {
			return nil, actual, err
		}
		return into, actual, nil
	case err != nil:
		return nil, actual, err
	default:
		copyKindDefaults(actual, typed)
		// if the result of defaulting did not set a version or group, ensure that at least group is set
		// (copyKindDefaults will not assign Group if version is already set). This guarantees that the group
		// of into is set if there is no better information from the caller or object.
		if len(actual.Version) == 0 && len(actual.Group) == 0 {
			actual.Group = typed.Group
		}
	}

	if len(actual.Kind) == 0 {
		return nil, actual, runtime.NewMissingKindErr("<protobuf encoded body - must provide default type>")
	}
	if len(actual.Version) == 0 {
		return nil, actual, runtime.NewMissingVersionErr("<protobuf encoded body - must provide default type>")
	}

	return unmarshalToObject(s.typer, s.creater, actual, into, data)
}

// unmarshalToObject is the common code between decode in the raw and normal serializer.
func unmarshalToObject(typer runtime.Typer, creater runtime.ObjectCreater, actual *unversioned.GroupVersionKind, into runtime.Object, data []byte) (runtime.Object, *unversioned.GroupVersionKind, error) {
	// use the target if necessary
	obj, err := runtime.UseOrCreateObject(typer, creater, *actual, into)
	if err != nil {
		return nil, actual, err
	}

	pb, ok := obj.(proto.Message)
	if !ok {
		return nil, actual, errNotMarshalable{reflect.TypeOf(obj)}
	}
	if err := proto.Unmarshal(data, pb); err != nil {
		return nil, actual, err
	}
	return obj, actual, nil
}

// EncodeToStream serializes the provided object to the given writer. Overrides is ignored.
func (s *RawSerializer) EncodeToStream(obj runtime.Object, w io.Writer, overrides ...unversioned.GroupVersion) error {
	switch t := obj.(type) {
	case bufferedMarshaller:
		// this path performs a single allocation during write but requires the caller to implement
		// the more efficient Size and MarshalTo methods
		encodedSize := uint64(t.Size())
		data := make([]byte, encodedSize)

		n, err := t.MarshalTo(data)
		if err != nil {
			return err
		}
		_, err = w.Write(data[:n])
		return err

	case proto.Marshaler:
		// this path performs extra allocations
		data, err := t.Marshal()
		if err != nil {
			return err
		}
		_, err = w.Write(data)
		return err

	default:
		return errNotMarshalable{reflect.TypeOf(obj)}
	}
}

var LengthDelimitedFramer = lengthDelimitedFramer{}

type lengthDelimitedFramer struct{}

// NewFrameWriter implements stream framing for this serializer
func (lengthDelimitedFramer) NewFrameWriter(w io.Writer) io.Writer {
	return framer.NewLengthDelimitedFrameWriter(w)
}

// NewFrameReader implements stream framing for this serializer
func (lengthDelimitedFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
	return framer.NewLengthDelimitedFrameReader(r)
}


text:
#include <jni.h>
#include <JNIHelp.h>

#include <sensorservice/SensorService.h>

#include <cutils/properties.h>
#include <utils/Log.h>
#include <utils/misc.h>

namespace android {

static void android_server_SystemServer_startSensorService(JNIEnv* /* env */, jobject /* clazz */) {
    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsensorservice", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        // Start the sensor service
        SensorService::instantiate();
    }
}

/*
 * JNI registration.
 */
static const JNINativeMethod gMethods[] = {
    /* name, signature, funcPtr */
    { "startSensorService", "()V", (void*) android_server_SystemServer_startSensorService },
};

int register_android_server_SystemServer(JNIEnv* env)
{
    return jniRegisterNativeMethods(env, "com/android/server/SystemServer",
            gMethods, NELEM(gMethods));
}

}; // namespace android


text:
import React from 'react';
import TreeView from 'react-treeview';
import { Link } from 'react-router';
import 'react-treeview/react-treeview.css';

import TableStore from '../stores/TableStore';
import AdhocQueryActions from '../actions/AdhocQueryActions';
import UserStore from '../stores/UserStore';
import Loader from './LoaderComponent';
import '../styles/css/tree.css';

let filterString = '';

function getState (page, filterString, database) {
  let state = getTables(page, filterString, database);
  state.page = page;
  state.loading = false;
  return state;
}

function getTables (page, filterString, database) {
  // get all the native tables
  // so that Object.keys does not throw up
  let tables = TableStore.getTables(database) || {};
  let pageSize = 10;
  let allTables;
  let startIndex;
  let relevantIndexes;
  let pageTables;

  if (!filterString) {
    // no need for filtering
    allTables = Object.keys(tables);
  } else {
    // filter
    allTables = Object.keys(tables).map(name => {
      if (name.match(filterString)) return name;
    }).filter(name => { return !!name; });
  }

  startIndex = (page - 1) * pageSize;
  relevantIndexes = allTables.slice(startIndex, startIndex + pageSize);
  pageTables = relevantIndexes.map(name => {
    return tables[name];
  });

  return {
    totalPages: Math.ceil(allTables.length / pageSize),
    tables: pageTables
  };
}

class TableTree extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      tables: [],
      totalPages: 0,
      page: 0,
      loading: true,
      isCollapsed: false
    };
    this._onChange = this._onChange.bind(this);
    this.prevPage = this.prevPage.bind(this);
    this.nextPage = this.nextPage.bind(this);
    this.toggle = this.toggle.bind(this);
    this.validateClickEvent = this.validateClickEvent.bind(this);

    if (!TableStore.getTables(props.database)) {
      AdhocQueryActions
        .getTables(UserStore.getUserDetails().secretToken, props.database);
    } else {
      let state = getState(1, '', props.database);
      this.state = state;

      // on page refresh only a single table is fetched, and hence we need to
      // fetch others too.
      if (!TableStore.areTablesCompletelyFetched(props.database)) {
        AdhocQueryActions
          .getTables(UserStore.getUserDetails().secretToken, props.database);
      }
    }
  }

  componentDidMount () {
    TableStore.addChangeListener(this._onChange);

    // listen for opening tree
    this.refs.tableTree.getDOMNode()
      .addEventListener('click', this.validateClickEvent);
  }

  componentWillUnmount () {
    this.refs.tableTree.getDOMNode()
      .removeEventListener('click', this.validateClickEvent);
    TableStore.removeChangeListener(this._onChange);
  }

  render () {
    let tableTree = '';

    // construct tree
    tableTree = this.state.tables.map(table => {
      let label = (<Link to='tableschema' params={{tableName: table.name}}
        title={table.name} query={{database: this.props.database}}>
          {table.name}</Link>);
      return (
        <TreeView key={table.name} nodeLabel={label}
          defaultCollapsed={!table.isLoaded}>

          {table.isLoaded ? table.columns.map(col => {
            return (

                {col.name} ({col.type})

            );
          }) : <Loader size='4px' margin='2px' />}

        </TreeView>
      );
    });

    // show a loader when tree is loading
    if (this.state.loading) {
      tableTree = <Loader size='4px' margin='2px' />;
    } else if (!this.state.tables.length) {
      tableTree = (

          Sorry, we couldn't find any.

);
    }

    let pagination = this.state.tables.length ?
      (

            <button className='btn btn-link glyphicon glyphicon-triangle-left page-back'
              onClick={this.prevPage}>
            </button>
            {this.state.page} of {this.state.totalPages}
            <button className='btn btn-link glyphicon glyphicon-triangle-right page-next'
              onClick={this.nextPage}>
            </button>

      ) : null;

    return (

        { !this.state.loading &&

            <input type='search' className='form-control'
              placeholder='Type to filter tables'
              onChange={this._filter.bind(this)}/>

        }

        {pagination}

          {tableTree}

    );
  }

  _onChange (page) {
    // so that page doesn't reset to beginning
    page = page || this.state.page || 1;
    this.setState(getState(page, filterString, this.props.database));
  }

  getDetails (tableName, database) {
    // find the table
    let table = this.state.tables.filter(table => {
      return tableName === table.name;
    });

    if (table.length && table[0].isLoaded) return;

    AdhocQueryActions
      .getTableDetails(UserStore.getUserDetails().secretToken, tableName,
        database);
  }

  _filter (event) {
    filterString = event.target.value;
    this._onChange();
  }

  prevPage () {
    if (this.state.page - 1) this._onChange(this.state.page - 1);
  }

  nextPage () {
    if (this.state.page < this.state.totalPages) {
      this._onChange(this.state.page + 1);
    }
  }

  toggle () {
    this.setState({ isCollapsed: !this.state.isCollapsed });
  }

  validateClickEvent (e) {
    if (e.target && e.target.nodeName === 'DIV' &&
      e.target.nextElementSibling.nodeName === 'A') {
      this.getDetails(e.target.nextElementSibling.textContent, this.props.database);
    }
  }

}

TableTree.propTypes = {
  database: React.PropTypes.string.isRequired
};

export default TableTree;