text:
package com.webs.graub.tinywebserver;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

public class LimitedOutputStream extends FilterOutputStream {

	int mLimit;

	public LimitedOutputStream(OutputStream out, int limit) {
		super(out);
		this.mLimit = limit;
	}

	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		int bytesToWrite = Math.min(len, Math.max(mLimit,0));
		out.write(b,off,bytesToWrite);
		mLimit -= len;
		if (mLimit < 0) {
			System.out.println("WARNING: LimitedOutputStream is discarding "+
					(len-bytesToWrite)+" extra bytes");
		}
	}

	@Override
	public void write(int b) throws IOException {
		if (mLimit>0) out.write(b);
		mLimit -= 1;
		if (mLimit < 0) {
			System.out.println("WARNING: LimitedOutputStream is discarding "+
					1+" extra bytes");
		}
	}

	/**
	 * This method can be called
	 */
	public void complete() throws IOException {
		if (mLimit > 0) {
			System.out.println("WARNING: LimitedOutputStream is writing "+
					mLimit+" dummy bytes");
			byte[] dummy = new byte[mLimit];
			Arrays.fill(dummy, (byte)0);
			write(dummy,0,dummy.length);
			assert(mLimit==0);
		}
	}

}


text:
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "private/ErrnoRestorer.h"

class ScopedSignalBlocker {
 public:
  ScopedSignalBlocker() {
    sigset_t set;
    sigfillset(&set);
    sigprocmask(SIG_BLOCK, &set, &old_set_);
  }

  ~ScopedSignalBlocker() {
    sigprocmask(SIG_SETMASK, &old_set_, NULL);
  }

 private:
  sigset_t old_set_;
};

static FILE* __tmpfile_dir(const char* tmp_dir) {
  char buf[PATH_MAX];
  int path_length = snprintf(buf, sizeof(buf), "%s/tmp.XXXXXXXXXX", tmp_dir);
  if (path_length >= static_cast<int>(sizeof(buf))) {
    return NULL;
  }

  int fd;
  {
    ScopedSignalBlocker ssb;
    fd = mkstemp(buf);
    if (fd == -1) {
      return NULL;
    }

    // Unlink the file now so that it's removed when closed.
    unlink(buf);

    // Can we still use the file now it's unlinked?
    // File systems without hard link support won't have the usual Unix semantics.
    struct stat sb;
    int rc = fstat(fd, &sb);
    if (rc == -1) {
      ErrnoRestorer errno_restorer;
      close(fd);
      return NULL;
    }
  }

  // Turn the file descriptor into a FILE*.
  FILE* fp = fdopen(fd, "w+");
  if (fp != NULL) {
    return fp;
  }

  // Failure. Clean up. We already unlinked, so we just need to close.
  ErrnoRestorer errno_restorer;
  close(fd);
  return NULL;
}

