text:
require 'baseball_stats/ui/plain_text_menu'

module BaseballStats
  module UI
    describe PlainTextMenu do
      let(:reporters)    { [double(:reporter, menu_name: 'Reporter Name 1'),
                            double(:reporter, menu_name: 'Reporter Name 2')] }
      let(:printer)      { double(:printer).as_null_object }
      let(:input_device) { double(:input_device).as_null_object }

      subject { PlainTextMenu.new(reporters, printer, input_device) }

      def assert_printed(txt)
        printer.should_receive(:write).with(txt)
      end

      describe "initialize" do
        it "writes the printer's header" do
          PlainTextMenu.any_instance.stub(:header) { 'Menu header' }
          assert_printed('Menu header')
          subject
        end
      end

      describe "#prompt" do
        before { subject.stub(:run_option) }

        it "writes the reporter names to the printer" do
          assert_printed('1. Reporter Name 1')
          assert_printed('2. Reporter Name 2')
          subject.prompt
        end

        it "writes the quit option to the printer" do
          assert_printed('q. Quit')
          subject.prompt
        end

        it "asks the user to make a choice" do
          assert_printed("\nPlease select from the options above:")
          input_device.should_receive(:prompt)
          subject.prompt
        end

        it "passes the user's option to the #run_option function" do
          input_device.stub(:prompt) { '1' }
          subject.should_receive(:run_option).with('1')
          subject.prompt
        end
      end

      describe "#run_option" do
        before { subject.stub(:prompt_to_start_over_or_quit) }

        context "when option is unrecognized" do
          it "tells the user it's confused and asks to prompt again or quit" do
            assert_printed("\nSorry! We didn't recognize that option!")
            subject.should_receive(:prompt_to_start_over_or_quit)
            subject.run_option('h')
          end
        end

        context "when the option is Q/q" do
          it "quits" do
            ['Q', 'q'].each do |q|
              subject.should_receive(:exit)
              subject.run_option(q)
            end
          end
        end

        context "when the option is a number from the menu" do
          it "prompts that reporter with devices, asks to restart or quit" do
            reporters[0].should_receive(:prompt).with(printer, input_device)
            subject.should_receive(:prompt_to_start_over_or_quit)
            subject.run_option('1')
          end
        end
      end
    end
  end
end


text:
package org.apache.geode.internal.cache.tier;

import org.jetbrains.annotations.NotNull;

/**
 * Pre-defined interest list types supported by the system.
 * Partial duplicate of {@link org.apache.geode.cache.operations.InterestType}.
 */
public enum InterestType {

  /** For registering interest in a specific key or list of keys */
  KEY,

  /** For registering interest in all keys matching a regular expression */
  REGULAR_EXPRESSION,

  /** For registering interest in all key/value pairs that satisfy a provided filtering class */
  FILTER_CLASS,

  /** For registering interest in all key/value pairs that satisfy an OQL query */
  OQL_QUERY,

  /** For registering CQs */
  CQ;

  /**
   * Convert an interest type to a printable string
   *
   * @param kind the type to convert
   * @return a printable string
   */
  public static String getString(final @NotNull InterestType kind) {
    switch (kind) {
      case KEY:
        return "KEY";
      case REGULAR_EXPRESSION:
        return "REGEX";
      case FILTER_CLASS:
        return "FILTER";
      case OQL_QUERY:
        return "OQL_QUERY";
      case CQ:
        return "CQ";
      default:
        return "Invalid(" + kind + ")";
    }
  }

  public static @NotNull InterestType valueOf(final int ordinal) {
    return values()[ordinal];
  }
}

redpajama_set_name: RedPajamaGithub


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

namespace BefunWrite.Helper
{
	public static class LinqHelper
	{
		///Finds the index of the first item matching an expression in an enumerable.
		///<param name="items">The enumerable to search.</param>
		///<param name="predicate">The expression to test the items against.</param>
		///<returns>The index of the first matching item, or -1 if no items match.</returns>
		public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate)
		{
			if (items == null) throw new ArgumentNullException("items");
			if (predicate == null) throw new ArgumentNullException("predicate");

			int retVal = 0;
			foreach (var item in items)
			{
				if (predicate(item)) return retVal;
				retVal++;
			}
			return -1;
		}
		///Finds the index of the first occurence of an item in an enumerable.
		///<param name="items">The enumerable to search.</param>
		///<param name="item">The item to find.</param>
		///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
		public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }
	}
}


text:
.. toctree::
   :caption: ADCaaS
   :glob:
   :maxdepth: 1

   F5 OpenStack Services (ADCaaS) <https://clouddocs.f5.com/cloud/openstack/v1/adcaas>

.. toctree::
   :caption: Heat
   :glob:
   :maxdepth: 1

   F5 HOT Library <http://clouddocs.f5.com/products/templates/openstack-heat/latest>
   F5 Plugins for Heat <http://clouddocs.f5.com/products/openstack/heat-plugins/latest>
   Integration Overview <heat/index>
   heat/how-to-deploy-heat-stack
   heat/deploy-bigip-lb-heat-stack

.. toctree::
   :caption: Neutron LBaaS
   :glob:
   :maxdepth: 1

   F5 Agent for Neutron <http://clouddocs.f5.com/products/openstack/agent/latest>
   F5 Driver for Neutron LBaaS <http://clouddocs.f5.com/products/openstack/lbaasv2-driver/latest>
   Integration Overview <lbaas/index>
   lbaas/quick-reference
   lbaas/basic-environment-reqs
   lbaas/bigip-command-mapping
   lbaas/f5-agent-modes
   lbaas/redundancy-and-scaleout
   lbaas/capacity-based-scaleout
   lbaas/hierarchical-port-binding
   lbaas/set-up-agent-hpb
   lbaas/differentiated-service-environments
   lbaas/enhanced-service-definitions
   lbaas/l7-content-switching
   lbaas/applying-multiple-esds
   lbaas/agent-cert-manager-config
   lbaas/ssl-offloading-configuration
   lbaas/manage-common-net-objects
   lbaas/deploy-basic-load-balancer
   lbaas/manage-bigip-clusters
   lbaas/manage-vcmp
   F5 LBaaS v1 integration (EOTS) <http://clouddocs.f5.com/products/openstack/lbaasv1/master>

.. toctree::
   :caption: Troubleshooting
   :glob:
   :maxdepth: 1

   troubleshooting/*

.. toctree::
   :caption: Tutorials
   :glob:
   :maxdepth: 1

   tutorials/*

.. toctree::
   :caption: Support
   :glob:
   :maxdepth: 1

   Releases and Versioning <support/releases_and_versioning>
   support/solution-test-plan
   support/openstack_big-ip_flavors
   support/partners
   support/acknowledgements
   F5 Contributor License Agreement <support/cla_landing>


text:
package org.jspare.forvertx;

import static org.jspare.core.container.Environment.my;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.jspare.core.exception.InfraRuntimeException;
import org.jspare.core.loader.ResourceLoader;

import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.VertxOptionsConverter;
import io.vertx.core.json.JsonObject;
import lombok.AllArgsConstructor;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

/** The Constant log. */
@Slf4j
@Accessors(fluent = true)

/**
 * Instantiates a new vertx manager impl.
 *
 * @param vertxOptions
 *            the vertx options
 * @param vertx
 *            the vertx
 */
@AllArgsConstructor
public class VertxManagerImpl implements VertxManager {

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.jspare.forvertx.VertxManager#vertxOptions(io.vertx.core.VertxOptions)
	 */
	@Setter
	private VertxOptions vertxOptions;

	/** The vertx. */
	private Vertx vertx;

