text:
var credentials = require('./credentials.json');

var Discord = require("discord.js");

var bot = new Discord.Client();

bot.on('message', function (message){
    if(message.content === 'cyka') {
        bot.reply(message, ':horse:');
	}
});

bot.on('ready', function () {
	bot.setPlayingGame('League of Legends');
	for (var i = 0; i < bot.channels.length; i++) {
		if (bot.channels[i].name === 'general') {
			bot.sendMessage(bot.channels[i], ':horse:', {}, function (err, message) {
				setInterval(function () {
					bot.updateMessage(message, new Date().toTimeString(), {}, function () {});
				}, 1000);
			});
		}
	}
});

bot.on('userTypingStart', function (user, channel) {
	bot.sendMessage(channel, 'type faster, you fool @' + user.username, {});
});

bot.login(credentials.email, credentials.password);

redpajama_set_name: RedPajamaGithub


text:
def PickScorer(name):
  # For now, just raise KeyError if the scorer doesn't exist.
  scorer_map = {
    'psnr': ScorePsnrBitrate,
    'rt': ScoreCpuPsnr,
  }

  return scorer_map[name]

def ScorePsnrBitrate(target_bitrate, result):
  """Returns the score of a particular encoding result.

  Arguments:
  - target_bitrate: Desired bitrate in kilobits per second
  - result: a dictionary containing the analysis of the encoding.

  In this particular score function, the PSNR and the achieved bitrate
  of the encoding are of interest.
  """
  if not result:
    return None
  score = result['psnr']
  # We penalize bitrates that exceed the target bitrate.
  if result['bitrate'] > int(target_bitrate):
    score -= (result['bitrate'] - int(target_bitrate)) * 0.1
  return score

def ScoreCpuPsnr(target_bitrate, result):
  """Returns the score relevant to interactive usage.

  The constraints are:
  - Stay within the requested bitrate
  - Encode time needs to stay below clip length
  - Decode time needs to stay below clip length
  Otherwise, PSNR rules."""

  # There are cases where we don't know a target bitrate.
  # Return a negative score for these.
  if target_bitrate == 0.0:
    return -1.0
  score = result['psnr']
  # We penalize bitrates that exceed the target bitrate.
  # Score reduction is 0.1 dB per percentage point over target.
  if result['bitrate'] > int(target_bitrate):
    percent_overshoot = 100.0 * ((result['bitrate'] - float(target_bitrate))
        / float(target_bitrate))
    score -= 0.1 * percent_overshoot
  # We penalize CPU usage that exceeds clip time.
  used_time = result['encode_cputime']
  available_time = result['cliptime']

  if used_time > available_time:
    badness = (used_time - available_time) / available_time
    score -= badness * 100
  return score

def DelayCalculation(frame_info_list, framerate, bitrate, buffer_size,
                     print_trace=False):
  """Calculate the total delay in frame delivery for these frames.
  Arguments:
  - frame_info_list: a list of frame information records.
      Each frame information record has the size in bits in the "size" field
  - framerate: frames per second
  - bitrate: integer, bits per second
  - buffer_size: Initial buffer size, in seconds
  Returns:
  Delay as a proportion of total clip time - that is, if the clip is 10s
  long, and the function returns 0.2, the clip will take 12 seconds to play.
  """
  for frame in frame_info_list:
    frame['transmit_time'] = float(frame['size']) / bitrate
  playback_clock = buffer_size
  buffer_clock = 0
  delay = 0
  frame_count = 0
  for frame in frame_info_list:
    buffer_clock += frame['transmit_time'] # time this frame arrives
    playback_clock += 1.0/framerate # time this frame should be played back
    if buffer_clock > playback_clock:
      delay += (buffer_clock - playback_clock)
      if print_trace:
        print 'Frame %d %f behind' % (frame_count,
                                      buffer_clock - playback_clock)
      # In this model, we assume that playback pauses until frame is available.
      # No further delay penalty is imposed on the next frame.
      playback_clock = buffer_clock
    frame_count += 1
  return delay / (float(frame_count) / framerate)