FILE* tmpfile() {
  // TODO: get this app's temporary directory from the framework ("/data/data/app/cache").

  // $EXTERNAL_STORAGE turns out not to be very useful because it doesn't support hard links.
  // This means we can't do the usual trick of calling unlink before handing the file back.

  FILE* fp = __tmpfile_dir("/data/local/tmp");
  if (fp == NULL) {
    // P_tmpdir is "/tmp/", but POSIX explicitly says that tmpdir(3) should try P_tmpdir before
    // giving up. This is potentially useful for bionic on the host anyway.
    fp = __tmpfile_dir(P_tmpdir);
  }
  return fp;
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Set-CaasVIPVirtualListener — CaaS PowerShell 3.1 documentation</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="CaaS PowerShell 3.1 documentation" href="index.html" />

  <link rel="stylesheet" href="_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Set-CaasVIPVirtualListener¶

Synopsis¶

Set-CaasVIPVirtualListener -VirtualListener <VirtualListenerType> -ConnectionLimit <int> -ConnectionRateLimit <int> [-Description <string>] [-Enabled <bool>] [-SourcePortPreservation <string>] [-PoolId <guid>] [-ClientClonePoolId <guid>] [-PersistenceProfileId <string>] [-FallbackPersistenceProfileId <string>] [-OptimizationProfileId <string>] [-iRuleId <string[]>] [-Connection <ComputeServiceConnection>] [<CommonParameters>]

Syntax¶

syntaxItem

{@{name=Set-CaasVIPVirtualListener; CommonParameters=True; WorkflowCommonParameters=False; parameter=System.Object[]}}

Description¶

Parameters¶

-ClientClonePoolId <guid>¶

The VIP virtual listener Client Clone Pool Id

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-Connection <ComputeServiceConnection>¶

The CaaS Connection created by New-CaasConnection

Position?                    Named

Accept pipeline input?       true (ByPropertyName)
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-ConnectionLimit <int>¶

The VIP virtual listener Connection Limit

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-ConnectionRateLimit <int>¶

The VIP virtual listener Connection Rate Limit

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-Description <string>¶

The virtual listener description

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-Enabled <bool>¶

The VIP virtual listener Status

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-FallbackPersistenceProfileId <string>¶

The VIP virtual listener Fallback Persistence Profile Id

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-OptimizationProfileId <string>¶

The VIP virtual listener Optimization Profile Id

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-PersistenceProfileId <string>¶

The VIP virtual listener Persistence Profile Id

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-PoolId <guid>¶

The VIP virtual listener Pool Id

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-SourcePortPreservation <string>¶

The VIP virtual listener Source Port Preservation

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-VirtualListener <VirtualListenerType>¶

The virtual listener

Position?                    Named

Accept pipeline input?       true (ByValue)
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

-iRuleId <string[]>¶

The VIP virtual listener iRule Ids

Position?                    Named

Accept pipeline input?       false
Parameter set name           (All)
Aliases                      None
Dynamic?                     false

INPUTS¶

DD.CBU.Compute.Api.Contracts.Network20.VirtualListenerType
DD.CBU.Compute.Powershell.ComputeServiceConnection

OUTPUTS¶

DD.CBU.Compute.Api.Contracts.Network20.ResponseType

NOTES¶

EXAMPLES¶

Table Of Contents

Set-CaasVIPVirtualListener

Synopsis

Syntax

Description

Parameters

-ClientClonePoolId <guid>

-Connection <ComputeServiceConnection>

-ConnectionLimit <int>

-ConnectionRateLimit <int>

-Description <string>

-Enabled <bool>

-FallbackPersistenceProfileId <string>

-OptimizationProfileId <string>

-PersistenceProfileId <string>

-PoolId <guid>

-SourcePortPreservation <string>

-VirtualListener <VirtualListenerType>

-iRuleId <string[]>

INPUTS

OUTPUTS

NOTES

EXAMPLES

Related Topics

Documentation overview

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

      ©2016, Dimension Data.

      |
      Powered by Sphinx 1.3.1
      & Alabaster 0.7.8

      |
      Page source


text:
#region License

#endregion

#region Imports

using System.Collections.Generic;
using Apache.NMS;

using FakeItEasy;

using NUnit.Framework;
using Spring.Context;
using Spring.Context.Support;
using Spring.Messaging.Nms.Core;
using Spring.Messaging.Nms.Connections;
using Spring.Messaging.Nms.Listener;
using Spring.Objects;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;

#endregion

namespace Spring.Messaging.Nms.Config
{
    /// <summary>
    /// This class contains tests for
    /// </summary>
    /// <author>Mark Pollack</author>
    /// <version>$Id:$</version>
    [TestFixture]
    public class NmsNamespaceHandlerTests
    {
        private static string DEFAULT_CONNECTION_FACTORY = "ConnectionFactory";
        private static string EXPLICIT_CONNECTION_FACTORY = "testConnectionFactory";
        private IApplicationContext ctx;

        [SetUp]
        public void Setup()
        {
            // WELLKNOWN
            //NamespaceParserRegistry.RegisterParser(typeof(NmsNamespaceParser));
            ctx = new XmlApplicationContext(ReadOnlyXmlTestResource.GetFilePath("NmsNamespaceHandlerTests.xml", GetType()));
        }

        [Test]
        public void Registered()
        {
            Assert.IsNotNull(NamespaceParserRegistry.GetParser("http://www.springframework.net/nms"));
        }

        [Test]
        public void ObjectsCreated()
        {
            var containers = ctx.GetObjects<SimpleMessageListenerContainer>();
            Assert.AreEqual(3, containers.Count);
        }

        [Test]
        public void ContainerConfiguration()
        {
            var containers = ctx.GetObjects<SimpleMessageListenerContainer>();
            IConnectionFactory defaultConnectionFactory = (IConnectionFactory) ctx.GetObject(DEFAULT_CONNECTION_FACTORY);
            IConnectionFactory explicitConnectionFactory = (IConnectionFactory) ctx.GetObject(EXPLICIT_CONNECTION_FACTORY);

            int defaultConnectionFactoryCount = 0;
		    int explicitConnectionFactoryCount = 0;
            foreach (KeyValuePair<string, SimpleMessageListenerContainer> dictionaryEntry in containers)
            {
                SimpleMessageListenerContainer container = dictionaryEntry.Value;
                if (container.ConnectionFactory.Equals(defaultConnectionFactory))
                {
                    defaultConnectionFactoryCount++;
                }
                else if (container.ConnectionFactory.Equals(explicitConnectionFactory))
                {
                    explicitConnectionFactoryCount++;
                }
            }

            Assert.AreEqual(1, defaultConnectionFactoryCount, "1 container should have the default connectionFactory");
            Assert.AreEqual(2, explicitConnectionFactoryCount, "2 containers should have the explicit connectionFactory");

        }

        [Test]
        public void Listeners()
        {
            TestObject testObject1 = (TestObject) ctx.GetObject("testObject1");
            TestObject testObject2 = (TestObject) ctx.GetObject("testObject2");
            TestMessageListener testObject3 = (TestMessageListener) ctx.GetObject("testObject3");

            Assert.IsNull(testObject1.Name);
            Assert.IsNull(testObject2.Name);
            Assert.IsNull(testObject3.Message);

            ITextMessage message1 = A.Fake<ITextMessage>();
            A.CallTo(() => message1.Text).Returns("Test1");

            IMessageListener listener1 = GetListener("listener1");
            listener1.OnMessage(message1);
            Assert.AreEqual("Test1", testObject1.Name);

            ITextMessage message2 = A.Fake<ITextMessage>();
            A.CallTo(() => message2.Text).Returns("Test1");

            IMessageListener listener2 = GetListener("listener2");
            listener2.OnMessage(message2);
            A.CallTo(() => message2.Text).MustHaveHappened();

            ITextMessage message3 = A.Fake<ITextMessage>();

            //Default naming strategy is to use full type name + # + number
            string className = typeof(SimpleMessageListenerContainer).FullName;
            string targetName = className + ObjectDefinitionReaderUtils.GENERATED_OBJECT_NAME_SEPARATOR + "0";
            IMessageListener listener3 = GetListener(targetName);
            listener3.OnMessage(message3);
            Assert.AreSame(message3, testObject3.Message);
        }

        private IMessageListener GetListener(string containerObjectName)
        {
            SimpleMessageListenerContainer container =
                (SimpleMessageListenerContainer) ctx.GetObject(containerObjectName);
            return (IMessageListener) container.MessageListener;
        }
    }
}


text:
using System.Reflection;

namespace Octokit.Tests
{
    public static class Fixtures
    {
        public static EmbeddedResource AuthorizationsJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.authorizations.json");

        public static EmbeddedResource AuthorizationJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.authorization.json");

        public static EmbeddedResource UserJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.user.json");

        public static EmbeddedResource UserFullJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.user_full.json");

        public static EmbeddedResource RepositoryJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.repository.json");

        public static EmbeddedResource RepositoriesJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.repositories.json");

        public static EmbeddedResource ReleasesJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.releases.json");

        public static EmbeddedResource ReleaseJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.release.json");

        public static EmbeddedResource ReleaseAssetJson =
            new EmbeddedResource(typeof(Fixtures).GetTypeInfo().Assembly, "Octokit.Tests.Fixtures.release_asset.json");
    }
}


text:
var mongoose = require('mongoose');
mongoose.Promise = require('q').Promise;

var dbname = process.env.DB_NAME || 'niltava-dns';
var dbhost = process.env.DB_HOST || 'localhost';
var dbport = process.env.DB_PORT || '27017';

mongoose.connect('mongodb://' + dbhost + ':' + dbport + '/' + dbname, { config: { } });


text:
<?php

namespace Bootstrap\Facades;

class Route extends Facade
{
    protected static function getFacadeAccessor() { return 'router'; }
}


text:
package main

import (
	"bufio"
	"crypto/md5"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/divoxx/llog"
	"github.com/peterbourgon/diskv"
)

const (
	transformBlockSize = 2 // grouping of chars per directory depth
	VERSION            = "0.2.0"
)

var l *llog.Log

// Host contains the configuration details for a SSH Host.
type Host struct {
	// Name provided to ssh-manage, used to get/update a configuration
	Nickname string
	// Hostname or alias for the server
	Name string
	// Fully qualified hostname or IP address to connect
	IP string
	// Port number that the SSH daemon is listening on
	Port int16
	// The name of the remote user to connect as
	User string
	// Path the SSH key that should be used when connecting
	Key string
	// Interval that the ServerKeepAlive command should be passed to the server
	KeepAlive int8
}

// Get configuration details from defaults and arguments
func (h *Host) config(info []string) error {
	var err error
	if info[0] == "" {
		return errors.New("hostname or alias is required")
	}

	if info[1] == "" {
		return errors.New("SSH key is required")
	}

	h.Name = info[0]
	h.IP = info[0]
	h.Port = getPort()

	h.User, err = getCurrentUser()
	if err != nil {
		return err
	}
	h.Key = info[1]
	h.Key, _ = getSSHKey(h.Key)

	return nil
}

// Get the information from the user by asking a series of questions
func (h *Host) interactiveConfig() error {
	var err error
	fmt.Print("Hostname(s) or alias(s) of server: ")
	h.Name, err = getInput()
	if err != nil {
		return err
	}

	if h.Name == "" {
		return errors.New("hostname or alias is required to continue")
	}

	fmt.Print("Hostname or IP address of server: ")
	h.IP, err = getInput()
	if err != nil {
		return err
	}

	if h.IP == "" {
		h.IP = h.Name
	}

	fmt.Print("Port number of server: ")
	p, err := getInput()
	if err != nil {
		return err
	}

	if p != "" {
		port, err := strconv.Atoi(p)
		if err != nil {
			return err
		}
		h.Port = int16(port)
	} else {
		h.Port = getPort()
	}

	fmt.Print("User on server: ")
	h.User, err = getInput()
	if err != nil {
		return err
	}

	if h.User == "" {
		h.User, err = getCurrentUser()
		if err != nil {
			return err
		}
	}

	fmt.Print("SSH key: ")
	h.Key, err = getInput()
	if err != nil {
		return err
	}

	h.Key, err = getSSHKey(h.Key)
	if err != nil {
		return err
	}

	return nil
}

// Update the information from the user by asking a series of questions
func (h *Host) updateConfig() error {
	fmt.Printf("Hostname(s) or aliases for the server (%s): ", h.Name)
	val, err := getInput()
	if err != nil {
		return err
	}
	if val != "" {
		h.Name = val
	}

	fmt.Printf("Hostname(s) or IP addresses of the server (%s): ", h.IP)
	val, err = getInput()
	if err != nil {
		return nil
	}
	if val != "" {
		h.IP = val
	}

	fmt.Printf("Port number of the server (%d): ", h.Port)
	val, err = getInput()
	if err != nil {
		return nil
	}
	if val != "" {
		port, err := strconv.Atoi(val)
		if err != nil {
			return err
		}
		h.Port = int16(port)
	}

	fmt.Printf("User on the server (%s): ", h.User)
	val, err = getInput()
	if err != nil {
		return nil
	}
	if val != "" {
		h.User = val
	}

	fmt.Printf("SSH key (%s): ", h.Key)
	val, err = getInput()
	if err != nil {
		return nil
	}
	if val != "" {
		h.Key, _ = getSSHKey(val)
	}

	return nil
}

// BlockTransform builds out the directory structure for file.
func BlockTransform(s string) []string {
	sliceSize := len(s) / transformBlockSize
	pathSlice := make([]string, sliceSize)
	for i := 0; i < sliceSize; i++ {
		from, to := i*transformBlockSize, (i*transformBlockSize)+transformBlockSize
		pathSlice[i] = s[from:to]
	}
	return pathSlice
}

func main() {
	ll := flag.String("log", "ERROR", "Set the log level")
	version := flag.Bool("version", false, "Display the version number")

	configDir, err := getConfigPath()
	if err != nil {
		panic(err)
	}

	envFile := configDir + "/ssh-manage.env"
	_, err = os.Stat(envFile)
	if err == nil {
		loadConfig(envFile)
	}

	d := diskv.New(diskv.Options{
		BasePath:     configDir + "/hosts", // where the data is stored
		Transform:    BlockTransform,
		CacheSizeMax: 1024 * 1024, // 1MB
	})

	flag.Usage = usage
	flag.Parse()

	if *version {
		fmt.Printf("%s version: %v\n", os.Args[0], VERSION)
		os.Exit(0)
	}

	logLevel := getLogLevel(*ll)
	l = llog.New(os.Stdout, logLevel)

	logHandler("DEBUG", fmt.Sprintln("configuration directory:", configDir))

	if flag.NArg() == 0 {
		logHandler("ERROR", "please supply a command")
		// TODO list supported commands (Redirect to help message or usage text?)
		os.Exit(1)
	}

	// TODO add the ability to set if a record or records should get
	// printed.  This needs to be host dependant.
	switch flag.Arg(0) {
	case "add":
		var hostInfo string
		if flag.Arg(2) != "" {
			hostInfo = flag.Arg(2)
		}

		err = addRecord(d, strings.TrimSpace(flag.Arg(1)), hostInfo)
		if err != nil {
			logHandler("ERROR",
				fmt.Sprintf("failed creating a new record: %s\n", err.Error()))
			os.Exit(1)
		}
	case "get":
		err := getRecord(d, strings.TrimSpace(flag.Arg(1)))
		if err != nil {
			logHandler("ERROR",
				fmt.Sprintf("failed fetching record details: %s\n", err.Error()))
			os.Exit(1)
		}
	case "list":
		err := listRecords(d)
		if err != nil {
			logHandler("ERROR",
				fmt.Sprintf("failed fetching all records: %s\n", err.Error()))
			os.Exit(1)
		}
	case "rm":
		err := removeRecord(d, strings.TrimSpace(flag.Arg(1)))
		if err != nil {
			logHandler("ERROR",
				fmt.Sprintf("failed removing record: %s\n", err.Error()))
			os.Exit(1)
		}
	case "write":
		err := writeFile(d)
		if err != nil {
			logHandler("ERROR",
				fmt.Sprintf("failed when writing out SSH configuration file: %s\n",
					err.Error()))
			os.Exit(1)
		}
	case "update":
		if flag.Arg(1) == "" {
			logHandler("ERROR", "update requires an argument")
			os.Exit(1)
		}

		err := updateRecord(d, strings.TrimSpace(flag.Arg(1)))
		if err != nil {
			logHandler("ERROR",
				fmt.Sprintf("faild updating record: %s\n", err.Error()))
			os.Exit(1)
		}
	default:
		usage()
		os.Exit(1)
	}

	os.Exit(0)
}

func usage() {
	command := os.Args[0]
	fmt.Fprintf(os.Stderr,
		`Usage: %s [options] {add|get|list|rm|write|update} [arguments]
%s requires one of the following commands:

add:   Add a new host record to the datastore
get:   Get details about a host record from the datastore
update Update an existing host record
list:  Lists all records in the datastore
rm:    Removes a record from the datastore
write: Write out SSH configuration file

Options:
  --help: Displays this help message
`, command, command)
}

func getLogLevel(ll string) llog.Level {
	switch ll {
	case "debug":
		return llog.DEBUG
	case "info":
		return llog.INFO
	case "warn":
		return llog.WARNING
	case "error":
		return llog.ERROR
	default:
		return llog.ERROR
	}
}

func logHandler(lvl, msg string) {
	switch lvl {
	case "DEBUG":
		l.Debug("[DEBUG]", logTime(), msg)
	case "INFO":
		l.Info("[INFO]", logTime(), msg)
	case "WARN":
		l.Warning("[WARNING]", logTime(), msg)
	case "ERROR":
		l.Error("[ERROR]", logTime(), msg)
	default:
		return
	}
}

func logTime() string {
	return time.Now().Format(time.RFC3339)
}

func md5sum(s string) string {
	h := md5.New()
	io.WriteString(h, s)
	return fmt.Sprintf("%x", h.Sum(nil))
}

// Read in input using STDIN, returns the value as a string.
func getInput() (string, error) {
	s := bufio.NewScanner(os.Stdin)
	s.Scan()
	if err := s.Err(); err != nil {
		return "", err
	}
	t := s.Text()
	return t, nil
}

// Create the configuration record and store it in the datastore
func addRecord(d *diskv.Diskv, name, hostInfo string) error {
	h := Host{Nickname: name, KeepAlive: 30}
	var err error

	if hostInfo == "" {
		err = h.interactiveConfig()
		if err != nil {
			return err
		}
	} else {
		info := strings.Split(hostInfo, ":")
		err = h.config(info)
		if err != nil {
			return err
		}
	}

	val, err := json.Marshal(h)
	if err != nil {
		return err
	}

	d.Write(md5sum(name), []byte(val))
	return nil
}

// Fetch a record from the datastore and display the current configuration to the user
func getRecord(d *diskv.Diskv, name string) error {
	val, err := d.Read(md5sum(name))
	if err != nil {
		return fmt.Errorf("no configuration found for %s", name)
	}

	fmt.Println("Configuration for", name)
	fmt.Println(string(val))
	return nil
}

// Lets the nickname for all configurations currently in the datastore
func listRecords(d *diskv.Diskv) error {
	var h Host
	keyChan, keyCount := d.Keys(nil), 0
	for key := range keyChan {
		val, err := d.Read(key)
		if err != nil {
			return err
		}

		err = json.Unmarshal(val, &h)
		if err != nil {
			return err
		}
		fmt.Printf("%s: %s\n", h.Nickname, val)
		keyCount++
	}
	fmt.Println("Total configuration(s) currently stored:", keyCount)
	return nil
}

// Given a record remove it from from the datastore.
func removeRecord(d *diskv.Diskv, name string) error {
	err := d.Erase(md5sum(name))
	if err != nil {
		return fmt.Errorf("no configuration found for %s\n", name)
	}
	return nil
}

// Given a record allow settings to be updated.
func updateRecord(d *diskv.Diskv, name string) error {
	var h Host
	val, err := d.Read(md5sum(name))
	if err != nil {
		return fmt.Errorf("no configuration found for %s\n", name)
	}

	err = json.Unmarshal(val, &h)
	if err != nil {
		return fmt.Errorf("failed to parse the configuration: %s\n", err.Error())
	}

	err = h.updateConfig()
	if err != nil {
		return fmt.Errorf("failed to update the host information: %s", err.Error())
	}

	val, err = json.Marshal(h)
	if err != nil {
		return err
	}

	d.Write(md5sum(name), []byte(val))

	return nil
}


text:
package ardrone

type testDrone struct{}

func (t testDrone) Takeoff() bool              { return true }
func (t testDrone) Land()                      {}
func (t testDrone) Up(a float64)               {}
func (t testDrone) Down(a float64)             {}
func (t testDrone) Left(a float64)             {}
func (t testDrone) Right(a float64)            {}
func (t testDrone) Forward(a float64)          {}
func (t testDrone) Backward(a float64)         {}
func (t testDrone) Clockwise(a float64)        {}
func (t testDrone) Counterclockwise(a float64) {}
func (t testDrone) Hover()                     {}


text:
import radioChannels from './radioChannels';

export class AppRouteDispatcher extends Marionette.Object {
    routeHome() {
        radioChannels.router.trigger('route:uploader:initialize');
    }
    routeUploader() {
        radioChannels.router.trigger('route:uploader:initialize');
    }
}

export class AppRouter extends Marionette.AppRouter {
    protected appRoutes;
    constructor(options?: any) {
        this.appRoutes = {
            'home': 'routeHome',
            'uploader': 'routeUploader',
            '': 'routeHome',
            '*path': 'routeHome'
        };
        super(options);
        this.navigate('', true);
    }

    onRoute() {
        console.log('on route', arguments);
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" >

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

<title>Lecture - HTML Forms - Java Camp</title>
<meta property="og:title" content="Lecture - HTML Forms" />
<meta name="description" content="  30 minutes  Learning Objectives          Learn the concept of HTML forms      Learn a textbox input control      Learn querystring parameters      Learn URL encoding      Learn external "get" form submission      " />
<meta property="og:description" content="  30 minutes  Learning Objectives          Learn the concept of HTML forms      Learn a textbox input control      Learn querystring parameters      Learn URL encoding      Learn external "get" form submission      " />
<link rel="canonical" href="http://localhost:4000/units/unit3007_lecture_html_forms.html" />
<meta property="og:url" content="http://localhost:4000/units/unit3007_lecture_html_forms.html" />
<meta property="og:site_name" content="Java Camp" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2016-11-09T16:56:17-06:00" />

			<form action="/search/" method="get">
				<input type="text" name="q" id="search-input" placeholder="Search">
				<input type="submit" value="Search" style="display: none;">
			</form>

Course Material

Week 3 Material

Day 11 Material

				Welcome to Camp

				Lecture - Introduction to HTML

				Lab - HTML Page

				Debrief Lab - HTML Page

				Lunch

				Quiz - HTML

				Lecture - HTML Forms

				Lab - HTML Forms

				Debrief Lab - HTML Forms

				Social Exercise - Web Pages

				Lecture - Web Server

				Lab - Install Java JDK and Apache Tomcat

				Lab - Test Apache Tomcat

				Quiz - HTML Forms

				Career Planning

Lecture - HTML Forms

30 minutes

Learning Objectives

Learn the concept of HTML forms

Learn a textbox input control

Learn querystring parameters

Learn URL encoding

Learn external "get" form submission

User Input

So far, you've learned how to display text, images, and links on a webpage.  Many of these elements are referred to as output, which are things that our code will display to a user.

But what if you want to collect information from a user?  For example, Google.com has a text box to ask what a user wants to search.  Elements that a user can type or change the state of are often referred to as input.

Textbox

The textbox might be the most common input element across all of programming.  Here in HTML, we're going to use the following code to put one on our page.

<input type="textbox" name="a name for your textbox" />

Notice that there is no separate closing tag!  But the opening tag closes itself with a />

1.  Create a new html file called textbox.html and write the basic page structure elements and place a textbox named "search" in the body.

    After you've tried, if you need a hint, you can click on the example tab.

<!doctype html>
<html>
<head></head>
<body>
    <input type="textbox" name="search" />
</body>
</html>

2.  View your page in a web browser.  Try typing the word "iPhone" into the textbox and try pressing enter.

You should be able to type text in the box, but the enter key should not do anything.

Forms

In order to bring your HTML input elements to life, you'll need to put them inside a form.  Once a form wraps the input elements on a page, the enter key will submit the webpage which either triggers a page refresh or takes us to a completely new webpage.

We're going to use the following code to put one on our page:

<form method="get">
    <input type="textbox" name="search" />
    <input type="submit" value="Go!" />  <!-- good practice to put a "submit" button in each form -->
</form>

3.  Update your code, type the word "iPhone" into the textbox and press enter again.

4.  Look at the address of your webpage in the web browser.  What do you notice is different?

When a form's action is set to "get", the values of all input elements in a form get placed on the web address.  We call these querystring parameters.

5.  Place a second textbox on your form named "search2".

6.  Type the word "iPhone" in the first textbox, and type the word "radio" in the second textbox.  Press the enter key and look at your browser's address bar.

When a form's method is set to "get", a "?" is added to the end of the original web address to signal the beginning of querystring parameters.  Then each input element gets added with a name=value convention, and multiple input elements are separated with a "&".

For example:

http://samplewebsite.com/searchpage.html?search1=iPhone&search2=radio

Special Characters

There are some text characters that don't work as part of a web address.  This is often because they are characters used in internet addresses.  So, if your querystring parameter value contains one of these special characters, they will get translated to a special code, a process we call url encoding.

To see an example, try the following search terms and review your web browser bar to see how the querystring parameter looks.

7.  Type "test space" into the first textbox and "test:colon" into the second textbox

You should see the space character encoded as a + sign and the : character encoded as %3A

8.  Type "test&ampersand" into the first textbox and "test@at" into the second textbox

You should see the & character encoded as %26 and the @ character encoded as %40

9.  Type "test/slash" into the first textbox and "test\backslash" into the second textbox

You should see the / character encoded as %2F and the \ character encoded as %5C

10.  Type "test+plus" into the first textbox and "test%percentage" into the second textbox

You should see the + character encoded as %2B and the % character encoded as %25

The presence of a % in an address bar usually signals that a parameter has been url encoded.

External Websites

Did you know that many Internet websites use "get" forms and querystring parameters?

11.  Head to http://www.amazon.com and enter iPhone as a search term.  Press enter and look at the address bar.  Can you find the name of the input element and see your search term in the address bar?

At the time of writing this lesson, the website url looks like this:

https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=iphone

You can see very easily that the name of the textbox was "field-keywords" and that my search term is attached to it.  There are also several other querystring parameters that Amazon is using, but if you try searching a few different things, you will see these values aren't changing, meaning they aren't affected by a user's input.

Submitting a Form to External Websites

Did you know that we can make our textbox.html page interact with Amazon.com?

12.  Update your form tag with an action attribute with the enter Amazon address before the "?", and change the name of the first textbox to "field-keywords":

<form method="get" action="https://www.amazon.com/s/ref=nb_sb_noss">
    <input type="textbox" name="field-keywords" />
    <input type="textbox" name="search2" />
    <input type="submit" value="Go!" />
</form>

13.  Type "iPhone" in the first textbox and "radio" in the second textbox.  Press enter or click the form button and see what happens.

Your search page should work with Amazon! The second textbox has a name that Amazon doesn't recognize, so its value is ignored by their program.  However, the first search box should control the search results from Amazon.

Challenge Question

In your own words, what is happening and how did we make this happen?

We visited Amazon.com and tried using their search engine.  We noticed they use querystring parameters, because we could see the search terms go up into the address bar.  We created our own web form and gave a textbox the exact same name that we saw in the Amazon address bar ("field-keywords").  Then we told our form, when submitted, to pass all of its infomation via querystring to an Amazon web address.


text:
<?php

defined('JPATH_BASE') or die;

JHtml::_('behavior.core');

$doTask = $displayData['doTask'];
$class  = $displayData['class'];
$text   = $displayData['text'];
$name   = $displayData['name'];
?>
<button value="<?php echo $doTask; ?>" class="btn btn-small modal" data-toggle="modal" data-target="#modal-<?php echo $name; ?>">
	<span class="<?php echo $class; ?>" aria-hidden="true">
	<?php echo $text; ?>
</button>


text:
@class ItineraryModel;

@interface MapViewController : UIViewController

@property (nonatomic) ItineraryModel *itineraryModel;

@end


text:
class IChainRecordNotFound < StandardError
end

class UserDisabled < StandardError
end

class User < ActiveRecord::Base
  rolify
  include Gravtastic
  gravtastic size: 32

  before_create :setup_role

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise_modules = []

  if CONFIG['authentication']['ichain']['enabled']
    devise_modules += [ :ichain_authenticatable, :ichain_registerable, :omniauthable, omniauth_providers: [] ]
  else
    devise_modules += [:database_authenticatable, :registerable,
                       :recoverable, :rememberable, :trackable, :validatable, :confirmable,
                       :omniauthable, omniauth_providers: [:suse, :google, :facebook, :github] ]
  end

  devise(*devise_modules)

  has_and_belongs_to_many :roles
  has_many :openids

  attr_accessible :email, :password, :password_confirmation, :remember_me, :role_id, :role_ids,
                  :name, :email_public, :biography, :nickname, :affiliation, :is_admin,
                  :tshirt, :mobile, :volunteer_experience, :languages, :username, :login, :is_disabled

  attr_accessor :login

  has_many :event_users, dependent: :destroy
  has_many :events, -> { uniq }, through: :event_users
  has_many :registrations, dependent: :destroy
  has_many :ticket_purchases, dependent: :destroy
  has_many :tickets, through: :ticket_purchases, source: :ticket
  has_many :votes, dependent: :destroy
  has_many :voted_events, through: :votes, source: :events
  has_many :subscriptions, dependent: :destroy
  accepts_nested_attributes_for :roles

  scope :admin, -> { where(is_admin: true) }

  validates :email, presence: true

  validates :username,
            uniqueness: {
                case_sensitive: false
            },
            presence: true

  def subscribed? conference
    self.subscriptions.find_by(conference_id: conference.id).present?
  end

  # Returns the purchased ticket
  # ====Returns
  # * +TicketUser::ActiveRecord_Relation+ -> user
  def ticket(id)
    ticket_purchases.where(ticket_id: id).first
  end

  def supports? conference
    ticket_purchases.find_by(conference_id: conference.id).present?
  end

  def self.for_ichain_username(username, attributes)
    user = find_by(username: username)

    raise UserDisabled if user && user.is_disabled

    if user
      user.update_attributes(email: attributes[:email])
    else
      begin
        user = create!(username: username, email: attributes[:email])
      rescue ActiveRecord::RecordNotUnique
        raise IChainRecordNotFound
      end
    end
    user
  end

  def self.find_for_database_authentication(warden_conditions)
    conditions = warden_conditions.dup
    login = conditions.delete(:login)
    if login
      where(conditions).where(['lower(username) = :value OR lower(email) = :value', { value: login.downcase }]).first
    else
      where(conditions).first
    end
  end

  # Searches for user based on email. Returns found user or new user.
  # ====Returns
  # * +User::ActiveRecord_Relation+ -> user
  def self.find_for_auth(auth, current_user = nil)
    user = current_user

    if user.nil? # No current user available, user is not already logged in
      user = User.where(email: auth.info.email).first_or_initialize
    end

    if user.new_record?
      user.email = auth.info.email
      user.name = auth.info.name
      user.username = auth.info.username
      user.password = Devise.friendly_token[0, 20]
      user.skip_confirmation!
    end

    user
  end

  def setup_role
    if User.count == 1 && User.first.email == 'deleted@localhost.osem'
      self.is_admin = true
    end
  end

  # Gets the roles of the user, groups them by role.name and returns the resource(s) of each role
  # ====Returns
  # * +Hash+ * ->  e.g. 'organizer' =>  "(conf1, conf2)"
  def get_roles
    result = {}
    Role::ACTIONABLES.each do |role|
      resources = self.roles.where(name: role.parameterize.underscore).map{ |myrole| Conference.find(myrole.resource_id).short_title }.join ', '
      result[role.parameterize.underscore] = "(#{ resources })" unless resources.blank?
    end
    result
  end

  def self.prepare(params)
    email = params['email']
    user = User.where(email: email).first_or_initialize

    # If there is a new user, add the necessary attributes
    if user.new_record?
      user.password = Devise.friendly_token[0, 20]
      user.skip_confirmation!
      user.attributes = params
    end

    user
  end

  def registered
    registrations = self.registrations
    if registrations.count == 0
      'None'
    else
      registrations.map { |r| r.conference.title }.join ', '
    end
  end

  def attended
    registrations_attended = registrations.where(attended: true)
    if registrations_attended.count == 0
      'None'
    else
      registrations_attended.map { |r| r.conference.title }.join ', '
    end
  end

  def confirmed?
    !confirmed_at.nil?
  end

  def attending_conference?(conference)
    Registration.where(conference_id: conference.id,
                       user_id: id).count
  end

  def proposals(conference)
    events.where('conference_id = ? AND event_users.event_role=?', conference.id, 'submitter')
  end

  def proposal_count(conference)
    proposals(conference).count
  end

  def biography_word_count
    if biography.nil?
      0
    else
      biography.split.size
    end
  end

  private

  def biography_limit
    errors.add(:abstract, 'cannot have more than 150 words') if biography &&
                                                                biography.split.size > 150
  end
end


text:
package com.opengamma.bbg.loader;

import static com.opengamma.bbg.BloombergConstants.BLOOMBERG_BOND_FUTURE_TYPE;
import static com.opengamma.bbg.BloombergConstants.FIELD_CRNCY;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUTURES_CATEGORY;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_CONT_SIZE;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_DELIVERABLE_BONDS;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_DLV_DT_FIRST;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_DLV_DT_LAST;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_LAST_TRADE_DT;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_LONG_NAME;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_TRADING_HRS;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_VAL_PT;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_BBG_UNIQUE;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_CUSIP;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_ISIN;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_MIC_PRIM_EXCH;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_SEDOL1;
import static com.opengamma.bbg.BloombergConstants.FIELD_PARSEKYABLE_DES;
import static com.opengamma.bbg.util.BloombergDataUtils.isValidField;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.fudgemsg.FudgeField;
import org.fudgemsg.FudgeMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.ZonedDateTime;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.opengamma.bbg.referencedata.ReferenceDataProvider;
import com.opengamma.bbg.util.BloombergDataUtils;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.financial.security.future.BondFutureDeliverable;
import com.opengamma.financial.security.future.BondFutureSecurity;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.master.security.ManageableSecurity;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.Expiry;

/**
 * Loads the data for a Bond Future from Bloomberg.
 */
public class BondFutureLoader extends SecurityLoader {

  /** Logger. */
  private static final Logger LOGGER = LoggerFactory.getLogger(BondFutureLoader.class);
  /**
   * The fields to load from Bloomberg.
   */
  private static final Set<String> BLOOMBERG_BOND_FUTURE_FIELDS = Collections.unmodifiableSet(Sets.newHashSet(
      FIELD_FUT_LONG_NAME,
      FIELD_ID_MIC_PRIM_EXCH,
      FIELD_CRNCY,
      FIELD_FUT_LAST_TRADE_DT,
      FIELD_FUT_TRADING_HRS,
      FIELD_FUT_DELIVERABLE_BONDS,
      FIELD_FUT_DELIVERABLE_BONDS,
      FIELD_FUTURES_CATEGORY,
      FIELD_FUT_DLV_DT_FIRST,
      FIELD_FUT_DLV_DT_LAST,
      FIELD_ID_BBG_UNIQUE,
      FIELD_ID_CUSIP,
      FIELD_ID_ISIN,
      FIELD_ID_SEDOL1,
      FIELD_PARSEKYABLE_DES,
      FIELD_FUT_VAL_PT,
      FIELD_FUT_CONT_SIZE));

  /**
   * The valid Bloomberg future categories for Bond Futures.
   */
  public static final Set<String> VALID_FUTURE_CATEGORIES = ImmutableSet.of(BLOOMBERG_BOND_FUTURE_TYPE);

  /**
   * Creates an instance.
   *
   * @param referenceDataProvider
   *          the provider, not null
   */
  public BondFutureLoader(final ReferenceDataProvider referenceDataProvider) {
    super(LOGGER, referenceDataProvider, SecurityType.BOND_FUTURE);
  }

  // -------------------------------------------------------------------------
  @Override
  protected ManageableSecurity createSecurity(final FudgeMsg fieldData) {
    final String expiryDate = fieldData.getString(FIELD_FUT_LAST_TRADE_DT);
    final String futureTradingHours = fieldData.getString(FIELD_FUT_TRADING_HRS);
    final String micExchangeCode = fieldData.getString(FIELD_ID_MIC_PRIM_EXCH);
    final String currencyStr = fieldData.getString(FIELD_CRNCY);
    final String category = BloombergDataUtils.removeDuplicateWhiteSpace(fieldData.getString(FIELD_FUTURES_CATEGORY), " ");
    final String firstDeliveryDateStr = fieldData.getString(FIELD_FUT_DLV_DT_FIRST);
    final String lastDeliveryDateStr = fieldData.getString(FIELD_FUT_DLV_DT_LAST);
    final String name = BloombergDataUtils.removeDuplicateWhiteSpace(fieldData.getString(FIELD_FUT_LONG_NAME), " ");
    final String bbgUnique = fieldData.getString(FIELD_ID_BBG_UNIQUE);
    final Double unitAmount = fieldData.getDouble(FIELD_FUT_CONT_SIZE);
    if (!fieldData.hasField(FIELD_FUT_CONT_SIZE) || unitAmount == null) {
      LOGGER.warn("FIELD_FUT_VAL_PT does not contain a numeric value (" + fieldData.getString(FIELD_FUT_VAL_PT) + ")");
      return null;
    }

    if (!isValidField(bbgUnique)) {
      LOGGER.warn("bbgUnique is null, cannot construct bond future security");
      return null;
    }
    if (!isValidField(futureTradingHours)) {
      LOGGER.warn("futures trading hours is null, cannot construct bond future security");
      return null;
    }
    if (!isValidField(expiryDate)) {
      LOGGER.warn("expiry date is null, cannot construct bond future security");
      return null;
    }
    if (!isValidField(micExchangeCode)) {
      LOGGER.warn("settlement exchange is null, cannot construct bond future security");
      return null;
    }
    if (!isValidField(currencyStr)) {
      LOGGER.warn("currency is null, cannot construct bond future security");
      return null;
    }
    if (!isValidField(category)) {
      LOGGER.warn("category is null, cannot construct bond future security");
      return null;
    }
    if (!isValidField(firstDeliveryDateStr)) {
      LOGGER.warn("first delivery date is invalid, cannot construct bond future security");
    }
    if (!isValidField(lastDeliveryDateStr)) {
      LOGGER.warn("lastt delivery date is invalid, cannot construct bond future security");
    }

    final Expiry expiry = decodeExpiry(expiryDate, futureTradingHours);
    if (expiry == null) {
      return null;
    }
    final Currency currency = Currency.parse(currencyStr);

    final ZonedDateTime firstDeliverDate = decodeDeliveryDate(firstDeliveryDateStr);
    final ZonedDateTime lastDeliverDate = decodeDeliveryDate(lastDeliveryDateStr);
    final Set<BondFutureDeliverable> basket = createBondDeliverables(fieldData);
    final BondFutureSecurity security = new BondFutureSecurity(expiry, micExchangeCode, micExchangeCode, currency, unitAmount, basket,
        firstDeliverDate, lastDeliverDate, category);

    // set identifiers
    parseIdentifiers(fieldData, security);
    security.setName(name);
    return security;
  }

  /**
   * @param fieldData
   * @return
   */
  private Set<BondFutureDeliverable> createBondDeliverables(final FudgeMsg fieldData) {
    final Set<BondFutureDeliverable> result = new HashSet<>();
    for (final FudgeField field : fieldData.getAllByName(FIELD_FUT_DELIVERABLE_BONDS)) {
      if (field.getValue() instanceof FudgeMsg) {
        final FudgeMsg deliverableContainer = (FudgeMsg) field.getValue();
        final Double conversionFactor = deliverableContainer.getDouble("Conversion Factor");
        final String tcm = deliverableContainer.getString("Ticker, Coupon, Maturity of Deliverable Bonds");
        if (conversionFactor != null && isValidField(tcm)) {
          final ExternalIdBundle ids = ExternalIdBundle.of(ExternalSchemes.bloombergTickerSecurityId(tcm));
          final BondFutureDeliverable deliverable = new BondFutureDeliverable(ids, conversionFactor);
          result.add(deliverable);
        }
      }
    }
    return result;
  }

  @Override
  protected Set<String> getBloombergFields() {
    return BLOOMBERG_BOND_FUTURE_FIELDS;
  }

}


text:
<?php

namespace Sweikenb\Clutter\Datastore\API;

use Sweikenb\Clutter\Datastore\Exceptions\InvalidQueryConditionModeException;

/**
 * Interface RepositoryQueryInterface
 *
 * @package Sweikenb\Clutter\Datastore\API
 */
interface RepositoryQueryInterface
{
    const EQ = 'eq';
    const NEQ = 'neq';
    const IN = 'in';
    const NOT_IN = 'nin';
    const GT = 'gt';
    const GTE = 'gte';
    const LT = 'lt';
    const LTE = 'lte';
    const IS_NULL = 'inull';
    const NOT_NULL = 'nnull';
    const BETWEEN = 'btw';
    const NOT_BETWEEN = 'nbtw';

    /**
     * @return array
     */
    public function getConditionModes();

    /**
     * @return array
     */
    public function getConditions();

    /**
     * @param string     $field
     * @param string     $mode
     * @param mixed|null $value
     *
     * @return $this
     * @throws InvalidQueryConditionModeException
     */
    public function field($field, $mode, $value = null);
}


text:
#include "alloutil/al_OmniApp.hpp"
using namespace al;

struct MyApp : OmniApp {
  Mesh mesh;
  Light light;

  MyApp() {
    mesh.primitive(Graphics::TRIANGLES);
    addSphere(mesh, 1.0, 32, 32);
    for (int i = 0; i < mesh.vertices().size(); ++i) {
      float f = (float)i / mesh.vertices().size();
      mesh.color(Color(HSV(f, 1 - f, 1), 1));
    }
    mesh.generateNormals();
    light.ambient(Color(0.4, 0.4, 0.4, 1.0));
    light.pos(5, 5, 5);
  }

  virtual ~MyApp() {}

  virtual void onDraw(Graphics& g) {
    light();
    // say how much lighting you want
    shader().uniform("lighting", 1.0);

/*!*/ g.fog(lens().far(), lens().near()+2, Color(0, 0, 0, 1));
/*!*/ shader().uniform("fogCurve", 30.0);

    g.draw(mesh);
  }

  virtual void onAnimate(al_sec dt) {
    //light.pos(nav().pos());
    //std::cout << dt << std::endl;
  }

  virtual void onSound(AudioIOData& io) {
    while (io()) {
      io.out(0) = rnd::uniformS() * 0.05;
    }
  }

  virtual void onMessage(osc::Message& m) {
    OmniApp::onMessage(m);
  }

  virtual bool onKeyDown(const Keyboard& k){
    return true;
  }

  std::string vertexCode() {
    return R"(
      varying vec4 color;
      varying vec3 normal, lightDir, eyeVec;

/*!*/ uniform float fogCurve;
/*!*/ varying float fogFactor;

      void main(){
        color = gl_Color;
        vec4 vertex = gl_ModelViewMatrix * gl_Vertex;

        normal = gl_NormalMatrix * gl_Normal;
        vec3 V = vertex.xyz;
        eyeVec = normalize(-V);
        lightDir = normalize(vec3(gl_LightSource[0].position.xyz - V));
        gl_TexCoord[0] = gl_MultiTexCoord0;
        gl_Position = omni_render(vertex);

/*!*/   float z = gl_Position.z;
/*!*/   fogFactor = (z - gl_Fog.start) * gl_Fog.scale;
/*!*/   fogFactor = clamp(fogFactor, 0., 1.);
/*!*/   if(fogCurve != 0.){
/*!*/     fogFactor = (1. - exp(-fogCurve*fogFactor))/(1. - exp(-fogCurve));
/*!*/   }
      }
    )";
  }

  std::string fragmentCode() {
    return R"(
      uniform float lighting;
      uniform float texture;
      uniform sampler2D texture0;
      varying vec4 color;
      varying vec3 normal, lightDir, eyeVec;

/*!*/ varying float fogFactor;

      void main() {
        vec4 colorMixed;
        if( texture > 0.0){
          vec4 textureColor = texture2D(texture0, gl_TexCoord[0].st);
          colorMixed = mix(color, textureColor, texture);
        }else{
          colorMixed = color;
        }

        vec4 final_color = colorMixed * gl_LightSource[0].ambient;
        vec3 N = normalize(normal);
        vec3 L = lightDir;
        float lambertTerm = max(dot(N, L), 0.0);
        final_color += gl_LightSource[0].diffuse * colorMixed * lambertTerm;
        vec3 E = eyeVec;
        vec3 R = reflect(-L, N);
        float spec = pow(max(dot(R, E), 0.0), 0.9 + 1e-20);
        final_color += gl_LightSource[0].specular * spec;
/*!*/   gl_FragColor = mix(mix(colorMixed, final_color, lighting), gl_Fog.color, fogFactor);
      }
    )";
  }
};

int main(int argc, char * argv[]) {
  MyApp().start();
  return 0;
}


text:
/* global describe, it */

var chron = require('chronic');
var browserify = require('browserify')
var babelify = require('babelify')
var assert = require('assert');
var lrload = require('livereactload')

describe('default', function () {
  chron('default', function (t) { console.log('hello'); t.done() });
  it('should run default', function () {});
})

describe('tasks', function () {
  it('should have correct info', function (done) {
    chron('default', chron
      .source('./src/main.js', 'testing.js')
      .dest('static'),
      function (t) {
        assert.equal(t.files[0], './src/main.js');
        assert.equal(t.path, 'static');

        var b = browserify({
          entries: [t.files[0]],
          cache: {},
          packageCache: {},
          transform: [ babelify, lrload ],
          debug: t.params.d || t.params.debug,
          bundleExternal: false
        })

        var name = t.files[1] || 'bundle.js';

        assert.equal(name, 'testing.js');

        assert.equal(t.path + '/' + name, 'static/testing.js')

        t.pump(b.bundle(), t.source(name), t.dest(), function (err) {
          if (err) throw err;
          t.done(err)
          done(err);
        })
      }
    ).run()
  })
})


text:
/*
  Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/composite-private.h"
#include "magick/draw.h"
#include "magick/draw-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/token.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)
#include <pango/pango.h>
#include <pango/pangocairo.h>
#include <pango/pango-features.h>
#endif

#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d P A N G O I m a g e                                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadPANGOImage() reads an image in the Pango Markup Language Format.
%
%  The format of the ReadPANGOImage method is:
%
%      Image *ReadPANGOImage(const ImageInfo *image_info,
%        ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadPANGOImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  cairo_font_options_t
    *font_options;

  cairo_surface_t
    *surface;

  char
    *caption,
    *property;

  cairo_t
    *cairo_image;

  const char
    *option;

  DrawInfo
    *draw_info;

  Image
    *image;

  MagickBooleanType
    status;

  MemoryInfo
    *pixel_info;

  PangoAlignment
    align;

  PangoContext
    *context;

  PangoFontMap
    *fontmap;

  PangoGravity
    gravity;

  PangoLayout
    *layout;

  PangoRectangle
    extent;

  PixelPacket
    fill_color;

  RectangleInfo
    page;

  register unsigned char
    *p;

  size_t
    stride;

  ssize_t
    y;

  unsigned char
    *pixels;

  /*
    Initialize Image structure.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info);
  (void) ResetImagePage(image,"0x0+0+0");
  /*
    Format caption.
  */
  option=GetImageOption(image_info,"filename");
  if (option == (const char *) NULL)
    property=InterpretImageProperties(image_info,image,image_info->filename);
  else
    if (LocaleNCompare(option,"pango:",6) == 0)
      property=InterpretImageProperties(image_info,image,option+6);
    else
      property=InterpretImageProperties(image_info,image,option);
  (void) SetImageProperty(image,"caption",property);
  property=DestroyString(property);
  caption=ConstantString(GetImageProperty(image,"caption"));
  /*
    Get context.
  */
  fontmap=pango_cairo_font_map_new();
  pango_cairo_font_map_set_resolution(PANGO_CAIRO_FONT_MAP(fontmap),
    image->x_resolution == 0.0 ? 90.0 : image->x_resolution);
  font_options=cairo_font_options_create();
  option=GetImageOption(image_info,"pango:hinting");
  if (option != (const char *) NULL)
    {
      if (LocaleCompare(option,"none") != 0)
        cairo_font_options_set_hint_style(font_options,CAIRO_HINT_STYLE_NONE);
      if (LocaleCompare(option,"full") != 0)
        cairo_font_options_set_hint_style(font_options,CAIRO_HINT_STYLE_FULL);
    }
  context=pango_font_map_create_context(fontmap);
  pango_cairo_context_set_font_options(context,font_options);
  cairo_font_options_destroy(font_options);
  option=GetImageOption(image_info,"pango:language");
  if (option != (const char *) NULL)
    pango_context_set_language(context,pango_language_from_string(option));
  draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
  pango_context_set_base_dir(context,draw_info->direction ==
    RightToLeftDirection ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR);
  switch (draw_info->gravity)
  {
    case NorthGravity:
    {
      gravity=PANGO_GRAVITY_NORTH;
      break;
    }
    case NorthWestGravity:
    case WestGravity:
    case SouthWestGravity:
    {
      gravity=PANGO_GRAVITY_WEST;
      break;
    }
    case NorthEastGravity:
    case EastGravity:
    case SouthEastGravity:
    {
      gravity=PANGO_GRAVITY_EAST;
      break;
    }
    case SouthGravity:
    {
      gravity=PANGO_GRAVITY_SOUTH;
      break;
    }
    default:
    {
      gravity=PANGO_GRAVITY_AUTO;
      break;
    }
  }
  pango_context_set_base_gravity(context,gravity);
  option=GetImageOption(image_info,"pango:gravity-hint");
  if (option != (const char *) NULL)
    {
      if (LocaleCompare(option,"line") == 0)
        pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_LINE);
      if (LocaleCompare(option,"natural") == 0)
        pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_NATURAL);
      if (LocaleCompare(option,"strong") == 0)
        pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_STRONG);
    }
  /*
    Configure layout.
  */
  layout=pango_layout_new(context);
  option=GetImageOption(image_info,"pango:auto-dir");
  if (option != (const char *) NULL)
    pango_layout_set_auto_dir(layout,1);
  option=GetImageOption(image_info,"pango:ellipsize");
  if (option != (const char *) NULL)
    {
      if (LocaleCompare(option,"end") == 0)
        pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_END);
      if (LocaleCompare(option,"middle") == 0)
        pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_MIDDLE);
      if (LocaleCompare(option,"none") == 0)
        pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_NONE);
      if (LocaleCompare(option,"start") == 0)
        pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_START);
    }
  option=GetImageOption(image_info,"pango:justify");
  if ((option != (const char *) NULL) && (IsMagickTrue(option) != MagickFalse))
    pango_layout_set_justify(layout,1);
  option=GetImageOption(image_info,"pango:single-paragraph");
  if ((option != (const char *) NULL) && (IsMagickTrue(option) != MagickFalse))
    pango_layout_set_single_paragraph_mode(layout,1);
  option=GetImageOption(image_info,"pango:wrap");
  if (option != (const char *) NULL)
    {
      if (LocaleCompare(option,"char") == 0)
        pango_layout_set_wrap(layout,PANGO_WRAP_CHAR);
      if (LocaleCompare(option,"word") == 0)
        pango_layout_set_wrap(layout,PANGO_WRAP_WORD);
      if (LocaleCompare(option,"word-char") == 0)
        pango_layout_set_wrap(layout,PANGO_WRAP_WORD_CHAR);
    }
  option=GetImageOption(image_info,"pango:indent");
  if (option != (const char *) NULL)
    pango_layout_set_indent(layout,(int) ((StringToLong(option)*
      (image->x_resolution == 0.0 ? 90.0 : image->x_resolution)*PANGO_SCALE+45)/
      90.0+0.5));
  switch (draw_info->align)
  {
    case CenterAlign: align=PANGO_ALIGN_CENTER; break;
    case RightAlign: align=PANGO_ALIGN_RIGHT; break;
    case LeftAlign: align=PANGO_ALIGN_LEFT; break;
    default:
    {
      if (draw_info->gravity == CenterGravity)
        {
          align=PANGO_ALIGN_CENTER;
          break;
        }
      align=PANGO_ALIGN_LEFT;
      break;
    }
  }
  if ((align != PANGO_ALIGN_CENTER) &&
      (draw_info->direction == RightToLeftDirection))
    align=(PangoAlignment) (PANGO_ALIGN_LEFT+PANGO_ALIGN_RIGHT-align);
  pango_layout_set_alignment(layout,align);
  if (draw_info->font != (char *) NULL)
    {
      PangoFontDescription
        *description;

      /*
        Set font.
      */
      description=pango_font_description_from_string(draw_info->font);
      pango_font_description_set_size(description,(int) (PANGO_SCALE*
        draw_info->pointsize+0.5));
      pango_layout_set_font_description(layout,description);
      pango_font_description_free(description);
    }
  option=GetImageOption(image_info,"pango:markup");
  if ((option != (const char *) NULL) && (IsMagickTrue(option) == MagickFalse))
    pango_layout_set_text(layout,caption,-1);
  else
    {
      GError
        *error;

      error=(GError *) NULL;
      if (pango_parse_markup(caption,-1,0,NULL,NULL,NULL,&error) == 0)
        (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
          error->message,"`%s'",image_info->filename);
      pango_layout_set_markup(layout,caption,-1);
    }
  pango_layout_context_changed(layout);
  page.x=0;
  page.y=0;
  if (image_info->page != (char *) NULL)
    (void) ParseAbsoluteGeometry(image_info->page,&page);
  if (image->columns == 0)
    {
      pango_layout_get_extents(layout,NULL,&extent);
      image->columns=(extent.x+extent.width+PANGO_SCALE/2)/PANGO_SCALE+2*page.x;
    }
  else
    {
      image->columns-=2*page.x;
      pango_layout_set_width(layout,(int) ((PANGO_SCALE*image->columns*
        (image->x_resolution == 0.0 ? 90.0 : image->x_resolution)+45.0)/90.0+
        0.5));
    }
  if (image->rows == 0)
    {
      pango_layout_get_extents(layout,NULL,&extent);
      image->rows=(extent.y+extent.height+PANGO_SCALE/2)/PANGO_SCALE+2*page.y;
    }
  else
    {
      image->rows-=2*page.y;
      pango_layout_set_height(layout,(int) ((PANGO_SCALE*image->rows*
        (image->y_resolution == 0.0 ? 90.0 : image->y_resolution)+45.0)/90.0+
        0.5));
    }
  /*
    Render markup.
  */
  stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,
    image->columns);
  pixel_info=AcquireVirtualMemory(image->rows,stride*sizeof(*pixels));
  if (pixel_info == (MemoryInfo *) NULL)
    {
      draw_info=DestroyDrawInfo(draw_info);
      caption=DestroyString(caption);
      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
    }
  pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
  surface=cairo_image_surface_create_for_data(pixels,CAIRO_FORMAT_ARGB32,
    image->columns,image->rows,stride);
  cairo_image=cairo_create(surface);
  cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);
  cairo_paint(cairo_image);
  cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);
  cairo_translate(cairo_image,page.x,page.y);
  pango_cairo_show_layout(cairo_image,layout);
  cairo_destroy(cairo_image);
  cairo_surface_destroy(surface);
  g_object_unref(layout);
  g_object_unref(fontmap);
  /*
    Convert surface to image.
  */
  (void) SetImageBackgroundColor(image);
  p=pixels;
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    register PixelPacket
      *q;

    register ssize_t
      x;

    q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
    if (q == (PixelPacket *) NULL)
      break;
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      double
        gamma;

      fill_color.blue=ScaleCharToQuantum(*p++);
      fill_color.green=ScaleCharToQuantum(*p++);
      fill_color.red=ScaleCharToQuantum(*p++);
      fill_color.opacity=QuantumRange-ScaleCharToQuantum(*p++);
      /*
        Disassociate alpha.
      */
      gamma=1.0-QuantumScale*fill_color.opacity;
      gamma=PerceptibleReciprocal(gamma);
      fill_color.blue*=gamma;
      fill_color.green*=gamma;
      fill_color.red*=gamma;
      MagickCompositeOver(&fill_color,fill_color.opacity,q,(MagickRealType)
        q->opacity,q);
      q++;
    }
    if (SyncAuthenticPixels(image,exception) == MagickFalse)
      break;
    if (image->previous == (Image *) NULL)
      {
        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
        image->rows);
        if (status == MagickFalse)
          break;
      }
  }
  /*
    Relinquish resources.
  */
  pixel_info=RelinquishVirtualMemory(pixel_info);
  draw_info=DestroyDrawInfo(draw_info);
  caption=DestroyString(caption);
  return(GetFirstImageInList(image));
}
#endif

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e g i s t e r P A N G O I m a g e                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  RegisterPANGOImage() adds attributes for the Pango Markup Language format to
%  the list of supported formats.  The attributes include the image format
%  tag, a method to read and/or write the format, whether the format
%  supports the saving of more than one frame to the same file or blob,
%  whether the format supports native in-memory I/O, and a brief
%  description of the format.
%
%  The format of the RegisterPANGOImage method is:
%
%      size_t RegisterPANGOImage(void)
%
*/
ModuleExport size_t RegisterPANGOImage(void)
{
  char
    version[MaxTextExtent];

  MagickInfo
    *entry;

  *version='\0';
#if defined(PANGO_VERSION_STRING)
  (void) FormatLocaleString(version,MaxTextExtent,"Pangocairo %s",
    PANGO_VERSION_STRING);
#endif
  entry=SetMagickInfo("PANGO");
#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)
  entry->decoder=(DecodeImageHandler *) ReadPANGOImage;
#endif
  entry->description=ConstantString("Pango Markup Language");
  if (*version != '\0')
    entry->version=ConstantString(version);
  entry->adjoin=MagickFalse;
  entry->module=ConstantString("PANGO");
  (void) RegisterMagickInfo(entry);
  return(MagickImageCoderSignature);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   U n r e g i s t e r P A N G O I m a g e                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  UnregisterPANGOImage() removes format registrations made by the Pango module
%  from the list of supported formats.
%
%  The format of the UnregisterPANGOImage method is:
%
%      UnregisterPANGOImage(void)
%
*/
ModuleExport void UnregisterPANGOImage(void)
{
  (void) UnregisterMagickInfo("PANGO");
}


text:
namespace sky {
namespace shell {

class Internals : public base::SupportsUserData::Data {
 public:
  virtual ~Internals();

  static void Create(Dart_Isolate isolate,
                     mojo::ServiceProviderPtr service_provider);

  mojo::Handle TakeServicesProvidedByEmbedder();

 private:
  explicit Internals(mojo::ServiceProviderPtr service_provider);

  mojo::ServiceProviderPtr service_provider_;

  MOJO_DISALLOW_COPY_AND_ASSIGN(Internals);
};

}  // namespace shell
}  // namespace sky

#endif  // SKY_SHELL_UI_INTERNALS_H_


text:
namespace boost_range_test
{
    namespace
    {

class single_pass_iterator
        : public boost::iterator_facade<
            single_pass_iterator,
            boost::int32_t,
            boost::single_pass_traversal_tag,
            const boost::int32_t&
        >
{
    friend class boost::iterator_core_access;

    typedef std::vector<boost::int32_t>::const_iterator iterator_t;

public:
    single_pass_iterator() { }

    explicit single_pass_iterator(iterator_t it)
        : m_it(it)
    {
    }

private:
    void increment()
    {
        ++m_it;
    }

    bool equal(single_pass_iterator other) const
    {
        return m_it == other.m_it;
    }

    reference dereference() const
    {
        return *m_it;
    }

    iterator_t m_it;
};

class bidirectional_iterator
        : public boost::iterator_facade<
            bidirectional_iterator,
            boost::int32_t,
            boost::bidirectional_traversal_tag,
            const boost::int32_t&
        >
{
    friend class boost::iterator_core_access;

    typedef std::vector<boost::int32_t>::const_iterator iterator_t;

public:
    bidirectional_iterator() { }

    explicit bidirectional_iterator(iterator_t it)
        : m_it(it)
    {
    }

private:
    void increment()
    {
        ++m_it;
    }

    void decrement()
    {
        --m_it;
    }

    bool equal(bidirectional_iterator other) const
    {
        return m_it == other.m_it;
    }

    reference dereference() const
    {
        return *m_it;
    }

    iterator_t m_it;
};

template<typename SinglePassRange>
boost::iterator_range<single_pass_iterator>
single_pass_range(const SinglePassRange& rng)
{
    return boost::iterator_range<single_pass_iterator>(
                single_pass_iterator(boost::begin(rng)),
                single_pass_iterator(boost::end(rng)));
}

template<typename BidirectionalRange>
boost::iterator_range<bidirectional_iterator>
bidirectional_range(const BidirectionalRange& rng)
{
    return boost::iterator_range<bidirectional_iterator>(
                bidirectional_iterator(boost::begin(rng)),
                bidirectional_iterator(boost::end(rng)));
}

void test_drop_front()
{
    std::vector<boost::int32_t> v;
    std::vector<boost::int32_t> ref_output;

    for (boost::int32_t i = 0; i < 10; ++i)
    {
        v.push_back(i);
        ref_output.push_back(i);
    }

    boost::iterator_range<single_pass_iterator> rng = single_pass_range(v);

    BOOST_CHECK_EQUAL_COLLECTIONS(rng.begin(), rng.end(),
                                  ref_output.begin(), ref_output.end());

    rng.drop_front();

    ref_output.erase(ref_output.begin());

    BOOST_CHECK_EQUAL_COLLECTIONS(rng.begin(), rng.end(),
                                  ref_output.begin(), ref_output.end());

    rng.drop_front(5);

    ref_output.erase(ref_output.begin(), ref_output.begin() + 5);

    BOOST_CHECK_EQUAL_COLLECTIONS(rng.begin(), rng.end(),
                                  ref_output.begin(), ref_output.end());
}

void test_drop_back()
{
    std::vector<boost::int32_t> v;
    std::vector<boost::int32_t> ref_output;

    for (boost::int32_t i = 0; i < 10; ++i)
    {
        v.push_back(i);
        ref_output.push_back(i);
    }

    boost::iterator_range<bidirectional_iterator> rng = bidirectional_range(v);

    BOOST_CHECK_EQUAL_COLLECTIONS(rng.begin(), rng.end(),
                                  ref_output.begin(), ref_output.end());

    rng.drop_back();

    ref_output.pop_back();

    BOOST_CHECK_EQUAL_COLLECTIONS(rng.begin(), rng.end(),
                                  ref_output.begin(), ref_output.end());

    rng.drop_back(5);

    ref_output.erase(ref_output.end() - 5, ref_output.end());

    BOOST_CHECK_EQUAL_COLLECTIONS(rng.begin(), rng.end(),
                                  ref_output.begin(), ref_output.end());
}

    } // anonymous namespace
} // namespace boost_range_test

boost::unit_test::test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    boost::unit_test::test_suite* test =
        BOOST_TEST_SUITE("Boost.Range iterator_range drop functions");

    test->add(BOOST_TEST_CASE(&boost_range_test::test_drop_front));
    test->add(BOOST_TEST_CASE(&boost_range_test::test_drop_back));

    return test;
}


