text:
using System.Reflection;
using Microsoft.AspNetCore.Builder;

namespace Microsoft.AspNetCore.Http.Metadata;

/// <summary>
/// Indicates that a type provides a static method that provides <see cref="Endpoint"/> metadata when declared as the
/// parameter type of an <see cref="Endpoint"/> route handler delegate.
/// </summary>
public interface IEndpointParameterMetadataProvider
{
    /// <summary>
    /// Populates metadata for the related <see cref="Endpoint"/> and <see cref="ParameterInfo"/>.
    /// </summary>
    /// <remarks>
    /// This method is called by RequestDelegateFactory when creating a <see cref="RequestDelegate"/> and by MVC when creating endpoints for controller actions.
    /// This is called for each parameter of the route handler or action with a declared type implementing this interface.
    /// Add or remove objects on the <see cref="EndpointBuilder.Metadata"/> property of the <paramref name="builder"/> to modify the <see cref="Endpoint.Metadata"/> being built.
    /// </remarks>
    /// <param name="parameter">The <see cref="ParameterInfo"/> of the route handler delegate or MVC Action of the endpoint being created.</param>
    /// <param name="builder">The <see cref="EndpointBuilder"/> used to construct the endpoint for the given <paramref name="parameter"/>.</param>
    static abstract void PopulateMetadata(ParameterInfo parameter, EndpointBuilder builder);
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

global $CFG;
require_once(dirname(__FILE__) . '/../../../engine/lib.php');
require_once(dirname(__FILE__) . '/../../../engine/tests/helpers.php');

/**
 * Unit tests for the interactive with countback behaviour.
 *
 * @copyright  2009 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class qbehaviour_interactivecountback_walkthrough_test extends qbehaviour_walkthrough_test_base {
    public function test_interactive_feedback_match_reset() {

        // Create a matching question.
        $m = test_question_maker::make_a_matching_question();
        $m->shufflestems = false;
        $m->hints = array(
            new question_hint_with_parts(0, 'This is the first hint.', FORMAT_HTML, true, true),
            new question_hint_with_parts(0, 'This is the second hint.', FORMAT_HTML, true, true),
        );
        $this->start_attempt_at_question($m, 'interactive', 12);

        $choiceorder = $m->get_choice_order();
        $orderforchoice = array_combine(array_values($choiceorder), array_keys($choiceorder));
        $choices = array(0 => get_string('choose') . '...');
        foreach ($choiceorder as $key => $choice) {
            $choices[$key] = $m->choices[$choice];
        }

        // Check the initial state.
        $this->check_current_state(question_state::$todo);
        $this->check_current_mark(null);
        $this->assertEquals('interactivecountback',
                $this->quba->get_question_attempt($this->slot)->get_behaviour_name());
        $this->check_current_output(
                $this->get_contains_select_expectation('sub0', $choices, null, true),
                $this->get_contains_select_expectation('sub1', $choices, null, true),
                $this->get_contains_select_expectation('sub2', $choices, null, true),
                $this->get_contains_select_expectation('sub3', $choices, null, true),
                $this->get_contains_question_text_expectation($m),
                $this->get_contains_submit_button_expectation(true),
                $this->get_does_not_contain_feedback_expectation(),
                $this->get_tries_remaining_expectation(3),
                $this->get_does_not_contain_num_parts_correct(),
                $this->get_no_hint_visible_expectation());

        // Submit an answer with two right, and two wrong.
        $this->process_submission(array('sub0' => $orderforchoice[1],
                'sub1' => $orderforchoice[1], 'sub2' => $orderforchoice[1],
                'sub3' => $orderforchoice[1], '-submit' => 1));

        // Verify.
        $this->check_current_state(question_state::$todo);
        $this->check_current_mark(null);
        $this->check_current_output(
                $this->get_contains_select_expectation('sub0', $choices, $orderforchoice[1], false),
                $this->get_contains_select_expectation('sub1', $choices, $orderforchoice[1], false),
                $this->get_contains_select_expectation('sub2', $choices, $orderforchoice[1], false),
                $this->get_contains_select_expectation('sub3', $choices, $orderforchoice[1], false),
                $this->get_contains_submit_button_expectation(false),
                $this->get_contains_try_again_button_expectation(true),
                $this->get_does_not_contain_correctness_expectation(),
                new question_pattern_expectation('/Tries remaining: 2/'),
                $this->get_contains_hint_expectation('This is the first hint'),
                $this->get_contains_num_parts_correct(2),
                $this->get_contains_standard_partiallycorrect_combined_feedback_expectation(),
                $this->get_contains_hidden_expectation(
                        $this->quba->get_field_prefix($this->slot) . 'sub0', $orderforchoice[1]),
                $this->get_contains_hidden_expectation(
                        $this->quba->get_field_prefix($this->slot) . 'sub1', '0'),
                $this->get_contains_hidden_expectation(
                        $this->quba->get_field_prefix($this->slot) . 'sub2', '0'),
                $this->get_contains_hidden_expectation(
                        $this->quba->get_field_prefix($this->slot) . 'sub3', $orderforchoice[1]));

        // Check that extract responses will return the reset data.
        $prefix = $this->quba->get_field_prefix($this->slot);
        $this->assertEquals(array('sub0' => 1),
                $this->quba->extract_responses($this->slot, array($prefix . 'sub0' => 1)));

        // Do try again.
        $this->process_submission(array('sub0' => $orderforchoice[1],
                'sub3' => $orderforchoice[1], '-tryagain' => 1));

        // Verify.
        $this->check_current_state(question_state::$todo);
        $this->check_current_mark(null);
        $this->check_current_output(
                $this->get_contains_select_expectation('sub0', $choices, $orderforchoice[1], true),
                $this->get_contains_select_expectation('sub1', $choices, null, true),
                $this->get_contains_select_expectation('sub2', $choices, null, true),
                $this->get_contains_select_expectation('sub3', $choices, $orderforchoice[1], true),
                $this->get_contains_submit_button_expectation(true),
                $this->get_does_not_contain_correctness_expectation(),
                $this->get_does_not_contain_feedback_expectation(),
                $this->get_tries_remaining_expectation(2),
                $this->get_no_hint_visible_expectation());

        // Submit the right answer.
        $this->process_submission(array('sub0' => $orderforchoice[1],
                'sub1' => $orderforchoice[2], 'sub2' => $orderforchoice[2],
                'sub3' => $orderforchoice[1], '-submit' => 1));

        // Verify.
        $this->check_current_state(question_state::$gradedright);
        $this->check_current_mark(10);
        $this->check_current_output(
                $this->get_contains_select_expectation('sub0', $choices, $orderforchoice[1], false),
                $this->get_contains_select_expectation('sub1', $choices, $orderforchoice[2], false),
                $this->get_contains_select_expectation('sub2', $choices, $orderforchoice[2], false),
                $this->get_contains_select_expectation('sub3', $choices, $orderforchoice[1], false),
                $this->get_contains_submit_button_expectation(false),
                $this->get_does_not_contain_try_again_button_expectation(),
                $this->get_contains_correct_expectation(),
                $this->get_contains_standard_correct_combined_feedback_expectation(),
                new question_no_pattern_expectation('/class="control\b[^"]*\bpartiallycorrect"/'));
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation NIMNotificationContentConfig
- (CGSize)contentSize:(CGFloat)cellWidth message:(NIMMessage *)message
{
    NIMNotificationObject *object = message.messageObject;
    NSAssert([object isKindOfClass:[NIMNotificationObject class]], @"message should be notification");

    CGSize contentSize = CGSizeZero;

    switch (object.notificationType) {
        case NIMNotificationTypeTeam:
        case NIMNotificationTypeSuperTeam:
        case NIMNotificationTypeChatroom:
        {
            CGFloat TeamNotificationMessageWidth  = cellWidth;
            UILabel *label = [[UILabel alloc] init];
            label.text  = [NIMKitUtil messageTipContent:message];
            label.font = [[NIMKit sharedKit].config setting:message].font;
            label.numberOfLines = 0;
            CGFloat padding =   [NIMKit sharedKit].config.maxNotificationTipPadding;
            CGSize size = [label sizeThatFits:CGSizeMake(cellWidth - 2 * padding, CGFLOAT_MAX)];
            CGFloat cellPadding = 11.f;
            contentSize = CGSizeMake(TeamNotificationMessageWidth, size.height + 2 * cellPadding);
            break;
        }
        case NIMNotificationTypeNetCall:{
            M80AttributedLabel *label = [[M80AttributedLabel alloc] initWithFrame:CGRectZero];
            label.autoDetectLinks = NO;
            label.font = [[NIMKit sharedKit].config setting:message].font;
            NSString *text = [NIMKitUtil messageTipContent:message];
            [label nim_setText:text];

            CGFloat msgBubbleMaxWidth    = (cellWidth - 130);
            CGFloat bubbleLeftToContent  = 14;
            CGFloat contentRightToBubble = 14;
            CGFloat msgContentMaxWidth = (msgBubbleMaxWidth - contentRightToBubble - bubbleLeftToContent);
            contentSize = [label sizeThatFits:CGSizeMake(msgContentMaxWidth, CGFLOAT_MAX)];
            break;
        }
        default:
        {
            NIMUnsupportContentConfig *config = [[NIMUnsupportContentConfig alloc] init];
            contentSize = [config contentSize:cellWidth message:message];
            NSAssert(0, @"not supported notification type %zd",object.notificationType);
        }
            break;
    }
    return contentSize;
}

- (NSString *)cellContent:(NIMMessage *)message
{
    NIMNotificationObject *object = message.messageObject;
    NSAssert([object isKindOfClass:[NIMNotificationObject class]], @"message should be notification");

    switch (object.notificationType) {
        case NIMNotificationTypeTeam:
        case NIMNotificationTypeSuperTeam:
        case NIMNotificationTypeChatroom:
            return @"NIMSessionNotificationContentView";
        case NIMNotificationTypeNetCall:
            return @"NIMSessionNetChatNotifyContentView";
        case NIMNotificationTypeUnsupport:
            return @"NIMSessionUnknowContentView";
        default:
            break;
    }
}

- (UIEdgeInsets)contentViewInsets:(NIMMessage *)message
{
    return [[NIMKit sharedKit].config setting:message].contentInsets;
}

- (BOOL)enableBackgroundBubbleView:(NIMMessage *)message
{
    NIMNotificationObject *object = message.messageObject;
    NSAssert([object isKindOfClass:[NIMNotificationObject class]], @"message should be notification");

    switch (object.notificationType) {
        case NIMNotificationTypeTeam:
        case NIMNotificationTypeSuperTeam:
        case NIMNotificationTypeChatroom:
            return NO;
        case NIMNotificationTypeNetCall:
            return YES;
        case NIMNotificationTypeUnsupport:
            return NO;
        default:
            break;
    }
    return YES;
}

@end


text:
using ProgressMeter

push!(LOAD_PATH, @__DIR__)
using PCREO

function main()
    @assert isdir(ENV["PCREO_DATABASE_DIRECTORY"])
    for num_dir in lsdir(ENV["PCREO_DATABASE_DIRECTORY"]; join=true)
        println(num_dir)
        flush(stdout)
        @showprogress for entry_dir in lsdir(num_dir)
            for record_path in lsdir(num_dir, entry_dir; join=true)
                old = read(record_path, String)
                new = string(PCREORecord(record_path))
                if length(old) != length(new)
                    error(record_path)
                end
                for i = 1 : length(new)
                    if !(old[i] == new[i] ||
                         (old[i:i+3] == "-0.0" && new[i:i+3] == "+0.0"))
                        error(record_path)
                    end
                end
                write(record_path, new)
            end
        end
    end
end

main()


text:
from tests.isolated_testcase import IsolatedTestCase

class PitchForkTest(IsolatedTestCase):

    def test(self):
        self.assertCommand('!pitchfork @meet', 'being pitchforked')
        self.assertCommand('!pitchfork @meet down to hell', 'being pitchforked')
        self.assertCommand('!pitchfork meet to hell', 'being pitchforked')
        self.assertCommand('!pitchfork', 'Usage')


text:
export default class EventDispatcher {
  public listeners: any[];

  public on(event: string, fn: () => void) {
    this.validate(fn);
    this.init(event).push(fn);
  }

  public off(event: string, fn: () => void) {
    const pool = this.init(event);
    pool.splice(pool.indexOf(fn), 1);
  }

  public once(event: string, fn: () => void) {
    this.validate(fn);
    const wrapper = () => {
      this.off(event, wrapper);
      fn.apply(this, arguments);
    };
    this.on(event, wrapper);
  }

  public emit(event: string, ...args) {
    const pool = this.init(event).slice(0);
    for (const i in pool) pool[i].apply(this, [].slice.call(arguments, 1));
  }

  private validate(fn: () => void) {
    if (!(fn && fn instanceof Function))
      throw new Error(fn + ' is not a Function');
  }

  private init(event: string) {
    const tmp = this.listeners || (this.listeners = []);
    return tmp[event] || (tmp[event] = []);
  }
}


text:
============
= Assignment
============

Description
===========
Assigns a value to a variable(s).

Syntax
======
**A = B**

*A*
    Any valid object.
*B*
    Any valid object.

Return Value
============
According to coercion rules.

Time Complexity
============
#TODO

Remarks
=======
Assignment operation always works from right to left. The object that was referenced by the variable prior to the assignment is now dereferenced.

Example 1
====
>>> a = 10
>>> a = 5
>>> a
5

Multiple assignment also follows the right-to-left rule. Consider the following example:

Example 2
====
>>> a = b = c = 10
>>> a
10
>>> b
10
>>> c
10

First the integer 10 is assigned to the variable c, then the value of c (10) is assigned to b and b is assigned to a. After evaluating this expression all the variables are referencing the same object - integer 10.

Another case of assignment is a multi-variable assignment. Consider the following example:

Example 3
====
>>> a, b, c = 1, 2, 3  # <- this is a tuple
>>> a
1
>>> b
2
>>> c
3

Following right-to-left rule a tuple containing (1, 2, 3) is created, then it is iterated over and its consequent values are assigned to the comma separated list of variables on the left.

This syntax can be used to swap the values of two variables:

Example 4
====
>>> a = 0
>>> b = 1
>>> a, b = b, a
>>> a
1
>>> b
0

Another common use is when we want to assign new values based on existing values:

Example 5a
====
>>> a = 10
>>> b = 5
>>> a, b = a + b, a * b
>>> a
15
>>> b
50

this is different than:

Example 5b
====
>>> a = 10
>>> b = 5
>>> a = a + b
>>> b = a * b
>>> a
15
>>> b
75

See Also
========
#TODO


text:
package com.sixrr.stockmetrics.moduleCalculators;

import java.util.Set;

import com.intellij.openapi.module.Module;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.sixrr.metrics.utils.BucketedCount;
import com.sixrr.metrics.utils.ClassUtils;

abstract class ElementCountModuleCalculator extends ModuleCalculator
{

	protected final BucketedCount<Module> elementsCountPerModule = new BucketedCount<Module>();

	@Override
	public void endMetricsRun()
	{
		final Set<Module> modules = elementsCountPerModule.getBuckets();
		for(final Module module : modules)
		{
			final int numCommentLines = elementsCountPerModule.getBucketValue(module);

			postMetric(module, numCommentLines);
		}
	}

	protected void incrementElementCount(PsiElement element, int count)
	{
		final PsiFile file = PsiTreeUtil.getParentOfType(element, PsiFile.class, false);
		final Module module = ClassUtils.calculateModule(file);
		if(module == null)
		{
			return;
		}
		elementsCountPerModule.incrementBucketValue(module, count);
	}
}


text:
<form class = "form-horizontal" [formGroup]="myForm" novalidate (ngSubmit)="save(myForm._value)">
  <fieldset>
    <legend>Agregar Asiento</legend>

      Fecha
      <input class = "form-control" type="date" formControlName="fecha">

        Fecha es requerida.

          Concepto Debe {{i + 1}}
          <button type="button" class = "btn btn-success pull-right" *ngIf="myForm.controls.debe.controls.length > 1" (click)="removeConceptoDebe(i)">Eliminar concepto</button>

            Concepto
            <select class = "form-control" formControlName="concepto">
              <option>Caja</option>
              <option>Proveedores</option>
              <option>Mercaderia</option>
            </select>

              Concepto es requerido

            Monto
            <input class = "form-control" type="text" formControlName="monto">

              Monto es requerido

    <button type="button" class = "btn btn-success pull-right" (click) = "addConceptoDebe()">Agregar Debe</button>

          Concepto Haber {{i + 1}}
          <button type="button" class = "btn btn-success pull-right" *ngIf="myForm.controls.haber.controls.length > 1" (click)="removeConceptoHaber(i)">Eliminar concepto</button>

            Concepto
            <select class = "form-control" formControlName="concepto">
              <option>Caja</option>
              <option>Proveedores</option>
              <option>Mercaderia</option>
            </select>

              Concepto es requerido

            Monto
            <input class = "form-control" type="text" formControlName="monto">

              Monto es requerido

    <button type = "button" class = "btn btn-success pull-right" (click) = "addConceptoHaber()"> Agregar Haber</button>
  </fieldset>

  <button class = "btn btn-primary pull-left" type="submit" [disabled]="!myForm.valid">Agregar Asiento</button>
</form>


text:
/*
 *	Nama File 	:	Tombol.cpp
 *	Deskripsi	: 	Implementasi dari library Tombol.h
 */

#include "Tombol.h"

Tombol::Tombol(const uint8_t _pinTombol)
{
	pinTombol = _pinTombol;
	pinMode(pinTombol, INPUT_PULLUP);
	debounceTerakhir = 0;
	stateTerakhir = HIGH;
}

void Tombol::bacaState(boolean &stateIn, boolean &stateOut)
{
	boolean stateTerbaca = digitalRead(pinTombol);
	if (stateTerbaca != stateTerakhir)
	{
		debounceTerakhir = millis();
	}
	if (millis() - debounceTerakhir >= DEBOUNCING_TIME)
	{
		if (stateTerbaca != stateIn)
		{
			stateIn = stateTerbaca;
			if (stateIn == LOW)
			{
				stateOut = !(stateOut);
			}
		}
	}
	stateTerakhir = stateTerbaca;
}


text:
Previous
1
2
3
…
6
Next


text:
import { registerNodeProcessor } from '../node.js';

registerNodeProcessor({

  name: 'UpdateExpression',

  parseExpression(node) {
    throw new Error('Not Implemented');
  },

  scan(node) {
    throw new Error('Not Implemented');
  },

  declare(node) {
    throw new Error('Not Implemented');
  }

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>tdc.com.br</groupId>
    <artifactId>tdc-2015-spring-boot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.M5</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 05-working-with-views -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mustache</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
        </dependency>

        <!-- 07-persistence-dependencies -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.3.0.M5</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
using inSyca.foundation.framework;
using inSyca.foundation.framework.diagnostics;
using System;
using System.Collections.Generic;
using System.Data;
using System.Management;
using System.Net;

namespace inSyca.foundation.integration.biztalk.diagnostics
{
    public static class Monitoring
    {
        static public event EventHandler<MonitoringEventArgs> MonitoringEvent;
        static public event EventHandler<MonitoringEventArgs> EventEntryEvent;

        static private List<ManagementEventWatcher> hostInstanceWatcherList;
        static private List<ManagementEventWatcher> serviceInstanceSuspendedWatcherList;
        static private List<ManagementEventWatcher> receiveLocationWatcherList;
        static private List<ManagementEventWatcher> sendPortWatcherList;

        static private MonitorBizTalk monitorBizTalk;

        public static void disposeWatcher()
        {
            Log.Debug("disposeWatcher()");

            if (hostInstanceWatcherList != null)
            {
                foreach (ManagementEventWatcher hostInstanceWatcher in hostInstanceWatcherList)
                {
                    hostInstanceWatcher.Stop();
                    hostInstanceWatcher.Dispose();
                }
                hostInstanceWatcherList.Clear();
            }

            if (serviceInstanceSuspendedWatcherList != null)
            {
                foreach (ManagementEventWatcher serviceInstanceSuspendedWatcher in serviceInstanceSuspendedWatcherList)
                {
                    serviceInstanceSuspendedWatcher.Stop();
                    serviceInstanceSuspendedWatcher.Dispose();
                }
                serviceInstanceSuspendedWatcherList.Clear();
            }

            if (receiveLocationWatcherList != null)
            {
                foreach (ManagementEventWatcher receiveLocationWatcher in receiveLocationWatcherList)
                {
                    receiveLocationWatcher.Stop();
                    receiveLocationWatcher.Dispose();
                }
                receiveLocationWatcherList.Clear();
            }

            if (sendPortWatcherList != null)
            {
                foreach (ManagementEventWatcher sendPortWatcher in sendPortWatcherList)
                {
                    sendPortWatcher.Stop();
                    sendPortWatcher.Dispose();
                }
                sendPortWatcherList.Clear();
            }
        }

        public static void invokeWatcher()
        {
            Log.Debug("invokeWatcher()");

            monitorBizTalk = new MonitorBizTalk();
            monitorBizTalk.MonitoringEvent += new EventHandler<MonitoringEventArgs>(monitorBizTalk_MonitoringEvent);

            string[] serverCollection = Configuration.GetTextAppSettingsValue("LogServerNames").Split(';');

            if (serverCollection.GetLength(0) == 0)
                return;

            hostInstanceWatcherList = new List<ManagementEventWatcher>();
            serviceInstanceSuspendedWatcherList = new List<ManagementEventWatcher>();
            receiveLocationWatcherList = new List<ManagementEventWatcher>();
            sendPortWatcherList = new List<ManagementEventWatcher>();

            foreach (string server in serverCollection)
            {
               Log.InfoFormat("Setup watcher for server: {0}", server );

                if (MonitoringEvent != null)
                    MonitoringEvent(null, new MonitoringEventArgs("Start WMI for Server: " + server));

                if (string.IsNullOrEmpty(server))
                    return;

                ManagementPath managementPathBizTalk = new ManagementPath(string.Format(@"\\{0}\root\MicrosoftBizTalkServer", server));
                ConnectionOptions managementConnectionOptions = new ConnectionOptions();

                managementConnectionOptions.Authentication = AuthenticationLevel.Packet;
                managementConnectionOptions.Timeout = new TimeSpan(0, 0, 5, 0);
                managementConnectionOptions.EnablePrivileges = true;

                if (server.ToUpper() != Dns.GetHostName().ToUpper() && server.ToUpper() != "LOCALHOST")
                {
                    Log.InfoFormat("Applied user credentials for remote host: {0}", server );

                    //managementConnectionOptions.Username = "USERNAME";
                    //managementConnectionOptions.Password = "PASSWORD";
                }

                ManagementEventWatcher hostInstanceWatcher = null;

                try
                {
                    WqlEventQuery hostInstanceQuery = new WqlEventQuery("__InstanceModificationEvent", new TimeSpan(0, 0, 10), "TargetInstance ISA 'MSBTS_HostInstance'");
                    hostInstanceWatcher = new ManagementEventWatcher(new ManagementScope(managementPathBizTalk, managementConnectionOptions), hostInstanceQuery);
                    hostInstanceWatcher.EventArrived += new EventArrivedEventHandler(hostInstanceEventHandler);
                    hostInstanceWatcher.Start();
                    hostInstanceWatcherList.Add(hostInstanceWatcher);

                    if (MonitoringEvent != null)
                        MonitoringEvent(null, new MonitoringEventArgs("hostInstanceWatcher started. Query:" + hostInstanceQuery.QueryString));

                    Log.InfoFormat("hostInstanceWatcher started. Query: {0}", hostInstanceQuery.QueryString );
                }
                catch (Exception ex)
                {
                    if (hostInstanceWatcher != null)
                    {
                        hostInstanceWatcher.Stop();
                        hostInstanceWatcher.Dispose();
                    }

                    if (MonitoringEvent != null)
                        MonitoringEvent(null, new MonitoringEventArgs("Error (hostInstanceWatcher): " + ex.Message));

                    Log.Error(new LogEntry(System.Reflection.MethodBase.GetCurrentMethod(), null, "Error (hostInstanceWatcher): {0}", new object[] { ex.Message }));
                }

                ManagementEventWatcher serviceInstanceSuspendedWatcher = null;

                try
                {
                    WqlEventQuery serviceInstanceSuspendedQuery = new WqlEventQuery(String.Format(@"SELECT * FROM MSBTS_ServiceInstanceSuspendedEvent", "5"));
                    serviceInstanceSuspendedWatcher = new ManagementEventWatcher(new ManagementScope(managementPathBizTalk, managementConnectionOptions), serviceInstanceSuspendedQuery);
                    serviceInstanceSuspendedWatcher.EventArrived += new EventArrivedEventHandler(suspendedMessageEventHandler);
                    serviceInstanceSuspendedWatcher.Start();
                    serviceInstanceSuspendedWatcherList.Add(serviceInstanceSuspendedWatcher);

                    if (MonitoringEvent != null)
                        MonitoringEvent(null, new MonitoringEventArgs("serviceInstanceSuspendedWatcher started. Query:" + serviceInstanceSuspendedQuery.QueryString));

                    Log.InfoFormat("serviceInstanceSuspendedWatcher started. Query: {0}", serviceInstanceSuspendedQuery.QueryString );
                }
                catch (Exception ex)
                {
                    if (serviceInstanceSuspendedWatcher != null)
                    {
                        serviceInstanceSuspendedWatcher.Stop();
                        serviceInstanceSuspendedWatcher.Dispose();
                    }

                    if (MonitoringEvent != null)
                        MonitoringEvent(null, new MonitoringEventArgs("Error (serviceInstanceSuspendedWatcher): " + ex.Message));

                    Log.Error(new LogEntry(System.Reflection.MethodBase.GetCurrentMethod(), null, "Error (serviceInstanceSuspendedWatcher): {0}", new object[] { ex.Message }));
                }

                ManagementEventWatcher receiveLocationWatcher = null;

                try
                {
                    WqlEventQuery receiveLocationQuery = new WqlEventQuery("__InstanceModificationEvent", new TimeSpan(0, 0, 10), "TargetInstance ISA 'MSBTS_ReceiveLocation'");
                    receiveLocationWatcher = new ManagementEventWatcher(new ManagementScope(managementPathBizTalk, managementConnectionOptions), receiveLocationQuery);
                    receiveLocationWatcher.EventArrived += new EventArrivedEventHandler(receiveLocationEventHandler);
                    receiveLocationWatcher.Start();
                    receiveLocationWatcherList.Add(receiveLocationWatcher);

                    if (MonitoringEvent != null)
                        MonitoringEvent(null, new MonitoringEventArgs("receiveLocationWatcher started. Query:" + receiveLocationQuery.QueryString));

                    Log.InfoFormat("receiveLocationWatcher started. Query: {0}",  receiveLocationQuery.QueryString );
                }
                catch (Exception ex)
                {
                    if (receiveLocationWatcher != null)
                    {
                        receiveLocationWatcher.Stop();
                        receiveLocationWatcher.Dispose();
                    }

                    if (MonitoringEvent != null)
                        MonitoringEvent(null, new MonitoringEventArgs("Error (receiveLocationWatcher): " + ex.Message));

                    Log.Error(new LogEntry(System.Reflection.MethodBase.GetCurrentMethod(), null, "Error (receiveLocationWatcher): {0}", new object[] { ex.Message }));
                }

                ManagementEventWatcher sendPortWatcher = null;

                try
                {
                    WqlEventQuery sendPortQuery = new WqlEventQuery("__InstanceModificationEvent", new TimeSpan(0, 0, 10), "TargetInstance ISA 'MSBTS_SendPort'");
                    sendPortWatcher = new ManagementEventWatcher(new ManagementScope(managementPathBizTalk, managementConnectionOptions), sendPortQuery);
                    sendPortWatcher.EventArrived += new EventArrivedEventHandler(sendPortEventHandler);
                    sendPortWatcher.Start();
                    sendPortWatcherList.Add(sendPortWatcher);

                    if (MonitoringEvent != null)
                        MonitoringEvent(null, new MonitoringEventArgs("sendPortWatcher started. Query:" + sendPortQuery.QueryString));

                    Log.InfoFormat("sendPortWatcher started. Query: {0}", sendPortQuery.QueryString );
                }
                catch (Exception ex)
                {
                    if (sendPortWatcher != null)
                    {
                        sendPortWatcher.Stop();
                        sendPortWatcher.Dispose();
                    }

                    if (MonitoringEvent != null)
                        MonitoringEvent(null, new MonitoringEventArgs("Error (sendPortWatcher): " + ex.Message));

                    Log.Error(new LogEntry(System.Reflection.MethodBase.GetCurrentMethod(), null, "Error (sendPortWatcher): {0}", new object[] { ex.Message }));
                }

               Log.DebugFormat("Setup done - Server{0}", server );
            }
        }

        static public void hostInstanceEventHandler(object sender, EventArrivedEventArgs e)
        {
            Log.DebugFormat("hostInstanceEventHandler(object sender {0}, EventArrivedEventArgs e {1})", sender, e);

            DataRow eventEntryRow;
            monitorBizTalk.SetEvent(e, BizTalkEventType.hostInstanceEvent, out eventEntryRow);
            EventEntryEvent(null, new MonitoringEventArgs(eventEntryRow));
        }

        static public void receiveLocationEventHandler(object sender, EventArrivedEventArgs e)
        {
            Log.DebugFormat("receiveLocationEventHandler(object sender {0}, EventArrivedEventArgs e {1})", sender, e);

            DataRow eventEntryRow;
            monitorBizTalk.SetEvent(e, BizTalkEventType.receiveLocationEvent, out eventEntryRow);
            EventEntryEvent(null, new MonitoringEventArgs(eventEntryRow));
        }

        static public void sendPortEventHandler(object sender, EventArrivedEventArgs e)
        {
            Log.DebugFormat("sendPortEventHandler(object sender {0}, EventArrivedEventArgs e {1})", sender, e);

            DataRow eventEntryRow;
            monitorBizTalk.SetEvent(e, BizTalkEventType.sendPortEvent, out eventEntryRow);
            EventEntryEvent(null, new MonitoringEventArgs(eventEntryRow));
        }

        static public void suspendedMessageEventHandler(object sender, EventArrivedEventArgs e)
        {
            Log.DebugFormat("suspendedMessageEventHandler(object sender {0}, EventArrivedEventArgs e {1})", sender, e);

            DataRow eventEntryRow;
            monitorBizTalk.SetEvent(e, BizTalkEventType.suspendedMessageEvent, out eventEntryRow);
            EventEntryEvent(null, new MonitoringEventArgs(eventEntryRow));
        }

        static void monitorBizTalk_MonitoringEvent(object sender, MonitoringEventArgs e)
        {
            MonitoringEvent(null, e);
        }
    }
}


text:
/****** Object:  StoredProcedure [dbo].[app_PatronPoints_Delete]    Script Date: 01/05/2015 14:43:23 ******/
--Create the Delete Proc
CREATE PROCEDURE [dbo].[app_PatronPoints_Delete] @PPID INT
AS
DELETE
FROM [PatronPoints]
WHERE PPID = @PPID


text:
extern crate byteorder;
extern crate flate2;
extern crate test;

use std::collections::HashMap;
use std::error::FromError;
use std::fmt;
use std::io;
use std::io::ErrorKind::InvalidInput;
use std::iter::AdditiveIterator;
use std::ops::Index;
use std::string;

use byteorder::{ByteOrder, BigEndian, WriteBytesExt, ReadBytesExt};

use flate2::Compression;
use flate2::read::{GzDecoder, ZlibDecoder};
use flate2::write::{GzEncoder, ZlibEncoder};

/// Errors that may be encountered when constructing, parsing, or encoding
/// `NbtValue` and `NbtBlob` objects.
///
/// `NbtError`s can be seamlessly converted to more general `io::Error` objects
/// using the `FromError` trait.
#[derive(Clone, Debug, PartialEq)]
pub enum NbtError {
    /// Wraps errors emitted by methods during I/O operations.
    IoError(io::Error),
    /// An error for when an unknown type ID is encountered in decoding NBT
    /// binary representations. Includes the ID in question.
    InvalidTypeId(u8),
    /// An error emitted when trying to create `NbtBlob`s with incorrect lists.
    HeterogeneousList,
    /// An error for when NBT binary representations do not begin with an
    /// `NbtValue::Compound`.
    NoRootCompound,
    /// An error for when NBT binary representations contain invalid UTF-8
    /// strings.
    InvalidUtf8,
    /// An error for when NBT binary representations are missing end tags,
    /// contain fewer bytes than advertised, or are otherwise incomplete.
    IncompleteNbtValue,
}

impl FromError<io::Error> for NbtError {
    fn from_error(e: io::Error) -> NbtError {
        NbtError::IoError(e)
    }
}

impl FromError<string::FromUtf8Error> for NbtError {
    fn from_error(_: string::FromUtf8Error) -> NbtError {
        NbtError::InvalidUtf8
    }
}

impl FromError<byteorder::Error> for NbtError {
    fn from_error(err: byteorder::Error) -> NbtError {
        match err {
            // Promote byteorder's I/O errors to NbtError's I/O errors.
            byteorder::Error::Io(e) => NbtError::IoError(e),
            // Anything else is really an incomplete value.
            byteorder::Error::UnexpectedEOF => NbtError::IncompleteNbtValue
        }
    }
}

impl FromError<NbtError> for io::Error {
    fn from_error(e: NbtError) -> io::Error {
        match e {
            NbtError::IoError(e) => e,
            NbtError::InvalidTypeId(id) =>
                io::Error::new(InvalidInput, "invalid NbtValue id", Some(format!("id = {}", id))),
            NbtError::HeterogeneousList =>
                io::Error::new(InvalidInput, "List values must be homogeneous", None),
            NbtError::NoRootCompound =>
                io::Error::new(InvalidInput, "root value must be a Compound (0x0a)", None),
            NbtError::InvalidUtf8 =>
                io::Error::new(InvalidInput, "string is not UTF-8", None),
            NbtError::IncompleteNbtValue =>
                io::Error::new(InvalidInput, "data does not represent a complete NbtValue", None),
        }
    }
}

/// A value which can be represented in the Named Binary Tag (NBT) file format.
#[derive(Clone, Debug, PartialEq)]
pub enum NbtValue {
    Byte(i8),
    Short(i16),
    Int(i32),
    Long(i64),
    Float(f32),
    Double(f64),
    ByteArray(Vec<i8>),
    String(String),
    List(Vec<NbtValue>),
    Compound(HashMap<String, NbtValue>),
    IntArray(Vec<i32>),
}

impl NbtValue {
    /// The type ID of this `NbtValue`, which is a single byte in the range
    /// `0x01` to `0x0b`.
    pub fn id(&self) -> u8 {
        match *self {
            NbtValue::Byte(_)      => 0x01,
            NbtValue::Short(_)     => 0x02,
            NbtValue::Int(_)       => 0x03,
            NbtValue::Long(_)      => 0x04,
            NbtValue::Float(_)     => 0x05,
            NbtValue::Double(_)    => 0x06,
            NbtValue::ByteArray(_) => 0x07,
            NbtValue::String(_)    => 0x08,
            NbtValue::List(_)      => 0x09,
            NbtValue::Compound(_)  => 0x0a,
            NbtValue::IntArray(_)  => 0x0b
        }
    }

    /// A string representation of this tag.
    fn to_string(&self) -> &str {
        match *self {
            NbtValue::Byte(_)      => "TAG_Byte",
            NbtValue::Short(_)     => "TAG_Short",
            NbtValue::Int(_)       => "TAG_Int",
            NbtValue::Long(_)      => "TAG_Long",
            NbtValue::Float(_)     => "TAG_Float",
            NbtValue::Double(_)    => "TAG_Double",
            NbtValue::ByteArray(_) => "TAG_ByteArray",
            NbtValue::String(_)    => "TAG_String",
            NbtValue::List(_)      => "TAG_List",
            NbtValue::Compound(_)  => "TAG_Compound",
            NbtValue::IntArray(_)  => "TAG_IntArray"
        }
    }

    /// The length of the payload of this `NbtValue`, in bytes.
    pub fn len(&self) -> usize {
        match *self {
            NbtValue::Byte(_)            => 1,
            NbtValue::Short(_)           => 2,
            NbtValue::Int(_)             => 4,
            NbtValue::Long(_)            => 8,
            NbtValue::Float(_)           => 4,
            NbtValue::Double(_)          => 8,
            NbtValue::ByteArray(ref val) => 4 + val.len(), // size + bytes
            NbtValue::String(ref val)    => 2 + val.len(), // size + bytes
            NbtValue::List(ref vals)     => {
                // tag + size + payload for each element
                5 + vals.iter().map(|x| x.len()).sum()
            },
            NbtValue::Compound(ref vals) => {
                vals.iter().map(|(name, nbt)| {
                    // tag + name + payload for each entry
                    3 + name.len() + nbt.len()
                }).sum() + 1 // + u8 for the Tag_End
            },
            NbtValue::IntArray(ref val)  => 4 + 4 * val.len(),
        }
    }

    /// Writes the header (that is, the value's type ID and optionally a title)
    /// of this `NbtValue` to an `io::Write` destination.
    pub fn write_header(&self, mut dst: &mut io::Write, title: &String) -> Result<(), NbtError> {
        try!(dst.write_u8(self.id()));
        try!(dst.write_u16::<BigEndian>(title.len() as u16));
        try!(dst.write_all(title.as_slice().as_bytes()));
        Ok(())
    }

    /// Writes the payload of this `NbtValue` to an `io::Write` destination.
    pub fn write(&self, mut dst: &mut io::Write) -> Result<(), NbtError> {
        match *self {
            NbtValue::Byte(val)   => try!(dst.write_i8(val)),
            NbtValue::Short(val)  => try!(dst.write_i16::<BigEndian>(val)),
            NbtValue::Int(val)    => try!(dst.write_i32::<BigEndian>(val)),
            NbtValue::Long(val)   => try!(dst.write_i64::<BigEndian>(val)),
            NbtValue::Float(val)  => try!(dst.write_f32::<BigEndian>(val)),
            NbtValue::Double(val) => try!(dst.write_f64::<BigEndian>(val)),
            NbtValue::ByteArray(ref vals) => {
                try!(dst.write_i32::<BigEndian>(vals.len() as i32));
                for &byte in vals {
                    try!(dst.write_i8(byte));
                }
            },
            NbtValue::String(ref val) => {
                try!(dst.write_u16::<BigEndian>(val.len() as u16));
                try!(dst.write_all(val.as_slice().as_bytes()));
            },
            NbtValue::List(ref vals) => {
                // This is a bit of a trick: if the list is empty, don't bother
                // checking its type.
                if vals.len() == 0 {
                    try!(dst.write_u8(1));
                    try!(dst.write_i32::<BigEndian>(0));
                } else {
                    // Otherwise, use the first element of the list.
                    let first_id = vals[0].id();
                    try!(dst.write_u8(first_id));
                    try!(dst.write_i32::<BigEndian>(vals.len() as i32));
                    for nbt in vals {
                        // Ensure that all of the tags are the same type.
                        if nbt.id() != first_id {
                            return Err(NbtError::HeterogeneousList);
                        }
                        try!(nbt.write(dst));
                    }
                }
            },
            NbtValue::Compound(ref vals)  => {
                for (name, ref nbt) in vals {
                    // Write the header for the tag.
                    try!(nbt.write_header(dst, &name));
                    try!(nbt.write(dst));
                }
                // Write the marker for the end of the Compound.
                try!(dst.write_u8(0x00))
            }
            NbtValue::IntArray(ref vals) => {
                try!(dst.write_i32::<BigEndian>(vals.len() as i32));
                for &nbt in vals {
                    try!(dst.write_i32::<BigEndian>(nbt));
                }
            },
        };
        Ok(())
    }

    /// Reads any valid `NbtValue` header (that is, a type ID and a title of
    /// arbitrary UTF-8 bytes) from an `io::Read` source.
    pub fn read_header(mut src: &mut io::Read) -> Result<(u8, String), NbtError> {
        let id = try!(src.read_u8());
        if id == 0x00 { return Ok((0x00, "".to_string())); }
        // Extract the name.
        let name_len = try!(src.read_u16::<BigEndian>());
        let name = if name_len != 0 {
            try!(read_utf8(src, name_len as usize))
        } else {
            "".to_string()
        };
        Ok((id, name))
    }

    /// Reads the payload of an `NbtValue` with a given type ID from an
    /// `io::Read` source.
    pub fn from_reader(id: u8, mut src: &mut io::Read) -> Result<NbtValue, NbtError> {
        match id {
            0x01 => Ok(NbtValue::Byte(try!(src.read_i8()))),
            0x02 => Ok(NbtValue::Short(try!(src.read_i16::<BigEndian>()))),
            0x03 => Ok(NbtValue::Int(try!(src.read_i32::<BigEndian>()))),
            0x04 => Ok(NbtValue::Long(try!(src.read_i64::<BigEndian>()))),
            0x05 => Ok(NbtValue::Float(try!(src.read_f32::<BigEndian>()))),
            0x06 => Ok(NbtValue::Double(try!(src.read_f64::<BigEndian>()))),
            0x07 => { // ByteArray
                let len = try!(src.read_i32::<BigEndian>()) as usize;
                let mut buf = Vec::with_capacity(len);
                for _ in 0..len {
                    buf.push(try!(src.read_i8()));
                }
                Ok(NbtValue::ByteArray(buf))
            },
            0x08 => { // String
                let len = try!(src.read_u16::<BigEndian>()) as usize;
                Ok(NbtValue::String(try!(read_utf8(src, len as usize))))
            },
            0x09 => { // List
                let id = try!(src.read_u8());
                let len = try!(src.read_i32::<BigEndian>()) as usize;
                let mut buf = Vec::with_capacity(len);
                for _ in 0..len {
                    buf.push(try!(NbtValue::from_reader(id, src)));
                }
                Ok(NbtValue::List(buf))
            },
            0x0a => { // Compound
                let mut buf = HashMap::new();
                loop {
                    let (id, name) = try!(NbtValue::read_header(src));
                    if id == 0x00 { break; }
                    let tag = try!(NbtValue::from_reader(id, src));
                    buf.insert(name, tag);
                }
                Ok(NbtValue::Compound(buf))
            },
            0x0b => { // IntArray
                let len = try!(src.read_i32::<BigEndian>()) as usize;
                let mut buf = Vec::with_capacity(len);
                for _ in 0..len {
                    buf.push(try!(src.read_i32::<BigEndian>()));
                }
                Ok(NbtValue::IntArray(buf))
            },
            e => Err(NbtError::InvalidTypeId(e))
        }
    }
}

impl fmt::Display for NbtValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            NbtValue::Byte(v)   => write!(f, "{}", v),
            NbtValue::Short(v)  => write!(f, "{}", v),
            NbtValue::Int(v)    => write!(f, "{}", v),
            NbtValue::Long(v)   => write!(f, "{}", v),
            NbtValue::Float(v)  => write!(f, "{}", v),
            NbtValue::Double(v) => write!(f, "{}", v),
            NbtValue::ByteArray(ref v) => write!(f, "{:?}", v),
            NbtValue::String(ref v) => write!(f, "{}", v),
            NbtValue::List(ref v) => {
                if v.len() == 0 {
                    write!(f, "zero entries")
                } else {
                    try!(write!(f, "{} entries of type {}\n{{\n", v.len(), v[0].to_string()));
                    for tag in v {
                        try!(write!(f, "{}(None): {}\n", tag.to_string(), tag));
                    }
                    try!(write!(f, "}}"));
                    Ok(())
                }
            }
            NbtValue::Compound(ref v) => {
                try!(write!(f, "{} entry(ies)\n{{\n", v.len()));
                for (name, tag) in v {
                    try!(write!(f, "{}(\"{}\"): {}\n", tag.to_string(), name, tag));
                }
                try!(write!(f, "}}"));
                Ok(())
            }
            NbtValue::IntArray(ref v) => write!(f, "{:?}", v)
        }
    }
}

