text:
Dados do veículo

    <spacer></spacer>

    <form role="form" form-submit="regCtrl.submit()" novalidate name="carForm" autocomplete="off"
          class="top-left-tooltip">

                <input type="text" class="form-control input-lg card-shadow"
                       maxlength="11"
                       auto-tab-to="chassi"
                       ng-readonly="SystemService.readOnly"
                       number
                       reverse-mask="true" auto-focus="registerPage"
                       name="renavam"
                       ng-model="regCtrl.car.renavam"
                       required ng-blur="regCtrl.findCarByRenavam($event)"
                       tooltip="Renavam *"
                       tooltip-trigger="focus"
                       placeholder="Renavam *">

                <input id="chassi" type="text" class="form-control input-lg card-shadow uppercase"
                       mask="AAAAAAAAAAAAAAAAA"
                       name="chassi"
                       ng-readonly="SystemService.readOnly"
                       ng-model="regCtrl.car.chassi"
                       required
                       auto-tab-to="plate"
                       minlength="12"
                       maxlength="17"
                       tooltip="Chassi *" tooltip-trigger="focus"
                       placeholder="Chassi *">

                <input id="plate" type="text" class="form-control input-lg card-shadow uppercase"
                       mask="SSS-0000"
                       ng-readonly="SystemService.readOnly"
                       name="plate"
                       maxlength="8"
                       auto-tab-to="fuelType"
                       valid-plate
                       ng-model="regCtrl.car.licensePlate"
                       required
                       tooltip="Placa *" tooltip-trigger="focus"
                       placeholder="Placa *">

                <select id="fuelType" class="form-control input-lg card-shadow" name="fuelType"
                        ng-options="fuel as fuel.name for fuel in regCtrl.fuelTypes"
                        tooltip="Combustível *" tooltip-trigger="focus" title=""
                        ng-disabled="SystemService.readOnly"
                        ng-model="regCtrl.fuelType" required>
                </select>

                <input type="text" class="form-control input-lg card-shadow"
                       name="manufacturer" required
                       ng-readonly="SystemService.readOnly"
                       ng-model="regCtrl.manufacturer"
                       placeholder="Marca *"
                       tooltip="Marca *" tooltip-trigger="focus"
                       ng-blur="regCtrl.getModels($event)"
                       typeahead="man as man.name for man in regCtrl.manufacturers | orderBy: 'name' | filter:{name:$viewValue}">

                <input type="text" class="form-control input-lg card-shadow"
                       name="model" required
                       ng-disabled="!regCtrl.manufacturer"
                       ng-readonly="SystemService.readOnly"
                       ng-model="regCtrl.model"
                       ng-blur="regCtrl.validateModel($event)"
                       tooltip="Modelo *" tooltip-trigger="focus"
                       placeholder="Modelo *"
                       typeahead="mod as mod.name for mod in regCtrl.models | orderBy: 'name' | filter:{name:$viewValue}">

                <input type="text" class="form-control input-lg card-shadow uppercase"
                       required
                       tooltip="Cor *" tooltip-trigger="focus"
                       name="color"
                       alpha
                       minlength="3"
                       ng-readonly="SystemService.readOnly"
                       ng-model="regCtrl.car.color"
                       placeholder="Cor *">

                <input name="modelYear" class="form-control input-lg card-shadow col-xs-6"
                       type="text"
                       minlength="4"
                       maxlength="4"
                       number
                       auto-tab-to="year-manufacture"
                       required
                       tooltip="Ano modelo *" tooltip-trigger="focus"
                       placeholder="Ano modelo *"
                       ng-readonly="SystemService.readOnly"
                       ng-blur="regCtrl.car.yearOfManufacture = regCtrl.car.yearOfModel"
                       ng-model="regCtrl.car.yearOfModel">

                <button id="year-manufacture" role="radio" class="btn btn-checkbox btn-lg col-xs-12 ellipsis card-shadow"
                        tooltip="Mesmo ano de fabricação" tooltip-trigger="focus"
                        ng-class="{active: regCtrl.sameYearManufacturer}"
                        ng-disabled="SystemService.readOnly"
                        ng-click="regCtrl.toggleYear()">
                    Mesmo ano de fabricação
                </button>

                    <input type="text" class="form-control input-lg " placeholder="Quilometragem *"
                           name="kilometers" mask="#.##0" reverse-mask="true"
                           tooltip="Quilometragem *" tooltip-trigger="focus"
                           required
                           maxlength="9"
                           ng-readonly="SystemService.readOnly"
                           number
                           ng-model="regCtrl.car.kilometers">
                    km

                    R$
                    <input class="form-control input-lg " placeholder="Preço *"
                           name="price" mask="#.##0" reverse-mask="true"
                           tooltip="Preço *" tooltip-trigger="focus"
                           required number
                           maxlength="9"
                           ng-readonly="SystemService.readOnly"
                           ng-model="regCtrl.car.price">
                    ,00

        <spacer></spacer>

                <button type="button" role="button" class="btn btn-default btn-lg col-xs-12 card-shadow"
                        tabindex="-1"
                        ng-click="SystemService.page = 0;">
                    Cancelar
                </button>

                <button type="{{SystemService.readOnly ? 'button' : 'submit'}}" ng-click="SystemService.readOnly ? regCtrl.submit() : null"
                        role="button" class="btn btn-primary btn-lg col-xs-12 card-shadow">
                    Próximo
                </button>

    </form>

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O renavam não foi informado

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O renavam é composto por no mínimo 9 dígitos

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O chassi não foi informado

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O chassi é composto por 17 dígitos

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

A placa não foi informada

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

A placa é composta por 3 letras e 4 números

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

A precedencia não foi informada

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

A precedencia precisa de pelo menos 3 caracteres

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

A marca não foi informada

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O modelo não foi informado

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

A cor não foi informada

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O cor precisa de pelo menos 3 caracteres

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O cor deve ter no máximo 15 caracteres

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O ano do modelo não foi informado

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O ano é composto por 4 caracteres

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O preço não foi informado

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

O preço precisa ter pelo menos 4 digitos

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

A quilometragem não foi informada

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

A quilometragem precisa ter pelo menos 3 digitos


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.ObjectModel;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Microsoft.Azure.WebJobs.Script.Scale
{
    public class HostPerformanceManager
    {
        private readonly IEnvironment _environment;
        private readonly IOptions<HostHealthMonitorOptions> _healthMonitorOptions;

        public HostPerformanceManager(IEnvironment environment, IOptions<HostHealthMonitorOptions> healthMonitorOptions)
        {
            if (environment == null)
            {
                throw new ArgumentNullException(nameof(environment));
            }
            if (healthMonitorOptions == null)
            {
                throw new ArgumentNullException(nameof(healthMonitorOptions));
            }

            _environment = environment;
            _healthMonitorOptions = healthMonitorOptions;
        }

        public virtual bool IsUnderHighLoad(Collection<string> exceededCounters = null, ILogger logger = null)
        {
            var counters = GetPerformanceCounters(logger);
            if (counters != null)
            {
                return IsUnderHighLoad(counters, exceededCounters, _healthMonitorOptions.Value.CounterThreshold);
            }

            return false;
        }

        internal static bool IsUnderHighLoad(ApplicationPerformanceCounters counters, Collection<string> exceededCounters = null, float threshold = HostHealthMonitorOptions.DefaultCounterThreshold)
        {
            bool exceeded = false;

            // determine all counters whose limits have been exceeded
            exceeded |= ThresholdExceeded("ActiveConnections", counters.ActiveConnections, counters.ActiveConnectionLimit, threshold, exceededCounters);
            exceeded |= ThresholdExceeded("Connections", counters.Connections, counters.ConnectionLimit, threshold, exceededCounters);
            exceeded |= ThresholdExceeded("Threads", counters.Threads, counters.ThreadLimit, threshold, exceededCounters);
            exceeded |= ThresholdExceeded("Processes", counters.Processes, counters.ProcessLimit, threshold, exceededCounters);
            exceeded |= ThresholdExceeded("NamedPipes", counters.NamedPipes, counters.NamedPipeLimit, threshold, exceededCounters);
            exceeded |= ThresholdExceeded("Sections", counters.Sections, counters.SectionLimit, threshold, exceededCounters);
            exceeded |= ThresholdExceeded("RemoteDirMonitors", counters.RemoteDirMonitors, counters.RemoteDirMonitorLimit, threshold, exceededCounters);

            return exceeded;
        }

        internal static bool ThresholdExceeded(string name, long currentValue, long limit, float threshold, Collection<string> exceededCounters = null)
        {
            if (limit <= 0)
            {
                // no limit to apply
                return false;
            }

            float currentUsage = (float)currentValue / limit;
            bool exceeded = currentUsage > threshold;
            if (exceeded && exceededCounters != null)
            {
                exceededCounters.Add(name);
            }
            return exceeded;
        }

        internal ApplicationPerformanceCounters GetPerformanceCounters(ILogger logger = null)
        {
            string json = _environment.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteAppCountersName);
            if (!string.IsNullOrEmpty(json))
            {
                try
                {
                    // TEMP: need to parse this specially to work around bug where
                    // sometimes an extra garbage character occurs after the terminal
                    // brace
                    int idx = json.LastIndexOf('}');
                    if (idx > 0)
                    {
                        json = json.Substring(0, idx + 1);
                    }

                    return JsonConvert.DeserializeObject<ApplicationPerformanceCounters>(json);
                }
                catch (JsonReaderException ex)
                {
                    logger.LogError($"Failed to deserialize application performance counters. JSON Content: \"{json}\"", ex);
                }
            }

            return null;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import org.tensorflow.Graph
import org.tensorflow.Session
import org.tensorflow.Tensor
import org.tensorflow.TensorFlow

object HelloTensorFlow {
  def main(args: Array[String]): Unit = {
    val g = new Graph()
    val value = "Hello from " + TensorFlow.version()

    // Construct the computation graph with a single operation, a constant
    // named "MyConst" with a value "value".
    val t = Tensor.create(value.getBytes("UTF-8"))

    // The Java API doesn't yet include convenience functions for adding operations.
    g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build()

    // Execute the "MyConst" operation in a Session.
    val s = new Session(g)
    val output = s.runner().fetch("MyConst").run().get(0)
    System.out.println(new String(output.bytesValue(), "UTF-8"))
  }
}


text:
registerManualTests('chrome.embed', function(rootEl, addButton) {
  var wURL = window.URL || window.webkitURL;

  addButton('Get image via XHR (traditional events)', function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://www.apache.org/images/feather-small.gif', true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
      var $document = rootEl.ownerDocument;
      var img = $document.createElement('img');
      img.src = wURL.createObjectURL(this.response);
      rootEl.appendChild(img);
    };
    xhr.send();
  });

  addButton('Get image via XHR (DOM2 Events)', function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://www.apache.org/images/feather-small.gif', true);
    xhr.responseType = 'blob';
    xhr.addEventListener('load', function(e) {
      var $document = rootEl.ownerDocument;
      var img = $document.createElement('img');
      img.src = wURL.createObjectURL(this.response);
      rootEl.appendChild(img);
    });
    xhr.send();
  });

  addButton('Get image via RAL', function() {
    var wnd = chrome.app.window.current();
    var RAL = window.RAL || wnd.RAL;
    var remoteImage = new RAL.RemoteImage({src:'http://www.apache.org/images/feather-small.gif'});

    rootEl.appendChild(remoteImage.element);
    RAL.Queue.add(remoteImage);
    RAL.Queue.setMaxConnections(4);
    RAL.Queue.start();
  });
});