text:
from zendesk import resources

SINGULAR_NOUN_MAP = {
    'group': resources.Group,
    'organization': resources.Organization,
    'ticket': resources.Ticket,
    'ticket_form': resources.TicketForm,
    'user': resources.User,
    'upload': resources.Upload,
}

def map_result_type(client, data):
    return SINGULAR_NOUN_MAP[data['result_type']](client, data)

PLURAL_NOUN_MAP = {
    'audits': resources.TicketAudit,
    'comments': resources.TicketComment,
    'groups': resources.Group,
    'organizations': resources.Organization,
    'results': map_result_type,
    'tickets': resources.Ticket,
    'ticket_fields': resources.TicketField,
    'ticket_forms': resources.TicketForm,
    'users': resources.User,
}

def map_single(noun):
    def outer(func):
        def inner(client, *args, **kwargs):
            data = func(client, *args, **kwargs)
            return SINGULAR_NOUN_MAP[noun](client, data[noun])

        return inner

    return outer

def map_paged(noun):
    def outer(func):
        def inner(client, *args, **kwargs):
            for page in func(client, *args, **kwargs):
                for data in page[noun]:
                    yield PLURAL_NOUN_MAP[noun](client, data)

        return inner

    return outer

__ALL__ = ['map_single', 'map_paged']


