text:
package com.phloc.commons.mutable;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;

import com.phloc.commons.CDefault;
import com.phloc.commons.compare.CompareUtils;
import com.phloc.commons.hash.HashCodeGenerator;
import com.phloc.commons.state.EChange;
import com.phloc.commons.string.ToStringGenerator;

/**
 * Object wrapper around a short so that it can be passed a final object but is
 * mutable.
 *
 * @author Philip Helger
 */
@NotThreadSafe
public final class MutableShort extends Number implements IMutableInteger <MutableShort>
{
  /** The default value if the default constructor is used. */
  public static final short DEFAULT_VALUE = CDefault.DEFAULT_SHORT;

  private short m_nValue;

  /**
   * Initialize with default value {@value #DEFAULT_VALUE}.
   */
  public MutableShort ()
  {
    this (DEFAULT_VALUE);
  }

  /**
   * Initialize with a certain int value. If the value does not fit into a
   * short, the value is cut!
   *
   * @param nValue
   *        The value to be used.
   */
  public MutableShort (final int nValue)
  {
    this ((short) nValue);
  }

  /**
   * Initialize with a certain value.
   *
   * @param aValue
   *        The value to be used.
   */
  public MutableShort (@Nonnull final Short aValue)
  {
    this (aValue.shortValue ());
  }

  /**
   * Initialize with a certain value.
   *
   * @param nValue
   *        The value to be used.
   */
  public MutableShort (final short nValue)
  {
    m_nValue = nValue;
  }

  @Override
  public short shortValue ()
  {
    return m_nValue;
  }

  @Nonnull
  public Short getAsShort ()
  {
    return Short.valueOf (m_nValue);
  }

  @Override
  public float floatValue ()
  {
    return m_nValue;
  }

  @Override
  public double doubleValue ()
  {
    return m_nValue;
  }

  @Override
  public int intValue ()
  {
    return m_nValue;
  }

  @Override
  public long longValue ()
  {
    return m_nValue;
  }

  /**
   * Increment by 1 and return the modified value.
   *
   * @return The by 1 incremented value.
   */
  public int inc ()
  {
    return inc (1);
  }

  public int inc (final int nDelta)
  {
    m_nValue += nDelta;
    return m_nValue;
  }

  public int dec ()
  {
    return inc (-1);
  }

  public int dec (final int nDelta)
  {
    return inc (-nDelta);
  }

  @Nonnull
  public EChange set (final int nValue)
  {
    return set ((short) nValue);
  }

  @Nonnull
  public EChange set (final short nValue)
  {
    if (m_nValue == nValue)
      return EChange.UNCHANGED;
    m_nValue = nValue;
    return EChange.CHANGED;
  }

  public boolean is0 ()
  {
    return m_nValue == 0;
  }

  public boolean isNot0 ()
  {
    return m_nValue != 0;
  }

  public boolean isSmaller0 ()
  {
    return m_nValue < 0;
  }

  public boolean isSmallerOrEqual0 ()
  {
    return m_nValue <= 0;
  }

  public boolean isGreater0 ()
  {
    return m_nValue > 0;
  }

  public boolean isGreaterOrEqual0 ()
  {
    return m_nValue >= 0;
  }

  public boolean isEven ()
  {
    return (m_nValue % 2) == 0;
  }

  public boolean isOdd ()
  {
    return (m_nValue % 2) != 0;
  }

  public int compareTo (@Nonnull final MutableShort rhs)
  {
    return CompareUtils.compare (m_nValue, rhs.m_nValue);
  }

  @Nonnull
  public MutableShort getClone ()
  {
    return new MutableShort (m_nValue);
  }

  @Override
  public boolean equals (final Object o)
  {
    if (o == this)
      return true;
    if (!(o instanceof MutableShort))
      return false;
    final MutableShort rhs = (MutableShort) o;
    return m_nValue == rhs.m_nValue;
  }

  @Override
  public int hashCode ()
  {
    return new HashCodeGenerator (this).append (m_nValue).getHashCode ();
  }

  @Override
  public String toString ()
  {
    return new ToStringGenerator (this).append ("value", m_nValue).toString ();
  }
}


text:
package com.inferlytics.jdruid.helper;

import com.inferlytics.druidlet.core.DruidIndices;
import com.inferlytics.druidlet.loader.Loader;
import io.druid.data.input.impl.DimensionsSpec;
import io.druid.granularity.QueryGranularity;
import io.druid.query.Druids;
import io.druid.query.Query;
import io.druid.query.aggregation.*;
import io.druid.query.filter.DimFilter;
import io.druid.query.filter.DimFilters;
import io.druid.query.groupby.GroupByQuery;
import io.druid.query.spec.QuerySegmentSpecs;
import io.druid.query.topn.TopNQueryBuilder;
import io.druid.segment.QueryableIndex;
import io.druid.segment.incremental.IncrementalIndexSchema;
import org.joda.time.DateTime;
import org.joda.time.Interval;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Provides helper methods for testing
 *
 * @author Sriram
 * @since 4/16/2016
 */
public class TestHelper {
    private static final DruidIndices indices = DruidIndices.getInstance();

    public static QueryableIndex getIndex(String indexKey) throws IOException {
        if (indices.has(indexKey)) {
            return indices.get(indexKey);
        }
        //  Create druid segments from raw data
        Reader reader = new FileReader(new File("./src/test/resources/report.csv"));

        List<String> columns = Arrays.asList("colo", "pool", "report", "URL", "TS", "metric", "value", "count", "min", "max", "sum");
        List<String> metrics = Arrays.asList("value", "count", "min", "max", "sum");
        List<String> dimensions = new ArrayList<>(columns);
        dimensions.removeAll(metrics);
        Loader loader = Loader.csv(reader, columns, dimensions, "TS");

        DimensionsSpec dimensionsSpec = new DimensionsSpec(dimensions, null, null);
        AggregatorFactory[] metricsAgg = new AggregatorFactory[]{
                new LongSumAggregatorFactory("agg_count", "count"),
                new DoubleMaxAggregatorFactory("agg_max", "max"),
                new DoubleMinAggregatorFactory("agg_min", "min"),
                new DoubleSumAggregatorFactory("agg_sum", "sum")
        };
        IncrementalIndexSchema indexSchema = new IncrementalIndexSchema(0, QueryGranularity.ALL, dimensionsSpec, metricsAgg);
        indices.cache(indexKey, loader, indexSchema);
        return indices.get(indexKey);
    }

    public static Query getGroupByQuery() {
        List<DimFilter> filters = new ArrayList<>();
        filters.add(DimFilters.dimEquals("report", "URLTransaction"));
        filters.add(DimFilters.dimEquals("pool", "r1cart"));
        filters.add(DimFilters.dimEquals("metric", "Duration"));
        return GroupByQuery.builder()
                .setDataSource("test")
                .setQuerySegmentSpec(QuerySegmentSpecs.create(new Interval(0, new DateTime().getMillis())))
                .setGranularity(QueryGranularity.NONE)
                .addDimension("URL")
                .addAggregator(new LongSumAggregatorFactory("agg_count", "agg_count"))
                .addAggregator(new DoubleMaxAggregatorFactory("agg_max", "agg_max"))
                .addAggregator(new DoubleMinAggregatorFactory("agg_min", "agg_min"))
                .addAggregator(new DoubleSumAggregatorFactory("agg_sum", "agg_sum"))
                .setDimFilter(DimFilters.and(filters))
                .build();
    }

    public static Query getTopNQuery() {
        List<DimFilter> filters = new ArrayList<>();
        filters.add(DimFilters.dimEquals("report", "URLTransaction"));
        filters.add(DimFilters.dimEquals("pool", "r1cart"));
        filters.add(DimFilters.dimEquals("metric", "Duration"));
        return new TopNQueryBuilder()
                .threshold(5)
                .metric("agg_count")
                .dataSource("test")
                .intervals(QuerySegmentSpecs.create(new Interval(0, new DateTime().getMillis())))
                .granularity(QueryGranularity.NONE)
                .dimension("colo")
                .aggregators(
                        Arrays.asList(
                                new LongSumAggregatorFactory("agg_count", "agg_count"),
                                new DoubleMaxAggregatorFactory("agg_max", "agg_max"),
                                new DoubleMinAggregatorFactory("agg_min", "agg_min"),
                                new DoubleSumAggregatorFactory("agg_sum", "agg_sum")))
                .filters(DimFilters.and(filters)).build();
    }

    public static Query getTimeseriesQuery() {
        List<DimFilter> filters = new ArrayList<>();
        filters.add(DimFilters.dimEquals("report", "URLTransaction"));
        filters.add(DimFilters.dimEquals("pool", "r1cart"));
        filters.add(DimFilters.dimEquals("metric", "Duration"));
        return Druids.newTimeseriesQueryBuilder()
                .dataSource("test")
                .intervals(QuerySegmentSpecs.create(new Interval(0, new DateTime().getMillis())))
                .granularity(QueryGranularity.ALL)
                .aggregators(Arrays.asList(
                        new LongSumAggregatorFactory("agg_count", "agg_count"),
                        new DoubleMaxAggregatorFactory("agg_max", "agg_max"),
                        new DoubleMinAggregatorFactory("agg_min", "agg_min"),
                        new DoubleSumAggregatorFactory("agg_sum", "agg_sum")))
                .filters(DimFilters.and(filters)).build();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.amortaza.hellina_j2d.font;

import java.awt.*;
import java.util.*;

public class FontManager {
    private static Map<FontKey, Font> fontByFontKey = new HashMap<FontKey, Font>();

    public static Font getFont( FontKey key ) {
        Font font = fontByFontKey.get( key );

        if ( font == null ) {
            int style;

            if ( key.fontstyle == FontKey.PLAIN )
                style = Font.PLAIN;
            else if ( key.fontstyle == FontKey.BOLD )
                style = Font.BOLD;
            else
                style = Font.ITALIC;

            font = new Font( key.fontname, style, ( int ) key.fontsize );

            fontByFontKey.put( key, font );
        }

        return font;
    }
}


text:
<?php

namespace FileNamingResolver\NamingStrategy;

/**
 * @author Victor Bocharsky <bocharsky.bw@gmail.com>
 */
abstract class AbstractNamingStrategy implements NamingStrategyInterface
{
    /**
     * @return string
     */
    public static function generateUniqueString()
    {
        return str_replace('.', '', microtime(true)).uniqid();
    }
}


text:
package com.spikeify.cron.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public final class DateTimeUtils {

	private DateTimeUtils() {
		// hiding constructor
	}

	private static ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {

			return new SimpleDateFormat("yyyy-MM-dd");
		}
	};

	private static ThreadLocal<SimpleDateFormat> simpleTimeFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {

			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
		}
	};

