From http://www.weberdev.com/get_example-4769.html
430489
public function elapsedTime($timestamp)
    {
        if ($timestamp instanceof DateTime) {
            $timestamp = $timestamp->format('U');
        } else if (is_string($timestamp)) {
            $timestamp = strtotime($timestamp);
        }
        
        $diff = time() - $timestamp; 
        $periods = self::$texts['times']; 
        $lengths = array(60, 60, 24, 7, 4.35, 12, 10); 
        $ending = self::$texts['ago'];
        
        if ($diff < 60) {
            return self::$texts['less_than_a_minute'];
        } else if ($diff < 0) {
            $diff = -$diff; 
            $ending = self::$texts['togo']; 
        }
              
        for($j = 0; $j < count($lengths) && $diff >= $lengths[$j]; $j++) {
            $diff /= $lengths[$j]; 
        }
        $diff = round($diff); 
        if($diff != 1) {
            $periods[$j].= "s"; 
        }
        
        if (self::$agoAfter) {
            return "$diff $periods[$j] $ending";
        } else {
            return "$ending $diff $periods[$j]";
        }
    }
457666
def html(args = {})
      id     = SecureRandom.uuid
      width  = args[:width]  || "50"
      config = args[:config] || @config.json
      type   = @config.type

      "<div id=\"canvas-holder\" style=\"width:#{width}%\">
        <canvas id=\"#{id}\" />
      </div>
      <script>
        var config = #{config}
        window.onload = function() {
          var ctx = document.getElementById(\"#{id}\").getContext(\"2d\");
          new Chart(ctx, config);
        };
      </script>" 
    end
192797
def editor_example():
    
    sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]
    agent = AgentDefinition("uav0", agents.UavAgent, sensors)
    env = HolodeckEnvironment(agent, start_world=False)
    env.agents["uav0"].set_control_scheme(1)
    command = [0, 0, 10, 50]

    for i in range(10):
        env.reset()
        for _ in range(1000):
            state, reward, terminal, _ = env.step(command)
536103
function (aNode, sourceBuffer, owner) {
        var forElementANode = {
            children: aNode.children,
            props: aNode.props,
            events: aNode.events,
            tagName: aNode.tagName,
            directives: extend({}, aNode.directives),
            hotspot: aNode.hotspot
        };
        forElementANode.directives['for'] = null;

        var forDirective = aNode.directives['for']; // eslint-disable-line dot-notation
        var itemName = forDirective.item;
        var indexName = forDirective.index || genSSRId();
        var listName = genSSRId();


        sourceBuffer.addRaw('var ' + listName + ' = ' + compileExprSource.expr(forDirective.value) + ';');
        sourceBuffer.addRaw('if (' + listName + ' instanceof Array) {');

        // for array
        sourceBuffer.addRaw('for ('
            + 'var ' + indexName + ' = 0; '
            + indexName + ' < ' + listName + '.length; '
            + indexName + '++) {'
        );
        sourceBuffer.addRaw('componentCtx.data.' + indexName + '=' + indexName + ';');
        sourceBuffer.addRaw('componentCtx.data.' + itemName + '= ' + listName + '[' + indexName + '];');
        sourceBuffer.addRaw(
            aNodeCompiler.compile(
                forElementANode,
                sourceBuffer,
                owner
            )
        );
        sourceBuffer.addRaw('}');

        sourceBuffer.addRaw('} else if (typeof ' + listName + ' === "object") {');

        // for object
        sourceBuffer.addRaw('for (var ' + indexName + ' in ' + listName + ') {');
        sourceBuffer.addRaw('if (' + listName + '[' + indexName + '] != null) {');
        sourceBuffer.addRaw('componentCtx.data.' + indexName + '=' + indexName + ';');
        sourceBuffer.addRaw('componentCtx.data.' + itemName + '= ' + listName + '[' + indexName + '];');
        sourceBuffer.addRaw(
            aNodeCompiler.compile(
                forElementANode,
                sourceBuffer,
                owner
            )
        );
        sourceBuffer.addRaw('}');
        sourceBuffer.addRaw('}');

        sourceBuffer.addRaw('}');
    }
712629
function () {
    var data = this.data;

    // If true, show wireframes around physics bodies.
    this.debug = data.debug;

    this.callbacks = {beforeStep: [], step: [], afterStep: []};

    this.listeners = {};

    this.driver = null;
    switch (data.driver) {
      case 'local':
        this.driver = new LocalDriver();
        break;

      case 'network':
        this.driver = new NetworkDriver(data.networkUrl);
        break;

      case 'worker':
        this.driver = new WorkerDriver({
          fps: data.workerFps,
          engine: data.workerEngine,
          interpolate: data.workerInterpolate,
          interpolationBufferSize: data.workerInterpBufferSize,
          debug: data.workerDebug
        });
        break;

      default:
        throw new Error('[physics] Driver not recognized: "%s".', data.driver);
    }

    this.driver.init({
      quatNormalizeSkip: 0,
      quatNormalizeFast: false,
      solverIterations: data.iterations,
      gravity: data.gravity
    });

    this.driver.addMaterial({name: 'defaultMaterial'});
    this.driver.addMaterial({name: 'staticMaterial'});
    this.driver.addContactMaterial('defaultMaterial', 'defaultMaterial', {
      friction: data.friction,
      restitution: data.restitution,
      contactEquationStiffness: data.contactEquationStiffness,
      contactEquationRelaxation: data.contactEquationRelaxation,
      frictionEquationStiffness: data.frictionEquationStiffness,
      frictionEquationRegularization: data.frictionEquationRegularization
    });
    this.driver.addContactMaterial('staticMaterial', 'defaultMaterial', {
      friction: 1.0,
      restitution: 0.0,
      contactEquationStiffness: data.contactEquationStiffness,
      contactEquationRelaxation: data.contactEquationRelaxation,
      frictionEquationStiffness: data.frictionEquationStiffness,
      frictionEquationRegularization: data.frictionEquationRegularization
    });
  }