	/**
	 * Instantiates a new vertx manager impl.
	 */
	public VertxManagerImpl() {

		vertxOptions = new VertxOptions();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.jspare.forvertx.VertxManager#clusteredVertx(io.vertx.core.Handler)
	 */
	@Override
	public void clusteredVertx(Handler<Vertx> handler) {

		if (vertx == null) {

			Vertx.clusteredVertx(vertxOptions, result -> {
				if (!result.succeeded()) {
					log.error("Cannot create Vert.x instance");
					throw new InfraRuntimeException(result.cause());
				}
				handler.handle(result.result());
			});
			return;
		}
		handler.handle(vertx);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.jspare.forvertx.VertxManager#loadVertxOptions()
	 */
	@Override
	public VertxManager loadVertxOptions() {
		loadVertxOptions(DEFAULT_VERTX_OPTIONS_JSON_PATH);
		return this;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.jspare.forvertx.VertxManager#loadVertxOptions(java.lang.String)
	 */
	@Override
	@SneakyThrows(IOException.class)
	public VertxManager loadVertxOptions(String path) {
		String content = my(ResourceLoader.class).readFileToString(path);
		if (StringUtils.isNotEmpty(content)) {

			VertxOptionsConverter.fromJson(io.vertx.core.json.Json.decodeValue(content, JsonObject.class), vertxOptions);
		}
		return this;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.jspare.forvertx.VertxManager#vertx()
	 */
	@Override
	public Vertx vertx() {

		if (vertx == null) {

			vertx = Vertx.vertx(vertxOptions);
		}
		return vertx;
	}
}


text:
'use strict';

/**
 * Module dependencies
 */
var followsPolicy = require('../policies/follows.server.policy'),
  follows = require('../controllers/follows.server.controller');

module.exports = function(app) {
  // follows Routes
  app.route('/api/follows').all(followsPolicy.isAllowed)
    .get(follows.list)
    .post(follows.create);

  app.route('/api/follows/:followId').all(followsPolicy.isAllowed)
    .get(follows.read)
    .put(follows.update)
    .delete(follows.delete);

  // Finish by binding the follow middleware
  app.param('followId', follows.followByID);
};


text:
/*
 * Do not modify this file. This file is generated from the monitoring-2010-08-01.normal.json service model.
 */
using System;
using System.Net;
using Amazon.Runtime;

namespace Amazon.CloudWatch.Model
{
    ///<summary>
    /// CloudWatch exception
    /// </summary>
    public class InvalidFormatException : AmazonCloudWatchException
    {
        /// <summary>
        /// Constructs a new InvalidFormatException with the specified error
        /// message.
        /// </summary>
        /// <param name="message">
        /// Describes the error encountered.
        /// </param>
        public InvalidFormatException(string message)
            : base(message) {}

        /// <summary>
        /// Construct instance of InvalidFormatException
        /// </summary>
        /// <param name="message"></param>
        /// <param name="innerException"></param>
        public InvalidFormatException(string message, Exception innerException)
            : base(message, innerException) {}

        /// <summary>
        /// Construct instance of InvalidFormatException
        /// </summary>
        /// <param name="innerException"></param>
        public InvalidFormatException(Exception innerException)
            : base(innerException) {}

        /// <summary>
        /// Construct instance of InvalidFormatException
        /// </summary>
        /// <param name="message"></param>
        /// <param name="innerException"></param>
        /// <param name="errorType"></param>
        /// <param name="errorCode"></param>
        /// <param name="requestId"></param>
        /// <param name="statusCode"></param>
        public InvalidFormatException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
            : base(message, innerException, errorType, errorCode, requestId, statusCode) {}

        /// <summary>
        /// Construct instance of InvalidFormatException
        /// </summary>
        /// <param name="message"></param>
        /// <param name="errorType"></param>
        /// <param name="errorCode"></param>
        /// <param name="requestId"></param>
        /// <param name="statusCode"></param>
        public InvalidFormatException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
            : base(message, errorType, errorCode, requestId, statusCode) {}

    }
}


text:
'use strict';
let mocha = require('mocha');
let should = require('should');
let tests = require('./british_terms.js');

//apply the plugin
const plugin = require('../../src/index.js');
const nlp = require('nlp_compromise');
nlp.plugin(plugin);

let tiny_tests = [
  ['accessorise', 'accessorize'],
  ['accessorised', 'accessorized'],
  ['accessorises', 'accessorizes'],
  ['accessorising', 'accessorizing'],
  ['acclimatisation', 'acclimatization'],
  ['acclimatise', 'acclimatize'],
  ['acclimatised', 'acclimatized'],
  ['acclimatises', 'acclimatizes'],
  ['acclimatising', 'acclimatizing'],
  ['popularise', 'popularize'],
  ['popularised', 'popularized'],
  ['popularises', 'popularizes'],
  ['popularising', 'popularizing'],
  ['pouffe', 'pouf'],
  ['pouffes', 'poufs'],
  ['practise', 'practice'],
  ['practised', 'practiced'],
  ['practises', 'practices']
];

describe('localize', function() {
  //americanize it
  it('americanize', function(done) {
    tests.forEach(function(a) {
      let t = nlp.term(a[0]);
      t.toAmerican().normal.should.equal(a[1]);
    });
    done();
  });
  //britishize it
  it('britishize', function(done) {
    tiny_tests.forEach(function(a) {
      let t = nlp.term(a[1]);
      t.toBritish().normal.should.equal(a[0]);
    });
    done();
  });

});


text:
import csv
from tulip import tlp
dirPath = '/Users/albertocottica/github/local/ODFest2017-horizon2020-network/H2020_Data_2017/'

# The updateVisualization(centerViews = True) function can be called
# during script execution to update the opened views

# The pauseScript() function can be called to pause the script execution.
# To resume the script execution, you will have to click on the "Run script " button.

# The runGraphScript(scriptFile, graph) function can be called to launch
# another edited script on a tlp.Graph object.
# The scriptFile parameter defines the script name to call (in the form [a-zA-Z0-9_]+.py)

# The main(graph) function must be defined
# to run the script on the current graph

def main(graph):
  KCore = graph.getDoubleProperty("K-Core")
  TentativeSIC = graph.getStringProperty("TentativeSIC")
  acronym = graph.getStringProperty("acronym")
  activityType = graph.getStringProperty("activityType")
  barPower = graph.getDoubleProperty("barPower")
  betwCentrality = graph.getDoubleProperty("betwCentrality")
  birthDate = graph.getIntegerProperty("birthDate")
  call = graph.getStringProperty("call")
  city = graph.getStringProperty("city")
  commDate = graph.getDoubleProperty("commDate")
  country = graph.getStringProperty("country")
  ecContribution = graph.getDoubleProperty("ecContribution")
  ecMaxContribution = graph.getDoubleProperty("ecMaxContribution")
  endDate = graph.getStringProperty("endDate")
  endOfParticipation = graph.getBooleanProperty("endOfParticipation")
  fundingScheme = graph.getStringProperty("fundingScheme")
  intimacy = graph.getDoubleProperty("intimacy")
  manager = graph.getBooleanProperty("manager")
  myMoney = graph.getDoubleProperty("myMoney")
  name = graph.getStringProperty("name")
  numPartners = graph.getDoubleProperty("numPartners")
  numProjects = graph.getDoubleProperty("numProjects")
  objective = graph.getStringProperty("objective")
  orgId = graph.getStringProperty("orgId")
  organizationUrl = graph.getStringProperty("organizationUrl")
  postCode = graph.getStringProperty("postCode")
  programme = graph.getStringProperty("programme")
  projectNode = graph.getBooleanProperty("projectNode")
  projectUrl = graph.getStringProperty("projectUrl")
  rcn = graph.getStringProperty("rcn")
  role = graph.getStringProperty("role")
  shortName = graph.getStringProperty("shortName")
  startDate = graph.getStringProperty("startDate")
  status = graph.getStringProperty("status")
  street = graph.getStringProperty("street")
  topics = graph.getStringProperty("topics")
  totMoney = graph.getDoubleProperty("totMoney")
  totalCost = graph.getDoubleProperty("totalCost")
  viewBorderColor = graph.getColorProperty("viewBorderColor")
  viewBorderWidth = graph.getDoubleProperty("viewBorderWidth")
  viewColor = graph.getColorProperty("viewColor")
  viewFont = graph.getStringProperty("viewFont")
  viewFontSize = graph.getIntegerProperty("viewFontSize")
  viewIcon = graph.getStringProperty("viewIcon")
  viewLabel = graph.getStringProperty("viewLabel")
  viewLabelBorderColor = graph.getColorProperty("viewLabelBorderColor")
  viewLabelBorderWidth = graph.getDoubleProperty("viewLabelBorderWidth")
  viewLabelColor = graph.getColorProperty("viewLabelColor")
  viewLabelPosition = graph.getIntegerProperty("viewLabelPosition")
  viewLayout = graph.getLayoutProperty("viewLayout")
  viewMetric = graph.getDoubleProperty("viewMetric")
  viewRotation = graph.getDoubleProperty("viewRotation")
  viewSelection = graph.getBooleanProperty("viewSelection")
  viewShape = graph.getIntegerProperty("viewShape")
  viewSize = graph.getSizeProperty("viewSize")
  viewSrcAnchorShape = graph.getIntegerProperty("viewSrcAnchorShape")
  viewSrcAnchorSize = graph.getSizeProperty("viewSrcAnchorSize")
  viewTexture = graph.getStringProperty("viewTexture")
  viewTgtAnchorShape = graph.getIntegerProperty("viewTgtAnchorShape")
  viewTgtAnchorSize = graph.getSizeProperty("viewTgtAnchorSize")
  wBarPower = graph.getDoubleProperty("wBarPower")
  weightedBarPower = graph.getDoubleProperty("weightedBarPower")
  stablePartners = graph.getDoubleProperty('stablePartners')

  gC = graph.getSubGraph('stableGC')

  # make a list and populated it with all nodes that are part of the giant component.
  inGC = []
  for nGC in gC.getNodes():
    inGC.append(nGC)

  # next, make another list and populate it with all nodes that are NOT in the first list.
  outGC = []
  for n in graph.getNodes():
    if n not in inGC:
      outGC.append(n)

  # make a list of dicts for export as csv. Dicts have the form [GC]n: weightedBarPower[n], where
  # [GC]n takes value 1 if the node is in the giant component, 0 otherwise.

  listOfDicts = []
  for nGC in inGC:
    row = {}
    row['weightedBarPower'] = weightedBarPower[nGC]
    row['numProjects'] = numProjects[nGC]
    row['stablePartners'] = stablePartners[nGC]
    row['GC'] = True
    row['activityType'] = activityType[nGC]
    row['betwCentrality'] = betwCentrality[nGC]
    listOfDicts.append(row)

  for n in outGC:
    row = {}
    row['weightedBarPower'] = weightedBarPower[n]
    row['numProjects'] = numProjects[n]
    row['stablePartners'] = stablePartners[n]
    row['GC'] = False
    row['activityType'] = activityType[n]
    row['betwCentrality'] = betwCentrality[n]
    listOfDicts.append(row)

  with open(dirPath + 'weightedBarPowerByComp.csv', 'w') as outFile:
    fieldnames = ['GC', 'weightedBarPower', 'numProjects', 'stablePartners', 'activityType', 'betwCentrality']
    writer = csv.DictWriter(outFile, fieldnames = fieldnames)
    success = writer.writeheader()
    for row in listOfDicts:
      success = writer.writerow(row)


text:
import Error from '../components/error';

// https://nextjs.org/docs/advanced-features/custom-error-page#404-page
export default function Custom404() {
  return <Error errorCode="404" errorMessage="This page does not exist." />;
}


text:
/*global define console */

define(function(){

	var OPERATOR = {
		NUL: {first:"", sep:",", named: false, ifemp: "", allow: "U"}, //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		"+": {first:"", sep:",", named: false, ifemp: "", allow: "U+R"}, //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		".": {first:".", sep:",", named: false, ifemp: "", allow: "U"}, //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		"/": {first:"/", sep:"/", named: false, ifemp: "", allow: "U"}, //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		";": {first:";", sep:";", named: true, ifemp: "", allow: "U"}, //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		"?": {first:"?", sep:"&", named: true, ifemp: "=", allow: "U"}, //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		"&": {first:"&", sep:"&", named: true, ifemp: "=", allow: "U"}, //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		"#": {first:"#", sep:",", named: false, ifemp: "", allow: "U+R"}, //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		",": {first:"", sep:",", named: false, ifemp: "", allow: "U+R-,"}		 //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
	};

	var VARSPEC_REGEXP = /^((?:(?:[a-zA-Z0-9_])|(?:%[0-9A-F][0-9A-F]))(?:(?:[a-zA-Z0-9_.])|(?:%[0-9A-F][0-9A-F]))*)(?:(\*)|:([0-9]+))?$/;

	function Literal(text) {
		this._text = text;
	}

	Literal.prototype = {
		expand: function(vars) {
			return encodeURI(this._text);
		}
	};

	function encodeString(value, encoding) {
		if (encoding === "U") { //$NON-NLS-0$
			return encodeURIComponent(value).replace(/[!'()*]/g, function(str) {
				return '%' + str.charCodeAt(0).toString(16).toUpperCase(); //$NON-NLS-0$
			});
		}
		if (encoding === "U+R") { //$NON-NLS-0$
			return encodeURI(value).replace(/%5B/g, '[').replace(/%5D/g, ']'); //$NON-NLS-1$ //$NON-NLS-0$
		}
		if (encoding === "U+R-,") { //$NON-NLS-0$
			return encodeURI(value).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/,/g, '%2C'); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$
		}
		throw new Error("Unknown allowed character set: " + encoding);
	}

	function encodeArray(value, encoding, separator) {
		var result = [];
		for (var i=0; i < value.length; i++) {
			if (typeof(value[i]) !== "undefined") { //$NON-NLS-0$
				result.push(encodeString(value[i], encoding));
			}
		}
		return result.join(separator);
	}

	function encodeObject(value, encoding, nameValueSeparator, pairSeparator ) {
		var keys = Object.keys(value);
		var result = [];
		for (var i=0; i < keys.length; i++) {
			if (typeof(value[keys[i]]) !== "undefined") { //$NON-NLS-0$
				result.push(encodeString(keys[i], encoding) + nameValueSeparator + encodeString(value[keys[i]], encoding));
			}
		}
		return result.join(pairSeparator);
	}

	function parseVarSpecs(text) {
		var result = [];
		var rawSpecs = text.split(","); //$NON-NLS-0$
		for (var i=0; i < rawSpecs.length; i++) {
			var match = rawSpecs[i].match(VARSPEC_REGEXP);
			if (match === null) {
				throw new Error("Bad VarSpec: " + text); //$NON-NLS-0$
			}
			result.push({
				name: match[1],
				explode: !!match[2],
				prefix: match[3] ? parseInt(match[3], 10) : -1
			});
		}
		return result;
	}

	function Expression(text) {
		if (text.length === 0) {
			throw new Error("Invalid Expression: 0 length expression"); //$NON-NLS-0$
		}

		this._operator = OPERATOR[text[0]];
		if (this._operator) {
			text = text.substring(1);
		} else {
			this._operator = OPERATOR.NUL;
		}

		this._varSpecList = parseVarSpecs(text);
	}

	Expression.prototype = {
		expand: function(params) {
			var result = [];
			for (var i=0; i < this._varSpecList.length; i++) {
				var varSpec = this._varSpecList[i];
				var name = varSpec.name;
				var value = params[name];
				var valueType = typeof(value);
				if (valueType !== "undefined" && value !== null) { //$NON-NLS-0$
					var resultText = result.length === 0 ? this._operator.first: this._operator.sep;
					if (valueType === "string") { //$NON-NLS-0$
						if (this._operator.named) {
							resultText += encodeString(name, "U+R"); //$NON-NLS-0$
							resultText += (value.length === 0) ? this._operator.ifemp : "="; //$NON-NLS-0$
						}
						if (varSpec.prefix !== -1 && varSpec.prefix < value.length) {
							value = value.substring(0, varSpec.prefix);
						}

						resultText += encodeString(value, this._operator.allow);
					} else if (Array.isArray(value)) {
						if (!varSpec.explode) {
							if (this._operator.named) {
								resultText += encodeString(name, "U+R"); //$NON-NLS-0$
								resultText += (value.length === 0) ? this._operator.ifemp : "="; //$NON-NLS-0$
							}
							resultText += encodeArray(value, this._operator.allow, ","); //$NON-NLS-0$
						} else {
							resultText += encodeArray(value, this._operator.allow, this._operator.sep);
						}
					} else if (valueType === "object") { //$NON-NLS-0$
						if (!varSpec.explode) {
							if (this._operator.named) {
								resultText += encodeString(name, "U+R"); //$NON-NLS-0$
								resultText += (Object.keys(value).length === 0) ? this._operator.ifemp : "="; //$NON-NLS-0$
							}
							resultText += encodeObject(value, this._operator.allow, ",", ","); //$NON-NLS-1$ //$NON-NLS-0$
						} else {
							resultText += encodeObject(value, this._operator.allow, "=", this._operator.sep); //$NON-NLS-0$
						}
					} else {
						throw new Error("bad param type: " + name + " : " + valueType); //$NON-NLS-1$ //$NON-NLS-0$
					}
					result.push(resultText);
				}
			}
			return result.join("");
		}
	};

	function parseTemplate(text) {
		var result = [];
		var current = 0;
		var curlyStartIndex = text.indexOf("{", current); //$NON-NLS-0$
		while (curlyStartIndex !== -1) {
			result.push(new Literal(text.substring(current, curlyStartIndex)));
			var curlyEndIndex = text.indexOf("}", curlyStartIndex + 1); //$NON-NLS-0$
			if (curlyEndIndex === -1) {
				throw new Error("Invalid template: " + text); //$NON-NLS-0$
			}
			result.push(new Expression(text.substring(curlyStartIndex + 1, curlyEndIndex)));
			current = curlyEndIndex + 1;
			curlyStartIndex = text.indexOf("{", current);			 //$NON-NLS-0$
		}
		result.push(new Literal(text.substring(current)));
		return result;
	}

	/**
	 * @name orion.URITemplate
	 * @class A URITemplate describes a range of Uniform Resource Identifiers through variable expansion, and allows for particular URIs to
	 * be generated by expanding variables to actual values.

	 *
Because the syntax and encoding rules of URIs can be complex, URITemplates are recommended over manual construction of URIs through
	 * string concatenation or other means.

	 *
A URITemplate is created by invoking the constructor, passing a template string:

	 *
new URITemplate(template)

	 *
The <dfn>template string</dfn> is an expression following a well-defined syntax (see here
	 * for an introduction). Most notably, the template may include variables.

	 *
Once created, a URITemplate's {@link #expand} method can be invoked to generate a URI. Arguments to {@link #expand} give the values to be
	 * substituted for the template variables.

	 * @description Creates a new URITemplate.
	 * @param {String} template The template string. Refer to RFC 6570 for details
	 * of the template syntax.
	 */
	function URITemplate(template) {
		this._templateComponents = parseTemplate(template);
	}

	URITemplate.prototype = /** @lends orion.URITemplate.prototype */ {
		/**
		 * Expands this URITemplate to a URI.
		 * @param {Object} params The parameters to use for expansion. This object is a map of keys (variable names) to values (the variable's
		 * value in the expansion algorithm).
		 * @returns {String} The resulting URI.
		 */
		expand: function(params) {
			var result = [];
			for (var i = 0; i < this._templateComponents.length; i++) {
				result.push(this._templateComponents[i].expand(params));
			}
			return result.join("");
		}
	};

	return URITemplate;
});


text:
class Monitor
  # rakuten item search api (to set applicationId value)
  HTTP = 'http://'
  MONITOR_URL = '/api/monitor'

  # retriving data via api
  def self.retrieve_data(block, sensor_id)
    url = HTTP + $settings.server_address + MONITOR_URL + "?sensor_id=#{sensor_id}"
    BW::HTTP.get(url, {cookie: $loginSession}) do |response|
      if response.ok?
        data = []
        #p "response=#{response}"
        json = BW::JSON.parse(response.body.to_str)
        data << {
          :id => sensor_id,
          :min => json['min'],
          :max => json['max'],
        }
        block.call(data)
      else
        #App.alert(response.error_message)
        App.alert("監視値の取得に失敗しました")
      end
    end
  end

  def self.post_data(block, sensor_id, min, max)
    url = HTTP + $settings.server_address + MONITOR_URL + "?sensor_id=#{sensor_id}"
    payload = { "#{sensor_id}" => { "min" => "#{min}", "max" => "#{max}" } }
    BW::HTTP.post(url, payload: BW::JSON.generate(payload), cookie: $loginSession) do |response|
      if response.ok?
        p "OK"
      else
        p "NG"
      end
      block.call
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector
        xmlns:android="http://schemas.android.com/apk/res/android">
    <item
            android:state_selected="true"
            android:state_pressed="true"
            android:color="@color/white"/>
    <item
            android:state_selected="false"
            android:state_pressed="true"
            android:color="@color/white"/>
    <item
            android:state_selected="true"
            android:color="@color/lightgrey"/>
    <item
            android:state_selected="false"
            android:color="@color/lightgrey"/>
</selector>


text:
require('ts-node/register');
require('./src/main');


text:
<?php

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Null;
use Symfony\Component\Validator\Constraints\NullValidator;

class NullValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new NullValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->assertTrue($this->validator->isValid(null, new Null()));
    }

    /**
     * @dataProvider getInvalidValues
     */
    public function testInvalidValues($value)
    {
        $constraint = new Null(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $value,
            ));

        $this->assertFalse($this->validator->isValid($value, $constraint));
    }