/// An object in the Named Binary Tag (NBT) file format.
///
/// This is essentially a map of names to `NbtValue`s, with an optional top-
/// level name of its own. It can be created in a similar way to a `HashMap`,
/// or read from an `io::Read` source, and its binary representation can be
/// written to an `io::Write` destination.
///
/// These read and write methods support both uncompressed and compressed
/// (through Gzip or zlib compression) methods.
///
/// ```rust
/// use nbt::{NbtBlob, NbtError, NbtValue};
///
/// // Create a `NbtBlob` from key/value pairs.
/// let mut nbt = NbtBlob::new("".to_string());
/// nbt.insert("name".to_string(), NbtValue::String("Herobrine".to_string()));
/// nbt.insert("health".to_string(), NbtValue::Byte(100));
/// nbt.insert("food".to_string(), NbtValue::Float(20.0));
///
/// // Write a compressed binary representation to a byte array.
/// let mut dst = Vec::new();
/// nbt.write_zlib(&mut dst);
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct NbtBlob {
    title: String,
    content: NbtValue
}

impl NbtBlob {
    /// Create a new NBT file format representation with the given name.
    pub fn new(title: String) -> NbtBlob {
        let map: HashMap<String, NbtValue> = HashMap::new();
        NbtBlob { title: title, content: NbtValue::Compound(map) }
    }

