text:
Udacity Full Stack Web Developer Nanodegree Project 4

## Products
- [App Engine][1]

## Language
- [Python][2]

## APIs
- [Google Cloud Endpoints][3]

## Setup Instructions
1. Run the app with the devserver using `dev_appserver.py DIR`
2. Run the local front-end portal at http://localhost:8080
3. Run the local back-end portal at http://localhost:8000
4. Run the API explorer at http://localhost:8080/_ah/api/explorer

## Task 1: Sessions
### Basic Information:
Only the creator of that conference can create a Session under a particular conference.
The Session contains attribute like name, highlights, speaker, duration (in minutes), type, date and startHour.

### Technical Information:
Session is created as a child of a conference, for easy referencing. All its attributes are simple data structure to avoid complexity at this level.

### API Details:
#### 1. createSession
**Method:**
POST

**URL:**
{websafeConferenceKey}/createSession

**Fields:**
name          (Compulsory)
highlights    (Optional, Default "None")
speaker       (Optional, Default "None")
duration      (Optional, Default 30)
type          (Optional, Default "None")
date          (Optional, 2015-06-08 (a random date))
startHour     (Optional, Default 0)

This will create a Session Object under a Conference.The user who creates the Session must be the same user as who has created the Conference
#### 2. getConferenceSessions
**Method:**
GET

**URL:**
{websafeConferenceKey}/getConferenceSessions

This will return all Sessions created under a Conference. A user must be logged in to use this API, but he/she may not be the creator of the Conference.
#### 3. getConferenceSessionsByType
**Method:**
POST

**URL:**
{websafeConferenceKey}/getSessionByType

**Fields:**
field          (Optional)

This will return all Sessions created under a Conference of a given type. The type is called "field" in the request message and can be blank, in cause a Session has blank type. A user must be logged in to use this API, but he/she may not be the creator of the Conference.
#### 4. getSessionsBySpeaker
**Method:**
POST

**URL:**
getSessionsBySpeaker

**Fields:**
field          (Optional)

This will return all Sessions of a given speaker. The speaker is called "field" in the request message and can be blank, in cause a Session has blank speaker. A user must be logged in to use this API, but he/she may not be the creator of the Conference.

### TODO List/Future Improvement
1. Speaker can be modelled as a complex data-type with first name, last name and DOB.
2. Session can have start-time and end-time, which cannot exceed the start-time/end-time of the parent conference.
3. One Conference cannnot have conflicting Sessions

## Task 2: Wishlist
### Basic Information:
Users should be able to mark some sessions that they are interested in and retrieve their own current wishlist.
User is not restricted to store Session of Conferences that they have registered

### Technical Information:
Additional parameter of wishlist is added to the Profile object. This is a StringProperty with repeated=True that stores the key of all interested Sessions.

### API Details:
#### 1. addSessionToWishlist
**Method:**
POST

**URL:**
addSessionToWishList

**Fields:**
sessionKey          (Compulsory)

This will add the sessionKey to the user's wishlist under the Profile object. The sessionKey must be a valid Key Object
#### 2. getSessionsInWishlist
**Method:**
GET

**URL:**
getSessionsInWishlist

This will return all user's interested sessions. API will return multiple SessionForms depends on the number of Sessions that the user added to his/her wishlist

## Task 3: Query
### API Details:
#### 1. getSessionByDuration
**Method:**
GET

**URL:**
getSessionByDuration

Task 3 Additional Query 1: return all session with duration less than 30 minutes
#### 2. getSessionByStartHour
**Method:**
GET

**URL:**
getSessionByStartHour

Task 3 Additional Query 2: return all session starts after 5 o'clock (17:00)
#### 3. getComplexQuery
**Method:**
GET

**URL:**
getComplexQuery

Task 3 Complex Query: return all non-workshop sessions before 7 pm. Only one equality filter can be applied, so ndb.OR operator is used to return sessions starts at 20:00, 21:00, 22:00, etc

## Task 4: Featured Speaker
### Basic Information:
When a new session is added to a conference, check the speaker. If there is more than one session by this speaker at this conference, also add a new Memcache entry that features the speaker and session names.

### Technical Information:
A check is carried out before the insertion of the Session object. If the query(same conference, same speaker) returns more than 0 results, set memcache message with the key "featuredSpeaker".

### API Details:
#### 1. getFeaturedSpeaker
**Method:**
GET

**URL:**
getFeaturedSpeaker

This will return the featured speaker message

[1]: https://developers.google.com/appengine
[2]: http://python.org
[3]: https://developers.google.com/appengine/docs/python/endpoints/


text:
package bluesky.protocol.packet.client;

import bluesky.protocol.packet.Packet;
import org.msgpack.annotation.Message;

@Message
public class SC_Notify implements Packet {
    public String msg;
    public int time;

    @Override
    public byte getPacketId() { return 1; }