    public function getInvalidValues()
    {
        return array(
            array(0),
            array(false),
            array(true),
            array(''),
        );
    }
}


text:
package org.bubblecloud.zigbee.api.cluster.impl.general;

import org.bubblecloud.zigbee.api.cluster.impl.api.HVAC.PumpConfigurationAndControl;
import org.bubblecloud.zigbee.api.cluster.impl.api.core.Attribute;
import org.bubblecloud.zigbee.api.cluster.impl.attribute.Attributes;
import org.bubblecloud.zigbee.api.cluster.impl.core.AttributeImpl;
import org.bubblecloud.zigbee.api.cluster.impl.core.ZCLClusterBase;
import org.bubblecloud.zigbee.network.ZigBeeEndpoint;

public class PumpConfigurationAndControlCluster extends ZCLClusterBase implements PumpConfigurationAndControl {

	private static AttributeImpl description;
	private final Attribute[] attributes;

	public PumpConfigurationAndControlCluster(ZigBeeEndpoint zbDevice){
		super(zbDevice);

		description = new AttributeImpl(zbDevice,this, Attributes.DESCRIPTION);

		attributes = new AttributeImpl[]{description};
	}

	@Override
	public short getId() {
		return PumpConfigurationAndControl.ID;
	}

	@Override
	public String getName() {
		return PumpConfigurationAndControl.NAME;
	}