text:
<?php $v=$view->row();?>

                Name *
                <input type="text" name="name" id="name" class="form-control" placeholder="Name of Consignor" required=""  value="<?=$v->name?>">

                Contact  No-1
                <input type="text" name="phone1" id="name" class="form-control"  placeholder=" Enter Contact  No-1"  value="<?=$v->phone1?>">

                Contact  No-2
                <input type="text" name="phone2" id="name" class="form-control"  placeholder=" Enter Contact  No-2 "  value="<?=$v->phone2?>">

                Email ID-1
                <input type="email" name="email1" id="contactemail" placeholder=" Enter Email ID-1"class="form-control"  value="<?=$v->email1?>">

                Email ID-2
                <input type="email" name="email2" id="contactemail"  placeholder=" Enter Email ID-2" class="form-control" value="<?=$v->email2?>">

                Address 1 *
                <input type="text" name="addressline1" id="contactemail" placeholder=" Enter Address 1" required class="form-control"  value="<?=$v->addressline1?>">

                Address 2
                <input type="text" name="addressline2" id="contactemail" placeholder=" Enter Address 2" class="form-control"  value="<?=$v->addressline2?>">

                City *
                <input type="text" name="city" id="city" placeholder=" Enter City" required class="form-control"  value="<?=$v->city?>">

                State  *
                <input type="text" name="state" id="state" class="form-control"placeholder=" Enter State" required  value="<?=$v->state?>">

                Country *
                <input type="text" name="country" id="country" class="form-control" placeholder=" Enter Country" required  value="<?=$v->country?>">

                Fax
                <input type="text" name="fax" id="fax" class="form-control" placeholder=" Enter Fax"   value="<?=$v->fax?>">

                Website
                <input type="text" name="website" id="name" class="form-control" placeholder=" Enter Website"  value="<?=$v->website?>">