	public static SimpleDateFormat getDateFormat() {

		return simpleDateFormatThreadLocal.get();
	}

	public static SimpleDateFormat getTimeFormat() {

		return simpleTimeFormatThreadLocal.get();
	}

	public static Calendar getCalendar() {

		return Calendar.getInstance(TimeZone.getTimeZone("UTC"));
	}

	public static Calendar getCalendar(long time) {

		Calendar calendar = getCalendar();
		calendar.setTimeInMillis(time);
		return calendar;
	}

	public static String formatDateTime(long time) {

		SimpleDateFormat format = getTimeFormat();
		Calendar calendar = getCalendar(time);

		return format.format(calendar.getTime());
	}

	public static String formatDate(long time) {

		SimpleDateFormat format = getDateFormat();
		Calendar calendar = getCalendar(time);

		return format.format(calendar.getTime());
	}

	public static String format(long time, SimpleDateFormat format) {

		if (format == null) {
			return formatDateTime(time);
		}

		Calendar calendar = getCalendar(time);
		return format.format(calendar.getTime());
	}

	/**
	 * Converts UTC hour to time zone hour
	 * @param hour UTC hour
	 * @param timezone time zone
	 * @return hour as seen in the given time zone
	 */
	public static int getTimezoneHour(int hour, int timezone) {

		hour = (hour + timezone) % 24;
		if (hour < 0) {
			return 24 + hour;
		}

		return hour;
	}

	public static long getTimezoneTime(long time, int timezone) {

		Calendar calendar = getCalendar(time);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);

		hour = (hour + timezone) % 24;
		if (hour < 0) {
			hour = 24 + hour;
			calendar.add(Calendar.DAY_OF_MONTH, -1);
		}

		calendar.set(Calendar.HOUR_OF_DAY, hour);
		return calendar.getTimeInMillis();
	}

	/**
	 * Converts local hour back to UTC hour
	 * @param hour local hour in time zone
	 * @param timezone current time zone
	 * @return UTC hour
	 */
	public static int getUtcHour(int hour, int timezone) {

		hour = (hour - timezone) % 24;
		if (hour < 0) {
			return 24 + hour;
		}

		return hour;
	}
}


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
+ (void)generateBlockerListJSON;

@end