	@Override
	public Attribute[] getStandardAttributes() {
		return attributes;
	}

	public Attribute getAttributeDescription() {
		return description;
	}

}


text:
package com.jfixby.r3.api.ui.unit.shader;

public interface Shader {

}


text:
Parties = new Mongo.Collection("parties");  //on both client and server side (Mongo and moniMongo)

if (Meteor.isClient) {
  angular.module('socially', ['angular-meteor']);

  angular.module('socially').controller('PartiesListCtrl',function ($scope, $meteor) {
    $scope.parties = $meteor.collection(Parties);

    $scope.remove = function(party){
      // $scope.parties.splice($scope.parties.indexOf(party), 1);
      $scope.parties.remove(party);
    };
  });
}


text:
angular.module('WAU.controllers')
    .controller('taskListCtrl',
    ['$scope', function (scope) {

        scope.onDismiss = function (task) {
            task.state = Task.STATE.DISMISSED;
            task.switch = false;
        };

        scope.onComplete = function (task) {
            task.state = Task.STATE.COMPLETED;
            task.switch = true;
        };

        scope.switchChanged = function (task) {
            if (task.switch) {
                scope.onComplete(task);
            } else {
                scope.onDismiss(task);
            }
        };

        scope.getTaskKindInfo = function (task) {
            if (task.kind === Task.KIND.SCHEDULE) {
                return scope.getDateStrFromNow(task.schedule)
            } else if (task.kind === Task.KIND.PLACE) {
                return task.getLocation().name;
            } else {
                return '';
            }
        };

        scope.getTaskKindIcon = function (task) {
            if (task.kind === Task.KIND.SCHEDULE) {
                return 'icons/material/ic_alarm.svg';
            } else if (task.kind === Task.KIND.PLACE) {
                return task.getLocation().iconUrl;
            } else {
                return '';
            }
        };

    }]);


text: SELECT f2('three')


text:
<?php
/**
 * @link       http://zoopcommerce.github.io/shard
 * @package    Zoop
 * @license    MIT
 */
namespace Zoop\Shard\Serializer;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
use Zoop\Shard\Exception;
use Zoop\Shard\Core\ModelManagerAwareInterface;
use Zoop\Shard\Core\ModelManagerAwareTrait;

/**
 * Provides methods for unserializing models
 *
 * @since   1.0
 * @author  Tim Roediger <superdweebie@gmail.com>
 */
class Unserializer implements ServiceLocatorAwareInterface, ModelManagerAwareInterface
{
    use ServiceLocatorAwareTrait;
    use ModelManagerAwareTrait;

    const UNSERIALIZE_UPDATE = 'unserialize_update';
    const UNSERIALIZE_PATCH = 'unserliaze_patch';

    /** @var array */
    protected $typeSerializers = [];

    public function setTypeSerializers(array $typeSerializers)
    {
        $this->typeSerializers = $typeSerializers;
    }

    public function fieldList(ClassMetadata $metadata, $includeId = true)
    {
        $return = [];
        $serializerMetadata = $metadata->getSerializer();

        foreach ($metadata->getFieldNames() as $field) {
            if (isset($serializerMetadata['fields'][$field]['unserializeIgnore']) &&
                $serializerMetadata['fields'][$field]['unserializeIgnore']
            ) {
                continue;
            }
            $return[] = $field;
        }

        if (!$includeId) {
            unset($return[$metadata->getIdentifier()]);
        }

        return $return;
    }

    /**
     * This will create a document from the supplied array.
     *
     * @param  array $data
     * @param  type  $class
     * @param  type  $document
     * @param  type  $mode
     * @return type
     */
    public function fromArray(
        array $data,
        $class,
        $document = null,
        $mode = self::UNSERIALIZE_PATCH
    ) {
        return $this->unserialize($data, $class, $document, $mode);
    }

    /**
     *
     * @param  type $data
     * @param  type $class
     * @param  type $document
     * @param  type $mode
     * @return type
     */
    public function fromJson(
        $data,
        $class,
        $document = null,
        $mode = self::UNSERIALIZE_PATCH
    ) {
        return $this->unserialize(json_decode($data, true), $class, $document, $mode);
    }

    /**
     *
     * @param  array                            $data
     * @param  array                            $className
     * @param  type                             $mode
     * @param  type                             $document
     * @return type
     * @throws Exception\ClassNotFoundException
     */
    protected function unserialize(
        array $data,
        $class,
        $document = null,
        $mode = self::UNSERIALIZE_PATCH
    ) {
        $metadata = $this->modelManager->getClassMetadata($class);

        // Check for discrimnator and discriminator field in data
        if (isset($metadata->discriminatorField) && isset($data[$metadata->discriminatorField])) {
            $metadata = $this->modelManager->getClassMetadata(
                $metadata->discriminatorMap[$data[$metadata->discriminatorField]]
            );
        }

        // Check for reference
        if (isset($data['$ref'])) {
            return $this->modelManager->getRepository($metadata->name)->find($data['$ref']);
        }

        // Attempt to load prexisting model
        if (!isset($document) && isset($data[$metadata->identifier])) {
            $document = $this->modelManager->getRepository($metadata->name)->find($data[$metadata->identifier]);
        }

        $newInstance = false;
        if (! isset($document)) {
            $document = $metadata->newInstance();
            $newInstance = true;
        }

        foreach ($this->fieldList($metadata, $newInstance) as $field) {
            $this->unserializeField($data, $metadata, $document, $field, $mode);
        }

        return $document;
    }

    protected function unserializeField($data, ClassMetadata $metadata, $document, $field, $mode)
    {
        if ($metadata->hasAssociation($field) && $metadata->isSingleValuedAssociation($field)) {
            $value = $this->unserializeSingleModel($data, $metadata, $document, $field, $mode);
        } elseif ($metadata->hasAssociation($field)) {
            $value = $this->unserializeCollection($data, $metadata, $document, $field, $mode);
        } else {
            $value = $this->unserializeSingleValue($data, $metadata, $field);
        }

        if (isset($value)) {
            $metadata->setFieldValue($document, $field, $value);
        } elseif ($mode == self::UNSERIALIZE_UPDATE) {
            $metadata->setFieldValue($document, $field, null);
        }
    }

    protected function unserializeSingleModel($data, ClassMetadata $metadata, $document, $field, $mode)
    {
        if (!isset($data[$field])) {
            return null;
        }

        if (isset($data[$field]['$ref'])) {
            return $this->modelManager
                ->getRepository($this->getTargetClass($metadata, $data[$field], $field))
                ->find($data[$field]['$ref']);
        }

        if (is_string($data[$field])) {
            $document = $this->modelManager->getRepository($metadata->name)->find($data[$field]);
        }

        $targetClass = $this->getTargetClass($metadata, $data[$field], $field);

        return $this->unserialize(
            $data[$field],
            $targetClass,
            $metadata->getFieldValue($document, $field),
            $mode
        );
    }

    protected function unserializeCollection($data, ClassMetadata $metadata, $document, $field, $mode)
    {
        $collection = new ArrayCollection;

        if (isset($data[$field])) {
            foreach ($data[$field] as $dataItem) {
                $targetClass = $this->getTargetClass($metadata, $dataItem, $field);
                if (isset($dataItem['$ref'])) {
                    $collection[] = $this->modelManager->getRepository($targetClass)->find($dataItem['$ref']);
                } else {
                    $collection[] = $this->unserialize($dataItem, $targetClass, null, $mode);
                }
            }
        } elseif ($mode == self::UNSERIALIZE_PATCH &&
            $existingCollection = $metadata->getFieldValue($document, $field)
        ) {
            return $existingCollection;
        }

        return $collection;
    }

    protected function unserializeSingleValue($data, ClassMetadata $metadata, $field)
    {
        if (!isset($data[$field])) {
            return null;
        }

        $type = $metadata->getTypeOfField($field);

        if (isset($this->typeSerializers[$type])) {
            return $this->serviceLocator->get($this->typeSerializers[$type])
                ->unserialize($data[$field], $metadata, $field);
        }
        if ($type == 'float' && is_integer($data[$field])) {
            return (float) $data[$field];
        }

        return $data[$field];
    }

    protected function getTargetClass(ClassMetadata $metadata, $data, $field)
    {
        $mapping = $metadata->fieldMappings[$field];
        if (isset($mapping['discriminatorMap'])) {
            $discriminatorField = isset($mapping['discriminatorField']) ?
            $mapping['discriminatorField'] :
            '_doctrine_class_name';
            $targetClass = $mapping['discriminatorMap'][$data[$discriminatorField]];
        } elseif (isset($mapping['targetDocument']) && class_exists($mapping['targetDocument'])) {
            $targetClass = $mapping['targetDocument'];
        } else {
            $targetClass = $metadata->getAssociationTargetClass($field);
        }

        return $targetClass;
    }
}


text:
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
typedef struct in_addr IN_ADDR;

#endif

#define CRLF        "\r\n"
#define MAX_CLIENTS 10

typedef struct
{
   SOCKET sock;
   uint8_t connected; // 0 = not connected, otherwise identifier
} peer;

void tcp_initialize(void)
{
#ifdef WIN32
   WSADATA wsa;
   int err = WSAStartup(MAKEWORD(2, 2), &wsa);
   if(err < 0)
   {
      puts("WSAStartup failed !");
      exit(EXIT_FAILURE);
   }
#endif
}

void tcp_end(void)
{
#ifdef WIN32
   WSACleanup();
#endif
}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.cloudsearch.v1.model;

