text:
These scripts are provided for inferring Boolean regulatory rules from single-cell expression profiles. The algorithm has been designed for use
with qRT-PCR data but could also be applied to other types of single-cell data measuring gene or protein expression.
The user should provide an initial list of possible activators and repressors of each gene, a binary gene expression matrix,
and a pseudotime ordering of cells along a differentiation trajectory.

## Network inference scripts
Two python scripts are provided for applying the network inference algorithm. Python can be downloaded from https://www.python.org/.
These scripts use the Microsoft Z3 theorem prover to identify
high scoring Boolean rules. Z3 can be downloaded from https://github.com/Z3Prover/z3 and installed following the instructions provided at
this link.

The script encodingFunctions.py provides Z3 encoding for the form and scoring of Boolean functions. Users can run the script
booleanRules.py to infer Boolean rules for a chosen gene. Users should change the line
```python
sys.path.append('/Users/fiona/z3/build')
```
to the path of the Z3 build on their own machine in both booleanRules.py and encodingFunctions.py. Additionally the line
```python
sys.path.append('Users/fiona/Desktop/PhD/MRes/Rotation_2/Code/Python/')
```
in booleanRules.py should be changed to the path of the network inference scripts.

To run this rule inference on the command line use the following command.

```python booleanRules.py gene expressionFile step orderFile maxAct maxRep networkFile threshold thresholdStep```

* **gene** = Name of gene for which rules are to be inferred, e.g Gata1.
* **expressionFile** = Path to the expression file. This is a binary gene expression matrix with column names equal to genes and
row names equal to cell names.
* **step** = An integer, e.g. 5. This is how far back in pseudotime to take as input for the boolean function evaluated at current time t.
So for step=5 the input to the boolean function at time t is given by the gene expression states at time t=t-5.
* **orderFile** = Path to pseudotime ordering file. This should be a list of cell names indicating the pseudotime ordering of cells.
These cells names should match those in expressionFile.
* **maxAct** = An integer from the set {0,1,2,3,4}. The number of activators allowed for each gene. Increasing this parameter can produce
more complex Boolean rules but will increase computation time.
* **maxRep** = An integer from the set {0,1,2,3,4}. The number of repressors allowed for each gene. Increasing this parameter can produce
more complex Boolean rules but will increase computation time.
* **networkFile** = Path to the network file. This indicates possible activators and repressors of each gene. Each line should be of the
form "from.gene relation to.gene" where the relation is either 1 (indicating activation) or -1 (indicating repression).
* **threshold** = A decimal in the range [0,1] giving the starting threshold for agreement of rules.
* **thresholdStep** = A decimal in the range [0,1] giving the increment in which the threshold will be lowered if no rules are found.

The rules found will be written to the file gene_boolean_rules_step.txt along with their score.

## Example script
Running this line of code would identify regulatory rules for *Bptf* in the LMPP network.

```python booleanRules.py Bptf binary_expression_LMPP.txt 5 LMPP_trajectory_order.txt 2 2 startingNetworkParCor.txt 0.95 0.05```