text:
module Lex where

data Token = TokLiteral String
           | TokEqual
           | TokLambda
           | TokPeriod
           | TokSemicolon
           | TokWhitespace
           | TokLBracket
           | TokRBracket

instance Show Token where
  show = stringify

-- convert Token to String
stringify :: Token -> String
stringify (TokLiteral s) = s
stringify TokEqual       = " = "
stringify TokLambda      = "\\"
stringify TokPeriod      = ". "
stringify TokSemicolon   = ";\n"
stringify TokWhitespace  = " "
stringify TokLBracket    = "("
stringify TokRBracket    = ")"

data TokenList = TokenList [Token]

stringify_list :: TokenList -> String
stringify_list (TokenList lst) = concat $ map stringify $ padout lst

instance Show TokenList where
  show = stringify_list

-- add whitespace tokens between adjacent TokLiteral
padout :: [Token] -> [Token]
padout toks = padout_inner toks []

padout_inner :: [Token] -> [Token] -> [Token]
padout_inner [] toks = reverse toks
padout_inner ((TokLiteral l):ltoks) ((TokLiteral r):rtoks) = padout_inner ltoks ((TokLiteral l):(TokWhitespace):(TokLiteral r):rtoks)
padout_inner (l:ltoks) rtoks = padout_inner ltoks (l:rtoks)