    /// Extracts an `NbtBlob` object from an `io::Read` source.
    pub fn from_reader(mut src: &mut io::Read) -> Result<NbtBlob, NbtError> {
        let header = try!(NbtValue::read_header(src));
        // Although it would be possible to read NBT format files composed of
        // arbitrary objects using the current API, by convention all files
        // have a top-level Compound.
        if header.0 != 0x0a {
            return Err(NbtError::NoRootCompound);
        }
        let content = try!(NbtValue::from_reader(header.0, src));
        Ok(NbtBlob { title: header.1, content: content })
    }

    /// Extracts an `NbtBlob` object from an `io::Read` source that is
    /// compressed using the Gzip format.
    pub fn from_gzip(src: &mut io::Read) -> Result<NbtBlob, NbtError> {
        // Reads the gzip header, and fails if it is incorrect.
        let mut data = try!(GzDecoder::new(src));
        NbtBlob::from_reader(&mut data)
    }

    /// Extracts an `NbtBlob` object from an `io::Read` source that is
    /// compressed using the zlib format.
    pub fn from_zlib(src: &mut io::Read) -> Result<NbtBlob, NbtError> {
        NbtBlob::from_reader(&mut ZlibDecoder::new(src))
    }

    /// Writes the binary representation of this `NbtBlob` to an `io::Write`
    /// destination.
    pub fn write(&self, dst: &mut io::Write) -> Result<(), NbtError> {
        try!(self.content.write_header(dst, &self.title));
        self.content.write(dst)
    }