/**
 * Reference to a transcoded video attachment.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Search API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class AppsDynamiteSharedVideoReference extends com.google.api.client.json.GenericJson {

  /**
   * Available transcode format. Value is defined in video/storage/proto/content_header.proto
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.Integer> format;

  /**
   * Transcode status
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String status;

  /**
   * Available transcode format. Value is defined in video/storage/proto/content_header.proto
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.Integer> getFormat() {
    return format;
  }

  /**
   * Available transcode format. Value is defined in video/storage/proto/content_header.proto
   * @param format format or {@code null} for none
   */
  public AppsDynamiteSharedVideoReference setFormat(java.util.List<java.lang.Integer> format) {
    this.format = format;
    return this;
  }

  /**
   * Transcode status
   * @return value or {@code null} for none
   */
  public java.lang.String getStatus() {
    return status;
  }

  /**
   * Transcode status
   * @param status status or {@code null} for none
   */
  public AppsDynamiteSharedVideoReference setStatus(java.lang.String status) {
    this.status = status;
    return this;
  }

  @Override
  public AppsDynamiteSharedVideoReference set(String fieldName, Object value) {
    return (AppsDynamiteSharedVideoReference) super.set(fieldName, value);
  }

  @Override
  public AppsDynamiteSharedVideoReference clone() {
    return (AppsDynamiteSharedVideoReference) super.clone();
  }

}


text:
var urlEncode = function(string) {
  return string.replace(new RegExp('/', 'g'), '%2F').replace(new RegExp(':', 'g'), '%3A');
}

// start /index js
//-------------------------------------
$('a.index_toggle').on('click', function(event) {

  var _this = $(this);
  var dataModule = $(this).attr('data-module');

  var url = '/toggle-enabled/' + urlEncode(dataModule);
  $.ajax(url, {
    method: 'GET',
    success: function(data, textStatus, jqXHR) {
      console.log('JS | ' + url + ' | success');
      if (_this.hasClass('btn-success')) {
        _this.removeClass('btn-success').addClass('btn-default');
        _this.text('Off');
      } else {
        _this.removeClass('btn-default').addClass('btn-success');
        _this.text('On');
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log('JS | ' + url + ' | error');
    }
  });
});

// start /pizza js
//-------------------------------------
$('input, select').on('focus', function(event) {
  $(this).parent().removeClass('has-error').removeClass('has-success');
});

$('input, select').on('blur', function(event) {
  var target_ids = ['pizza_firstName', 'pizza_lastName', 'pizza_phone', 'pizza_email', 'pizza_street', 'pizza_city', 'pizza_zip', 'pizza_card_number', 'pizza_card_type', 'pizza_card_expiration', 'pizza_card_ccv', 'pizza_card_zip'];
  var id = $(this).attr('id');

  if ($.inArray(id, target_ids) == -1) return;

  var val = $(this).val();
  if (val === '') return;

  var parent = $(this).parent();
  var url = '/pizza/input/' + urlEncode(id.replace('pizza_', '')) + '/' + urlEncode(val);
  $.ajax(url, {
    method: 'GET',
    success: function(data, textStatus, jqXHR) {
      console.log('JS | ' + url + ' | success');
      parent.removeClass('parent');
      parent.addClass('has-success');
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log('JS | ' + url + ' | error');
      parent.removeClass('has-success');
      parent.addClass('has-error');
    }
  });
});

$('a.order_action').on('click', function(event) {

  var dataAction = $(this).attr('data-action');
  var dataCode = $(this).attr('data-code');

  var url = '/pizza/order/' + urlEncode(dataAction) + '/' + urlEncode(dataCode);
  $.ajax(url, {
    method: 'GET',
    success: function(data, textStatus, jqXHR) {
      console.log('JS | ' + url + ' | success');
      location.reload();
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log('JS | ' + url + ' | error');
    }
  });
});


text:
#include "servant/Global.h"
#include "servant/BaseF.h"

namespace tars
{

//////////////////////////////////////////////////////////////////////////
void TarsException::throwException(int ret, const string& desc)
{
    switch (ret)
    {
    case tars::TARSSERVERSUCCESS:
        break;
    case TARSSERVERDECODEERR:
        throw TarsServerDecodeException("server decode exception: ret:" + TC_Common::tostr(ret) + " msg:"+ desc);
        break;
    case TARSSERVERENCODEERR:
        throw TarsServerEncodeException("server encode exception: ret:" + TC_Common::tostr(ret) + " msg:"+ desc);
        break;
    case TARSSERVERNOFUNCERR:
        throw TarsServerNoFuncException("server function mismatch exception: ret:" + TC_Common::tostr(ret) + " msg:"+ desc);
        break;
    case TARSSERVERNOSERVANTERR:
        throw TarsServerNoServantException("server servant mismatch exception: ret:" + TC_Common::tostr(ret) + " msg:"+ desc);
        break;
    case TARSSERVERQUEUETIMEOUT:
        throw TarsServerQueueTimeoutException("server queue timeout exception: ret:" + TC_Common::tostr(ret) + " msg:"+ desc);
        break;
    case TARSPROXYCONNECTERR:
        throw TarsServerQueueTimeoutException("server connection lost: ret:" + TC_Common::tostr(ret) + " msg:"+ desc);
        break;
    default:
        throw TarsServerUnknownException("server unknown exception: ret:" + TC_Common::tostr(ret) + " msg:"+ desc);
    }
}
////////////////////////////////////////////////////////////////////////////
}


text:
define(
//begin v1.x content
({
	displayOptions: "[Visningsalternativ]",
	title: "Rubrik",
	authors: "Författare",
	contributors: "Medverkande",
	id: "ID",
	close: "[Stäng]",
	updated: "Uppdaterat",
	summary: "Sammanfattning",
	content: "Innehåll"
})
//end v1.x content
);


text:
import os
import shutil
import subprocess
import sys

def main(args):
    script_dir = os.path.dirname(__file__)
    crashpad_dir = os.path.join(script_dir, os.pardir, os.pardir)

    # Run from the Crashpad project root directory.
    os.chdir(crashpad_dir)

    output_dir = os.path.join('out', 'doc', 'doxygen')

    if os.path.isdir(output_dir) and not os.path.islink(output_dir):
        shutil.rmtree(output_dir)
    elif os.path.exists(output_dir):
        os.unlink(output_dir)

    os.makedirs(output_dir, 0o755)

    doxy_file = os.path.join('doc', 'support', 'crashpad.doxy')
    subprocess.check_call(['doxygen', doxy_file])

    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))


text:
namespace web {

class SerializableUserDataManagerImpl : public SerializableUserDataManager {
 public:
  SerializableUserDataManagerImpl();

  SerializableUserDataManagerImpl(const SerializableUserDataManagerImpl&) =
      delete;
  SerializableUserDataManagerImpl& operator=(
      const SerializableUserDataManagerImpl&) = delete;

  ~SerializableUserDataManagerImpl();

  // SerializableUserDataManager:
  void AddSerializableData(id<NSCoding> data, NSString* key) override;
  id<NSCoding> GetValueForSerializationKey(NSString* key) override;
  CRWSessionUserData* GetUserDataForSession() const override;
  void SetUserDataFromSession(CRWSessionUserData* data) override;

 private:
  // The object storing the user data.
  __strong CRWSessionUserData* data_;
};

}  // namespace web

#endif  // IOS_WEB_NAVIGATION_SERIALIZABLE_USER_DATA_MANAGER_IMPL_H_


text:
#include "sim/fd_entry.hh"

#include "sim/serialize.hh"

void
FDEntry::serialize(CheckpointOut &cp) const
{
    SERIALIZE_SCALAR(_closeOnExec);
}

void
FDEntry::unserialize(CheckpointIn &cp)
{
    UNSERIALIZE_SCALAR(_closeOnExec);
}

void
FileFDEntry::serialize(CheckpointOut &cp) const
{
    SERIALIZE_SCALAR(_closeOnExec);
    SERIALIZE_SCALAR(_flags);
    SERIALIZE_SCALAR(_fileName);
    SERIALIZE_SCALAR(_fileOffset);
}

void
FileFDEntry::unserialize(CheckpointIn &cp)
{
    UNSERIALIZE_SCALAR(_closeOnExec);
    UNSERIALIZE_SCALAR(_flags);
    UNSERIALIZE_SCALAR(_fileName);
    UNSERIALIZE_SCALAR(_fileOffset);
}

void
PipeFDEntry::serialize(CheckpointOut &cp) const
{
    SERIALIZE_SCALAR(_closeOnExec);
    SERIALIZE_SCALAR(_flags);
    //SERIALIZE_SCALAR(_pipeEndType);
}

void
PipeFDEntry::unserialize(CheckpointIn &cp)
{
    UNSERIALIZE_SCALAR(_closeOnExec);
    UNSERIALIZE_SCALAR(_flags);
    //UNSERIALIZE_SCALAR(_pipeEndType);
}

void
DeviceFDEntry::serialize(CheckpointOut &cp) const
{
    SERIALIZE_SCALAR(_closeOnExec);
    //SERIALIZE_SCALAR(_driver);
    SERIALIZE_SCALAR(_fileName);
}

void
DeviceFDEntry::unserialize(CheckpointIn &cp)
{
    UNSERIALIZE_SCALAR(_closeOnExec);
    //UNSERIALIZE_SCALAR(_driver);
    UNSERIALIZE_SCALAR(_fileName);
}


text:
<?php

namespace Illuminate\Tests\Integration\View;

use Exception;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
use Orchestra\Testbench\TestCase;

class RenderableViewExceptionTest extends TestCase
{
    public function testRenderMethodOfExceptionThrownInViewGetsHandled()
    {
        Route::get('/', function () {
            return View::make('renderable-exception');
        });

        $response = $this->get('/');

        $response->assertSee('This is a renderable exception.');
    }

    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('view.paths', [__DIR__.'/templates']);
    }
}

class RenderableException extends Exception
{
    public function render($request)
    {
        return new Response('This is a renderable exception.');
    }
}


text:
var jsConsole;