    public SC_Notify() {}
    public SC_Notify(String msg, int time) {
        this.msg = msg;
        this.time = time;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
  Some basic tests of the client API.
*/

#include "my_test.h"
#include "ma_common.h"

static int perf1(MYSQL *mysql)
{
  int rc;
  MYSQL_STMT *stmt;
  char *stmtstr= "SELECT s.emp_no, s.salary, e.emp_no, e.first_name, e.last_name, e.gender FROM salaries s, employees e WHERE s.emp_no = e.emp_no";

  rc= mysql_select_db(mysql, "employees");
  if (rc)
  {
    diag("Employees database not installed");
    return SKIP;
  }

  stmt= mysql_stmt_init(mysql);

  diag("prepare");
  rc= mysql_stmt_prepare(stmt, stmtstr, strlen(stmtstr));
  check_stmt_rc(rc, stmt);

  diag("execute");
  rc= mysql_stmt_execute(stmt);
  check_stmt_rc(rc, stmt);

  diag("store");
  rc= mysql_stmt_store_result(stmt);
  check_stmt_rc(rc, stmt);

  diag("fetch");
  while (!mysql_stmt_fetch(stmt));

  mysql_stmt_close(stmt);
  return OK;
}

struct my_tests_st my_tests[] = {
  {"perf1", perf1, TEST_CONNECTION_NEW, 0,  NULL,  NULL},
  {NULL, NULL, 0, 0, NULL, NULL}
};

int main(int argc, char **argv)
{
  if (argc > 1)
    get_options(argc, argv);

  get_envvars();

  run_tests(my_tests);

  return(exit_status());
}


text:
<?php

namespace Butterfly\Application\RequestResponse\Routing;

/**
 * @author Marat Fakhertdinov <marat.fakhertdinov@gmail.com>
 */
class UndefinedUriException extends \RuntimeException
{

}


text:
.. _parsing:

Request Parsing
===============

.. warning ::

    The whole request parser part of Flask-RESTPlus is slated for removal and
    will be replaced by documentation on how to integrate with other packages
    that do the input/output stuff better
    (such as `marshmallow <http://marshmallow.readthedocs.org>`_).
    This means that it will be maintained until 2.0 but consider it deprecated.
    Don't worry, if you have code using that now and wish to continue doing so,
    it's not going to go away any time too soon.

.. currentmodule:: flask_restplus

Flask-RESTPlus's request parsing interface, :mod:`reqparse`,
is modeled after the :mod:`python:argparse` interface.
It's designed to provide simple and uniform access to any variable on the
:class:`flask.request` object in Flask.

Basic Arguments
---------------

Here's a simple example of the request parser.
It looks for two arguments in the :attr:`flask.Request.values` dict: an integer and a string

.. code-block:: python

    from flask_restplus import reqparse

    parser = reqparse.RequestParser()
    parser.add_argument('rate', type=int, help='Rate cannot be converted')
    parser.add_argument('name')
    args = parser.parse_args()

.. note ::

    The default argument type is a unicode string.
    This will be ``str`` in python3 and ``unicode`` in python2.

If you specify the ``help`` value,
it will be rendered as the error message when a type error is raised while parsing it.
If you do not specify a help message,
the default behavior is to return the message from the type error itself.
See :ref:`error-messages` for more details.

.. note ::
    By default, arguments are **not** required.
    Also, arguments supplied in the request that are not part of the :class:`~reqparse.RequestParser` will be ignored.

.. note ::
    Arguments declared in your request parser but not set in the request itself will default to ``None``.

Required Arguments
------------------

To require a value be passed for an argument,
just add ``required=True`` to the call to :meth:`~reqparse.RequestParser.add_argument`.

.. code-block:: python

    parser.add_argument('name', required=True, help="Name cannot be blank!")

Multiple Values & Lists
-----------------------

If you want to accept multiple values for a key as a list, you can pass ``action='append'`` ::

    parser.add_argument('name', action='append')

This will let you make queries like ::

    curl http://api.example.com -d "name=bob" -d "name=sue" -d "name=joe"

And your args will look like this ::

    args = parser.parse_args()
    args['name']    # ['bob', 'sue', 'joe']

Other Destinations
------------------

If for some reason you'd like your argument stored under a different name once
it's parsed, you can use the ``dest`` keyword argument. ::

    parser.add_argument('name', dest='public_name')

    args = parser.parse_args()
    args['public_name']

Argument Locations
------------------

By default, the :class:`~reqparse.RequestParser` tries to parse values from
:attr:`flask.Request.values`, and :attr:`flask.Request.json`.

Use the ``location`` argument to :meth:`~reqparse.RequestParser.add_argument`
to specify alternate locations to pull the values from. Any variable on the
:class:`flask.Request` can be used. For example: ::

    # Look only in the POST body
    parser.add_argument('name', type=int, location='form')

    # Look only in the querystring
    parser.add_argument('PageSize', type=int, location='args')

    # From the request headers
    parser.add_argument('User-Agent', location='headers')

    # From http cookies
    parser.add_argument('session_id', location='cookies')

    # From file uploads
    parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')

.. note ::

    Only use ``type=list`` when ``location='json'``. `See this issue for more
    details <https://github.com/flask-restplus/flask-restplus/issues/380>`_

Multiple Locations
------------------

Multiple argument locations can be specified by passing a list to ``location``::

    parser.add_argument('text', location=['headers', 'values'])

When multiple locations are specified, the arguments from all locations
specified are combined into a single :class:`~werkzeug.datastructures.MultiDict`.
The last ``location`` listed takes precedence in the result set.

If the argument location list includes the :attr:`~flask.Request.headers`
location the argument names will no longer be case insensitive and must match
their title case names (see :meth:`str.title`). Specifying
``location='headers'`` (not as a list) will retain case insensitivity.

Parser Inheritance
------------------

Often you will make a different parser for each resource you write. The problem
with this is if parsers have arguments in common. Instead of rewriting
arguments you can write a parent parser containing all the shared arguments and
then extend the parser with :meth:`~reqparse.RequestParser.copy`. You can
also overwrite any argument in the parent with
:meth:`~reqparse.RequestParser.replace_argument`, or remove it completely
with :meth:`~reqparse.RequestParser.remove_argument`. For example: ::

    from flask_restplus import reqparse

    parser = reqparse.RequestParser()
    parser.add_argument('foo', type=int)

    parser_copy = parser.copy()
    parser_copy.add_argument('bar', type=int)

    # parser_copy has both 'foo' and 'bar'

    parser_copy.replace_argument('foo', required=True, location='json')
    # 'foo' is now a required str located in json, not an int as defined
    #  by original parser

    parser_copy.remove_argument('foo')
    # parser_copy no longer has 'foo' argument

Error Handling
--------------

The default way errors are handled by the RequestParser is to abort on the
first error that occurred. This can be beneficial when you have arguments that
might take some time to process. However, often it is nice to have the errors
bundled together and sent back to the client all at once. This behavior can be
specified either at the Flask application level or on the specific
RequestParser instance. To invoke a RequestParser with the bundling errors
option, pass in the argument ``bundle_errors``. For example ::

    from flask_restplus import reqparse

    parser = reqparse.RequestParser(bundle_errors=True)
    parser.add_argument('foo', type=int, required=True)
    parser.add_argument('bar', type=int, required=True)

    # If a request comes in not containing both 'foo' and 'bar', the error that
    # will come back will look something like this.

    {
        "message":  {
            "foo": "foo error message",
            "bar": "bar error message"
        }
    }

    # The default behavior would only return the first error

    parser = RequestParser()
    parser.add_argument('foo', type=int, required=True)
    parser.add_argument('bar', type=int, required=True)

    {
        "message":  {
            "foo": "foo error message"
        }
    }

The application configuration key is "BUNDLE_ERRORS". For example ::

    from flask import Flask

    app = Flask(__name__)
    app.config['BUNDLE_ERRORS'] = True

.. warning ::

    ``BUNDLE_ERRORS`` is a global setting that overrides the ``bundle_errors``
    option in individual :class:`~reqparse.RequestParser` instances.

.. _error-messages:

Error Messages
--------------

Error messages for each field may be customized using the ``help`` parameter
to ``Argument`` (and also ``RequestParser.add_argument``).

If no help parameter is provided, the error message for the field will be
the string representation of the type error itself. If ``help`` is provided,
then the error message will be the value of ``help``.

``help`` may include an interpolation token, ``{error_msg}``, that will be
replaced with the string representation of the type error. This allows the
message to be customized while preserving the original error::

    from flask_restplus import reqparse

    parser = reqparse.RequestParser()
    parser.add_argument(
        'foo',
        choices=('one', 'two'),
        help='Bad choice: {error_msg}'
    )

    # If a request comes in with a value of "three" for `foo`:

    {
        "message":  {
            "foo": "Bad choice: three is not a valid choice",
        }
    }


text:
'''
Created on Mar 7, 2012

@author: vencax
'''
import string

from django.conf import settings

HASH_METHOD = getattr(settings, 'HASH_METHOD', 'MD5')

def createPasswdHash(passwd):
    if HASH_METHOD == 'MD5':
        from hashlib import md5
        return md5(passwd).hexdigest()
    if HASH_METHOD == 'CRYPT':
        import crypt, random

        def getsalt(chars=string.letters + string.digits):
            # generate a random 2-character 'salt'
            return random.choice(chars) + random.choice(chars)
        return crypt.crypt(passwd, getsalt())

def checkPasswd(rawpasswd, pwhash):
    try:
        if HASH_METHOD == 'MD5':
            from hashlib import md5
            return md5(rawpasswd).hexdigest() == pwhash
        if HASH_METHOD == 'CRYPT':
            import crypt
            return crypt.crypt(rawpasswd, pwhash) == pwhash
    except UnicodeEncodeError:
        return False

def checkPasswdValidity(pwd):
    for l in pwd:
        if l not in string.printable:
            return False
    return True


text:
package org.apache.ignite.spark;

import org.apache.ignite.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.spi.discovery.tcp.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
import org.apache.ignite.testframework.junits.common.*;
import org.apache.spark.api.java.*;
import org.apache.spark.api.java.function.*;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.sql.*;

import scala.*;

import java.util.*;

/**
 * Tests for {@link JavaIgniteRDD}.
 */
public class JavaIgniteRDDSelfTest extends GridCommonAbstractTest {
    /** Grid count. */
    private static final int GRID_CNT = 3;

    /** Keys count. */
    private static final int KEYS_CNT = 10000;

    /** Cache name. */
    private static final String PARTITIONED_CACHE_NAME = "partitioned";

    /** Ip finder. */
    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);

    /** Sum function. */
    private static final Function2<Integer, Integer, Integer> SUM_F = new Function2<Integer, Integer, Integer>() {
        public Integer call(Integer x, Integer y) {
            return x + y;
        }
    };

    /** To pair function. */
    private static final PairFunction<Integer, String, String> TO_PAIR_F = new PairFunction<Integer, String, String>() {
        /** {@inheritDoc} */
        @Override public Tuple2<String, String> call(Integer i) {
            return new Tuple2<>(String.valueOf(i), "val" + i);
        }
    };

    /** (String, Integer); pair to Integer value function. */
    private static final Function<Tuple2<String, Integer>, Integer> STR_INT_PAIR_TO_INT_F = new PairToValueFunction<>();

    /** (String, Entity) pair to Entity value function. */
    private static final Function<Tuple2<String, Entity>, Entity> STR_ENTITY_PAIR_TO_ENTITY_F =
        new PairToValueFunction<>();

    /** Integer to entity function. */
    private static final PairFunction<Integer, String, Entity> INT_TO_ENTITY_F =
        new PairFunction<Integer, String, Entity>() {
            @Override public Tuple2<String, Entity> call(Integer i) throws Exception {
                return new Tuple2<>(String.valueOf(i), new Entity(i, "name" + i, i * 100));
            }
        };

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        Ignition.ignite("grid-0").cache(PARTITIONED_CACHE_NAME).removeAll();
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        Ignition.stop("client", false);
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        for (int i = 0; i < GRID_CNT; i++)
            Ignition.start(getConfiguration("grid-" + i, false));
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        for (int i = 0; i < GRID_CNT; i++)
            Ignition.stop("grid-" + i, false);
    }