text:
![Last version](https://img.shields.io/github/tag/Kikobeats/farm-cli.svg?style=flat-square)
[![Build Status](https://img.shields.io/travis/Kikobeats/farm-cli/master.svg?style=flat-square)](https://travis-ci.org/Kikobeats/farm-cli)
[![Coverage Status](https://img.shields.io/coveralls/Kikobeats/farm-cli.svg?style=flat-square)](https://coveralls.io/github/Kikobeats/farm-cli)
[![Dependency status](https://img.shields.io/david/Kikobeats/farm-cli.svg?style=flat-square)](https://david-dm.org/Kikobeats/farm-cli)
[![NPM Status](https://img.shields.io/npm/dm/farm-cli.svg?style=flat-square)](https://www.npmjs.org/package/farm-cli)

![](https://i.imgur.com/BKQqOy4.png)

`farm` allows allows you to create a resilient multi-process architecture from your CLI. It's based on [worker-farm](https://github.com/rvagg/node-worker-farm).

> **Note**: See [examples](/examples) for common user case.

## Installation

First, install the library globally:

```bash
$ npm install farm-cli --global
```

Additionally, you can invoke it using `npx`:

```bash
$ npx farm-cli
```

## Getting Started

### Basic Usage

You need to specify a file and export a main method as entry point.

```js
const createLog = n => (...args) => console.log(`[#${n}] ${args}`)

module.exports = function (opts, exit) {
  const { isMaster, maxWorkers, worker } = opts
  const log = createLog(worker)
  log(`I'm worker ${worker + 1} of ${maxWorkers} ${isMaster ? '(master)' : ''}`)
}
```

Finally, invoke the file using `farm`:

```bash
$ farm examples/basic

[#0] Hello I'm worker 1 of 4 (master)
[#1] Hello I'm worker 2 of 4
[#2] Hello I'm worker 3 of 4
[#3] Hello I'm worker 4 of 4
```

###  Creating Your Own Farm

By default, the library will create as many processes as number of CPUs in the machine and a thread per process.

Let's use the same example but this time specifying multiple threads per process

```bash
$ farm examples/basic --threads=2

[#0] Hello I'm worker 1 of 8 (master)
[#1] Hello I'm worker 2 of 8
[#2] Hello I'm worker 3 of 8
[#4] Hello I'm worker 4 of 8
[#5] Hello I'm worker 5 of 8
[#6] Hello I'm worker 6 of 8
[#7] Hello I'm worker 7 of 8
[#8] Hello I'm worker 8 of 8
```

This time the farm has 2 threads per process (2 threads * 4 cores = 8 workers).

Type `farm --help` to know more.

### Passing File Arguments

The parameters passed after the filename will used as file arguments:

```
$ farm examples/fiboniacci --memoize
[#0] Enable memoize mode!
```

### Load Configuration File

The same things passed to `farm` from a `.farmrc` file created in the same directory.

```bash
$ ls -al examples/load-config

-rw-r--r--@ 1  50 Jan 21  2017 .farmrc
-rw-r--r--@ 1 105 Nov 26  2017 README.md
-rw-r--r--@ 1  50 Jan 21  2017 index.js
```

### Resilient Errors

If a process unexpectedly dies for any reason, it automagically re-enter.

This can be adjusted using `--retries` flag.

Type `farm --help` to know more.

### Finishing the Execution

When you want to finish, call the second argument:

```js
module.exports = function (opts, exit) {
  const { worker } = opts

  setTimeout(() => {
    console.log(`[#${worker}] bye bye!`)
    exit()
  })
}
```

It will finish gracefully when all the threads exit.

### Debug Mode

If you need to debug, enable it passing `DEBUG=farm` as environment variable

```
DEBUG=farm examples/fiboniacci --memoize
```

## License

**farm-cli** © [Kiko Beats](https://kikobeats.com), released under the [MIT](https://github.com/Kikobeats/farm-cli/blob/master/LICENSE.md) License.<br>
Authored and maintained by Kiko Beats with help from [contributors](https://github.com/Kikobeats/farm-cli/contributors).

> [kikobeats.com](https://kikobeats.com) · GitHub [Kiko Beats](https://github.com/Kikobeats) · Twitter [@Kikobeats](https://twitter.com/Kikobeats)


text:
module Jekyll
  class TrainingboxTag < Liquid::Tag

    def initialize(tag_name, text, tokens)
      super
    end

    def render(context)
      output = <<-output

Wish to become a GigaSpaces professional and get training from our product experts?

Click here for details about our various training education programs.

output
    end
  end
end

Liquid::Template.register_tag('trainingbox', Jekyll::TrainingboxTag)


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class Application\Modules\Rest\Controllers\EnginesController | Phalcon REST API</title>

	<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">

		Overview

Namespaces

						Application

						Aware

						Helpers

						Models

						Modules

						Rest

						Aware

						Controllers

						DTO

						Events

						BeforeDispatchLoop

						BeforeException

						BeforeExecuteRoute

						Exceptions

						Services

						Validators

						Services

						Advanced

						Cache

						Database

						Develop

						Mail

						Mappers

						Security

						PHP

Classes

AttributesController

BannersController

CategoriesController

ControllerBase

CurrenciesController

EnginesController

ErrorsController

FilesController

ItemsController

LogsController

PagesController

SignController

SubscribeController

TestController

UsersController

ValuesController

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

				Namespace

Class

				Tree

						Deprecated

						Todo

				Download

Class EnginesController

Class EnginesController

			Phalcon\Di\Injectable

			 implements
				Phalcon\Di\InjectionAwareInterface,

				Phalcon\Events\EventsAwareInterface

			Phalcon\Mvc\Controller

			Application\Modules\Rest\Controllers\ControllerBase

Application\Modules\Rest\Controllers\EnginesController

		Namespace: Application\Modules\Rest\Controllers

		Package: Application\Modules\Rest\Controllers

				Author:
				Stanislav WEB | Lugansk stanisov@gmail.com

				Version:
				1.0

				Since:
				PHP >=5.6

			Located at Modules/Rest/Controllers/EnginesController.php

Methods summary

			 public

		#
		initialize( )

Initialize cache service

Initialize cache service

			 public

		#
		getAction( )

GET Engines action

GET Engines action

Methods inherited from Application\Modules\Rest\Controllers\ControllerBase

			afterDispatch(),
			afterExecuteRoute(),
			beforeExecuteRoute()

Methods inherited from Phalcon\Mvc\Controller

			__construct()

Methods inherited from Phalcon\Di\Injectable

			__get(),
			getDI(),
			getEventsManager(),
			setDI(),
			setEventsManager()

Properties summary

			protected
			Application\Modules\Rest\Services\RestCacheService

				<var>$cache</var>

REST cache container

REST cache container

				#

			protected
			string

				<var>$key</var>

Cache key

Cache key

				#

Properties inherited from Application\Modules\Rest\Controllers\ControllerBase

			<var>$response</var>,
			<var>$rest</var>

Properties inherited from Phalcon\Di\Injectable

			<var>$_dependencyInjector</var>,
			<var>$_eventsManager</var>

		Phalcon REST API API documentation generated by ApiGen


text:
<?php

namespace Tuto\LibraryBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Book
 *
 * @ORM\Table(name="book")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="Tuto\LibraryBundle\Repository\BookRepository")
 */
class Book
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /** @var int
     *
     * @ORM\Column(name="nb_copies", type="integer")
     */
    private $nbCopies;

    /**
     * @var string
     *
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @var string
     *
     * @ORM\Column(type="datetime", nullable = true)
     */
    protected $updated;

    /**
     * @ORM\ManyToMany(targetEntity="Author", inversedBy="books", cascade={"persist"})
     * @ORM\JoinTable(name="book_author")
     */
    protected $authors;

    /**
     * Constructeur
     */
    public function __construct()
    {
        $this->authors = new ArrayCollection();
    }

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

    /**
     * Set title
     *
     * @param string $title
     * @return Book
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

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

    /**
     * Ajoute un auteur
     * @param Author $author
     * @return $this
     */
    public function addAuthor(Author $author)
    {
        if(!$this->authors->contains($author)) {
            $this->authors[] = $author;
        }

        return $this;
    }

    /**
     * Supprime un auteur
     * @param Author $author
     */
    public function removeAuthor(Author $author)
    {
        if($this->authors->contains($author)) {
            // Utilisation de la méthode removeElement de l'objet ArrayCollection
            $this->authors->removeElement($author);
        }
    }

    /**
     * Retourne la liste des auteurs
     * @return ArrayCollection
     */
    public function getAuthors()
    {
        return $this->authors;
    }

    /**
     * Set nb_copies
     *
     * @param integer $nbCopies
     * @return Book
     */
    public function setNbCopies($nbCopies)
    {
        $this->nbCopies = $nbCopies;

        return $this;
    }

    /**
     * Get nb_copies
     *
     * @return integer
     */
    public function getNbCopies()
    {
        return $this->nbCopies;
    }

    /**
     * Gets triggered only on insert
     * @ORM\PrePersist
     */
    public function onPrePersist()
    {
        $this->created = new \DateTime("now");
    }

    /**
     * Gets triggered every time on update
     * @ORM\PreUpdate
     */
    public function onPreUpdate()
    {
        $this->updated = new \DateTime("now");
    }
}


text:
"""
argparse supplements
"""
# ----------------------------------------------------------------------------

from __future__ import absolute_import

import argparse
import os
import re
import shlex

__all__ = [
    "action",
    "type",
]

class _Registry(object):
    pass

def _register(registry, name, value):
    setattr(registry, name, value)

# Types ----------------------------------------------------------------------
type = _Registry()

def type_bool(string):
    """
    A strict parser for bools

    unlike Python's `bool()`, where `bool('False')` is `True`
    This function can be passed as `type=` argument to argparse to parse values
    passed to command line arguments.
    """
    if string in ['0', 'false', 'False']:
        return False
    if string in ['1', 'true', 'True']:
        return True
    raise argparse.ArgumentTypeError("%r is not a boolean value" % string)

_register(type, 'bool', type_bool)

def type_shell_split(string):
    """
    Parse and split shell arguments string into a list of shell arguments.

    Recognize `,` as a separator as well as white spaces.
    string: -BAR="foo bar" -BAZ='foo,bar',-QUX 42
    into
    ['-BAR=foo bar', '-BAZ=foo,bar', "-QUX", "42"]
    """
    lex = shlex.shlex(string, posix=True)
    lex.whitespace_split = True
    lex.whitespace += ','
    return list(lex)

_register(type, 'shell_split', type_shell_split)

class CompilerVersion(object):
    """A typed representation of a compiler version."""

    def __init__(self, string_representation, components):
        self.string_representation = string_representation
        self.components = components

    def __str__(self):
        return self.string_representation

def type_clang_compiler_version(string):
    """
    Parse version string and split into a tuple of strings
    (major, minor, patch)

    Supports "MAJOR.MINOR.PATCH" and "MAJOR.MINOR.PATCH.PATCH" formats.
    """
    m = re.match(r'^([0-9]+)\.([0-9]+)\.([0-9]+)(\.([0-9]+))?$', string)
    if m is not None:
        return CompilerVersion(
            string_representation=string,
            components=m.group(1, 2, 3, 5))
    raise argparse.ArgumentTypeError(
        "%r is an invalid version value, "
        "must be 'MAJOR.MINOR.PATCH' or "
        "'MAJOR.MINOR.PATCH.PATCH'" % string)

_register(type, 'clang_compiler_version', type_clang_compiler_version)

def type_swift_compiler_version(string):
    """
    Parse version string and split into a tuple of strings
    (major, minor, patch)

    Supports "MAJOR.MINOR" and "MAJOR.MINOR.PATCH" formats.
    """
    m = re.match(r'^([0-9]+)\.([0-9]+)(\.([0-9]+))?$', string)
    if m is not None:
        return CompilerVersion(
            string_representation=string,
            components=m.group(1, 2, 4))
    raise argparse.ArgumentTypeError(
        "%r is an invalid version value, "
        "must be 'MAJOR.MINOR' or "
        "'MAJOR.MINOR.PATCH'" % string)

_register(type, 'swift_compiler_version', type_swift_compiler_version)

def type_executable(string):
    """
    Check the string is executable path string.

    Convert it to absolute path.
    """
    if os.path.isfile(string) and os.access(string, os.X_OK):
        return os.path.abspath(string)
    raise argparse.ArgumentTypeError(
        "%r is not executable" % string)

_register(type, 'executable', type_executable)

# Actions --------------------------------------------------------------------
action = _Registry()

class _UnavailableAction(argparse.Action):
    def __init__(self,
                 option_strings,
                 dest=argparse.SUPPRESS,
                 default=argparse.SUPPRESS,
                 nargs='?',
                 help=None):
        super(_UnavailableAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            default=default,
            nargs=nargs,
            help=help)

    def __call__(self, parser, namespace, values, option_string=None):
        if option_string is not None:
            arg = option_string
        else:
            arg = str(values)
        parser.error('unknown argument: %s' % arg)

_register(action, 'unavailable', _UnavailableAction)

class _ConcatAction(argparse.Action):

    def __call__(self, parser, namespace, values, option_string=None):
        old_val = getattr(namespace, self.dest)
        if old_val is None:
            val = values
        else:
            val = old_val + values
        setattr(namespace, self.dest, val)

_register(action, 'concat', _ConcatAction)

class _OptionalBoolAction(argparse.Action):
    def __init__(self,
                 option_strings,
                 dest,
                 default=False,
                 const=True,
                 metavar="BOOL",
                 help=None):
        super(_OptionalBoolAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            default=default,
            metavar=metavar,
            nargs="?",
            type=type.bool,
            help=help,
            const=const)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values)

_register(action, 'optional_bool', _OptionalBoolAction)

_TRUE_VALUES = [True, 1, 'true', 'True', 'TRUE', '1']
_FALSE_VALUES = [False, 0, 'false', 'False', 'FALSE', '0']

class _OnOffAction(argparse.Action):
    """Action that can be toggled on or off, defaulting to the off state. An
    optional bool-ish argument can be passed to set the state manually.
    """

    def __init__(self, **kwargs):
        assert 'choices' in kwargs and len(kwargs['choices']) == 2

        self._on_value, self._off_value = kwargs.pop('choices')
        kwargs['nargs'] = '?'

        if 'default' not in kwargs:
            kwargs['default'] = self._off_value

        if 'metavar' not in kwargs:
            kwargs['metavar'] = 'BOOL'

        super(_OnOffAction, self).__init__(**kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        if values is None:
            val = self._on_value
        elif values in _TRUE_VALUES:
            val = self._on_value
        elif values in _FALSE_VALUES:
            val = self._off_value
        else:
            raise argparse.ArgumentTypeError(
                values + ' is not a boolean value')

        setattr(namespace, self.dest, val)

class _EnableAction(_OnOffAction):
    """Action that defaults to False when absent and to True when parsed with
    the option to override the value by passing a bool-like value as an
    argument.
    """

    def __init__(self, **kwargs):
        kwargs['choices'] = (True, False)
        super(_EnableAction, self).__init__(**kwargs)

_register(action, 'enable', _EnableAction)

class _DisableAction(_OnOffAction):
    """Action that defaults to True when absent and to False when parsed with
    the option to override the value by passing a bool-like value as an
    argument. When overridden the resulting value is negated, thus passing
    'True' will result in the destination being set to False.
    """

    def __init__(self, **kwargs):
        kwargs['choices'] = (False, True)
        super(_DisableAction, self).__init__(**kwargs)

_register(action, 'disable', _DisableAction)


text:
'''
Helper Functions
****************

The following helper functions are useful shortcuts for interacting with File objects.

'''

from __future__ import (print_function, unicode_literals)

import os, sys, math, mmap, stat

import dxpy
from . import dxfile, DXFile

def open_dxfile(dxid, project=None, read_buffer_size=dxfile.DEFAULT_BUFFER_SIZE):
    '''
    :param dxid: file ID
    :type dxid: string
    :rtype: :class:`~dxpy.bindings.dxfile.DXFile`

    Given the object ID of an uploaded file, returns a remote file
    handler that is a Python file-like object.

    Example::

      with open_dxfile("file-xxxx") as fd:
          for line in fd:
              ...

    Note that this is shorthand for::

      DXFile(dxid)

    '''
    return DXFile(dxid, project=project, read_buffer_size=read_buffer_size)

def new_dxfile(mode=None, write_buffer_size=dxfile.DEFAULT_BUFFER_SIZE, **kwargs):
    '''
    :param mode: One of "w" or "a" for write and append modes, respectively
    :type mode: string
    :rtype: :class:`~dxpy.bindings.dxfile.DXFile`

    Additional optional parameters not listed: all those under
    :func:`dxpy.bindings.DXDataObject.new`.

    Creates a new remote file object that is ready to be written to;
    returns a :class:`~dxpy.bindings.dxfile.DXFile` object that is a
    writable file-like object.

    Example::

        with new_dxfile(media_type="application/json") as fd:
            fd.write("foo\\n")

    Note that this is shorthand for::

        dxFile = DXFile()
        dxFile.new(**kwargs)

    '''
    dx_file = DXFile(mode=mode, write_buffer_size=write_buffer_size)
    dx_file.new(**kwargs)
    return dx_file

def download_dxfile(dxid, filename, chunksize=dxfile.DEFAULT_BUFFER_SIZE, append=False, show_progress=False,
                    project=None, **kwargs):
    '''
    :param dxid: Remote file ID
    :type dxid: string
    :param filename: Local filename
    :type filename: string
    :param append: If True, appends to the local file (default is to truncate local file if it exists)
    :type append: boolean

    Downloads the remote file with object ID *dxid* and saves it to
    *filename*.

    Example::

        download_dxfile("file-xxxx", "localfilename.fastq")

    '''

    def print_progress(bytes_downloaded, file_size):
        num_ticks = 60

        effective_file_size = file_size or 1
        if bytes_downloaded > effective_file_size:
            effective_file_size = bytes_downloaded

        ticks = int(round((bytes_downloaded / float(effective_file_size)) * num_ticks))
        percent = int(round((bytes_downloaded / float(effective_file_size)) * 100))

        fmt = "[{done}{pending}] Downloaded {done_bytes:,}{remaining} bytes ({percent}%) {name}"
        sys.stderr.write(fmt.format(done=('=' * (ticks - 1) + '>') if ticks > 0 else '',
                                    pending=' ' * (num_ticks - ticks),
                                    done_bytes=bytes_downloaded,
                                    remaining=' of {size:,}'.format(size=file_size) if file_size else "",
                                    percent=percent,
                                    name=filename))
        sys.stderr.flush()
        sys.stderr.write("\r")
        sys.stderr.flush()

    file_size = None
    _bytes = 0

    mode = 'ab' if append else 'wb'
    with DXFile(dxid, mode='r', project=project, read_buffer_size=chunksize) as dxfile, open(filename, mode) as fd:
        if show_progress:
            print_progress(0, None)
        while True:
            file_content = dxfile.read(chunksize, **kwargs)
            if file_size is None:
                file_size = dxfile._file_length

            if show_progress:
                _bytes += len(file_content)
                print_progress(_bytes, file_size)

            if len(file_content) == 0:
                if show_progress:
                    sys.stderr.write("\n")
                break

            fd.write(file_content)

def _get_buffer_size_for_file(file_size, file_is_mmapd=False):
    """Returns an upload buffer size that is appropriate to use for a file
    of size file_size. If file_is_mmapd is True, the size is further
    constrained to be suitable for passing to mmap.

    """
    # Raise buffer size (for files exceeding DEFAULT_BUFFER_SIZE * 10k
    # bytes) in order to prevent us from exceeding 10k parts limit.
    min_buffer_size = int(math.ceil(float(file_size) / 10000))
    buffer_size = max(dxfile.DEFAULT_BUFFER_SIZE, min_buffer_size)
    if file_size >= 0 and file_is_mmapd:
        # For mmap'd uploads the buffer size additionally must be a
        # multiple of the ALLOCATIONGRANULARITY.
        buffer_size = int(math.ceil(float(buffer_size) / mmap.ALLOCATIONGRANULARITY)) * mmap.ALLOCATIONGRANULARITY
    if buffer_size * 10000 < file_size:
        raise AssertionError('part size is not large enough to complete upload')
    if file_is_mmapd and buffer_size % mmap.ALLOCATIONGRANULARITY != 0:
        raise AssertionError('part size will not be accepted by mmap')
    return buffer_size

def upload_local_file(filename=None, file=None, media_type=None, keep_open=False,
                      wait_on_close=False, use_existing_dxfile=None, show_progress=False, **kwargs):
    '''
    :param filename: Local filename
    :type filename: string
    :param file: File-like object
    :type file: File-like object
    :param media_type: Internet Media Type
    :type media_type: string
    :param keep_open: If False, closes the file after uploading
    :type keep_open: boolean
    :param wait_on_close: If True, waits for the file to close
    :type wait_on_close: boolean
    :param use_existing_dxfile: Instead of creating a new file object, upload to the specified file
    :type use_existing_dxfile: :class:`~dxpy.bindings.dxfile.DXFile`
    :returns: Remote file handler
    :rtype: :class:`~dxpy.bindings.dxfile.DXFile`

    Additional optional parameters not listed: all those under
    :func:`dxpy.bindings.DXDataObject.new`.

    Exactly one of *filename* or *file* is required.

    Uploads *filename* or reads from *file* into a new file object (with
    media type *media_type* if given) and returns the associated remote
    file handler. The "name" property of the newly created remote file
    is set to the basename of *filename* or to *file.name* (if it
    exists).

    Examples::

      # Upload from a path
      dxpy.upload_local_file("/home/ubuntu/reads.fastq.gz")
      # Upload from a file-like object
      with open("reads.fastq") as fh:
          dxpy.upload_local_file(file=fh)

    '''
    fd = file if filename is None else open(filename, 'rb')

    try:
        file_size = os.fstat(fd.fileno()).st_size
    except:
        file_size = 0
    buffer_size = _get_buffer_size_for_file(file_size, file_is_mmapd=hasattr(fd, "fileno"))

    if use_existing_dxfile:
        handler = use_existing_dxfile
    else:
        # Set a reasonable name for the file if none has been set
        # already
        creation_kwargs = kwargs.copy()
        if 'name' not in kwargs:
            if filename is not None:
                creation_kwargs['name'] = os.path.basename(filename)
            else:
                # Try to get filename from file-like object
                try:
                    local_file_name = file.name
                except AttributeError:
                    pass
                else:
                    creation_kwargs['name'] = os.path.basename(local_file_name)

        # Use 'a' mode because we will be responsible for closing the file
        # ourselves later (if requested).
        handler = new_dxfile(mode='a', media_type=media_type, write_buffer_size=buffer_size, **creation_kwargs)

    # For subsequent API calls, don't supply the dataobject metadata
    # parameters that are only needed at creation time.
    _, remaining_kwargs = dxpy.DXDataObject._get_creation_params(kwargs)

    num_ticks = 60
    offset = 0

    def can_be_mmapd(fd):
        if not hasattr(fd, "fileno"):
            return False
        mode = os.fstat(fd.fileno()).st_mode
        return not (stat.S_ISCHR(mode) or stat.S_ISFIFO(mode))

    def read(num_bytes):
        """
        Returns a string or mmap'd data containing the next num_bytes of
        the file, or up to the end if there are fewer than num_bytes
        left.
        """
        # If file cannot be mmap'd (e.g. is stdin, or a fifo), fall back
        # to doing an actual read from the file.
        if not can_be_mmapd(fd):
            return fd.read(handler._write_bufsize)

        bytes_available = max(file_size - offset, 0)
        if bytes_available == 0:
            return b""

        return mmap.mmap(fd.fileno(), min(handler._write_bufsize, bytes_available), offset=offset, access=mmap.ACCESS_READ)

    handler._num_bytes_transmitted = 0

    def report_progress(handler, num_bytes):
        handler._num_bytes_transmitted += num_bytes
        if file_size > 0:
            ticks = int(round((handler._num_bytes_transmitted / float(file_size)) * num_ticks))
            percent = int(round((handler._num_bytes_transmitted / float(file_size)) * 100))

            fmt = "[{done}{pending}] Uploaded {done_bytes:,} of {total:,} bytes ({percent}%) {name}"
            sys.stderr.write(fmt.format(done='=' * (ticks - 1) + '>' if ticks > 0 else '',
                                        pending=' ' * (num_ticks - ticks),
                                        done_bytes=handler._num_bytes_transmitted,
                                        total=file_size,
                                        percent=percent,
                                        name=filename if filename is not None else ''))
            sys.stderr.flush()
            sys.stderr.write("\r")
            sys.stderr.flush()

    if show_progress:
        report_progress(handler, 0)

    while True:
        buf = read(handler._write_bufsize)
        offset += len(buf)

        if len(buf) == 0:
            break

        handler.write(buf, report_progress_fn=report_progress if show_progress else None, **remaining_kwargs)

    if filename is not None:
        fd.close()

    handler.flush(report_progress_fn=report_progress if show_progress else None, **remaining_kwargs)

    if show_progress:
        sys.stderr.write("\n")
        sys.stderr.flush()

    if not keep_open:
        handler.close(block=wait_on_close, report_progress_fn=report_progress if show_progress else None, **remaining_kwargs)

    return handler

def upload_string(to_upload, media_type=None, keep_open=False, wait_on_close=False, **kwargs):
    """
    :param to_upload: String to upload into a file
    :type to_upload: string
    :param media_type: Internet Media Type
    :type media_type: string
    :param keep_open: If False, closes the file after uploading
    :type keep_open: boolean
    :param wait_on_close: If True, waits for the file to close
    :type wait_on_close: boolean
    :returns: Remote file handler
    :rtype: :class:`~dxpy.bindings.dxfile.DXFile`

    Additional optional parameters not listed: all those under
    :func:`dxpy.bindings.DXDataObject.new`.

    Uploads the data in the string *to_upload* into a new file object
    (with media type *media_type* if given) and returns the associated
    remote file handler.

    """

    # Use 'a' mode because we will be responsible for closing the file
    # ourselves later (if requested).
    handler = new_dxfile(media_type=media_type, mode='a', **kwargs)

    # For subsequent API calls, don't supply the dataobject metadata
    # parameters that are only needed at creation time.
    _, remaining_kwargs = dxpy.DXDataObject._get_creation_params(kwargs)

    handler.write(to_upload, **remaining_kwargs)

    if not keep_open:
        handler.close(block=wait_on_close, **remaining_kwargs)

    return handler


text:
<?php

namespace Elastica\Test\Transport;

use Elastica\Client;
use Elastica\Connection;
use Elastica\Query;
use Elastica\Test\Base as BaseTest;

/**
 * Elastica Null Transport Test
 *
 * @package Elastica
 * @author James Boehmer <james.boehmer@jamesboehmer.com>
 */
class NullTest extends BaseTest
{

    public function testEmptyResult()
    {
        // Creates a client with any destination, and verify it returns a response object when executed
        $client = $this->_getClient();
        $connection = new Connection(array('transport' => 'Null'));
        $client->setConnections(array($connection));

        $index = $client->getIndex('elasticaNullTransportTest1');

        $resultSet = $index->search(new Query());
        $this->assertNotNull($resultSet);

        $response = $resultSet->getResponse();
        $this->assertNotNull($response);

         // Validate most of the expected fields in the response data.  Consumers of the response
         // object have a reasonable expectation of finding "hits", "took", etc
         $responseData = $response->getData();
        $this->assertContains("took", $responseData);
        $this->assertEquals(0, $responseData["took"]);
        $this->assertContains("_shards", $responseData);
        $this->assertContains("hits", $responseData);
        $this->assertContains("total", $responseData["hits"]);
        $this->assertEquals(0, $responseData["hits"]["total"]);
        $this->assertContains("params", $responseData);

        $took = $response->getEngineTime();
        $this->assertEquals(0, $took);

        $errorString = $response->getError();
        $this->assertEmpty($errorString);

        $shards = $response->getShardsStatistics();
        $this->assertContains("total", $shards);
        $this->assertEquals(0, $shards["total"]);
        $this->assertContains("successful", $shards);
        $this->assertEquals(0, $shards["successful"]);
        $this->assertContains("failed", $shards);
        $this->assertEquals(0, $shards["failed"]);
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';

import _ from 'lodash';

import { Route, Switch, Redirect } from 'react-router-dom';

import { FeaturedSet } from './FeaturedSet';
import { FindSet } from './FindSet';
import { TargetSet } from './TargetSet';
import { YourSets } from './YourSets';
import { Whoops404 } from './Whoops404';

const checkSetParam = setNum => {
	const setIdArray = setNum.split('-');
	const buildNum = parseInt(setIdArray[1], 10);

	return _.isNumber(buildNum);
};

const renderMergedProps = (component, ...rest) => {
	const finalProps = Object.assign({}, ...rest);

	return (
		React.createElement(component, finalProps)
	);
};

// Easy way to pass properties to components rendered via Route
const PropsRoute = ({ component, ...rest }) => {
	return (
		<Route {...rest} render={routeProps => {
			return renderMergedProps(component, routeProps, rest);
		}}/>
	);
};

const PrivateRoute = ({ component, ...rest }) => {
	return (
		<Route {...rest} render={routeProps => {
			return checkSetParam(routeProps.match.params.set_number)
			? renderMergedProps(component, routeProps, rest)
			: <Redirect from='/target_set' to='/' />
		}}/>
	);
};

export const Main = (props) => (
	<section className="main-wrapper">
		<Switch>
			<PropsRoute component={FeaturedSet}
						exact path='/'
						handleShowAnother={props.handleShowAnother}
						handleAddSet={props.handleAddSet}
						userSets={props.userSets}
						featuredSet={props.featuredSet}
						popularThemes={props.popularThemes}
						statusMessage={props.statusMessage} />
			<PropsRoute component={FindSet}
						path='/find_set'
						handleFindSet={props.handleFindSet}
						handleInputChange={props.handleInputChange}
						searchResults={props.searchResults}
						popularThemes={props.popularThemes} />
			<PropsRoute component={YourSets}
						path='/your_sets'
						handleRemoveSet={props.handleRemoveSet}
						userSets={props.userSets}
						popularThemes={props.popularThemes}
						statusMessage={props.statusMessage} />

			<PrivateRoute component={TargetSet}
						  path='/target_set/:set_number'
						  cachedThemes={props.cachedThemes}
						  userSets={props.userSets}
						  popularThemes={props.popularThemes}
						  handleAddSet={props.handleAddSet}
						  getCurrentSet={props.getCurrentSet} />

			<Redirect from='/target_set' to='/' />
			<PropsRoute component={Whoops404} />
		</Switch>
	</section>
);

Main.propTypes = {
	handleShowAnother: PropTypes.func.isRequired,
	handleAddSet: PropTypes.func.isRequired,
	handleRemoveSet: PropTypes.func.isRequired,
	handleFindSet: PropTypes.func.isRequired,
	handleInputChange: PropTypes.func.isRequired,
	getCurrentSet: PropTypes.func.isRequired,
	featuredSet: PropTypes.object.isRequired,
	userSets: PropTypes.array.isRequired,
	cachedThemes: PropTypes.array.isRequired,
	popularThemes: PropTypes.array.isRequired,
	statusMessage: PropTypes.string.isRequired,
	searchResults: PropTypes.array.isRequired
};


text:
package Q9_02_Social_Network;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

public class BFSData {
	public Queue<PathNode> toVisit = new LinkedList<PathNode>();
	public HashMap<Integer, PathNode> visited = new HashMap<Integer, PathNode>();

	public BFSData(Person root) {
		PathNode sourcePath = new PathNode(root, null);
		toVisit.add(sourcePath);
		visited.put(root.getID(), sourcePath);
	}

	public boolean isFinished() {
		return toVisit.isEmpty();
	}
}


text:
{% extends "layout.html" %}

{% block page_title %}
  GOV.UK prototype kit
{% endblock %}

{% block content %}

    {% include 'includes/phase_banner_alpha.html' %}

MVP Prototype

Sprint 3 - May/June 2016

          Content changes to start page, dependant children page, exit page. Entire
          redesign of end page as users thought the journey was complete when they
          still needed to send their marriage certificates. Slight tweak to bank
          details page to include ‘safe and secure’ in the sidebar.

Start now

			    Previous Iterations

Sprint 2 - May 2016

              In this version, inline with user research insights, we have removed the
              page asking about registering for child benefits. We have also split the
              contact details collection onto a page of its own. We also moved the
              collection of the partners details to the front of the journey, so the
              users felt it was important.

Start now

Sprint 1 - Apr 2016

Version 1 - One thing per page

    					This is the first iteration of the prototype. We have encorporated three
              knockout questions to try and determine if the user is eligible for BSP.
              The journey ends where an agent will have to pick up the claim to gather
              evidence.

Start now v1

Version 2 - Grouped eligibility and child benefit

    					This iteration has moved the eligibility questions into one page, and has
              moved the two questions around child benefit and dependent children into
              one page. This iteration also has 'full name' instead of seperate first
              name and last name.

Start now v2

Version 3

    					This iteration has kept eligibility questions on one page from v2,
              but has kept the two step child-benefit process from v1. This iteration
              has a different exit journey, allowing the user to continue regardless
              of their eligibility.

Start now v3

Alternate journeys

Marriage certificates

          This prototype is to test the various ways people can supply their
          marriage certificates. Because only 20% of marriages can be automatically
          verified, we are exploring ways the user can get their certificates to
          us for that verification.

Start now

Overseas

          This prototype is to test the journey for users who's partners may
          have worked abroad and payed into their social security scheme. The
          journey will change based on if you worked in a partnering EU country,
          so to view the entire journey choose countries such as Italy and Spain.

Start now

{% endblock %}


text:
package com.google.cloud.pubsub.deprecated;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.cloud.ByteArray;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.ByteString;
import com.google.protobuf.Timestamp;
import com.google.pubsub.v1.PubsubMessage;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * A Google Cloud Pub/Sub message. A message is the combination of data and (optional) attributes
 * that a publisher sends to a topic and is eventually delivered to subscribers.
 *
 *
Message attributes are key-value pairs that a publisher can define for a message. For example,
 * a key {@code iana.org/language_tag} and value {@code en} could be added to messages to mark them
 * as readable by an English-speaking subscriber.
 *
 *
To be published, a message must have a non-empty payload, or at least one attribute.
 *
 * @see Pub/Sub Data Model
 */
public class Message implements Serializable {

  static final Function<Message, PubsubMessage> TO_PB_FUNCTION =
      new Function<Message, PubsubMessage>() {
        @Override
        public PubsubMessage apply(Message message) {
          return message.toPb();
        }
      };

  private static final long serialVersionUID = -1436515787233340634L;
  private static final long NANOS_PER_MILLISECOND = 1000000;
  private static final long MILLIS_PER_SECOND = 1000;

  private final String id;
  private final InternalByteArray payload;
  private final ImmutableMap<String, String> attributes;
  private final Long publishTime;

  private static final class InternalByteArray extends ByteArray {

    private static final long serialVersionUID = -3330181485911805428L;

    InternalByteArray(ByteString byteString) {
      super(byteString);
    }

    InternalByteArray(ByteArray byteArray) {
      super(byteArray);
    }

    @Override
    protected ByteString getByteString() {
      return super.getByteString();
    }
  }

  /**
   * Builder for {@code Message} objects.
   */
  public abstract static class Builder {

    abstract Builder setId(String id);

    /**
     * Sets the message payload to the provided string. The string is enconded {@code UTF-8}.
     */
    @Deprecated
    public abstract Builder payload(String payload);

    /**
     * Sets the message payload to the provided string. The string is enconded {@code UTF-8}.
     */
    public abstract Builder setPayload(String payload);

    /**
     * Sets the message payload to the provided {@link ByteArray}.
     */
    @Deprecated
    public abstract Builder payload(ByteArray payload);

    /**
     * Sets the message payload to the provided {@link ByteArray}.
     */
    public abstract Builder setPayload(ByteArray payload);

    /**
     * Sets the message attributes to the provided map. Message attributes are key-value pairs that
     * a publisher can define for a message. For example, a key {@code iana.org/language_tag} and
     * value {@code en} could be added to messages to mark them as readable by an English-speaking
     * subscriber.
     */
    @Deprecated
    public abstract Builder attributes(Map<String, String> attributes);

    /**
     * Sets the message attributes to the provided map. Message attributes are key-value pairs that
     * a publisher can define for a message. For example, a key {@code iana.org/language_tag} and
     * value {@code en} could be added to messages to mark them as readable by an English-speaking
     * subscriber.
     */
    public abstract Builder setAttributes(Map<String, String> attributes);

    /**
     * Adds a new attribute to the message attributes. If an attribute with name {@code name} was
     * already set, its value is updated.
     */
    public abstract Builder addAttribute(String name, String value);

    /**
     * Removes an attribute give its name from the message attributes.
     */
    public abstract Builder removeAttribute(String name);

    /**
     * Clears all message attributes.
     */
    public abstract Builder clearAttributes();

    abstract Builder setPublishTime(long publishTime);

    /**
     * Creates a message object.
     */
    public abstract Message build();
  }

  static final class BuilderImpl extends Builder {

    private String id;
    private ByteArray payload;
    private Map<String, String> attributes = new HashMap<>();
    private Long publishTime;

    private BuilderImpl() {}

    BuilderImpl(Message message) {
      id = message.id;
      payload = message.payload;
      attributes = new HashMap<>(message.attributes);
      publishTime = message.publishTime;
    }

    @Override
    BuilderImpl setId(String id) {
      this.id = checkNotNull(id);
      return this;
    }

    @Override
    @Deprecated
    public Builder payload(String payload) {
      return setPayload(payload);
    }

    @Override
    public Builder setPayload(String payload) {
      return setPayload(ByteArray.copyFrom(payload));
    }

    @Override
    @Deprecated
    public Builder payload(ByteArray payload) {
      return setPayload(payload);
    }

    @Override
    public Builder setPayload(ByteArray payload) {
      this.payload = payload;
      return this;
    }

    @Override
    public Builder addAttribute(String name, String value) {
      attributes.put(name, value);
      return this;
    }

    @Override
    @Deprecated
    public Builder attributes(Map<String, String> attributes) {
      return setAttributes(attributes);
    }

    @Override
    public Builder setAttributes(Map<String, String> attributes) {
      this.attributes = new HashMap<>(attributes);
      return this;
    }

    @Override
    public Builder removeAttribute(String name) {
      attributes.remove(name);
      return this;
    }

    @Override
    public Builder clearAttributes() {
      attributes.clear();
      return this;
    }

    @Override
    Builder setPublishTime(long publishTime) {
      this.publishTime = publishTime;
      return this;
    }

    @Override
    public Message build() {
      return new Message(this);
    }
  }

  Message(BuilderImpl builder) {
    id = builder.id;
    payload = new InternalByteArray(checkNotNull(builder.payload));
    attributes = ImmutableMap.copyOf(builder.attributes);
    publishTime = builder.publishTime;
  }

  /**
   * Returns the time in milliseconds at which the message was published. This value is set by the
   * server when it receives the publish call. If not set, this method returns {@code null}.
   */
  @Deprecated
  public Long publishTime() {
    return getPublishTime();
  }

  /**
   * Returns the time in milliseconds at which the message was published. This value is set by the
   * server when it receives the publish call. If not set, this method returns {@code null}.
   */
  public Long getPublishTime() {
    return publishTime;
  }

  /**
   * Returns the message attributes. Message attributes are key-value pairs that a publisher can
   * define for a message. For example, a key {@code iana.org/language_tag} and value {@code en}
   * could be added to messages to mark them as readable by an English-speaking subscriber.
   */
  @Deprecated
  public Map<String, String> attributes() {
    return getAttributes();
  }

  /**
   * Returns the message attributes. Message attributes are key-value pairs that a publisher can
   * define for a message. For example, a key {@code iana.org/language_tag} and value {@code en}
   * could be added to messages to mark them as readable by an English-speaking subscriber.
   */
  public Map<String, String> getAttributes() {
    return attributes;
  }

  /**
   * Returns the id of this message, set by the server when the message is published. The id is
   * guaranteed to be unique within the topic. This value may be read by a subscriber that receives
   * a Pub/Sub message via a pull call or a push delivery. If not set, this method returns
   * {@code null}.
   */
  @Deprecated
  public String id() {
    return getId();
  }

  /**
   * Returns the id of this message, set by the server when the message is published. The id is
   * guaranteed to be unique within the topic. This value may be read by a subscriber that receives
   * a Pub/Sub message via a pull call or a push delivery. If not set, this method returns
   * {@code null}.
   */
  public String getId() {
    return id;
  }

  /**
   * Returns the message payload as a string, decoded using {@code UTF-8}.
   */
  @Deprecated
  public String payloadAsString() {
    return getPayloadAsString();
  }

  /**
   * Returns the message payload as a string, decoded using {@code UTF-8}.
   */
  public String getPayloadAsString() {
    return payload.toStringUtf8();
  }

  /**
   * Returns the message payload.
   */
  @Deprecated
  public ByteArray payload() {
    return getPayload();
  }

  /**
   * Returns the message payload.
   */
  public ByteArray getPayload() {
    return payload;
  }

  final boolean baseEquals(Message message) {
    return Objects.equals(id, message.id)
        && Objects.equals(payload, message.payload)
        && Objects.equals(attributes, message.attributes)
        && Objects.equals(publishTime, message.publishTime);
  }

  @Override
  public boolean equals(Object obj) {
    return obj == this
        || obj != null
        && obj.getClass().equals(Message.class)
        && baseEquals((Message) obj);
  }

  @Override
  public int hashCode() {
    return Objects.hash(id, payload, attributes, publishTime);
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this)
        .add("id", id)
        .add("payload", payload)
        .add("attributes", attributes)
        .add("publishTime", publishTime)
        .toString();
  }

  PubsubMessage toPb() {
    PubsubMessage.Builder builder = PubsubMessage.newBuilder();
    if (id != null) {
      builder.setMessageId(id);
    }
    builder.setData(payload.getByteString());
    builder.putAllAttributes(attributes);
    Timestamp.Builder tsBuilder = Timestamp.newBuilder();
    if (publishTime != null) {
      tsBuilder.setSeconds(publishTime / MILLIS_PER_SECOND);
      tsBuilder.setNanos((int) (publishTime % MILLIS_PER_SECOND * NANOS_PER_MILLISECOND));
    }
    builder.setPublishTime(tsBuilder);
    return builder.build();
  }

  static Message fromPb(PubsubMessage messagePb) {
    Builder builder = newBuilder(new InternalByteArray(messagePb.getData()));
    if (messagePb.hasPublishTime()) {
      Timestamp ts = messagePb.getPublishTime();
      Long millis = ts.getSeconds() * MILLIS_PER_SECOND + ts.getNanos() / NANOS_PER_MILLISECOND;
      if (millis != 0) {
        builder.setPublishTime(millis);
      }
    }
    if (!Objects.equals(messagePb.getMessageId(), "")) {
      builder.setId(messagePb.getMessageId());
    }
    for (Map.Entry<String, String> entry : messagePb.getAttributesMap().entrySet()) {
      builder.addAttribute(entry.getKey(), entry.getValue());
    }
    return builder.build();
  }

  /**
   * Returns a builder for the message object.
   */
  public Builder toBuilder() {
    return new BuilderImpl(this);
  }

  /**
   * Creates a {@code Message} object given the payload as a string. The string is enconded using
   * {@code UTF-8}.
   */
  public static Message of(String payload) {
    return newBuilder(payload).build();
  }

  /**
   * Creates a {@code Message} object given the payload as a {@link ByteArray}. To be published a
   * message must have a non-empty payload.
   */
  public static Message of(ByteArray payload) {
    return newBuilder(payload).build();
  }

  /**
   * Creates a builder for {@code Message} objects given the payload as a string. The string is
   * enconded using {@code UTF-8}. To be published a message must have a non-empty payload.
   */
  @Deprecated
  public static Builder builder(String payload) {
    return newBuilder(payload);
  }

  /**
   * Creates a builder for {@code Message} objects given the payload as a string. The string is
   * enconded using {@code UTF-8}. To be published a message must have a non-empty payload.
   */
  public static Builder newBuilder(String payload) {
    return new BuilderImpl().setPayload(payload);
  }

  /**
   * Creates a builder for {@code Message} objects given the payload as a {@link ByteArray}. To be
   * published a message must have a non-empty payload, or at least one attribute.
   */
  @Deprecated
  public static Builder builder(ByteArray payload) {
    return newBuilder(payload);
  }

  /**
   * Creates a builder for {@code Message} objects given the payload as a {@link ByteArray}. To be
   * published a message must have a non-empty payload, or at least one attribute.
   */
  public static Builder newBuilder(ByteArray payload) {
    return new BuilderImpl().setPayload(payload);
  }
}


text:
<?php
namespace App\Component;

class TaskList extends \Nette\Application\UI\Control {

	/** @var \App\Model\TaskList **/
	public $List;

	/** @var \App\Model\Project **/
	public $Project;

	/** @var \Nette\Database\Context **/
	public $DB;

	/** @var \App\Model\User **/
	public $User;

	/** @var array */
	protected $tasks;

	public function handleTask($id, $projectId = null) {
		if ($projectId) {
			$this->Project->loadFromId($projectId);
		}
		if ($this->presenter->isAjax()) {
			$this->redrawControl('task');
		}
		else {
			// $this->presenter->redirect('Task:detail', array('id' => $id, 'projectID'=>$this->Project->pr_ID,'projectName'=>$this->Project->pr_name,'listID'=>$this->List ? $this->List->tl_ID : null,'listName'=>$this->List ? $this->List->tl_name : null));
		}
	}

	public function handletaskDone($id, $blockId, $projectId, $taskListId) {

		$Task = $this->presenter->TaskFactory->getById($this->getParameter('id'));
		$Task->finish();

		if ($taskListId) {
			$this->List = $this->presenter->TaskList;
			$this->List->load($taskListId);
			$this->List->setProject($this->presenter->ProjectFactory->get($projectId));
			$this->tasks = null;
		}
		else {
			$this->tasks = $this->presenter->TaskFactory->getAll()->getTasks();
			$this->List = null;
		}

		$this->redrawControl('taskList');

	}

	public function setList(\App\Model\TaskList $List) {
		$this->List = $List;
	}

	public function setProject(\App\Model\Project $Project) {
		$this->Project =  $Project;
	}

	public function setTasks(array $list) {
		$this->tasks = $list;
	}

	public function setUser(\App\Model\User $User) {
		$this->User = $User;
	}

	public function getTasks() {
		return $this->tasks;
	}

	public function render() {
		$template = $this->template;
		$template->setFile(__DIR__ . '/../templates/controls/taskList.latte');
		$template->List    = $this->List;
		$template->tasks   = $this->tasks;
		$template->Project = $this->Project;
		$template->User    = $this->User;
		$template->render();
	}

	public function createComponentTaskDetail() {
		$Component = new TaskDetail();

		$Component->setTaskFactory($this->presenter->TaskFactory);

		if ($this->Project) {
			$Component->setProject($this->Project);
		}
		if ($this->List) {
			$Component->setList($this->List);
		}
		if ($this->getParameter('id')) {
			$Component->setTask($this->presenter->TaskFactory->getById($this->getParameter('id')));
		}
		return $Component;
	}
}


text:
package cni

import "github.com/containernetworking/cni/pkg/types/current"

// Deprecated: use cni.Opt instead
type CNIOpt = Opt //nolint: golint // type name will be used as cni.CNIOpt by other packages, and that stutters

// Deprecated: use cni.Result instead
type CNIResult = Result //nolint: golint // type name will be used as cni.CNIResult by other packages, and that stutters

// GetCNIResultFromResults creates a Result from the given slice of current.Result,
// adding structured data containing the interface configuration for each of the
// interfaces created in the namespace. It returns an error if validation of
// results fails, or if a network could not be found.
// Deprecated: do not use
func (c *libcni) GetCNIResultFromResults(results []*current.Result) (*Result, error) {
	return c.createResult(results)
}


text:
namespace Stripe
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    public class ApplicationFeeRefundService : ServiceNested<ApplicationFeeRefund>,
        INestedCreatable<ApplicationFeeRefund, ApplicationFeeRefundCreateOptions>,
        INestedListable<ApplicationFeeRefund, ApplicationFeeRefundListOptions>,
        INestedRetrievable<ApplicationFeeRefund, ApplicationFeeRefundGetOptions>,
        INestedUpdatable<ApplicationFeeRefund, ApplicationFeeRefundUpdateOptions>
    {
        public ApplicationFeeRefundService()
            : base(null)
        {
        }

        public ApplicationFeeRefundService(IStripeClient client)
            : base(client)
        {
        }

        public override string BasePath => "/v1/application_fees/{PARENT_ID}/refunds";

        [Obsolete("Use BaseOptions.AddExpand instead.")]
        public bool ExpandBalanceTransaction { get; set; }

        [Obsolete("Use BaseOptions.AddExpand instead.")]
        public bool ExpandFee { get; set; }

        public virtual ApplicationFeeRefund Create(string applicationFeeId, ApplicationFeeRefundCreateOptions options = null, RequestOptions requestOptions = null)
        {
            return this.CreateNestedEntity(applicationFeeId, options, requestOptions);
        }

        public virtual Task<ApplicationFeeRefund> CreateAsync(string applicationFeeId, ApplicationFeeRefundCreateOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            return this.CreateNestedEntityAsync(applicationFeeId, options, requestOptions, cancellationToken);
        }

        public virtual ApplicationFeeRefund Get(string applicationFeeId, string refundId, ApplicationFeeRefundGetOptions options = null, RequestOptions requestOptions = null)
        {
            return this.GetNestedEntity(applicationFeeId, refundId, options, requestOptions);
        }

        public virtual Task<ApplicationFeeRefund> GetAsync(string applicationFeeId, string refundId, ApplicationFeeRefundGetOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            return this.GetNestedEntityAsync(applicationFeeId, refundId, options, requestOptions, cancellationToken);
        }

        public virtual StripeList<ApplicationFeeRefund> List(string applicationFeeId, ApplicationFeeRefundListOptions options = null, RequestOptions requestOptions = null)
        {
            return this.ListNestedEntities(applicationFeeId, options, requestOptions);
        }

        public virtual Task<StripeList<ApplicationFeeRefund>> ListAsync(string applicationFeeId, ApplicationFeeRefundListOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            return this.ListNestedEntitiesAsync(applicationFeeId, options, requestOptions, cancellationToken);
        }

        public virtual IEnumerable<ApplicationFeeRefund> ListAutoPaging(string applicationFeeId, ApplicationFeeRefundListOptions options = null, RequestOptions requestOptions = null)
        {
            return this.ListNestedEntitiesAutoPaging(applicationFeeId, options, requestOptions);
        }

        public virtual ApplicationFeeRefund Update(string applicationFeeId, string refundId, ApplicationFeeRefundUpdateOptions options, RequestOptions requestOptions = null)
        {
            return this.UpdateNestedEntity(applicationFeeId, refundId, options, requestOptions);
        }

        public virtual Task<ApplicationFeeRefund> UpdateAsync(string applicationFeeId, string refundId, ApplicationFeeRefundUpdateOptions options, RequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            return this.UpdateNestedEntityAsync(applicationFeeId, refundId, options, requestOptions, cancellationToken);
        }
    }
}


text:
/**
 * NOTE: this is not the original header file from the hal component. It is a stripped-down copy to support mocking.
 */

#pragma once

/**
 * @brief Enum with the three SPI peripherals that are software-accessible in it
 */
typedef enum {
// SPI_HOST (SPI1_HOST) is not supported by the SPI Master and SPI Slave driver on ESP32-S2
    SPI1_HOST=0,    ///< SPI1
    SPI2_HOST=1,    ///< SPI2
    SPI3_HOST=2,    ///< SPI3
    SPI_HOST_MAX=3,   ///< invalid host value
} spi_host_device_t;


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

namespace Amazon.Auth.AccessControlPolicy.ActionIdentifiers
{
    /// <summary>
    /// The available AWS access control policy actions for AWS Import Export.
    /// </summary>
    /// <see cref="Amazon.Auth.AccessControlPolicy.Statement.Actions"/>
    public static class ImportExportActionIdentifiers
    {
        public static readonly ActionIdentifier AllImportExportActions = new ActionIdentifier("importexport:*");

        public static readonly ActionIdentifier CreateJob = new ActionIdentifier("importexport:CreateJob");
        public static readonly ActionIdentifier UpdateJob = new ActionIdentifier("importexport:UpdateJob");
        public static readonly ActionIdentifier CancelJob = new ActionIdentifier("importexport:CancelJob");
        public static readonly ActionIdentifier ListJobs = new ActionIdentifier("importexport:ListJobs");
        public static readonly ActionIdentifier GetStatus = new ActionIdentifier("importexport:GetStatus");
    }
}


text:
from os import path

from gluon import current
from gluon.html import *
from gluon.storage import Storage

from s3.s3crud import S3CRUD
from s3.s3filter import S3DateFilter, S3LocationFilter, S3OptionsFilter, S3TextFilter
from s3.s3query import FS
from s3.s3utils import s3_avatar_represent

THEME = "NEREIDS"

# =============================================================================
class index():
    """ Custom Home Page """

    def __call__(self):

        response = current.response
        output = {}
        #output["title"] = response.title = current.deployment_settings.get_system_name()
        view = path.join(current.request.folder, "private", "templates",
                         THEME, "views", "index.html")
        try:
            # Pass view as file not str to work in compiled mode
            response.view = open(view, "rb")
        except IOError:
            from gluon.http import HTTP
            raise HTTP(404, "Unable to open Custom View: %s" % view)

        s3 = response.s3
        # Image Carousel
        s3.jquery_ready.append('''$('#myCarousel').carousel()''')

        if current.auth.is_logged_in():
            s3db = current.s3db
            # Latest 4 Events
            resource = s3db.resource("cms_post")
            resource.add_filter(FS("series_id$name") == "Event")
            list_fields = ["location_id",
                           "date",
                           "body",
                           "created_by",
                           "created_by$organisation_id",
                           "document.file",
                           "event_post.event_id",
                           ]
            orderby = resource.get_config("list_orderby",
                                          ~resource.table.date)
            datalist, numrows, ids = resource.datalist(fields=list_fields,
                                                       start=None,
                                                       limit=4,
                                                       list_id="event_datalist",
                                                       orderby=orderby,
                                                       layout=render_cms_events)
            if numrows == 0:
                # Empty table or just no match?
                table = resource.table
                if "deleted" in table:
                    available_records = current.db(table.deleted != True)
                else:
                    available_records = current.db(table._id > 0)
                if available_records.select(table._id,
                                            limitby=(0, 1)).first():
                    msg = DIV(S3CRUD.crud_string(resource.tablename,
                                                 "msg_no_match"),
                              _class="empty")
                else:
                    msg = DIV(S3CRUD.crud_string(resource.tablename,
                                                 "msg_list_empty"),
                              _class="empty")
                data = msg
            else:
                # Render the list
                dl = datalist.html()
                data = dl
            output["events"] = data

            # Latest 4 Updates
            resource = s3db.resource("cms_post")
            list_fields = ["series_id",
                           "location_id",
                           "date",
                           "body",
                           "created_by",
                           "created_by$organisation_id",
                           "document.file",
                           "event_post.event_id",
                           ]
            orderby = resource.get_config("list_orderby",
                                          ~resource.table.date)
            datalist, numrows, ids = resource.datalist(fields=list_fields,
                                                       start=None,
                                                       limit=4,
                                                       list_id="news_datalist",
                                                       orderby=orderby,
                                                       layout=s3.render_posts)
            if numrows == 0:
                # Empty table or just no match?
                table = resource.table
                if "deleted" in table:
                    available_records = current.db(table.deleted != True)
                else:
                    available_records = current.db(table._id > 0)
                if available_records.select(table._id,
                                            limitby=(0, 1)).first():
                    msg = DIV(S3CRUD.crud_string(resource.tablename,
                                                 "msg_no_match"),
                              _class="empty")
                else:
                    msg = DIV(S3CRUD.crud_string(resource.tablename,
                                                 "msg_list_empty"),
                              _class="empty")
                data = msg
            else:
                # Render the list
                dl = datalist.html()
                data = dl
            output["news"] = data

        return output

# =============================================================================
class datalist():
    """ Alternate URL for Updates page """

    def __call__(self):

        return _updates()

# =============================================================================
class datalist_dl_post():
    """ AJAX URL for CMS Posts (for Updates page) """

    def __call__(self):

        return _updates()

# =============================================================================
class datalist_dl_filter():
    """ AJAX URL for CMS Posts Filter Form (for Updates page) """

    def __call__(self):

        return _updates()

# =============================================================================
class login():
    """ Custom Login page """

    def __call__(self):

        return _login()

# =============================================================================
class updates():
    """ Updates page """

    def __call__(self):

        return _updates()

# =============================================================================
class validate():
    """ Alternate URL for Updates page """

    def __call__(self):

        return _updates()

# =============================================================================
def _updates():
    """
        Custom Page
        - Filterable DataList of CMS Posts & a DataList of Events
    """

    #if not current.auth.is_logged_in():
    #    current.auth.permission.fail()

    T = current.T
    s3db = current.s3db
    request = current.request
    response = current.response
    s3 = response.s3

    current.deployment_settings.ui.customise_cms_post()

    list_layout = s3.render_posts

    filter_widgets = [S3TextFilter(["body"],
                                   label = "",
                                   _class = "filter-search",
                                   #_placeholder = T("Search").upper(),
                                   ),
                      S3OptionsFilter("series_id",
                                      label = T("Filter by Type"),
                                      # We want translations
                                      #represent = "%(name)s",
                                      hidden = True,
                                      ),
                      S3LocationFilter("location_id",
                                       label = T("Filter by Location"),
                                       levels = ("L1", "L2", "L3",),
                                       hidden = True,
                                       ),
                      S3OptionsFilter("created_by$organisation_id",
                                      label = T("Filter by Organization"),
                                      # Can't use this for integers, use field.represent instead
                                      #represent="%(name)s",
                                      hidden = True,
                                      ),
                      S3DateFilter("created_on",
                                   label = T("Filter by Date"),
                                   hide_time = True,
                                   hidden = True,
                                   ),
                      ]

    s3db.configure("cms_post",
                   # We use a custom Advanced widget
                   filter_advanced = False,
                   filter_formstyle = filter_formstyle,
                   filter_submit = (T("SEARCH"), "btn btn-primary"),
                   filter_widgets = filter_widgets,
                   list_layout = list_layout,
                   # Create form comes via AJAX in a Modal
                   insertable = False,
                   )

    s3.dl_pagelength = 6  # 5 forces an AJAX call

    old_args = request.args
    if "datalist_dl_post" in old_args:
        # DataList pagination or Ajax-deletion request
        request.args = ["datalist_f"]
        ajax = "list"
    elif "datalist_dl_filter" in old_args:
        # FilterForm options update request
        request.args = ["filter"]
        ajax = "filter"
    elif "validate.json" in old_args:
        # Inline component validation request
        request.args = []
        ajax = True
    else:
        # Default
        request.args = ["datalist_f"]
        ajax = None

    def prep(r):
        if ajax == "list":
            r.representation = "dl"
        elif ajax == "filter":
            r.representation = "json"
        return True
    s3.prep = prep

    output = current.rest_controller("cms", "post",
                                     list_ajaxurl = URL(f="index",
                                                        args="datalist_dl_post"),
                                     filter_ajax_url = URL(f="index",
                                                           args="datalist_dl_filter",
                                                           vars={}))

    request.args = old_args

    if ajax == "list":
        # Don't override view if this is an Ajax-deletion request
        if not "delete" in request.get_vars:
            response.view = "plain.html"
    elif not ajax:
        # Set Title & View after REST Controller, in order to override
        output["title"] = T("News Feed")
        view = path.join(request.folder, "private", "templates",
                         THEME, "views", "updates.html")
        try:
            # Pass view as file not str to work in compiled mode
            response.view = open(view, "rb")
        except IOError:
            from gluon.http import HTTP
            raise HTTP(404, "Unable to open Custom View: %s" % view)

        scripts = []
        sappend = scripts.append
        # Style the Search TextFilter widget
        sappend('''$('#post-cms_post_body-text-filter__row').addClass('input-append').append('')''')
        # Button to toggle Advanced Form
        sappend('''$('#list-filter').append(' %s')''' % T("Advanced Search"))
        sappend('''$('.accordion-toggle').click(function(){$('.advanced').toggle()})''')
        s3.jquery_ready.append('''\n'''.join(scripts))

        # Latest 5 Disasters
        resource = s3db.resource("event_event")
        list_fields = ["name",
                       "event_type_id$name",
                       "start_date",
                       "closed",
                       ]
        orderby = resource.get_config("list_orderby",
                                      ~resource.table.created_on)
        datalist, numrows, ids = resource.datalist(fields=list_fields,
                                                   start=None,
                                                   limit=5,
                                                   list_id="event_datalist",
                                                   orderby=orderby,
                                                   layout=render_events)
        # Render the list
        data = datalist.html()
        if numrows == 0:
            # Empty table or just no match?
            table = resource.table
            if "deleted" in table:
                available_records = current.db(table.deleted != True)
            else:
                available_records = current.db(table._id > 0)
            if available_records.select(table._id,
                                        limitby=(0, 1)).first():
                msg = DIV(S3CRUD.crud_string(resource.tablename,
                                             "msg_no_match"),
                          _class="empty")
            else:
                msg = DIV(S3CRUD.crud_string(resource.tablename,
                                             "msg_list_empty"),
                          _class="empty")
            data.insert(1, msg)
        output["disasters"] = data

    return output

# -----------------------------------------------------------------------------
def filter_formstyle(row_id, label, widget, comment, hidden=False):
    """
        Custom Formstyle for FilterForm

        @param row_id: HTML id for the row
        @param label: the label
        @param widget: the form widget
        @param comment: the comment
        @param hidden: whether the row should initially be hidden or not
    """

    if hidden:
        _class = "advanced hide"
    else:
        _class= ""

    if label:
        return DIV(label, widget, _id=row_id, _class=_class)
    else:
        return DIV(widget, _id=row_id, _class=_class)

# -----------------------------------------------------------------------------
def render_events(list_id, item_id, resource, rfields, record):
    """
        Custom dataList item renderer for 'Disasters' on the Updates page

        @param list_id: the HTML ID of the list
        @param item_id: the HTML ID of the item
        @param resource: the S3Resource to render
        @param rfields: the S3ResourceFields to render
        @param record: the record as dict
    """

    record_id = record["event_event.id"]
    item_class = "thumbnail"

    raw = record._row
    name = record["event_event.name"]
    date = record["event_event.start_date"]
    closed = raw["event_event.closed"]
    event_type = record["event_event_type.name"]

    if closed:
        edit_bar = DIV()
    else:
        item_class = "%s disaster" % item_class

        permit = current.auth.s3_has_permission
        table = resource.table
        if permit("update", table, record_id=record_id):
            edit_btn = A(I(" ", _class="icon icon-edit"),
                         _href=URL(c="event", f="event",
                                   args=[record_id, "update.popup"],
                                   vars={"refresh": list_id,
                                         "record": record_id}),
                         _class="s3_modal",
                         _title=current.response.s3.crud_strings.event_event.title_update,
                         )
        else:
            edit_btn = ""
        if permit("delete", table, record_id=record_id):
            delete_btn = A(I(" ", _class="icon icon-remove-sign"),
                           _class="dl-item-delete",
                          )
        else:
            delete_btn = ""
        edit_bar = DIV(edit_btn,
                       delete_btn,
                       _class="edit-bar fright",
                       )

    # Render the item
    item = DIV(DIV(A(IMG(_class="media-object",
                         _src=URL(c="static",
                                  f="img",
                                  args=["event", "%s.png" % event_type]),
                         ),
                     _class="pull-left",
                     _href="#",
                     ),
  		           edit_bar,
                   DIV(A(H5(name,
                            _class="media-heading"),
                         SPAN(date,
                              _class="date-title",
                              ),
                         _href=URL(c="event", f="event",
                                   args=[record_id, "profile"]),
                         ),
                       _class="media-body",
                       ),
                   _class="media",
                   ),
               _class=item_class,
               _id=item_id,
               )

    return item

# -----------------------------------------------------------------------------
def render_cms_events(list_id, item_id, resource, rfields, record):
    """
        Custom dataList item renderer for 'Events' on the Home page

        @param list_id: the HTML ID of the list
        @param item_id: the HTML ID of the item
        @param resource: the S3Resource to render
        @param rfields: the S3ResourceFields to render
        @param record: the record as dict
    """

    record_id = record["cms_post.id"]
    item_class = "thumbnail"

    T = current.T

    raw = record._row
    series = "Event"
    date = record["cms_post.date"]
    body = record["cms_post.body"]
    location = record["cms_post.location_id"]
    location_id = raw["cms_post.location_id"]
    location_url = URL(c="gis", f="location", args=[location_id])
    author = record["cms_post.created_by"]
    author_id = raw["cms_post.created_by"]
    organisation = record["auth_user.organisation_id"]
    organisation_id = raw["auth_user.organisation_id"]
    org_url = URL(c="org", f="organisation", args=[organisation_id, "profile"])
    # @ToDo: Optimise by not doing DB lookups (especially duplicate) within render, but doing these in the bulk query
    avatar = s3_avatar_represent(author_id,
                                 _class="media-object",
                                 _style="width:50px;padding:5px;padding-top:0;")
    db = current.db
    ltable = current.s3db.pr_person_user
    ptable = db.pr_person
    query = (ltable.user_id == author_id) & \
            (ltable.pe_id == ptable.pe_id)
    row = db(query).select(ptable.id,
                           limitby=(0, 1)
                           ).first()
    if row:
        person_url = URL(c="hrm", f="person", args=[row.id])
    else:
        person_url = "#"
    author = A(author,
               _href=person_url,
               )
    avatar = A(avatar,
               _href=person_url,
               _class="pull-left",
               )

    # Edit Bar
    permit = current.auth.s3_has_permission
    table = db.cms_post
    if permit("update", table, record_id=record_id):
        edit_btn = A(I(" ", _class="icon icon-edit"),
                     _href=URL(c="cms", f="post",
                               args=[record_id, "update.popup"],
                               vars={"refresh": list_id,
                                     "record": record_id}),
                     _class="s3_modal",
                     _title=T("Edit Event"),
                     )
    else:
        edit_btn = ""
    if permit("delete", table, record_id=record_id):
        delete_btn = A(I(" ", _class="icon icon-remove-sign"),
                       _class="dl-item-delete",
                       )
    else:
        delete_btn = ""
    edit_bar = DIV(edit_btn,
                   delete_btn,
                   _class="edit-bar fright",
                   )

    # Dropdown of available documents
    documents = raw["doc_document.file"]
    if documents:
        if not isinstance(documents, list):
            documents = [documents]
        doc_list = UL(_class="dropdown-menu",
                      _role="menu",
                      )
        retrieve = db.doc_document.file.retrieve
        for doc in documents:
            try:
                doc_name = retrieve(doc)[0]
            except IOError:
                doc_name = current.messages["NONE"]
            doc_url = URL(c="default", f="download",
                          args=[doc])
            doc_item = LI(A(I(_class="icon-file"),
                            " ",
                            doc_name,
                            _href=doc_url,
                            ),
                          _role="menuitem",
                          )
            doc_list.append(doc_item)
        docs = DIV(A(I(_class="icon-paper-clip"),
                     SPAN(_class="caret"),
                     _class="btn dropdown-toggle",
                     _href="#",
                     **{"_data-toggle": "dropdown"}
                     ),
                   doc_list,
                   _class="btn-group attachments dropdown pull-right",
                   )
    else:
        docs = ""

    # Render the item
    item = DIV(DIV(I(SPAN(" %s" % T("Event"),
                          _class="card-title",
                          ),
                     _class="icon icon-%s" % series.lower().replace(" ", "_"),
                     ),
                   SPAN(A(location,
                          _href=location_url,
                          ),
                        _class="location-title",
                        ),
                   SPAN(date,
                        _class="date-title",
                        ),
                   edit_bar,
                   _class="card-header",
                   ),
               DIV(avatar,
                   DIV(DIV(body,
                           DIV(author,
                               " - ",
                               A(organisation,
                                 _href=org_url,
                                 _class="card-organisation",
                                 ),
                               docs,
                               _class="card-person",
                               ),
                           _class="media",
                           ),
                       _class="media-body",
                       ),
                   _class="media",
                   ),
               _class=item_class,
               _id=item_id,
               )

    return item

# =============================================================================
class glossary():
    """
        Custom page
    """

    def __call__(self):

        view = path.join(current.request.folder, "private", "templates",
                         THEME, "views", "glossary.html")
        try:
            # Pass view as file not str to work in compiled mode
            current.response.view = open(view, "rb")
        except IOError:
            from gluon.http import HTTP
            raise HTTP(404, "Unable to open Custom View: %s" % view)

        title = current.T("Glossary")

        return dict(title = title,
                    )

# END =========================================================================


text:
import { Injectable } from '@angular/core';

// libs
import { Angulartics2 } from 'angulartics2';
import { Angulartics2Segment } from 'angulartics2/dist/providers';

// TODO: This is a wip at the moment
// Will implement native segment sdk soon
// https://github.com/NathanWalker/nativescript-segment/issues/1

@Injectable()
export class NSAngulartics2Segment extends Angulartics2Segment {

  constructor(angulartics2: Angulartics2) {
    super(angulartics2);
    angulartics2.pageTrack.subscribe((x: any) => this.pageTrack(x.path, x.location));
    angulartics2.eventTrack.subscribe((x: any) => this.eventTrack(x.action, x.properties));
    angulartics2.setUserProperties.subscribe((x: any) => this.setUserProperties(x));
    angulartics2.setUserPropertiesOnce.subscribe((x: any) => this.setUserProperties(x));
  }

  public pageTrack(path: string, location: any) {
    // TODO
  }

  public eventTrack(action: string, properties: any) {
    // TODO
  }

  public setUserProperties(properties: any) {
    // TODO
  }
}


text:
angular.module('<%= module %>').directive('updateOnBlur', function () {
  return {
    restrict: 'E',
    require: 'ngModel',
    scope: {},
    template: '<input type="text" class="form-control" ng-model="modelValue" ng-blur="updateModel(modelValue)"></input>',
    link: function (scope, element, attrs, ngModel) {
      scope.modelValue = ngModel.$viewValue;

      scope.updateModel = function (modelValue) {
        ngModel.$setViewValue(modelValue);
      };
    },
  };
});