text:
fplutil    {#fplutil}
=======

fplutil is a set of small libraries and tools that can be useful when
developing applications for Android and other platforms.

Download the latest release from the
[fplutil github page](http://github.com/google/fplutil) or the
[releases page](https://github.com/google/fplutil/releases).

**Important**: fplutil uses submodules to reference other components it depends
upon so to download the source use:

~~~{.sh}
    git clone --recursive https://github.com/google/fplutil.git
~~~

   * Discuss fplutil with other developers and users on the
     [fplutil Google Group][].
   * File issues on the [fplutil Issues Tracker][]
     or post your questions to [stackoverflow.com][] with a mention of
     **fplutil**.

Before getting started, make sure all
[prerequisites](@ref fplutil_prerequisites) are installed and configured.

# Components

   * [build_all_android][] is an all-in-one build script that allows you to
     build, install and run native (C/C++) Android apps from the command line.
     This is ideal for build automation, but can also be in a developer's
     compile/run loop.
   * [buildutil][] performs the configuration, build and archive steps
     of [Android][] and [Linux][] C/C++ applications using a suite of
     [Python][] modules.  This suite of modules can automate builds in a
     continuous integration environment.
   * [android_ndk_perf][] is a desktop tool that enables native (C/C++)
     developers to measure the CPU utilization of their applications on
     [Android][], guiding their optimization efforts.
   * [libfplutil][] enables C/C++ developers to write traditional applications
     (like [Hello World][]) using "main()" and "printf()" on [Android][].

  [Android]: http://www.android.com
  [Linux]: http://en.m.wikipedia.org/wiki/Linux
  [Python]: http://www.python.org
  [android_ndk_perf]: @ref android_ndk_perf
  [build_all_android]: @ref build_all_android
  [buildutil]: @ref buildutil_overview
  [fplutil Google Group]: http://groups.google.com/group/fplutil
  [fplutil Issues Tracker]: http://github.com/google/fplutil/issues
  [fplutil]: index.html
  [libfplutil]: @ref libfplutil_overview
  [stackoverflow.com]: http://stackoverflow.com/search?q=fplutil
  [Hello World]: http://en.wikipedia.org/wiki/%22Hello,_world!%22_program


text:
//-----------------------------------------------------------------------
// <copyright file="AppNexusAppRestClient.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using ConfigManager;
using Diagnostics;
using Microsoft.Http;
using Utilities.Cryptography;
using Utilities.Net;
using Utilities.Net.Http;
using Utilities.Storage;

namespace AppNexusClient
{
    /// REST client for AppNexus using credentials from config
    [SuppressMessage("Microsoft.Design", "CA1063", Justification = "IDisposable is correctly implemented by HttpRestClient")]
    public class AppNexusAppRestClient : AppNexusRestClientBase, IAppNexusRestClient
    {
        /// URI for the auth request
        private const string AuthRequestUriFormat = "auth?user_id={0}&plugin_id={1}&signature={2}";

        /// Backing field for AppUserId. DO NOT USE DIRECTLY.
        private string appUserId;

        /// Backing field for CryptoProvider. DO NOT USE DIRECTLY.
        private ICryptoProvider cryptoProvider;

        /// Initializes a new instance of the AppNexusAppRestClient class.
        /// <param name="config">Configuration to use</param>
        public AppNexusAppRestClient(IConfig config)
            : base(config)
        {
        }

        /// Gets a string identifying this AppNexus client
        public override string Id
        {
            get { return this.AppUserId; }
        }

        /// Gets the AppNexus App UserId
        private string AppUserId
        {
            get { return this.appUserId = this.appUserId ?? this.Config.GetValue("AppNexus.App.UserId"); }
        }

        /// Gets the AppNexus App Id
        private string AppId
        {
            get { return this.Config.GetValue("AppNexus.App.AppId"); }
        }

        /// Gets the crypto provider
        private ICryptoProvider CryptoProvider
        {
            get { return this.cryptoProvider = this.cryptoProvider ?? CreateCryptoProvider(); }
        }

        /// Authenticates the REST client
        /// <returns>The new authentication token</returns>
        internal override string Authenticate()
        {
            var signature = this.CreateEncryptedSignature();
            var authRequestUri = AuthRequestUriFormat.FormatInvariant(this.AppUserId, this.AppId, signature);
            var httpResponse = this.Client.Send(new HttpRequestMessage
            {
                Uri = new Uri(this.Client.BaseAddress, authRequestUri),
                Method = HttpMethod.GET.ToString(),
            });

            if (httpResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new AppNexusClientException(
                    "AppNexus Authentication Failed: Status Code: {0}".FormatInvariant(httpResponse.StatusCode),
                    httpResponse.Content.ReadAsString());
            }

            var responseContent = httpResponse.Content.ReadAsString();
            var values = TryGetResponseValues(responseContent);
            if (values == null)
            {
                throw new AppNexusClientException(
                    "Authentication Failed: Unable to get values from response",
                    responseContent);
            }

            if (IsErrorResponse(values))
            {
                var exception = new AppNexusClientException(
                    "AppNexus Authentication Failed",
                    responseContent,
                    values);
                if (exception.ErrorId == AppNexusErrorId.System &&
                    exception.ErrorMessage.Contains(AuthLimitExceededErrorMessage))
                {
                    // Authentication limit has been exceeded
                    // Sleep until the auth limit period has passed
                    Thread.Sleep(AuthLimitPeriodSeconds * 1000);
                }

                throw exception;
            }

            if (!values.ContainsKey(AppNexusValues.AuthToken))
            {
                throw new AppNexusClientException(
                    "AppNexus Authentication Failed (response did not contain an auth token)",
                    responseContent,
                    values);
            }

            return values[AppNexusValues.AuthToken] as string;
        }

        /// Create the crypto provider
        /// <remarks>
        /// TODO: Create and use a static CryptoManager to get the ICryptoProvider instance
        /// registered in the RunTimeIoc and resolved in the role initialization.
        /// </remarks>
        /// <returns>The crypto provider</returns>
        private static ICryptoProvider CreateCryptoProvider()
        {
            return new Utilities.Cryptography.OpenSsl.OpenSslCryptoProvider();
        }

        /// Gets the AppNexus App private key from config
        /// <remarks>
        /// TODO: Retrieve the key from the system certificate store instead.
        /// </remarks>
        /// <returns>A container with the private key</returns>
        private IKeyContainer ReadPrivateKeyFromConfig()
        {
            var privateKeyPem = this.Config.GetValue("AppNexus.App.PrivateKey");
            var keyContainer = this.CryptoProvider.CreatePemKeyContainer();
            keyContainer.ReadPem(privateKeyPem);
            return keyContainer;
        }

        /// Creates a base-64, encrypted signature for AppNexus auth
        /// <remarks>
        /// Combines seconds since unix epoch with the user's AppNexus user id and signs it with
        /// the private key corresponding to the public key that has been provided to AppNexus.
        /// </remarks>
        /// <seealso href="https://wiki.appnexus.com/display/apps/3.2+-+Get+your+app+on+Sand+and+Authenticate+with+AppNexus#3.2-GetyourapponSandandAuthenticatewithAppNexus-ObtaininganAuthenticationToken"/>
        /// <returns>The encrypted signature</returns>
        private string CreateEncryptedSignature()
        {
            var rsa = this.CryptoProvider.CreateCipherEngine("RSA");
            rsa.KeyContainer = this.ReadPrivateKeyFromConfig();

            var time = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            var signatureText = "{0}|{1}".FormatInvariant(time, this.AppUserId);
            var signatureBytes = Encoding.UTF8.GetBytes(signatureText);

            var encryptedSignature = rsa.Encrypt(signatureBytes);
            var signatureBase64 = Convert.ToBase64String(encryptedSignature);
            return signatureBase64;
        }
    }
}


text:
import logging
import os
from aiohttp.web import Application
from .jinja import *
from wolverine.module import MicroModule

__all__ = (jinja.__all__,)

logger = logging.getLogger(__name__)

class WebModule(MicroModule, Application):

    def __init__(self):
        super().__init__()
        self.name = 'web'
        self.default_settings = os.path.join(__path__[0],
                                             'settings.ini')

    def register(self, app):
        self.app = app
        app.config.read(self.default_settings)

    def read_config(self):
        config = self.app.config[self.name.upper()]
        self.http_host = config.get('HTTP_HOST')
        self.http_port = config.get('HTTP_PORT')
        self.static_folder = config.get('STATIC', '/tmp/')

    def init(self):
        logger.info('running the web console')
        self.read_config()
        self.router.add_static('/static', self.static_folder)

    def create_server(self):
        self.http_handler = self.make_handler()
        self.srv = self.app.loop.create_server(
            self.http_handler, self.http_host, self.http_port)
        self.app.loop.create_task(self.srv)

    def stop_server(self):
        yield from self.http_handler.finish_connections(1.0)
        yield from self.shutdown()

    def add_route(self, *args, **kwargs):
        return self.router.add_route(*args, **kwargs)


text:
  'use strict'
  var _ = require('underscore-node')
    var country = {
        "countries": [
            "US",
            "India",
            "China",
            "Japan"
        ]
    }

    var perCountries = {
        "permittedCountries": [
            "US",
            "India"
        ]
    }
    var countries = country.countries;
    var perCountries = perCountries.permittedCountries;
    var nonCountry = _.difference(countries,perCountries)
    console.log(nonCountry)


text:
using UnityEngine;
using System.Collections;

public class LevelSelect : MainMenu
{
	//Inherits from MainMenu class
	void OnGUI()
	{
		GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), backgroundTexture);
		GUI.skin = mySkin;

		//Simple level select system
		if (GUI.Button (new Rect(Screen.width *  0.1f, Screen.height * 0.2f, Screen.width * 0.8f, Screen.height * 0.1f), "Level 1"))
		{
			print ("Clicked Level 1");
			Application.LoadLevel("Level 1");
		}
		if (GUI.Button (new Rect(Screen.width *  0.1f, Screen.height * 0.3f, Screen.width * 0.8f, Screen.height * 0.1f), "Level 2"))
		{
			print ("Clicked Level 2");
			Application.LoadLevel("Level 2");
		}
		if (GUI.Button (new Rect(Screen.width *  0.1f, Screen.height * 0.4f, Screen.width * 0.8f, Screen.height * 0.1f), "Level 3"))
		{
			print ("Clicked Level 3");
			Application.LoadLevel("Level 3");
		}
		if (GUI.Button (new Rect(Screen.width *  0.1f, Screen.height * 0.5f, Screen.width * 0.8f, Screen.height * 0.1f), "Level 4"))
		{
			print ("Clicked Level 4");
			Application.LoadLevel("Level 4");
		}
		if (GUI.Button (new Rect(Screen.width *  0.1f, Screen.height * 0.6f, Screen.width * 0.8f, Screen.height * 0.1f), "Level 5"))
		{
			print ("Clicked Level 5");
			Application.LoadLevel("Level 5");
		}
		if (GUI.Button (new Rect(Screen.width *  0.1f, Screen.height * 0.7f, Screen.width * 0.8f, Screen.height * 0.1f), "Back"))
		{
			print ("Clicked Back");
			Application.LoadLevel("Main Menu");
		}
	}
}


text: SELECT _rowid_, rowid FROM t2 ORDER BY x DESC


text:
<?php

require_once '../repository/SeriesRepository.php';

class PreviewController
{
    private $SeriesRepository;

    public function index($title)
    {
        //  session des Benutzers
        session_start();

        //  views
        $view = new View('preview');
        $view->title = $title;
        $view->heading = $title;

        //  initialisiert das Repository
        $SeriesRepository = new SeriesRepository();

        //  ersetzt '%20' aus der URL durch space, damit der $title in
        //  der Datenbank gefunden wird, dann wird Eintrag[1] des Assoziativen
        //  array ausgelesen, damit man aus der View einfacher zugreifen kann.
        $title = str_replace('-', ' ', $title);
        $a = $SeriesRepository->selectByTitle($title);
        $b = $a[0];

        //  liest ratings der serie aus.
        $id = $b->id;
        $rating = $SeriesRepository->selectRatingById($id);

        //  "wandelt" assoziatives array in normales array um, damit der
        //  Durchschnitt berechnet werden kann. Der $avg wird auf ganze Zahlen
        //  gerundet.
        $avg = 0;
        $avgArray = array();
        foreach ($rating as $r) {
            array_push($avgArray, $r->rating);
        }

        if (array_sum($avgArray) != 0) {
            $avg = round(array_sum($avgArray) / count($avgArray));
        }

        //  holt alle Seasons der Serie
        $c = $SeriesRepository->selectSeasonBySeriesId($id);
        $seasons = $c[0]->seasons;

        $view->check = false;
        if (isset($_SESSION['logedin'])) {
            $view->check = true;
        }

        $view->seasons = $seasons;
        $view->series = $b;
        $view->avg = $avg;

        $view->session = $_SESSION;

        //  view wird gerendert
        $view->display();
    }

    public function comment()
    {

        $ContactRepository = new ContactRepository();

        $view = new View('contact_submited');
        $view->title = 'Contact';
        $view->heading = 'Contact';

        // Save Input in variables
        $message = htmlspecialchars($_POST['message']);

        // Creating the validate-variables
        $fieldsNotEmpty = true;
        $validname = true;
        $validlastname = true;
        $validmail = true;
        $validmessage = true;

        // Check if fields are empty
        if($name == '' || $lastname == '' || $email == '' || $message == '')
        {
            // at least one field is empty
            $fieldsNotEmpty = false;
        }

        // check if name only contains letters and has more than 2 chars
        if (preg_match('/[^A-Za-z]/', $name) || strlen($name) < 3)
        {
            // User is not valid
            $validname = false;
        }

        // check if lastname only contains letters and has more than 2 chars
        if (preg_match('/[^A-Za-z]/', $lastname) || strlen($lastname) < 3)
        {
            // User is not valid
            $validlastname = false;
        }

        // Check if the email is an emailadress
        if (!filter_var($email, FILTER_VALIDATE_EMAIL))
        {
           // Email is not an valid Emailadress
           $validmail = false;
        }

        // check if lastname only contains letters and has more than 2 chars
        if (preg_match('/[^A-Za-z0-9]/', $message) || strlen($message) < 1)
        {
            // User is not valid
            $validmessage = false;
        }

        // Check if all validates are true
        if ($fieldsNotEmpty & $validname & $validlastname & $validmail & $validmessage)
        {
            //Start function for inserting the contactrequest into DB
            $ContactRepository->insertContact($name, $lastname, $email, $message);
            $view->display();
        }
        else{
          $view = new View('contact');
          $view->title = 'Contact';
          $view->heading = 'Contact';
          $view->display();
          if($validname == false){
            echo '
Enter a name with at least 3 bookstamps.
';
          }

          if($validlastname == false){
            echo '
Enter a name with at least 3 bookstamps.
';
          }

          if($validmail == false){
            echo '
Enter a correct email address.
';
          }

          if($validmessage == false){
            echo '
Enter a message containing only numbers and letters.
';
          }

        }
    }
}


text:
#jQuery Selectric ![icon](http://i.imgur.com/D2hcnUN.png)

jQuery Selectric is a jQuery plugin designed to help at stylizing and manipulating HTML selects.

* Keyboard navigation (Up/Down/Left/Right/Word search)
* Easily customizable
* Pretty lightweight (3,4KB minified and less than 2KB minified/gzip)
* Options box always stay visible
* Doesn't rely on external libraries (besides jQuery)
* Word search works with western latin characters set (e.g.: á, ñ, ç...)

###[Demo](http://lcdsantos.github.io/jQuery-Selectric/)

##How to use:

Make sure to include jQuery in your page:

```html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
```

Include **jQuery Selectric:**

```html
<script src="js/jquery.selectric.min.js"></script>
```

Put styles in your CSS and change it to your taste :D

```css
/*======================================================================
  Selectric
======================================================================*/

.selectricWrapper {
  position: relative;
  margin: 0 0 10px;
  width: 300px;
  cursor: pointer;
}

.selectricResponsive {
  width: 100%;
}

.selectric {
  border: 1px solid #DDD;
  background: #F8F8F8;
  position: relative;
  border-radius: 2px;
}

.selectric .label {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  margin: 0 30px 0 0;
  padding: 6px;
  font-size: 12px;
  line-height: 18px;
  color: #444;
  min-height: 18px;
}

.selectric .button {
  display: block;
  position: absolute;
  right: 0;
  top: 0;
  width: 30px;
  height: 30px;
  color: #BBB;
  text-align: center;
  font: 0/0 a;
  /* IE Fix */
  *font: 20px/30px Lucida Sans Unicode, Arial Unicode MS, Arial;
}

.selectric .button:after {
  content: " ";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 0;
  height: 0;
  border: 4px solid transparent;
  border-top-color: #BBB;
  border-bottom: none;
}

.selectricHover .selectric {
  border-color: #CCC;
}

.selectricHover .selectric .button {
  color: #888;
}

.selectricHover .selectric .button:after {
  border-top-color: #888;
}

.selectricOpen {
  z-index: 9999;
}

.selectricOpen .selectric {
  border-color: #CCC;
  background: #F0F0F0;
  z-index: 9999;
}

.selectricOpen .selectricItems {
  display: block;
}

.selectricDisabled {
  filter: alpha(opacity=50);
  opacity: 0.5;
  cursor: default;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.selectricHideSelect {
  position: relative;
  overflow: hidden;
  width: 0;
  height: 0;
}

.selectricHideSelect select {
  position: absolute;
  left: -100%;
  display: none;
}

.selectricInput {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  overflow: hidden !important;
  clip: rect(0, 0, 0, 0) !important;
  margin: 0 !important;
  padding: 0 !important;
  width: 1px !important;
  height: 1px !important;
  outline: none !important;
  border: none !important;
  *font: 0/0 a !important;
  background: none !important;
}

.selectricTempShow {
  position: absolute !important;
  visibility: hidden !important;
  display: block !important;
}

/* Items box */

.selectricItems {
  display: none;
  position: absolute;
  overflow: auto;
  top: 100%;
  left: 0;
  background: #F9F9F9;
  border: 1px solid #CCC;
  z-index: 9998;
  -webkit-box-shadow: 0 0 10px -6px;
  box-shadow: 0 0 10px -6px;
}

.selectricItems ul,
.selectricItems li {
  list-style: none;
  padding: 0;
  margin: 0;
  font-size: 12px;
  line-height: 20px;
  min-height: 20px;
}

.selectricItems li {
  display: block;
  padding: 5px;
  border-top: 1px solid #FFF;
  border-bottom: 1px solid #EEE;
  color: #666;
  cursor: pointer;
}

.selectricItems li.selected {
  background: #EFEFEF;
  color: #444;
  border-top-color: #E0E0E0;
}

.selectricItems li:hover {
  background: #F0F0F0;
  color: #444;
}

.selectricItems li.disabled {
  background: #F5F5F5;
  color: #BBB;
  border-top-color: #FAFAFA;
  cursor: default;
}
```

Initialize **jQuery Selectric:**

```html
<script>
$(function(){
	$('select').selectric();
});
</script>
```

##Options:

		Option
		Default
		Type
		Description

		onOpen
		function() {}
		Function
		Function called when select options is opened

		onChange
		function() {}
		Function
		Function called when select options is changed

		onClose
		function() {}
		Function
		Function called when select options is closed

		maxHeight
		300
		Integer
		Maximum height options box can be

		keySearchTimeout
		500
		Integer
		After this time without pressing any key, the search string is reseted

		arrowButtonMarkup
		<b class="button">&#9662;</b>
		String [HTML]
		Markup for open options button

		disableOnMobile
		true
		Boolean
		Initialize plugin on mobile browsers

		border
		1
		Integer
		Options box border thickness

		openOnHover
		false
		Boolean
		Open select box on hover, instead of click

		expandToItemText
		false
		Boolean
		Expand options box past wrapper

	  responsive
	  false
	  Boolean
	  The select element become responsive

    customClass
    {

    prefix: 'selectric',

    postfixes: 'Input Items Open Disabled TempShow HideSelect Wrapper Hover Responsive',

    camelCase: true

    }
    Object
    Custom classes

##Public methods:

```js
$('select').selectric('refresh'); // Reconstruct the instance of plugin
$('select').selectric('destroy'); // Destroy Selectric and go back to normal
$('select').selectric('open');    // Open options
$('select').selectric('close');   // Close options
```

##Browser support:

* Firefox
* Chrome
* Safari
* Internet Explorer 7+
* Opera


text:
namespace content {

URLDataSourceImpl::URLDataSourceImpl(const std::string& source_name,
                                     URLDataSource* source)
    : source_name_(source_name),
      backend_(NULL),
      source_(source) {
}

URLDataSourceImpl::~URLDataSourceImpl() {
}

void URLDataSourceImpl::SendResponse(
    int request_id,
    base::RefCountedMemory* bytes) {
  // Take a ref-pointer on entry so byte->Release() will always get called.
  scoped_refptr<base::RefCountedMemory> bytes_ptr(bytes);
  if (URLDataManager::IsScheduledForDeletion(this)) {
    // We're scheduled for deletion. Servicing the request would result in
    // this->AddRef being invoked, even though the ref count is 0 and 'this' is
    // about to be deleted. If the AddRef were allowed through, when 'this' is
    // released it would be deleted again.
    //
    // This scenario occurs with DataSources that make history requests. Such
    // DataSources do a history query in |StartDataRequest| and the request is
    // live until the object is deleted (history requests don't up the ref
    // count). This means it's entirely possible for the DataSource to invoke
    // |SendResponse| between the time when there are no more refs and the time
    // when the object is deleted.
    return;
  }
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&URLDataSourceImpl::SendResponseOnIOThread, this, request_id,
                 bytes_ptr));
}