lex :: String -> TokenList
lex str = res
  where res = TokenList $ strip_whitespace $ lex_inner str "" []

lex_inner :: String -> String -> [Token] -> [Token]
lex_inner    ""        ""        toks                    = reverse toks
lex_inner    ""        cur       toks                    = reverse $ (tokenize cur):toks
lex_inner    (c:str)   ""        toks                    = lex_inner str [c]        toks
lex_inner    (c:str)   cur       toks    | consume c cur = lex_inner str (cur++[c]) toks
lex_inner    (c:str)   cur       toks                    = lex_inner str [c]        $(tokenize cur):toks

-- given a char and a string, is this char a valid extension of this string
-- aka should I consume the char adding it to the string
-- if true -> add them together, carry on lexing
-- if false -> stop, finish string, then carrying on lexing from char
consume :: Char -> String -> Bool
consume '\\' _    = False
consume '.'  _    = False
consume ';'  _    = False
consume '='  _    = False
consume ' '  _    = False
consume '\t' _    = False
consume '\n' _    = False
consume '(' _     = False
consume ')' _     = False
consume _    "\\" = False
consume _    "."  = False
consume _    ";"  = False
consume _    "="  = False
consume _    " "  = False
consume _    "\t" = False
consume _    "\n" = False
consume _    "("  = False
consume _    ")"  = False
consume _    _    = True