(function () {

    function carBuilder(brand, model, year, type, gearsCount, gearboxType) {
        var car = {
            brand: brand,
            model: model,
            year: year,
            type: type,
            gearbox: {
                gearsCount: gearsCount,
                gearboxType: gearboxType
            }
        }
        return car;
    };

    var myCar = carBuilder("opel", "mokka", 2014, "suv", 6,"menual");
    printObj(myCar);

    var prop = "year",
        hasProp = hasProperty(myCar, prop);

    if (hasProp) {
        jsConsole.writeLine("The property \'" + prop + "\' exists. " )
    }
    else {
        jsConsole.writeLine("There is no such property - " + prop);
    }

    function hasProperty(obj, prop) {
        return obj.hasOwnProperty(prop);
    }

    function printObj(obj) {
        if (obj === null || typeof (obj) !== 'object') {
            jsConsole.writeLine(obj);
            return 0;
        }

        for (var prop in obj) {
            jsConsole.write(prop + " ");
            printObj(obj[prop]);
        }
    }

}());


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

namespace ZimmerBot.Core.Processors
{
  public class ProcessorRegistration
  {
    public string Name { get; protected set; }

    public List<string> RequiredOutputTemplateNames { get; protected set; }

    public Func<ProcessorInput, ProcessorOutput> Function { get; protected set; }

    public ProcessorRegistration(string name, Func<ProcessorInput, ProcessorOutput> f)
    {
      Condition.Requires(name, nameof(name)).IsNotNullOrEmpty();
      Condition.Requires(f, nameof(f)).IsNotNull();

      Name = name;
      RequiredOutputTemplateNames = new List<string>();
      Function = f;
    }

    public ProcessorRegistration WithRequiredTemplate(string templateName)
    {
      RequiredOutputTemplateNames.Add(templateName);
      return this;
    }
  }
}


text:
<?php

namespace Ekyna\Component\Commerce\Common\Currency;