void URLDataSourceImpl::SendResponseOnIOThread(
    int request_id,
    scoped_refptr<base::RefCountedMemory> bytes) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (backend_)
    backend_->DataAvailable(request_id, bytes);
}

}  // namespace content


text:
package org.elasticsearch.action.index;

import org.elasticsearch.action.bulk.TransportBulkAction;
import org.elasticsearch.action.bulk.TransportShardBulkAction;
import org.elasticsearch.action.bulk.TransportSingleItemBulkWriteAction;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

/**
 * Performs the index operation.
 *
 * Allows for the following settings:
 *

 *
autoCreateIndex: When set to {@code true}, will automatically create an index if one does not exists.
 * Defaults to {@code true}.
 *
allowIdGeneration: If the id is set not, should it be generated. Defaults to {@code true}.
 *

 *
 * Deprecated use TransportBulkAction with a single item instead
 */
@Deprecated
public class TransportIndexAction extends TransportSingleItemBulkWriteAction<IndexRequest, IndexResponse> {

    @Inject
    public TransportIndexAction(Settings settings, TransportService transportService, ClusterService clusterService,
                                IndicesService indicesService,
                                ThreadPool threadPool,
                                ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver,
                                TransportBulkAction bulkAction, TransportShardBulkAction shardBulkAction) {
        super(settings, IndexAction.NAME, transportService, clusterService, indicesService, threadPool,
            actionFilters, indexNameExpressionResolver, IndexRequest::new, IndexRequest::new, ThreadPool.Names.INDEX,
            bulkAction, shardBulkAction);
    }

    @Override
    protected IndexResponse newResponseInstance() {
        return new IndexResponse();
    }
}


text:
<?php