739644
public static void main(String[] args) {
		// get the sample tree
		TreeForTreeLayout<TextInBox> tree = SampleTreeFactory
				.createSampleTree();

		// setup the tree layout configuration
		double gapBetweenLevels = 50;
		double gapBetweenNodes = 10;
		DefaultConfiguration<TextInBox> configuration = new DefaultConfiguration<TextInBox>(
				gapBetweenLevels, gapBetweenNodes);

		// create the NodeExtentProvider for TextInBox nodes
		TextInBoxNodeExtentProvider nodeExtentProvider = new TextInBoxNodeExtentProvider();

		// create the layout
		TreeLayout<TextInBox> treeLayout = new TreeLayout<TextInBox>(tree,
				nodeExtentProvider, configuration);

		// Generate the SVG and write it to System.out
		SVGForTextInBoxTree generator = new SVGForTextInBoxTree(treeLayout);
		System.out.println(generator.getSVG());
	}
916760
function () {
/*Line 30 - 'AtomFormGrid.js' */                var element = this._element;
/*Line 31 - 'AtomFormGrid.js' */                $(element).addClass("atom-form-grid");

/*Line 33 - 'AtomFormGrid.js' */                var children = $(element).children();

/*Line 35 - 'AtomFormGrid.js' */                var ae = new AtomEnumerator(children);

/*Line 37 - 'AtomFormGrid.js' */                AtomUI.removeAllChildren(element);

/*Line 39 - 'AtomFormGrid.js' */                var container = document.createElement("DIV");
/*Line 40 - 'AtomFormGrid.js' */                //container.setAttribute("style-width", "[$owner.controlWidth]");
/*Line 41 - 'AtomFormGrid.js' */                $(container).addClass("atom-form-grid-container");

/*Line 43 - 'AtomFormGrid.js' */                element.appendChild(container);

/*Line 45 - 'AtomFormGrid.js' */                var minLabelWidth = AtomUI.attr(this._element, "atom-min-label-width");

/*Line 47 - 'AtomFormGrid.js' */                this.getTemplate("fieldTemplate");

/*Line 49 - 'AtomFormGrid.js' */                while (ae.next()) {
/*Line 50 - 'AtomFormGrid.js' */                    var item = ae.current();

/*Line 52 - 'AtomFormGrid.js' */                    var at = AtomUI.attr(item,"atom-type");
/*Line 53 - 'AtomFormGrid.js' */                    if (at == "AtomFormRow") {
/*Line 54 - 'AtomFormGrid.js' */                        var table = document.createElement("TABLE");
/*Line 55 - 'AtomFormGrid.js' */                        container.appendChild(table);
/*Line 56 - 'AtomFormGrid.js' */                        $(table).addClass("atom-form-grid-row");
/*Line 57 - 'AtomFormGrid.js' */                        var tbody = document.createElement("TBODY");
/*Line 58 - 'AtomFormGrid.js' */                        table.appendChild(tbody);

/*Line 60 - 'AtomFormGrid.js' */                        var tr = document.createElement("TR");
/*Line 61 - 'AtomFormGrid.js' */                        tbody.appendChild(tr);

/*Line 63 - 'AtomFormGrid.js' */                        var children = $(item).children();
/*Line 64 - 'AtomFormGrid.js' */                        var ce = new AtomEnumerator(children);
/*Line 65 - 'AtomFormGrid.js' */                        while (ce.next()) {
/*Line 66 - 'AtomFormGrid.js' */                            var td = document.createElement("TD");
/*Line 67 - 'AtomFormGrid.js' */                            tr.appendChild(td);
/*Line 68 - 'AtomFormGrid.js' */                            this.createField(td, ce.current());
/*Line 69 - 'AtomFormGrid.js' */                        }

/*Line 71 - 'AtomFormGrid.js' */                        continue;
/*Line 72 - 'AtomFormGrid.js' */                    }
/*Line 73 - 'AtomFormGrid.js' */                    if (at == "AtomFormTabControl" || at == "AtomTabControl") {


/*Line 76 - 'AtomFormGrid.js' */                        var tabBar = document.createElement("ul");
/*Line 77 - 'AtomFormGrid.js' */                        tabBar.setAttribute("atom-type", "AtomToggleButtonBar");
/*Line 78 - 'AtomFormGrid.js' */                        var tabBarID = AtomUI.assignID(tabBar);
/*Line 79 - 'AtomFormGrid.js' */                        tabBar.setAttribute("atom-name", tabBarID);
/*Line 80 - 'AtomFormGrid.js' */                        tabBar.setAttribute("atom-show-tabs", "true");
/*Line 81 - 'AtomFormGrid.js' */                        var te = document.createElement("li");
/*Line 82 - 'AtomFormGrid.js' */                        tabBar.appendChild(te);
/*Line 83 - 'AtomFormGrid.js' */                        te.setAttribute("atom-text", "{$data.label}");
/*Line 84 - 'AtomFormGrid.js' */                        te.setAttribute("atom-template", "itemTemplate");
/*Line 85 - 'AtomFormGrid.js' */                        //td.appendChild(tabBar);
/*Line 86 - 'AtomFormGrid.js' */                        this.createField(container, tabBar);

/*Line 88 - 'AtomFormGrid.js' */                        var tbc = allControls[tabBarID];

/*Line 90 - 'AtomFormGrid.js' */                        var ce = new ChildEnumerator(item);
/*Line 91 - 'AtomFormGrid.js' */                        var list = [];
/*Line 92 - 'AtomFormGrid.js' */                        var index = 0;
/*Line 93 - 'AtomFormGrid.js' */                        while (ce.next()) {
/*Line 94 - 'AtomFormGrid.js' */                            var child = ce.current();
/*Line 95 - 'AtomFormGrid.js' */                            $(child).remove();
/*Line 96 - 'AtomFormGrid.js' */                            child.setAttribute("style-display", "[$scope." + tabBarID + ".selectedIndex == " + index + " ? '' : 'none']");
/*Line 97 - 'AtomFormGrid.js' */                            var cf = this.createField(container, child);
/*Line 98 - 'AtomFormGrid.js' */                            list.push(cf);
/*Line 99 - 'AtomFormGrid.js' */                            //if (cf.constructor == WebAtoms.AtomFormGridLayout) {

/*Line 101 - 'AtomFormGrid.js' */                            //}
/*Line 102 - 'AtomFormGrid.js' */                            index++;
/*Line 103 - 'AtomFormGrid.js' */                        }

/*Line 105 - 'AtomFormGrid.js' */                        tbc.set_items(list);
/*Line 106 - 'AtomFormGrid.js' */                        continue;
/*Line 107 - 'AtomFormGrid.js' */                    }
/*Line 108 - 'AtomFormGrid.js' */                    this.createField(container, item);

/*Line 110 - 'AtomFormGrid.js' */                }

/*Line 112 - 'AtomFormGrid.js' */            }
1097959
public static void main(String[] args) {
    SparkSession spark = SparkSession
      .builder()
      .appName("Java Spark SQL user-defined DataFrames aggregation example")
      .getOrCreate();

    // $example on:untyped_custom_aggregation$
    // Register the function to access it
    spark.udf().register("myAverage", new MyAverage());

    Dataset<Row> df = spark.read().json("examples/src/main/resources/employees.json");
    df.createOrReplaceTempView("employees");
    df.show();
    // +-------+------+
    // |   name|salary|
    // +-------+------+
    // |Michael|  3000|
    // |   Andy|  4500|
    // | Justin|  3500|
    // |  Berta|  4000|
    // +-------+------+

    Dataset<Row> result = spark.sql("SELECT myAverage(salary) as average_salary FROM employees");
    result.show();
    // +--------------+
    // |average_salary|
    // +--------------+
    // |        3750.0|
    // +--------------+
    // 

    spark.stop();
  }