    /// Writes the binary representation of this `NbtBlob`, compressed using
    /// the Gzip format, to an `io::Write` destination.
    pub fn write_gzip(&self, dst: &mut io::Write) -> Result<(), NbtError> {
        self.write(&mut GzEncoder::new(dst, Compression::Default))
    }

    /// Writes the binary representation of this `NbtBlob`, compressed using
    /// the Zlib format, to an `io::Write` dst.
    pub fn write_zlib(&self, dst: &mut io::Write) -> Result<(), NbtError> {
        self.write(&mut ZlibEncoder::new(dst, Compression::Default))
    }

    /// Insert an `NbtValue` with a given name into this `NbtBlob` object. This
    /// method is just a thin wrapper around the underlying `HashMap` method of
    /// the same name.
    ///
    /// This method will also return an error if a `NbtValue::List` with
    /// heterogeneous elements is passed in, because this is illegal in the NBT
    /// file format.
    pub fn insert(&mut self, name: String, value: NbtValue) -> Result<(), NbtError> {
        // The follow prevents `List`s with heterogeneous tags from being
        // inserted into the file. It would be nicer to return an error, but
        // this would depart from the `HashMap` API for `insert`.
        if let NbtValue::List(ref vals) = value {
            if vals.len() != 0 {
                let first_id = vals[0].id();
                for nbt in vals {
                    if nbt.id() != first_id {
                        return Err(NbtError::HeterogeneousList)
                    }
                }
            }
        }
        if let NbtValue::Compound(ref mut v) = self.content {
            v.insert(name, value);
        } else {
            unreachable!();
        }
        Ok(())
    }