/**
 * Class AbstractExchangeRateProvider
 * @package Ekyna\Component\Commerce\Common\Currency
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
abstract class AbstractExchangeRateProvider implements ExchangeRateProviderInterface
{
    /**
     * @var ExchangeRateProviderInterface
     */
    private $fallback;

    /**
     * Constructor.
     *
     * @param ExchangeRateProviderInterface|null $fallback
     */
    public function __construct(ExchangeRateProviderInterface $fallback = null)
    {
        $this->fallback = $fallback;
    }

    /**
     * @inheritDoc
     */
    public function get(string $base, string $quote, \DateTime $date): ?float
    {
        if (null !== $rate = $this->fetch($base, $quote, $date)) {
            return $rate;
        }

        if (null === $this->fallback) {
            return null;
        }

        if (null !== $rate = $this->fallback->get($base, $quote, $date)) {
            $this->persist($base, $quote, $date, $rate);
        }

        return $rate;
    }

    /**
     * Fetches the exchange rate.
     *
     * @param string    $base
     * @param string    $quote
     * @param \DateTime $date
     *
     * @return float|null
     */
    abstract protected function fetch(string $base, string $quote, \DateTime $date): ?float;

    /**
     * Persists the exchange rate.
     *
     * @param string    $base
     * @param string    $quote
     * @param \DateTime $date
     * @param float     $rate
     */
    abstract protected function persist(string $base, string $quote, \DateTime $date, float $rate): void;

    /**
     * Builds the exchange rate cache key.
     *
     * @param string    $base
     * @param string    $quote
     * @param \DateTime $date
     *
     * @return string
     */
    protected function buildKey(string $base, string $quote, \DateTime $date): string
    {
        return sprintf("%s-%s-%s", $base, $quote, $date->format('YmdHi'));
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="gps2-1.css">
    <title>Git Cheat Sheet</title>

GitHub: Git Cheat Sheet

Git is the open source distributed version control system that
        facilitates GitHub activities on your laptop or desktop.
        This cheat sheet summarizes commonly used Git command line
        instructions for quick reference.

INSTALL GIT

GitHub provides desktop clients that include a graphical user
        interface for the most common repository actions and an automatically
        updating command line edition of Git for advanced scenarios.

GitHub for Windows

GitHub for Mac

Git for All Platforms

        Git distributions for Linux and POSIX systems are available on the
        official Git SCM web site.

CONFIGURE TOOLING

Configure user information for all local repositories

 To see a summary of each command, click it.

          $ git config --global user.name "[name]"

Sets the name you want attached to your commit transactions

          $ git config --global user.email "[email address]"

Sets the email you want atached to your commit transactions

          $ git config --global color.ui auto

Enables helpful colorization of command line output

CREATE REPOSITORIES

Start a new repository or obtain one from an existing URL

          $ git init [project-name]

Creates a new local repository with the specified name

          $ git clone [url]

Downloads a project and its entire version history

MAKE CHANGES

Review edits and craft a commit transaction

          $ git status

Lists all new or modified files to be committed

          $ git add [file]

Snapshots the file in preparation for versioning

          $ git reset [file]

Unstages the file, but preserve its contents

          $ git diff

Shows file differences not yet staged

          $ git diff --staged

Shows file differences between staging and the last file version

          $ git commit -m "[descriptive message]"

Records file snapshots permanently in version history

GROUP CHANGES

Name a series of commits and combine completed efforts

          $ git branch

Lists all local branches in the current repository

          $ git branch [branch-name]

Creates a new branch

          $ git checkout [branch-name]

Switches to the specified branch and updates the working directory

          $ git merge [branch]

Combines the specified branch's history into the current branch

          $ git branch -d [branch-name]

Deletes the specified branch

REFACTOR FILENAMES

Relocate and remove versioned files

          $ git rm [file]

Deletes the file from the working directory and stages the deletion

          $ git rm --cached [file]

Removes the file from version control but preserves the file locally

          $ git mv [file-original] [file-renamed]

Changes the file name and prepares it for commit

SUPPRESS TRACKING

Exclude temporary files and paths

          *.log
                    build/
                    temp-*

A text file named .gitignore suppresses accidental versioning of files and paths matching the specified paterns

          $ git ls-files --other --ignored --exclude-standard

Lists all ignored files in this project

SAVE FRAGMENTS

Shelve and restore incomplete changes

          $ git stash

Temporarily stores all modified tracked files

          $ git stash listLists all stashed changesets

          $ git stash pop

Restores the most recently stashed files

          $ git stash drop

Discards the most recently stashed changeset

REVIEW HISTORY

Browse and inspect the evolution of project files

          $ git log

Lists version history for the current branch

          $ git log --follow [file]

Lists version history for a file, including renames

          $ git diff [first-branch]...[second-branch]

Shows content differences between two branches

          $ git show [commit]

Outputs metadata and content changes of the specified commit

REDO COMMITS

Erase mistakes and craft replacement history

          $ git reset [commit]

Undoes all commits after [commit], preserving changes locally

          $ git reset --hard [commit]

Discards all history and changes back to the specified commit

SYNCHRONIZE CHANGES

Register a repository bookmark and exchange version history

          $ git fetch [bookmark]

Downloads all history from the repository bookmark

          $ git merge [bookmark]/[branch]

Combines bookmark's branch into current local branch

          $ git push [alias] [branch]

Uploads all local branch commits to GitHub

          $ git pull

Downloads bookmark history and incorporates changes

      This information is copied directly from GitHub's Training Cheatsheet.


text:
package com.tencent.mm.sdk.modelbase;

import android.os.Bundle;

public abstract class BaseReq
{

    public String openId;
    public String transaction;

    public BaseReq()
    {
    }

    public abstract boolean checkArgs();

    public void fromBundle(Bundle bundle)
    {
        transaction = bundle.getString("_wxapi_basereq_transaction");
        openId = bundle.getString("_wxapi_basereq_openid");
    }

    public abstract int getType();

    public void toBundle(Bundle bundle)
    {
        bundle.putInt("_wxapi_command_type", getType());
        bundle.putString("_wxapi_basereq_transaction", transaction);
        bundle.putString("_wxapi_basereq_openid", openId);
    }
}


text:
package net.pens.pensmessenger.app.model;

import com.kii.cloud.storage.KiiObject;
import com.kii.cloud.storage.exception.IllegalKiiBaseObjectFormatException;

/**
 * Common base class for Domain classes.
 *
 * @author noriyoshi.fukuzaki@kii.com
 */
public abstract class KiiObjectWrapper {

	// Following fields are reserved fields.
	// You can use these fields as a query condition or sort condition.
	public static final String FIELD_ID = "_id";
	public static final String FIELD_CREATED = "_created";
	public static final String FIELD_MODIFIED = "_modified";

	protected final KiiObject kiiObject;

	public KiiObjectWrapper(KiiObject object) {
		this.kiiObject = object;
	}

	protected void set(String key, String value) {
		this.kiiObject.set(key, value);
	}
	protected void remove(String key) {
		this.kiiObject.remove(key);
	}
	protected String getString(String key) {
		try {
			return this.kiiObject.getString(key);
		} catch (IllegalKiiBaseObjectFormatException e) {
			return null;
		}
	}
	protected Boolean getBoolean(String key) {
		try {
			return this.kiiObject.getBoolean(key);
		} catch (IllegalKiiBaseObjectFormatException e) {
			return null;
		}
	}
	public KiiObject getKiiObject() {
		return this.kiiObject;
	}
	public long getCreatedTime() {
		return this.kiiObject.getCreatedTime();
	}
	public long getModifedTime() {
		return this.kiiObject.getModifedTime();
	}
	@Override
	public String toString() {
		return this.kiiObject.toString();
	}
}


text:
typedef struct {
//current position
unsigned long u4CurrentPosition;
//macro position
unsigned long u4MacroPosition;
//Infiniti position
unsigned long u4InfPosition;
//Motor Status
bool          bIsMotorMoving;
//Motor Open?
bool          bIsMotorOpen;
//Support SR?
bool          bIsSupportSR;
} stAK7345AF_MotorInfo;

//Control commnad
//S means "set through a ptr"
//T means "tell by a arg value"
//G means "get by a ptr"
//Q means "get by return a value"
//X means "switch G and S atomically"
//H means "switch T and Q atomically"
#define AK7345AFIOC_G_MOTORINFO _IOR(AK7345AF_MAGIC,0,stAK7345AF_MotorInfo)

#define AK7345AFIOC_T_MOVETO _IOW(AK7345AF_MAGIC,1,unsigned long)

#define AK7345AFIOC_T_SETINFPOS _IOW(AK7345AF_MAGIC,2,unsigned long)

#define AK7345AFIOC_T_SETMACROPOS _IOW(AK7345AF_MAGIC,3,unsigned long)

#else
#endif


text:
@implementation SDLDiagnosticMessageResponse

- (instancetype)init {
    if (self = [super initWithName:NAMES_DiagnosticMessage]) {
    }
    return self;
}

- (instancetype)initWithDictionary:(NSMutableDictionary *)dict {
    if (self = [super initWithDictionary:dict]) {
    }
    return self;
}

- (void)setMessageDataResult:(NSMutableArray *)messageDataResult {
    if (messageDataResult != nil) {
        [parameters setObject:messageDataResult forKey:NAMES_messageDataResult];
    } else {
        [parameters removeObjectForKey:NAMES_messageDataResult];
    }
}

- (NSMutableArray *)messageDataResult {
    return [parameters objectForKey:NAMES_messageDataResult];
}

@end


text:
typedef std::vector<double> vec_dbl;
void linspace(double a, double b, double *z, int n);
void linspaceV(double a, double b, vec_dbl &x);
double sum_of_squares(double *x, int n);
double sum_of_squaresV(vec_dbl x);


text:
from __future__ import print_function

import sublime, sublime_plugin
import subprocess
import threading

DEBUG = False

# Base rsync command template: rsync -arv <local> <remote>
base_cmd = "rsync -arv {0} {1}"

class SyncOnSaveCommand(sublime_plugin.EventListener):
    def on_post_save(self, view):
        """ Sync directory containing the current directory after saving. """
        synced_dirs = sublime.load_settings("SyncOnSave.sublime-settings").get("synced_dirs")

        file_name = view.file_name()

        for synced_dir in synced_dirs.keys():
            if file_name.startswith(synced_dir):
                # Current file is in a synced directory.
                remote = synced_dirs[synced_dir]["remote"]
                cmd = base_cmd.format(synced_dir, remote)

                if DEBUG:
                    print(cmd)

                # Execute rsync in a new thread, to avoid noticeable network lag on save.
                thread = threading.Thread(target=subprocess.call, args=(cmd,), kwargs={"shell": True})
                thread.daemon = True
                thread.start()


text:
//Provides Brunel event handling and communication facilities that are relatively agnostic to a specific GUI toolkit
//used to create the UI controls.

//Using Tiny Pub/Sub for now.  May need to replace..
(function($) {

  var o = $({});

  $.subscribe = function() {
    o.on.apply(o, arguments);
  };

  $.unsubscribe = function() {
    o.off.apply(o, arguments);
  };

  $.publish = function() {
    o.trigger.apply(o, arguments);
  };

}(jQuery));

function BrunelEventHandlers (brunel) {

	var brunel = brunel;			//The Brunel visualization to operate on
	var filterHandler;				//Handles all filter requests (multiple filters)

	/**
	 * A simple filter handler.
	 *
	 * Example Filter event:
	 *
	 *  {
    		"aFieldId" : {
    			"filter" : {"min":0, "max":10}  //or array of selected categories
    			"filter_type" : 'range',        //or 'category'
    			"datasetIndex" : 0              //Index of the dataset containing the field in the brunel instance
    		}
        }

	 *
	 */
	function FilterHandler(defaultFilter)   {

		//All filter values for the given visualization are by field id and whether the field's type.
        var filterState = defaultFilter;

        function makeFilterStatement (data) {

        	var filterStatement = "";
        	for (var field in filterState) {
                var state = filterState[field];

        		//Only filter on fields known to be in the particular dataset
                if (data === brunel.data(null,state.datasetIndex)) {
	        		if (state.filter_type === 'range') {
	        			filterStatement += makeRangeFilter(field, state.filter, state.keepMissing);
	        		}
	        		else if (state.filter_type === 'category') {
	        			filterStatement += makeCategoryFilter(field, state.filter, state.keepMissing);
	        		}
	        		filterStatement += ";";
//	        		console.log("Appended Filter Statement for dataset (" + filterState[field].datasetIndex + "): " + filterStatement )
        		}

			}

        	return filterStatement.substring(0,filterStatement.length-1);
        }

        function makeRangeFilter(field, filter, keepMissing) {
        	return field + " in " + filter.min + ", " + filter.max + (keepMissing ? " || missing" : "");
        }

        function makeCategoryFilter(field, filter, keepMissing) {
        	var filterCommand = field + " is ";
        	for (var filterVal in filter) {
        		filterCommand += filter[filterVal] + ", ";
			}
        	return filterCommand.substring(0,filterCommand.length-1) + (keepMissing ? " || missing" : "");
		}

		return {

			//Executes a request to filter
			filter: function (filterField, filterValue, animationSpeed) {
				 if (animationSpeed == null) animationSpeed = 500;
	             if (filterField != null && filterValue != null) {
					 filterState[filterField] = filterValue;
					 buildVisualization(animationSpeed);
	             }
			},

			//Generates a single filter statment for all filter controls
			makeFilterStatement:  makeFilterStatement
		}
	}

	function createFilterHandlerAndSubscribe(defaultFilter) {

		if (!defaultFilter) defaultFilter = {};
    	filterHandler = FilterHandler(defaultFilter);
        addDataProcess();

		$.subscribe('filter.' + brunel.visId, function (_, a, b, c) {
			filterHandler.filter(a, b, c);
		});
     }

	//All data pre & post processing needed should be coordinated here.
	//Currently this is just processing the filtering
	function addDataProcess() {

		brunel.dataPreProcess(function (data) {
			return data.filter(filterHandler.makeFilterStatement(data))
		});
	}

	//Rebuild a visualization including any data processing.
	function buildVisualization(animationSpeed) {
		addDataProcess();
    	brunel.rebuild(animationSpeed);
	}

	return {
		//Create a filter handler with a default (can be null or empty).
		make_filter_handler: function (defaultFilter) {
			createFilterHandlerAndSubscribe(defaultFilter);
		}
     }

};


text:
package com.advancedpwr.record.methods;

import com.advancedpwr.record.AccessPath;

public class ArrayBuilder extends AbstractMultiBuilder
{
	private static final String ARRAY = "Array";

	protected void writePopulators()
	{
		int index = 0;
		for ( AccessPath result : getInstanceTree().getAccessPaths() )
		{
			BuildMethodWriter builder = createCachedInstanceMethodBuilder( result );
			writeLine( instanceName() + "[" + index++ + "] = " + builder.resultBuilder() );
		}
	}

	protected String instanceName()
	{
		return nameRoot().toLowerCase() + ARRAY + getAccessPath().suffix() + depth();
	}

	public String resultBuilder()
	{
		return "build" + nameRoot() + ARRAY + getAccessPath().suffix() + depth() + "()";
	}

	protected String nameRoot()
	{
		return getAccessPath().getResultClass().getComponentType().getSimpleName();
	}

	protected void writeInstance()
	{
		writeIfNotNullReturnInstance();
		writeLine( instanceName() + " = new " + nameRoot() + "[" + getInstanceTree().getAccessPaths().size() + "]");
	}

}


text:
package org.knowm.xchange.ftx.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;

public class FtxModifyConditionalOrderRequestPayload {

  private final BigDecimal orderPrice;

  private final BigDecimal triggerPrice;

  private final BigDecimal trailValue;

  private final BigDecimal size;

  public FtxModifyConditionalOrderRequestPayload(
      @JsonProperty("orderPrice") BigDecimal orderPrice,
      @JsonProperty("triggerPrice") BigDecimal triggerPrice,
      @JsonProperty("trailValue") BigDecimal trailValue,
      @JsonProperty("size") BigDecimal size) {
    this.orderPrice = orderPrice;
    this.triggerPrice = triggerPrice;
    this.trailValue = trailValue;
    this.size = size;
  }

  public BigDecimal getOrderPrice() {
    return orderPrice;
  }

  public BigDecimal getTriggerPrice() {
    return triggerPrice;
  }

  public BigDecimal getTrailValue() {
    return trailValue;
  }

  public BigDecimal getSize() {
    return size;
  }

  @Override
  public String toString() {
    return "FtxModifyOrderRequestPayload{"
        + "orderPrice="
        + orderPrice
        + "triggerPrice="
        + triggerPrice
        + ", trailValue="
        + trailValue
        + ", size="
        + size
        + '}';
  }
}


text:
require 'eventmachine'
require_relative './promise'

include Farcall

# As the eventmachine callback paradigm is completely different from the threaded paradigm
# of the Farcall, that runs pretty well under JRuby and in multithreaded MRI, we provide
# compatible but different implementations: {EmFarcall::Endpoint}, {EmFarcall::Interface}
# and {EmFarcall::Provider}. Changes to adapt these are minimal except of the callback
# paradigm. The rest is the same.
#
# The eventmachine is not a required dependency, to use EmFarcall place eventmachine _before_
# _requiring_ _farcall:_
#
#     require 'eventmachine'
#     require 'farcall'
module EmFarcall

  # Endpoint that run in the reactor thread of the EM. Eventmachine should run by the time of
  # creation of the endpoint. All the methods can be called from any thread, not only
  # EM's reactor thread.
  #
  # As the eventmachine callback paradigm is completely different from the threaded paradigm
  # of the Farcall, that runs pretty well under
  # JRuby and in multithreaded MRI, we provide
  # compatible but different endpoint to run under EM.
  #
  # Its main difference is that there is no sync_call, instead, calling remote commands
  # from the endpoint and/ot interface can provide blocks that are called when the remote
  # is executed.
  #
  # The EM version of the endpoint works with any 2 EM:C:Channels.
  #
  class Endpoint

    # Create new endpoint to work with input and output channels
    #
    # @param [EM::Channel] input_channel
    # @param [EM::Channel] output_channel
    def initialize(input_channel, output_channel, errback=nil, provider: nil)
      EM.schedule {
        @input, @output, @errback = input_channel, output_channel, errback
        @trace                    = false
        @in_serial                = @out_serial = 0
        @callbacks                = {}
        @handlers                 = {}
        @unnamed_handler          = -> (name, *args, **kwargs) {
          raise NoMethodError, "method does not exist: #{name}"
        }
        @input.subscribe { |data|
          process_input(data)
        }
        if provider
          @provider         = provider
          provider.endpoint = self
        end
      }
    end

    # Set or get provider instance. When provider is set, its public methods are called by the remote
    # and any possible exception are passed back to caller party. You can use any ruby class instance
    # everything will work, operators, indexes[] and like.
    attr_accessor :provider

    # Call the remote method with specified name and arguments calling block when done. Returns
    # immediately a {Farcall::Promise} instance which could be used to control remote procedure
    # invocation result asynchronously and effective.
    #
    # Also, if block is provided, it will be called when the remote will be called and possibly
    # return some data. It receives single object paramter with two fields: result.error and
    # result.result. It is also possible to use returned {Farcall::Promise} instance to set
    # multiple callbacks with ease. Promise callbacks are called _after_ the block.
    #
    # `result.error` is not nil when the remote raised error, then `error[:class]` and
    # `error.text` are set accordingly.
    #
    # if error is nil then result.result receives any return data from the remote method.
    #
    # for example:
    #
    #   endpoint.call( 'some_func', 10, 20) { |done|
    #      if done.error
    #        puts "Remote error class: #{done.error[:class]}: #{done.error.text}"
    #      else
    #        puts "Remote returned #{done.result}"
    #   }
    #
    # @param name [String] remote method name
    # @return [Promise] object that call be used to set multiple handlers on success
    #           or fail event. {Farcall::Promise#success} receives remote return result on
    #           success and {Farcall::Promise#fail} receives error object.
    def call(name, *args, **kwargs, &block)
      promise = Farcall::Promise.new
      EM.schedule {
        @callbacks[@in_serial] = -> (result) {
          block.call(result) if block != nil
          if result.error
            promise.set_fail result.error
          else
            promise.set_success result.result
          end
        }
        send_block cmd: name, args: args, kwargs: kwargs
      }
      promise
    end

    # Close the endpoint
    def close
      super
    end

    # Report error via errback and the endpoint
    def error text
      STDERR.puts "farcall ws server error #{text}"
      EM.schedule {
        @errback.call(text) if @errback
        close
      }
    end

    # Set handler to perform the named command. Block will be called when the remote party calls
    # with parameters passed from the remote. The block returned value will be passed back to
    # the caller.
    #
    # If the block raises the exception it will be reported to the caller as an error (depending
    # on it's platofrm, will raise exception on its end or report error)
    def on(name, &block)
      @handlers[name.to_s] = block
    end

    # Process remote command. First parameter passed to the block is the method name, the rest
    # are optional arguments of the call:
    #
    #    endpoint.on_command { |name, *args, **kwargs|
    #      if name == 'echo'
    #        { args: args, keyword_args: kwargs }
    #      else
    #        raise "unknown command"
    #      end
    #    }
    #
    # raising exceptions from the block cause farcall error to be returned back th the caller.
    def on_command &block
      raise "unnamed handler should be present" unless block
      @unnamed_handler = block
    end

    # Same as #on_command (compatibilty method)
    def on_remote_call &block
      on_command &block
    end

    # Get the Farcall::RemoteInterface connnected to this endpoint. Any subsequent calls with
    # return the same instance.
    def remote
      @remote ||= EmFarcall::Interface.new endpoint: self
    end

    private

    # :nodoc: sends block with correct framing
    def send_block **data
      data[:serial] = @out_serial
      @out_serial   += 1
      @output << data
    end

    # :nodoc:
    def execute_command cmd, ref, args, kwargs
      kwargs = (kwargs || {}).inject({}) {
          |all, kv|
        all[kv[0].to_sym] = kv[1]
        all
      }
      args << kwargs if kwargs && !kwargs.empty?
      result = if proc = @handlers[cmd.to_s]
                 proc.call(*args)
               elsif @provider
                 provider.send :remote_call, cmd.to_sym, args
               else
                 @unnamed_handler.call(cmd, args)
               end
      send_block ref: ref, result: result

    rescue Exception => e
      if @trace
        puts $!
        puts $!.backtrace.join("\n")
      end
      error_data = { 'class' => e.class.name, 'text' => e.to_s }
      e.respond_to?(:data) and error_data[:data] = e.data
      send_block ref: ref, error: error_data
    end

    # :nodoc: important that this method is called from reactor thread only
    def process_input data
      # To be free from :keys and 'keys'
      data = SmartHash.new(data) unless data.is_a?(SmartHash)
      if data.serial != @in_serial
        error "framing error (wrong serial:)"
      else
        @in_serial += 1
        if (cmd = data.cmd) != nil
          execute_command(cmd, data.serial, data.args || [], data.kwargs || {})
        else
          ref = data.ref
          if ref
            if (block = @callbacks.delete(ref)) != nil
              block.call(SmartHash.new(result: data.result, error: data.error))
            end
          else
            error "framing error: no ref in block #{data.inspect}"
          end
        end
      end
    end
  end

  # Interface to the remote provider via Farcall protocols. Works the same as if the object
  # is local and yields block in return, unlike Farcall::Interface that blocks
  #
  # RemoteInterface transparently creates methods as you call them to speedup subsequent
  # calls.
  #
  class Interface

    # Create interface to the endpoint.
    #
    # @param endpoint [Farcall::Endpoint] to connect to.
    def initialize(endpoint)
      @endpoint = endpoint
    end

    def method_missing(method_name, *arguments, **kw_arguments, &block)
      instance_eval <<-End
        def #{method_name} *arguments, **kw_arguments, &block
          @endpoint.call '#{method_name}', *arguments, **kw_arguments, &block
        end
      End
      @endpoint.call method_name, *arguments, **kw_arguments, &block
    end

    def respond_to_missing?(method_name, include_private = false)
      true
    end
  end

  class Provider < Farcall::Provider

    attr_accessor :endpoint

    def far_interface
      endpoint.remote
    end

  end
end


text:
using NUnit.Framework;
using WebAPI.Common.Executors;
using WebAPI.Common.Models.Raven.Keys;
using WebAPI.Dashboard.Areas.secure.Models.ViewModels;
using WebAPI.Dashboard.Commands.Key;

namespace WebAPI.Dashboard.Tests.Commands
{
    public class ValidateAndGetKeyTypeCommandTests
    {
        [Test]
        public void Empty_Parameters_Returns_None_with_Message()
        {
            var data = new ApiKeyData
                {
                    Ip = "",
                    UrlPattern = "",
                    AppStatus = ApiKey.ApplicationStatus.Production
                };

            var command = new ValidateAndGetKeyTypeCommand(data);
            var type = CommandExecutor.ExecuteCommand(command);

            Assert.That(type, Is.EqualTo(ApiKey.ApplicationType.None));
            Assert.That(command.ErrorMessage, Is.Not.Null);
        }

        [TestFixture]
        public class Browser
        {
            [TestFixture]
            public class Production
            {
                [TestCase("localhost/*")]
                [TestCase("localhost:1237")]
                [TestCase("localhost")]
                [TestCase("127.0.0.1")]
                [TestCase("127.0.0.1/app")]
                [TestCase("127.0.0.1/*")]
                [TestCase("machine-name")]
                [TestCase("agrc-sg1/*")]
                public void Bad_Url(string url)
                {
                    var data = new ApiKeyData
                        {
                            Ip = "",
                            UrlPattern = url,
                            AppStatus = ApiKey.ApplicationStatus.Production
                        };

                    var command = new ValidateAndGetKeyTypeCommand(data);
                    var type = CommandExecutor.ExecuteCommand(command);

                    Assert.That(type, Is.EqualTo(ApiKey.ApplicationType.None));
                    Assert.That(command.ErrorMessage, Is.Not.Null);
                }

                [TestCase("*.example.com/*")]
                [TestCase("http://atlas.utah.gov")]
                [TestCase("*.atlas.utah.gov/*")]
                [TestCase("*.mapserv.utah.gov/applicationname/*")]
                [TestCase("*.url.com/folder/appname/*")]
                [TestCase("*.nedds.health.utah.gov*")]
                [TestCase("api.utlegislators.com")]
                [TestCase("*168.177.222.22/app/*")]
                public void Good_Url(string url)
                {
                    var data = new ApiKeyData
                        {
                            Ip = "",
                            UrlPattern = url,
                            AppStatus = ApiKey.ApplicationStatus.Production
                        };

                    var command = new ValidateAndGetKeyTypeCommand(data);
                    var type = CommandExecutor.ExecuteCommand(command);

                    Assert.That(type, Is.EqualTo(ApiKey.ApplicationType.Browser));
                    Assert.That(command.ErrorMessage, Is.Null);
                }
            }

            [TestFixture]
            public class Development
            {
                [TestCase("localhost/*")]
                [TestCase("localhost")]
                [TestCase("127.0.0.1")]
                [TestCase("127.0.0.1/app")]
                [TestCase("127.0.0.1/*")]
                [TestCase("machine-name")]
                [TestCase("agrc-sg1/*")]
                [TestCase("*.example.com/*")]
                [TestCase("http://atlas.utah.gov")]
                [TestCase("*.atlas.utah.gov/*")]
                [TestCase("*.mapserv.utah.gov/applicationname/*")]
                [TestCase("*.url.com/folder/appname/*")]
                [TestCase("*.nedds.health.utah.gov*")]
                [TestCase("api.utlegislators.com")]
                [TestCase("*168.177.222.22/app/*")]
                public void Good_Url(string url)
                {
                    var data = new ApiKeyData
                    {
                        Ip = "",
                        UrlPattern = url,
                        AppStatus = ApiKey.ApplicationStatus.Development
                    };

                    var command = new ValidateAndGetKeyTypeCommand(data);
                    var type = CommandExecutor.ExecuteCommand(command);

                    Assert.That(type, Is.EqualTo(ApiKey.ApplicationType.Browser));
                    Assert.That(command.ErrorMessage, Is.Null);
                }
            }
        }
    }
}


text:
<!DOCTYPE html>

	<title>onInputChange</title>
	<meta charset="utf-8" />

	#textInput
	<input id="textInput" type="text">