namespace Surfnet\ServiceProviderDashboard\Infrastructure\HttpClient\Exceptions\HttpException;

class UndeleteableResourceException extends HttpException
{
}


text: @import '@10up/component-animate';


text:
module SolrWrapper
  # Runs a command using popen4 (typically for JRuby)
  class Popen4Runner < Runner
    def run(stringio)
      pid, input, output, error = IO.popen4(command)
      if config.verbose? && !silence_output?
        IO.copy_stream(output, $stderr)
        IO.copy_stream(error, $stderr)
      else
        IO.copy_stream(output, stringio)
        IO.copy_stream(error, stringio)
      end

      input.close
      output.close
      error.close
      exit_status = Process.waitpid2(pid).last
      stringio.rewind
      exit_status
    end

    private

    def command
      env_str + ' ' + argument_list.join(' ')
    end

    def env_str
      config.env.map { |k, v| "#{Shellwords.escape(k)}=#{Shellwords.escape(v)}" }.join(' ')
    end
  end
end


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-4270',
  templateUrl: './comp-4270.component.html',
  styleUrls: ['./comp-4270.component.css']
})
export class Comp4270Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
from sklearn2sql_heroku.tests.regression import generic as reg_gen

reg_gen.test_model("GradientBoostingRegressor" , "california_housing" , "sqlite")


text:
package org.drools.guvnor.client.common;

import org.drools.guvnor.client.packages.AssetAttachmentFileWidget;
import org.drools.guvnor.client.resources.Images;
import org.drools.guvnor.client.rpc.RuleAsset;
import org.drools.guvnor.client.ruleeditor.RuleViewer;
import org.drools.guvnor.client.messages.Constants;

import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.core.client.GWT;

public class DefaultContentUploadEditor extends AssetAttachmentFileWidget {

    private static Images images = (Images) GWT.create( Images.class );

    public DefaultContentUploadEditor(RuleAsset asset,
                                      RuleViewer viewer) {
        super( asset,
               viewer );
        super.addDescription( new HTML( ((Constants) GWT.create( Constants.class )).UploadNewVersionDescription() ) );
    }

    public ImageResource getIcon() {
        return images.decisionTable();
    }

    public String getOverallStyleName() {
        return "decision-Table-upload"; //NON-NLS
    }

}


text:
<!DOCTYPE html>

		<title>Welcome to Angular.js</title>

				{{message}}


text:
/*
 *
 * TaskConstants
 */

var keyMirror = require('keymirror');

module.exports = keyMirror({
  USER_LOGIN: null
});


text:
Using a graphical interface
###########################

In the previous tutorial we measured the IV characteristic of a sample to show how we can set up a simple experiment in PyMeasure. The real power of PyMeasure comes when we also use the graphical tools that are included to turn our simple example into a full-flegged user interface.

Using the Plotter
~~~~~~~~~~~~~~~~~

While it lacks the nice features of the ManagedWindow, the Plotter object is the simplest way of getting live-plotting. The Plotter takes a Results object and plots the data at a regular interval, grabbing the latest data each time from the file.

Let's extend our SimpleProcedure with a RandomProcedure, which generates random numbers during our loop. This example does not include instruments to provide a simpler example. ::

    import logging
    log = logging.getLogger(__name__)
    log.addHandler(logging.NullHandler())

    import random
    from time import sleep
    from pymeasure.log import console_log
    from pymeasure.display import Plotter
    from pymeasure.experiment import Procedure, Results, Worker
    from pymeasure.experiment import IntegerParameter, FloatParameter, Parameter

    class RandomProcedure(Procedure):

        iterations = IntegerParameter('Loop Iterations')
        delay = FloatParameter('Delay Time', units='s', default=0.2)
        seed = Parameter('Random Seed', default='12345')

        DATA_COLUMNS = ['Iteration', 'Random Number']

        def startup(self):
            log.info("Setting the seed of the random number generator")
            random.seed(self.seed)

        def execute(self):
            log.info("Starting the loop of %d iterations" % self.iterations)
            for i in range(self.iterations):
                data = {
                    'Iteration': i,
                    'Random Number': random.random()
                }
                self.emit('results', data)
                log.debug("Emitting results: %s" % data)
                sleep(self.delay)
                if self.should_stop():
                    log.warning("Caught the stop flag in the procedure")
                    break

    if __name__ == "__main__":
        console_log(log)

        log.info("Constructing a RandomProcedure")
        procedure = RandomProcedure()
        procedure.iterations = 100

        data_filename = 'random.csv'
        log.info("Constructing the Results with a data file: %s" % data_filename)
        results = Results(procedure, data_filename)

        log.info("Constructing the Plotter")
        plotter = Plotter(results)
        plotter.start()
        log.info("Started the Plotter")

        log.info("Constructing the Worker")
        worker = Worker(results)
        worker.start()
        log.info("Started the Worker")

        log.info("Joining with the worker in at most 1 hr")
        worker.join(timeout=3600) # wait at most 1 hr (3600 sec)
        log.info("Finished the measurement")

The important addition is the construction of the Plotter from the Results object. ::

    plotter = Plotter(results)
    plotter.start()

Just like the Worker, the Plotter is started in a different process so that it can be run on a separate CPU for higher performance. The Plotter launches a Qt graphical interface using pyqtgraph which allows the Results data to be viewed based on the columns in the data.

.. image:: pymeasure-plotter.png
    :alt: Results Plotter Example

Using the ManagedWindow
~~~~~~~~~~~~~~~~~~~~~~~

The ManagedWindow is the most convenient tool for running measurements with your Procedure. This has the major advantage of accepting the input parameters graphically. From the parameters, a graphical form is automatically generated that allows the inputs to be typed in. With this feature, measurements can be started dynamically, instead of defined in a script.

Another major feature of the ManagedWindow is its support for running measurements in a sequential queue. This allows you to set up a number of measurements with different input parameters, and watch them unfold on the live-plot. This is especially useful for long running measurements. The ManagedWindow achieves this through the Manager object, which coordinates which Procedure the Worker should run and keeps track of its status as the Worker progresses.

Below we adapt our previous example to use a ManagedWindow. ::

    import logging
    log = logging.getLogger(__name__)
    log.addHandler(logging.NullHandler())

    import random
    from time import sleep
    from pymeasure.log import console_log
    from pymeasure.display.Qt import QtGui
    from pymeasure.display.windows import ManagedWindow
    from pymeasure.experiment import Procedure, Results
    from pymeasure.experiment import IntegerParameter, FloatParameter, Parameter

    class RandomProcedure(Procedure):

        iterations = IntegerParameter('Loop Iterations')
        delay = FloatParameter('Delay Time', units='s', default=0.2)
        seed = Parameter('Random Seed', default='12345')

        DATA_COLUMNS = ['Iteration', 'Random Number']

        def startup(self):
            log.info("Setting the seed of the random number generator")
            random.seed(self.seed)

        def execute(self):
            log.info("Starting the loop of %d iterations" % self.iterations)
            for i in range(self.iterations):
                data = {
                    'Iteration': i,
                    'Random Number': random.random()
                }
                self.emit('results', data)
                log.debug("Emitting results: %s" % data)
                sleep(self.delay)
                if self.should_stop():
                    log.warning("Caught the stop flag in the procedure")
                    break

    class MainWindow(ManagedWindow):

        def __init__(self):
            super(MainWindow, self).__init__(
                procedure_class=RandomProcedure,
                inputs=['iterations', 'delay', 'seed'],
                displays=['iterations', 'delay', 'seed'],
                x_axis='Iteration',
                y_axis='Random Number'
            )
            self.setWindowTitle('GUI Example')

        def queue(self):
            filename = tempfile.mktemp()

            procedure = self.make_procedure()
            results = Results(procedure, filename)
            experiment = self.new_experiment(results)

            self.manager.queue(experiment)

    if __name__ == "__main__":
        app = QtGui.QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())

This results in the following graphical display.

.. image:: pymeasure-managedwindow.png
    :alt: ManagedWindow Example

In the code, the MainWindow class is a sub-class of the ManagedWindow class. We overwrite the constructor to provide information about the procedure class and its options. The :python:`inputs` are a list of Parameters class-variable names, which the display will generate graphical fields for. The :python:`displays` is a similar list, which instead defines the parameters to display in the browser window. This browser keeps track of the experiments being run in the sequential queue.

The :python:`queue` method establishes how the Procedure object is constructed. We use the :python:`self.make_procedure` method to create a Procedure based on the graphical input fields. Here we are free to modify the procedure before putting it on the queue. In this context, the Manager uses an Experiment object to keep track of the Procedure, Results, and its associated graphical representations in the browser and live-graph. This is then given to the Manager to queue the experiment.

.. image:: pymeasure-managedwindow-queued.png
    :alt: ManagedWindow Queue Example

By default the Manager starts a measurement when its procedure is queued. The abort button can be pressed to stop an experiment. In the Procedure, the :python:`self.should_stop` call will catch the abort event and halt the measurement. It is important to check this value, or the Procedure will not be responsive to the abort event.

.. image:: pymeasure-managedwindow-resume.png
    :alt: ManagedWindow Resume Example

If you abort a measurement, the resume button must be pressed to continue the next measurement. This allows you to adjust anything, which is presumably why the abort was needed.