1367994
public static void main(String[] args) throws Exception {

    SAXProcessor sp = new SAXProcessor();

    // data
    //
    double[] dat = TSProcessor.readFileColumn(DAT_FNAME, 1, 0);
    // TSProcessor tp = new TSProcessor();
    // double[] dat = tp.readTS("src/resources/dataset/asys40.txt", 0);
    // double[] dat = TSProcessor.readFileColumn(filename, columnIdx,
    // sizeLimit)FileColumn(DAT_FNAME, 1, 0);
    LOGGER.info("read {} points from {}", dat.length, DAT_FNAME);

    String str = "win_width: " + cPoint + "; SAX: W " + SAX_WINDOW_SIZE + ", P " + SAX_PAA_SIZE
        + ", A " + SAX_ALPHABET_SIZE + ", STR " + SAX_NR_STRATEGY.toString();

    int frameCounter = 0;
    int startOffset = cPoint;
    while (cPoint < dat.length - startOffset - 1) {

      if (0 == cPoint % 2) {

        BufferedImage tsChart = getChart(dat, cPoint);

        // bitmap 1
        //
        double[] win1 = Arrays.copyOfRange(dat, cPoint - startOffset, cPoint);
        Map<String, Integer> shingledData1 = sp.ts2Shingles(win1, SAX_WINDOW_SIZE, SAX_PAA_SIZE,
            SAX_ALPHABET_SIZE, SAX_NR_STRATEGY, SAX_NORM_THRESHOLD, SHINGLE_SIZE);
        BufferedImage pam1 = getHeatMap(shingledData1, "pre-window");

        double[] win2 = Arrays.copyOfRange(dat, cPoint, cPoint + startOffset);
        Map<String, Integer> shingledData2 = sp.ts2Shingles(win2, SAX_WINDOW_SIZE, SAX_PAA_SIZE,
            SAX_ALPHABET_SIZE, SAX_NR_STRATEGY, SAX_NORM_THRESHOLD, SHINGLE_SIZE);
        BufferedImage pam2 = getHeatMap(shingledData2, "post-window");

        // the assemble
        //
        BufferedImage target = new BufferedImage(800, 530, BufferedImage.TYPE_INT_ARGB);
        Graphics targetGraphics = target.getGraphics();
        targetGraphics.setColor(Color.WHITE);
        targetGraphics.fillRect(0, 0, 799, 529);

        targetGraphics.drawImage(tsChart, 0, 0, null);

        targetGraphics.drawImage(pam1, 10, 410, null);// draws the first image onto it

        targetGraphics.drawImage(pam2, 120, 410, null);// draws the first image onto it

        targetGraphics.setColor(Color.RED);
        targetGraphics.setFont(new Font("monospaced", Font.PLAIN, 16));
        targetGraphics.drawString(str, 300, 420);

        targetGraphics.setColor(Color.BLUE);
        targetGraphics.setFont(new Font("monospaced", Font.PLAIN, 24));
        double dist = ed.distance(toVector(shingledData1), toVector(shingledData2));
        targetGraphics.drawString("ED=" + df.format(dist), 300, 480);

        // String fileName = new SimpleDateFormat("yyyyMMddhhmmssSS'.png'").format(new Date());
        File outputfile = new File("dframe" + String.format("%04d", frameCounter) + ".png");
        ImageIO.write(target, "png", outputfile);
        frameCounter++;
      }

      cPoint++;
    }
  }