## Acknowledgements
I would like to thank Steven Woodhouse for help in writing the encoding of the Boolean functions - his scripts from the
[Single Cell Network Synthesis Toolkit](https://github.com/swoodhouse/SCNS-Toolkit) were an extremely useful starting point.

## License
Scripts for the pseudotime network inference algorithm are released under the Apache 2.0 license; see LICENSE for more details.


text:
layout: post
title: "Welcome to Binary's Technical Blog"
categories: [intro]
date: 2015-11-25T14:35:24+08:00
---

Hello All!

We would like to introduce Binary's technical blog.

We will publish tech articles from binary's developers and devops team here.

redpajama_set_name: RedPajamaGithub


text:
A little travelmap visualisation built with Raphaël, Async.js and CoffeeScript.
It was used in the context of a larger presentation and I thought it might be
share-worthy. [Have fun with the demo](http://2013-03-23.s3-website-eu-west-1.amazonaws.com/).

## Setup / Development

* `mm-server` to run local server in development mode
* `rake build` to package up
* `rake clean` to wipe the build directory

## Directory Structure -- Finding your way around

    app/               CoffeeScript sources for the app

    views/             Pages & Layouts
      stylesheets/     Compass/Sass sources for stylesheets
      index.html.haml  Home page content
      layout.haml      Default layout

    public/            Static assets
      images/          yeah, what you think it is
      javascripts/     "vendored" JS libs & init script

    build              Target dir for packaged build

    assets.yml         Jammit config
    config.rb          Middleman / Sinatra config


text:
<template #tpl>

ViewContainerRef

</template>


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

namespace Eto.Forms
{
	///
	/// Specifies which panel has a fixed size the parent container is resized.
	///
	public enum SplitterFixedPanel
	{
		///
		/// The first panel will be fixed size, where the second will resize along with the splitter's container.
		///
		Panel1,
		///
		/// The second panel will be fixed size, where the first will resize along with the splitter's container.
		///
		Panel2,
		///
		/// Both panels will resize along with the splitter's container.
		///
		None
	}

	///
	/// Control to show two panels separated by a splitter
	///
	/// <remarks>
	/// Most desktop platforms allow the user to modify the position of the splitter, though some (notibly iOS) do
	/// not.
	/// The <see cref="Orientation"/> of the splitter determines how the controls are laid out, either horizontally
	/// or vertically.
	/// </remarks>
	[Handler(typeof(Splitter.IHandler))]
	public class Splitter : Container
	{
		new IHandler Handler { get { return (IHandler)base.Handler; } }

		///
		/// Gets an enumeration of controls that are directly contained by this container
		///
		/// <value>The contained controls.</value>
		public override IEnumerable<Control> Controls
		{
			get
			{
				if (Panel1 != null)
					yield return Panel1;
				if (Panel2 != null)
					yield return Panel2;
			}
		}

		///
		/// Gets a value indicating the <see cref="Splitter"/> is supported in the platform
		///
		/// <value><c>true</c> if supported; otherwise, <c>false</c>.</value>
		public static bool IsSupported
		{
			get { return Platform.Instance.Supports<IHandler>(); }
		}

		#region Events

		///
		/// Identifier for the <see cref="PositionChanged"/> event
		///
		public const string PositionChangedEvent = "Splitter.PositionChanged";

		///
		/// Raised when the user moves the splitter.
		///
		public event EventHandler<EventArgs> PositionChanged
		{
			add { Properties.AddHandlerEvent(PositionChangedEvent, value); }
			remove { Properties.RemoveEvent(PositionChangedEvent, value); }
		}

		///
		/// Raises the <see cref="PositionChanged"/> event.
		///
		/// <param name="e">Event arguments.</param>
		protected virtual void OnPositionChanged(EventArgs e)
		{
			Properties.TriggerEvent(PositionChangedEvent, this, e);
		}

		#endregion

		static Splitter()
		{
			EventLookup.Register<Splitter>(c => c.OnPositionChanged(null), Splitter.PositionChangedEvent);
		}

		///
		/// Gets or sets the orientation of the panels in the splitter.
		///
		/// <remarks>
		/// This defines the orientation of the panels, with a splitter of the opposite orientation between them.
		/// For example, when set to <see cref="Orientation.Horizontal"/>, Panel1 and Panel2 will be horizontal to
		/// eachother with a vertical splitter/gutter between them.
		/// </remarks>
		/// <value>The orientation of the panels.</value>
		public Orientation Orientation
		{
			get { return Handler.Orientation; }
			set { Handler.Orientation = value; }
		}

		///
		/// Gets or sets the panel with fixed size.
		///
		/// <remarks>
		/// This specifies which panel will not change its size when the splitter's container is resized.
		/// If <see cref="SplitterFixedPanel.None"/>, both panels will resize.
		/// </remarks>
		/// <value>The fixed panel.</value>
		public SplitterFixedPanel FixedPanel
		{
			get { return Handler.FixedPanel; }
			set { Handler.FixedPanel = value; }
		}

		///
		/// Gets or sets the position of the splitter from the left or top, in pixels.
		///
		/// <value>The position of the splitter.</value>
		public int Position
		{
			get { return Handler.Position; }
			set { Handler.Position = value; }
		}

		///
		/// Gets or sets the relative position of the splitter which is based on <see cref="FixedPanel"/>.
		///
		/// <remarks>
		/// Same as <see cref="Position"/> with SplitterFixedPanel.Panel1,
		/// width/height of second panel with SplitterFixedPanel.Panel2
		/// and ratio of width/height of first panel against available size with SplitterFixedPanel.None.
		/// </remarks>
		public double RelativePosition
		{
			get { return Handler.RelativePosition; }
			set { Handler.RelativePosition = value; }
		}

		///
		/// Gets or sets size of the splitter/gutter
		///
		public int SplitterWidth
		{
			get { return Handler.SplitterWidth; }
			set { Handler.SplitterWidth = value; }
		}

		///
		/// Gets or sets the top or left panel of the splitter.
		///
		/// <value>The first panel.</value>
		public Control Panel1
		{
			get { return Handler.Panel1; }
			set
			{
				SetParent(value, () => Handler.Panel1 = value, Handler.Panel1);
			}
		}

		///
		/// Gets or sets the bottom or right panel of the splitter.
		///
		/// <value>The second panel.</value>
		public Control Panel2
		{
			get { return Handler.Panel2; }
			set
			{
				SetParent(value, () => Handler.Panel2 = value, Handler.Panel2);
			}
		}

		///
		/// Removes the specified child from the container.
		///
		/// <param name="child">Child to remove.</param>
		public override void Remove(Control child)
		{
			if (object.ReferenceEquals(Panel1, child))
			{
				Panel1 = null;
			}
			else if (object.ReferenceEquals(Panel2, child))
			{
				Panel2 = null;
			}
		}

		static readonly object callback = new Callback();
		///
		/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
		///
		/// <returns>The callback instance to use for this widget</returns>
		protected override object GetCallback() { return callback; }

		///
		/// Callback interface for the <see cref="Splitter"/>
		///
		public new interface ICallback : Container.ICallback
		{
			///
			/// Raises the position changed event.
			///
			void OnPositionChanged(Splitter widget, EventArgs e);
		}

		///
		/// Callback implementation for handlers of the <see cref="Splitter"/>
		///
		protected new class Callback : Container.Callback, ICallback
		{
			///
			/// Raises the position changed event.
			///
			public void OnPositionChanged(Splitter widget, EventArgs e)
			{
				widget.Platform.Invoke(() => widget.OnPositionChanged(e));
			}
		}

		///
		/// Handler interface for the <see cref="Splitter"/>
		///
		public new interface IHandler : Container.IHandler
		{
			///
			/// Gets or sets the orientation of the panels in the splitter.
			///
			/// <value>The orientation of the panels.</value>
			Orientation Orientation { get; set; }

			///
			/// Gets or sets the panel with fixed size.
			///
			/// <remarks>
			/// This specifies which panel will not change its size when the splitter's container is resized.
			/// If <see cref="SplitterFixedPanel.None"/>, both panels will resize.
			/// </remarks>
			/// <value>The fixed panel.</value>
			SplitterFixedPanel FixedPanel { get; set; }

			///
			/// Gets or sets the position of the splitter from the left or top, in pixels.
			///
			/// <value>The position of the splitter.</value>
			int Position { get; set; }

			///
			/// Gets or sets the relative position of the splitter which is based on <see cref="FixedPanel"/>.
			///
			/// <remarks>
			/// Same as <see cref="Position"/> with SplitterFixedPanel.Panel1,
			/// width/height of second panel with SplitterFixedPanel.Panel2
			/// and ratio of width/height of first panel against available size with SplitterFixedPanel.None.
			/// </remarks>
			double RelativePosition { get; set; }

			///
			/// Gets or sets size of the splitter/gutter
			///
			int SplitterWidth { get; set; }

			///
			/// Gets or sets the top or left panel of the splitter.
			///
			/// <value>The first panel.</value>
			Control Panel1 { get; set; }

			///
			/// Gets or sets the bottom or right panel of the splitter.
			///
			/// <value>The second panel.</value>
			Control Panel2 { get; set; }
		}
	}

	///
	/// Orientation of a <see cref="Splitter"/> control.
	///
	[Obsolete("Since 2.1: Use Orientation instead")]
	public struct SplitterOrientation
	{
		readonly Orientation orientation;

		SplitterOrientation(Orientation orientation)
		{
			this.orientation = orientation;
		}

		///
		/// Controls are in horizontal orientation, with a vertical divider between them.
		///
		public static SplitterOrientation Horizontal { get { return Orientation.Horizontal; } }

		///
		/// Controls are in vertical orientation, with a horizontal divider betwen them.
		///
		public static SplitterOrientation Vertical { get { return Orientation.Vertical; } }

		/// Converts to an Orientation
		public static implicit operator Orientation(SplitterOrientation orientation)
		{
			return orientation.orientation;
		}

		/// Converts an Orientation to a SplitterOrientation
		public static implicit operator SplitterOrientation(Orientation orientation)
		{
			return new SplitterOrientation(orientation);
		}

		/// Compares for equality
		/// <param name="orientation1">Orientation1.</param>
		/// <param name="orientation2">Orientation2.</param>
		public static bool operator ==(Orientation orientation1, SplitterOrientation orientation2)
		{
			return orientation1 == orientation2.orientation;
		}

		/// Compares for inequality
		/// <param name="orientation1">Orientation1.</param>
		/// <param name="orientation2">Orientation2.</param>
		public static bool operator !=(Orientation orientation1, SplitterOrientation orientation2)
		{
			return orientation1 != orientation2.orientation;
		}

		///
		/// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="Eto.Forms.SplitterOrientation"/>.
		///
		/// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="Eto.Forms.SplitterOrientation"/>.</param>
		/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current
		/// <see cref="Eto.Forms.SplitterOrientation"/>; otherwise, <c>false</c>.</returns>
		public override bool Equals(object obj)
		{
			return (obj is SplitterOrientation && (this == (SplitterOrientation)obj))
				|| (obj is Orientation && (this == (Orientation)obj));
		}

		///
		/// Serves as a hash function for a <see cref="Eto.Forms.SplitterOrientation"/> object.
		///
		/// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a hash table.</returns>
		public override int GetHashCode()
		{
			return orientation.GetHashCode();
		}
	}

}


text:
<?php

namespace controllers;

use \helpers\session,
    \helpers\url,
    \core\view;

class Inicio extends \core\controller {

    private $_componente;
    private $_archivoNombre;
    private $_model;

    public function __construct() {
        $this->_model = new \models\admin\auth();
        $this->_componente = new \models\admin\componente();

        $this->clase = "inicio";
        $this->_archivoNombre = "inicio.php";
        $this->_archivo["raiz"]["componente_archivo"] = $this->_archivoNombre;
        $this->_archivo["raiz"]["componente_enlace"] = "inicio";
        $this->_archivo["raiz"]["componente_url"] = DIR;
        $this->_archivo["raiz"]["componente_nombre"] = "Cambios el Saman";
        $this->_archivo["raiz"]["componente_slug"] = url::generateSafeSlug($this->_archivo["raiz"]["componente_nombre"]);

        foreach ($this->_archivo as $componente) {
            $this->_componente->createComponente($componente["componente_nombre"], $componente["componente_enlace"], $componente["componente_url"], $componente);
        }

        $this->_componente->controlAcceso();
    }

    public function index() {
        $data["title"] = $this->_archivo["raiz"]["componente_nombre"];
        view::apptemplate("header", $data);
        view::render($this->_archivo["raiz"]["componente_enlace"], $data);
        view::apptemplate("footer", $data);
    }

}


text:
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../constants/counter';

export default (state = 0, action) => {
  switch (action.type) {
    case INCREMENT_COUNTER:
      return state + 1;
    case DECREMENT_COUNTER:
      return state - 1;
    default:
      return state;
  }
};


text:
.. _metrics-page:

*******
Metrics
*******

This section details how the resource usage metrics from the :ref:`Execution report <execution-report>` are computed.

CPU Usage
=========

The plot reports how much CPU resources were used by each process.

.. image:: images/report-resource-cpu.png

Let's illustrate how this plot behaves with several examples.

In the first example, let's consider the simple use case in which a process performs one task of pure computation using one CPU. Then, you expect the `Raw Usage` tab to report 100%. If the task is distributed over, 2, 3, 4, `etc.` CPUs, then the `Raw Usage` will be 200%, 300%, 400%, `etc.` respectively. The `% Allocated` tab just rescales the raw value usage with respect to the number of CPUs set with the ``cpus`` directive (if not set with the directive, the number of CPUs is set to 1, thus showing the same values as in the `Raw Usage` tab). Using the program `stress <https://people.seas.harvard.edu/~apw/stress/>`_  as follows would report 100% in the `Raw Usage` tab  and 50% in the `% Allocated` tab since the process asked twice the number of CPUs needed by the process::

  #!/usr/bin/env nextflow

  process CpuUsageEx1 {
    cpus 2

    """
    stress -c 1 -t 10 # compute square-root of random numbers during 10s using 1 CPU
    """
  }

In the second example, some time will be spent performing pure computation and some time just waiting. Using the program `stress <https://people.seas.harvard.edu/~apw/stress/>`_  and ``sleep`` as follows would report 75% in the `Raw Usage` tab::

  #!/usr/bin/env nextflow

  process CpuUsageEx2 {
    cpus 1

    """
    stress -c 1 -t 10 # compute square-root of random numbers during 10s using 1 CPU
    stress -c 1 -t 5 # compute square-root of random numbers during 5s using 1 CPU
    sleep 5 # use no CPU during 5s
    """
  }

Indeed, the percentage of the CPU that this process got is a weighted average taking into account the percentage of the CPU and duration of each individual program over the job duration (a.k.a. elapsed real time, real time or wall time ) as follows:

.. math::
  \frac{ 100\% \times 10s + 100\% \times 5s + 0\% \times 5s }{10s+5s+5s} = 75\%

The third example is similar to the second one except that the pure computation stage is performed in a single step forked on 2 CPUs::

  #!/usr/bin/env nextflow

  process CpuUsageEx3 {
    cpus 2

    """
    stress -c 2 -t 10 # compute square-root of random numbers during 10s using 2 CPUs
    sleep 10 # use no CPU during 10s
    """
  }

The `Raw Usage` tab would report 100% in the `Raw Usage` tab:

.. math::
  \frac{ 200\% \times 10s }{10s+10s} = 100\%

The `% Allocated` tab would report 50%, however, it would not be relevant to change the ``cpus`` directive from 2 to 1 as the process really uses 2 CPUs at it peak load.

.. tip::
  The `stress <https://people.seas.harvard.edu/~apw/stress/>`_ program can be installed with ``sudo apt-get install stress`` or ``sudo yum install stress`` depending on your Linux distribution.

Memory Usage
============

The plot has three tabs showing the usage of the physical memory (RAM), the virtual memory (vmem) and the percentage of RAM used by the process with respect to what was set in the ``memory`` directive. The peak usage during the execution of the process is reported for both physical and virtual memories.

.. note::
  To better understand the memory usage plot, it is important to know that:

  - the total amount of memory used by a processs is the `virtual memory (vmem)`. The ``vmem`` contains all memory areas whether they are in the physical memory (RAM), in the Swap space, on the disk or shared with other processes,
  - the `resident set size (RSS)` is the amount of space of `physical memory (RAM)` held by a process,
  - the relationship is: vmem :math:`\geq` RSS + Swap,
  - the ``memory`` directive sets the RAM requested by the process.

Let's illustrate how this plot behaves with one example which relies on two C programs.

The first program just allocates a variable of 1 GiB:

.. code-block:: c
   :linenos:
   :emphasize-lines: 31,43

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/resource.h>
    #include <sys/time.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <time.h>

    /* Get vmem and rss usage from /proc/<pid>/statm */
    static int mem_used(pid_t pid, unsigned long* vmem, unsigned long* rss) {
        FILE* file;
        char path[40];
        unsigned int page_size;

        snprintf(path, 40, "/proc/%ld/statm", (long) pid);
        file = fopen(path, "r");
        // vmem and rss are the first values in the file
        fscanf(file, "%lu %lu", vmem, rss);
        // values in statm are in pages so to get bytes we need to know page size
        page_size = (unsigned) getpagesize();
        *vmem = *vmem * page_size;
        *rss = *rss * page_size;

        fclose(file);
        return 0;
    }

    int main(int argc, char **argv) {
        unsigned char *address;
        char input;
        size_t size = 1024*1024*1024;  // 1 GiB
        unsigned long i;
        unsigned long vmem = 0;
        unsigned long rss = 0;
        pid_t pid;

        pid = getpid();
        printf("Pid: %ld\n", (long) pid);

        mem_used(pid, &vmem, &rss);
        printf("VMEM: %lu RSS: %lu\n", vmem, rss);

        address = malloc(size);
        printf("Allocated %d Bytes of memory\n", (int) size);

        mem_used(pid, &vmem, &rss);
        printf("VMEM: %lu RSS: %lu\n", vmem, rss);

        // Leave time for nextflow to get information
        sleep(15);

        free(address);
        return 0;
    }

The second program allocates a variable of 1 GiB and fills it with data:

.. code-block:: c
   :linenos:
   :emphasize-lines: 31,43,49-53

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/resource.h>
    #include <sys/time.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <time.h>

    /* Get vmem and rss usage from /proc/<pid>/statm */
    static int mem_used(pid_t pid, unsigned long* vmem, unsigned long* rss) {
        FILE* file;
        char path[40];
        unsigned int page_size;

        snprintf(path, 40, "/proc/%ld/statm", (long) pid);
        file = fopen(path, "r");
        // vmem and rss are the first values in the file
        fscanf(file, "%lu %lu", vmem, rss);
        // values in statm are in pages so to get bytes we need to know page size
        page_size = (unsigned) getpagesize();
        *vmem = *vmem * page_size;
        *rss = *rss * page_size;

        fclose(file);
        return 0;
    }

    int main(int argc, char **argv) {
        unsigned char *address;
        char input;
        size_t size = 1024*1024*1024;  // 1 GiB
        unsigned long i;
        unsigned long vmem = 0;
        unsigned long rss = 0;
        pid_t pid;

        pid = getpid();
        printf("Pid: %ld\n", (long) pid);

        mem_used(pid, &vmem, &rss);
        printf("VMEM: %lu RSS: %lu\n", vmem, rss);

        address = malloc(size);
        printf("Allocated %d Bytes of memory\n", (int) size);

        mem_used(pid, &vmem, &rss);
        printf("VMEM: %lu RSS: %lu\n", vmem, rss);

        printf("Filling memory with data...");
        fflush(stdout);
        for (i = 0; i < size; i++) {
            *(address + i) = 123;
        }

        mem_used(pid, &vmem, &rss);
        printf("\nVMEM: %lu RSS: %lu\n", vmem, rss);

        // Leave time for nextflow to get information
        sleep(15);

        free(address);
        return 0;
    }

The first and second programs are executed in ``foo`` and ``bar`` processes respectively as follows::

  #!/usr/bin/env nextflow

  process foo {
      memory '1.5 GB'

      """
      memory_vmem_1GiB_ram_0Gib
      """
  }

  process bar {
      memory '1.5 GB'

      """
      memory_vmem_1GiB_ram_1Gib
      """
  }

The `Virtual (RAM + Disk swap)` tab shows that both ``foo`` and ``bar`` processes use the same amount of virtual memory (~1 GiB):

.. image:: images/report-resource-memory-vmem.png

However, the `Physical (RAM)` tab shows that only the ``bar`` process uses ~1 GiB of RAM while ``foo`` process uses  ~0 GiB:

.. image:: images/report-resource-memory-ram.png

As expected, the `% RAM Allocated` tab shows that 0% of the resource set in the ``memory`` directive was used for ``foo`` process while 67% (= 1 / 1.5) of the resource were used for ``bar`` process:

.. image:: images/report-resource-memory-pctram.png

.. warning::
  Memory and storage metrics are reported in bytes. This means that 1KB = :math:`1024` bytes, 1 MB = :math:`1024^2` bytes, 1 GB = :math:`1024^3` bytes, etc.

Job Duration
============

The plot has two tabs the job duration (a.k.a. elapsed real time, real time or wall time ) in the `Raw Usage` tag and the percentage  of requested time used in the `% Allocated` tab with respect to the duration set in the ``time`` directive of the process.

.. image:: images/report-resource-job-duration.png

I/O Usage
=========

The plot has two tabs showing how many data were read and/or written each process. For example, the following processes read and write 1GB and 256MB of data respectively::

    #!/usr/bin/env nextflow

    process io_read_write_1G {
      """
      dd if=/dev/zero of=/dev/null bs=1G count=1
      """
    }

    process io_read_write_256M {
      """
      dd if=/dev/zero of=/dev/null bs=256M count=1
      """
    }

`Read` tab:

.. image:: images/report-resource-io-read.png

`Write` tab:

.. image:: images/report-resource-io-write.png


text:
using System;
using System.Linq;

namespace P01.ListyIterator
{
    public class Program
    {
        static void Main()
        {
            string[] createArgs = Console.ReadLine().Split(' ');

            var listyIterator = new ListyIterator<string>(createArgs.Skip(1).ToList());

            string input = string.Empty;
            while ((input = Console.ReadLine()) != "END")
            {
                try
                {
                    switch (input)
                    {
                        case "HasNext":
                            Console.WriteLine(listyIterator.HasNext());
                            break;
                        case "Move":
                            Console.WriteLine(listyIterator.Move());
                            break;
                        case "Print":
                            listyIterator.Print();
                            break;
                        case "PrintAll":
                            Console.WriteLine(string.Join(" ", listyIterator));
                            break;
                    }
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
}


text:
<!DOCTYPE html>

        <title>{{ if eq .title nil }}{{ .info.Name }}{{ else }}{{ .title }} - {{ .info.Name }}{{ end }}</title>
        <meta content="{{ .info.Name }}" name="author">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,900' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" type="text/css" href="/public/css/today.css">
        <link rel="shortcut icon" type="image/png" href="/public/img/favicon.png">

        {{ range .moreStyles }}
            <link rel="stylesheet" type="text/css" href="/public/{{.}}">
        {{ end }}

                Home

{{ .info.Name }}

{{ .info.Tagline }}

                            @{{ .info.Twitter }}

                            @{{ .info.Github }}

                            email

                            rss


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

    <description>
      Servlet configuration for NorthBreeze demo
    </description>
    <display-name>Servlet configuration for NorthBreeze demo</display-name>

    <!-- Initialize the app configuration upon startup -->
    <listener>
      <listener-class>northwind.service.AppContextListener</listener-class>
    </listener>

<!--
    <filter>
        <filter-name>Request Dumper Filter</filter-name>
        <filter-class>org.apache.catalina.filters.RequestDumperFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Request Dumper Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
-->

    <!-- Define servlets  -->
  <servlet>
    <servlet-name>Jersey</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
	<init-param>
	    <param-name>jersey.config.server.provider.classnames</param-name>
	    <param-value>
	        northwind.service.NorthBreeze
	    </param-value>
	</init-param>
	<init-param>
	    <param-name>jersey.config.server.tracing</param-name>
	    <param-value>ALL</param-value>
	</init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Jersey</servlet-name>
    <url-pattern>/breeze/*</url-pattern>
  </servlet-mapping>

</web-app>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ado_net_gemfirexd_client.Properties;
using Pivotal.Data.GemFireXD;
using System.Data;
using ado_net_sqlsvr_client.Properties;

namespace ado_net_gemfirexd_client.ViewModels
{
    public class BulkInsertUpdateDeleteViewModel
    {
        public BulkInsertUpdateDeleteViewModel()
        {
            // load the connection string from the configuration files
            _connectionString = Settings.Default.AdventureWorksConnectionString;
        }

        public void LoadTableRowListData(string table)
        {
            using (var conn = new GFXDClientConnection(ConnectionString))
            {
                conn.Open();

                // load no data 1=0, but get the columns...
                string[] words = table.Split('.');
                string query =
                   "SELECT * FROM " + table + " order by " + words[1] + "ID";
                GFXDCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;

                var da = new GFXDDataAdapter(cmd);
                _dtTableDataRows.Clear();
                da.Fill(_dtTableDataRows);

            }
        }

        // only show grid data after button pressed...
        private DataTable _dtTableDataRows = new DataTable();
        public DataTable GridData
        {
            get
            {
                return _dtTableDataRows;
            }
        }

        private string _connectionString = string.Empty;
        public string ConnectionString
        {
            get { return _connectionString; }
            set
            {
                _connectionString = value;
                // OnPropertyChanged("ConnectionString");
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<tei xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
	<teiHeader>
		<fileDesc>
			<sourceDesc>
				<biblStruct>
					<analytic>
						<author>

						<affiliation>
							<address>
								<settlement>Rosharon</settlement>,
								<region>Texas</region>,
								<country>USA</country>
							<lb/>
							</address>
						</affiliation>
						<affiliation>
							<orgName type="institution">Shell Global Solutions (US Inc.)</orgName>
							<lb/>
							<address>
								<settlement>Houston</settlement>,
								<region>Texas</region>
							</address>
						</affiliation>

						</author>
					</analytic>
				</biblStruct>
			</sourceDesc>
		</fileDesc>
	</teiHeader>
</tei>


text:
import { DEMO_TYPE } from '../actions/types';

export default function (state = {}, action) {
    switch (action.type) {
        case DEMO_TYPE:
            return {...state};
    }

    return state;
}


text:
package controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.core.Config;
/**
 *
 */
@WebServlet(name = "Language",
            urlPatterns = {"/chooseLanguage"})
public class LanguageServlet extends SimpleAffableBeanServlet {

    private static final List<String> SUPPORTED_LANGUAGES = Arrays.asList("en", "cs");

    /**
     * Handles the HTTP GET method.
     *
     * @param request  servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException      if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        HttpSession session = request.getSession();

        // get language choice
        String language = request.getParameter("language");

        // get relative url to redirect back to
        String relativeReturnUrl = request.getParameter("relativeReturnUrl");

        // make a locale out of the language
        Locale locale;
        if (isUnsupported(language)) {
            locale = getFallbackLocale(request);
        } else {
            locale = new Locale(language, "");
        }

        // establish jstl and response locale
        Config.set(session, Config.FMT_LOCALE, locale);
        response.setLocale(locale);

        doTemporaryRedirect(request, response, relativeReturnUrl);
    }

    private boolean isUnsupported(String language) {
        return language == null || language.isEmpty() || !SUPPORTED_LANGUAGES.contains(language);
    }

    private Locale getFallbackLocale(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Locale locale;
        locale = (Locale) Config.get(session, Config.FMT_LOCALE);
        if (locale == null) {
            locale = request.getLocale();
            if (locale == null) {
                locale = (Locale) Config.get(session, Config.FMT_FALLBACK_LOCALE);
                if (locale == null) {
                    locale = Locale.getDefault();
                }
            }
        }
        return locale;
    }
}


text:
<?php
namespace Scalr\Service\Aws\Ec2\DataType;

use Scalr\Service\Aws\Ec2\Ec2ListDataType;

/**
 * GroupList
 *
 * @author   Vitaliy Demidov   <vitaliy@scalr.com>
 * @since    09.01.2013
 *
 * @method   \Scalr\Service\Aws\Ec2\DataType\GroupData get()
 *           get(int $index)
 *           Gets the GroupData object from the specified position in the list.
 */
class GroupList extends Ec2ListDataType
{

    /**
     * Constructor
     *
     * @param array|GroupData  $aListData List of GroupData objects
     */
    public function __construct($aListData = null)
    {
        parent::__construct($aListData, array('groupId', 'groupName'), __NAMESPACE__ . '\\GroupData');
    }

    /**
     * {@inheritdoc}
     * @see Scalr\Service\Aws\DataType.ListDataType::getQueryArray()
     */
    public function getQueryArray($uriParameterName = 'Group', $member = true)
    {
        return parent::getQueryArray($uriParameterName, $member);
    }
}


text:
=======
Credits
=======

Development Lead
----------------

* Michael Warkentin <mwarkentin@gmail.com> - https://github.com/mwarkentin - `@mwarkentin <https://twitter.com/mwarkentin>`_

Contributors
------------

* Keryn Knight - https://github.com/kezabelle
* blag - https://github.com/blag


text:
/**
 * Created by Ardobras on 02.07.2015.
 */

$(document).ready(loadQ);

var queue,spriteSheet;

function loadQ() {
    queue = new createjs.LoadQueue(true);
    queue.loadFile({id:"coin", src:"images/coin.png"});
    queue.loadFile({id:"coin_invulnerable", src:"images/coin_invulnerable.png"});
    queue.loadFile({id:"coin_bad", src:"images/coin_bad.png"});
    queue.loadFile({id:"bg", src:"images/background2.jpg"});
    createjs.Sound.registerSound("sounds/jump.mp3", "jump");
    createjs.Sound.registerSound("sounds/coin.wav", "coin");
    createjs.Sound.registerSound("sounds/death.mp3", "death");
    var data = {
        images: ["images/sprite.png"],
        frames: {width:48, height:48},
        animations: {
            dead:[0],
            jump:[1],
            run: {
                frames: [5, 6, 7 , 6],
                speed:0.1
            }
        }
    };

    spriteSheet = new createjs.SpriteSheet(data);
    queue.on("complete", mainMenu, this);
}

function init() {
    console.log("Hello WORLD");

    var stage = new createjs.Stage("canvas");
    createjs.Touch.enable(stage);

    stage.canvas.width = $(window).width();
    stage.canvas.height = $(window).height();

    var skyhigh = stage.canvas.height - 600 - 150;

    if(skyhigh > 0) {
        var sky = new createjs.Shape();
        sky.graphics.beginFill('rgb(16,43,206)').drawRect(0, 0, stage.canvas.width, skyhigh);
        sky.x = 0;
        sky.y = 0;
        stage.addChild(sky);
    }

    var bg1 = new createjs.Bitmap(queue.getResult("bg"));
    var bg2 = new createjs.Bitmap(queue.getResult("bg"));

    bg1.y = stage.canvas.height - 150 - 600;
    bg2.y = stage.canvas.height - 150 - 600;

    bg1.x = 0;
    bg2.x = 2500;

    stage.addChild(bg1);
    stage.addChild(bg2);

    animate(bg1);
    animate2();

    var bg_speed = 8000;

    function animate(bg) {
        createjs.Tween.get(bg)
            .to({x: -2500}, bg_speed, createjs.Ease.linear).call(
            function() {
                bg.x = 2500;
                createjs.Tween.get(bg).to({ x: 0 }, bg_speed, createjs.Ease.linear).call(function () {
                    animate(bg);
                });
            }
        )
    }

    function animate2() {
        createjs.Tween.get(bg2)
            .to({x: 0}, bg_speed, createjs.Ease.linear).call(
            function() {
                animate(bg2);
            }
        )
    }

    var floor = new createjs.Shape();
    floor.height = 150;
    floor.graphics.beginFill('rgb(55,56,69)').drawRect(0, 0, stage.canvas.width, floor.height);
    floor.x = 0;
    floor.y = stage.canvas.height - floor.height;
    stage.addChild(floor);

    var player = new Player();
    player.create();

    $(document).off("keydown");
    $(document).on('keydown',function(event) {
        if(event.keyCode == 32) {
            if(player.isAlive) {
                player.jump();
            } else {
                if(!player.tween) reset();
            }
        }
    });

    $(document).off("touchstart");
    $(document).on('touchstart',function() {
        if(player.isAlive) {
            player.jump();
        } else {
            if(!player.tween) reset();
        }
    });

    function Player(sprite) {
        this.isAlive = true;
        this.sprite = sprite;
        this.width = 40;
        this.height = 48;
        this.jumpheight = 100;
        this.collides = {
            points:0,
            on:true
        };
        this.create = function() {
            var pSprite = new createjs.Sprite(spriteSheet, "run");
            pSprite.x = this.x = (stage.canvas.width / 2 ) - this.width / 2 ;
            pSprite.y = this.y =  stage.canvas.height - floor.height - this.height;
            this.sprite = stage.addChild(pSprite);
        };
        this.die = function() {
            this.isAlive = false;
            createjs.Tween.removeTweens(this.sprite);
            createjs.Sound.play("death");
            stage.removeChild(this.sprite);
            var pSprite = new createjs.Sprite(spriteSheet, "dead");
            pSprite.x = this.x = (stage.canvas.width / 2 ) - this.width / 2 ;
            pSprite.y = this.y =  stage.canvas.height - floor.height - this.height;
            this.sprite = stage.addChild(pSprite);
            var context = this;
            this.tween = createjs.Tween.get(this.sprite)
                .to({ y: this.y - this.jumpheight }, 500, createjs.Ease.circOut)
                .to({ y: stage.canvas.height }, 500, createjs.Ease.circIn).call(function() {context.tween = null})
        };
        this.jump = function() {
            if(!this.tween) {
                stage.removeChild(this.sprite);
                var pSprite = new createjs.Sprite(spriteSheet, "jump");
                pSprite.x = this.x = (stage.canvas.width / 2 ) - this.width / 2 ;
                pSprite.y = this.y =  stage.canvas.height - floor.height - this.height;
                this.sprite = stage.addChild(pSprite);
                var context = this;
                createjs.Sound.play("jump");
                this.tween = createjs.Tween.get(this.sprite)
                    .to({ y: this.y - this.jumpheight }, 500, createjs.Ease.circOut)
                    .to({ y: this.y }, 500, createjs.Ease.circIn).call(function() {
                        context.tween = null;
                        stage.removeChild(context.sprite);
                        var pSprite = new createjs.Sprite(spriteSheet, "run");
                        pSprite.x = context.x = (stage.canvas.width / 2 ) - context.width / 2 ;
                        pSprite.y = context.y =  stage.canvas.height - floor.height - context.height;
                        context.sprite = stage.addChild(pSprite);

                    })
            }
        };
        this.collect = function() {
            createjs.Sound.play("coin");
        };
    }

    var scoreText = new createjs.Text("Coins: 0", "20px Arial", "#fff");
    scoreText.x = (stage.canvas.width * 0.9);
    scoreText.y = Math.round(stage.canvas.height * 0.05);
    scoreText.textAlign = "center";
    scoreText.score = 0;

    stage.addChild(scoreText);

    //Obstacles

    var obstacles = [], speed = 4, coins = [], specialtext_good, specialtext_bad, obstacle_factor = 0.001;

    function obstacleCourse() {

        if(obstacles.length < 1 || Math.random() < (0.001 * scoreText.score / 5) + obstacle_factor) {
            createObstacle();
        }

        if(Math.random() < 0.005) {
            createCoin();
        }

        coins.forEach(function(coin) {
            if(checkCollision(coin)) {
                if(!coin.scored) {
                    coin.scored = true;
                    createjs.Tween.removeTweens(coin);
                    stage.removeChild(coin);
                    coins = coins.filter(function(element,i){
                        return element.id !== coin.id;
                    });
                    if(coin.hasOwnProperty("special")) {

                        switch (coin.special) {
                            case "invulnerable":
                                if(player.collides.points == 0) {
                                    specialtext_good = new createjs.Text("Invulernable!", stage.canvas.width / 35 + "px Arial", "#0F0");
                                    specialtext_good.x = (stage.canvas.width / 2);
                                    specialtext_good.y = Math.round(stage.canvas.height * 0.1);
                                    specialtext_good.textAlign = "center";
                                    stage.addChild(specialtext_good);
                                    player.collides.on = false;
                                }

                                player.collides.points++;

                                setTimeout(function(){
                                    player.collides.points--;
                                    if(player.collides.points == 0) {
                                        player.collides.on = true;
                                        stage.removeChild(specialtext_good);
                                        specialtext_good = null;
                                    }
                                },5000);

                                break;
                            case "bad":

                                if(specialtext_bad == null) {
                                    specialtext_bad = new createjs.Text("More obstacles :(", stage.canvas.width / 35 + "px Arial", "#F00");
                                    specialtext_bad.x = (stage.canvas.width / 2);
                                    specialtext_bad.y = Math.round(stage.canvas.height * 0.15);
                                    specialtext_bad.textAlign = "center";
                                    stage.addChild(specialtext_bad);
                                }
                                obstacle_factor = obstacle_factor + 0.001;

                                setTimeout(function(){

                                    stage.removeChild(specialtext_bad);
                                    specialtext_bad = null;

                                },1000);

                                break;
                        }

                    } else {
                        scorePoint();
                    }
                    player.collect();

                }

            }
        });

        obstacles.forEach(function(obstacle) {
            if(player.collides.on && checkCollision(obstacle)) {
                player.die();
            }
        });

        function checkCollision(obstacle) {
            if(player.x + player.width > obstacle.x && player.x < obstacle.x + obstacle.width) {
                if(player.sprite.y + player.height < obstacle.y) {
                    return false;
                }
                return player.sprite.y <= obstacle.y + obstacle.height;
            }
            return false;
        }

    }

    function createObstacle() {
        var width = Math.round(Math.random() * 70 + 10);
        var height = Math.round(Math.random() * 50 + 30);

        var obstacle = new createjs.Shape();
        obstacle.graphics.beginFill('grey').drawRect(0, 0, width, height);
        obstacle.x = stage.canvas.width - width;
        obstacle.y = stage.canvas.height - 150 - height;
        obstacle.width = width;
        obstacle.height = height;
        stage.addChild(obstacle);

        createjs.Tween.get(obstacle)
            .to({ x: 0 - obstacle.width }, stage.canvas.width * speed, createjs.Ease.linear)
            .call(function() {
                stage.removeChild(obstacle);
                obstacles.shift();
            });
        obstacles.push(obstacle);
    }

    function createCoin() {

        var width = 30;
        var height = 30;

        var coin;

        var random = Math.random();

        if(random < 0.05) {
            coin = new createjs.Bitmap(queue.getResult("coin_invulnerable"));
            coin.special = "invulnerable";
        } else if(random > 0.9) {
            coin = new createjs.Bitmap(queue.getResult("coin_bad"));
            coin.special = "bad";
        } else {
            //Normaler Coin
            coin = new createjs.Bitmap(queue.getResult("coin"));
        }

        coin.x = stage.canvas.width;
        coin.y = stage.canvas.height - 150 - (Math.random() * 100) - height;
        coin.width = width;
        coin.height = height;
        stage.addChild(coin);

        coin.id = Math.round(random * 100);
        coin.scored = false;

        createjs.Tween.get(coin)
            .to({ x: 0 - coin.width }, stage.canvas.width * speed, createjs.Ease.linear)
            .call(function() {
                stage.removeChild(coin);
                delete coins[coin.id];
            });
        if(typeof coins[coin.id] === "undefined") {
            coins[coin.id] = coin;
        } else {
            var repeat = true;
            do {
                var id = Math.round(Math.random() * 100);
                if(typeof coins[id] === "undefined") {
                    coin.id = id;
                    coins[id] = coin;
                    repeat = false;
                }
            } while(repeat);
        }
        coins.push(coin);
    }

    //GameLoop
    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener("tick", tick);

    var text,restart,once;

    function tick() {
        if(player.isAlive) {
            stage.update();
            obstacleCourse();
        } else {
            if(!once) {
                if(specialtext_bad) stage.removeChild(specialtext_bad);
                if(specialtext_good) stage.removeChild(specialtext_good);

                console.log("Collision! :(");
                text = new createjs.Text("GAME OVER", "25px Arial", "#fff");
                text.x = (stage.canvas.width / 2);
                text.y = Math.round(stage.canvas.height * 0.1);
                text.textAlign = "center";

                text.textBaseline = "alphabetic";
                stage.addChild(text);
                restart = new createjs.Text("RESTART? (Press Space / Touch)", "25px Arial", "#FFF");
                restart.x = (stage.canvas.width / 2);
                restart.y = Math.round(stage.canvas.height * 0.15);
                restart.textBaseline = "alphabetic";
                restart.textAlign = "center";
                stage.addChild(restart);
                restart.addEventListener("click",reset);
                obstacles.forEach(function(obstacle) {
                    createjs.Tween.removeTweens(obstacle);
                });
                coins.forEach(function(coin) {
                    createjs.Tween.removeTweens(coin);
                });
                createjs.Tween.removeTweens(bg1);
                createjs.Tween.removeTweens(bg2);
                once = "done";
            }
            stage.update();
        }
    }

    function reset() {
        createjs.Ticker.off("tick");
        stage.autoClear = true; // This must be true to clear the stage.
        stage.removeAllChildren();
        init();
        stage.update();
    }

    function scorePoint(reset) {
        if(reset) {
            scoreText.text = "Coins: 0";
            scoreText.score = 0;
        } else {
            scoreText.text = "Coins: " + ++scoreText.score;
        }
    }
}

function mainMenu() {
    var stage = new createjs.Stage("canvas");

    stage.canvas.width = $(window).width();
    stage.canvas.height = $(window).height();

    $(document).off("keydown");
    $(document).on('keydown',function(event) {
        if(event.keyCode == 32) {
            init();
        }
    });

    $(document).off("touchstart");
    $(document).on('touchstart',function() {
        init();
    });

    var sky = new createjs.Shape();
    sky.graphics.beginFill('rgb(0,0,128)').drawRect(0, 0, stage.canvas.width, stage.canvas.height);
    sky.x = 0;
    sky.y = 0;
    stage.addChild(sky);

    var pSprite = new createjs.Sprite(spriteSheet, "run");
    pSprite.x = (stage.canvas.width / 2 );
    pSprite.y =  stage.canvas.height * 0.5;
    stage.addChild(pSprite);

    var text = new createjs.Text("Mario on the moon", stage.canvas.width / 15 + "px Arial", "#ffffff");
    text.x = (stage.canvas.width / 2);
    text.y = Math.round(stage.canvas.height * 0.2);
    text.textAlign = "center";
    stage.addChild(text);

    var start = new createjs.Text("Press Space / Touch to start", stage.canvas.width / 22 + "px Arial", "#ffffff");
    start.x = (stage.canvas.width / 2);
    start.y = Math.round(stage.canvas.height * 0.8);
    start.textAlign = "center";
    stage.addChild(start);

    stage.update();
}


text:
VERSION=$1
if [[ ! -z $VERSION ]]; then
    cp ../../target/openvidu-server-*.jar ./openvidu-server.jar
    docker build --pull --no-cache --rm=true -t openvidu/openvidu-dev:$VERSION .
    rm ./openvidu-server.jar
else
    echo "Error: You need to specify a version as first argument"
fi


text:
<?php

namespace CC\DataBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Curriculum
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Curriculum
{
    /**
     * @var string
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="abbreviation", type="string", length=255)
     */
    private $abbreviation;

    /**
     * @var string
     *
     * @ORM\Column(name="fullName", type="string", length=255)
     */
    private $fullName;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="College", inversedBy="curricula")
     * @ORM\JoinColumn(name="college_abbr", referencedColumnName="abbreviation", onDelete="CASCADE")
     **/
    private $college;

    /**
     * @ORM\OneToMany(targetEntity="Course", mappedBy="curriculum")
     **/
    private $courses;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set abbreviation
     *
     * @param string $abbreviation
     * @return Curriculum
     */
    public function setAbbreviation($abbreviation)
    {
        $this->abbreviation = $abbreviation;

        return $this;
    }

    /**
     * Get abbreviation
     *
     * @return string
     */
    public function getAbbreviation()
    {
        return $this->abbreviation;
    }

    /**
     * Set fullName
     *
     * @param string $fullName
     * @return Curriculum
     */
    public function setFullName($fullName)
    {
        $this->fullName = $fullName;

        return $this;
    }

    /**
     * Get fullName
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->fullName;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Curriculum
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set college
     *
     * @param \CC\DataBundle\Entity\College $college
     * @return Curriculum
     */
    public function setCollege(\CC\DataBundle\Entity\College $college = null)
    {
        $this->college = $college;

        return $this;
    }

    /**
     * Get college
     *
     * @return \CC\DataBundle\Entity\College
     */
    public function getCollege()
    {
        return $this->college;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->courses = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add courses
     *
     * @param \CC\DataBundle\Entity\Course $courses
     * @return Curriculum
     */
    public function addCourse(\CC\DataBundle\Entity\Course $courses)
    {
        $this->courses[] = $courses;

        return $this;
    }

    /**
     * Remove courses
     *
     * @param \CC\DataBundle\Entity\Course $courses
     */
    public function removeCourse(\CC\DataBundle\Entity\Course $courses)
    {
        $this->courses->removeElement($courses);
    }

    /**
     * Get courses
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCourses()
    {
        return $this->courses;
    }
}


text:
> [Java EE Integration Test Framework](https://github.com/probedock/jee-itf) probe for [Probe Dock RT](https://github.com/probedock/probedock-rt).

## Usage

1. Put the following dependency in your test project pom.xml

  ```xml
  <dependency>
    <groupId>io.probedock.rt.client</groupId>
    <artifactId>probedock-rt-itf</artifactId>
    <version>0.1.0</version>
  </dependenc>
  ```

  **Remark**: For the ITF setup, go to the [readme](https://github.com/probedock/jee-itf) of the project.

2. Extends `ProbeDockRTAbstractTestResource` in your web test project. You should replace the class which implements the
`AbstractDefaultTestResource` from ITF itself. In fact, you can simply change the `extends`.

  ```java
  import io.probedock.rt.client.itf.ProbeDockRTAbstractTestResource;

  @Resource
  public class TestEndPoint extends ProbeDockAbstractTestResource {
    @EJB
    private MyTestController myTestController;

    @Override
    public TestController getController() {
      return myTestController;
    }
  }
  ```

  **Remark**: If you are using the [Probe Dock ITF Probe](https://github.com/probedock/probedock-itf), you should have to
  replace the `extends ProbeDockAbstractTestResource` by `extends ProbeDockRTAbstractTestResource`. It will not be other
  changes.

3. Make sure the resource is exposed as standard REST resource. If you use annotations, you can follow the next example
present in the [demo project](https://github.com/probedock/probedock-demo-itf/blob/master/probedock-demo-itf-test-war/src/main/java/io/probedock/demo/itf)

4. Deploy your application.

5. To start the tests, you need to do `POST` request with the following content in the body. In fact, you have the full
control of the path where the resource is exposed.

  ```json
  {
    "filters": [{
      "type": "key",
      "text": "agas"
    }, {
      "type": "tag",
      "text": "feature-a"
    }],
    "seed": 123456
  }
  ```

  #### Main object

  | Name         | Mandatory | Description |
  | ------------ | --------- | ----------- |
  | filters[]    | No        | Define a list of filters to run specific tests. |
  | seed         | No        | Used to generate the test run order. If not sent, the order is random and the seed will appear in the logs. |

  #### Filter object

  | Name         | Mandatory | Description |
  | ------------ | --------- | ----------- |
  | type         | Yes       | The filter type: *, key, name, fingerprint, tag and ticket are valid values. |
  | text         | Yes       | Free text applied to filter type to match tests to run. |

### Requirements

* Java 6+

## Contributing

* [Fork](https://help.github.com/articles/fork-a-repo)
* Create a topic branch - `git checkout -b feature`
* Push to your branch - `git push origin feature`
* Create a [pull request](http://help.github.com/pull-requests/) from your branch

Please add a changelog entry with your name for new features and bug fixes.

## License

**probedock-rt-itf** is licensed under the [MIT License](http://opensource.org/licenses/MIT).
See [LICENSE.txt](LICENSE.txt) for the full text.


text:
<?php
namespace morphine\core;

/**
 * Class which implements this interface receives container for its purposes
 *
 * @author Michal Vasicek, Lex Vjatkin
 */
interface ContainerAware {

	/**
	 * Sets Container to object
	 *
	 * @param Container $container
	 */
	public function setContainer(Container $container);
}


text:
+++
title = "TM1637"
description = "Segment controller"
picture = "/img/tm1637.jpg"
+++

# Overview

[tm1637](https://periph.io/x/devices/v3/tm1637) provides support for the
TM1637 hex digits controller. It is controlled directly over GPIO pins.

# Example

Please [edit this page on
GitHub](https://github.com/periph/website/edit/master/site/content/device/tm1637.md)
to complete the example. Thanks!

```go
package main

func main() {
    // TODO 😳
}
```

# Buying

- Aliexpress:
  [aliexpress.com/wholesale?SearchText=tm1637](https://aliexpress.com/wholesale?SearchText=tm1637)
- Amazon:
  [amazon.com/s?field-keywords=tm1637](https://amazon.com/s?field-keywords=tm1637)
- Pimoroni: [shop.pimoroni.com/?q=tm1637](https://shop.pimoroni.com/?q=tm1637)

_The periph authors do not endorse any specific seller. These are only provided
for your convenience._


text:
package org.o3project.odenos.core.component.network.flow.ofpflow;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.msgpack.type.MapValue;
import org.msgpack.type.Value;
import org.msgpack.type.ValueFactory;
import org.o3project.odenos.core.component.network.flow.basic.FlowAction;

import java.util.Map;

/**
 * An action that pops an MPLS shim header from the packet. Only ethernet type
 * 0x8847(mpls) and 0x8848(mpls-ual) should be used.
 */
public class OFPFlowActionPopMpls extends FlowAction {

  public static final Integer MPLS_UNICAST = 0x8847;
  public static final Integer MPLS_MULTICAST = 0x8848;

  private Integer ethType;

  /**
   * Constructor.
   */
  public OFPFlowActionPopMpls() {
  }

  /**
   * Constructor.
   *
   * @param ethType the ethertype to set to.
   */
  public OFPFlowActionPopMpls(Integer ethType) {
    this.ethType = ethType;
  }

  @Override
  public boolean validate() {
    if (ethType == null) {
      return false;
    }
    if (!ethType.equals(MPLS_MULTICAST) && !ethType.equals(MPLS_UNICAST)) {
      return false;
    }
    return true;
  }

  /**
   * Returns a ethType.
   *
   * @return ethType the ethertype to set to.
   */
  public Integer getEthType() {
    return ethType;
  }

  /**
   * Sets a ethType.
   *
   * @param ethType the ethertype to set to.
   */
  public void setEthType(Integer ethType) {
    this.ethType = ethType;
  }

  @Override
  public String getType() {
    return OFPFlowActionPopMpls.class.getSimpleName();
  }

  @Override
  public boolean readValue(Value value) {
    MapValue map = value.asMapValue();
    Value targetValue;

    targetValue = map.get(ValueFactory.createRawValue("eth_type"));
    if (!targetValue.isNilValue()) {
      ethType = targetValue.asIntegerValue().getInt();
    }

    return true;
  }

  @Override
  public boolean writeValueSub(Map<String, Value> values) {
    if (!super.writeValueSub(values)) {
      return false;
    }

    if (ethType == null) {
      values.put("eth_type", ValueFactory.createIntegerValue(0));
    } else {
      values.put("eth_type", ValueFactory.createIntegerValue(ethType));
    }

    return true;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }

    if (obj == this) {
      return true;
    }

    if (!(obj instanceof OFPFlowActionPopMpls)) {
      return false;
    }

    if (!(super.equals(obj))) {
      return false;
    }

    final OFPFlowActionPopMpls obj2 = (OFPFlowActionPopMpls) obj;

    try {
      if (!obj2.getEthType().equals(this.ethType)) {
        return false;
      }
    } catch (NullPointerException ex) {
      return false;
    }
    return true;
  }

  @Override
  public OFPFlowActionPopMpls clone() {
    return new OFPFlowActionPopMpls(ethType);
  }

  /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {

    ToStringBuilder sb = new ToStringBuilder(this);
    sb.append("ethType", ethType);

    return sb.toString();
  }

}


text:
@protocol XMLParserDelegate <NSObject>

- (void)finishParsing:(NSMutableArray*)result;

@end

@interface ScrobbleListenedMusic : NSObject

@property (nonatomic, weak) id<XMLParserDelegate> delegate;

- (id)initWithURL:(NSURL*)url;
- (id)initWithURL:(NSURL*)url AndData:(NSMutableArray*)data;
- (void)startParsing;

@end


text:
class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :init_sidebar

  def init_sidebar
    if !request.xhr?
      @entities = Entity.order(:name)
    end
  end
end


text:
experiments.reactjs
===================

Learning experiences with react.js


text:
package com.yan.common.logging.mapper;

import com.yan.common.logging.model.LoggingEventException;
import com.yan.common.logging.model.LoggingEventExceptionExample;
import com.yan.common.logging.model.LoggingEventExceptionKey;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface LoggingEventExceptionMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    long countByExample(LoggingEventExceptionExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    int deleteByExample(LoggingEventExceptionExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    int deleteByPrimaryKey(LoggingEventExceptionKey key);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    int insert(LoggingEventException record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    int insertSelective(LoggingEventException record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    List<LoggingEventException> selectByExample(LoggingEventExceptionExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    LoggingEventException selectByPrimaryKey(LoggingEventExceptionKey key);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    int updateByExampleSelective(@Param("record") LoggingEventException record, @Param("example") LoggingEventExceptionExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    int updateByExample(@Param("record") LoggingEventException record, @Param("example") LoggingEventExceptionExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    int updateByPrimaryKeySelective(LoggingEventException record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table logging_event_exception
     *
     * @mbg.generated Fri Sep 15 16:14:57 CST 2017
     */
    int updateByPrimaryKey(LoggingEventException record);
}


text:
#ifdef _WIN32
#   include <windows.h>
#endif

#include <vector>
#include <string>

#ifndef _MSC_VER
#   define BOOST_TEST_DYN_LINK
#endif

#include <boost/test/unit_test.hpp>

#include "test_type.h"
#include "sql_test_suite_fixture.h"
#include <ignite/common/decimal.h>

using namespace ignite;

BOOST_FIXTURE_TEST_SUITE(SqlOperatorTestSuite, ignite::SqlTestSuiteFixture)

BOOST_AUTO_TEST_CASE(TestOperatorAddInt)
{
    CheckSingleResult<SQLINTEGER>("SELECT 123 + 51", 123 + 51);
};

BOOST_AUTO_TEST_CASE(TestOperatorSubInt)
{
    CheckSingleResult<SQLINTEGER>("SELECT 123 - 51", 123 - 51);
};

BOOST_AUTO_TEST_CASE(TestOperatorDivInt)
{
    CheckSingleResult<SQLINTEGER>("SELECT 123 / 51", 123 / 51);
};

BOOST_AUTO_TEST_CASE(TestOperatorModInt)
{
    CheckSingleResult<SQLINTEGER>("SELECT 123 % 51", 123 % 51);
};

BOOST_AUTO_TEST_CASE(TestOperatorMultInt)
{
    CheckSingleResult<SQLINTEGER>("SELECT 123 * 51", 123 * 51);
};

BOOST_AUTO_TEST_CASE(TestOperatorAddDouble)
{
    CheckSingleResult<double>("SELECT 123.0 + 51.0", 123.0 + 51.0);
};

BOOST_AUTO_TEST_CASE(TestOperatorSubDouble)
{
    CheckSingleResult<double>("SELECT 123.0 - 51.0", 123.0 - 51.0);
};

BOOST_AUTO_TEST_CASE(TestOperatorDivDouble)
{
    CheckSingleResult<double>("SELECT 123.0 / 51.0", 123.0 / 51.0);
};

BOOST_AUTO_TEST_CASE(TestOperatorModDouble)
{
    CheckSingleResult<double>("SELECT 123.0 % 51.0", 123 % 51);
};

BOOST_AUTO_TEST_CASE(TestOperatorMultDouble)
{
    CheckSingleResult<double>("SELECT 123.0 * 51.0", 123.0 * 51.0);
};

BOOST_AUTO_TEST_CASE(TestOperatorConcatString)
{
    CheckSingleResult<std::string>("SELECT 'Hello' || ' ' || 'World' || '!'", "Hello World!");
};

BOOST_AUTO_TEST_CASE(TestOperatorGreaterInt)
{
    CheckSingleResult<bool>("SELECT 2 > 3", false);
    CheckSingleResult<bool>("SELECT 3 > 3", false);
    CheckSingleResult<bool>("SELECT 34 > 3", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorLessInt)
{
    CheckSingleResult<bool>("SELECT 4 < 4", false);
    CheckSingleResult<bool>("SELECT 4 < 4", false);
    CheckSingleResult<bool>("SELECT 8 < 42", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorGreaterEquealInt)
{
    CheckSingleResult<bool>("SELECT 2 >= 3", false);
    CheckSingleResult<bool>("SELECT 3 >= 3", true);
    CheckSingleResult<bool>("SELECT 34 >= 3", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorLessEquealInt)
{
    CheckSingleResult<bool>("SELECT 4 <= 3", false);
    CheckSingleResult<bool>("SELECT 4 <= 4", true);
    CheckSingleResult<bool>("SELECT 8 <= 42", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorEquealInt)
{
    CheckSingleResult<bool>("SELECT 4 = 3", false);
    CheckSingleResult<bool>("SELECT 4 = 4", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorNotEquealInt)
{
    CheckSingleResult<bool>("SELECT 4 != 3", true);
    CheckSingleResult<bool>("SELECT 4 != 4", false);
};

BOOST_AUTO_TEST_CASE(TestOperatorGreaterDouble)
{
    CheckSingleResult<bool>("SELECT 2 > 3", false);
    CheckSingleResult<bool>("SELECT 3 > 3", false);
    CheckSingleResult<bool>("SELECT 34 > 3", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorLessDouble)
{
    CheckSingleResult<bool>("SELECT 4.0 < 4.0", false);
    CheckSingleResult<bool>("SELECT 4.0 < 4.0", false);
    CheckSingleResult<bool>("SELECT 8.0 < 42.0", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorGreaterEquealDouble)
{
    CheckSingleResult<bool>("SELECT 2.0 >= 3.0", false);
    CheckSingleResult<bool>("SELECT 3.0 >= 3.0", true);
    CheckSingleResult<bool>("SELECT 34.0 >= 3.0", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorLessEquealDouble)
{
    CheckSingleResult<bool>("SELECT 4.0 <= 3.0", false);
    CheckSingleResult<bool>("SELECT 4.0 <= 4.0", true);
    CheckSingleResult<bool>("SELECT 8.0 <= 42.0", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorEquealDouble)
{
    CheckSingleResult<bool>("SELECT 4.0 = 3.0", false);
    CheckSingleResult<bool>("SELECT 4.0 = 4.0", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorNotEquealDouble)
{
    CheckSingleResult<bool>("SELECT 4.0 != 3.0", true);
    CheckSingleResult<bool>("SELECT 4.0 != 4.0", false);
};

BOOST_AUTO_TEST_CASE(TestOperatorGreaterString)
{
    CheckSingleResult<bool>("SELECT 'abc' > 'bcd'", false);
    CheckSingleResult<bool>("SELECT 'abc' > 'abc'", false);
    CheckSingleResult<bool>("SELECT 'bcd' > 'abc'", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorLessString)
{
    CheckSingleResult<bool>("SELECT 'bcd' < 'abc'", false);
    CheckSingleResult<bool>("SELECT 'abc' < 'abc'", false);
    CheckSingleResult<bool>("SELECT 'abc' < 'bcd'", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorGreaterEquealString)
{
    CheckSingleResult<bool>("SELECT 'abc' >= 'bcd'", false);
    CheckSingleResult<bool>("SELECT 'abc' >= 'abc'", true);
    CheckSingleResult<bool>("SELECT 'bcd' >= 'abc'", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorLessEquealString)
{
    CheckSingleResult<bool>("SELECT 'bcd' <= 'abc'", false);
    CheckSingleResult<bool>("SELECT 'abc' <= 'bcd'", true);
    CheckSingleResult<bool>("SELECT 'abc' <= 'abc'", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorEquealString)
{
    CheckSingleResult<bool>("SELECT 'bcd' = 'abc'", false);
    CheckSingleResult<bool>("SELECT 'abc' = 'abc'", true);
};

BOOST_AUTO_TEST_CASE(TestOperatorNotEquealString)
{
    CheckSingleResult<bool>("SELECT 'abc' != 'abc'", false);
    CheckSingleResult<bool>("SELECT 'bcd' != 'abc'", true);
};

BOOST_AUTO_TEST_SUITE_END()


text:
module RuboCop
  module Cop
    module Lint
      # This cop checks for *return* from an *ensure* block.
      #
      # @example
      #
      #   # bad
      #
      #   begin
      #     do_something
      #   ensure
      #     do_something_else
      #     return
      #   end
      #
      # @example
      #
      #   # good
      #
      #   begin
      #     do_something
      #   ensure
      #     do_something_else
      #   end
      class EnsureReturn < Cop
        MSG = 'Do not return from an `ensure` block.'.freeze

        def on_ensure(node)
          ensure_body = node.body

          return unless ensure_body

          ensure_body.each_node(:return) do |return_node|
            add_offense(return_node)
          end
        end
      end
    end
  end
end


text:
#pragma once
#include <aws/connect/Connect_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Connect
{
namespace Model
{
  enum class IntegrationType
  {
    NOT_SET,
    EVENT,
    VOICE_ID,
    PINPOINT_APP,
    WISDOM_ASSISTANT,
    WISDOM_KNOWLEDGE_BASE
  };

namespace IntegrationTypeMapper
{
AWS_CONNECT_API IntegrationType GetIntegrationTypeForName(const Aws::String& name);

AWS_CONNECT_API Aws::String GetNameForIntegrationType(IntegrationType value);
} // namespace IntegrationTypeMapper
} // namespace Model
} // namespace Connect
} // namespace Aws


text:
package org.mybatis.dynamic.sql.where;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Stream;

import org.mybatis.dynamic.sql.SqlCriterion;
import org.mybatis.dynamic.sql.render.RenderingStrategy;
import org.mybatis.dynamic.sql.render.TableAliasCalculator;
import org.mybatis.dynamic.sql.where.render.WhereClauseProvider;
import org.mybatis.dynamic.sql.where.render.WhereRenderer;

public class WhereModel {
    private static final WhereClauseProvider EMPTY_WHERE_CLAUSE =
            new WhereClauseProvider.Builder().withWhereClause("").build(); //$NON-NLS-1$

    private final List<SqlCriterion> criteria = new ArrayList<>();

    private WhereModel(List<SqlCriterion> criteria) {
        this.criteria.addAll(criteria);
    }

    public <R> Stream<R> mapCriteria(Function<SqlCriterion, R> mapper) {
        return criteria.stream().map(mapper);
    }

    /**
     * Renders a where clause without table aliases.
     *
     * @param renderingStrategy rendering strategy
     * @return rendered where clause
     */
    public WhereClauseProvider render(RenderingStrategy renderingStrategy) {
        return WhereRenderer.withWhereModel(this)
                .withRenderingStrategy(renderingStrategy)
                .withSequence(new AtomicInteger(1))
                .withTableAliasCalculator(TableAliasCalculator.empty())
                .build()
                .render()
                .orElse(EMPTY_WHERE_CLAUSE);
    }

    public WhereClauseProvider render(RenderingStrategy renderingStrategy,
            TableAliasCalculator tableAliasCalculator) {
        return WhereRenderer.withWhereModel(this)
                .withRenderingStrategy(renderingStrategy)
                .withSequence(new AtomicInteger(1))
                .withTableAliasCalculator(tableAliasCalculator)
                .build()
                .render()
                .orElse(EMPTY_WHERE_CLAUSE);
    }

    public WhereClauseProvider render(RenderingStrategy renderingStrategy,
            String parameterName) {
        return WhereRenderer.withWhereModel(this)
                .withRenderingStrategy(renderingStrategy)
                .withSequence(new AtomicInteger(1))
                .withTableAliasCalculator(TableAliasCalculator.empty())
                .withParameterName(parameterName)
                .build()
                .render()
                .orElse(EMPTY_WHERE_CLAUSE);
    }

    public WhereClauseProvider render(RenderingStrategy renderingStrategy,
            TableAliasCalculator tableAliasCalculator, String parameterName) {
        return WhereRenderer.withWhereModel(this)
                .withRenderingStrategy(renderingStrategy)
                .withSequence(new AtomicInteger(1))
                .withTableAliasCalculator(tableAliasCalculator)
                .withParameterName(parameterName)
                .build()
                .render()
                .orElse(EMPTY_WHERE_CLAUSE);
    }

    public static WhereModel of(List<SqlCriterion> criteria) {
        return new WhereModel(criteria);
    }
}


text: define({pageBreak:"Prelom stranice"});


text:
package com.graphhopper.util.details;

import com.graphhopper.routing.Path;
import com.graphhopper.routing.profiles.EncodedValueLookup;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.util.EdgeIteratorState;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class calculates a PathDetail list in a similar fashion to the instruction calculation,
 * also see {@link com.graphhopper.routing.InstructionsFromEdges}.
 * <p>
 * This class uses the {@link PathDetailsBuilder}. We provide every edge to the builder
 * and up to its internals we create a new interval, ie. a new PathDetail in the List.
 *
 * @author Robin Boldt
 * @see PathDetail
 */
public class PathDetailsFromEdges implements Path.EdgeVisitor {

    private final List<PathDetailsBuilder> calculators;
    private int lastIndex = 0;

    public PathDetailsFromEdges(List<PathDetailsBuilder> calculators, int previousIndex) {
        this.calculators = calculators;
        this.lastIndex = previousIndex;
    }

    /**
     * Calculates the PathDetails for a Path. This method will return fast, if there are no calculators.
     *
     * @param path
     * @param weighting
     * @param pathBuilderFactory Generates the relevant PathBuilders
     * @return List of PathDetails for this Path
     */
    public static Map<String, List<PathDetail>> calcDetails(Path path, EncodedValueLookup evLookup, Weighting weighting,
                                                            List<String> requestedPathDetails, PathDetailsBuilderFactory pathBuilderFactory, int previousIndex) {
        if (!path.isFound() || requestedPathDetails.isEmpty())
            return Collections.emptyMap();
        List<PathDetailsBuilder> pathBuilders = pathBuilderFactory.createPathDetailsBuilders(requestedPathDetails, evLookup, weighting);
        if (pathBuilders.isEmpty())
            return Collections.emptyMap();

        path.forEveryEdge(new PathDetailsFromEdges(pathBuilders, previousIndex));

        Map<String, List<PathDetail>> pathDetails = new HashMap<>(pathBuilders.size());
        for (PathDetailsBuilder builder : pathBuilders) {
            Map.Entry<String, List<PathDetail>> entry = builder.build();
            List<PathDetail> existing = pathDetails.put(entry.getKey(), entry.getValue());
            if (existing != null)
                throw new IllegalStateException("Some PathDetailsBuilders use duplicate key: " + entry.getKey());
        }

        return pathDetails;
    }

    @Override
    public void next(EdgeIteratorState edge, int index, int prevEdgeId) {
        for (PathDetailsBuilder calc : calculators) {
            if (calc.isEdgeDifferentToLastEdge(edge)) {
                calc.endInterval(lastIndex);
                calc.startInterval(lastIndex);
            }
        }
        lastIndex += edge.fetchWayGeometry(2).size();
    }

    @Override
    public void finish() {
        for (PathDetailsBuilder calc : calculators) {
            calc.endInterval(lastIndex);
        }
    }
}


text:
const assert = require('assert');
const _ = require('lodash');
const fs = require('fs');
const React = require('react');
const acorn = require('acorn-jsx');

const generateFileText = require('./codeGen.js').generateFileText;
const matchTree = require('./treeMatcher').matchTree;

function interfaceForClassName(className) {	return `I${className}Props`; }

const typeNames = {
	// About as good as they can be
	array: 'Array<any>',
	bool: 'boolean',
	number: 'number',
	object: 'Object',
	string: 'string',

	// Could (probably) be better
	symbol: 'any',
	func: 'any',
	node: 'any',
	element: 'any'
}

const variableDeclarationTree = {
	_matchMultiple: true,
	_optional: true,
	type: "VariableDeclarator",
	init: {
		type: "CallExpression",
		callee: {
			type: "MemberExpression",
			object: { type: "Identifier", name: "React" },
			property: { type: "Identifier", name: "createClass" }
		},
		arguments: [{
			_orderedMatch: true,
			type: "ObjectExpression",
			properties: [{
				type: "Property",
				key: { type: "Identifier", name: "propTypes" },
				value: {
					type: "ObjectExpression",
					properties: [{
						_matchMultiple: true,
						type: "Property",
						key: {
							type: "Identifier",
							_onMatch: (node, state) => { state.propName = node.name; }
						},
						value: {
							type: "MemberExpression",
							object: {
								type: "MemberExpression",
								object: { type: "Identifier", name: "React" },
								property: { type: 'Identifier', name: 'PropTypes' }
							},
							property: {
								type: 'Identifier',
								_onMatch: (node, state) => {
									state.propType = typeNames[node.name] || 'any';
								}
							}
						},
						_onMatch: (node, state) => {
							state.props = state.props || [];
							state.props.push({name: state.propName, type: state.propType });
						}
					}]
				}
			}]
		}]
	},
	_onMatch: (node, state) => {
		state.classes = state.classes || [];
		state.classes.push({
			name: node.id.name,
			props: state.props
		});

		state.props = [];
	}
}

var bodyTree = {
	type: 'Program',
	body: [{
		_matchMultiple: true,
		type: 'VariableDeclaration',
		declarations: [variableDeclarationTree]
	}]
}

function buildInterfaceTypes(classes) {
	return _.map(classes, (c) => {
		return {
			name: interfaceForClassName(c.name),
			componentClassName: c.name,
			members: c.props
		};
	});
}

function buildClassTypes(classes) {
	return _.map(classes, (c) => {
		return {
			propsInterface: interfaceForClassName(c.name),
			name: c.name
		};
	});
}

// TODO: Reference the base react.d.ts file
function processFile(fileName) {
	var content = fs.readFileSync(fileName, {encoding: 'utf8'});

	var ast = acorn.parse(content, {
		plugins: { jsx: true },
		//locations: true
	});

	var state = {};
	var match = matchTree(ast, bodyTree, state);

	if(!match) {
		console.log("Error: Failed to find class definitions in " + fileName);
		return { interfaces: [], classes: [] }
	}

	var output = {
		interfaces: buildInterfaceTypes(state.classes),
		classes: buildClassTypes(state.classes)
	};

	return output;
}

function processFiles(config, fileNames) {
	var processedFiles = _.map(fileNames, (value) => {
		return processFile(value);
	});

	var interfaces = _.map(processedFiles, (value) => { return value.interfaces; });
	var classes = _.map(processedFiles, (value) => { return value.classes; });

	var output = {
		moduleName: config.moduleName,
		interfaces: _.flatten(interfaces),
		classes: _.flatten(classes)
	};

	generateFileText(output);
	fs.writeFileSync(config.moduleName + ".d.ts", output.text);
}

module.exports = {
	processFiles: processFiles
}


text:
<?php

namespace System\Support;

use Symfony\Component\Yaml\Parser;

/**
 * Yaml helper class
 *
 * @package system\support
 *
 */
class Yaml
{
    /**
     * Parses supplied YAML contents in to a PHP array.
     * @param string $contents YAML contents to parse.
     * @return array The YAML contents as an array.
     */
    public static function parse($contents)
    {
        $yaml = new Parser();
        return $yaml->parse($contents);
    }

    /**
     * Parses YAML file contents in to a PHP array.
     * @param $fileName \File to read contents and parse.
     * @return array The YAML contents as an array.
     */
    public static function parseFile($fileName)
    {
        $contents = file_get_contents($fileName);
        return self::parse($contents);
    }
}


text:
title: 'Week 9 - Mobile and Multi-device Design'
published: true
visible: false
swipe_deck_title: 'Mobile and Multi-device Design'
swipe_deck_id: 9967fp
swipe_deck_pdf_url:
---


text:
=====
Usage
=====

To use markovmc in a project::

    import markovmc


text:
package legends.model;

import java.util.ArrayList;
import java.util.List;

import legends.Application;
import legends.helper.EventHelper;
import legends.model.basic.AbstractObject;
import legends.model.events.basic.Coords;
import legends.xml.annotation.Xml;
import legends.xml.annotation.XmlConverter;
import legends.xml.converter.CoordListConverter;

public class WorldConstruction extends AbstractObject {
	@Xml("name")
	private String name;
	@Xml("type")
	private String type;
	@Xml("coords")
	@XmlConverter(CoordListConverter.class)
	private List<Coords> coords = new ArrayList<>();

	private List<Site> sites = new ArrayList<>();
	private List<WorldConstruction> parts = new ArrayList<>();
	private WorldConstruction master;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<Coords> getCoords() {
		return coords;
	}

	public List<Site> getSites() {
		return sites;
	}

	public List<WorldConstruction> getParts() {
		return parts;
	}

	public WorldConstruction getMaster() {
		return master;
	}

	public void setMaster(WorldConstruction master) {
		this.master = master;
	}

	public String getColor() {
		switch (type) {
		case "road":
			return "#FFF";
		case "bridge":
			return "#FFF";
		case "tunnel":
			return "#000";

		default:
			return "#FFF";
		}
	}

	public String getURL() {
		return Application.getSubUri() + "/worldconstruction/" + id;
	}

	public static String getGlyph(String type) {
		switch (type) {
		case "road":
			return "glyphicon glyphicon-road";
		case "bridge":
			return "fas fa-chevron-up";
		case "tunnel":
			return "fas fa-archway";

		default:
			return "fas fa-share-alt";
		}
	}

	public String getIcon() {
		return " ";
	}

	public String getLink() {
		if (id == -1)
			return "UNKNOWN WORLD CONSTRUCTION";
		return "" + getIcon() + getName() + "";
	}

	public String getMapDescription() {
		String description = getLink() + "
" + type;
		switch (type) {
		case "road":
		case "tunnel":
			description += " connecting " + getSites().stream().map(site -> site.getLink()).collect(EventHelper.stringList());
			break;
		case "bridge":
			description += " on " + getMaster().getLink();
			break;
		}
		return description + "";
	}

}


text:
package com.facebook.buck.android;

import static org.junit.Assert.assertThat;

import com.facebook.buck.jvm.java.JavaLibraryBuilder;
import com.facebook.buck.jvm.java.KeystoreBuilder;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeSourcePath;
import com.facebook.buck.rules.SingleThreadedBuildRuleResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.testutil.TargetGraphFactory;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Paths;
import org.hamcrest.Matchers;
import org.junit.Test;

public class AndroidInstrumentationApkDescriptionTest {

  @Test
  public void testNoDxRulesBecomeFirstOrderDeps() throws Exception {
    // Build up the original APK rule.
    TargetNode<?, ?> transitiveDepNode =
        JavaLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("//exciting:dep"))
            .addSrc(Paths.get("Dep.java"))
            .build();
    TargetNode<?, ?> dep =
        JavaLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("//exciting:target"))
            .addSrc(Paths.get("Other.java"))
            .addDep(transitiveDepNode.getBuildTarget())
            .build();
    TargetNode<?, ?> keystore =
        KeystoreBuilder.createBuilder(BuildTargetFactory.newInstance("//:keystore"))
            .setStore(FakeSourcePath.of("store"))
            .setProperties(FakeSourcePath.of("properties"))
            .build();
    TargetNode<?, ?> androidBinary =
        AndroidBinaryBuilder.createBuilder(BuildTargetFactory.newInstance("//:apk"))
            .setManifest(FakeSourcePath.of("manifest.xml"))
            .setKeystore(keystore.getBuildTarget())
            .setNoDx(ImmutableSet.of(transitiveDepNode.getBuildTarget()))
            .setOriginalDeps(ImmutableSortedSet.of(dep.getBuildTarget()))
            .build();
    BuildTarget target = BuildTargetFactory.newInstance("//:rule");
    TargetNode<?, ?> androidInstrumentationApk =
        AndroidInstrumentationApkBuilder.createBuilder(target)
            .setManifest(FakeSourcePath.of("manifest.xml"))
            .setApk(androidBinary.getBuildTarget())
            .build();

    TargetGraph targetGraph =
        TargetGraphFactory.newInstance(
            transitiveDepNode, dep, keystore, androidBinary, androidInstrumentationApk);
    BuildRuleResolver ruleResolver =
        new SingleThreadedBuildRuleResolver(
            targetGraph, new DefaultTargetNodeToBuildRuleTransformer());
    BuildRule transitiveDep = ruleResolver.requireRule(transitiveDepNode.getBuildTarget());
    ruleResolver.requireRule(target);
    BuildRule nonPredexedRule =
        ruleResolver.requireRule(
            target.withFlavors(AndroidBinaryGraphEnhancer.NON_PREDEXED_DEX_BUILDABLE_FLAVOR));
    assertThat(nonPredexedRule.getBuildDeps(), Matchers.hasItem(transitiveDep));
  }
}


text:
"""Offer sun based automation rules."""
from datetime import timedelta

import voluptuous as vol

from homeassistant.components.automation import (
    AutomationActionType,
    AutomationTriggerInfo,
)
from homeassistant.const import (
    CONF_EVENT,
    CONF_OFFSET,
    CONF_PLATFORM,
    SUN_EVENT_SUNRISE,
)
from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant, callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_sunrise, async_track_sunset
from homeassistant.helpers.typing import ConfigType

# mypy: allow-untyped-defs, no-check-untyped-defs

TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
    {
        vol.Required(CONF_PLATFORM): "sun",
        vol.Required(CONF_EVENT): cv.sun_event,
        vol.Required(CONF_OFFSET, default=timedelta(0)): cv.time_period,
    }
)

async def async_attach_trigger(
    hass: HomeAssistant,
    config: ConfigType,
    action: AutomationActionType,
    automation_info: AutomationTriggerInfo,
) -> CALLBACK_TYPE:
    """Listen for events based on configuration."""
    trigger_data = automation_info["trigger_data"]
    event = config.get(CONF_EVENT)
    offset = config.get(CONF_OFFSET)
    description = event
    if offset:
        description = f"{description} with offset"
    job = HassJob(action)

    @callback
    def call_action():
        """Call action with right context."""
        hass.async_run_hass_job(
            job,
            {
                "trigger": {
                    **trigger_data,
                    "platform": "sun",
                    "event": event,
                    "offset": offset,
                    "description": description,
                }
            },
        )

    if event == SUN_EVENT_SUNRISE:
        return async_track_sunrise(hass, call_action, offset)
    return async_track_sunset(hass, call_action, offset)


text:
module Watir
  class FileField < Input

    #
    # Set the file field to the given path
    #
    # @param [String] a path
    # @raise [Errno::ENOENT] if the file doesn't exist
    #

    def set(path)
      raise Errno::ENOENT, path unless File.exist?(path)
      self.value = path
    end

    #
    # Sets the file field to the given path
    #
    # @param [String] path
    #

    def value=(path)
      path = path.gsub(File::SEPARATOR, File::ALT_SEPARATOR) if File::ALT_SEPARATOR
      element_call { @element.send_keys path }
    end

  end # FileField

  module Container
    def file_field(*args)
      FileField.new(self, extract_selector(args).merge(tag_name: "input", type: "file"))
    end

    def file_fields(*args)
      FileFieldCollection.new(self, extract_selector(args).merge(tag_name: "input", type: "file"))
    end
  end # Container

  class FileFieldCollection < InputCollection
  end # FileFieldCollection
end # Watir


text:
FROM alpine:3.6

ARG UNISON_VERSION=2.48.4

# Install in one run so that build tools won't remain in any docker
# layers
RUN apk add --no-cache build-base curl bash supervisor inotify-tools rsync ruby \
    && apk add --update-cache --repository http://dl-4.alpinelinux.org/alpine/edge/testing/ ocaml \
    && curl -L https://github.com/bcpierce00/unison/archive/$UNISON_VERSION.tar.gz | tar zxv -C /tmp \
    && cd /tmp/unison-${UNISON_VERSION} \
    && sed -i -e 's/GLIBC_SUPPORT_INOTIFY 0/GLIBC_SUPPORT_INOTIFY 1/' src/fsmonitor/linux/inotify_stubs.c \
    && make UISTYLE=text NATIVE=true STATIC=true \
    && cp src/unison src/unison-fsmonitor /usr/local/bin \
    && apk del curl build-base ocaml \
    && apk add --no-cache libgcc libstdc++ \
    && rm -rf /tmp/unison-${UNISON_VERSION} \
    && apk add --no-cache --repository http://dl-4.alpinelinux.org/alpine/edge/testing/ shadow \
    && apk add --no-cache tzdata

# These can be overridden later
ENV LANG="C.UTF-8" \
    HOME="/root"

VOLUME /output
WORKDIR /input

COPY entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]