tokenize :: String -> Token
tokenize "\\" = TokLambda
tokenize "."  = TokPeriod
tokenize ";"  = TokSemicolon
tokenize "="  = TokEqual
tokenize "("  = TokLBracket
tokenize ")"  = TokRBracket
tokenize " "  = TokWhitespace
tokenize "\t" = TokWhitespace
tokenize "\n" = TokWhitespace
tokenize s    = TokLiteral s

-- remove TokWhitespace
strip_whitespace :: [Token] -> [Token]
strip_whitespace toks = strip_whitespace_inner toks []

strip_whitespace_inner :: [Token] -> [Token] -> [Token]
strip_whitespace_inner []                    toks = reverse toks
strip_whitespace_inner (TokWhitespace:rtoks) toks = strip_whitespace_inner rtoks toks
strip_whitespace_inner (t:            rtoks) toks = strip_whitespace_inner rtoks (t:toks)


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.browser_ui.modaldialog;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.doesNotExist;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withText;

import static org.hamcrest.Matchers.not;

import static org.chromium.components.browser_ui.modaldialog.ModalDialogTestUtils.checkCurrentPresenter;
import static org.chromium.components.browser_ui.modaldialog.ModalDialogTestUtils.checkDialogDismissalCause;
import static org.chromium.components.browser_ui.modaldialog.ModalDialogTestUtils.checkPendingSize;
import static org.chromium.components.browser_ui.modaldialog.ModalDialogTestUtils.createDialog;
import static org.chromium.components.browser_ui.modaldialog.ModalDialogTestUtils.showDialog;

import android.app.Activity;
import android.graphics.Color;
import android.view.View;
import android.widget.Button;

import androidx.test.espresso.Espresso;
import androidx.test.espresso.matcher.BoundedMatcher;
import androidx.test.filters.SmallTest;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.BaseActivityTestRule;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.Feature;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.ui.modaldialog.DialogDismissalCause;
import org.chromium.ui.modaldialog.ModalDialogManager;
import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogType;
import org.chromium.ui.modaldialog.ModalDialogProperties;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.test.util.DisableAnimationsTestRule;
import org.chromium.ui.test.util.DummyUiActivity;

/**
 * Tests for {@link AppModalPresenter}.
 */
@RunWith(BaseJUnit4ClassRunner.class)
@Batch(Batch.PER_CLASS)
public class AppModalPresenterTest {
    @ClassRule
    public static DisableAnimationsTestRule disableAnimationsRule = new DisableAnimationsTestRule();
    @ClassRule
    public static BaseActivityTestRule<DummyUiActivity> activityTestRule =
            new BaseActivityTestRule<>(DummyUiActivity.class);

    private class TestObserver implements ModalDialogTestUtils.TestDialogDismissedObserver {
        public final CallbackHelper onDialogDismissedCallback = new CallbackHelper();

        @Override
        public void onDialogDismissed(int dismissalCause) {
            onDialogDismissedCallback.notifyCalled();
            checkDialogDismissalCause(mExpectedDismissalCause, dismissalCause);
        }
    }

    private static Activity sActivity;
    private static ModalDialogManager sManager;
    private TestObserver mTestObserver;
    private Integer mExpectedDismissalCause;

    @BeforeClass
    public static void setupSuite() {
        activityTestRule.launchActivity(null);
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            sActivity = activityTestRule.getActivity();
            sManager = new ModalDialogManager(
                    new AppModalPresenter(sActivity), ModalDialogManager.ModalDialogType.APP);
        });
    }

    @Before
    public void setupTest() {
        mTestObserver = new TestObserver();
    }

    @After
    public void tearDown() {
        TestThreadUtils.runOnUiThreadBlocking(sManager::destroy);
    }

    @Test
    @SmallTest
    @Feature({"ModalDialog"})
    public void testDismiss_BackPressed() throws Exception {
        PropertyModel dialog1 = createDialog(sActivity, sManager, "1", null);
        PropertyModel dialog2 = createDialog(sActivity, sManager, "2", null);

        // Initially there are no dialogs in the pending list. Browser controls are not restricted.
        checkPendingSize(sManager, ModalDialogType.APP, 0);
        checkCurrentPresenter(sManager, null);

        // Add three dialogs available for showing. The app modal dialog should be shown first.
        showDialog(sManager, dialog1, ModalDialogType.APP);
        showDialog(sManager, dialog2, ModalDialogType.APP);
        checkPendingSize(sManager, ModalDialogType.APP, 1);
        onView(withText("1")).check(matches(isDisplayed()));
        checkCurrentPresenter(sManager, ModalDialogType.APP);

        // Perform back press. The first app modal dialog should be dismissed, and the second one
        // should be shown.
        Espresso.pressBack();
        checkPendingSize(sManager, ModalDialogType.APP, 0);
        onView(withText("1")).check(doesNotExist());
        onView(withText("2")).check(matches(isDisplayed()));
        checkCurrentPresenter(sManager, ModalDialogType.APP);

        // Perform a second back press. The second app modal dialog should be dismissed.
        Espresso.pressBack();
        checkPendingSize(sManager, ModalDialogType.APP, 0);
        onView(withText("2")).check(doesNotExist());
        checkCurrentPresenter(sManager, null);
    }

    @Test
    @SmallTest
    @Feature({"ModalDialog"})
    public void testDismiss_DismissalCause_BackPressed() throws Exception {
        PropertyModel dialog1 = createDialog(sActivity, sManager, "1", mTestObserver);
        mExpectedDismissalCause = DialogDismissalCause.NAVIGATE_BACK_OR_TOUCH_OUTSIDE;

        showDialog(sManager, dialog1, ModalDialogType.APP);

        // Dismiss the tab modal dialog and verify dismissal cause.
        int callCount = mTestObserver.onDialogDismissedCallback.getCallCount();
        Espresso.pressBack();
        mTestObserver.onDialogDismissedCallback.waitForCallback(callCount);

        mExpectedDismissalCause = null;
    }

    @Test
    @SmallTest
    @Feature({"ModalDialog"})
    public void testButton_negativeButtonFilled() throws Exception {
        PropertyModel dialog1 = createDialog(sActivity, sManager, "1", mTestObserver,
                ModalDialogProperties.ButtonStyles.PRIMARY_OUTLINE_NEGATIVE_FILLED);
        showDialog(sManager, dialog1, ModalDialogType.APP);
        onView(withText(R.string.cancel)).check(matches(hasCurrentTextColor(Color.WHITE)));
        onView(withText(R.string.ok)).check(matches(not(hasCurrentTextColor(Color.WHITE))));
    }

    @Test
    @SmallTest
    @Feature({"ModalDialog"})
    public void testButton_primaryButtonFilled() throws Exception {
        PropertyModel dialog1 = createDialog(sActivity, sManager, "1", mTestObserver,
                ModalDialogProperties.ButtonStyles.PRIMARY_FILLED_NEGATIVE_OUTLINE);
        showDialog(sManager, dialog1, ModalDialogType.APP);
        onView(withText(R.string.cancel)).check(matches(not(hasCurrentTextColor(Color.WHITE))));
        onView(withText(R.string.ok)).check(matches(hasCurrentTextColor(Color.WHITE)));
    }

    private static Matcher<View> hasCurrentTextColor(int expected) {
        return new BoundedMatcher<View, Button>(Button.class) {
            private int mColor;
            @Override
            public boolean matchesSafely(Button button) {
                mColor = button.getCurrentTextColor();
                return expected == mColor;
            }
            @Override
            public void describeTo(final Description description) {
                description.appendText("Color did not match " + mColor);
            }
        };
    }
}