241300
public static void main(String[] args) throws Exception {

		final ParameterTool params = ParameterTool.fromArgs(args);

		if (!params.has("lineitem") && !params.has("customer") && !params.has("orders")) {
			System.err.println("  This program expects data from the TPC-H benchmark as input data.");
			System.err.println("  Due to legal restrictions, we can not ship generated data.");
			System.out.println("  You can find the TPC-H data generator at http://www.tpc.org/tpch/.");
			System.out.println("  Usage: TPCHQuery3 --lineitem <path> --customer <path> --orders <path> [--output <path>]");
			return;
		}

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		env.getConfig().setGlobalJobParameters(params);

		// get input data
		DataSet<Lineitem> lineitems = getLineitemDataSet(env, params.get("lineitem"));
		DataSet<Customer> customers = getCustomerDataSet(env, params.get("customer"));
		DataSet<Order> orders = getOrdersDataSet(env, params.get("orders"));

		// Filter market segment "AUTOMOBILE"
		customers = customers.filter(
								new FilterFunction<Customer>() {
									@Override
									public boolean filter(Customer c) {
										return c.getMktsegment().equals("AUTOMOBILE");
									}
								});

		// Filter all Orders with o_orderdate < 12.03.1995
		orders = orders.filter(
							new FilterFunction<Order>() {
								private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
								private final Date date = format.parse("1995-03-12");

								@Override
								public boolean filter(Order o) throws ParseException {
									return format.parse(o.getOrderdate()).before(date);
								}
							});

		// Filter all Lineitems with l_shipdate > 12.03.1995
		lineitems = lineitems.filter(
								new FilterFunction<Lineitem>() {
									private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
									private final Date date = format.parse("1995-03-12");

									@Override
									public boolean filter(Lineitem l) throws ParseException {
										return format.parse(l.getShipdate()).after(date);
									}
								});

		// Join customers with orders and package them into a ShippingPriorityItem
		DataSet<ShippingPriorityItem> customerWithOrders =
				customers.join(orders).where(0).equalTo(1)
							.with(
								new JoinFunction<Customer, Order, ShippingPriorityItem>() {
									@Override
									public ShippingPriorityItem join(Customer c, Order o) {
										return new ShippingPriorityItem(o.getOrderKey(), 0.0, o.getOrderdate(),
												o.getShippriority());
									}
								});

		// Join the last join result with Lineitems
		DataSet<ShippingPriorityItem> result =
				customerWithOrders.join(lineitems).where(0).equalTo(0)
									.with(
											new JoinFunction<ShippingPriorityItem, Lineitem, ShippingPriorityItem>() {
												@Override
												public ShippingPriorityItem join(ShippingPriorityItem i, Lineitem l) {
													i.setRevenue(l.getExtendedprice() * (1 - l.getDiscount()));
													return i;
												}
											})
								// Group by l_orderkey, o_orderdate and o_shippriority and compute revenue sum
								.groupBy(0, 2, 3)
								.aggregate(Aggregations.SUM, 1);

		// emit result
		if (params.has("output")) {
			result.writeAsCsv(params.get("output"), "\n", "|");
			// execute program
			env.execute("TPCH Query 3 Example");
		} else {
			System.out.println("Printing result to stdout. Use --output to specify output path.");
			result.print();
		}

	}