.. image:: pymeasure-managedwindow-running.png
    :alt: ManagedWindow Running Example

Now that you have learned about the ManagedWindow, you have all of the basics to get up and running quickly with a measurement and produce an easy to use graphical interface with PyMeasure.


text:
class Api::ConversationsController < ApiController

  def index
    find_account!
    @conversations = @account.conversations
    respond_with(@conversations)
  end

  def create
    find_account!
    @conversation = @account.conversations.create!(conversation_params)
    render json: @conversation, status: :created
  end

  def show
    @conversation = Conversation.find(params.fetch(:id))
    authorize! AccountReadPolicy.new(@conversation.account, current_user)
    respond_with(@conversation)
  end

  protected

  def find_account!
    @account = Account.find_by!(id: params.fetch(:account))
    authorize! AccountReadPolicy.new(@account, current_user)
  end

  def conversation_params
    params.permit(subject: :string, tags: [])
  end

end


text:
package org.simplity.core.jms;

import java.io.Serializable;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.UUID;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.simplity.core.ApplicationError;
import org.simplity.core.app.Application;
import org.simplity.core.app.internal.JsonReqReader;
import org.simplity.core.app.internal.JsonRespWriter;
import org.simplity.core.comp.IValidationContext;
import org.simplity.core.comp.ValidationMessage;
import org.simplity.core.data.DataSerializationType;
import org.simplity.core.dm.Record;
import org.simplity.core.msg.Messages;
import org.simplity.core.service.IDataDeserializer;
import org.simplity.core.service.IDataSerializer;
import org.simplity.core.service.InputData;
import org.simplity.core.service.OutputData;
import org.simplity.core.service.ServiceContext;
import org.simplity.core.trans.IBatchInput;
import org.simplity.core.trans.IBatchOutput;
import org.simplity.core.trans.InvalidRowException;
import org.simplity.core.value.Value;
import org.simplity.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Manages all aspects of a JmsQueue
 *
 * @author simplity.org
 */
public class JmsDestination {
	protected static final Logger logger = LoggerFactory.getLogger(JmsDestination.class);

	/**
	 * name of the queue (destination) used for requesting a service. This is
	 * the jndi name that is available in the context.
	 */
	String name;

	/**
	 * is this destination a topic? false means it is a queue. This is for
	 * documentation. JNDI set up for name decides whether it is a queue or
	 * topic
	 */
	boolean isTopic;
	/**
	 * if this is used for working with other services, we need to accept body
	 * of the message as a payload and parse it into our data structures
	 */
	InputData inputData;
	/**
	 * if this is used for working with other services, we need to accept body
	 * of the message as a payload and parse it into our data structures
	 */
	OutputData outputData;
	/**
	 * null if message body is not used, but header parameters are used to
	 * transport data. How the body of the message is used to transport data.
	 */
	DataSerializationType messageBodyType;
	/**
	 * field that is associated with body. Entire body is
	 * assigned-to/retrieved-from this field
	 */
	String bodyFieldName;
	/**
	 * comma separated list of fields that supply/receive data.
	 */
	String fieldNames[];
	/**
	 * data structure on which this message data is based on
	 */
	String recordName;
	/**
	 * just extract all fields with no validation, if this queue is being
	 * consumed
	 */
	boolean extractAll;
	/**
	 * java class that implements org.simplity.service.DataFormatter interface.
	 * message body text is formatted using this class.
	 */
	String messageFormatter;
	/**
	 * java class that implements org.simplity.service.DataExtractor interface
	 * to extract data from message body text
	 */
	String messageExtractor;

	/**
	 * sheet name with two columns, first one name, second one value, both text.
	 * bodyMessageType must be set to COMMA_SEPARATED_PAIRS. Consumer extracts
	 * into this sheet, while producer formats the text using data in this sheet
	 */
	String nameValueSheetName;
	/**
	 * subset of messages that we are interested. As per JMS selector syntax.
	 */
	String messageSelector;
	/**
	 * message type of the message header. Use this ONLY if the provider insists
	 * on this, or your application uses this.
	 */
	String messageType;

	/** object instance for re-use */
	private IDataSerializer dataFormatter;
	/** object instance for re-use */
	private IDataDeserializer dataExtractor;
	/** jms queue instance for this queue */
	protected Destination destination;

	/**
	 * consume a request queue, and optionally put a message on to the response
	 * queue. Keep doing this for messages in the request queue, till the queue
	 * is closed, or the processor signals a shut-down
	 *
	 * @param ctx
	 *            service context where all this is happening
	 * @param processor
	 *            object instance that is interested in processing the message
	 * @param responseQ
	 *            optional response queue to be used to respond back to the
	 *            incoming message
	 * @param consumeAll
	 *            false means we will process (at most) one message. true means
	 *            no such restrictions.
	 * @param waitForMessage
	 *            true means we will wait for at least the first message. If
	 *            consumeAll is true, then we do not come-out till interrupted,
	 *            or the queue closes
	 */
	@SuppressWarnings("resource")
	public void consume(ServiceContext ctx, IJmsClient processor, JmsDestination responseQ, boolean consumeAll,
			boolean waitForMessage) {

		Session session = ctx.getJmsSession();
		MessageConsumer consumer = null;
		MessageProducer producer = null;

		try {
			consumer = session.createConsumer(this.destination, this.messageSelector);
			String nam = this.name;

			logger.info("Started consumer for destination " + nam);

			/*
			 * We may not use producer at all, but an empty producer does not
			 * hurt as much as creating it repeatedly..
			 */
			producer = session.createProducer(null);
			/*
			 * wait 0 means blocking-wait, 1 means try and come out.
			 */
			long wait = waitForMessage ? 0 : 1;
			/*
			 * loop for each message.
			 */
			do {
				if (waitForMessage) {
					logger.info("Looking/waiting for next message on " + nam);
				}
				Message msg = consumer.receive(wait);
				if (msg == null) {
					logger.info("No message in " + this.name + ". Consumer will not continue;");
					/*
					 * queue is shut down
					 */
					break;
				}
				/*
				 * let exception in one message not affect the over-all process
				 */
				try {
					/*
					 * data content of message is extracted into ctx
					 */
					this.extractMessage(msg, ctx);
					/*
					 * is the requester asking us to respond on a specific
					 * queue?
					 */
					Destination replyQ = msg.getJMSReplyTo();
					/*
					 * and the all important correlation id for the requester to
					 * select the message back
					 */
					String corId = msg.getJMSCorrelationID();
					if (replyQ == null && responseQ != null) {
						replyQ = responseQ.getDestination();
					}

					processor.process(ctx);
					if (replyQ != null) {
						Message respMsg = null;
						if (responseQ == null) {
							logger.info(
									"No response is specified for this consumer, but producer is asking for a reply. Sending a blank message");
							respMsg = session.createMessage();
						} else {
							/*
							 * prepare a reply based on specification
							 */
							respMsg = responseQ.createMessage(ctx);
						}
						if (corId != null) {
							respMsg.setJMSCorrelationID(corId);
						}
						producer.send(replyQ, respMsg);
					}
				} catch (Exception e) {
					ctx.addMessage(Messages.INTERNAL_ERROR, "Message processor threw an excpetion. " + e.getMessage());
				}
				if (consumeAll == false) {
					break;
				}
			} while (processor.toContinue());
		} catch (Exception e) {
			throw new ApplicationError(e, "Error while consuming and procesing JMS queue " + this.name);

		} finally {
			if (consumer != null) {
				try {
					consumer.close();
				} catch (Exception ignore) {
					//
				}
			}
			if (producer != null) {
				try {
					producer.close();
				} catch (Exception ignore) {
					//
				}
			}
		}
	}

	/**
	 * produce message on this queue
	 *
	 * @param ctx
	 *            service context where this is all happening
	 * @param responseQ
	 *            in case we are to get a response for this message-send
	 *            operation
	 * @return true if a message indeed was put on the queue. False otherwise
	 */
	@SuppressWarnings("resource")
	public boolean produce(ServiceContext ctx, JmsDestination responseQ) {
		MessageProducer producer = null;
		MessageConsumer consumer = null;
		Destination response = null;
		String corId = null;
		Session session = ctx.getJmsSession();
		try {
			producer = session.createProducer(this.destination);
			/*
			 * create a message with data from ctx
			 */
			Message msg = this.createMessage(ctx);

			/*
			 * should we ask for a return message?
			 */
			if (responseQ != null) {
				if (responseQ.name == null) {
					response = session.createTemporaryQueue();
					consumer = session.createConsumer(response);
				} else {
					response = responseQ.getDestination();
					corId = UUID.randomUUID().toString();
					consumer = session.createConsumer(response, "JMSCorrelationID='" + corId + '\'');
					msg.setJMSCorrelationID(corId);
				}
				msg.setJMSReplyTo(response);
			}
			producer.send(msg);
			/*
			 * checking for one of them is good enough, but compiler would crib.
			 * We would rather live with whatever is the over-head of checking
			 * for another null than loosing the null-check facility for this
			 * method
			 */
			if (consumer != null && responseQ != null) {
				Message message = consumer.receive();
				if (message == null) {
					/*
					 * some issue in the queue
					 */
					logger.info("Response message is null. Probably some issue with the queue provider");
					return false;
				}
				responseQ.extractMessage(message, ctx);
			}
			return true;
		} catch (Exception e) {
			logger.info("Error while putting mesage on to a queue. " + e.getMessage());
			return false;
		} finally {
			if (consumer != null) {
				try {
					consumer.close();
				} catch (Exception ignore) {
					//
				}
			}
			if (producer != null) {
				try {
					producer.close();
				} catch (Exception ignore) {
					//
				}
			}
		}
	}