    /**
     * @throws Exception If failed.
     */
    public void testStoreDataToIgnite() throws Exception {
        JavaSparkContext sc = new JavaSparkContext("local[*]", "test");

        try {
            JavaIgniteContext<String, String> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());

            ic.fromCache(PARTITIONED_CACHE_NAME)
                .savePairs(sc.parallelize(F.range(0, KEYS_CNT), 2).mapToPair(TO_PAIR_F));

            Ignite ignite = Ignition.ignite("grid-0");

            IgniteCache<String, String> cache = ignite.cache(PARTITIONED_CACHE_NAME);

            for (int i = 0; i < KEYS_CNT; i++) {
                String val = cache.get(String.valueOf(i));

                assertNotNull("Value was not put to cache for key: " + i, val);
                assertEquals("Invalid value stored for key: " + i, "val" + i, val);
            }
        }
        finally {
            sc.stop();
        }
    }

    /**
     * @throws Exception If failed.
     */
    public void testReadDataFromIgnite() throws Exception {
        JavaSparkContext sc = new JavaSparkContext("local[*]", "test");

        try {
            JavaIgniteContext<String, Integer> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());

            Ignite ignite = Ignition.ignite("grid-0");

            IgniteCache<String, Integer> cache = ignite.cache(PARTITIONED_CACHE_NAME);

            for (int i = 0; i < KEYS_CNT; i++)
                cache.put(String.valueOf(i), i);

            JavaRDD<Integer> values = ic.fromCache(PARTITIONED_CACHE_NAME).map(STR_INT_PAIR_TO_INT_F);

            int sum = values.fold(0, SUM_F);

            int expSum = (KEYS_CNT * KEYS_CNT + KEYS_CNT) / 2 - KEYS_CNT;

            assertEquals(expSum, sum);
        }
        finally {
            sc.stop();
        }
    }

    /**
     * @throws Exception If failed.
     */
    public void testQueryObjectsFromIgnite() throws Exception {
        JavaSparkContext sc = new JavaSparkContext("local[*]", "test");

        try {
            JavaIgniteContext<String, Entity> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());

            JavaIgniteRDD<String, Entity> cache = ic.fromCache(PARTITIONED_CACHE_NAME);

            cache.savePairs(sc.parallelize(F.range(0, 1001), 2).mapToPair(INT_TO_ENTITY_F));

            List<Entity> res = cache.objectSql("Entity", "name = ? and salary = ?", "name50", 5000)
                .map(STR_ENTITY_PAIR_TO_ENTITY_F).collect();

            assertEquals("Invalid result length", 1, res.size());
            assertEquals("Invalid result", 50, res.get(0).id());
            assertEquals("Invalid result", "name50", res.get(0).name());
            assertEquals("Invalid result", 5000, res.get(0).salary());
            assertEquals("Invalid count", 500, cache.objectSql("Entity", "id > 500").count());
        }
        finally {
            sc.stop();
        }
    }

    /**
     * @throws Exception If failed.
     */
    public void testQueryFieldsFromIgnite() throws Exception {
        JavaSparkContext sc = new JavaSparkContext("local[*]", "test");

        try {
            JavaIgniteContext<String, Entity> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());

            JavaIgniteRDD<String, Entity> cache = ic.fromCache(PARTITIONED_CACHE_NAME);

            cache.savePairs(sc.parallelize(F.range(0, 1001), 2).mapToPair(INT_TO_ENTITY_F));

            DataFrame df =
                cache.sql("select id, name, salary from Entity where name = ? and salary = ?", "name50", 5000);

            df.printSchema();

            Row[] res = df.collect();

            assertEquals("Invalid result length", 1, res.length);
            assertEquals("Invalid result", 50, res[0].get(0));
            assertEquals("Invalid result", "name50", res[0].get(1));
            assertEquals("Invalid result", 5000, res[0].get(2));

            Column exp = new Column("NAME").equalTo("name50").and(new Column("SALARY").equalTo(5000));

            DataFrame df0 = cache.sql("select id, name, salary from Entity").where(exp);

            df.printSchema();

            Row[] res0 = df0.collect();

            assertEquals("Invalid result length", 1, res0.length);
            assertEquals("Invalid result", 50, res0[0].get(0));
            assertEquals("Invalid result", "name50", res0[0].get(1));
            assertEquals("Invalid result", 5000, res0[0].get(2));

            assertEquals("Invalid count", 500, cache.sql("select id from Entity where id > 500").count());
        }
        finally {
            sc.stop();
        }

    }

    /**
     * @param gridName Grid name.
     * @param client Client.
     */
    private static IgniteConfiguration getConfiguration(String gridName, boolean client) throws Exception {
        IgniteConfiguration cfg = new IgniteConfiguration();

        TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();

        discoSpi.setIpFinder(IP_FINDER);

        cfg.setDiscoverySpi(discoSpi);

        cfg.setCacheConfiguration(cacheConfiguration());

        cfg.setClientMode(client);

        cfg.setGridName(gridName);

        return cfg;
    }

    /**
     * Creates cache configuration.
     */
    private static CacheConfiguration<Object, Object> cacheConfiguration() {
        CacheConfiguration<Object, Object> ccfg = new CacheConfiguration<>();

        ccfg.setBackups(1);

        ccfg.setName(PARTITIONED_CACHE_NAME);

        ccfg.setIndexedTypes(String.class, Entity.class);

        return ccfg;
    }

    /**
     * Ignite configiration provider.
     */
    static class IgniteConfigProvider implements IgniteOutClosure<IgniteConfiguration> {
        /** {@inheritDoc} */
        @Override public IgniteConfiguration apply() {
            try {
                return getConfiguration("client", true);
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * @param <K>
     * @param <V>
     */
    static class PairToValueFunction<K, V> implements Function<Tuple2<K, V>, V> {
        /** {@inheritDoc} */
        @Override public V call(Tuple2<K, V> t) throws Exception {
            return t._2();
        }
    }
}


text:
from heat.engine import properties
from heat.engine import constraints
from heat.engine import attributes
from heat.common.i18n import _
from avi.heat.avi_resource import AviResource
from avi.heat.avi_resource import AviNestedResource
from options import *

from options import *
from compression_profile import *
from httpcache import *
from common import *
from ssl import *
from rate import *
from dos import *
from match import *
from dns import *

class DosRateLimitProfile(object):
    # all schemas
    rl_profile_schema = properties.Schema(
        properties.Schema.MAP,
        _("Profile for Connections/Requests rate limiting."),
        schema=RateLimiterProfile.properties_schema,
        required=False,
        update_allowed=True,
    )
    dos_profile_schema = properties.Schema(
        properties.Schema.MAP,
        _("Profile for DoS attack detection."),
        schema=DosThresholdProfile.properties_schema,
        required=False,
        update_allowed=True,
    )

    # properties list
    PROPERTIES = (
        'rl_profile',
        'dos_profile',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'rl_profile': rl_profile_schema,
        'dos_profile': dos_profile_schema,
    }

    # for supporting get_avi_uuid_by_name functionality
    field_references = {
        'rl_profile': getattr(RateLimiterProfile, 'field_references', {}),
        'dos_profile': getattr(DosThresholdProfile, 'field_references', {}),
    }

class DnsServiceApplicationProfile(object):
    # all schemas
    num_dns_ip_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Specifies the number of IP addresses returned by the DNS Service. Enter 0 to return all IP addresses"),
        required=False,
        update_allowed=True,
    )
    ttl_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Specifies the TTL value (in seconds) for records served by DNS Service"),
        required=False,
        update_allowed=True,
    )
    error_response_schema = properties.Schema(
        properties.Schema.STRING,
        _("Error response to the client when the DNS service encounters an error processing the client query"),
        required=False,
        update_allowed=True,
        constraints=[
            constraints.AllowedValues(['DNS_ERROR_RESPONSE_ERROR', 'DNS_ERROR_RESPONSE_NONE']),
        ],
    )
    domain_names_item_schema = properties.Schema(
        properties.Schema.STRING,
        _(""),
        required=True,
        update_allowed=False,
    )
    domain_names_schema = properties.Schema(
        properties.Schema.LIST,
        _("Subdomain names serviced by this Virtual Service. These are configured as Ends-With semantics"),
        schema=domain_names_item_schema,
        required=False,
        update_allowed=True,
    )
    edns_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Enable DNS service to be aware of EDNS (Extension mechanism for DNS)"),
        required=False,
        update_allowed=True,
    )

    # properties list
    PROPERTIES = (
        'num_dns_ip',
        'ttl',
        'error_response',
        'domain_names',
        'edns',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'num_dns_ip': num_dns_ip_schema,
        'ttl': ttl_schema,
        'error_response': error_response_schema,
        'domain_names': domain_names_schema,
        'edns': edns_schema,
    }

class TCPApplicationProfile(object):
    # all schemas
    proxy_protocol_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Enable/Disable the usage of proxy protocol to convey client connection information to the back-end servers.  Valid only for L4 application profiles and TCP proxy."),
        required=False,
        update_allowed=True,
    )
    proxy_protocol_version_schema = properties.Schema(
        properties.Schema.STRING,
        _("Version of proxy protocol to be used to convey client connection information to the back-end servers."),
        required=False,
        update_allowed=True,
        constraints=[
            constraints.AllowedValues(['PROXY_PROTOCOL_VERSION_2', 'PROXY_PROTOCOL_VERSION_1']),
        ],
    )

    # properties list
    PROPERTIES = (
        'proxy_protocol_enabled',
        'proxy_protocol_version',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'proxy_protocol_enabled': proxy_protocol_enabled_schema,
        'proxy_protocol_version': proxy_protocol_version_schema,
    }

class SSLClientRequestHeader(object):
    # all schemas
    request_header_schema = properties.Schema(
        properties.Schema.STRING,
        _("If this header exists, reset the connection. If the ssl variable is specified, add a header with this value"),
        required=False,
        update_allowed=True,
    )
    request_header_value_schema = properties.Schema(
        properties.Schema.STRING,
        _("Set the request header with the value as indicated by this SSL variable. Eg. send the whole certificate in PEM format"),
        required=False,
        update_allowed=True,
        constraints=[
            constraints.AllowedValues(['HTTP_POLICY_VAR_SSL_CLIENT_SERIAL', 'HTTP_POLICY_VAR_SSL_CIPHER', 'HTTP_POLICY_VAR_SSL_CLIENT_FINGERPRINT', 'HTTP_POLICY_VAR_USER_NAME', 'HTTP_POLICY_VAR_HTTP_HDR', 'HTTP_POLICY_VAR_VS_PORT', 'HTTP_POLICY_VAR_SSL_CLIENT_SUBJECT', 'HTTP_POLICY_VAR_SSL_SERVER_NAME', 'HTTP_POLICY_VAR_CLIENT_IP', 'HTTP_POLICY_VAR_VS_IP', 'HTTP_POLICY_VAR_SSL_CLIENT_RAW', 'HTTP_POLICY_VAR_SSL_CLIENT_ISSUER', 'HTTP_POLICY_VAR_SSL_PROTOCOL']),
        ],
    )

    # properties list
    PROPERTIES = (
        'request_header',
        'request_header_value',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'request_header': request_header_schema,
        'request_header_value': request_header_value_schema,
    }

class SSLClientCertificateAction(object):
    # all schemas
    headers_item_schema = properties.Schema(
        properties.Schema.MAP,
        _(""),
        schema=SSLClientRequestHeader.properties_schema,
        required=True,
        update_allowed=False,
    )
    headers_schema = properties.Schema(
        properties.Schema.LIST,
        _(""),
        schema=headers_item_schema,
        required=False,
        update_allowed=True,
    )
    close_connection_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _(""),
        required=False,
        update_allowed=True,
    )

    # properties list
    PROPERTIES = (
        'headers',
        'close_connection',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'headers': headers_schema,
        'close_connection': close_connection_schema,
    }

    # for supporting get_avi_uuid_by_name functionality
    field_references = {
        'headers': getattr(SSLClientRequestHeader, 'field_references', {}),
    }