82316
function baseDirectiveCreate(index, directive, directiveDef) {
    ngDevMode &&
        assertEqual(viewData[BINDING_INDEX], -1, 'directives should be created before any bindings');
    ngDevMode && assertPreviousIsParent();
    Object.defineProperty(directive, NG_HOST_SYMBOL, { enumerable: false, value: previousOrParentNode });
    if (directives == null)
        viewData[DIRECTIVES] = directives = [];
    ngDevMode && assertDataNext(index, directives);
    directives[index] = directive;
    if (firstTemplatePass) {
        var flags = previousOrParentNode.tNode.flags;
        if ((flags & 4095 /* DirectiveCountMask */) === 0) {
            // When the first directive is created:
            // - save the index,
            // - set the number of directives to 1
            previousOrParentNode.tNode.flags =
                index << 14 /* DirectiveStartingIndexShift */ | flags & 4096 /* isComponent */ | 1;
        }
        else {
            // Only need to bump the size when subsequent directives are created
            ngDevMode && assertNotEqual(flags & 4095 /* DirectiveCountMask */, 4095 /* DirectiveCountMask */, 'Reached the max number of directives');
            previousOrParentNode.tNode.flags++;
        }
    }
    else {
        var diPublic = directiveDef.diPublic;
        if (diPublic)
            diPublic(directiveDef);
    }
    if (directiveDef.attributes != null && previousOrParentNode.tNode.type == 3 /* Element */) {
        setUpAttributes(previousOrParentNode.native, directiveDef.attributes);
    }
    return directive;
}
347113
function buildScales() {
            let yMax = d3Array.max(data.map(getValue));

            if (isHorizontal) {
                xScale = d3Scale.scaleLinear()
                    .domain([0, yMax])
                    .rangeRound([0, chartWidth - 1]);
                // 1 pix for edge tick

                yScale = d3Scale.scaleBand()
                    .domain(data.map(getName))
                    .rangeRound([chartHeight, 0])
                    .padding(0.1);

                yScale2 = d3Scale.scaleBand()
                    .domain(data.map(getGroup))
                    .rangeRound([yScale.bandwidth(), 0])
                    .padding(0.1);
            } else {
                xScale = d3Scale.scaleBand()
                    .domain(data.map(getName))
                    .rangeRound([0, chartWidth])
                    .padding(0.1);
                xScale2 = d3Scale.scaleBand()
                    .domain(data.map(getGroup))
                    .rangeRound([0, xScale.bandwidth()])
                    .padding(0.1);

                yScale = d3Scale.scaleLinear()
                    .domain([0, yMax])
                    .rangeRound([chartHeight, 0])
                    .nice();
            }

            colorScale = d3Scale.scaleOrdinal()
                .range(colorSchema)
                .domain(data.map(getGroup));

            categoryColorMap = colorScale
                .domain(data.map(getName)).domain()
                .reduce((memo, item) => {
                    data.forEach(function (v) {
                        if (getName(v) == item) {
                            memo[v.name] = colorScale(v.group)
                            memo[v.group] = colorScale(v.group)
                            memo[v.group + item] = colorScale(v.group)
                        }
                    })
                    return memo;
                }, {});
        }
1160085
def graph(graph_def, max_const_size=32):
    
    if hasattr(graph_def, 'as_graph_def'):
        graph_def = graph_def.as_graph_def()
    strip_def = _strip_consts(graph_def, max_const_size=max_const_size)
    code = """
        <script>
          function load() {{
            document.getElementById("{id}").pbtxt = {data};
          }}
        </script>
        <link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
        <div style="height:600px">
          <tf-graph-basic id="{id}"></tf-graph-basic>
        </div>
    """.format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))

    iframe = """
        <iframe seamless style="width:100%; height:620px; border: none;" srcdoc="{}"></iframe>
    """.format(code.replace('"', '&quot;'))
    _display_html(iframe)