    /// The uncompressed length of this `NbtBlob`, in bytes.
    pub fn len(&self) -> usize {
        // tag + name + content
        1 + 2 + self.title.as_slice().len() + self.content.len()
    }
}

impl<'a> Index<&'a str> for NbtBlob {
    type Output = NbtValue;

    fn index<'b>(&'b self, s: &'a str) -> &'b NbtValue {
        match self.content {
            NbtValue::Compound(ref v) => v.get(s).unwrap(),
            _ => unreachable!()
        }
    }
}

impl fmt::Display for NbtBlob {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(f, "TAG_Compound(\"{}\"): {}", self.title, self.content)
    }
}

/// Returns a `Vec<u8>` containing the next `len` bytes in the reader.
///
/// Adapted from `byteorder::read_full`.
fn read_utf8(mut src: &mut io::Read, len: usize) -> Result<String, NbtError> {
    let mut bytes = vec![0; len];
    let mut n_read = 0usize;
    while n_read < bytes.len() {
        match try!(src.read(&mut bytes[n_read..])) {
            0 => return Err(NbtError::IncompleteNbtValue),
            n => n_read += n
        }
    }
    Ok(try!(String::from_utf8(bytes)))
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::collections::HashMap;
    use std::io;
    use std::fs::File;

    use test::Bencher;

    #[test]
    fn nbt_nonempty() {
        let mut nbt = NbtBlob::new("".to_string());
        nbt.insert("name".to_string(), NbtValue::String("Herobrine".to_string())).unwrap();
        nbt.insert("health".to_string(), NbtValue::Byte(100)).unwrap();
        nbt.insert("food".to_string(), NbtValue::Float(20.0)).unwrap();
        nbt.insert("emeralds".to_string(), NbtValue::Short(12345)).unwrap();
        nbt.insert("timestamp".to_string(), NbtValue::Int(1424778774)).unwrap();

        let bytes = vec![
            0x0a,
                0x00, 0x00,
                0x08,
                    0x00, 0x04,
                    0x6e, 0x61, 0x6d, 0x65,
                    0x00, 0x09,
                    0x48, 0x65, 0x72, 0x6f, 0x62, 0x72, 0x69, 0x6e, 0x65,
                0x01,
                    0x00, 0x06,
                    0x68, 0x65, 0x61, 0x6c, 0x74, 0x68,
                    0x64,
                0x05,
                    0x00, 0x04,
                    0x66, 0x6f, 0x6f, 0x64,
                    0x41, 0xa0, 0x00, 0x00,
                0x02,
                    0x00, 0x08,
                    0x65, 0x6d, 0x65, 0x72, 0x61, 0x6c, 0x64, 0x73,
                    0x30, 0x39,
                0x03,
                    0x00, 0x09,
                    0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70,
                    0x54, 0xec, 0x66, 0x16,
            0x00
        ];

        // Test correct length.
        assert_eq!(bytes.len(), nbt.len());

        // We can only test if the decoded bytes match, since the HashMap does
        // not guarantee order (and so encoding is likely to be different, but
        // still correct).
        let mut src = io::Cursor::new(bytes);
        let file = NbtBlob::from_reader(&mut src).unwrap();
        assert_eq!(&file, &nbt);
    }

    #[test]
    fn nbt_empty_nbtfile() {
        let nbt = NbtBlob::new("".to_string());

        let bytes = vec![
            0x0a,
                0x00, 0x00,
            0x00
        ];

        // Test correct length.
        assert_eq!(bytes.len(), nbt.len());

        // Test encoding.
        let mut dst = Vec::new();
        nbt.write(&mut dst).unwrap();
        assert_eq!(&dst, &bytes);

        // Test decoding.
        let mut src = io::Cursor::new(bytes);
        let file = NbtBlob::from_reader(&mut src).unwrap();
        assert_eq!(&file, &nbt);
    }

    #[test]
    fn nbt_nested_compound() {
        let mut inner = HashMap::new();
        inner.insert("test".to_string(), NbtValue::Byte(123));
        let mut nbt = NbtBlob::new("".to_string());
        nbt.insert("inner".to_string(), NbtValue::Compound(inner)).unwrap();

        let bytes = vec![
            0x0a,
                0x00, 0x00,
                0x0a,
                    0x00, 0x05,
                    0x69, 0x6e, 0x6e, 0x65, 0x72,
                    0x01,
                    0x00, 0x04,
                    0x74, 0x65, 0x73, 0x74,
                    0x7b,
                0x00,
            0x00
        ];

        // Test correct length.
        assert_eq!(bytes.len(), nbt.len());

        // Test encoding.
        let mut dst = Vec::new();
        nbt.write(&mut dst).unwrap();
        assert_eq!(&dst, &bytes);

        // Test decoding.
        let mut src = io::Cursor::new(bytes);
        let file = NbtBlob::from_reader(&mut src).unwrap();
        assert_eq!(&file, &nbt);
    }

    #[test]
    fn nbt_empty_list() {
        let mut nbt = NbtBlob::new("".to_string());
        nbt.insert("list".to_string(), NbtValue::List(Vec::new())).unwrap();

        let bytes = vec![
            0x0a,
                0x00, 0x00,
                0x09,
                    0x00, 0x04,
                    0x6c, 0x69, 0x73, 0x74,
                    0x01,
                    0x00, 0x00, 0x00, 0x00,
            0x00
        ];

        // Test correct length.
        assert_eq!(bytes.len(), nbt.len());

        // Test encoding.
        let mut dst = Vec::new();
        nbt.write(&mut dst).unwrap();
        assert_eq!(&dst, &bytes);

        // Test decoding.
        let mut src = io::Cursor::new(bytes);
        let file = NbtBlob::from_reader(&mut src).unwrap();
        assert_eq!(&file, &nbt);
    }

    #[test]
    fn nbt_no_root() {
        let bytes = vec![0x00];
        // Will fail, because the root is not a compound.
        assert_eq!(NbtBlob::from_reader(&mut io::Cursor::new(bytes.as_slice())),
                Err(NbtError::NoRootCompound));
    }

    #[test]
    fn nbt_no_end_tag() {
        let bytes = vec![
            0x0a,
                0x00, 0x00,
                0x09,
                    0x00, 0x04,
                    0x6c, 0x69, 0x73, 0x74,
                    0x01,
                    0x00, 0x00, 0x00, 0x00
        ];

        // Will fail, because there is no end tag.
        assert_eq!(NbtBlob::from_reader(&mut io::Cursor::new(bytes.as_slice())),
                Err(NbtError::IncompleteNbtValue));
    }

    #[test]
    fn nbt_invalid_id() {
        let bytes = vec![
            0x0a,
                0x00, 0x00,
                0x0f, // No tag associated with 0x0f.
                    0x00, 0x04,
                    0x6c, 0x69, 0x73, 0x74,
                    0x01,
            0x00
        ];
        assert_eq!(NbtBlob::from_reader(&mut io::Cursor::new(bytes.as_slice())),
                   Err(NbtError::InvalidTypeId(15)));
    }

    #[test]
    fn nbt_invalid_list() {
        let mut nbt = NbtBlob::new("".to_string());
        let mut badlist = Vec::new();
        badlist.push(NbtValue::Byte(1));
        badlist.push(NbtValue::Short(1));
        // Will fail to insert, because the List is heterogeneous.
        assert_eq!(nbt.insert("list".to_string(), NbtValue::List(badlist)),
                   Err(NbtError::HeterogeneousList));
    }

    #[test]
    fn nbt_bad_compression() {
        // These aren't in the zlib or gzip format, so they'll fail.
        let bytes = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        assert!(NbtBlob::from_gzip(&mut io::Cursor::new(bytes.as_slice())).is_err());
        assert!(NbtBlob::from_zlib(&mut io::Cursor::new(bytes.as_slice())).is_err());
    }

    #[test]
    fn nbt_compression() {
        // Create a non-trivial NbtBlob.
        let mut nbt = NbtBlob::new("".to_string());
        nbt.insert("name".to_string(), NbtValue::String("Herobrine".to_string())).unwrap();
        nbt.insert("health".to_string(), NbtValue::Byte(100)).unwrap();
        nbt.insert("food".to_string(), NbtValue::Float(20.0)).unwrap();
        nbt.insert("emeralds".to_string(), NbtValue::Short(12345)).unwrap();
        nbt.insert("timestamp".to_string(), NbtValue::Int(1424778774)).unwrap();

        // Test zlib encoding/decoding.
        let mut zlib_dst = Vec::new();
        nbt.write_zlib(&mut zlib_dst).unwrap();
        let zlib_file = NbtBlob::from_zlib(&mut io::Cursor::new(zlib_dst)).unwrap();
        assert_eq!(&nbt, &zlib_file);

        // Test gzip encoding/decoding.
        let mut gzip_dst = Vec::new();
        nbt.write_gzip(&mut gzip_dst).unwrap();
        let gz_file = NbtBlob::from_gzip(&mut io::Cursor::new(gzip_dst)).unwrap();
        assert_eq!(&nbt, &gz_file);
    }

    #[test]
    fn nbt_bigtest() {
        let mut bigtest_file = File::open("../tests/big1.nbt").unwrap();
        let bigtest = NbtBlob::from_gzip(&mut bigtest_file).unwrap();
        // This is a pretty indirect way of testing correctness.
        assert_eq!(1544, bigtest.len());
    }

    #[bench]
    fn nbt_bench_bigwrite(b: &mut Bencher) {
        let mut file = File::open("../tests/big1.nbt").unwrap();
        let nbt = NbtBlob::from_gzip(&mut file).unwrap();
        b.iter(|| {
            nbt.write(&mut io::sink())
        });
    }

    #[bench]
    fn nbt_bench_smallwrite(b: &mut Bencher) {
        let mut file = File::open("../tests/small4.nbt").unwrap();
        let nbt = NbtBlob::from_reader(&mut file).unwrap();
        b.iter(|| {
            nbt.write(&mut io::sink())
        });
    }
}