	/**
	 * @param session
	 * @param ctx
	 * @return
	 * @throws JMSException
	 */
	@SuppressWarnings("resource")
	protected Message createMessage(ServiceContext ctx) throws JMSException {
		Session session = ctx.getJmsSession();
		if (this.dataFormatter != null) {
			String text = this.dataFormatter.format(ctx);
			return session.createTextMessage(text);
		}

		Application app = Application.getActiveInstance();
		if (this.messageBodyType == null) {
			/*
			 * properties are used for transporting data
			 */
			Message message = session.createMessage();
			if (this.fieldNames != null) {
				this.setHeaderFields(message, ctx, this.fieldNames);
			} else if (this.recordName != null) {
				Record record = app.getRecord(this.recordName);
				this.setHeaderFields(message, ctx, record.getFieldNames());
			} else {

				logger.info("No fields specified to be added to the message.");
			}
			return message;
		}

		if (this.messageBodyType == DataSerializationType.MAP) {
			MapMessage message = session.createMapMessage();
			if (this.fieldNames != null) {
				this.setMapFields(message, ctx, this.fieldNames);
			} else if (this.recordName != null) {
				Record record = app.getRecord(this.recordName);
				this.setMapFields(message, ctx, record.getFieldNames());
			} else {

				logger.info("No fields specified to be added Map.");
			}
			return message;
		}

		if (this.messageBodyType == DataSerializationType.OBJECT) {
			if (this.bodyFieldName == null) {
				throw new ApplicationError(
						"bodyFieldName is not specified for messaage body when messageBodyType is set to object");
			}
			Object object = ctx.getObject(this.bodyFieldName);
			if (object == null) {

				logger.info("Service context has no object named " + this.bodyFieldName
						+ ". No object assigned to message.");

				return session.createObjectMessage();
			}
			if (object instanceof Serializable) {
				return session.createObjectMessage((Serializable) object);
			}
			throw new ApplicationError("Service context has an instance of " + object.getClass().getName()
					+ " as object for message. This class must be serializable.");
		}

		/*
		 * so, it is a TextMessage. Our task is to create the text to be set to
		 * the message body
		 */
		TextMessage message = session.createTextMessage();
		String text = null;

		if (this.outputData != null) {
			StringWriter sr = new StringWriter();
			JsonRespWriter writer = new JsonRespWriter(sr);
			this.outputData.write(writer, ctx);
			writer.done();
			message.setText(sr.toString());
			return message;
		}

		if (this.bodyFieldName != null) {
			/*
			 * simplest of our task. text is readily available in this field.
			 */
			text = ctx.getTextValue(this.bodyFieldName);
			if (text == null) {

				logger.info("No value found for body text with field name " + this.bodyFieldName + ". Data not set.");

			} else {
				message.setText(text);
			}
			return message;
		}

		if (this.recordName != null) {
			Record record = app.getRecord(this.recordName);
			message.setText(this.messageBodyType.serializeFields(ctx, record.getFields()));
			return message;
		}
		if (this.fieldNames != null) {
			message.setText(this.messageBodyType.serializeFields(ctx, this.fieldNames));
			return message;
		}
		throw new ApplicationError("Record or field details are required for creating message");
	}

	/**
	 * @param message
	 * @param ctx
	 * @throws JMSException
	 */
	public void extractMessage(Message message, ServiceContext ctx) throws JMSException {
		if (this.dataExtractor != null) {
			logger.info("Using a custom class to extract data " + this.messageExtractor);
			if (message instanceof TextMessage == false) {
				throw new ApplicationError("Expecting a TextMessage on queue " + this.bodyFieldName + " but we got a "
						+ message.getClass().getSimpleName());
			}
			String text = ((TextMessage) message).getText();
			this.dataExtractor.extract(text, ctx);
			return;
		}
		Application app = Application.getActiveInstance();
		if (this.messageBodyType == null) {
			/*
			 * properties are used for transporting data
			 */
			if (this.extractAll) {
				this.extractAllFromHeader(message, ctx);
			} else if (this.fieldNames != null && this.fieldNames.length > 0) {
				this.extractHeaderFields(message, ctx, this.fieldNames);
			} else if (this.recordName != null) {
				Record record = app.getRecord(this.recordName);
				this.extractHeaderFields(message, ctx, record.getFieldNames());
			} else {
				logger.info("No fields specified to be extracted from the message. Nothing extracted. ");
			}
			return;
		}
		/*
		 * we use three types of message body. TEXT, MAP and OBJECT
		 */
		if (this.messageBodyType == DataSerializationType.OBJECT) {
			if (message instanceof ObjectMessage == false) {
				logger.info("We expected a ObjectMessage but got " + message.getClass().getSimpleName()
						+ ". No object extracted.");
				return;
			}
			Object object = ((ObjectMessage) message).getObject();
			if (object == null) {
				logger.info("Messaage object is null. No object extracted.");
			} else if (this.bodyFieldName == null) {
				logger.info("bodyFieldName not set, and hence the object of instance " + object.getClass().getName()
						+ "  " + object + " not added to context.");
			} else {
				ctx.setObject(this.bodyFieldName, object);
			}
			return;
		}

		if (this.messageBodyType == DataSerializationType.MAP) {
			if (message instanceof MapMessage == false) {

				logger.info("We expected a MapMessage but got " + message.getClass().getSimpleName()
						+ ". No data extracted.");

				return;
			}
			MapMessage msg = (MapMessage) message;
			if (this.extractAll) {
				this.extractAllFromMap(ctx, msg);
			} else if (this.fieldNames != null) {
				this.extractMapFields(ctx, msg, this.fieldNames);
			} else if (this.recordName != null) {
				Record record = app.getRecord(this.recordName);
				this.extractMapFields(ctx, msg, record.getFieldNames());
			} else {

				logger.info("No directive to extract any fields from this MapMessage.");
			}
			return;
		}

		if (message instanceof TextMessage == false) {
			logger.info(
					"We expected a TextMessage but got " + message.getClass().getSimpleName() + ". No data extracted.");
			return;
		}

		String text = ((TextMessage) message).getText();
		if (text == null) {
			logger.info("Messaage text is null. No data extracted.");
			return;
		}
		if (this.inputData != null) {
			JSONObject json;
			if (text.isEmpty()) {
				json = new JSONObject();
			} else {
				json = new JSONObject(text);
			}
			JsonReqReader reader = new JsonReqReader(json, null);
			this.inputData.read(reader, ctx);
			return;
		}
		if (this.bodyFieldName != null) {
			ctx.setTextValue(this.bodyFieldName, text);
			return;
		}
		if (this.recordName != null) {
			Record record = app.getRecord(this.recordName);
			this.messageBodyType.parseFields(text, ctx, record.getFields());
			return;
		}
		this.messageBodyType.parseFields(text, ctx, this.fieldNames, null);
		return;
	}

	/**
	 * @param ctx
	 * @param message
	 * @param names
	 * @throws JMSException
	 */
	private void extractMapFields(ServiceContext ctx, MapMessage message, String[] names) throws JMSException {
		for (String nam : names) {
			Object val = message.getObject(nam);
			if (val != null) {
				ctx.setValue(nam, Value.parse(val));
			}
		}
	}

	/**
	 * @param ctx
	 * @param message
	 * @throws JMSException
	 */
	private void extractAllFromMap(ServiceContext ctx, MapMessage message) throws JMSException {
		@SuppressWarnings("unchecked")
		Enumeration<String> names = message.getMapNames();
		while (true) {
			try {
				String nam = names.nextElement();
				Object val = message.getObject(nam);
				if (val != null) {
					ctx.setValue(nam, Value.parse(val));
				}
			} catch (NoSuchElementException e) {
				/*
				 * unfortunately we have to live with this old-styled exception
				 * for a normal event!!!
				 */
				return;
			}
		}
	}

	/**
	 * @param message
	 * @param ctx
	 * @throws JMSException
	 */
	private void extractAllFromHeader(Message message, ServiceContext ctx) throws JMSException {
		@SuppressWarnings("unchecked")
		Enumeration<String> names = message.getPropertyNames();
		while (true) {
			try {
				String nam = names.nextElement();
				Object val = message.getObjectProperty(nam);
				if (val != null) {
					ctx.setValue(nam, Value.parse(val));
				}
			} catch (NoSuchElementException e) {
				/*
				 * unfortunately we have to live with this old-styled exception
				 * for a normal event!!!
				 */
				return;
			}
		}
	}

	/**
	 * @param message
	 * @param ctx
	 * @param names
	 * @throws JMSException
	 */
	private void extractHeaderFields(Message message, ServiceContext ctx, String[] names) throws JMSException {
		for (String nam : names) {
			Object val = message.getObjectProperty(nam);
			if (val != null) {
				ctx.setValue(nam, Value.parse(val));
			}
		}
	}