1357095
function ViewModel(options) {
    // inherit Compiler

    var vm = this
    var el = options.el
    var components = [gcomps, options.components || {}]
    var directives = allDirectives.concat([options.directives || {}])

    var _directives = [] // local refs for all directives instance of the vm    
    var _components = [] // local refs for all components    
    var NS = conf.namespace
    var componentProps = [NS + 'component', NS + 'data', NS + 'methods', NS + 'ref', NS + 'replace']
    var $childrens = options.$childrens

    // set $parent ref
    vm.$parent = options.$parent || null

    /**
     *  Mounted element detect
     */
    if (util.type(el) == 'string') {
        el = document.querySelector(el)
    } 
    if (el && options.template) {
        el.innerHTML = options.template
    } else if (options.template) {
        el = document.createElement('div')
        el.innerHTML = options.template
    } else if (!is.Element(el)) {
        throw new Error('Unmatch el option')
    }

    // replace "$NS-template" of actual instance's DOM  
    if (el.children.length == 1 && el.firstElementChild.tagName.toLowerCase() == (NS + 'template')) {
        var $holder = el.firstElementChild
        var childNodes = _slice($holder.childNodes)
        var attributes = _slice($holder.attributes)

        el.removeChild($holder)
        /**
         *  Migrate childNodes
         */
        $(childNodes).appendTo(el)
        /**
         *  Merge attributes
         */
        attributes.forEach(function (att) {
            var nv
            if (att.name == 'class') {
                nv = att.value + (el.className 
                                    ? ' ' + el.className 
                                    : '')

            } else if (!el.hasAttribute(att.name)) {
                nv = att.value
            } else {
                return
            }
            el.setAttribute(att.name, nv)
        })
    }
    // content insertion
    var points = _slice(el.querySelectorAll('content'))
    if (points) {
        var $con
        if ($childrens && $childrens.length) {
            $con = document.createDocumentFragment()
            _slice($childrens).forEach(function (n) {
                $con.appendChild(n)
            })
        }
        points.forEach(function (p) {
            if (!$childrens || !$childrens.length) {
                return $(p).remove()
            }
            var $p = $(p)
            var select = $p.attr('select')
            var tar
            var ind

            if (select 
                && (tar = $con.querySelector(select)) 
                && ~(ind = $childrens.indexOf(tar)) ) {

                $p.replace(tar)
                $childrens.splice(ind, 1)
            } else if (!select) {
                $p.replace($con)
                $childrens = null
            }
        })
    }

    /**
     * Replace external component element holder with internal child element
     */
    if (options.replace) {
        if (el.children.length !== 1) {
            console.warn('Can\'t using \'' + NS + 'replace=true\' for a component that has no or multiple child-elements.')
        } else if (el.parentNode) {
            var replacedEl = el.firstElementChild
            _cloneArributes(replacedEl, el)
            el.parentNode.replaceChild(replacedEl, el)
            el = replacedEl
        } else {
            el = el.firstElementChild
        }
    }

    vm.$el = el

    /**
     *  get component define by tagName
     */
    vm.$component = getComponent

    /**
     *  Component instance refs
     */
    vm.$refs = {}

    /**
     *  assign methods
     */
    var methods = {}
    util.objEach(options.methods, function(k, v) {
        if (util.type(v) !== 'function') return console.warn(k + ' is not a function.')
        vm[k] = methods[k] = util.bind(v, vm)
    })
    vm.$methods = methods

    var $data
    var dataOpt = {}

    Object.defineProperty(vm, '$data', {
        enumerable: true,
        get: function() {
            // $data will be undefined in created calling, so using dataOpt as temporary
            return $data || dataOpt
        },
        set: function(v) {
            if (!$data) return util.merge(dataOpt, v)

            $data.$set(v)
            return $data
        }
    })
    vm.$set = function () {
        $data.$set.apply($data, arguments)
    }
    vm.$get = function () {
        return $data.$get.apply($data, arguments)
    }
    vm.$watch = function (/*[ keypath ], fn*/) {
        return $data.$watch.apply($data, arguments)
    }
    vm.$unwatch = function (/*[ keypath ], fn*/) {
        return $data.$unwatch.apply($data, arguments)
    }

    var created = options.created
    if (options.$data) {
        $data = options.$data
        // if state model instance passsing, call after set
        created && created.call(vm)
    } else {
        util.merge(dataOpt, _funcOrObject(options, 'data'))
        // Call before vm-$data instance
        created && created.call(vm)
        // Instance observable state model
        var mopts = {
            props: dataOpt,
            computed: options.computed,
            computedContext: vm
        }
        $data = new Mux(mopts)
    }

    /**
     *  DOM Compile
     *  @TODO the unique interface for a compiled node($el, $remove)
     */
    vm.$compile = function (el, scope) {
        var compiler

        util.walk(el, function (node) {
            var isRoot = node === el
            var result = compile(node, scope, isRoot)
            if (isRoot) compiler = result.inst
            return result.into
        })
        return compiler
    }

    var beforeDestroy = options.destroy
    vm.$destroy = function () {
        if (vm.$destroyed) return
        beforeDestroy && beforeDestroy.call(vm)

        ;[_components, _directives].forEach(function (items) {
            items.forEach(function (inst) {
                inst.$destroy()
            })
        })

        $data.$destroy()

        // instance methods/properties
        vm.$el = null
        vm.$get = null
        vm.$set = null
        vm.$refs = null
        vm.$watch = null
        vm.$unwatch = null
        vm.$compile = null
        vm.$component = null

        // private vars
        directives = null
        components = null
        _directives = null
        _components = null

        // marked
        vm.$destroyed = true
    }
    vm.$compiler = vm.$compile(el)

    /**
     *  Call ready after compile
     */
    options.ready && options.ready.call(vm)

    function _getAllDirts () {
        var _dirts = {}
        directives.forEach(function(group) {
            util.objEach(group, function(id, def) {
                _dirts[NS + id] = def
            })
        })
        return _dirts
    }
    function _setBindings2Scope (scope, ref) {
        scope && scope.bindings && (scope.bindings.push(ref))
    }
    function compile (node, scope, isRoot) {
        /**
         *  1. ELEMENT_NODE; 
         *  2. ATTRIBUTE_NODE; 
         *  3. TEXT_NODE; 
         *  8. COMMENT_NODE; 
         *  9. DOCUMENT_NODE; 
         *  11. DOCUMENT_FRAGMENT;
         */
        var into = true
        var inst
        switch (node.nodeType) {
            case 1:
                /**
                 * static block no parsing
                 */
                if (node.hasAttribute(NS + 'static')) {
                    into = false
                    break
                }
                /**
                 * convert those $ns-if, $ns-repeat attribute to block element
                 */
                node = compilePseudoDirectiveElement(node)
                /**
                 *  scope syntax
                 */
                if (inst = compileElement(node, scope, isRoot)) {
                    into = false
                    break
                }
                /**
                 *  Attribute directive
                 */
                compileDirective(node, scope)
                /**
                 *  Compile custom-element
                 */
                if (inst = compileComponent(node, vm, scope, isRoot)) {
                    into = false
                    break
                }
                break
            case 3:
                // ignore whitespace
                if (node.nodeValue.trim()) inst = compileText(node, vm, scope, isRoot)
                into = false
                break
            case 11:
                // document fragment
                break
            default:
                into = false
        }
        return {
            into: !!into,
            inst: !inst && isRoot ? new Compiler(node) : inst
        }
    }

    function compilePseudoDirectiveElement (node) {
        var repeatAttName = NS + 'repeat'
        var ifAttName = NS + 'if'
        var valueAttName
        var matchedAttName

        if (node.hasAttribute(ifAttName)) {
            matchedAttName = ifAttName
            valueAttName = 'is'
        } else if (node.hasAttribute(repeatAttName)) {
            matchedAttName = repeatAttName
            valueAttName = 'items'
        } else {
            return node
        }
        var attValue = node.getAttribute(matchedAttName)
        var blockNode = document.createElement(matchedAttName)
        node.removeAttribute(matchedAttName)
        node.parentNode && node.parentNode.replaceChild(blockNode, node)
        blockNode.appendChild(node)
        blockNode.setAttribute(valueAttName, attValue)

        while(node.hasAttribute(ifAttName) || node.hasAttribute(repeatAttName)) {
            compilePseudoDirectiveElement(node)
        }
        return blockNode
    }

    /**
     *  Reverse component Constructor by tagName
     */
    function getComponent(tn) {
        var cid = tn.toLowerCase()
        var compDef
        components.some(function (comp) {
            if (comp.hasOwnProperty(cid)) {
                compDef = comp[cid]
                return true
            }
        })
        return compDef
    }
    /**
     *  Compile element for block syntax handling
     */
    function compileElement(node, scope, isRoot) {
        var tagName = node.tagName
        var inst
        switch(true) {
            /**
             *  <*-if></*-if>
             */
            case is.IfElement(tagName):
                var children = _slice(node.children)
                var exprs = [$(node).attr('is')]
                children.forEach(function(c) {
                    if (is.ElseElement(c)) {
                        exprs.push($(c).attr(conf.namespace + 'else') || '')
                    }
                })
                inst = new ElementDirective(
                        vm, 
                        scope,
                        node, 
                        elements['if'], 
                        NS + 'if', 
                        exprs
                )
                if (!isRoot) {
                    inst.$mount(node)
                }
                // save elements refs
                _directives.push(inst)
                // save bindins to scope
                _setBindings2Scope(scope, inst)
                return inst
            /**
             *  <*-repeat></*-repeat>
             */
            case is.RepeatElement(tagName):
                inst = new ElementDirective(
                        vm, 
                        scope,
                        node, 
                        elements.repeat,
                        NS + 'repeat', 
                        $(node).attr('items')
                )
                if (!isRoot) {
                    inst.$mount(node)
                }
                _directives.push(inst)
                _setBindings2Scope(scope, inst)
                return inst
        }
    }

    /**
     *  comment
     */
    function compileComponent (node, parentVM, scope) {
        var cAttName = NS + 'component'
        var CompName = node.getAttribute(cAttName)
        var tagName = node.tagName
        // filtrate most no-compoment element
        if (!CompName && (tagName == 'DIV' || tagName == 'SPAN' || tagName == 'A' || tagName == 'IMG')) return
        CompName = CompName || tagName
        var Comp = getComponent(CompName)

        /**
         *  Tag is not a custom component element
         */
        if (!Comp) return
        var $node = $(node)
        $node.removeAttr(cAttName)

        // don't need deep into self
        if (node === parentVM.$el) return
        // suport expression, TBD
        var refName = NS + 'ref'
        var dAttName = NS + 'data'
        var mAttName = NS + 'methods'
        var rAttName = NS + 'replace'

        var ref = $node.attr(refName)
        var dataExpr = $node.attr(dAttName)
        var methods = $node.attr(mAttName)
        var replace = $node.attr(rAttName)

        $node.removeAttr(refName)
             .removeAttr(dAttName)
             .removeAttr(mAttName)
             .removeAttr(rAttName)

        var _isDataExpr = _isExpr(dataExpr)
        var bindingData
        var bindingMethods
        /**
         *  Watch
         */
        var execLiteral = Expression.execLiteral
        var ast = {}
        var revealAst = {}
        var compVM

        function _parseExpr (exp) {
            var name
            exp = exp.replace(/^[^:]+:/, function (m) {
                            name = m.replace(/:$/, '').trim()
                            return ''
                        }).trim()
            return {
                name: name,
                expr: exp,
                vars: Expression.extract(exp)
            }
        }
        function _setBindingObj (expr) {
            var r = _parseExpr(expr)
            ast[r.name] = r
            ;(r.vars || []).forEach(function (v) {
                !revealAst[v] && (revealAst[v] = []);
                !~revealAst[v].indexOf(r.name) && revealAst[v].push(r.name)
            })
        }

        bindingData = execLiteral(dataExpr, parentVM, scope)
        bindingMethods = execLiteral(methods, parentVM, scope) // --> bindingMethods
        
        compVM = new Comp({
            el: node,
            data: bindingData,
            methods: bindingMethods,
            $parent: parentVM,
            $childrens: _slice(node.childNodes),
            replace: replace == 'true'
        })

        var plainDataExpr = _isDataExpr ? Expression.strip(dataExpr) : ''
        var sep = Expression.sep

        if (plainDataExpr) {
            if (plainDataExpr.match(sep)) {
                plainDataExpr.replace(new RegExp(sep + '\\s*$'), '') // trim last seperator
                       .split(sep)
                       .forEach(_setBindingObj)
            } else {
                _setBindingObj(plainDataExpr)
            }
        }
        // watch and binding
        if (_isDataExpr) {
            parentVM.$data.$watch(function (keyPath) {
                var nextState
                util.objEach(revealAst, function (varName, bindingNames) {
                    if (keyPath.indexOf(varName) === 0) {
                        ;!nextState && (nextState = {})
                        bindingNames.forEach(function (n) {
                            nextState[n] = execute(parentVM, scope, ast[n].expr)
                        })
                    }
                })
                nextState && compVM.$set(nextState)
            })
        }
        // set ref to parentVM
        ref && (parentVM.$refs[ref] = compVM)

        _components.push(compVM)
        _setBindings2Scope(scope, compVM)
        // TBM -- to be modify, instance method should not be attached here
        compVM.$update = function () {
            _isDataExpr && compVM.$set(execLiteral(dataExpr, parentVM, scope))
        }
        return compVM
    }
    /**
     *  Compile attributes to directive
     */
    function compileDirective (node, scope) {
        var ast = {
                attrs: {},
                dires: {}
            }
        var dirtDefs = _getAllDirts()
        /**
         *  attributes walk
         */
        _slice(node.attributes).forEach(function(att) {
            var aname = att.name
            var v = att.value
            // parse att
            if (~componentProps.indexOf(aname)) {
                return
            } else if (_isExpr(aname)) {
                // variable attribute name
                ast.attrs[aname] = v
            } else if (aname.indexOf(NS) === 0) {
                var def = dirtDefs[aname]
                if (def) {
                    // directive
                    ast.dires[aname] = {
                        def: def,
                        expr: v
                    }
                } else {
                    return
                }
            } else if (_isExpr(v.trim())) {
                // named attribute with expression
                ast.attrs[aname] = v
            } else {
                return
            }
            node.removeAttribute(aname)
        })

        /**
         *  Attributes binding
         */
        util.objEach(ast.attrs, function(name, value) {
            var attd = new AttributeDirective(vm, scope, node, name, value)
            _directives.push(attd)
            _setBindings2Scope(scope, attd)
        })

        /**
         *  Directives binding
         */
        util.objEach(ast.dires, function(dname, spec) {
            var def = spec.def
            var expr = spec.expr
            var sep = ';'
            var d
            // multiple defines expression parse
            if (def.multi && expr.match(sep)) {
                Expression.strip(expr)
                        .split(sep)
                        .forEach(function(item) {
                            // discard empty expression 
                            if (!item.trim()) return
                            
                            d = new Directive(vm, scope, node, def, dname, '{' + item + '}')
                            _directives.push(d)
                            _setBindings2Scope(scope, d)
                        })
            } else {
                d = new Directive(vm, scope, node, def, dname, expr)
                _directives.push(d)
                _setBindings2Scope(scope, d)
            }
        })
    }

    function compileText (node, vm, scope) {
        var originExpr = node.nodeValue
        var v = Expression.veil(originExpr)
        var exprReg = Expression.exprRegexp

        var parts = v.split(exprReg)
        var exprs = v.match(exprReg)

        var inst
        // expression match or not
        if (exprs && exprs.length) {
            inst = new TextDirective(vm, scope, node, originExpr, parts, exprs)
            _directives.push(inst)
            _setBindings2Scope(scope, inst)
        }
        return inst
    }
}
1142692
@Override
  public DynamicFactorGraph getModelFromParameters(SufficientStatistics parameters) {
    List<SufficientStatistics> parameterList = parameters.coerceToList().getStatistics();
    Preconditions.checkArgument(parameterList.size() == parametricFactors.size());
    List<PlateFactor> plateFactors = Lists.newArrayList();
    for (int i = 0; i < parameterList.size(); i++) {
      plateFactors.add(new ReplicatedFactor(
          parametricFactors.get(i).getModelFromParameters(parameterList.get(i)),
          factorPatterns.get(i)));
    }
    return baseFactorGraph.addPlateFactors(plateFactors, factorNames.items());
  }