text:
'use strict';

var raf = require('raf');

module.exports = rafListen;

function rafListen(observ, fn) {
    var sending = false;
    var currValue;

    return observ(onvalue);

    function onvalue(value) {
        currValue = value;
        if (sending) {
            return;
        }

        sending = true;
        raf(send);
    }

    function send() {
        var oldValue = currValue;
        fn(currValue);
        sending = false;

        if (oldValue !== currValue) {
            sending = true;
            raf(send);
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class Shaker : MonoBehaviour {

    public Vector3 PositionScale = new Vector3(1, 1, 0);
    public Vector3 RotationScale = new Vector3(0, 0, 0);
    [Range(1, 50)]
    public int shakeSpeed = 1;

    Vector3 origin;
    Quaternion originRotation;
    Coroutine co = null;

    /// <summary>
    /// Shake at POWER for DURATION seconds. Multiple calls will yield most recent only.
    /// </summary>
    /// <param name="duration">Duration of shaking</param>
    /// <param name="power">Optional. How violent to shake (0-50). Defaults to previous used Power.</param>
    public void Shake(float duration, int power=0) {
        if (co != null)
        {
            StopCoroutine(co);
            RevertOrigin();
        }
        shakeSpeed = power > 0 ? power : shakeSpeed;
        co = StartCoroutine(DoShake(duration));
    }

    /// <summary>
    /// Set current position and rotation as 'origin'
    /// </summary>
    void SetOrigin() {
        origin = transform.localPosition;
        originRotation = transform.localRotation;
    }

    /// <summary>
    /// Revert the transform to the original position and rotation
    /// </summary>
    void RevertOrigin() {
        transform.localPosition = origin;
        transform.localRotation = originRotation;
        co = null;
    }

    IEnumerator DoShake(float duration) {
        SetOrigin();
        float speed = shakeSpeed / 200f;
        // Start on a 0.5f value (center) for smooth transition into shaking.
        Vector2 noise = new Vector2(Random.value * 10, Random.value * 100);
        float factor = Mathf.PerlinNoise(noise.x, noise.y);
        while (factor > 0.525f || factor < 0.475f)
        {
            noise.x += 0.05f;
            factor = Mathf.PerlinNoise(noise.x, noise.y);
        }
        // Shake for DURATION
        Vector3 offset = origin;
        Vector3 q = originRotation.eulerAngles;
        float step = 0;
        float elapsed = 0;
        while (elapsed < duration)
        {
            // Generate unique perlin noise, only if needed
            if (PositionScale.x != 0)
                offset.x = (Mathf.PerlinNoise(noise.x + step, noise.y) * 2f - 1f) * PositionScale.x;
            if (PositionScale.y != 0)
                offset.y = (Mathf.PerlinNoise(noise.x + step * 0.41f, noise.y + step * 0.41f) * 2f - 1f) * PositionScale.y;
            if (PositionScale.z != 0)
                offset.z = (Mathf.PerlinNoise(noise.x, noise.y + step) * 2f - 1f) * PositionScale.z;
            if (RotationScale.x != 0)
                q.x = (Mathf.PerlinNoise(noise.x - step, noise.y) * 2f - 1f) * RotationScale.x;
            if (RotationScale.y != 0)
                q.y = (Mathf.PerlinNoise(noise.x - step * 0.41f, noise.y - step * 0.41f) * 2f - 1f) * RotationScale.y;
            if (RotationScale.z != 0)
                q.z = (Mathf.PerlinNoise(noise.x, noise.y - step) * 2f - 1f) * RotationScale.z;
            // Update transform
            transform.rotation = Quaternion.Euler(originRotation.eulerAngles + q);
            transform.localPosition = origin + offset;
            step += speed;
            elapsed += Time.deltaTime;
            yield return null;
        }
        // Smoothly return to start (this bleeds over the given 'duration')
        float dt = 0;
        Vector3 at = transform.localPosition;
        Quaternion rot = transform.localRotation;
        while (dt < 1)
        {
            transform.localPosition = Vector3.Lerp(at, origin, dt);
            transform.localRotation = Quaternion.Lerp(rot, originRotation, dt);
            dt += shakeSpeed / 50f;
            yield return null;
        }
        RevertOrigin();
    }

}


text:
The application object must accept two positional arguments.  For
the sake of illustration, we have named them <tt class="docutils literal">environ</tt> and
<tt class="docutils literal">start_response</tt>, but they are not required to have these names.
A server or gateway **must** invoke the application object using
positional (not keyword) arguments.  (E.g. by calling
<tt class="docutils literal">result = application(environ, start_response)</tt> as shown above.)

The <tt class="docutils literal">environ</tt> parameter is a dictionary object, containing CGI-style
environment variables.  This object **must** be a builtin Python
dictionary (_not_ a subclass, <tt class="docutils literal">UserDict</tt> or other dictionary
emulation), and the application is allowed to modify the dictionary
in any way it desires.  The dictionary must also include certain
WSGI-required variables (described in a later section), and may
also include server-specific extension variables, named according
to a convention that will be described below.

The <tt class="docutils literal">start_response</tt> parameter is a callable accepting two
required positional arguments, and one optional argument.  For the sake
of illustration, we have named these arguments <tt class="docutils literal">status</tt>,
<tt class="docutils literal">response_headers</tt>, and <tt class="docutils literal">exc_info</tt>, but they are not required to
have these names, and the application **must** invoke the
<tt class="docutils literal">start_response</tt> callable using positional arguments (e.g.
<tt class="docutils literal">start_response(status, response_headers)</tt>).

The <tt class="docutils literal">status</tt> parameter is a status string of the form
<tt class="docutils literal">"999 Message here"</tt>, and <tt class="docutils literal">response_headers</tt> is a list of
<tt class="docutils literal">(header_name, header_value)</tt> tuples describing the HTTP response
header.  The optional <tt class="docutils literal">exc_info</tt> parameter is described below in the
sections on [The start_response() Callable](#the-start-response-callable) and [Error Handling](#error-handling).
It is used only when the application has trapped an error and is
attempting to display an error message to the browser.

The <tt class="docutils literal">start_response</tt> callable must return a <tt class="docutils literal">write(body_data)</tt>
callable that takes one positional parameter: a bytestring to be written
as part of the HTTP response body.  (Note: the <tt class="docutils literal">write()</tt> callable is
provided only to support certain existing frameworks' imperative output
APIs; it should not be used by new applications or frameworks if it
can be avoided.  See the [Buffering and Streaming](#buffering-and-streaming) section for more
details.)

When called by the server, the application object must return an
iterable yielding zero or more bytestrings.  This can be accomplished in a
variety of ways, such as by returning a list of bytestrings, or by the
application being a generator function that yields bytestrings, or
by the application being a class whose instances are iterable.
Regardless of how it is accomplished, the application object must
always return an iterable yielding zero or more bytestrings.

The server or gateway must transmit the yielded bytestrings to the client
in an unbuffered fashion, completing the transmission of each bytestring
before requesting another one.  (In other words, applications
**should** perform their own buffering.  See the [Buffering and
Streaming](#buffering-and-streaming) section below for more on how application output must be
handled.)

The server or gateway should treat the yielded bytestrings as binary byte
sequences: in particular, it should ensure that line endings are
not altered.  The application is responsible for ensuring that the
bytestring(s) to be written are in a format suitable for the client.  (The
server or gateway **may** apply HTTP transfer encodings, or perform
other transformations for the purpose of implementing HTTP features
such as byte-range transmission.  See [Other HTTP Features](#other-http-features), below,
for more details.)

If a call to <tt class="docutils literal">len(iterable)</tt> succeeds, the server must be able
to rely on the result being accurate.  That is, if the iterable
returned by the application provides a working <tt class="docutils literal">__len__()</tt>
method, it **must** return an accurate result.  (See
the [Handling the Content-Length Header](#handling-the-content-length-header) section for information
on how this would normally be used.)

If the iterable returned by the application has a <tt class="docutils literal">close()</tt> method,
the server or gateway **must** call that method upon completion of the
current request, whether the request was completed normally, or
terminated early due to an application error during iteration or an early
disconnect of the browser.  (The <tt class="docutils literal">close()</tt> method requirement is to
support resource release by the application.  This protocol is intended
to complement [PEP 342](/dev/peps/pep-0342)'s generator support, and other common iterables
with <tt class="docutils literal">close()</tt> methods.)

Applications returning a generator or other custom iterator **should not**
assume the entire iterator will be consumed, as it **may** be closed early
by the server.

(Note: the application **must** invoke the <tt class="docutils literal">start_response()</tt>
callable before the iterable yields its first body bytestring, so that the
server can send the headers before any body content.  However, this
invocation **may** be performed by the iterable's first iteration, so
servers **must not** assume that <tt class="docutils literal">start_response()</tt> has been called
before they begin iterating over the iterable.)

Finally, servers and gateways **must not** directly use any other
attributes of the iterable returned by the application, unless it is an
instance of a type specific to that server or gateway, such as a "file
wrapper" returned by <tt class="docutils literal">wsgi.file_wrapper</tt> (see [Optional
Platform-Specific File Handling](#optional-platform-specific-file-handling)).  In the general case, only
attributes specified here, or accessed via e.g. the [PEP 234](/dev/peps/pep-0234) iteration
APIs are acceptable.


text:
// Experimental ESRI ASCII grid parser by Samuel Luescher <sam@luescher.org>
// based on
// Module CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed)

var EventEmitter = require('events').EventEmitter,
    fs = require('fs');

// Utils function
var merge = function(obj1, obj2){
    var r = obj1||{};
    for(var key in obj2){
        r[key] = obj2[key];
    }
    return r;
}

module.exports = function(){
    var state = {
        count: 0,
        isHeader: true,
        colIndex: 0,
        rowIndex: 0,
        headerValues: {},
        countWriten: 0,
        field: '',
        line: [],
        lastC: '',
        quoted: false,
        commented: false,
        buffer: null,
        bufferPosition: 0
    }
    // Are we currently inside the transform callback? If so,
    // we shouldn't increment `state.count` which count provided lines
    var transforming = false;

    // Defined Class

    var CSV = function(){
        // Set options
        this.readOptions = {
            header: ["ncols", "nrows", "xllcorner", "yllcorner", "cellsize", "NODATA_value"],
            readHeader: true,
            delimiter: ' ',
            quote: '"',
            escape: '"',
            columns: null,
            flags: 'r',
            encoding: 'utf8',
            bufferSize: 8 * 1024 * 1024,
            trim: false,
            ltrim: false,
            rtrim: false,
            forceLineBreakAfter: 100,
        };
        this.writeOptions = {
            delimiter: null,
            quote: null,
            escape: null,
            columns: null,
            header: false,
            lineBreaks: null,
            flags: 'w',
            encoding: 'utf8',
            bufferSize: null,
            end: true // Call `end()` on close
        };
        // A boolean that is true by default, but turns false after an 'error' occurred,
        // the stream came to an 'end', or destroy() was called.
        this.readable = true;
        // A boolean that is true by default, but turns false after an 'error' occurred
        // or end() / destroy() was called.
        this.writable = true;
    }
    CSV.prototype.__proto__ = EventEmitter.prototype;

    // Reading API

    CSV.prototype.from = function(data,options){
        if(options) merge(this.readOptions,options);
        var self = this;
        process.nextTick(function(){
            if(data instanceof Array){
                if( csv.writeOptions.lineBreaks === null ){
                    csv.writeOptions.lineBreaks = "\r\n";
                }
                for(var i=0; i<data.length; i++){
                    state.line = data[i];
                    flush();
                }
            }else{
                try{
                    parse(data);
                }catch(e){
                    self.emit('error', e);
                    return;
                }
            }
            self.end();
        });
        return this;
    }
    CSV.prototype.fromStream = function(readStream, options){
        if(options) merge(this.readOptions,options);
        var self = this;
        readStream.on('data', function(data) {
            try{
                parse(data);
            }catch(e){
                self.emit('error', e);
                // Destroy the input stream
                this.destroy();
            }
        });
        readStream.on('error', function(error) { self.emit('error', error) });
        readStream.on('end', function() {
            self.end();
        });
        this.readStream = readStream;
        return this;
    }
    CSV.prototype.fromPath = function(path, options){
        if(options) merge(this.readOptions,options);
        var stream = fs.createReadStream(path, this.readOptions);
        stream.setEncoding(this.readOptions.encoding);
        return this.fromStream(stream, null);
    }

    // Writting API

    /**
     * Write data.
     * Data may be string in which case it could span multiple lines. If data
     * is an object or an array, it must represent a single line.
     * Preserve is for line which are not considered as CSV data.
     */
    CSV.prototype.write = function(data, preserve){
        if(typeof data === 'string' && !preserve){
            return parse(data);
        }
        write(data, preserve);
        if(!transforming && !preserve){
            state.count++;
        }
    }

    CSV.prototype.end = function(){
        if (state.quoted) {
            csv.emit('error', new Error('Quoted field not terminated'));
        } else {
            // dump open record
            if (state.field) {
                if(csv.readOptions.trim || csv.readOptions.rtrim){
                    state.field = state.field.trimRight();
                }
                state.line.push(state.field);
                state.field = '';
            }
            if (state.line.length > 0) {
                flush();
            }
            if(csv.writeStream){
                if(state.bufferPosition !== 0){
                    csv.writeStream.write(state.buffer.slice(0, state.bufferPosition));
                }
                if(this.writeOptions.end){
                    csv.writeStream.end();
                }else{
                    csv.emit('end', state.count);
                    csv.readable = false;
                }
            }else{
                csv.emit('end', state.count);
                csv.readable = false;
            }
        }
    }

    CSV.prototype.toStream = function(writeStream, options){
        if(options) merge(this.writeOptions,options);
        var self = this;
        switch(this.writeOptions.lineBreaks){
            case 'auto':
                this.writeOptions.lineBreaks = null;
                break;
            case 'unix':
                this.writeOptions.lineBreaks = "\n";
                break;
            case 'mac':
                this.writeOptions.lineBreaks = "\r";
                break;
            case 'windows':
                this.writeOptions.lineBreaks = "\r\n";
                break;
            case 'unicode':
                this.writeOptions.lineBreaks = "\u2028";
                break;
        }
        writeStream.on('close', function(){
            self.emit('end', state.count);
            self.readable = false;
            self.writable = false;
        })
        this.writeStream = writeStream;
        state.buffer = new Buffer(this.writeOptions.bufferSize||this.readOptions.bufferSize);
        state.bufferPosition = 0;
        return this;
    }

    CSV.prototype.toPath = function(path, options){
        // Merge user provided options
        if(options) merge(this.writeOptions,options);
        // clone options
        var options = merge({},this.writeOptions);
        // Delete end property which otherwise overwrite `WriteStream.end()`
        delete options.end;
        // Create the write stream
        var stream = fs.createWriteStream(path, options);
        return this.toStream(stream, null);
    }

    // Transform API

    CSV.prototype.transform = function(callback){
        this.transformer = callback;
        return this;
    }

    var csv = new CSV();

    // Private API

    /**
     * Parse a string which may hold multiple lines.
     * Private state object is enriched on each character until
     * flush is called on a new line
     */
    function parse(chars){
        chars = '' + chars;
        for (var i = 0, l = chars.length; i < l; i++) {
            var c = chars.charAt(i);
            switch (c) {
                case csv.readOptions.escape:
                case csv.readOptions.quote:
                    if( state.commented ) break;
                    var isEscape = false;
                    if (c === csv.readOptions.escape) {
                        // Make sure the escape is really here for escaping:
                        // if escape is same as quote, and escape is first char of a field and it's not quoted, then it is a quote
                        // next char should be an escape or a quote
                        var nextChar = chars.charAt(i + 1);
                        if( !( csv.readOptions.escape === csv.readOptions.quote && !state.field && !state.quoted )
                        &&   ( nextChar === csv.readOptions.escape || nextChar === csv.readOptions.quote ) ) {
                            i++;
                            isEscape = true;
                            c = chars.charAt(i);
                            state.field += c;
                        }
                    }
                    if (!isEscape && (c === csv.readOptions.quote)) {
                        if (state.field && !state.quoted) {
                            // Treat quote as a regular character
                            state.field += c;
                            break;
                        }
                        if (state.quoted) {
                            // Make sure a closing quote is followed by a delimiter
                            var nextChar = chars.charAt(i + 1);
                            if (nextChar && nextChar != '\r' && nextChar != '\n' && nextChar !== csv.readOptions.delimiter) {
                                throw new Error('Invalid closing quote; found "' + nextChar + '" instead of delimiter "' + csv.readOptions.delimiter + '"');
                            }
                            state.quoted = false;
                        } else if (state.field === '') {
                            state.quoted = true;
                        }
                    }
                    break;
                case csv.readOptions.delimiter:
                    if( state.commented ) break;
                    if( state.quoted ) {
                        state.field += c;
                    }else{
                        if(csv.readOptions.trim || csv.readOptions.rtrim){
                            state.field = state.field.trimRight();
                        }
                        state.line.push(state.field);
                        state.field = '';
                        // current row of cells is terminated because reaching end of
                        if (csv.readOptions.forceLineBreakAfter && state.line.length >= csv.readOptions.forceLineBreakAfter) {
                            flush();
                        }
                    }
                    break;
               case '\n':
                    if(state.quoted) {
                        state.field += c;
                        break;
                    }
                    if( !csv.readOptions.quoted && state.lastC === '\r' ){
                        break;
                    }
                case '\r':
                    if(state.quoted) {
                        state.field += c;
                        break;
                    }
                    if( csv.writeOptions.lineBreaks === null ){
                        // Auto-discovery of linebreaks
                        csv.writeOptions.lineBreaks = c + ( c === '\r' && chars.charAt(i+1) === '\n' ? '\n' : '' );
                    }
                    if(csv.readOptions.trim || csv.readOptions.rtrim){
                        state.field = state.field.trimRight();
                    }
                    // only flush if field is not empty (since row cells may have been terminated before line break)
                    if (state.field != '') {
                        state.line.push(state.field);
                        state.field = '';
                        flush();
                    }
                    break;
                case ' ':
                case '\t':
                    if(state.quoted || (!csv.readOptions.trim && !csv.readOptions.ltrim ) || state.field) {
                        state.field += c;
                        break;
                    }
                    break;
                default:
                    if(state.commented) break;
                    state.field += c;
            }
            state.lastC = c;
        }
    }

    // Called by the `parse` function on each line. It will then call `write`
    function flush(){
        for (var i = 0; i < state.line.length; i++) {
            var number = state.line[i] != '' ? Number(state.line[i]) : state.headerValues.NODATA_value;
            state.line[i] = !isNaN(number) ? number : state.line[i];
        }
        if (state.isHeader) {
            if (csv.readOptions.header.indexOf(state.line[0]) != -1) {
                state.headerValues[state.line.shift()] = state.line.pop();
                state.line = [];
                state.lastC = '';
                return;
            } else {
                csv.emit('header', {
                    'gridSize': state.headerValues['cellsize'],
                    'totalCount': state.headerValues['ncols'] * state.headerValues['nrows']
                });
                state.isHeader = false;
                return;
            }
        }

        /*if(csv.readOptions.columns){
            if(state.count === 0 && csv.readOptions.columns === true){
                csv.readOptions.columns = state.line;
                state.line = [];
                state.lastC = '';
                return;
            }
            var line = {};
            for(var i=0; i<csv.readOptions.columns.length; i++){
                var column = csv.readOptions.columns[i];
                line[column] = state.line[i]||null;
            }
            state.line = line;
            line = null;
        }*/

        if(state.count === 0 && csv.writeOptions.header === true){
            write(csv.writeOptions.columns || csv.readOptions.columns);
        }
        var line;
        if(csv.transformer){
            transforming = true;
            line = csv.transformer(state.line, state.count);
            transforming = false;
        }else{
            line = state.line;
        }
        write(line);
        state.count++;
        state.line = [];
        state.lastC = '';
    }

    /**
     * Write a line to the written stream.
     * Line may be an object, an array or a string
     * Preserve is for line which are not considered as CSV data
     */
    function write(line, preserve){
        if(typeof line === 'undefined' || line === null){
            return;
        }
        if(!preserve){
            try {
                for (var i = 0; i < line.length; i++) {
                    if (line[i] != state.headerValues.NODATA_value) {
                        //console.log(line[i]);
                        //console.log(state.count);

                        data = {
                            'coordinates': [
                                state.headerValues.xllcorner + state.headerValues.cellsize * state.colIndex + state.headerValues.cellsize / 2,
                                state.headerValues.yllcorner + state.headerValues.cellsize * (state.headerValues.nrows - 1 - state.rowIndex) + state.headerValues.cellsize / 2
                            ],
                            'val': line[i]
                        };

                        //console.log('emit', state.colIndex, state.rowIndex, data);
                        csv.emit('data', data, state.count);
                    } else {
                        //console.log('skip', state.colIndex, state.rowIndex);
                    }
                    state.colIndex++;
                    if (state.colIndex >= state.headerValues.ncols) {
                        state.colIndex = 0;
                        state.rowIndex++;
                    }
                    /*
                    if (state.colIndex >= state.headerValues.ncols) {
                        state.colIndex = 0;
                        state.rowIndex++;
                    }*/
                }
            }catch(e){
                csv.emit('error', e);
                csv.readable = false;
                csv.writable = false;
            }
        }
        if(typeof line === 'object'){
            if(!(line instanceof Array)){
                var columns = csv.writeOptions.columns || csv.readOptions.columns;
                var _line = [];
                if(columns){
                    for(var i=0; i<columns.length; i++){
                        var column = columns[i];
                        _line[i] = (typeof line[column] === 'undefined' || line[column] === null) ? '' : line[column];
                    }
                }else{
                    for(var column in line){
                        _line.push(line[column]);
                    }
                }
                line = _line;
                _line = null;
            }else if(csv.writeOptions.columns){
                // We are getting an array but the user want specified output columns. In
                // this case, we respect the columns indexes
                line.splice(csv.writeOptions.columns.length);
            }
            if(line instanceof Array){
                var newLine = state.countWriten ? csv.writeOptions.lineBreaks || "\r" : '';
                for(var i=0; i<line.length; i++){
                    var field = line[i];
                    if(typeof field === 'string'){
                        // fine 99% of the cases, keep going
                    }else if(typeof field === 'number'){
                        // Cast number to string
                        field = '' + field;
                    }else if(typeof field === 'boolean'){
                        // Cast boolean to string
                        field = field ? '1' : '';
                    }else if(field instanceof Date){
                        // Cast date to timestamp string
                        field = '' + field.getTime();
                    }
                    if(field){
                        var containsdelimiter = field.indexOf(csv.writeOptions.delimiter || csv.readOptions.delimiter) >= 0;
                        var containsQuote = field.indexOf(csv.writeOptions.quote || csv.readOptions.quote) >= 0;
                        var containsLinebreak = field.indexOf("\r") >= 0 || field.indexOf("\n") >= 0;
                        if(containsQuote){
                            field = field.replace(
                                    new RegExp(csv.writeOptions.quote || csv.readOptions.quote,'g')
                                  , (csv.writeOptions.escape || csv.readOptions.escape)
                                  + (csv.writeOptions.quote || csv.readOptions.quote));
                        }
                        if(containsQuote || containsdelimiter || containsLinebreak){
                            field = (csv.writeOptions.quote || csv.readOptions.quote) + field + (csv.writeOptions.quote || csv.readOptions.quote);
                        }
                        newLine += field;
                    }
                    if(i!==line.length-1){
                        newLine += csv.writeOptions.delimiter || csv.readOptions.delimiter;
                    }
                }
                line = newLine;
            }
        }
        if(state.buffer){
            if(state.bufferPosition + Buffer.byteLength(line,'utf8') > csv.readOptions.bufferSize){
                csv.writeStream.write(state.buffer.slice(0, state.bufferPosition));
                state.buffer = new Buffer(csv.readOptions.bufferSize);
                state.bufferPosition = 0;
            }
            state.bufferPosition += state.buffer.write(line, state.bufferPosition,'utf8');
        }
        if(!preserve){
            state.countWriten++;
        }
        return true;
    }

    return csv;
};


text:
#pragma once
#include <aws/mgn/Mgn_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace mgn
{
namespace Model
{
  enum class BootMode
  {
    NOT_SET,
    LEGACY_BIOS,
    UEFI
  };

namespace BootModeMapper
{
AWS_MGN_API BootMode GetBootModeForName(const Aws::String& name);

AWS_MGN_API Aws::String GetNameForBootMode(BootMode value);
} // namespace BootModeMapper
} // namespace Model
} // namespace mgn
} // namespace Aws


text:
module.exports = function(bh) {

    bh.match('select_mode_check', function(ctx, json) {
        ctx
            .applyBase()
            .extend(ctx.js(), { text : json.text });

        var checkedOptions = ctx.tParam('checkedOptions');

        if(checkedOptions[0]) {
            var res = checkedOptions.map(function(option) {
                return {
                    elem : 'control',
                    val : option.val
                };
            });

            ctx.content([
                res,
                ctx.content()
            ], true);
        }
    });

    bh.match('select_mode_check__button', function(ctx) {
        var checkedOptions = ctx.tParam('checkedOptions');

        ctx.content({
            elem : 'text',
            content : checkedOptions.length === 1?
                checkedOptions[0].text :
                checkedOptions.reduce(function(res, option) {
                    return res + (res? ', ' : '') + (option.checkedText || option.text);
                }, '') ||
                    ctx.tParam('select').text
        });
    });

};


text:
package model;

import static org.junit.Assert.assertEquals;

import java.util.Iterator;

import org.junit.Before;
import org.junit.Test;

import factory.GrafoStaticFactory;
import factory.GrafosFactory;

public class VerticeTest {

	private Vertice a;
	private Vertice b;
	private Aresta AB, AC;
	private Vertice c;

	@Before
	public void setup() {
		GrafosFactory factory = GrafoStaticFactory.criaFactory();
		a = factory.criaVertice("A", 0);
		c = factory.criaVertice("C", 2);
		b = factory.criaVertice("B", 1);
		AC = factory.criaAresta();
		a.addAresta(AC);
		c.addAresta(AC);
		AB = factory.criaAresta();
		a.addAresta(AB);
		b.addAresta(AB);
	}

	@Test
	public void test_adjacente() {
		Iterator<Vertice> iterator = a.getAdjacentes().iterator();
		assertEquals(b, iterator.next());
		assertEquals(c, iterator.next());
	}

	@Test
	public void test_aresta_vertice_ligado_a() {
		Vertice verticeLigado = AB.getVerticeLigadoA(b);
		assertEquals(a, verticeLigado);
	}

	@Test(expected = IllegalStateException.class)
	public void test_add_varios_vertices() {
		GrafosFactory factory = GrafoStaticFactory.criaFactory();
		Vertice verticeA = factory.criaVertice("A", 0);
		Vertice verticeB = factory.criaVertice("B", 1);
		Vertice verticeC = factory.criaVertice("C", 2);
		Aresta aresta = factory.criaAresta();
		aresta.addVertice(verticeA);
		aresta.addVertice(verticeB);
		aresta.addVertice(verticeC);
	}

}


text:
<?php

/**
 * CMB field types
 * @since  1.0.0
 */
class cmb_Meta_Box_types {

	/**
	 * @todo test taxonomy methods with non-post objects
	 * @todo test all methods with non-post objects
	 */

	/**
	 * A single instance of this class.
	 * @var cmb_Meta_Box_types object
	 */
	public static $instance = null;

	/**
	 * An iterator value for repeatable fields
	 * @var integer
	 */
	public static $iterator = 0;

	/**
	 * Holds cmb_valid_img_types
	 * @var array
	 */
	public static $valid    = array();

	/**
	 * Current field type
	 * @var string
	 */
	public static $type     = 'text';

	/**
	 * Current field
	 * @var array
	 */
	public static $field;

	/**
	 * Current field meta value
	 * @var mixed
	 */
	public static $meta;

	/**
	 * Creates or returns an instance of this class.
	 * @since  1.0.0
	 * @return cmb_Meta_Box_types A single instance of this class.
	 */
	public static function get() {
		if ( self::$instance === null )
			self::$instance = new self();

		return self::$instance;
	}

	/**
	 * Generates a field's description markup
	 * @since  1.0.0
	 * @param  string  $desc      Field's description
	 * @param  boolean $paragraph Paragraph tag or span
	 * @return strgin             Field's description markup
	 */
	private static function desc( $desc, $paragraph = false ) {
		$tag = $paragraph ? 'p' : 'span';
		return "\n<$tag class=\"cmb_metabox_description\">$desc</$tag>\n";
	}

	/**
	 * Generates repeatable text fields
	 * @since  1.0.0
	 * @param  string  $field Metabox field
	 * @param  mixed   $meta  Field's meta value
	 * @param  string  $class Field's class attribute
	 * @param  string  $type  Field Type
	 */
	private static function repeat_text_field( $field, $meta, $class = '', $type = 'text' ) {

		self::$field = $field; self::$meta = $meta; self::$type = $type;

		// check for default content
		$std = isset( $field['std'] ) ? array( $field['std'] ) : false;
		// check for saved data
		$meta = !empty( $meta ) && array_filter( $meta ) ? $meta : $std;

		self::repeat_table_open( $class );

		$class = $class ? $class .' widefat' : 'widefat';

		if ( !empty( $meta ) ) {
			foreach ( (array) $meta as $val ) {
				self::repeat_row( self::text_input( $class, $val ) );
			}
		} else {
			self::repeat_row( self::text_input( $class ) );
		}

		self::empty_row( self::text_input( $class ) );
		self::repeat_table_close();
		// reset iterator
		self::$iterator = 0;
	}

	/**
	 * Text input field used by repeatable fields
	 * @since  1.0.0
	 * @param  string  $class Field's class attribute
	 * @param  mixed   $val   Field's meta value
	 * @return string         HTML text input
	 */
	private static function text_input( $class = '', $val = '' ) {
		self::$iterator = self::$iterator ? self::$iterator + 1 : 1;
		$before = '';
		if ( self::$field['type'] == 'text_money' )
			$before = ! empty( self::$field['before'] ) ? ' ' : '$ ';
		return $before . '<input type="'. self::$type .'" class="'. $class .'" name="'. self::$field['id'] .'[]" id="'. self::$field['id'] .'_'. self::$iterator .'" value="'. $val .'" data-id="'. self::$field['id'] .'" data-count="'. self::$iterator .'"/>';
	}

	/**
	 * Generates repeatable field opening table markup for repeatable fields
	 * @since  1.0.0
	 * @param  string $class Field's class attribute
	 */
	private static function repeat_table_open( $class = '' ) {
		echo self::desc( self::$field['desc'] ), '

';
	}

	/**
	 * Generates repeatable feild closing table markup for repeatable fields
	 * @since 1.0.0
	 */
	private static function repeat_table_close() {
		echo '

'. __( 'Add Row', 'cmb' ) .'
';
	}

	/**
	 * Generates table row markup for repeatable fields
	 * @since 1.0.0
	 * @param string $input Table cell markup
	 */
	private static function repeat_row( $input ) {
		echo '
', self::repeat_cell( $input ) ,'
';
	}

	/**
	 * Generates the empty table row markup (for duplication) for repeatable fields
	 * @since 1.0.0
	 * @param string $input Table cell markup
	 */
	private static function empty_row( $input ) {
		echo '
', self::repeat_cell( $input ) ,'
';
	}

	/**
	 * Generates table cell markup for repeatable fields
	 * @since  1.0.0
	 * @param  string $input Text input field
	 * @return string        HTML table cell markup
	 */
	private static function repeat_cell( $input ) {
		return ''. $input .'	'. __( 'Remove', 'cmb' ) .'	';
	}

	/**
	 * Determine a file's extension
	 * @since  1.0.0
	 * @param  string       $file File url
	 * @return string|false       File extension or false
	 */
	public static function get_file_ext( $file ) {
		$parsed = @parse_url( $file, PHP_URL_PATH );
		return $parsed ? strtolower( pathinfo( $parsed, PATHINFO_EXTENSION ) ) : false;
	}

	/**
	 * Determines if a file has a valid image extension
	 * @since  1.0.0
	 * @param  string $file File url
	 * @return bool         Whether file has a valid image extension
	 */
	public static function is_valid_img_ext( $file ) {
		$file_ext = self::get_file_ext( $file );

		self::$valid = empty( self::$valid ) ? (array) apply_filters( 'cmb_valid_img_types', array( 'jpg', 'jpeg', 'png', 'gif', 'ico', 'icon' ) ) : self::$valid;

		return ( $file_ext && in_array( $file_ext, self::$valid ) );
	}

	/**
	 * Begin Field Types
	 */

	public static function text( $field, $meta ) {
		echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? $meta : $field['std'], '" />', self::desc( $field['desc'], true );
	}

	public static function text_repeat( $field, $meta ) {
		self::repeat_text_field( $field, $meta );
	}

	public static function text_small( $field, $meta ) {
		echo '<input class="cmb_text_small" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? $meta : $field['std'], '" />', self::desc( $field['desc'] );
	}

	public static function text_small_repeat( $field, $meta ) {
		self::repeat_text_field( $field, $meta, 'cmb_text_small' );
	}

	public static function text_medium( $field, $meta ) {
		echo '<input class="cmb_text_medium" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? $meta : $field['std'], '" />', self::desc( $field['desc'] );
	}

	public static function text_medium_repeat( $field, $meta ) {
		self::repeat_text_field( $field, $meta, 'cmb_text_medium' );
	}

	public static function text_email( $field, $meta ) {
		echo '<input class="cmb_text_email cmb_text_medium" type="email" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? $meta : $field['std'], '" />', self::desc( $field['desc'], true );
	}

	public static function text_email_repeat( $field, $meta ) {
		self::repeat_text_field( $field, $meta, 'cmb_text_email cmb_text_medium', 'email' );
	}

	public static function text_url( $field, $meta ) {
		$val = ! empty( $meta ) ? $meta : $field['std'];
		$protocols = isset( $field['protocols'] ) ? (array) $field['protocols'] : null;
		$val = $val ? esc_url( $val, $protocols ) : '';

		echo '<input class="cmb_text_url cmb_text_medium" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $val, '" />', self::desc( $field['desc'], true );
	}

	public static function text_url_repeat( $field, $meta ) {
		$val = ! empty( $meta ) ? $meta : $field['std'];
		$protocols = isset( $field['protocols'] ) ? (array) $field['protocols'] : null;
		$val = $val ? esc_url( $val, $protocols ) : '';
		self::repeat_text_field( $field, $val, 'cmb_text_url cmb_text_medium' );
	}

	public static function text_date( $field, $meta ) {
		echo '<input class="cmb_text_small cmb_datepicker" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? $meta : $field['std'], '" />', self::desc( $field['desc'] );
	}

	public static function text_date_timestamp( $field, $meta ) {
		echo '<input class="cmb_text_small cmb_datepicker" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? date( 'm\/d\/Y', $meta ) : $field['std'], '" />', self::desc( $field['desc'] );
	}

	public static function text_datetime_timestamp( $field, $meta, $object_id ) {

		// This will be used if there is a select_timezone set for this field
		$tz_offset = cmb_Meta_Box::field_timezone_offset( $object_id );
		if ( !empty( $tz_offset ) ) {
			$meta -= $tz_offset;
		}

		echo '<input class="cmb_text_small cmb_datepicker" type="text" name="', $field['id'], '[date]" id="', $field['id'], '_date" value="', '' !== $meta ? date( 'm\/d\/Y', $meta ) : $field['std'], '" />';
		echo '<input class="cmb_timepicker text_time" type="text" name="', $field['id'], '[time]" id="', $field['id'], '_time" value="', '' !== $meta ? date( 'h:i A', $meta ) : $field['std'], '" />', self::desc( $field['desc'] );
	}

	public static function text_datetime_timestamp_timezone( $field, $meta ) {

		$datetime = unserialize($meta);
		$meta = $tzstring = false;

		if ( $datetime && $datetime instanceof DateTime ) {
			$tz = $datetime->getTimezone();
			$tzstring = $tz->getName();

			$meta = $datetime->getTimestamp() + $tz->getOffset( new DateTime('NOW') );
		}

		echo '<input class="cmb_text_small cmb_datepicker" type="text" name="', $field['id'], '[date]" id="', $field['id'], '_date" value="', '' !== $meta ? date( 'm\/d\/Y', $meta ) : $field['std'], '" />';
		echo '<input class="cmb_timepicker text_time" type="text" name="', $field['id'], '[time]" id="', $field['id'], '_time" value="', '' !== $meta ? date( 'h:i A', $meta ) : $field['std'], '" />';

		echo '<select name="', $field['id'], '[timezone]" id="', $field['id'], '_timezone">';
		echo wp_timezone_choice( $tzstring );
		echo '</select>', self::desc( $field['desc'] );
	}

	public static function text_time( $field, $meta ) {
		echo '<input class="cmb_timepicker text_time" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? $meta : $field['std'], '" />', self::desc( $field['desc'] );
	}

	public static function select_timezone( $field, $meta ) {
		$meta = '' !== $meta ? $meta : $field['std'];
		if ( '' === $meta )
			$meta = cmb_Meta_Box::timezone_string();

		echo '<select name="', $field['id'], '" id="', $field['id'], '">';
		echo wp_timezone_choice( $meta );
		echo '</select>';
	}

	public static function text_money( $field, $meta ) {
		echo ! empty( $field['before'] ) ? '' : '$', ' <input class="cmb_text_money" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? $meta : $field['std'], '" />', self::desc( $field['desc'] );
	}

	public static function text_money_repeat( $field, $meta ) {
		self::repeat_text_field( $field, $meta, 'cmb_text_money' );
	}

	public static function colorpicker( $field, $meta ) {
		$meta = '' !== $meta ? $meta : $field['std'];
		$hex_color = '(([a-fA-F0-9]){3}){1,2}$';
		if ( preg_match( '/^' . $hex_color . '/i', $meta ) ) // Value is just 123abc, so prepend #.
			$meta = '#' . $meta;
		elseif ( ! preg_match( '/^#' . $hex_color . '/i', $meta ) ) // Value doesn't match #123abc, so sanitize to just #.
			$meta = "#";
		echo '<input class="cmb_colorpicker cmb_text_small" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta, '" />', self::desc( $field['desc'] );
	}

	public static function textarea( $field, $meta ) {
		echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="10">', '' !== $meta ? $meta : $field['std'], '</textarea>', self::desc( $field['desc'], true );
	}

	public static function textarea_small( $field, $meta ) {
		echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4">', '' !== $meta ? $meta : $field['std'], '</textarea>', self::desc( $field['desc'], true );
	}

	public static function textarea_code( $field, $meta ) {
		echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="10" class="cmb_textarea_code">', '' !== $meta ? $meta : $field['std'], '</textarea>', self::desc( $field['desc'], true );
	}

	public static function select( $field, $meta ) {
		if( empty( $meta ) && !empty( $field['std'] ) ) $meta = $field['std'];
		echo '<select name="', $field['id'], '" id="', $field['id'], '">';
		foreach ($field['options'] as $option) {
			echo '<option value="', $option['value'], '"', $meta == $option['value'] ? ' selected="selected"' : '', '>', $option['name'], '</option>';
		}
		echo '</select>', self::desc( $field['desc'], true );
	}

	public static function radio_inline( $field, $meta ) {
		if( empty( $meta ) && !empty( $field['std'] ) ) $meta = $field['std'];
		echo '
';
		$i = 1;
		foreach ($field['options'] as $option) {
			echo '
<input type="radio" name="', $field['id'], '" id="', $field['id'], $i, '" value="', $option['value'], '"', checked( $meta == $option['value'] ), ' /> ', $option['name'], '
';
			$i++;
		}
		echo '
', self::desc( $field['desc'], true );
	}

	public static function radio( $field, $meta ) {
		if( empty( $meta ) && !empty( $field['std'] ) ) $meta = $field['std'];
		echo '
';
		$i = 1;
		foreach ($field['options'] as $option) {
			echo '
<input type="radio" name="', $field['id'], '" id="', $field['id'], $i,'" value="', $option['value'], '" ', checked( $meta == $option['value'] ), ' /> ', $option['name'].'
';
			$i++;
		}
		echo '
', self::desc( $field['desc'], true );
	}

	public static function checkbox( $field, $meta ) {
		echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '" ', checked( ! empty( $meta ) ), ' /> ', self::desc( $field['desc'] ) ,'';
	}

	public static function multicheck( $field, $meta ) {
		echo '
';
		$i = 1;
		foreach ( $field['options'] as $value => $name ) {
			echo '
<input type="checkbox" name="', $field['id'], '[]" id="', $field['id'], $i, '" value="', $value, '" ', checked( in_array( $value, $meta ) ), '  /> ', $name, '
';
			$i++;
		}
		echo '
', self::desc( $field['desc'] );
	}

	public static function title( $field, $meta, $object_id, $object_type ) {
		$tag = $object_type == 'post' ? 'h5' : 'h3';
		echo '<'. $tag .' class="cmb_metabox_title">', $field['name'], '</'. $tag .'>', self::desc( $field['desc'], true );
	}

	public static function wysiwyg( $field, $meta ) {
		wp_editor( $meta ? $meta : $field['std'], $field['id'], isset( $field['options'] ) ? $field['options'] : array() );
		echo self::desc( $field['desc'], true );
	}

	public static function taxonomy_select( $field, $meta, $object_id ) {

		echo '<select name="', $field['id'], '" id="', $field['id'], '">';
		$names = wp_get_object_terms( $object_id, $field['taxonomy'] );
		$terms = get_terms( $field['taxonomy'], 'hide_empty=0' );
		foreach ( $terms as $term ) {
			if ( !is_wp_error( $names ) && !empty( $names ) && ! strcmp( $term->slug, $names[0]->slug ) ) {
				echo '<option value="' . $term->slug . '" selected>' . $term->name . '</option>';
			} else {
				echo '<option value="' . $term->slug . '  ' , $meta == $term->slug ? $meta : ' ' ,'  ">' . $term->name . '</option>';
			}
		}
		echo '</select>', self::desc( $field['desc'], true );
	}

	public static function taxonomy_radio( $field, $meta, $object_id ) {

		$names = wp_get_object_terms( $object_id, $field['taxonomy'] );
		$terms = get_terms( $field['taxonomy'], 'hide_empty=0' );
		echo '
';
		$i = 1;
		foreach ( $terms as $term ) {
			$checked = ( !is_wp_error( $names ) && !empty( $names ) && !strcmp( $term->slug, $names[0]->slug ) );

			echo '
<input type="radio" name="', $field['id'], '" id="', $field['id'], $i,'" value="'. $term->slug . '" ', checked( $checked ), ' /> ' . $term->name . '
';
			$i++;
		}
		echo '
', self::desc( $field['desc'], true );
	}

	public static function taxonomy_multicheck( $field, $meta, $object_id ) {
		echo '
';
		$names = wp_get_object_terms( $object_id, $field['taxonomy'] );
		$terms = get_terms( $field['taxonomy'], 'hide_empty=0' );
		$i = 1;
		foreach ( $terms as $term ) {
			echo '
<input type="checkbox" name="', $field['id'], '[]" id="', $field['id'], $i,'" value="'. $term->slug . '" ';
			foreach ($names as $name) {
				checked( $term->slug == $name->slug );
			}

			echo ' /> ' . $term->name . '
';
			$i++;
		}
		echo '
', self::desc( $field['desc'] );
	}

	public static function file_list( $field, $meta, $object_id ) {

		echo '<input class="cmb_upload_file cmb_upload_list" type="hidden" size="45" id="', $field['id'], '" name="', $field['id'], '" value="', $meta, '" />';
		echo '<input class="cmb_upload_button button cmb_upload_list" type="button" value="'. __( 'Add or Upload File', 'cmb' ) .'" />', self::desc( $field['desc'], true );

		echo '
';

		if ( $meta ) {

			foreach ( $meta as $id => $fullurl ) {
				if ( self::is_valid_img_ext( $fullurl ) ) {
					echo
					'
',
						wp_get_attachment_image( $id, array( 50, 50 ) ),
						'
'. __( 'Remove Image', 'cmb' ) .'

						<input type="hidden" id="filelist-', $id ,'" name="', $field['id'] ,'[', $id ,']" value="', $fullurl ,'" />

';

				} else {
					$parts = explode( '/', $fullurl );
					for ( $i = 0; $i < count( $parts ); ++$i ) {
						$title = $parts[$i];
					}
					echo
					'
',
						__( 'File:', 'cmb' ), ' ', $title, '    ('. __( 'Download', 'cmb' ) .' / '. __( 'Remove', 'cmb' ) .')
						<input type="hidden" id="filelist-', $id ,'" name="', $field['id'] ,'[', $id ,']" value="', $fullurl ,'" />

';
				}
			}
		}

		echo '
';
	}

	public static function file( $field, $meta, $object_id, $object_type ) {

		$input_type_url = 'hidden';
		if ( 'url' == $field['allow'] || ( is_array( $field['allow'] ) && in_array( 'url', $field['allow'] ) ) )
			$input_type_url = 'text';
		echo '<input class="cmb_upload_file" type="' . $input_type_url . '" size="45" id="', $field['id'], '" name="', $field['id'], '" value="', $meta, '" />';
		echo '<input class="cmb_upload_button button" type="button" value="'. __( 'Add or Upload File', 'cmb' ) .'" />';

		$_id_name = $field['id'] .'_id';

		$_id_meta = get_metadata( $object_type, $object_id, $_id_name, ( ! isset( $field['multiple'] ) || ! $field['multiple'] ) );

		// If there is no ID saved yet, try to get it from the url
		if ( $meta && ! $_id_meta ) {
			$_id_meta = cmb_Meta_Box::image_id_from_url( esc_url_raw( $meta ) );
		}

		echo '<input class="cmb_upload_file_id" type="hidden" id="', $_id_name, '" name="', $_id_name, '" value="', $_id_meta, '" />',
		self::desc( $field['desc'], true ),
		'
';
			if ( ! empty( $meta ) ) {

				if ( self::is_valid_img_ext( $meta ) ) {
					echo '
';
					echo '';
					echo '
'. __( 'Remove Image', 'cmb' ) .'
';
					echo '
';
				} else {
					// $file_ext = self::get_file_ext( $meta );
					$parts = explode( '/', $meta );
					for ( $i = 0; $i < count( $parts ); ++$i ) {
						$title = $parts[$i];
					}
					echo __( 'File:', 'cmb' ), ' ', $title, '    ('. __( 'Download', 'cmb' ) .' / '. __( 'Remove', 'cmb' ) .')';
				}
			}
		echo '
';
	}

	public static function oembed( $field, $meta, $object_id, $object_type ) {
		echo '<input class="cmb_oembed" type="text" name="', $field['id'], '" id="', $field['id'], '" value="', '' !== $meta ? $meta : $field['std'], '" />', self::desc( $field['desc'], true );
		echo '

';
		echo '
';

			if ( $meta != '' )
				echo cmb_Meta_Box_ajax::get_oembed( $meta, $object_id, array(
					'object_type' => $object_type,
					'oembed_args' => array( 'width' => '640' ),
					'field_id'    => $field['id'],
				) );

		echo '
';
	}

	/**
	 * Default fallback. Allows rendering fields via "cmb_render_$name" hook
	 * @since  1.0.0
	 * @param  string $name      Non-existent method name
	 * @param  array  $arguments All arguments passed to the method
	 */
	public function __call( $name, $arguments ) {
		list( $field, $meta, $object_id, $object_type ) = $arguments;
		// When a non-registered field is called, send it through an action.
		do_action( "cmb_render_$name", $field, $meta, $object_id, $object_type );
	}

}


text:
import Utils     = require("../helpers/Utils");
import transform = require("./ITransform");
import stream  = require('stream');

var splitStream = require("split");

class CsvToJsonTransformer implements transform.ITransform {
    id:          string;
    description: string;
    type = "CsvToJsonTransformer";
    headers:string[] = null;
    /**
     * Accepted input types.
     */
    inputDataTypes:  transform.InputDataType[];
    /**
     * Generated output types.
     */
    outputDataTypes: transform.OutputDataType[];

    //create?(opt?: ITransformFactoryOptions[]): stream.Readable | stream.Writable | stream.Transform;

    fieldDelimiter:string;
    textQualifier:string;
    latField:string;
    longField:string;

    constructor(public title: string) {
        this.id = Utils.newGuid();
        //this.description = description;
    }

    initialize(opt, callback) {
      var propertyParameter = opt.parameters.filter((p)=>p.type.title == "fieldDelimiter")[0];
      if (propertyParameter) {
        this.fieldDelimiter = propertyParameter.value;
      }

      propertyParameter = opt.parameters.filter((p)=>p.type.title == "textQualifier")[0];
      if (propertyParameter) {
        this.textQualifier = propertyParameter.value;
      }

      propertyParameter = opt.parameters.filter((p)=>p.type.title == "latField")[0];
      if (propertyParameter) {
        this.latField = propertyParameter.value;
      }

      propertyParameter = opt.parameters.filter((p)=>p.type.title == "longField")[0];
      if (propertyParameter) {
        this.longField = propertyParameter.value;
      }

      callback(null);
    }

    create(config, opt?: transform.ITransformFactoryOptions[]): NodeJS.ReadWriteStream {
      var t = new stream.Transform();
      /*stream.Transform.call(t);*/

      var split = -1;
      var headers :string[];

      t.setEncoding("utf8");

      t._transform = (chunk, encoding, done) => {
           /*console.log("##### CTJT #####");*/
          // console.log(chunk.toString("utf8"));

          var line :string= chunk.toString("utf8");

          if (!line || line.trim() == "") {
            console.log("Empty line, ignore");
            done();
            return;
          }

          var textQualifierRegExp = new RegExp("(?:\\s*(?:" + this.textQualifier + "([^" + this.textQualifier + "]*)" + this.textQualifier + "|([^" + this.fieldDelimiter + "]+))?\\s*" + this.fieldDelimiter + "?)+?","g");
          var fields:any[] = [];
          var result:RegExpExecArray;
          var prevIndex = -1;
          while ((result = textQualifierRegExp.exec(line)).index > prevIndex) {
            var strValue: string = '';
            if (result[1] && result[1].length > 0) {
              strValue = result[1];
            } else if (result[2] && result[2].length > 0) {
              strValue = result[2];
            }

              /*console.log("Number: '" + strValue + "': " + /^\-?[0-9]*(,|\.)?[0-9]+$/.test(strValue));*/
            if (/^\-?[0-9]*(,|\.)?[0-9]+$/.test(strValue)) {
              fields.push(parseInt(strValue.replace(/,/,'.')));
            }
            else {
              fields.push(strValue);
            }

            prevIndex = result.index;
          }

          /*var fields = line.split(this.fieldDelimiter);*/
          // console.log(line);

          if (!headers) {
            headers = [];
            fields.filter(f=>f && f!='').forEach(f=>{
              headers.push(f.toString());
            });
            console.log(headers);
            done();
            return;
          }
          else {
            var obj:any = {type:"Feature", properties:{}};

            headers.forEach(h=>{
              var hIndex = headers.indexOf(h);
              obj.properties[h] = fields[hIndex];
            })

            /*console.log(obj);*/

            if (this.latField && this.longField && !obj.geometry) {
              var strLat:string = obj.properties[this.longField];
              var strLong:string = obj.properties[this.latField];
              strLat = strLat.replace(/,/g,'.');
              strLong = strLong.replace(/,/g,'.');
              var lat = parseFloat(strLat);
              var long = parseFloat(strLong);

              /*console.log(lat + " - " + long);*/

              obj.geometry = {
                type: "Point",
                coordinates: [lat, long]
              }

            }

            // console.log(obj);
            t.push(JSON.stringify(obj));
            done();
          }
        }

    //var s = splitStream().pipe(t);

    return t;
  }

}
export=CsvToJsonTransformer;


text:
%% AVGSHAPES - averages avalanche shapes
% The shape, also known as the temporal profile, of a neuronal avalanche is
% the number of neurons active at each time bin. This function computes the
% mean temporal profile of neuronal avalanches. By default the function
% considers avalanches for all durations, but the user may specify an
% alternative sampling method as a variable input.
%
% Syntax:   avgProfiles = avgshapes(shapes, durations, varargin)
%
% Inputs:
%   shapes (cell array) - array containing vectors representing avalanche
%     shapes
%   durations (double) - vector containing duration of each avalanche
%
% Variable Inputs (shape sampling methods):
%   (..., 'limits', lowerLim, upperLim) - uses avalanche shapes whose
%     durations are inclusively bound by specified limits (scalar doubles)
%   (..., 'order', magnitude) - uses avalanche shapes whose durations
%     occur with frequency on the same order of magnitude if magnitude is
%     scalar or within the bounds of decades 10^(min(magnitude)) and
%     10^(max(magnitude)) if magnitude is a vector.
%   (..., 'linspace', lowerLim, upperLim, n) - uses avalanche shapes of
%     n different durations, linearly spaced between specified limits
%     (scalar double)
%   (..., 'logspace', x, lowerLim, upperLim) - uses avalanche shapes whose
%     durations are logarithmically spaced between x^(lowerLim) and
%     x^(upperLim) (scalar doubles)
%   (..., 'durations', durs) - uses avalanche shapes of specific durations,
%     durs (vector double)
%   (..., 'cutoffs', minDur, threshold) - uses avalanche shapes bounded
%     below by both an absolute minimum duration (>= minDur) and a
%     threshold for the frequency of occurrence (>= threshold) (scalar
%     doubles)
%
% Output:
%   avgProfiles (cell array) - array of mean temporal profiles (vector double)
%
% Examples:
%   raster = randi([0 1], [10 1000]);
%   asdf = sparse2asdf(raster, 1);
%   asdf2 = asdftoasdf2(asdf, 'test', 'spikes', 'date');
%   Av = avprops(asdf2, 'duration', 'shape');
%   avgProfiles1 = avgshapes(Av.shape, Av.duration, 'order', 2);
%     % computes aerage shapes for avalanches whose durations occur
%       between 100 and 1000 times
%   avgProfiles2 = avgshapes(Av.shape, Av.duration, 'order', [1 3]);
%     % computes average shapes for avalanches whose durations occur
%       between 10 and 1000 times.
%   avgProfiles3 = avgshapes(Av.shape, Av.duration, 'durations', [5 8 14]);
%     % computes average shapes for duration 5, 8, and 14 avalanches
%   avgProfiles4 = avgshapes(Av.shape, Av.duration, 'cutoffs', 5, 50);
%     % computes average shapes for durations greater than 5 and for
%       avalanches whose durations occur at least 50 times.
%
% Other m-files required: none
% Subfunctions: none
% MAT-files required: none
%
% See also: AVPROPS

% Author: Najja Marshall and Nick Timme
% Email: njm2149@columbia.edu and nicholas.m.timme@gmail.com
% June 2013; Last revision: 10-Aug-2014

%==============================================================================
% Copyright (c) 2013, The Trustees of Indiana University
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
%   1. Redistributions of source code must retain the above copyright notice,
%      this list of conditions and the following disclaimer.
%
%   2. Redistributions in binary form must reproduce the above copyright notice,
%      this list of conditions and the following disclaimer in the documentation
%      and/or other materials provided with the distribution.
%
%   3. Neither the name of Indiana University nor the names of its contributors
%      may be used to endorse or promote products derived from this software
%      without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.

function avgProfiles = avgshapes(shapes, durations, varargin)
%% Determine sampling method
if ~isempty(varargin)
    switch varargin{1}
        case 'limits'
            lowerLim = varargin{2};
            upperLim = varargin{3};

            targetIndices = (durations >= lowerLim & durations <= upperLim);

        case 'order'
            magnitude = varargin{2};

            unqDurations = unique(durations);
            nUnqDurations = zeros(1, numel(unqDurations));

            % Count number of unique durations
            for iUnqDur = 1:length(unqDurations)
                theseDurations = (durations == unqDurations(iUnqDur));
                nUnqDurations(iUnqDur) = nnz(theseDurations);
            end

            if isscalar(magnitude)
                lowerLim = 10^magnitude;
                upperLim = 10^(magnitude + 1);
            else
                lowerLim = 10^(min(magnitude));
                upperLim = 10^(max(magnitude));
            end

            targetDurations = ...
                (nUnqDurations >= lowerLim & nUnqDurations < upperLim);
            targetIndices = ...
                ismember(durations, unqDurations(targetDurations));

        case 'linspace'
            lowerLim = varargin{2};
            upperLim = varargin{3};
            n = varargin{4};

            targetDurations = round(linspace(lowerLim, upperLim, n));
            targetIndices = ismember(durations, targetDurations);

        case 'logspace'
            x = varargin{2};
            lowerLim = varargin{3};
            upperLim = varargin{4};

            targetDurations = x.^(lowerLim:upperLim);
            targetIndices = ismember(durations, targetDurations);

        case 'durations'
            targetDurations = varargin{2};
            targetIndices = ismember(durations, targetDurations);

        case 'cutoffs'
            lowerLim = varargin{2};
            threshold = varargin{3};

            unqDurations = unique(durations);
            nUnqDurations = zeros(1,numel(unqDurations));

            % Count number of unique durations
            for iUnqDur = 1:length(unqDurations)
                theseDurations = (durations == unqDurations(iUnqDur));
                nUnqDurations(iUnqDur) = nnz(theseDurations);
            end

            targetDurations = ...
                (unqDurations >= lowerLim & nUnqDurations >= threshold);
            targetIndices = ...
                ismember(durations, unqDurations(targetDurations));
    end
else
    targetIndices = true(1, length(durations));
end

%% Compute average shapes

% Subsample avalanche shapes and durations using targeted indices
sampledShapes = shapes(targetIndices);
sampledDurations = durations(targetIndices);

% Ensure proper alignment of shapes for vertical concatenation
sampledShapes = reshape(sampledShapes, length(sampledShapes), 1);

% Compute mean temporal profile of avalanches with identical durations
unqSampledDurations = unique(sampledDurations);

avgProfiles = cell(numel(unqSampledDurations), 1);
for iUnqDur = 1:length(unqSampledDurations)
    theseShapes = ...
        sampledShapes(sampledDurations == unqSampledDurations(iUnqDur));
    avgProfiles{iUnqDur} = mean(cell2mat(theseShapes),1);
end

avgProfiles = avgProfiles(~cellfun('isempty', avgProfiles));


text:
package uk.ac.warwick.dcs.SemEval;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.junit.Before;
import org.junit.Test;

import uk.ac.warwick.dcs.SemEval.exceptions.WordRangeMapException;
import uk.ac.warwick.dcs.SemEval.models.AnnotationSpan;
import uk.ac.warwick.dcs.SemEval.models.AnnotationType;
import uk.ac.warwick.dcs.SemEval.models.POSTaggedTweet;
import uk.ac.warwick.dcs.SemEval.models.Tweet;
import uk.ac.warwick.dcs.SemEval.models.AnnotationType.AnnotationKind;
import uk.ac.warwick.dcs.SemEval.subjectivity.SubjectivityMap;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.Evaluation;
import weka.classifiers.functions.SimpleLogistic;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import cmu.arktweetnlp.RawTagger;
import edu.stanford.nlp.util.Pair;

public class MLTest {

	private SubjectivityMap s;
	private RawTagger       tagger;

	@Before
	public void setup() throws IOException {
		this.s = new SubjectivityMap();
		this.tagger = new RawTagger();
		this.tagger.loadModel("model.20120919");
	}

	@Test
	public void testMatchingUp() throws Exception {
		Tweet t1 = new Tweet("In case you weren't invited . . .: ..it 'may' have been because Andy was hiding a deep,dark secret Personali... http://bit.ly/WdxawR ", 0, 0);
		t1.addAnnotation(new AnnotationSpan(AnnotationKind.Negative, 3, 4));
		t1.addAnnotation(new AnnotationSpan(AnnotationKind.Negative, 17, 20));

		Tweet t2 = new Tweet("Barclays Profit Driven by Investment Banking: LONDON--Barclays PLC (BCS) Wednesday continued to reap the rewards... http://bit.ly/W5t0au ", 0, 0);
		t2.addAnnotation(new AnnotationSpan(AnnotationKind.Positive, 10, 14));

		POSTaggedTweet p1 = new POSTaggedTweet(t1, this.tagger);
		POSTaggedTweet p2 = new POSTaggedTweet(t2, this.tagger);
		this.s.updateFromTweet(p1);
		this.s.updateFromTweet(p2);

		MLSubjectiveTweet m1 = new MLSubjectiveTweet(p1);
		MLSubjectiveTweet m2 = new MLSubjectiveTweet(p2);

		List<String> nominalVals = AnnotationType.getNominalSubjList();
		ArrayList<Attribute> attrs = new ArrayList<Attribute>();
		attrs.add(new Attribute("conf1"));
		attrs.add(new Attribute("conf2"));
		attrs.add(new Attribute("conf3"));
		Attribute classAttr = new Attribute("subjective", nominalVals);
		attrs.add(classAttr);

		Instances setInstances = new Instances("subj", attrs, 0);
		setInstances.setClassIndex(3);

		Instance instanceTemplate = new DenseInstance(4);
		instanceTemplate.setDataset(setInstances);

		for (Instance dat : m1.addInstanceData(instanceTemplate, setInstances, this.s)) {
			assertTrue(setInstances.checkInstance(dat));
			setInstances.add(dat);
		}
		for (Instance dat : m2.addInstanceData(instanceTemplate, setInstances, this.s)) {
			assertTrue(setInstances.checkInstance(dat));
			setInstances.add(dat);
		}

		AbstractClassifier clf = new SimpleLogistic();
		clf.buildClassifier(setInstances);
		Evaluation elv = new Evaluation(setInstances);
		//elv.crossValidateModel(clf, setInstances, 1, new Random());
		elv.evaluateModel(clf, setInstances);
		System.out.println(elv.toClassDetailsString());
		System.out.println(elv.toSummaryString());
		System.out.println(elv.toClassDetailsString());
		System.out.println(elv.toMatrixString());
		System.out.println(clf);

		for (Pair<Integer, Instance> dat : m1.getPredictionInstances(instanceTemplate, setInstances, this.s)) {
			double prediction = clf.classifyInstance(dat.second);
			String predictionStr = classAttr.value((int) prediction);
			AnnotationType a = new AnnotationType(predictionStr);
			m1.getWrappedTweet().applyDerivedAnnotation(dat.first, a);
		}

		for (Pair<Integer, Instance> dat : m2.getPredictionInstances(instanceTemplate, setInstances, this.s)) {
			double prediction = clf.classifyInstance(dat.second);
			String predictionStr = classAttr.value((int) prediction);
			AnnotationType a = new AnnotationType(predictionStr);
			m2.getWrappedTweet().applyDerivedAnnotation(dat.first, a);
		}

		assertTrue(m1.getWrappedTweet().getParent().subjEqual(t1));
		assertTrue(m2.getWrappedTweet().getParent().subjEqual(t2));
	}

	@Test
	public void testML() throws Exception {

		Tweet t1 = new Tweet("In case you weren't invited . . .: ..it 'may' have been because Andy was hiding a deep,dark secret Personali... http://bit.ly/WdxawR ", 0, 0);
		t1.addAnnotation(new AnnotationSpan(AnnotationKind.Negative, 3, 4));
		t1.addAnnotation(new AnnotationSpan(AnnotationKind.Negative, 17, 20));

		Tweet t2 = new Tweet("Barclays Profit Driven by Investment Banking: LONDON--Barclays PLC (BCS) Wednesday continued to reap the rewards... http://bit.ly/W5t0au ", 0, 0);
		t2.addAnnotation(new AnnotationSpan(AnnotationKind.Positive, 10, 14));

		POSTaggedTweet p1 = new POSTaggedTweet(t1, this.tagger);
		POSTaggedTweet p2 = new POSTaggedTweet(t2, this.tagger);
		this.s.updateFromTweet(p1);
		this.s.updateFromTweet(p2);

		MLSubjectiveTweet m1 = new MLSubjectiveTweet(p1);
		MLSubjectiveTweet m2 = new MLSubjectiveTweet(p2);

		List<String> nominalVals = AnnotationType.getNominalSubjList();
		ArrayList<Attribute> attrs = new ArrayList<Attribute>();
		attrs.add(new Attribute("conf1"));
		attrs.add(new Attribute("conf2"));
		attrs.add(new Attribute("conf3"));
		attrs.add(new Attribute("subjective", nominalVals));

		Instances setInstances = new Instances("subj", attrs, 0);
		setInstances.setClassIndex(3);

		Instance instanceTemplate = new DenseInstance(4);
		instanceTemplate.setDataset(setInstances);

		for (Instance dat : m1.addInstanceData(instanceTemplate, setInstances, this.s)) {
			assertTrue(setInstances.checkInstance(dat));
			setInstances.add(dat);
		}
		for (Instance dat : m2.addInstanceData(instanceTemplate, setInstances, this.s)) {
			assertTrue(setInstances.checkInstance(dat));
			setInstances.add(dat);
		}

		AbstractClassifier clf = new SimpleLogistic();
		clf.buildClassifier(setInstances);
		Evaluation elv = new Evaluation(setInstances);
		//elv.crossValidateModel(clf, setInstances, 1, new Random());
		elv.evaluateModel(clf, setInstances);
		System.out.println(elv.toClassDetailsString());
		System.out.println(elv.toSummaryString());
		System.out.println(elv.toClassDetailsString());
		System.out.println(elv.toMatrixString());
		System.out.println(clf);

	}

}


text:
package de.terrestris.shogun2.importer.communication;

import de.terrestris.shogun2.importer.communication.AbstractRESTEntity;
import de.terrestris.shogun2.importer.communication.RESTDataStore;

/**
 * @author Daniel Koch
 * @author terrestris GmbH & Co. KG
 */
public class RESTTarget extends AbstractRESTEntity {

    /**
     *
     */
    @SuppressWarnings("unused")
    private String href;

    /**
     *
     */
    @SuppressWarnings("unused")
    private RESTDataStore dataStore;

}


text:
@protocol ANListControllerItemsHandlerDelegate

- (id<ANListControllerWrapperInterface>)listViewWrapper;
- (id<ANListControllerConfigurationModelInterface>)configurationModel;

@end

@interface ANListControllerItemsHandler : NSObject
<
    ANListControllerReusableInterface,
    ANListControllerReusableLoadInterface
>

+ (instancetype)handlerWithDelegate:(id<ANListControllerItemsHandlerDelegate>)delegate;

@end


text:
/*jslint node: true, nomen: true */
"use strict";

var Boom = require('boom');

module.exports = function () {
    var Posts = require(__dirname + '/../schemas/posts'),
        updater = require(__dirname + '/../helpers/mongooseDocUpdater'),
        optionsParser = require(__dirname + '/../helpers/searchParamsParser'),
        options,
        exp = {
            getAll : function (request, reply) {
                Posts.find(function (err, result) {
                    if (err) { reply(Boom.badImplementation(err.message)); }
                    reply(result);
                });
            },
            search : function (request, reply) {
                options = optionsParser(request.query);
                Posts.textSearch(request.query.text, options, function (err, result) {
                    if (err) { reply(Boom.badImplementation(err.message)); }
                    reply(result);
                });
            },
            getById : function (request, reply) {
                Posts.findById(request.params.id, function (err, result) {
                    if (err) { reply(Boom.badImplementation(err.message)); }
                    reply(result);
                });
            },
            insert : function (request, reply) {
                var item = new Posts(request.params);
                item.created_at = new Date();
                item.updated_at = new Date();
                item.save(function (err) {
                    if (err) { reply(Boom.badImplementation(err.message)); }
                    reply(item);
                });
            },
            update : function (request, reply) {
                Posts.findById(request.params.id, function (err, item) {
                    if (err) { reply(Boom.badImplementation(err.message)); }
                    if (!item) { reply(Boom.notFound()); }
                    updater.updateDocument(item, Posts, request.params);
                    item.save(function (err) {
                        if (err) { reply(Boom.badImplementation(err.message)); }
                        reply(item);
                    });
                });
            },
            remove : function (request, reply) {
                Posts.findById(request.params.id, function (err, item) {
                    if (err) { reply(Boom.badImplementation(err.message)); }
                    if (!item) { reply(Boom.notFound()); }
                    item.remove(function (err) {
                        if (err) { reply(Boom.badImplementation(err.message)); }
                        reply({ success : true });
                    });
                });
            }
        };
    return exp;
};


text:
import optparse
import os
import pprint
import re
import shlex
import subprocess
import sys
import shutil
import string

# gcc and g++ as defaults matches what GYP's Makefile generator does,
# except on OS X.
CC = os.environ.get('CC', 'cc' if sys.platform == 'darwin' else 'gcc')
CXX = os.environ.get('CXX', 'c++' if sys.platform == 'darwin' else 'g++')

root_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(root_dir, 'tools', 'gyp', 'pylib'))
from gyp.common import GetFlavor

# parse our options
parser = optparse.OptionParser()

valid_os = ('win', 'mac', 'solaris', 'freebsd', 'openbsd', 'linux', 'android')
valid_arch = ('arm', 'arm64', 'ia32', 'mips', 'mipsel', 'x32', 'x64', 'x86')
valid_arm_float_abi = ('soft', 'softfp', 'hard')
valid_mips_arch = ('loongson', 'r1', 'r2', 'r6', 'rx')
valid_mips_fpu = ('fp32', 'fp64', 'fpxx')
valid_mips_float_abi = ('soft', 'hard')
valid_intl_modes = ('none', 'small-icu', 'full-icu', 'system-icu')

parser.add_option('--debug',
    action='store_true',
    dest='debug',
    help='also build debug build')

parser.add_option('--dest-cpu',
    action='store',
    dest='dest_cpu',
    choices=valid_arch,
    help='CPU architecture to build for ({0})'.format(', '.join(valid_arch)))

parser.add_option('--xcode',
    action='store_true',
    dest='use_xcode',
    help='Generate xcode files')

parser.add_option('--dest-os',
    action='store',
    dest='dest_os',
    choices=valid_os,
    help='operating system to build for ({0})'.format(', '.join(valid_os)))

(options, args) = parser.parse_args()

def warn(msg):
  warn.warned = True
  prefix = '\033[1m\033[93mWARNING\033[0m' if os.isatty(1) else 'WARNING'
  print('%s: %s' % (prefix, msg))

# track if warnings occured
warn.warned = False

def b(value):
  """Returns the string 'true' if value is truthy, 'false' otherwise."""
  if value:
    return 'true'
  else:
    return 'false'

def cc_macros():
  """Checks predefined macros using the CC command."""

  try:
    p = subprocess.Popen(shlex.split(CC) + ['-dM', '-E', '-'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
  except OSError:
    print '''jc3-handling-editor configure error: No acceptable C compiler found!

        Please make sure you have a C compiler installed on your system and/or
        consider adjusting the CC environment variable if you installed
        it in a non-standard prefix.
        '''
    sys.exit()

  p.stdin.write('\n')
  out = p.communicate()[0]

  out = str(out).split('\n')

  k = {}
  for line in out:
    lst = shlex.split(line)
    if len(lst) > 2:
      key = lst[1]
      val = lst[2]
      k[key] = val
  return k

def host_arch_cc():
  """Host architecture check using the CC command."""

  k = cc_macros()

  matchup = {
    '__aarch64__' : 'arm64',
    '__i386__'    : 'ia32',
    '__x86_64__'  : 'x64',
  }

  rtn = 'ia32' # default

  for i in matchup:
    if i in k and k[i] != '0':
      rtn = matchup[i]
      break

  return rtn

def host_arch_win():
  """Host architecture check using environ vars (better way to do this?)"""

  observed_arch = os.environ.get('PROCESSOR_ARCHITECTURE', 'x86')
  arch = os.environ.get('PROCESSOR_ARCHITEW6432', observed_arch)

  matchup = {
    'AMD64'  : 'x64',
    'x86'    : 'ia32',
    'arm'    : 'arm',
    'mips'   : 'mips',
  }

  return matchup.get(arch, 'ia32')

def write(filename, data):
  filename = os.path.join(root_dir, filename)
  print 'creating ', filename
  f = open(filename, 'w+')
  f.write(data)

do_not_edit = '# Do not edit. Generated by the configure script.\n'

output = {
  'variables': { 'python': sys.executable,
                  'deps_path': os.path.relpath('deps/') },
  'include_dirs': [],
  'libraries': [],
  'defines': [],
  'cflags': [],
}

host_arch = 'x64'
target_arch = options.dest_cpu or host_arch
  # ia32 is preferred by the build tools (GYP) over x86 even if we prefer the latter
  # the Makefile resets this to x86 afterward
if target_arch == 'x86':
  target_arch = 'ia32'

output['variables']['host_arch'] = host_arch
output['variables']['target_arch'] = target_arch

# Should we add a compiler check here?

# determine the "flavor" (operating system) we're building for,
# leveraging gyp's GetFlavor function
flavor_params = {}
if (options.dest_os):
  flavor_params['flavor'] = options.dest_os

flavor = GetFlavor(flavor_params)

# variables should be a root level element,
# move everything else to target_defaults
variables = output['variables']
del output['variables']

# make_global_settings should be a root level element too
if 'make_global_settings' in output:
  make_global_settings = output['make_global_settings']
  del output['make_global_settings']
else:
  make_global_settings = False

output = {
  'variables': variables,
  'target_defaults': output,
}
if make_global_settings:
  output['make_global_settings'] = make_global_settings

pprint.pprint(output, indent=2)

write('config.gypi', do_not_edit +
      pprint.pformat(output, indent=2) + '\n')

config = {
  'BUILDTYPE': 'Debug' if options.debug else 'Release',
 # 'USE_XCODE': str(int(options.use_xcode or 0)),
  'PYTHON': sys.executable,
}

config = '\n'.join(map('='.join, config.iteritems())) + '\n'

write('config.mk',
      '# Do not edit. Generated by the configure script.\n' + config)

gyp_args = [sys.executable, 'tools/gyp_jc3_handling_editor.py', '--no-parallel']

if options.use_xcode:
  gyp_args += ['-f', 'xcode']
elif flavor == 'win' and sys.platform != 'msys':
  gyp_args += ['-f', 'msvs', '-G', 'msvs_version=auto']
else:
  gyp_args += ['-f', 'make-' + flavor]

gyp_args += args

if warn.warned:
  warn('warnings were emitted in the configure phase')

sys.exit(subprocess.call(gyp_args))


text:
using System;
using System.Threading.Tasks;
using Akka.Actor;

using Shared;
using Messages;
using Actors;

namespace Application
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            PrintInstructions();

            Console.Write("Press any key to start the actor system and validate the implementation.");
            Console.ReadKey();

            Run().Wait();
        }

        private static void PrintInstructions()
        {
            Console.WriteLine("The step 1 of the workshop is simple: just teach your SFTP actor to connect to the FTP server.");
            Console.WriteLine("Once the actor is property implemented the program should display the following messages:");
            Console.WriteLine();
            ColoredConsole.WriteLine(ConsoleColor.Cyan, "SSH.NET: Connecting...");
            ColoredConsole.WriteLine(ConsoleColor.Green, "SSH.NET: Connected.");
            ColoredConsole.WriteLine(ConsoleColor.Cyan, "SSH.NET: Disconnecting...");
            ColoredConsole.WriteLine(ConsoleColor.Green, "SSH.NET: Disconnected.");
            Console.WriteLine();
        }

        private static async Task Run()
        {
            var clientFactory = ClientFactory.Create();
            var actorSystem = ActorSystem.Create("MyActorSystem");

            var sftpActor = actorSystem.ActorOf(
                Props.Create(() => new SftpActor(clientFactory)),
                "sftpActor");

            sftpActor.Tell(new Connect());
            sftpActor.Tell(new Disconnect());

            Console.ReadKey();

            await actorSystem.Terminate();
        }
    }
}