	/**
	 * @param message
	 * @param ctx
	 * @param names
	 * @throws JMSException
	 */
	private void setHeaderFields(Message message, ServiceContext ctx, String[] names) throws JMSException {
		for (String nam : names) {
			Value val = ctx.getValue(nam);
			if (val == null) {

				logger.info("No value for " + nam + ". Value not set to message header.");

			} else {
				message.setObjectProperty(nam, val.toObject());
			}
		}
	}

	/**
	 * @param message
	 * @param ctx
	 * @param names
	 * @throws JMSException
	 */
	private void setMapFields(MapMessage message, ServiceContext ctx, String[] names) throws JMSException {
		for (String nam : names) {
			Value val = ctx.getValue(nam);
			if (val == null) {

				logger.info("No value for " + nam + ". Value not set to Map.");

			} else {
				message.setObject(nam, val.toObject());
			}
		}
	}

	/** open shop and be ready for a repeated use */
	public void getReady() {
		/*
		 * avoid repeated check for empty array
		 */
		if (this.fieldNames != null && this.fieldNames.length == 0) {
			this.fieldNames = null;
		}
		/*
		 * cache object instance
		 */
		if (this.messageExtractor != null) {
			try {
				this.dataExtractor = (IDataDeserializer) Class.forName(this.messageExtractor).newInstance();
			} catch (Exception e) {
				throw new ApplicationError(e,
						"Error while creating an instance of DataExtractor for " + this.messageExtractor);
			}
		}

		/*
		 * cache object instance
		 */
		if (this.messageFormatter != null) {
			try {
				this.dataFormatter = (IDataSerializer) Class.forName(this.messageFormatter).newInstance();
			} catch (Exception e) {
				throw new ApplicationError(e,
						"Error while creating an instance of DataFormatter for " + this.messageFormatter);
			}
		}
		try {
			this.destination = (Destination) new InitialContext().lookup(this.name);
		} catch (Exception e) {
			throw new ApplicationError("Jms destination name " + this.name
					+ " could not be used as a JNDI name to locate a queue name. " + e.getMessage());
		}
		if (this.inputData != null) {
			this.inputData.getReady();
		}
		if (this.outputData != null) {
			this.outputData.getReady();
		}
	}

	/** @return name of this queue */
	public Destination getDestination() {
		return this.destination;
	}

	/**
	 * validate attributes
	 *
	 * @param vtx
	 *            validation context
	 * @param forProducer
	 */
	public void validate(IValidationContext vtx, boolean forProducer) {
		/*
		 * fieldNames and recordName are two ways to specify list if fields
		 */
		boolean fieldListSpecified = this.recordName != null || (this.fieldNames != null && this.fieldNames.length > 0);
		/*
		 * fieldName is required if we are set/get message body directly from
		 * one field rather than constructing it from other fields, or
		 * extracting it to other fields
		 */
		boolean fieldNameRequired = this.messageBodyType == DataSerializationType.TEXT
				|| this.messageBodyType == DataSerializationType.OBJECT;

		/*
		 * now let is start our role as an auditor - find anything unusual :-)
		 */
		if (this.bodyFieldName == null) {
			if (fieldNameRequired) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_ERROR,
						"messageBodyType=text/object requires bodyFieldName to which this text/object is to be assigned from/to",
						"bodyFieldName"));
			}
		} else {
			if (!fieldNameRequired) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
						"bodyFieldName is used for messageBodyType of object and text only. It is ignored otherwise.",
						"messageBodyType"));
			}
		}
		/*
		 * custom extractor
		 */
		if (this.messageExtractor != null) {
			if (forProducer) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
						"messageExtractor is used when the queue is used for consuming/reading message.",
						"messageExtractor"));
			} else {
				if (fieldListSpecified) {
					vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
							"messageExtractor is used for extrating data. fieldNames, and reordName settings are ignored.",
							null));
				}
			}
			if (this.messageBodyType != DataSerializationType.TEXT) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
						"messageExtractor is used when the message body usage is text. this.messageBodyType is set to "
								+ this.messageBodyType + ". we will ignore this setting and assume text body.",
						"messageBodyType"));
			}
		}

		/*
		 * custom formatter
		 */
		if (this.messageFormatter != null) {
			if (!forProducer) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
						"messageFormatter is used when message is to be created/produced. Setting ignored",
						"messageFormatter"));
			} else {
				if (fieldListSpecified) {
					vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
							"messageFormatter is used for formatting message body. fieldNames, and reordName settings are ignored.",
							"messageFormatter"));
				}
			}
			if (this.messageBodyType != DataSerializationType.TEXT) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
						"messageFormatter is used when the message body usage is text. this.messageBodyType is set to "
								+ this.messageBodyType + ". we will ignore this setting and assume text body.",
						"messageBodyType"));
			}
		}

		/*
		 * record name is required for fixed-width
		 */
		if (this.recordName != null) {
			if (fieldNameRequired) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
						"recordName is ignored for message body type of text/object.", "recordName"));
			}
		}

		/*
		 * no data specification?
		 */
		if (fieldNameRequired == false && fieldListSpecified == false) {
			if (forProducer) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
						"No fields/records specified. Message is designed to carry no data.", null));
			} else if (!this.extractAll) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
						"No fields/records specified, and extractAll is set to false. Message consumer is not looking for any data in this message.",
						"extractAll"));
			}
		}

		if (this.bodyFieldName == null) {
			if (this.messageBodyType == DataSerializationType.OBJECT
					|| this.messageBodyType == DataSerializationType.TEXT) {
				vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_ERROR,
						"messageBodyType=object or text requires bodyFieldName to which the body object/text is to be assigned to.",
						"bodyFieldName"));
			}
		}

		if (this.extractAll && forProducer) {
			vtx.message(new ValidationMessage(this, ValidationMessage.SEVERITY_WARNING,
					"extractAll is not relevant when the queue is used to produce/send message. Attribute ignored.",
					"extractAll"));
		}
	}

	/**
	 * @param ctx
	 * @return a worker instance that can work as a driver input for a batch
	 */
	public JmsInput getBatchInput(ServiceContext ctx) {
		return new JmsInput();
	}

	/**
	 * @param ctx
	 * @return a worker instance that can produce messages onto a queue
	 */
	public JmsOutput getBatchOutput(ServiceContext ctx) {
		return new JmsOutput();
	}

	/** @return name of the queue */
	public String getName() {
		return this.name;
	}

	/**
	 * worker class that inputs a message from this queue as input for a batch
	 * process
	 *
	 * @author simplity.org
	 */
	public class JmsInput implements IBatchInput {
		private MessageConsumer consumer;

		protected JmsInput() {
			//
		}

		@Override
		public void openShop(ServiceContext ctx) throws JMSException {
			@SuppressWarnings("resource")
			Session session = ctx.getJmsSession();
			this.consumer = session.createConsumer(JmsDestination.this.destination,
					JmsDestination.this.messageSelector);

			logger.info("Started consumer for queue " + JmsDestination.this.name);
		}

		@Override
		public void closeShop(ServiceContext ctx) {
			if (this.consumer != null) {
				try {
					this.consumer.close();
				} catch (Exception ignore) {
					//
				}
			}
		}

		@Override
		public boolean possiblyMultipleRowsPerParent() {
			return false;
		}

		@Override
		public boolean inputARow(ServiceContext ctx) throws JMSException {
			/*
			 * we should read, if there is some message. We use 1ms for this
			 */
			Message msg = this.consumer.receive(1);
			if (msg == null) {

				logger.info("No more messages in " + JmsDestination.this.name + ". Queue consumer will not continue;");

				return false;
			}
			JmsDestination.this.extractMessage(msg, ctx);
			return true;
		}

		/*
		 * this method should never be used
		 */
		@Override
		public boolean inputARow(String parentKey, ServiceContext ctx)
				throws InvalidRowException {
			throw new ApplicationError("JMS Queue can not be used to get messages for a gievn parent.");
		}

		@Override
		public String getParentKeyValue(ServiceContext ctx) {
			return null;
		}

		@Override
		public String getFileName() {
			return null;
		}
	}

	/**
	 * class that works as output for a batch row processor
	 *
	 * @author simplity.org
	 */
	public class JmsOutput implements IBatchOutput {
		private MessageProducer producer;

		@Override
		public void openShop(ServiceContext ctx) throws JMSException {
			@SuppressWarnings("resource")
			Session session = ctx.getJmsSession();
			this.producer = session.createProducer(JmsDestination.this.destination);
		}

		@Override
		public void closeShop(ServiceContext ctx) {
			if (this.producer != null) {
				try {
					this.producer.close();
				} catch (Exception ignore) {
					//
				}
			}
		}

		@Override
		public boolean outputARow(ServiceContext ctx) throws JMSException {
			/*
			 * create a message with data from ctx
			 */
			Message msg = JmsDestination.this.createMessage(ctx);
			this.producer.send(msg);
			return true;
		}
	}
}


text:
package helper

import (
	"time"

	"github.com/skynology/cloud-types"
	"github.com/skynology/go-sdk"
)

// 用于云代码中调用其他函数
type FuncHandler interface {
	// 调用内部方法
	Call(h *Helper, req types.CloudRequest, app *skynology.App, name string, data map[string]interface{}) (result map[string]interface{}, err error)
}