text:
'use strict';

var assert = require('assert');

/**
 * Implements behavior triggers as described in SIP-0003
 * @constructor
 * @license AGPL-3.0
 * @see https://github.com/storj/sips/blob/master/sip-0003.md
 */
function TriggerManager(options) {
  if (!(this instanceof TriggerManager)) {
    return new TriggerManager(options);
  }

  this._options = options;
  this._authorized = {};
  this._behaviors = {};
}

/**
 * Adds a trigger handler for the given nodeID and behavior
 * @param {String|Array} nodeID - The nodeID(s) to authorize for the trigger
 * (supports `*` wildcard)
 * @param {Object} behaviors - Behavior name to {TriggerManager~triggerHandler}s
 */
TriggerManager.prototype.add = function(nodeID, behaviors) {
  var self = this;

  if (Array.isArray(nodeID)) {
    return nodeID.forEach(function(nodeID) {
      self.add(nodeID, behaviors);
    });
  }

  for (var behavior in behaviors) {
    assert(
      typeof behaviors[behavior] === 'function',
      'Trigger handler must be a function'
    );

    if (!this._authorized[behavior]) {
      this._authorized[behavior] = [];
    }

    if (this._authorized[behavior].indexOf(nodeID) === -1) {
      this._authorized[behavior].push(nodeID);
    }

    this._behaviors[nodeID + ':' + behavior] = behaviors[behavior];
  }
};

/**
 * Removes a trigger handler for the given nodeID and behavior
 * @param {String|Array} nodeID - The nodeID(s) to deauthorize for the trigger
 * @param {String|Array} behaviors - Behavior name to unregister
 */
TriggerManager.prototype.remove = function(nodeID, behavior) {
  var self = this;

  if (Array.isArray(nodeID)) {
    return nodeID.forEach(function(nodeID) {
      if (Array.isArray(behavior)) {
        return behavior.forEach(function(behavior) {
          self.remove(nodeID, behavior);
        });
      }

      self.remove(nodeID, behavior);
    });
  }

  if (this._authorized[behavior]) {
    var index = this._authorized[behavior].indexOf(nodeID);

    if (index !== -1) {
      this._authorized[behavior].splice(index, 1);
    }
  }

  delete this._behaviors[nodeID + ':' + behavior];
};

/**
 * Process a received trigger message
 * @param {Object} messageParams - The received message params
 * @param {TriggerManager~processCallback} callback - Result of trigger process
 */
TriggerManager.prototype.process = function(messageParams, callback) {
  var authorized = this._authorized[messageParams.behavior];
  var allowAnySource = authorized ? authorized.indexOf('*') !== -1 : false;
  var sourceNodeId = allowAnySource || messageParams.contact.nodeID;

  if (!authorized) {
    return callback(new Error('No trigger handler defined for behavior'));
  }

  if (!allowAnySource && authorized.indexOf(sourceNodeId) === -1) {
    return callback(new Error('Not authorized to process trigger'));
  }

  this._behaviors[sourceNodeId + ':' + messageParams.behavior](
    messageParams,
    callback,
    this.remove.bind(this, sourceNodeId, messageParams.behavior)
  );
};

/**
 * Called when a trigger is received from authorized source
 * @callback TriggerManager~triggerHandler
 * @param {Object} messageParams - The RPC message parameters
 * @param {TriggerManager~replyToSender} replyToSender - Respond to the trigger
 * @param {TriggerManager~destroyTrigger} destroyTrigger - Unregisters trigger
 */

/**
 * Passed to the trigger handler for replying to the message
 * @callback TriggerManager~replyToSender
 * @param {Error|null} err - Optional error to respond with
 * @param {Object} params - Response parameters to return
 */

/**
 * Optionally called from trigger handler to unregister the trigger handler
 * @callback TriggerManager~destroyTrigger
 */

/**
 * Called upon the processing of a trigger message
 * @callback TriggerManager~processCallback
 * @param {Error|null} err - Optional error resulting from processing
 * @param {Object} params - Response parameters to send back
 */

module.exports = TriggerManager;


text:
package controlP5;

import java.util.Iterator;
import java.util.LinkedHashMap;

import processing.core.PApplet;
import processing.core.PGraphics;

/**
 * Use charts to display float array data as line chart, yet experimental, but see the
 * ControlP5chart example for more details.
 *
 * @example controllers/ControlP5chart
 */
public class Chart extends Controller< Chart > {

	public final static int LINE = 0;
	public final static int BAR = 1;
	public final static int BAR_CENTERED = 2;
	public final static int HISTOGRAM = 3;
	public final static int PIE = 4;
	public final static int AREA = 5;

	protected final LinkedHashMap< String , ChartDataSet > _myDataSet;
	protected float resolution = 1;
	protected float strokeWeight = 1;
	protected float _myMin = 0;
	protected float _myMax = 1;

	/**
	 * Convenience constructor to extend Chart.
	 *
	 * @example use/ControlP5extendController
	 * @param theControlP5
	 * @param theName
	 */
	public Chart( ControlP5 theControlP5 , String theName ) {
		this( theControlP5 , theControlP5.getDefaultTab( ) , theName , 0 , 0 , 200 , 100 );
		theControlP5.register( theControlP5.papplet , theName , this );
	}

	protected Chart( ControlP5 theControlP5 , ControllerGroup< ? > theParent , String theName , float theX , float theY , int theWidth , int theHeight ) {
		super( theControlP5 , theParent , theName , theX , theY , theWidth , theHeight );
		setRange( 0 , theHeight );
		_myDataSet = new LinkedHashMap< String , ChartDataSet >( );
		getCaptionLabel( ).align( LEFT, BOTTOM_OUTSIDE ).paddingX = 0;

	}

	public Chart setRange( float theMin , float theMax ) {
		_myMin = theMin;
		_myMax = theMax;
		return this;
	}

	public Chart setColors( String theSetIndex , int ... theColors ) {
		getDataSet( ).get( theSetIndex ).setColors( theColors );
		return this;
	}

	public Chart addData( ChartData theItem ) {
		return addData( getFirstDataSetIndex( ) , theItem );
	}

	private String getFirstDataSetIndex( ) {
		return getDataSet( ).keySet( ).iterator( ).next( );
	}

	private String getLastDataSetIndex( ) {
		Iterator< String > it = getDataSet( ).keySet( ).iterator( );
		String last = null;
		while ( it.hasNext( ) ) {
			last = it.next( );
		}
		return last;
	}

	public Chart addData( String theSetIndex , ChartData theItem ) {
		getDataSet( theSetIndex ).add( theItem );
		return this;
	}

	public Chart addData( float theValue ) {
		ChartData cdi = new ChartData( theValue );
		getDataSet( getFirstDataSetIndex( ) ).add( cdi );
		return this;
	}

	public Chart addData( String theSetIndex , float theValue ) {
		ChartData cdi = new ChartData( theValue );
		getDataSet( theSetIndex ).add( cdi );
		return this;
	}

	public Chart addData( ChartDataSet theChartData , float theValue ) {
		ChartData cdi = new ChartData( theValue );
		theChartData.add( cdi );
		return this;
	}

	// array operations see syntax
	// http://www.w3schools.com/jsref/jsref_obj_array.asp

	/**
	 * adds a new float at the beginning of the data set.
	 */
	public Chart unshift( float theValue ) {
		return unshift( getFirstDataSetIndex( ) , theValue );
	}

	public Chart unshift( String theSetIndex , float theValue ) {
		if ( getDataSet( theSetIndex ).size( ) > ( getWidth() / resolution ) ) {
			removeLast( theSetIndex );
		}
		return addFirst( theSetIndex , theValue );
	}

	public Chart push( float theValue ) {
		return push( getFirstDataSetIndex( ) , theValue );
	}

	public Chart push( String theSetIndex , float theValue ) {
		if ( getDataSet( theSetIndex ).size( ) > ( getWidth() / resolution ) ) {
			removeFirst( theSetIndex );
		}
		return addLast( theSetIndex , theValue );
	}

	public Chart addFirst( float theValue ) {
		return addFirst( getFirstDataSetIndex( ) , theValue );
	}

	public Chart addFirst( String theSetIndex , float theValue ) {
		ChartData cdi = new ChartData( theValue );
		getDataSet( theSetIndex ).add( 0 , cdi );
		return this;
	}

	public Chart addLast( float theValue ) {
		return addLast( getFirstDataSetIndex( ) , theValue );
	}

	public Chart addLast( String theSetIndex , float theValue ) {
		ChartData cdi = new ChartData( theValue );
		getDataSet( theSetIndex ).add( cdi );
		return this;
	}

	public Chart removeLast( ) {
		return removeLast( getFirstDataSetIndex( ) );
	}

	public Chart removeLast( String theSetIndex ) {
		return removeData( theSetIndex , getDataSet( theSetIndex ).size( ) - 1 );
	}

	public Chart removeFirst( ) {
		return removeFirst( getFirstDataSetIndex( ) );
	}

	public Chart removeFirst( String theSetIndex ) {
		return removeData( theSetIndex , 0 );
	}

	public Chart removeData( ChartData theItem ) {
		removeData( getFirstDataSetIndex( ) , theItem );
		return this;
	}

	public Chart removeData( String theSetIndex , ChartData theItem ) {
		getDataSet( theSetIndex ).remove( theItem );
		return this;
	}

	public Chart removeData( int theItemIndex ) {
		removeData( getFirstDataSetIndex( ) , theItemIndex );
		return this;
	}

	public Chart removeData( String theSetIndex , int theItemIndex ) {
		if ( getDataSet( theSetIndex ).size( ) < 1 ) {
			return this;
		}
		getDataSet( theSetIndex ).remove( theItemIndex );
		return this;
	}