539493
function queryExamplesData(graphql) {
  return graphql(`
    {
      site {
        siteMetadata {
          config {
            EXAMPLES {
              image
              title
              path
              componentUrl
            }
          }
        }
      }
      allImageSharp {
        edges {
          node {
            parent {
              id
            }
            resize(width: 150, height: 150) {
              src
            }
          }
        }
      }
      allFile {
        edges {
          node {
            id
            relativePath
          }
        }
      }
    }
  `)
  .then(result => {
    console.log(result);

    if (result.errors) {
      /* eslint no-console: "off" */
      console.log(result.errors);
      throw new Error(result.errors);
    }

    const { EXAMPLES } = result.data.site.siteMetadata.config;
    // build a lookup map that matches relative paths of images with their public URLs
    const thumbnailsPublicUrls = getExampleThumbnails(result.data);

    // matches public urls to paths of images
    const examplesWithImages = EXAMPLES.map(example => ({
      ...example,
      imageSrc: thumbnailsPublicUrls[example.image]
    }));

    return examplesWithImages;
  })
  .catch(error => {
    log.log(
      { color: COLOR.BRIGHT_YELLOW },
      `error in createPage query with images: ${error}`
    )();
    return graphql(`
      {
        site {
          siteMetadata {
            config {
              EXAMPLES {
                title
                path
              }
            }
          }
        }
      }
    `).then(result => {
      if (result.errors) {
        /* eslint no-console: "off" */
        console.log(result.errors);
        throw new Error(result.errors);
      }
      const { EXAMPLES } = result.data.site.siteMetadata.config;
      return EXAMPLES;
    });
  });
}
293466
function compatibilityValuesRamp (datasource, column, args) {
  var values = args[0];
  var method = (args[1] || 'quantiles').toLowerCase();
  var numBuckets = values.getLength();
  return getRamp(datasource, column, numBuckets, method).then(compatibilityCreateRampFn(values));
}