text:
package com.yue.demo.desktop;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.yue.demo.R;
import com.yue.demo.util.LogUtil;

/**
 * 桌面控件之液晶时钟
 * @author chengyue
 *
 */
public class LedClock extends AppWidgetProvider {
	private final String TAG = LedClock.class.getSimpleName();
	private Timer timer = new Timer();
	private AppWidgetManager appWidgetManager;
	private Context context;
	// 将0~9的液晶数字图片定义成数组
	private int[] digits = new int[] { R.drawable.su01, R.drawable.su02,
			R.drawable.su03, R.drawable.su04, R.drawable.su05, R.drawable.su06,
			R.drawable.su07, R.drawable.su08, R.drawable.su09, R.drawable.su10, };
	// 将显示小时、分钟、秒钟的ImageView定义成数组
	private int[] digitViews = new int[] { R.id.img01, R.id.img02, R.id.img04,
			R.id.img05, R.id.img07, R.id.img08 };

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		LogUtil.d(TAG, "----onUpdate----");
		Toast.makeText(context, "onUpdate", Toast.LENGTH_SHORT).show();
		this.appWidgetManager = appWidgetManager;
		this.context = context;
		// 定义计时器
		timer = new Timer();
		// 启动周期性调度
		timer.schedule(new TimerTask() {
			public void run() {
				// 发送空消息,通知界面更新
				handler.sendEmptyMessage(0x123);
			}
		}, 0, 1000);
		LogUtil.d(TAG, "----onUpdate end----");
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0x123) {
				RemoteViews views = new RemoteViews(context.getPackageName(),
						R.layout.led_lock);
				// 定义SimpleDateFormat对象
				SimpleDateFormat df = new SimpleDateFormat("HHmmss");
				// 将当前时间格式化成HHmmss的形式
				String timeStr = df.format(new Date());
				for (int i = 0; i < timeStr.length(); i++) {
					// 将第i个数字字符转换为对应的数字
					int num = timeStr.charAt(i) - 48;
					// 将第i个图片的设为对应的液晶数字图片
					views.setImageViewResource(digitViews[i], digits[num]);
				}
				// 将AppWidgetProvider子类实例包装成ComponentName对象
				ComponentName componentName = new ComponentName(context,
						LedClock.class);
				// 调用AppWidgetManager将remoteViews添加到ComponentName中
				appWidgetManager.updateAppWidget(componentName, views);
			}
			super.handleMessage(msg);
		}
	};
}


text:
import { after, afterEach, before } from '@ephox/bedrock-client';
import { Fun } from '@ephox/katamari';

import DOMUtils from 'tinymce/core/api/dom/DOMUtils';

interface ViewBlock {
  readonly attach: (preventDuplicates?: boolean) => void;
  readonly detach: () => void;
  readonly update: (html: string) => void;
  readonly get: () => HTMLElement;
}

const ViewBlock = (): ViewBlock => {
  const domElm = DOMUtils.DOM.create('div', {
    style: 'position: absolute; right: 10px; top: 10px;'
  });

  const attach = (preventDuplicates?: boolean) => {
    if (preventDuplicates && domElm.parentNode === document.body) {
      detach();
    }
    document.body.appendChild(domElm);
  };

  const detach = () => {
    DOMUtils.DOM.remove(domElm);
  };

  const update = (html: string) => {
    DOMUtils.DOM.setHTML(domElm, html);
  };

  const get = Fun.constant(domElm);

  return {
    attach,
    update,
    detach,
    get
  };
};

export const bddSetup = (preventDuplicates?: boolean): ViewBlock => {
  const viewBlock = ViewBlock();
  let hasFailure = false;

  before(() => viewBlock.attach(preventDuplicates));
  afterEach(function () {
    if (this.currentTest?.isFailed() === true) {
      hasFailure = true;
    }
  });
  after(() => {
    if (!hasFailure) {
      viewBlock.detach();
    }
  });
  return viewBlock;
};

export default ViewBlock;


text:
CodeMirror.registerHelper("fold", "comment", function(cm, start) {
  var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
  if (!startToken || !endToken) return;
  var line = start.line, lineText = cm.getLine(line);

  var startCh;
  for (var at = start.ch, pass = 0;;) {
    var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
    if (found == -1) {
      if (pass == 1) return;
      pass = 1;
      at = lineText.length;
      continue;
    }
    if (pass == 1 && found < start.ch) return;
    if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)))) {
      startCh = found + startToken.length;
      break;
    }
    at = found - 1;
  }

  var depth = 1, lastLine = cm.lastLine(), end, endCh;
  outer: for (var i = line; i <= lastLine; ++i) {
    var text = cm.getLine(i), pos = i == line ? startCh : 0;
    for (;;) {
      var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
      if (nextOpen < 0) nextOpen = text.length;
      if (nextClose < 0) nextClose = text.length;
      pos = Math.min(nextOpen, nextClose);
      if (pos == text.length) break;
      if (pos == nextOpen) ++depth;
      else if (!--depth) { end = i; endCh = pos; break outer; }
      ++pos;
    }
  }
  if (end == null || line == end && endCh == startCh) return;
  return {from: CodeMirror.Pos(line, startCh),
          to: CodeMirror.Pos(end, endCh)};
});


text:
namespace Engine {

class FileManagerAndroid;
typedef FileManagerAndroid FileManagerType;

class FileManagerAndroid: public FileManager {
public:
  FileManagerAndroid( AAssetManager *setAssetManager );
  virtual ~FileManagerAndroid();
  virtual bool FileExists( const std::string &fileName ) const;
  virtual bool GetFile( const std::string& fileName, Memory& fileContent, bool endZeroByte = false ) const;

private:
  FileManagerAndroid();
  FileManagerAndroid( FileManagerAndroid& );
  FileManagerAndroid& operator=( FileManagerAndroid& );

  AAssetManager *assetManager;
};

};


text:
This document keeps list of features we want (not yet prioritized).

## Documentation

* examples of running a single tool with a local executor (we have code from the Launcher), helps with development, testing, small-scale running.  Should be part of the dockstore command line.
  * +1
* examples of how to make workflows in CWL that bring together individual tools, and to scale up analysis using cloud orchestration systems like [Consonance](https://github.com/Consonance/)

## New Features

Feature requests are tracked at https://github.com/CancerCollaboratory/dockstore/issues


text:
    Note
    All functions are accessed via the data attribute e.g. $('#datetimepicker').data("DateTimePicker").FUNCTION()

###destroy()

Destroys the widget and removes all attached event listeners

----------------------

### toggle()

Shows or hides the widget

#### Emits

* `dp.hide` - if the widget is hidden after the toggle call

* `dp.show` - if the widget is show after the toggle call

* `dp.change` - if the widget is opened for the first time and the input element is empty and `options.useCurrent != false`

----------------------

### show()

Shows the widget

#### Emits

* `dp.show` - if the widget was hidden before that call

* `dp.change` - if the widget is opened for the first time and the useCurrent is set to true or to a granularity value and the input element the component is attached to has an empty value

----------------------

### hide()

Hides the widget

#### Emits

* `dp.hide` - if the widget was visible before that call

----------------------

### disable()

Disables the input element, the component is attached to, by adding a `disabled="true"` attribute to it. If the widget was visible before that call it is hidden.

#### Emits

* `dp.hide` - if the widget was visible before that call

----------------------

### enable()

Enables the input element, the component is attached to, by removing `disabled` attribute from it.

----------------------

### clear()

Clears the datepicker by setting the value to `null`

### viewDate

4.14.30 Issue #872

#### viewDate()

Returns a `moment` variable with the currently set `options.viewDate` option.

#### viewDate(viewDate)

Takes a `string, moment or Date` value.

This will change the `viewDate` without changing or setting the selected date.


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH.'libraries/REST_Controller.php';

//============ ============  ============  ============
//============ ============  ============  ============
//  GET
// index_get
// Params:
//      Void
// Return
//      list all books
// POST
// ============ ============  ============  ============
// add_book_post
// Params:
//      $title
//      $description
// Return
//      list all books
// ============ ============  ============  ============
// remove_all_book_post
// Params:
//      Void
// Return
//      void
//============ ============  ============  ============
//============ ============  ============  ============

class Book extends REST_Controller {

    private $em = NULL;

    function __construct()
    {
        parent::__construct();
        // uncomment this line if not using CI auto load feature
        //$this->load->library('doctrine');

        $this->em = $this->doctrine->em;
    }

    function index_get()
    {
        $bookRepository = $this->em->getRepository('Entity\Book');
        $books = [];
        if (!$this->get('id'))
        {
            $books = $bookRepository->getAllBookArrays();
        }
        else
        {
            $book = $bookRepository->getBookArrayById($this->get('id'));
            if ($book) $books[] = $book;
            else $this->response(NULL, 404);
        }
        $this->response($books);
    }

    public function add_book_post(){
        $book = new Entity\Book;
        $book->setName($this->input->post('title'));
        $book->setDescription($this->input->post('description'));
        $this->em->persist($book);
        $this->em->flush();
        //echo json_encode(["status"=>"Done"]);
        $this->index_get();
    }

    public function remove_all_book_post(){
        $obj_rm = $this->em->getRepository("Entity\Book")->findAll();
        foreach ($obj_rm as $key => $value) {
            $this->em->remove($value);
        }
        $this->em->flush();
        echo json_encode(["status"=>"Done"]);
    }

}

/* End of file Book.php */
/* Location: ./application/controllers/api/Book.php */