	public Chart setData( int theItemIndex , ChartData theItem ) {
		getDataSet( getFirstDataSetIndex( ) ).set( theItemIndex , theItem );
		return this;
	}

	public Chart setData( String theSetItem , int theItemIndex , ChartData theItem ) {
		getDataSet( theSetItem ).set( theItemIndex , theItem );
		return this;
	}

	public Chart addDataSet( String theName ) {
		getDataSet( ).put( theName , new ChartDataSet( theName ) );
		return this;
	}

	public Chart setDataSet( ChartDataSet theItems ) {
		setDataSet( getFirstDataSetIndex( ) , theItems );
		return this;
	}

	public Chart setDataSet( String theSetIndex , ChartDataSet theChartData ) {
		getDataSet( ).put( theSetIndex , theChartData );
		return this;
	}

	public Chart removeDataSet( String theIndex ) {
		getDataSet( ).remove( theIndex );
		return this;
	}

	public Chart setData( float ... theValues ) {
		setData( getFirstDataSetIndex( ) , theValues );
		return this;
	}

	public Chart setData( String theSetIndex , float ... theValues ) {
		if ( getDataSet( ).get( theSetIndex ).size( ) != theValues.length ) {
			getDataSet( ).get( theSetIndex ).clear( );
			for ( int i = 0 ; i < theValues.length ; i++ ) {
				getDataSet( ).get( theSetIndex ).add( new ChartData( 0 ) );
			}
		}
		int n = 0;
		resolution = ( float ) getWidth() / ( getDataSet( ).get( theSetIndex ).size( ) - 1 );
		for ( float f : theValues ) {
			getDataSet( ).get( theSetIndex ).get( n++ ).setValue( f );
		}
		return this;
	}

	public Chart updateData( float ... theValues ) {
		return setData( theValues );
	}

	public Chart updateData( String theSetIndex , float ... theValues ) {
		return setData( theSetIndex , theValues );
	}

	public LinkedHashMap< String , ChartDataSet > getDataSet( ) {
		return _myDataSet;
	}

	public ChartDataSet getDataSet( String theIndex ) {
		return getDataSet( ).get( theIndex );
	}

	public float[] getValuesFrom( String theIndex ) {
		return getDataSet( theIndex ).getValues( );
	}

	public ChartData getData( String theIndex , int theItemIndex ) {
		return getDataSet( theIndex ).get( theItemIndex );
	}

	public int size( ) {
		return getDataSet( ).size( );
	}

	@Override
	public void onEnter( ) {
	}

	@Override
	public void onLeave( ) {
	}

	@Override
	public Chart setValue( float theValue ) {
		// TODO Auto-generated method stub
		return this;
	}

	public Chart setStrokeWeight( float theWeight ) {
		strokeWeight = theWeight;
		for ( ChartDataSet c : getDataSet( ).values( ) ) {
			c.setStrokeWeight( theWeight );
		}
		return this;
	}

	public float getStrokeWeight( ) {
		return strokeWeight;
	}

	/**
	 * ?
	 *
	 * @param theValue
	 * @return
	 */
	public Chart setResolution( int theValue ) {
		resolution = theValue;
		return this;
	}

	public int getResolution( ) {
		return ( int ) resolution;
	}

	/**
	 * @exclude
	 */
	@Override
	@ControlP5.Invisible
	public Chart updateDisplayMode( int theMode ) {
		return updateViewMode( theMode );
	}

	/**
	 * @exclude
	 */
	@ControlP5.Invisible
	public Chart updateViewMode( int theMode ) {
		_myDisplayMode = theMode;
		switch ( theMode ) {
		case ( DEFAULT ):
			_myControllerView = new ChartViewPie( );
			break;
		case ( IMAGE ):
			// _myDisplay = new ChartImageDisplay();
			break;
		case ( SPRITE ):
			// _myDisplay = new ChartSpriteDisplay();
			break;
		case ( CUSTOM ):
		default:
			break;
		}
		return this;
	}

	public class ChartViewBar implements ControllerView< Chart > {

		public void display( PGraphics theGraphics , Chart theController ) {
			theGraphics.pushStyle( );
			theGraphics.fill( getColor( ).getBackground( ) );
			theGraphics.rect( 0 , 0 , getWidth( ) , getHeight( ) );
			theGraphics.noStroke( );

			Iterator< String > it = getDataSet( ).keySet( ).iterator( );
			String index = null;
			float o = 0;
			while ( it.hasNext( ) ) {
				index = it.next( );
				float s = getDataSet( index ).size( );
				for ( int i = 0 ; i < s ; i++ ) {
					theGraphics.fill( getDataSet( index ).getColor( i ) );
					float ww = ( ( getWidth() / s ) );
					float hh = PApplet.map( getDataSet( index ).get( i ).getValue( ) , _myMin , _myMax , 0 , getHeight( ) );
					theGraphics.rect( o + i * ww , getHeight( ) , ( ww / getDataSet( ).size( ) ) , -PApplet.min( getHeight( ) , PApplet.max( 0 , hh ) ) );
				}
				o += ( ( getWidth() / s ) ) / getDataSet( ).size( );
			}
			theGraphics.popStyle( );
		}
	}

	public class ChartViewBarCentered implements ControllerView< Chart > {

		public void display( PGraphics theGraphics , Chart theController ) {
			theGraphics.pushStyle( );
			theGraphics.fill( getColor( ).getBackground( ) );
			theGraphics.rect( 0 , 0 , getWidth( ) , getHeight( ) );
			theGraphics.noStroke( );

			Iterator< String > it = getDataSet( ).keySet( ).iterator( );
			String index = null;
			float o = 0;
			int n = 4;
			int off = ( getDataSet( ).size( ) - 1 ) * n;
			while ( it.hasNext( ) ) {
				index = it.next( );
				int s = getDataSet( index ).size( );
				float step = ( float ) getWidth() / ( float ) ( s );
				float ww = step - ( getWidth() % step );
				ww -= 1;
				ww = PApplet.max( 1 , ww );

				for ( int i = 0 ; i < s ; i++ ) {
					theGraphics.fill( getDataSet( index ).getColor( i ) );
					ww = ( ( getWidth() / s ) * 0.5f );
					float hh = PApplet.map( getDataSet( index ).get( i ).getValue( ) , _myMin , _myMax , 0 , getHeight( ) );
					theGraphics.rect( -off / 2 + o + i * ( ( getWidth() / s ) ) + ww / 2 , getHeight( ) , ww , -PApplet.min( getHeight( ) , PApplet.max( 0 , hh ) ) );
				}
				o += n;
			}
			theGraphics.popStyle( );
		}
	}

	public class ChartViewLine implements ControllerView< Chart > {

		public void display( PGraphics theGraphics , Chart theController ) {

			theGraphics.pushStyle( );
			theGraphics.fill( getColor( ).getBackground( ) );
			theGraphics.rect( 0 , 0 , getWidth( ) , getHeight( ) );
			theGraphics.noFill( );
			Iterator< String > it = getDataSet( ).keySet( ).iterator( );
			String index = null;
			while ( it.hasNext( ) ) {
				index = it.next( );
				theGraphics.stroke( getDataSet( index ).getColor( 0 ) );
				theGraphics.strokeWeight( getDataSet( index ).getStrokeWeight( ) );

				theGraphics.beginShape( );
				float res = ( ( float ) getWidth( ) ) / ( getDataSet( index ).size( ) - 1 );
				for ( int i = 0 ; i < getDataSet( index ).size( ) ; i++ ) {
					float hh = PApplet.map( getDataSet( index ).get( i ).getValue( ) , _myMin , _myMax , getHeight( ) , 0 );
					theGraphics.vertex( i * res , PApplet.min( getHeight( ) , PApplet.max( 0 , hh ) ) );
				}
				theGraphics.endShape( );
			}
			theGraphics.noStroke( );
			theGraphics.popStyle( );
			getCaptionLabel( ).draw( theGraphics , 0 , 0 , theController );
		}
	}

	public class ChartViewArea implements ControllerView< Chart > {

		public void display( PGraphics theGraphics , Chart theController ) {

			theGraphics.pushStyle( );
			theGraphics.fill( getColor( ).getBackground( ) );
			theGraphics.rect( 0 , 0 , getWidth( ) , getHeight( ) );
			theGraphics.noStroke( );

			Iterator< String > it = getDataSet( ).keySet( ).iterator( );
			String index = null;
			while ( it.hasNext( ) ) {
				index = it.next( );
				float res = ( ( float ) getWidth( ) ) / ( getDataSet( index ).size( ) - 1 );

				theGraphics.fill( getDataSet( index ).getColor( 0 ) );
				theGraphics.beginShape( );
				theGraphics.vertex( 0 , getHeight( ) );

				for ( int i = 0 ; i < getDataSet( index ).size( ) ; i++ ) {
					float hh = PApplet.map( getDataSet( index ).get( i ).getValue( ) , _myMin , _myMax , getHeight( ) , 0 );
					theGraphics.vertex( i * res , PApplet.min( getHeight( ) , PApplet.max( 0 , hh ) ) );
				}
				theGraphics.vertex( getWidth( ) , getHeight( ) );
				theGraphics.endShape( PApplet.CLOSE );
			}
			theGraphics.noStroke( );
			theGraphics.popStyle( );
		}
	}

	public class ChartViewPie implements ControllerView< Chart > {

		public void display( PGraphics theGraphics , Chart theController ) {
			theGraphics.pushStyle( );
			theGraphics.pushMatrix( );

			Iterator< String > it = getDataSet( ).keySet( ).iterator( );
			String index = null;
			while ( it.hasNext( ) ) {
				index = it.next( );
				float total = 0;
				for ( int i = 0 ; i < getDataSet( index ).size( ) ; i++ ) {
					total += getDataSet( index ).get( i ).getValue( );
				}

				float segment = TWO_PI / total;
				float angle = -HALF_PI;

				theGraphics.noStroke( );
				for ( int i = 0 ; i < getDataSet( index ).size( ) ; i++ ) {
					theGraphics.fill( getDataSet( index ).getColor( i ) );
					float nextAngle = angle + getDataSet( index ).get( i ).getValue( ) * segment;

					// a tiny offset to even out render artifacts when in smooth() mode.
					float a = PApplet.max( 0 , PApplet.map( getWidth( ) , 0 , 200 , 0.05f , 0.01f ) );

					theGraphics.arc( 0 , 0 , getWidth( ) , getHeight( ) , angle - a , nextAngle );
					angle = nextAngle;
				}
				theGraphics.translate( 0 , ( getHeight( ) + 10 ) );
			}
			theGraphics.popMatrix( );
			theGraphics.popStyle( );
		}
	}

	public Chart setView( int theType ) {
		switch ( theType ) {
		case ( PIE ):
			setView( new ChartViewPie( ) );
			break;
		case ( LINE ):
			setView( new ChartViewLine( ) );
			break;
		case ( BAR ):
			setView( new ChartViewBar( ) );
			break;
		case ( BAR_CENTERED ):
			setView( new ChartViewBarCentered( ) );
			break;
		case ( AREA ):
			setView( new ChartViewArea( ) );
			break;
		default:
			System.out.println( "Sorry, this ChartView does not exist" );
			break;
		}
		return this;
	}

	@Override
	public String getInfo( ) {
		return "type:\tChart\n" + super.toString( );
	}