class HTTPApplicationProfile(object):
    # all schemas
    connection_multiplexing_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Allows HTTP requests, not just TCP connections, to be load balanced across servers.  Proxied TCP connections to servers may be reused by multiple clients to improve performance. Not compatible with Preserve Client IP."),
        required=False,
        update_allowed=True,
    )
    xff_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("The client's original IP address is inserted into an HTTP request header sent to the server.  Servers may use this address for logging or other purposes, rather than Avi's source NAT address used in the Avi to server IP connection."),
        required=False,
        update_allowed=True,
    )
    xff_alternate_name_schema = properties.Schema(
        properties.Schema.STRING,
        _("Provide a custom name for the X-Forwarded-For header sent to the servers."),
        required=False,
        update_allowed=True,
    )
    ssl_everywhere_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Enable common settings to increase the level of security for  virtual services running HTTP and HTTPS.  For sites that are  HTTP only, these settings will have no effect."),
        required=False,
        update_allowed=True,
    )
    hsts_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Inserts HTTP Strict-Transport-Security header in the HTTPS response.  HSTS can help mitigate man-in-the-middle attacks by telling browsers that support HSTS that they should only access this site via HTTPS."),
        required=False,
        update_allowed=True,
    )
    hsts_max_age_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Number of days for which the client should regard this virtual service as a known HSTS host."),
        required=False,
        update_allowed=True,
    )
    secure_cookie_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Mark server cookies with the 'Secure' attribute.  Client browsers will not send a cookie marked as secure over an unencrypted connection.  If Avi is terminating SSL from clients and passing it as HTTP to the server, the server may return cookies without the secure flag set."),
        required=False,
        update_allowed=True,
    )
    httponly_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Mark HTTP cookies as HTTPonly.  This helps mitigate cross site scripting attacks as browsers will not allow these cookies to be read by third parties, such as javascript."),
        required=False,
        update_allowed=True,
    )
    http_to_https_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Client requests received via HTTP will be redirected to HTTPS."),
        required=False,
        update_allowed=True,
    )
    server_side_redirect_to_https_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("When terminating client SSL sessions at Avi, servers may incorrectly send redirect to clients as HTTP.  This option will rewrite the server's redirect responses for this virtual service from HTTP to HTTPS."),
        required=False,
        update_allowed=True,
    )
    x_forwarded_proto_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Insert an X-Forwarded-Proto header in the request sent to the server.  When the client connects via SSL, Avi terminates the SSL, and then forwards the requests to the servers via HTTP, so the servers can determine the original protocol via this header.  In this example, the value will be 'https'."),
        required=False,
        update_allowed=True,
    )
    compression_profile_schema = properties.Schema(
        properties.Schema.MAP,
        _("HTTP Compression settings to use with this HTTP Profile."),
        schema=CompressionProfile.properties_schema,
        required=False,
        update_allowed=True,
    )
    spdy_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Enable SPDY proxy for traffic from clients to the virtual service.  SPDY requires SSL from the clients to Avi.  Avi ADC will proxy the SPDY protocol, and forward requests to servers as HTTP 1.1. "),
        required=False,
        update_allowed=True,
    )
    spdy_fwd_proxy_mode_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Enable fwd proxy mode with SPDY. This makes the Proxy combine the :host and :uri spdy headers to create a fwd-proxy style request URI"),
        required=False,
        update_allowed=True,
    )
    post_accept_timeout_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("The max allowed length of time between a client establishing a TCP connection until Avi receives the first byte of the client's HTTP request."),
        required=False,
        update_allowed=True,
    )
    client_header_timeout_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("The maximum length of time allowed for a client to transmit an entire request header. This helps mitigate various forms of SlowLoris attacks."),
        required=False,
        update_allowed=True,
    )
    client_body_timeout_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("The maximum length of time allowed between consecutive read operations for a client request body. The value '0' specifies no timeout. This setting generally impacts the length of time allowed for a client to send a POST."),
        required=False,
        update_allowed=True,
    )
    keepalive_timeout_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("The max idle time allowed between HTTP requests over a Keep-alive connection."),
        required=False,
        update_allowed=True,
    )
    client_max_header_size_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum size in Kbytes of a single HTTP header in the client request."),
        required=False,
        update_allowed=True,
    )
    client_max_request_size_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum size in Kbytes of all the client HTTP request headers."),
        required=False,
        update_allowed=True,
    )
    client_max_body_size_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum size for the client request body.  This limits the size of the client data that can be uploaded/posted as part of a single HTTP Request.  Default 0 => Unlimited."),
        required=False,
        update_allowed=True,
    )
    cache_config_schema = properties.Schema(
        properties.Schema.MAP,
        _("HTTP Caching config to use with this HTTP Profile."),
        schema=HttpCacheConfig.properties_schema,
        required=False,
        update_allowed=True,
    )
    max_rps_unknown_uri_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum unknown URIs per second."),
        required=False,
        update_allowed=True,
    )
    max_rps_cip_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum requests per second per client IP."),
        required=False,
        update_allowed=True,
    )
    max_rps_uri_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum requests per second per URI."),
        required=False,
        update_allowed=True,
    )
    max_rps_cip_uri_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum requests per second per client IP and URI."),
        required=False,
        update_allowed=True,
    )
    ssl_client_certificate_action_schema = properties.Schema(
        properties.Schema.MAP,
        _("Set of match/action rules that govern what happens when the client certificate request is enabled"),
        schema=SSLClientCertificateAction.properties_schema,
        required=False,
        update_allowed=True,
    )
    ssl_client_certificate_mode_schema = properties.Schema(
        properties.Schema.STRING,
        _("Specifies whether the client side verification is set to none, request or require."),
        required=False,
        update_allowed=True,
        constraints=[
            constraints.AllowedValues(['SSL_CLIENT_CERTIFICATE_REQUEST', 'SSL_CLIENT_CERTIFICATE_REQUIRE', 'SSL_CLIENT_CERTIFICATE_NONE']),
        ],
    )
    pki_profile_uuid_schema = properties.Schema(
        properties.Schema.STRING,
        _("Select the PKI profile to be associated with the Virtual Service. This profile defines the Certificate Authority and Revocation List. You can either provide UUID or provide a name with the prefix 'get_avi_uuid_for_name:', e.g., 'get_avi_uuid_for_name:my_obj_name'."),
        required=False,
        update_allowed=True,
    )
    websockets_enabled_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Enable Websockets proxy for traffic from clients to the virtual service. Connections to this VS start in HTTP mode. If the client requests an Upgrade to Websockets, and the server responds back with success, then the connection is upgraded to WebSockets mode. "),
        required=False,
        update_allowed=True,
    )
    max_rps_unknown_cip_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum unknown client IPs per second."),
        required=False,
        update_allowed=True,
    )
    max_bad_rps_cip_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum bad requests per second per client IP."),
        required=False,
        update_allowed=True,
    )
    max_bad_rps_uri_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum bad requests per second per URI."),
        required=False,
        update_allowed=True,
    )
    max_bad_rps_cip_uri_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum bad requests per second per client IP and URI."),
        required=False,
        update_allowed=True,
    )
    keepalive_header_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Send HTTP 'Keep-Alive' header to the client. By default, the timeout specified in the 'Keep-Alive Timeout' field will be used unless the 'Use App Keepalive Timeout' flag is set, in which case the timeout sent by the application will be honored."),
        required=False,
        update_allowed=True,
    )
    use_app_keepalive_timeout_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Use 'Keep-Alive' header timeout sent by application instead of sending the HTTP Keep-Alive Timeout."),
        required=False,
        update_allowed=True,
    )

    # properties list
    PROPERTIES = (
        'connection_multiplexing_enabled',
        'xff_enabled',
        'xff_alternate_name',
        'ssl_everywhere_enabled',
        'hsts_enabled',
        'hsts_max_age',
        'secure_cookie_enabled',
        'httponly_enabled',
        'http_to_https',
        'server_side_redirect_to_https',
        'x_forwarded_proto_enabled',
        'compression_profile',
        'spdy_enabled',
        'spdy_fwd_proxy_mode',
        'post_accept_timeout',
        'client_header_timeout',
        'client_body_timeout',
        'keepalive_timeout',
        'client_max_header_size',
        'client_max_request_size',
        'client_max_body_size',
        'cache_config',
        'max_rps_unknown_uri',
        'max_rps_cip',
        'max_rps_uri',
        'max_rps_cip_uri',
        'ssl_client_certificate_action',
        'ssl_client_certificate_mode',
        'pki_profile_uuid',
        'websockets_enabled',
        'max_rps_unknown_cip',
        'max_bad_rps_cip',
        'max_bad_rps_uri',
        'max_bad_rps_cip_uri',
        'keepalive_header',
        'use_app_keepalive_timeout',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'connection_multiplexing_enabled': connection_multiplexing_enabled_schema,
        'xff_enabled': xff_enabled_schema,
        'xff_alternate_name': xff_alternate_name_schema,
        'ssl_everywhere_enabled': ssl_everywhere_enabled_schema,
        'hsts_enabled': hsts_enabled_schema,
        'hsts_max_age': hsts_max_age_schema,
        'secure_cookie_enabled': secure_cookie_enabled_schema,
        'httponly_enabled': httponly_enabled_schema,
        'http_to_https': http_to_https_schema,
        'server_side_redirect_to_https': server_side_redirect_to_https_schema,
        'x_forwarded_proto_enabled': x_forwarded_proto_enabled_schema,
        'compression_profile': compression_profile_schema,
        'spdy_enabled': spdy_enabled_schema,
        'spdy_fwd_proxy_mode': spdy_fwd_proxy_mode_schema,
        'post_accept_timeout': post_accept_timeout_schema,
        'client_header_timeout': client_header_timeout_schema,
        'client_body_timeout': client_body_timeout_schema,
        'keepalive_timeout': keepalive_timeout_schema,
        'client_max_header_size': client_max_header_size_schema,
        'client_max_request_size': client_max_request_size_schema,
        'client_max_body_size': client_max_body_size_schema,
        'cache_config': cache_config_schema,
        'max_rps_unknown_uri': max_rps_unknown_uri_schema,
        'max_rps_cip': max_rps_cip_schema,
        'max_rps_uri': max_rps_uri_schema,
        'max_rps_cip_uri': max_rps_cip_uri_schema,
        'ssl_client_certificate_action': ssl_client_certificate_action_schema,
        'ssl_client_certificate_mode': ssl_client_certificate_mode_schema,
        'pki_profile_uuid': pki_profile_uuid_schema,
        'websockets_enabled': websockets_enabled_schema,
        'max_rps_unknown_cip': max_rps_unknown_cip_schema,
        'max_bad_rps_cip': max_bad_rps_cip_schema,
        'max_bad_rps_uri': max_bad_rps_uri_schema,
        'max_bad_rps_cip_uri': max_bad_rps_cip_uri_schema,
        'keepalive_header': keepalive_header_schema,
        'use_app_keepalive_timeout': use_app_keepalive_timeout_schema,
    }

    # for supporting get_avi_uuid_by_name functionality
    field_references = {
        'pki_profile_uuid': 'pkiprofile',
        'compression_profile': getattr(CompressionProfile, 'field_references', {}),
        'ssl_client_certificate_action': getattr(SSLClientCertificateAction, 'field_references', {}),
        'cache_config': getattr(HttpCacheConfig, 'field_references', {}),
    }

class ApplicationProfile(AviResource):
    resource_name = "applicationprofile"
    # all schemas
    name_schema = properties.Schema(
        properties.Schema.STRING,
        _("The name of the application profile."),
        required=True,
        update_allowed=True,
    )
    type_schema = properties.Schema(
        properties.Schema.STRING,
        _("Specifies which application layer proxy is enabled for the virtual service."),
        required=True,
        update_allowed=True,
        constraints=[
            constraints.AllowedValues(['APPLICATION_PROFILE_TYPE_SSL', 'APPLICATION_PROFILE_TYPE_DNS', 'APPLICATION_PROFILE_TYPE_SYSLOG', 'APPLICATION_PROFILE_TYPE_HTTP', 'APPLICATION_PROFILE_TYPE_L4']),
        ],
    )
    http_profile_schema = properties.Schema(
        properties.Schema.MAP,
        _("Specifies the HTTP application proxy profile parameters."),
        schema=HTTPApplicationProfile.properties_schema,
        required=False,
        update_allowed=True,
    )
    dos_rl_profile_schema = properties.Schema(
        properties.Schema.MAP,
        _("Specifies various security related controls for virtual service."),
        schema=DosRateLimitProfile.properties_schema,
        required=False,
        update_allowed=True,
    )
    tcp_app_profile_schema = properties.Schema(
        properties.Schema.MAP,
        _("Specifies the TCP application proxy profile parameters."),
        schema=TCPApplicationProfile.properties_schema,
        required=False,
        update_allowed=True,
    )
    dns_service_profile_schema = properties.Schema(
        properties.Schema.MAP,
        _("Specifies various DNS service related controls for virtual service."),
        schema=DnsServiceApplicationProfile.properties_schema,
        required=False,
        update_allowed=True,
    )
    preserve_client_ip_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Specifies if client IP needs to be preserved for backend connection. Not compatible with Connection Multiplexing."),
        required=False,
        update_allowed=True,
    )
    description_schema = properties.Schema(
        properties.Schema.STRING,
        _(""),
        required=False,
        update_allowed=True,
    )

    # properties list
    PROPERTIES = (
        'name',
        'type',
        'http_profile',
        'dos_rl_profile',
        'tcp_app_profile',
        'dns_service_profile',
        'preserve_client_ip',
        'description',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'name': name_schema,
        'type': type_schema,
        'http_profile': http_profile_schema,
        'dos_rl_profile': dos_rl_profile_schema,
        'tcp_app_profile': tcp_app_profile_schema,
        'dns_service_profile': dns_service_profile_schema,
        'preserve_client_ip': preserve_client_ip_schema,
        'description': description_schema,
    }

    # for supporting get_avi_uuid_by_name functionality
    field_references = {
        'dns_service_profile': getattr(DnsServiceApplicationProfile, 'field_references', {}),
        'tcp_app_profile': getattr(TCPApplicationProfile, 'field_references', {}),
        'http_profile': getattr(HTTPApplicationProfile, 'field_references', {}),
        'dos_rl_profile': getattr(DosRateLimitProfile, 'field_references', {}),
    }