// 创建新Helper
func NewHelper(handler FuncHandler) *Helper {
	return &Helper{
		HideFields:    []string{},
		ProtectFields: []string{},
		Logs:          []types.CloudLog{},
		Data:          make(map[string]interface{}),
		funcHandler:   handler,
	}
}

// Helper
type Helper struct {
	Type          string
	IsFunction    bool
	HideFields    []string
	ProtectFields []string
	Result        interface{}
	Data          map[string]interface{}
	Logs          []types.CloudLog
	Errors        types.CloudError
	funcHandler   FuncHandler
}

// 云代码中调用函数
func (h *Helper) Call(req types.CloudRequest, app *skynology.App, name string, data map[string]interface{}) (result map[string]interface{}, err error) {
	result, err = h.funcHandler.Call(h, req, app, name, data)
	return
}

// 完成并退出
// result 参数必须为可转为Json的对象
func (h *Helper) Render(result interface{}) {
	// 不允许在表hook中使用
	if h.Type == "hook" {
		return
	}
	h.Result = result
}

// 更新字段
func (h *Helper) Set(fieldName string, value interface{}) {
	h.Data[fieldName] = value
}

// 取消并返回
// 返回 RESTFul Error格式,
// Code: -1, Error: message
func (h *Helper) Cancel(message string) {
	h.Errors = types.CloudError{Code: -1, Message: message}
}

// 取消并返回
// 返回 RESTFul Error格式,
// Code: code, Error: message
func (h *Helper) CancelWithCode(message string, code int) {
	h.Errors = types.CloudError{Code: code, Message: message}
}

// 隐藏字段。不返回给API调用者
func (h *Helper) Hide(fieldName string) {
	h.HideFields = append(h.HideFields, fieldName)
}

// 保护字段, 设置过的字段将无法更新
func (h *Helper) Protect(fieldName string) {
	h.ProtectFields = append(h.ProtectFields, fieldName)
}

// 打印log, 方便调试
func (h *Helper) Log(message string) {
	h.LogWithFlag(message, "info")
}

func (h *Helper) LogWithFlag(message string, flag string) {
	l := types.CloudLog{}
	l.Content = message
	l.CreatedAt = time.Now().Format(time.RFC3339Nano)
	l.Flag = flag
	h.Logs = append(h.Logs, l)
}


text:
<?php
defined('_JEXEC') or die('Restricted access');

class CCExControllersAdd extends JControllerBase
{
    public function execute() {
        $app = JFactory::getApplication();
        $return = array('success' => false);

        $_model = $app->input->get('model', 'Cost');
        $view = $app->input->get('view', 'Cost');
        $layout = $app->input->get('layout', 'add');
        $item = $app->input->get('item', 'cost');

        $modelName = 'CCExModels' . ucwords($_model);

        $model = new $modelName();
        $result = $model->store();

        if ($result) {
            foreach ($result as $key => $value) {
                $return[$key] = $value;
            }
            $return['success'] = true;
            $return['message'] = JText::_('COM_CCEX_' . strtoupper($_model) . '_CREATE_SUCCESS');
        } else {
            $return['message'] = JText::_('COM_CCEX_' . strtoupper($_model) . '_CREATE_FAILURE');
        }

        echo json_encode($return);
    }
}


text:
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / DISCLAIMER
// /
// / Copyright 2015-2016 ArangoDB GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is ArangoDB GmbH, Cologne, Germany
// /
// / @author Alan Plum
// //////////////////////////////////////////////////////////////////////////////

const ALL_METHODS = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'];
const SwaggerContext = require('@arangodb/foxx/router/swagger-context');
const Route = require('@arangodb/foxx/router/route');
const Middleware = require('@arangodb/foxx/router/middleware');
const tokenize = require('@arangodb/foxx/router/tokenize');
const check = require('@arangodb/foxx/check-args');

const repeat = (times, value) => {
  const arr = Array(times);
  for (let i = 0; i < times; i++) {
    arr[i] = value;
  }
  return arr;
};

const Router = module.exports =
  class Router extends SwaggerContext {
    constructor () {
      super();
      this._routes = [];
      this._middleware = [];
      this._namedRoutes = new Map();
    }

    _PRINT (ctx) {
      ctx.output += '[Router]';
    }

    use (...args) {
      const argv = check(
        'router.use',
        args,
        [['path', 'string'], ['fn', check.validateMountable], ['name', 'string']],
        [['path', 'string'], ['fn', check.validateMountable]],
        [['fn', check.validateMountable], ['name', 'string']],
        [['fn', check.validateMountable]]
      );
      let path = argv.path;
      let fn = argv.fn;
      let name = argv.name;
      if (fn.isFoxxRouter) {
        if (!path) {
          path = '/*';
        } else if (path.charAt(path.length - 1) !== '*') {
          if (path.charAt(path.length - 1) !== '/') {
            path += '/';
          }
          path += '*';
        }
        {
          const n = path.length - 1;
          if (path.charAt(n) === '/') {
            path = path.slice(0, n);
          }
          if (path.charAt(0) !== '/') {
            path = `/${path}`;
          }
        }
        const child = {
          path: path,
          _pathParams: new Map(),
          _pathParamNames: [],
          router: fn
        };
        child._pathTokens = tokenize(path, child);
        this._routes.push(child);
        if (name) {
          child.name = name;
          this._namedRoutes.set(child.name, child);
        }
        return fn;
      }
      const middleware = new Middleware(path, fn);
      this._middleware.push(middleware);
      return middleware;
    }

    all (...args) {
      const argv = check(
        'router.all',
        args,
        [['path', 'string'], ...repeat(Math.max(1, args.length - 2), ['handler', 'function']), ['name', 'string']],
        [['path', 'string'], ...repeat(Math.max(1, args.length - 1), ['handler', 'function'])],
        [...repeat(Math.max(1, args.length - 1), ['handler', 'function']), ['name', 'string']],
        repeat(Math.max(1, args.length), ['handler', 'function'])
      );
      const path = argv.path;
      const handler = argv.handler;
      const name = argv.name;
      const route = new Route(ALL_METHODS, path, handler, name);
      this._routes.push(route);
      if (route.name) {
        this._namedRoutes.set(route.name, route);
      }
      return route;
    }
};

Router.prototype.isFoxxRouter = true;

ALL_METHODS.forEach(function (method) {
  Router.prototype[method.toLowerCase()] = function (...args) {
    const argv = check(
      `router.${method.toLowerCase()}`,
      args,
      [['path', 'string'], ...repeat(Math.max(1, args.length - 2), ['handler', 'function']), ['name', 'string']],
      [['path', 'string'], ...repeat(Math.max(1, args.length - 1), ['handler', 'function'])],
      [...repeat(Math.max(1, args.length - 1), ['handler', 'function']), ['name', 'string']],
      repeat(Math.max(1, args.length), ['handler', 'function'])
    );
    const path = argv.path;
    const handler = argv.handler;
    const name = argv.name;
    const route = new Route([method], path, handler, name);
    this._routes.push(route);
    if (route.name) {
      this._namedRoutes.set(route.name, route);
    }
    return route;
  };
});


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Camera</title>
</head>
<body>
<canvas id="webcam">

</canvas>
<script src="camera.js"></script>
<script>
    var images = {
                'dog':'http://upload.wikimedia.org/wikipedia/commons/8/89/Dog.svg',
                'elephant':'http://upload.wikimedia.org/wikipedia/commons/thumb/0/0e/Certain_Elephant.svg/228px-Certain_Elephant.svg.png' //http://www.misskatecuttables.com/uploads/shopping_cart/7460/large_elephant.png
                };
    var ananya_canvas = document.getElementById('webcam');
    function draw_animal(){
        var context = ananya_canvas.getContext("2d");
        img = document.createElement('img');
        img.src = images['dog'];
        context.drawImage(img,200,200,100,100);
        context.font = '40pt Calibri';
        context.fillStyle = 'blue';
        context.fillText('Ananya', 100, 100);

    };
    camera.init({
        width:600,
        height:480,
        fps:40,
        mirror:false,
        targetCanvas: ananya_canvas,
        onFrame:function(canvas) {
            draw_animal();
        },
        onSuccess: function() {
            // stream succesfully started, yay!
            draw_animal();
        },

        onError: function(error) {
            // something went wrong on initialization
        },

        onNotSupported: function() {
            // instruct the user to get a better browser
        }
    })
</script>
</body>
</html>


text:
#include <string>
#include <memory>

#include "modsecurity/actions/action.h"

#ifndef SRC_ACTIONS_SEVERITY_H_
#define SRC_ACTIONS_SEVERITY_H_

#ifdef __cplusplus

namespace modsecurity {
class Transaction;

namespace actions {

class Severity : public Action {
 public:
    explicit Severity(const std::string &action)
        : Action(action),
        m_severity(0) { }

    bool evaluate(RuleWithActions *rule, Transaction *transaction,
        std::shared_ptr<RuleMessage> rm) override;
    bool init(std::string *error) override;

    int m_severity;
};

}  // namespace actions
}  // namespace modsecurity
#endif

#endif  // SRC_ACTIONS_SEVERITY_H_