	@Override
	public String toString( ) {
		return super.toString( ) + " [ " + getValue( ) + " ]" + " Chart " + "(" + this.getClass( ).getSuperclass( ) + ")";
	}

}

/* NOTES what is the difference in meaning between chart and graph
 * http://answers.yahoo.com/question/index?qid=20090101193325AA3mgMl
 *
 * more charts to implement: from https://vimeo.com/groups/oaod/videos/60013194 (44:40) scatter
 * plot, star plot, histogram, dendrogram, box plot, physical map, tree, 2d 3d isosurfaces table,
 * half matrix, graph, hierarchical pie, line graph, numeric matrix, heat map, permutation matrix
 * bar graph, radial graph, */


text:
"""
Tools for sending email.
"""

import mimetypes
import os
import smtplib
import socket
import time
import random
from email import Charset, Encoders
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.Header import Header
from email.Utils import formatdate, parseaddr, formataddr

from django.conf import settings
from django.utils.encoding import smart_str, force_unicode

# Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from
# some spam filters.
Charset.add_charset('utf-8', Charset.SHORTEST, Charset.QP, 'utf-8')

# Default MIME type to use on attachments (if it is not explicitly given
# and cannot be guessed).
DEFAULT_ATTACHMENT_MIME_TYPE = 'application/octet-stream'

# Cache the hostname, but do it lazily: socket.getfqdn() can take a couple of
# seconds, which slows down the restart of the server.
class CachedDnsName(object):
    def __str__(self):
        return self.get_fqdn()

    def get_fqdn(self):
        if not hasattr(self, '_fqdn'):
            self._fqdn = socket.getfqdn()
        return self._fqdn

DNS_NAME = CachedDnsName()

# Copied from Python standard library, with the following modifications:
# * Used cached hostname for performance.
# * Added try/except to support lack of getpid() in Jython (#5496).
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <20020201195627.33539.96671@nightshade.la.mastaler.com>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    try:
        pid = os.getpid()
    except AttributeError:
        # No getpid() in Jython, for example.
        pid = 1
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = DNS_NAME
    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid

class BadHeaderError(ValueError):
    pass

def forbid_multi_line_headers(name, val):
    """Forbids multi-line headers, to prevent header injection."""
    val = force_unicode(val)
    if '\n' in val or '\r' in val:
        raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
    try:
        val = val.encode('ascii')
    except UnicodeEncodeError:
        if name.lower() in ('to', 'from', 'cc'):
            result = []
            for item in val.split(', '):
                nm, addr = parseaddr(item)
                nm = str(Header(nm, settings.DEFAULT_CHARSET))
                result.append(formataddr((nm, str(addr))))
            val = ', '.join(result)
        else:
            val = Header(val, settings.DEFAULT_CHARSET)
    return name, val

class SafeMIMEText(MIMEText):
    def __setitem__(self, name, val):
        name, val = forbid_multi_line_headers(name, val)
        MIMEText.__setitem__(self, name, val)

class SafeMIMEMultipart(MIMEMultipart):
    def __setitem__(self, name, val):
        name, val = forbid_multi_line_headers(name, val)
        MIMEMultipart.__setitem__(self, name, val)

class SMTPConnection(object):
    """
    A wrapper that manages the SMTP network connection.
    """

    def __init__(self, host=None, port=None, username=None, password=None,
                 use_tls=None, fail_silently=False):
        self.host = host or settings.EMAIL_HOST
        self.port = port or settings.EMAIL_PORT
        self.username = username or settings.EMAIL_HOST_USER
        self.password = password or settings.EMAIL_HOST_PASSWORD
        self.use_tls = (use_tls is not None) and use_tls or settings.EMAIL_USE_TLS
        self.fail_silently = fail_silently
        self.connection = None

    def open(self):
        """
        Ensures we have a connection to the email server. Returns whether or
        not a new connection was required (True or False).
        """
        if self.connection:
            # Nothing to do if the connection is already open.
            return False
        try:
            # If local_hostname is not specified, socket.getfqdn() gets used.
            # For performance, we use the cached FQDN for local_hostname.
            self.connection = smtplib.SMTP(self.host, self.port,
                                           local_hostname=DNS_NAME.get_fqdn())
            if self.use_tls:
                self.connection.ehlo()
                self.connection.starttls()
                self.connection.ehlo()
            if self.username and self.password:
                self.connection.login(self.username, self.password)
            return True
        except:
            if not self.fail_silently:
                raise

    def close(self):
        """Closes the connection to the email server."""
        try:
            try:
                self.connection.quit()
            except socket.sslerror:
                # This happens when calling quit() on a TLS connection
                # sometimes.
                self.connection.close()
            except:
                if self.fail_silently:
                    return
                raise
        finally:
            self.connection = None

    def send_messages(self, email_messages):
        """
        Sends one or more EmailMessage objects and returns the number of email
        messages sent.
        """
        if not email_messages:
            return
        new_conn_created = self.open()
        if not self.connection:
            # We failed silently on open(). Trying to send would be pointless.
            return
        num_sent = 0
        for message in email_messages:
            sent = self._send(message)
            if sent:
                num_sent += 1
        if new_conn_created:
            self.close()
        return num_sent

    def _send(self, email_message):
        """A helper method that does the actual sending."""
        if not email_message.recipients():
            return False
        try:
            self.connection.sendmail(email_message.from_email,
                    email_message.recipients(),
                    email_message.message().as_string())
        except:
            if not self.fail_silently:
                raise
            return False
        return True

class EmailMessage(object):
    """
    A container for email information.
    """
    content_subtype = 'plain'
    multipart_subtype = 'mixed'
    encoding = None     # None => use settings default

    def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
            connection=None, attachments=None, headers=None):
        """
        Initialize a single email message (which can be sent to multiple
        recipients).

        All strings used to create the message can be unicode strings (or UTF-8
        bytestrings). The SafeMIMEText class will handle any necessary encoding
        conversions.
        """
        if to:
            assert not isinstance(to, basestring), '"to" argument must be a list or tuple'
            self.to = list(to)
        else:
            self.to = []
        if bcc:
            assert not isinstance(bcc, basestring), '"bcc" argument must be a list or tuple'
            self.bcc = list(bcc)
        else:
            self.bcc = []
        self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
        self.subject = subject
        self.body = body
        self.attachments = attachments or []
        self.extra_headers = headers or {}
        self.connection = connection

    def get_connection(self, fail_silently=False):
        if not self.connection:
            self.connection = SMTPConnection(fail_silently=fail_silently)
        return self.connection

    def message(self):
        encoding = self.encoding or settings.DEFAULT_CHARSET
        msg = SafeMIMEText(smart_str(self.body, settings.DEFAULT_CHARSET),
                           self.content_subtype, encoding)
        if self.attachments:
            body_msg = msg
            msg = SafeMIMEMultipart(_subtype=self.multipart_subtype)
            if self.body:
                msg.attach(body_msg)
            for attachment in self.attachments:
                if isinstance(attachment, MIMEBase):
                    msg.attach(attachment)
                else:
                    msg.attach(self._create_attachment(*attachment))
        msg['Subject'] = self.subject
        msg['From'] = self.from_email
        msg['To'] = ', '.join(self.to)
        msg['Date'] = formatdate()
        msg['Message-ID'] = make_msgid()
        for name, value in self.extra_headers.items():
            msg[name] = value
        return msg

    def recipients(self):
        """
        Returns a list of all recipients of the email (includes direct
        addressees as well as Bcc entries).
        """
        return self.to + self.bcc

    def send(self, fail_silently=False):
        """Sends the email message."""
        return self.get_connection(fail_silently).send_messages([self])

    def attach(self, filename=None, content=None, mimetype=None):
        """
        Attaches a file with the given filename and content. The filename can
        be omitted (useful for multipart/alternative messages) and the mimetype
        is guessed, if not provided.

        If the first parameter is a MIMEBase subclass it is inserted directly
        into the resulting message attachments.
        """
        if isinstance(filename, MIMEBase):
            assert content == mimetype == None
            self.attachments.append(filename)
        else:
            assert content is not None
            self.attachments.append((filename, content, mimetype))

    def attach_file(self, path, mimetype=None):
        """Attaches a file from the filesystem."""
        filename = os.path.basename(path)
        content = open(path, 'rb').read()
        self.attach(filename, content, mimetype)

    def _create_attachment(self, filename, content, mimetype=None):
        """
        Converts the filename, content, mimetype triple into a MIME attachment
        object.
        """
        if mimetype is None:
            mimetype, _ = mimetypes.guess_type(filename)
            if mimetype is None:
                mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
        basetype, subtype = mimetype.split('/', 1)
        if basetype == 'text':
            attachment = SafeMIMEText(smart_str(content,
                settings.DEFAULT_CHARSET), subtype, settings.DEFAULT_CHARSET)
        else:
            # Encode non-text attachments with base64.
            attachment = MIMEBase(basetype, subtype)
            attachment.set_payload(content)
            Encoders.encode_base64(attachment)
        if filename:
            attachment.add_header('Content-Disposition', 'attachment',
                                  filename=filename)
        return attachment

class EmailMultiAlternatives(EmailMessage):
    """
    A version of EmailMessage that makes it easy to send multipart/alternative
    messages. For example, including text and HTML versions of the text is
    made easier.
    """
    multipart_subtype = 'alternative'

    def attach_alternative(self, content, mimetype=None):
        """Attach an alternative content representation."""
        self.attach(content=content, mimetype=mimetype)

def send_mail(subject, message, from_email, recipient_list,
              fail_silently=False, auth_user=None, auth_password=None):
    """
    Easy wrapper for sending a single message to a recipient list. All members
    of the recipient list will see the other recipients in the 'To' field.

    If auth_user is None, the EMAIL_HOST_USER setting is used.
    If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.

    Note: The API for this method is frozen. New code wanting to extend the
    functionality should use the EmailMessage class directly.
    """
    connection = SMTPConnection(username=auth_user, password=auth_password,
                                fail_silently=fail_silently)
    return EmailMessage(subject, message, from_email, recipient_list,
                        connection=connection).send()

def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
                   auth_password=None):
    """
    Given a datatuple of (subject, message, from_email, recipient_list), sends
    each message to each recipient list. Returns the number of e-mails sent.

    If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
    If auth_user and auth_password are set, they're used to log in.
    If auth_user is None, the EMAIL_HOST_USER setting is used.
    If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.

    Note: The API for this method is frozen. New code wanting to extend the
    functionality should use the EmailMessage class directly.
    """
    connection = SMTPConnection(username=auth_user, password=auth_password,
                                fail_silently=fail_silently)
    messages = [EmailMessage(subject, message, sender, recipient)
                for subject, message, sender, recipient in datatuple]
    return connection.send_messages(messages)

def mail_admins(subject, message, fail_silently=False):
    """Sends a message to the admins, as defined by the ADMINS setting."""
    EmailMessage(settings.EMAIL_SUBJECT_PREFIX + subject, message,
                 settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS]
                 ).send(fail_silently=fail_silently)

def mail_managers(subject, message, fail_silently=False):
    """Sends a message to the managers, as defined by the MANAGERS setting."""
    EmailMessage(settings.EMAIL_SUBJECT_PREFIX + subject, message,
                 settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS]
                 ).send(fail_silently=fail_silently)


text:
Re-writing stashcp in Python

Usage:
Use --debug for debugging and -r for directory copying.

ex.) python stashcp.py --debug user/taburaad/public/2gb_file.tar .