def resource_mapping():
    return {
        'Avi::LBaaS::ApplicationProfile': ApplicationProfile,
    }


text:
type: session
title: "Gabbi - Declarative HTTP Testing"
slug: "gabbi-declarative-http-testing"
url: "talks/gabbi-declarative-http-testing/index.html"
body_class_hack: talks
---

### [Chris](https://tank.peermore.com/tanks/cdent) [Dent](https://twitter.com/anticdent)

[Gabbi](http://cdent.github.io/gabbi/) is a Python-based tool for
testing web APIs using an easy to write and read YAML format that allows
tests to focus on HTTP requests and responses, not Python. It was
developed to make it easier to learn and contribute to OpenStack APIs
but can be used in any environment, even for testing services that don't
use Python (if that's your thing).

The presentation will give an overview of why Gabbi exists and a live
demonstration of its features. Listeners will hopefully go home with a
new and useful tool and an expanded perspective on ways to make tests
for web APIs.

For a taste of what the presentation will provide see
[these slides](http://redhat.slides.com/chdent/gabbi?token=EE3TApJU)
which were used to give a similar talk at the OpenStack Liberty Summit.
This talk will be an updated version including new features and learnings
from use in the field.


text:
//
//  LYJRecomendUserModel.h
//  SolveDemo
//
//  Created by hyp on 16/4/22.
//  Copyright © 2016年 hyp. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface LYJRecomendUserModel : NSObject

/** 头像 */
@property (nonatomic, copy) NSString *header;
/** 粉丝数(有多少人关注这个用户) */
@property (nonatomic, assign) NSInteger fans_count;
/** 昵称 */
@property (nonatomic, copy) NSString *screen_name;

@end


text:
;(function(){

  'use strict';

    module.exports = controllerPrompts;

    function controllerPrompts () {

      var questions = [
        {
          name: 'appName',
          message: 'What would you like to call your application?',
          default: 'ASD'
        }, {
          name: 'appDescription',
          message: 'How would you describe your application?',
          default: ''
        }, {
          name: 'appKeywords',
          message: 'How would you describe your application in comma seperated key words?',
          default: ''
        },{
          name: 'appAuthor',
          message: 'What is your company/author name?'
        },{
          type: 'list',
          name: 'script',
          message: 'What script would you like to use?',
          choices: [{
            value: 'js',
            name: 'Javascript',
            default: true
          }]

        },{
          type: 'list',
          name: 'httpType',
          message: 'How would you like to handle your http requests?',
          choices: [{
            value: 'http',
            name: 'angular $http',
            default: false
          }
          ,{
            value: 'restangular',
            name: 'Restangular',
            default: false
          }
          ]
        },
        // {
        //   type: 'confirm',
        //   name: 'auth',
        //   message: 'Would you like authentication built in?',
        //   default: true
        // },
        {
          type: 'checkbox',
          name: 'modules',
          message: 'Which AngularJS modules would you like to include?',
          choices: [{
            value: 'angularCookies',
            name: 'ngCookies',
            checked: true
          }, {
            value: 'angularAnimate',
            name: 'ngAnimate',
            checked: true
          }, {
            value: 'angularTouch',
            name: 'ngTouch',
            checked: true
          }, {
            value: 'angularSanitize',
            name: 'ngSanitize',
            checked: true
          }]
        }]
      return questions;

    }

}).call(this);


text: package org.encog.app.analyst.csv.sort;


text:
var secret = "8c25ab98336640a94f332b31877a1d5f8ffb7544"; // TODO move to config!!!

var finalhandler = require('finalhandler')
var serveStatic = require('serve-static')
var http = require('http');

var serve = serveStatic('/Users/nicholaw/git/run-calendar/dist/', {'index': ['interactive.html']});

http.createServer(function (req, res) {
  var url = require('url').parse(req.url, true);

  if (url.pathname === "/token_exchange")
{
  var q = url.query;
  var request = require('request');

  request.post("https://www.strava.com/oauth/token", {
    form: {
      client_id: 2746,
      client_secret: secret,
      code: q.code
    }
  }, function (error, response, body) {
      res.writeHead(200, {'Content-Type': 'text/html'});

      var data = JSON.parse(body);

      var response = ""

      res.end(response);

    });
  }
  else {
    var done = finalhandler(req, res);
    serve(req, res, done);
  }
}).listen(8123, '127.0.0.1');


text:
package com.jaamsim.render;

import java.nio.IntBuffer;

/**
 * The OffscreenTarget is an optional resource handle for offscreen rendering. Using an offscreen target prevents the
 * renderer from needing to allocate render buffer information
 * @author matt.chudleigh
 *
 */
public class OffscreenTarget {

	private int _width;
	private int _height;

	private boolean _loaded;

	// openGL handles to the frame buffer object, colour texture and depth render buffer respectively
	private int _drawFBO;
	private int _drawTex;
	private int _depthHandle;

	// A frame buffer and texture that are allocated single sample to blit to when done
	private int _blitFBO;
	private int _blitTex;

	private IntBuffer _pixelBuffer;

	/**
	 * Builds an OffScreenTarget of the specified size, the resources are not allocated right away, but will be before
	 * this can be used. As such it is safe to use this target immediately after being created.
	 *
	 * @param width
	 * @param height
	 */
	public OffscreenTarget(int width, int height) {
		assert(width > 0);
		assert(height > 0);

		_width = width;
		_height = height;
		_loaded = false;
	}

	public void load(int drawFBO, int drawTex, int depthBuff, int blitFBO, int blitTex) {
		assert !_loaded;

		_loaded = true;
		_drawFBO = drawFBO;
		_drawTex = drawTex;
		_depthHandle = depthBuff;
		_blitFBO = blitFBO;
		_blitTex = blitTex;
		_pixelBuffer = IntBuffer.allocate(_width * _height);

	}

	public int getDrawFBO() {
		assert _loaded;
		return _drawFBO;
	}

	public int getDrawTex() {
		assert _loaded;
		return _drawTex;
	}

	public int getDepthBuffer() {
		assert _loaded;
		return _depthHandle;
	}

	public int getBlitFBO() {
		assert _loaded;
		return _blitFBO;
	}

	public int getBlitTex() {
		assert _loaded;
		return _blitTex;
	}

	public boolean isLoaded() {
		return _loaded;
	}

	public void free() {
		_loaded = false;
		_pixelBuffer = null;
	}

	public int getWidth() {
		return _width;
	}

	public int getHeight() {
		return _height;
	}

	public IntBuffer getPixelBuffer() {
		return _pixelBuffer;
	}
}


text:
import {Annotation, AnnotationView} from "./annotation"
import {LegendItem} from "./legend_item"
import {GlyphRendererView} from "../renderers/glyph_renderer"
import {Color} from "core/types"
import {Line, Fill, Text} from "core/visuals"
import {FontStyle, TextAlign, TextBaseline, LineJoin, LineCap} from "core/enums"
import {Orientation, LegendLocation, LegendClickPolicy} from "core/enums"
import * as p from "core/properties"
import {get_text_height} from "core/util/text"
import {BBox} from "core/util/bbox"
import {max, all} from "core/util/array"
import {values} from "core/util/object"
import {isString, isArray} from "core/util/types"
import {Context2d} from "core/util/canvas"

export type LegendBBox = {x: number, y: number, width: number, height: number}

export class LegendView extends AnnotationView {
  model: Legend
  visuals: Legend.Visuals

  protected max_label_height: number
  protected text_widths: {[key: string]: number}

  get cursor(): string | null {
    return this.model.click_policy == "none" ? null : "pointer"
  }

  get legend_padding(): number {
    return this.visuals.border_line.line_color.value() != null ? this.model.padding : 0
  }

  connect_signals(): void {
    super.connect_signals()
    this.connect(this.model.properties.visible.change, () => this.plot_view.request_render())
  }

  compute_legend_bbox(): LegendBBox {
    const legend_names = this.model.get_legend_names()

    const {glyph_height, glyph_width} = this.model
    const {label_height, label_width} = this.model

    this.max_label_height = max(
      [get_text_height(this.visuals.label_text.font_value()).height, label_height, glyph_height],
    )

    // this is to measure text properties
    const { ctx } = this.plot_view.canvas_view
    ctx.save()
    this.visuals.label_text.set_value(ctx)
    this.text_widths = {}
    for (const name of legend_names) {
      this.text_widths[name] = max([ctx.measureText(name).width, label_width])
    }
    ctx.restore()

    const max_label_width = Math.max(max(values(this.text_widths)), 0)

    const legend_margin = this.model.margin
    const {legend_padding} = this
    const legend_spacing = this.model.spacing
    const {label_standoff} =  this.model

    let legend_height: number, legend_width: number
    if (this.model.orientation == "vertical") {
      legend_height = legend_names.length*this.max_label_height + Math.max(legend_names.length - 1, 0)*legend_spacing + 2*legend_padding
      legend_width = max_label_width + glyph_width + label_standoff + 2*legend_padding
    } else {
      legend_width = 2*legend_padding + Math.max(legend_names.length - 1, 0)*legend_spacing
      for (const name in this.text_widths) {
        const width = this.text_widths[name]
        legend_width += max([width, label_width]) + glyph_width + label_standoff
      }
      legend_height = this.max_label_height + 2*legend_padding
    }

    const panel = this.model.panel != null ? this.model.panel : this.plot_view.frame
    const [hr, vr] = panel.bbox.ranges

    const {location} = this.model
    let sx: number, sy: number
    if (isString(location)) {
      switch (location) {
        case 'top_left':
          sx = hr.start + legend_margin
          sy = vr.start + legend_margin
          break
        case 'top_center':
          sx = (hr.end + hr.start)/2 - legend_width/2
          sy = vr.start + legend_margin
          break
        case 'top_right':
          sx = hr.end - legend_margin - legend_width
          sy = vr.start + legend_margin
          break
        case 'bottom_right':
          sx = hr.end - legend_margin - legend_width
          sy = vr.end - legend_margin - legend_height
          break
        case 'bottom_center':
          sx = (hr.end + hr.start)/2 - legend_width/2
          sy = vr.end - legend_margin - legend_height
          break
        case 'bottom_left':
          sx = hr.start + legend_margin
          sy = vr.end - legend_margin - legend_height
          break
        case 'center_left':
          sx = hr.start + legend_margin
          sy = (vr.end + vr.start)/2 - legend_height/2
          break
        case 'center':
          sx = (hr.end + hr.start)/2 - legend_width/2
          sy = (vr.end + vr.start)/2 - legend_height/2
          break
        case 'center_right':
          sx = hr.end - legend_margin - legend_width
          sy = (vr.end + vr.start)/2 - legend_height/2
          break
        default:
          throw new Error("unreachable code")
      }
    } else if (isArray(location) && location.length == 2) {
      const [vx, vy] = location
      sx = panel.xview.compute(vx)
      sy = panel.yview.compute(vy) - legend_height
    } else
      throw new Error("unreachable code")

    return {x: sx, y: sy, width: legend_width, height: legend_height}
  }

  bbox(): BBox {
    const {x, y, width, height} = this.compute_legend_bbox()
    return new BBox({x, y, width, height})
  }

  on_hit(sx: number, sy: number): boolean {
    let yoffset
    const { glyph_width } = this.model
    const { legend_padding } = this
    const legend_spacing = this.model.spacing
    const { label_standoff } = this.model

    let xoffset = (yoffset = legend_padding)

    const legend_bbox = this.compute_legend_bbox()
    const vertical = this.model.orientation == "vertical"

    for (const item of this.model.items) {
      const labels = item.get_labels_list_from_label_prop()

      for (const label of labels) {
        const x1 = legend_bbox.x + xoffset
        const y1 = legend_bbox.y + yoffset

        let w: number, h: number
        if (vertical)
          [w, h] = [legend_bbox.width - 2*legend_padding, this.max_label_height]
        else
          [w, h] = [this.text_widths[label] + glyph_width + label_standoff, this.max_label_height]

        const bbox = new BBox({x: x1, y: y1, width: w, height: h})

        if (bbox.contains(sx, sy)) {
          switch (this.model.click_policy) {
            case "hide": {
              for (const r of item.renderers)
                r.visible = !r.visible
              break
            }
            case "mute": {
              for (const r of item.renderers)
                r.muted = !r.muted
              break
            }
          }
          return true
        }

        if (vertical)
          yoffset += this.max_label_height + legend_spacing
        else
          xoffset += this.text_widths[label] + glyph_width + label_standoff + legend_spacing
      }
    }

    return false
  }

  render(): void {
    if (!this.model.visible)
      return

    if (this.model.items.length == 0)
      return

    const {ctx} = this.plot_view.canvas_view
    const bbox = this.compute_legend_bbox()

    ctx.save()
    this._draw_legend_box(ctx, bbox)
    this._draw_legend_items(ctx, bbox)
    ctx.restore()
  }

  protected _draw_legend_box(ctx: Context2d, bbox: LegendBBox): void {
    ctx.beginPath()
    ctx.rect(bbox.x, bbox.y, bbox.width, bbox.height)
    this.visuals.background_fill.set_value(ctx)
    ctx.fill()
    if (this.visuals.border_line.doit) {
      this.visuals.border_line.set_value(ctx)
      ctx.stroke()
    }
  }

  protected _draw_legend_items(ctx: Context2d, bbox: LegendBBox): void {
    const {glyph_width, glyph_height} = this.model
    const {legend_padding} = this
    const legend_spacing = this.model.spacing
    const {label_standoff} = this.model
    let xoffset = legend_padding
    let yoffset = legend_padding
    const vertical = this.model.orientation == "vertical"

    for (const item of this.model.items) {
      const labels = item.get_labels_list_from_label_prop()
      const field = item.get_field_from_label_prop()

      if (labels.length == 0)
        continue

      const active = (() => { switch (this.model.click_policy) {
        case "none": return true
        case "hide": return all(item.renderers, r => r.visible)
        case "mute": return all(item.renderers, r => !r.muted)
      } })()

      for (const label of labels) {
        const x1 = bbox.x + xoffset
        const y1 = bbox.y + yoffset
        const x2 = x1 + glyph_width
        const y2 = y1 + glyph_height

        if (vertical)
          yoffset += this.max_label_height + legend_spacing
        else
          xoffset += this.text_widths[label] + glyph_width + label_standoff + legend_spacing

        this.visuals.label_text.set_value(ctx)
        ctx.fillText(label, x2 + label_standoff, y1 + this.max_label_height/2.0)
        for (const r of item.renderers) {
          const view = this.plot_view.renderer_views[r.id] as GlyphRendererView
          view.draw_legend(ctx, x1, x2, y1, y2, field, label)
        }

        if (!active) {
          let w: number, h: number
          if (vertical)
            [w, h] = [bbox.width - 2*legend_padding, this.max_label_height]
          else
            [w, h] = [this.text_widths[label] + glyph_width + label_standoff, this.max_label_height]

          ctx.beginPath()
          ctx.rect(x1, y1, w, h)
          this.visuals.inactive_fill.set_value(ctx)
          ctx.fill()
        }
      }
    }
  }

  protected _get_size(): number {
    const bbox = this.compute_legend_bbox()
    switch (this.model.panel!.side) {
      case "above":
      case "below":
        return bbox.height + 2*this.model.margin
      case "left":
      case "right":
        return bbox.width + 2*this.model.margin
    }
  }
}

export namespace Legend {
  // text:label_
  export interface LabelText {
    label_text_font: string
    label_text_font_size: string
    label_text_font_style: FontStyle
    label_text_color: Color
    label_text_alpha: number
    label_text_align: TextAlign
    label_text_baseline: TextBaseline
    label_text_line_height: number
  }

  // fill:inactive_
  export interface InactiveFill {
    inactive_fill_color: Color
    inactive_fill_alpha: number
  }

  // line:border_
  export interface BorderLine {
    border_line_color: Color
    border_line_width: number
    border_line_alpha: number
    border_line_join: LineJoin
    border_line_cap: LineCap
    border_line_dash: number[]
    border_line_dash_offset: number
  }

  // fill:background_
  export interface BackgroundFill {
    background_fill_color: Color
    background_fill_alpha: number
  }

  export interface Mixins extends LabelText, InactiveFill, BorderLine, BackgroundFill {}

  export interface Attrs extends Annotation.Attrs, Mixins {
    orientation: Orientation
    location: LegendLocation | [number, number]
    label_standoff: number
    glyph_height: number
    glyph_width: number
    label_height: number
    label_width: number
    margin: number
    padding: number
    spacing: number
    items: LegendItem[]
    click_policy: LegendClickPolicy
  }

  export interface Props extends Annotation.Props {}

  export type Visuals = Annotation.Visuals & {
    label_text: Text
    inactive_fill: Fill
    border_line: Line
    background_fill: Fill
  }
}

export interface Legend extends Legend.Attrs {}

export class Legend extends Annotation {

  properties: Legend.Props

  constructor(attrs?: Partial<Legend.Attrs>) {
    super(attrs)
  }

  static initClass(): void {
    this.prototype.type = 'Legend'
    this.prototype.default_view = LegendView

    this.mixins(['text:label_', 'fill:inactive_', 'line:border_', 'fill:background_'])

    this.define({
      orientation:      [ p.Orientation,    'vertical'  ],
      location:         [ p.Any,            'top_right' ], // TODO (bev)
      label_standoff:   [ p.Number,         5           ],
      glyph_height:     [ p.Number,         20          ],
      glyph_width:      [ p.Number,         20          ],
      label_height:     [ p.Number,         20          ],
      label_width:      [ p.Number,         20          ],
      margin:           [ p.Number,         10          ],
      padding:          [ p.Number,         10          ],
      spacing:          [ p.Number,         3           ],
      items:            [ p.Array,          []          ],
      click_policy:     [ p.Any,            "none"      ],
    })

    this.override({
      border_line_color: "#e5e5e5",
      border_line_alpha: 0.5,
      border_line_width: 1,
      background_fill_color: "#ffffff",
      background_fill_alpha: 0.95,
      inactive_fill_color: "white",
      inactive_fill_alpha: 0.7,
      label_text_font_size: "10pt",
      label_text_baseline: "middle",
    })
  }

  get_legend_names(): string[] {
    const legend_names: string[] = []
    for (const item of this.items) {
      const labels = item.get_labels_list_from_label_prop()
      legend_names.push(...labels)
    }
    return legend_names
  }
}
Legend.initClass()


text:
WSGI
====

Web interface which provides sorting of word lists


text:
package data

import (
	"regexp"
	"time"
)

// Tag describes a git tag
type Tag struct {
	Name   string
	Commit string
	Date   time.Time
	URL    string
}

// Tags is a slice with Tag elements
type Tags []Tag

// Len implements the Sort.Interface
func (t *Tags) Len() int {
	return len(*t)
}

// Less implements the Sort.Interface
func (t *Tags) Less(i, j int) bool {
	return (*t)[i].Date.After((*t)[j].Date)
}

// Swap implements the Sort.Interface
func (t *Tags) Swap(i, j int) {
	(*t)[i], (*t)[j] = (*t)[j], (*t)[i]
}

// FilterTags filters the tags based on the regexp and tag names
func FilterTags(ts Tags, regexp *regexp.Regexp) Tags {
	var ret Tags
	for _, t := range ts {
		if regexp.MatchString(t.Name) {
			ret = append(ret, t)
		}
	}
	return ret
}


text:
define(function(require) {
  var $ = require("jquery"),
      CStatView = require('summary/cstatview'),
      Backbone = require('backbone');

  return Backbone.View.extend({

    initialize: function() {
      this.listenTo(this.collection, 'add', this.addOne);
      this.listenTo(this.collection, 'reset', this.onReset);
      $("#facet-togglecheckall").click(this.toggleChecks.bind(this));
    },

    toggleChecks: function() {
      var btn = $("#facet-togglecheckall");
      var bchecked = false;
      if (btn.attr('state') == 'checked') {
        btn.text("check all");
        btn.attr('state', 'unchecked');
        bchecked = false;
      } else {
        btn.text('uncheck all');
        btn.attr('state', 'checked');
        bchecked = true;
      }

      this.$("input.errcol").each(function(idx, el) {
        el.checked = bchecked;
      });
    },

    onReset: function() {
      this.$el.empty();
      this.collection.each(this.addOne.bind(this));
    },

    addOne: function(model) {
      var view = new CStatView({model: model});
      var vel = view.render().el;
      this.$el.append(vel);
    }
  });
});


text:
package org.apache.struts2.views.jsp.ui;

import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.views.jsp.AbstractTagTest;
import org.apache.struts2.views.jsp.DateTag;

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

/**
 * Unit test for {@link org.apache.struts2.components.Date}.
 *
 */
public class DateTagTest extends AbstractTagTest {

    private DateTag tag;

    public void testCustomFormat() throws Exception {
        String format = "yyyy/MM/dd hh:mm:ss";
        Date now = new Date();
        String formatted = new SimpleDateFormat(format).format(now);
        context.put("myDate", now);

        tag.setName("myDate");
        tag.setNice(false);
        tag.setFormat(format);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals(formatted, writer.toString());
    }

    public void testCustomFormatWithTimezone() throws Exception {
        String format = "yyyy/MM/dd hh:mm:ss";
        Date now = Calendar.getInstance(TimeZone.getTimeZone("UTC+1")).getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC+1"));
        String formatted = sdf.format(now);
        context.put("myDate", now);

        tag.setName("myDate");
        tag.setNice(false);
        tag.setFormat(format);
        tag.setTimezone("UTC+1");
        tag.doStartTag();
        tag.doEndTag();
        assertEquals(formatted, writer.toString());
    }

    public void testCustomFormatWithTimezoneAsExpression() throws Exception {
        String format = "yyyy/MM/dd hh:mm:ss";
        Date now = Calendar.getInstance(TimeZone.getTimeZone("UTC+2")).getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC+2"));
        String formatted = sdf.format(now);
        context.put("myDate", now);
        context.put("myTimezone", "UTC+2");

        tag.setName("myDate");
        tag.setNice(false);
        tag.setFormat(format);
        tag.setTimezone("myTimezone");
        tag.doStartTag();
        tag.doEndTag();
        assertEquals(formatted, writer.toString());
    }

    public void testCustomFormatCalendar() throws Exception {
        String format = "yyyy/MM/dd hh:mm:ss";
        Calendar calendar = Calendar.getInstance();
        String formatted = new SimpleDateFormat(format).format(calendar.getTime());
        context.put("myDate", calendar);

        tag.setName("myDate");
        tag.setNice(false);
        tag.setFormat(format);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals(formatted, writer.toString());
    }

    public void testCustomFormatLong() throws Exception {
        String format = "yyyy/MM/dd hh:mm:ss";
        Date date = new Date();
        String formatted = new SimpleDateFormat(format).format(date);
        // long
        context.put("myDate", date.getTime());

        tag.setName("myDate");
        tag.setNice(false);
        tag.setFormat(format);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals(formatted, writer.toString());
    }

    public void testDefaultFormat() throws Exception {
        Date now = new Date();
        String formatted = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM,
                ActionContext.getContext().getLocale()).format(now);

        context.put("myDate", now);
        tag.setName("myDate");
        tag.setNice(false);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals(formatted, writer.toString());
    }

    public void testCustomFormatAndComponent() throws Exception {
        String format = "yyyy/MM/dd hh:mm:ss";
        Date now = new Date();
        String formatted = new SimpleDateFormat(format).format(now);
        context.put("myDate", now);

        tag.setName("myDate");
        tag.setFormat(format);
        tag.setNice(false);

        tag.doStartTag();

        // component test must be done between start and end tag
        org.apache.struts2.components.Date component = (org.apache.struts2.components.Date) tag.getComponent();
        assertEquals("myDate", component.getName());
        assertEquals(format, component.getFormat());
        assertEquals(false, component.isNice());

        tag.doEndTag();

        assertEquals(formatted, writer.toString());
    }

    public void testSetId() throws Exception {
        String format = "yyyy/MM/dd hh:mm:ss";
        Date now = new Date();
        String formatted = new SimpleDateFormat(format).format(now);
        context.put("myDate", now);

        tag.setName("myDate");
        tag.setNice(false);
        tag.setFormat(format);
        tag.setVar("myId");
        tag.doStartTag();
        tag.doEndTag();
        assertEquals(formatted, context.get("myId"));
    }

    public void testFutureNiceHour() throws Exception {
        Date now = new Date();
        Calendar future = Calendar.getInstance();
        future.setTime(now);
        future.add(Calendar.HOUR, 1);
        future.add(Calendar.SECOND, 5); // always add a little slack otherwise we could calculate wrong

        context.put("myDate", future.getTime());
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals("in one hour", writer.toString());
    }

    public void testPastNiceHour() throws Exception {
        Date now = new Date();
        Calendar future = Calendar.getInstance();
        future.setTime(now);
        future.add(Calendar.HOUR, -1);
        future.add(Calendar.SECOND, -5); // always add a little slack otherwise we could calculate wrong

        context.put("myDate", future.getTime());
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals("one hour ago", writer.toString());
    }

    public void testFutureNiceHourMinSec() throws Exception {
        Date now = new Date();
        Calendar future = Calendar.getInstance();
        future.setTime(now);
        future.add(Calendar.HOUR, 2);
        future.add(Calendar.MINUTE, 33);
        future.add(Calendar.SECOND, 5); // always add a little slack otherwise we could calculate wrong

        context.put("myDate", future.getTime());
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals("in 2 hours, 33 minutes", writer.toString());
    }

    public void testPastNiceHourMin() throws Exception {
        Date now = new Date();
        Calendar past = Calendar.getInstance();
        past.setTime(now);
        past.add(Calendar.HOUR, -4);
        past.add(Calendar.MINUTE, -55);
        past.add(Calendar.SECOND, -5); // always add a little slack otherwise we could calculate wrong

        context.put("myDate", past.getTime());
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals("4 hours, 55 minutes ago", writer.toString());
    }

    public void testFutureLessOneMin() throws Exception {
        Date now = new Date();
        Calendar future = Calendar.getInstance();
        future.setTime(now);
        future.add(Calendar.SECOND, 47);
        future.add(Calendar.SECOND, 5); // always add a little slack otherwise we could calculate wrong

        context.put("myDate", future.getTime());
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals("in an instant", writer.toString());
    }

    public void testFutureLessOneHour() throws Exception {
        Date now = new Date();
        Calendar future = Calendar.getInstance();
        future.setTime(now);
        future.add(Calendar.MINUTE, 36);
        future.add(Calendar.SECOND, 5); // always add a little slack otherwise we could calculate wrong

        context.put("myDate", future.getTime());
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals("in 36 minutes", writer.toString());
    }

    public void testFutureLessOneYear() throws Exception {
        Date now = new Date();
        Calendar future = Calendar.getInstance();
        future.setTime(now);
        future.add(Calendar.HOUR, 40 * 24);
        future.add(Calendar.SECOND, 5); // always add a little slack otherwise we could calculate wrong

        context.put("myDate", future.getTime());
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();
        assertEquals("in 40 days", writer.toString());
    }

    public void testFutureTwoYears() throws Exception {
        Date now = new Date();
        Calendar future = Calendar.getInstance();
        future.setTime(now);
        future.add(Calendar.YEAR, 2);
        future.add(Calendar.DATE, 1);
        future.add(Calendar.SECOND, 5); // always add a little slack otherwise we could calculate wrong

        context.put("myDate", future.getTime());
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();

        // hmmm the Date component isn't the best to calculate the excat difference so we'll just check
        // that it starts with in 2 years
        assertTrue(writer.toString().startsWith("in 2 years"));
    }

    public void testNoDateObjectInContext() throws Exception {
        context.put("myDate", "this is not a java.util.Date object");
        tag.setName("myDate");
        tag.setNice(true);
        tag.doStartTag();
        tag.doEndTag();
        //should return a blank
        assertEquals("", writer.toString());
    }

    protected void setUp() throws Exception {
        super.setUp();
        tag = new DateTag();
        tag.setPageContext(pageContext);
    }

    protected void tearDown() throws Exception {
        super.tearDown();
        tag = null;
    }

}


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

namespace Meou.Transport.DotNetty
{
    public class ResponseBytes : BytesHolder
    {
        // 用于映射 <id, request, response> 三元组
        private long id; // request.invokeId
        private byte status;

        public ResponseBytes(long id)
        {
            this.id = id;
        }

        public long Id
        {
            get { return this.id; }
            set { this.id = value; }
        }

        public byte Status
        {
            get { return this.status; }
            set { this.status = value; }
        }
    }
}


text:
// ----------------------------------------------------------------------------
// <copyright file="StubAssemblyGenerator.cs" company="MTCS (Matt Middleton)">
// Copyright (c) Meridian Technology Consulting Services (Matt Middleton).
// All rights reserved.
// </copyright>
// ----------------------------------------------------------------------------

namespace Meridian.InterSproc
{
    using System;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using System.Data;
    using System.Data.Linq;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using Meridian.InterSproc.Definitions;
    using Meridian.InterSproc.Model;
    using Microsoft.CSharp;

    /// <summary>
    /// Implements <see cref="IStubAssemblyGenerator" />.
    /// </summary>
    public class StubAssemblyGenerator : IStubAssemblyGenerator
    {
        /// <summary>
        /// The base namespace for stub implementations.
        /// </summary>
        private const string BaseStubNamespace =
            "Meridian.InterSproc.TemporaryStub";

        /// <summary>
        /// An instance of <see cref="CSharpCodeProvider" />, used by the
        /// generator to both compile and produce <c>.cs</c> files.
        /// </summary>
        private readonly CSharpCodeProvider csharpCodeProvider;

        /// <summary>
        /// An instance of <see cref="ILoggingProvider" />.
        /// </summary>
        private readonly ILoggingProvider loggingProvider;

        /// <summary>
        /// An instance of
        /// <see cref="IStubAssemblyGeneratorSettingsProvider" />.
        /// </summary>
        private readonly IStubAssemblyGeneratorSettingsProvider stubAssemblyGeneratorSettingsProvider;

        /// <summary>
        /// An instance of <see cref="IStubDatabaseContextGenerator" />.
        /// </summary>
        private readonly IStubDatabaseContextGenerator stubDatabaseContextGenerator;

        /// <summary>
        /// An instance of <see cref="IStubImplementationGenerator" />.
        /// </summary>
        private readonly IStubImplementationGenerator stubImplementationGenerator;

        /// <summary>
        /// Initialises a new instance of the
        /// <see cref="StubAssemblyGenerator" /> class.
        /// </summary>
        /// <param name="loggingProvider">
        /// An instance of <see cref="ILoggingProvider" />.
        /// </param>
        /// <param name="stubAssemblyGeneratorSettingsProvider">
        /// An instance of
        /// <see cref="IStubAssemblyGeneratorSettingsProvider" />.
        /// </param>
        /// <param name="stubDatabaseContextGenerator">
        /// An instance of <see cref="IStubDatabaseContextGenerator" />.
        /// </param>
        /// <param name="stubImplementationGenerator">
        /// An instance of <see cref="IStubImplementationGenerator" />.
        /// </param>
        public StubAssemblyGenerator(
            ILoggingProvider loggingProvider,
            IStubAssemblyGeneratorSettingsProvider stubAssemblyGeneratorSettingsProvider,
            IStubDatabaseContextGenerator stubDatabaseContextGenerator,
            IStubImplementationGenerator stubImplementationGenerator)
        {
            this.loggingProvider =
                loggingProvider;
            this.stubAssemblyGeneratorSettingsProvider =
                stubAssemblyGeneratorSettingsProvider;
            this.stubDatabaseContextGenerator =
                stubDatabaseContextGenerator;
            this.stubImplementationGenerator =
                stubImplementationGenerator;

            this.csharpCodeProvider =
                new CSharpCodeProvider();
        }

        /// <summary>
        /// Implements
        /// <see cref="IStubAssemblyGenerator.Create{DatabaseContractType}(FileInfo, ContractMethodInformation[])" />.
        /// </summary>
        /// <typeparam name="DatabaseContractType">
        /// The database contract interface type.
        /// </typeparam>
        /// <param name="destinationLocation">
        /// The destination location for the new stub <see cref="Assembly" />.
        /// </param>
        /// <param name="contractMethodInformations">
        /// An array of <see cref="ContractMethodInformation" /> instances.
        /// </param>
        /// <returns>
        /// An instance of <see cref="Assembly" />.
        /// </returns>
        public Assembly Create<DatabaseContractType>(
            FileInfo destinationLocation,
            ContractMethodInformation[] contractMethodInformations)
            where DatabaseContractType : class
        {
            Assembly toReturn = null;

            Type databaseContractType = typeof(DatabaseContractType);

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            this.loggingProvider.Debug(
                $"Generating {nameof(CodeNamespace)} for entire stub " +
                $"assembly...");

            // Generate the entire namespace and...
            CodeNamespace codeNamespace = this.GenerateEntireStubAssemblyDom(
                databaseContractType,
                contractMethodInformations);

            this.loggingProvider.Info(
                $"{nameof(CodeNamespace)} generation complete.");

            // ... add it to the CodeCompileUnit.
            codeCompileUnit.Namespaces.Add(codeNamespace);

            // Then, depending on the settings, output it to a code file.
            if (this.stubAssemblyGeneratorSettingsProvider.GenerateAssemblyCodeFile)
            {
                this.loggingProvider.Debug(
                    $"{nameof(IStubAssemblyGeneratorSettingsProvider.GenerateAssemblyCodeFile)} " +
                    $"= {true.ToString()}. Generating .cs code file prior " +
                    $"to compilation...");

                this.GenerateCodeFile(destinationLocation, codeCompileUnit);

                this.loggingProvider.Info($".cs file generated.");
            }

            Assembly hostAssembly = databaseContractType.Assembly;

            this.loggingProvider.Debug(
                $"Compiling {nameof(CodeNamespace)} to " +
                $"\"{destinationLocation.FullName}\"...");

            // Then finally, compile.
            toReturn = this.CompileStubAssembly(
                destinationLocation,
                hostAssembly,
                codeCompileUnit);

            this.loggingProvider.Info(
                $"\"{toReturn.FullName}\" generated. Returning.");

            return toReturn;
        }

        /// <summary>
        /// Compiles a stub assembly.
        /// Takes a <see cref="CodeCompileUnit" />, the
        /// <paramref name="hostAssembly" /> and a
        /// <paramref name="destinationLocation" />, and compiles an
        /// <see cref="Assembly" />.
        /// </summary>
        /// <param name="destinationLocation">
        /// A <see cref="FileInfo" /> describing the destination location of
        /// the compiled assembly.
        /// </param>
        /// <param name="hostAssembly">
        /// An instance of <see cref="Assembly" />, describing the host
        /// assembly containing the database contract.
        /// </param>
        /// <param name="codeCompileUnit">
        /// An instance of <see cref="CodeCompileUnit" />, describing the
        /// <see cref="Assembly" /> to generate.
        /// </param>
        /// <returns>
        /// An instance of <see cref="Assembly" />.
        /// </returns>
        private Assembly CompileStubAssembly(
            FileInfo destinationLocation,
            Assembly hostAssembly,
            CodeCompileUnit codeCompileUnit)
        {
            Assembly toReturn = null;

            CompilerParameters compilerParameters = new CompilerParameters()
            {
                OutputAssembly = destinationLocation.FullName
            };

            Assembly interSprocAssembly = this.GetType().Assembly;

            // Add a reference to the InterSproc assembly.
            compilerParameters.ReferencedAssemblies.Add(
                interSprocAssembly.Location);

            // Add a reference to the host assembly.
            compilerParameters.ReferencedAssemblies
                .Add(hostAssembly.Location);

            // Then the .net assemblies...
            string[] dotNetAssemblies =
            {
                // System.Data
                typeof(IDbConnection).Assembly.Location,

                // System.Data.Linq
                typeof(DataContext).Assembly.Location,

                // System.Linq
                typeof(Enumerable).Assembly.Location
            };

            compilerParameters.ReferencedAssemblies.AddRange(dotNetAssemblies);

            this.loggingProvider.Debug(
                $"About to compile stub assembly with the following " +
                $"referenced assemblies:");

            foreach (string referencedAssembly in compilerParameters.ReferencedAssemblies)
            {
                this.loggingProvider.Debug($"-> {referencedAssembly}");
            }

            CompilerResults compilerResults = this.csharpCodeProvider
                .CompileAssemblyFromDom(
                    compilerParameters,
                    codeCompileUnit);

            if (compilerResults.Errors.Count > 0)
            {
                this.loggingProvider.Fatal(
                    $"Fatal - more than one error was thrown during " +
                    $"compilation! Throwing a " +
                    $"{nameof(StubGenerationException)}...");

                CompilerError[] compilerErrors = compilerResults.Errors
                    .Cast<CompilerError>()
                    .ToArray();

                throw new StubGenerationException(compilerErrors);
            }
            else
            {
                toReturn = compilerResults.CompiledAssembly;

                this.loggingProvider.Info(
                    $"Compilation complete. {nameof(Assembly)} = " +
                    $"\"{toReturn.FullName}\".");
            }

            return toReturn;
        }

        /// <summary>
        /// Generates a <c>.cs</c> code file from the specified
        /// <see cref="CodeCompileUnit" />.
        /// </summary>
        /// <param name="destinationLocation">
        /// A <see cref="FileInfo" /> instance describing where to output
        /// the generated <c>.cs</c> file.
        /// </param>
        /// <param name="codeCompileUnit">
        /// An instance of <see cref="CodeCompileUnit" />, describing the
        /// <see cref="Assembly" /> that is about to be generated.
        /// </param>
        private void GenerateCodeFile(
            FileInfo destinationLocation,
            CodeCompileUnit codeCompileUnit)
        {
            FileInfo codeFileLoc =
                new FileInfo($"{destinationLocation.FullName}.cs");

            this.loggingProvider.Debug(
                $"Generating .cs codefile at: \"{codeFileLoc.FullName}\"...");

            using (StreamWriter fileStream = codeFileLoc.CreateText())
            {
                CodeGeneratorOptions codeGeneratorOptions =
                    new CodeGeneratorOptions()
                    {
                        BracingStyle = "C",
                        BlankLinesBetweenMembers = true
                    };

                this.csharpCodeProvider.GenerateCodeFromCompileUnit(
                    codeCompileUnit,
                    fileStream,
                    codeGeneratorOptions);
            }

            this.loggingProvider.Info(
                $".cs codefile generated at: \"{codeFileLoc.FullName}\".");
        }

        /// <summary>
        /// Generates the entire <see cref="Assembly" /> DOM, in the form of
        /// a <see cref="CodeNamespace" /> instance.
        /// </summary>
        /// <param name="databaseContractType">
        /// The database contract interface type.
        /// </param>
        /// <param name="contractMethodInformations">
        /// An array of <see cref="ContractMethodInformation" /> instances.
        /// </param>
        /// <returns>
        /// An instance of <see cref="CodeNamespace" />, containing the stub
        /// assembly DOM.
        /// </returns>
        private CodeNamespace GenerateEntireStubAssemblyDom(
            Type databaseContractType,
            ContractMethodInformation[] contractMethodInformations)
        {
            CodeNamespace toReturn = new CodeNamespace(BaseStubNamespace);

            // Add usings...
            // Add System.Linq...
            toReturn.Imports.Add(
                new CodeNamespaceImport(
                    typeof(Enumerable).Namespace));

            this.loggingProvider.Debug(
                $"Generating custom {nameof(DataContext)} class...");

            // Start first with the custom data context.
            CodeTypeDeclaration customDataContext =
                this.stubDatabaseContextGenerator.CreateClass(
                    databaseContractType,
                    contractMethodInformations);
            toReturn.Types.Add(customDataContext);

            this.loggingProvider.Info(
                $"Custom {nameof(DataContext)} generated.");

            CodeMemberMethod[] dataContextMethods =
                customDataContext.Members
                    .Cast<CodeTypeMember>()
                    .Where(x => x is CodeMemberMethod)
                    .Select(x => x as CodeMemberMethod)
                    .ToArray();

            this.loggingProvider.Debug(
                $"Generating implementation of " +
                $"{databaseContractType.Name}...");

            // Then the actual interface implementation.
            CodeTypeDeclaration interfaceImplementation =
                this.stubImplementationGenerator.CreateClass(
                    databaseContractType,
                    new CodeTypeReference(customDataContext.Name),
                    contractMethodInformations,
                    dataContextMethods);
            toReturn.Types.Add(interfaceImplementation);

            this.loggingProvider.Info(
                $"Implementation of {databaseContractType.Name} generated.");

            return toReturn;
        }
    }
}