text:
/* @test
 @summary Test RealTime-tunings using SoftReciver.send method */

import java.io.IOException;

import javax.sound.midi.*;
import javax.sound.sampled.*;

import com.sun.media.sound.*;

public class RealTimeTuning {

    private static class PitchSpy {
        public float pitch = 0;

        public Soundbank getSoundBank() {
            ModelOscillator osc = new ModelOscillator() {
                public float getAttenuation() {
                    return 0;
                }

                public int getChannels() {
                    return 0;
                }

                public ModelOscillatorStream open(float samplerate) {
                    return new ModelOscillatorStream() {
                        public void close() throws IOException {
                            pitch = 0;
                        }

                        public void noteOff(int velocity) {
                            pitch = 0;
                        }

                        public void noteOn(MidiChannel channel,
                                VoiceStatus voice, int noteNumber, int velocity) {
                            pitch = noteNumber * 100;
                        }

                        public int read(float[][] buffer, int offset, int len)
                                throws IOException {
                            return len;
                        }

                        public void setPitch(float ipitch) {
                            pitch = ipitch;
                        }
                    };
                }
            };
            ModelPerformer performer = new ModelPerformer();
            performer.getOscillators().add(osc);
            SimpleInstrument testinstrument = new SimpleInstrument();
            testinstrument.setPatch(new Patch(0, 0));
            testinstrument.add(performer);
            SimpleSoundbank testsoundbank = new SimpleSoundbank();
            testsoundbank.addInstrument(testinstrument);
            return testsoundbank;
        }
    }

    public static void sendTuningChange(Receiver recv, int channel,
            int tuningpreset, int tuningbank) throws InvalidMidiDataException {
        // Data Entry
        ShortMessage sm1 = new ShortMessage();
        sm1.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x64, 04);
        ShortMessage sm2 = new ShortMessage();
        sm2.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x65, 00);

        // Tuning Bank
        ShortMessage sm3 = new ShortMessage();
        sm3.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x06, tuningbank);
        // Data Increment
        ShortMessage sm4 = new ShortMessage();
        sm4.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x60, 0x7F);
        // Data Decrement
        ShortMessage sm5 = new ShortMessage();
        sm5.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x61, 0x7F);

        // Data Entry
        ShortMessage sm6 = new ShortMessage();
        sm6.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x64, 03);
        ShortMessage sm7 = new ShortMessage();
        sm7.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x65, 00);

        // Tuning program
        ShortMessage sm8 = new ShortMessage();
        sm8
                .setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x06,
                        tuningpreset);
        // Data Increment
        ShortMessage sm9 = new ShortMessage();
        sm9.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x60, 0x7F);
        // Data Decrement
        ShortMessage sm10 = new ShortMessage();
        sm10.setMessage(ShortMessage.CONTROL_CHANGE, channel, 0x61, 0x7F);

        recv.send(sm1, -1);
        recv.send(sm2, -1);
        recv.send(sm3, -1);
        recv.send(sm4, -1);
        recv.send(sm5, -1);
        recv.send(sm6, -1);
        recv.send(sm7, -1);
        recv.send(sm8, -1);
        recv.send(sm9, -1);
        recv.send(sm10, -1);

    }

    private static void assertTrue(boolean value) throws Exception {
        if (!value)
            throw new RuntimeException("assertTrue fails!");
    }

    public static void testTunings(int[] msg, int tuningProgram,
            int tuningBank, int targetNote, float targetPitch, boolean realtime)
            throws Exception {
        AudioSynthesizer synth = new SoftSynthesizer();
        AudioInputStream stream = synth.openStream(null, null);
        Receiver recv = synth.getReceiver();
        MidiChannel channel = synth.getChannels()[0];
        byte[] buff = new byte[2048];

        // Create test instrument which we can use to monitor pitch changes
        PitchSpy pitchspy = new PitchSpy();

        synth.unloadAllInstruments(synth.getDefaultSoundbank());
        synth.loadAllInstruments(pitchspy.getSoundBank());

        SysexMessage sysex = null;

        // Send tuning changes
        if (msg != null) {
            byte[] bmsg = new byte[msg.length];
            for (int i = 0; i < bmsg.length; i++)
                bmsg[i] = (byte) msg[i];
            sysex = new SysexMessage();
            sysex.setMessage(bmsg, bmsg.length);
            if (targetPitch == 0) {
                targetPitch = (float) new SoftTuning(bmsg)
                        .getTuning(targetNote);
                // Check if targetPitch != targetNote * 100
                assertTrue(Math.abs(targetPitch - targetNote * 100.0) > 0.001);
            }
        }

        if (tuningProgram != -1)
            sendTuningChange(recv, 0, tuningProgram, tuningBank);

        // First test without tunings
        channel.noteOn(targetNote, 64);
        stream.read(buff, 0, buff.length);
        assertTrue(Math.abs(pitchspy.pitch - (targetNote * 100.0)) < 0.001);

        // Test if realtime/non-realtime works
        if (sysex != null)
            recv.send(sysex, -1);
        stream.read(buff, 0, buff.length);
        if (realtime)
            assertTrue(Math.abs(pitchspy.pitch - targetPitch) < 0.001);
        else
            assertTrue(Math.abs(pitchspy.pitch - (targetNote * 100.0)) < 0.001);

        // Test if tunings works
        channel.noteOn(targetNote, 0);
        stream.read(buff, 0, buff.length);
        assertTrue(Math.abs(pitchspy.pitch - 0.0) < 0.001);

        channel.noteOn(targetNote, 64);
        stream.read(buff, 0, buff.length);
        assertTrue(Math.abs(pitchspy.pitch - targetPitch) < 0.001);

        channel.noteOn(targetNote, 0);
        stream.read(buff, 0, buff.length);
        assertTrue(Math.abs(pitchspy.pitch - 0.0) < 0.001);

        stream.close();
    }

    public static void main(String[] args) throws Exception {
        // Test with no-tunings
        testTunings(null, -1, -1, 60, 6000, false);

        int[] msg;
        // 0x02 SINGLE NOTE TUNING CHANGE (REAL-TIME)
        msg = new int[] { 0xf0, 0x7f, 0x7f, 0x08, 0x02, 0x10, 0x02, 36, 36, 64,
                0, 60, 70, 0, 0, 0xf7 };
        testTunings(msg, 0x10, 0, 60, 7000, true);

        // 0x07 SINGLE NOTE TUNING CHANGE (NON REAL-TIME) (BANK)
        msg = new int[] { 0xf0, 0x7e, 0x7f, 0x08, 0x07, 0x05, 0x07, 0x02, 36,
                36, 64, 0, 60, 80, 0, 0, 0xf7 };
        testTunings(msg, 0x07, 0x05, 60, 8000, false);

        // 0x07 SINGLE NOTE TUNING CHANGE (REAL-TIME) (BANK)
        msg = new int[] { 0xf0, 0x7f, 0x7f, 0x08, 0x07, 0x05, 0x07, 0x02, 36,
                36, 64, 0, 60, 80, 0, 0, 0xf7 };
        testTunings(msg, 0x07, 0x05, 60, 8000, true);

        // 0x08 scale/octave tuning 1-byte form (Non Real-Time)
        msg = new int[] { 0xf0, 0x7e, 0x7f, 0x08, 0x08, 0x03, 0x7f, 0x7f, 5,
                10, 15, 20, 25, 30, 35, 40, 45, 50, 51, 52, 0xf7 };
        testTunings(msg, -1, -1, 60, 0, false);

        // 0x08 scale/octave tuning 1-byte form (REAL-TIME)
        msg = new int[] { 0xf0, 0x7f, 0x7f, 0x08, 0x08, 0x03, 0x7f, 0x7f, 5,
                10, 15, 20, 25, 30, 35, 40, 45, 50, 51, 52, 0xf7 };
        testTunings(msg, -1, -1, 60, 0, true);

        // 0x09 scale/octave tuning 2-byte form (Non Real-Time)
        msg = new int[] { 0xf0, 0x7e, 0x7f, 0x08, 0x09, 0x03, 0x7f, 0x7f, 5,
                10, 15, 20, 25, 30, 35, 40, 45, 50, 51, 52, 5, 10, 15, 20, 25,
                30, 35, 40, 45, 50, 51, 52, 0xf7 };
        testTunings(msg, -1, -1, 60, 0, false);

        // 0x09 scale/octave tuning 2-byte form (REAL-TIME)
        msg = new int[] { 0xf0, 0x7f, 0x7f, 0x08, 0x09, 0x03, 0x7f, 0x7f, 5,
                10, 15, 20, 25, 30, 35, 40, 45, 50, 51, 52, 5, 10, 15, 20, 25,
                30, 35, 40, 45, 50, 51, 52, 0xf7 };
        testTunings(msg, -1, -1, 60, 0, true);

    }
}


text:
$Computer = $env:COMPUTERNAME
$GroupName = 'Mygroup'
$ADSI = [ADSI] ("WinNT://$Computer")
$Group = $ADSI.Children.Find($GroupName, 'group')

#Use this to call the ad user you're logged in as, but this only works if you have a loca account with the same name
#$User = $env:USERNAME
$User = 'Administrator'
$Group.Remove(("WinNt://$Computer/$User"))

redpajama_set_name: RedPajamaGithub


text:
from logging import getLogger

from turbulenz_local.lib.servicestatus import ServiceStatus

from turbulenz_local.controllers import BaseController
from turbulenz_local.decorators import jsonify
from turbulenz_local.models.userlist import get_current_user

LOG = getLogger(__name__)

class ProfilesController(BaseController):
    """ ProfilesController consists of all the Profiles methods
    """

    profiles_service = ServiceStatus.check_status_decorator('profiles')

    ##
    ## FRONT CONTROLLER METHODS
    ##

    @classmethod
    @profiles_service
    @jsonify
    def user(cls):
        user = get_current_user()
        user_profile = {'username': user.username,
                        'displayname': user.username,
                        'age': user.age,
                        'language': user.language,
                        'country': user.country,
                        'avatar': user.avatar,
                        'guest': user.guest}
        return {'ok': True, 'data': user_profile}


text:
package org.mockito.release.version;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class VersionBumper {

    /**
     * Increments 'patch' element of the version of provided version, e.g. 1.0.0 -> 1.0.1
     */
    String incrementVersion(String version) {
        Pattern pattern = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)(-(\\w+)){0,1}");
        Matcher matcher = pattern.matcher(version);
        boolean m = matcher.matches();
        if (!m) {
            throw new IllegalArgumentException("Unsupported version: '" + version + "'. Examples of supported versions: 1.0.0, 1.20.123, 1.0.10-beta");
        }

        int major = Integer.parseInt(matcher.group(1));
        int minor = Integer.parseInt(matcher.group(2));
        int patch = Integer.parseInt(matcher.group(3));
        String postfix = matcher.group(4) != null ? matcher.group(4) : "";
        return "" + major + "." + minor + "." + (patch + 1) + postfix;
    }
}


text:
namespace mtao::geometry::mesh {

// the circumcentral dual edge lengths
// takes in vertices, cells, and boundaries
template <typename VType, typename CellType, typename FacetType>
auto dual_edge_lengths(const Eigen::MatrixBase<VType>& V,
                       const Eigen::MatrixBase<CellType>& C,
                       const Eigen::MatrixBase<FacetType>& F) {
    auto DE = dual_edges<CellType::RowsAtCompileTime>(C, F);
    auto CC = circumcenters(V, C);

    using Scalar = typename VType::Scalar;
    VectorX<Scalar> R(F.cols());
    for (int j = 0; j < R.size(); ++j) {
        auto de = DE.col(j);

        if(de(1) == -1) {
            if(de(0) == -1) {
                continue;
            }
            R(j) = (circumcenters(V,F.col(j)) - CC.col(de(0))).norm();
        } else {
            R(j) = (CC.col(de(1)) - CC.col(de(0))).norm();
        }
    }
    return R;
}

}  // namespace mtao::geometry::mesh


text:
/**
 * app.keyhandler
 *
 * @description
 * - main game controller
 *
 * @author
 * @version 0.1
 *
 * @namespace app
 *
 * @changelog
 * - 0.1 basic functions and module structur
 *
 * @see
 * - http://wesopeli.appspot.com
 *
 * @bugs
 * -
 *
 **/
(function (app) {

    'use strict';

    /**
     * undefined is used here as the undefined global
     * variable in ECMAScript 3 and is mutable (i.e. it can
     * be changed by someone else). undefined isn't really
     * being passed in so we can ensure that its value is
     * truly undefined. In ES5, undefined can no longer be
     * modified.
     *
     * window and document are passed through as local
     * variables rather than as globals, because this (slightly)
     * quickens the resolution process and can be more
     * efficiently minified (especially when both are
     * regularly referenced in your plugin).
     *
     */

    var keyhandler = (function () {

        // select all posible keys
        var keys = [],
            i = 0;

        for (i = 0; i < 256; i = i + 1) {
            keys[i] = false;
        }

        /**
         * check for up movement
         *
         */
        function up() {
            /**
             * arrow up
             * Nintendo Wii up
             * char w
             */
            return keys[38] || keys[175] || keys[87];
        }

        /**
         * check for down movement
         *
         */
        function down() {
            /**
             * arrow down
             * Nintendo Wii down
             * char s
             */
            return keys[40] || keys[176] || keys[83];
        }

        /**
         * check for left movement
         *
         */
        function left() {
            /**
             * arrow left
             * Nintendo Wii left
             * char a
             */
            return keys[37] || keys[178] || keys[65];
        }

        /**
         * check for right movement
         *
         */
        function right() {
            /**
             * arrow right
             * Nintendo Wii right
             * char d
             */
            return keys[39] || keys[177] || keys[68];
        }

        /**
         * check for spacebar
         *
         */
        function spacebar() {
            /**
             * char space
             */
            return keys[32];
        }

        /**
         * set keydown
         *
         */
        function keydown(e) {
            var keycode = e.keyCode;
            keys[keycode] = true;

            if (spacebar()) {
                app.pacman.pause();
            }
        }

        /**
         * set keyup
         *
         */
        function keyup(e) {
            var keycode = e.keyCode;
            keys[keycode] = false;
        }

        /**
         * get current movement
         *
         */
        function getMovement() {

            // init local vars
            var movement = {
                x: 0,
                y: 0,
                objectRotation: null
            };

            // else if because we allow only one way movement at a time
            if (up()) {
                movement.y = -1;
                movement.objectRotation = 270;
            } else if (down()) {
                movement.y = 1;
                movement.objectRotation = 90;
            } else if (left()) {
                movement.x = -1;
                movement.objectRotation = 180;
            } else if (right()) {
                movement.x = 1;
                movement.objectRotation = 0;
            }

            // there is no movement
            if (movement.objectRotation === null) {
                return null;
            }

            // return current movement if found
            return movement;
        }

        /**
         * @interface
         *
         */
        return {
            keydown: keydown,
            keyup: keyup,
            getMovement: getMovement
        };

    })();

    /**
     * global export
     *
     * @export
     */
    app.namespace('pacman.keyhandler', keyhandler);

}(window.getNamespace()));


text:
PACKAGE_NAME="aria-query"
PACKAGE_VERSION=${1:-"v4.2.2"}
PACKAGE_URL="https://github.com/A11yance/aria-query"
OS_NAME=$(grep ^PRETTY_NAME /etc/os-release | cut -d= -f2)
HOME_DIR=$PWD
export NODE_VERSION=${NODE_VERSION:-v12}
export PATH=$PATH:$HOME_DIR/$PACKAGE_NAME/node_modules/.bin

yum install -y git

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc

nvm install "$NODE_VERSION"
npm install -g npm@6

HOME_DIR=$PWD

echo "cloning..."
if ! git clone -q $PACKAGE_URL $PACKAGE_NAME; then
	echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails"
	exit 1
fi

cd "$HOME_DIR"/$PACKAGE_NAME || exit 1
git checkout "$PACKAGE_VERSION" || exit 1
export ESLINT=${1:-6}
npm uninstall --no-save eslint-config-airbnb-base
npm install --no-save eslint@"$ESLINT"

if ! npm install && npm audit fix; then
	echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_Fails"
	exit 1
fi

cd "$HOME_DIR"/$PACKAGE_NAME || exit 1
if ! npm run | grep -q "test"; then
	echo "------------------$PACKAGE_NAME:install_success_but_test_not_present---------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub |  |  Install_success_but_test_not_present"
	exit 0
fi

npm run build
if ! npm run jest; then
	echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_success_but_test_Fails"
	exit 1
else
	echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub  | Pass |  Both_Install_and_Test_Success"
	exit 0
fi


text:
layout: external
title: Variational Sparse Coding
description: ICLR Reproducibility Challenge 2019
img: /assets/img/VariationalSparseCoding.png
external_url: https://github.com/Alfo5123/Variational-Sparse-Coding
---


text:
package chapter05_thread.t02_base;

public class T04_ThreadLocalTest {

	static class ResourceClass {

		public final static ThreadLocal<String> RESOURCE_1 = new ThreadLocal<String>();

		public final static ThreadLocal<String> RESOURCE_2 = new ThreadLocal<String>();

	}

	static class A {

		public void setOne(String value) {
			ResourceClass.RESOURCE_1.set(value);
		}

		public void setTwo(String value) {
			ResourceClass.RESOURCE_2.set(value);
		}
	}

	static class B {
		public void display() {
			System.out.println(ResourceClass.RESOURCE_1.get() + ":" + ResourceClass.RESOURCE_2.get());
		}
	}

	public static void main(String[] args) {
		final A a = new A();
		final B b = new B();
		for (int i = 0; i < 15; i++) {
			final String resouce1 = "Ïß³Ì-" + i,
					     resouce2 = " value = (" + i + ")";
			new Thread() {
				public void run() {
					try {
						a.setOne(resouce1);
						a.setTwo(resouce2);
						b.display();
					} finally {
						ResourceClass.RESOURCE_1.remove();
						ResourceClass.RESOURCE_2.remove();
					}
				}
			}.start();
		}
	}
}


text:
package rest

import (
	"net/http"
	"net/url"
	"testing"

	"github.com/couchbaselabs/go.assert"
)

func TestGetRestrictedIntQuery(t *testing.T) {

	defaultValue := uint64(42)
	minValue := uint64(20)
	maxValue := uint64(100)

	// make sure it returns default value when passed empty Values
	values := make(url.Values)
	restricted := getRestrictedIntQuery(
		values,
		"foo",
		defaultValue,
		minValue,
		maxValue,
		false,
	)
	assert.Equals(t, restricted, defaultValue)

	// make sure it returns default value when passed Values that doesn't contain key
	values.Set("bar", "99")
	restricted = getRestrictedIntQuery(
		values,
		"foo",
		defaultValue,
		minValue,
		maxValue,
		false,
	)
	assert.Equals(t, restricted, defaultValue)

	// make sure it returns appropriate value from Values
	values.Set("foo", "99")
	restricted = getRestrictedIntQuery(
		values,
		"foo",
		defaultValue,
		minValue,
		maxValue,
		false,
	)
	assert.Equals(t, restricted, uint64(99))

	// make sure it is limited to max when value value is over max
	values.Set("foo", "200")
	restricted = getRestrictedIntQuery(
		values,
		"foo",
		defaultValue,
		minValue,
		maxValue,
		false,
	)
	assert.Equals(t, restricted, maxValue)

	// make sure it is limited to min when value value is under min
	values.Set("foo", "1")
	restricted = getRestrictedIntQuery(
		values,
		"foo",
		defaultValue,
		minValue,
		maxValue,
		false,
	)
	assert.Equals(t, restricted, minValue)

	// Return zero when allowZero=true
	values.Set("foo", "0")
	restricted = getRestrictedIntQuery(
		values,
		"foo",
		defaultValue,
		minValue,
		maxValue,
		true,
	)
	assert.Equals(t, restricted, uint64(0))

	// Return minValue when allowZero=false
	values.Set("foo", "0")
	restricted = getRestrictedIntQuery(
		values,
		"foo",
		defaultValue,
		minValue,
		maxValue,
		false,
	)
	assert.Equals(t, restricted, minValue)
}

func TestParseHTTPRangeHeader(t *testing.T) {
	// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
	type testcase struct {
		header        string
		contentLength uint64
		status        int
		start         uint64
		end           uint64
	}
	testcases := []testcase{
		// No Range: header at all:
		{"", 100, http.StatusOK, 0, 0},

		// Syntactically invalid Range headers are ignored:
		{"lolwut", 100, http.StatusOK, 0, 0},
		{"inches=-", 100, http.StatusOK, 0, 0},
		{"bytes=-", 100, http.StatusOK, 0, 0},
		{"bytes=50-bar", 100, http.StatusOK, 0, 0},
		{"bytes=50-49", 100, http.StatusOK, 0, 0},                  // invalid, not unsatisfiable
		{"bytes=99999999999999999999-1", 100, http.StatusOK, 0, 0}, // again, invalid

		// These requests return the entire document:
		{"bytes=0-", 100, http.StatusOK, 0, 0},
		{"bytes=0-99", 100, http.StatusOK, 0, 0},
		{"bytes=-100", 100, http.StatusOK, 0, 0},
		{"bytes=-99999999999999999999", 100, http.StatusOK, 0, 0},

		// Not satisfiable:
		{"bytes=100-", 100, http.StatusRequestedRangeNotSatisfiable, 0, 0},
		{"bytes=100-200", 100, http.StatusRequestedRangeNotSatisfiable, 0, 0},
		{"bytes=100-99999999999999999999", 100, http.StatusRequestedRangeNotSatisfiable, 0, 0},
		{"bytes=-0", 100, http.StatusRequestedRangeNotSatisfiable, 0, 0},

		{"bytes=10-", 100, http.StatusPartialContent, 10, 99},
		{"bytes=-10", 100, http.StatusPartialContent, 90, 99},
		{"bytes=0-0", 100, http.StatusPartialContent, 0, 0},
		{"bytes=50-60", 100, http.StatusPartialContent, 50, 60},
		{"bytes=99-", 100, http.StatusPartialContent, 99, 99},
		{"bytes=99-200", 100, http.StatusPartialContent, 99, 99},
		{"bytes=90-200", 100, http.StatusPartialContent, 90, 99},
		{"bytes=90-99999999999999999999", 100, http.StatusPartialContent, 90, 99},
		{"bytes=2-98", 100, http.StatusPartialContent, 2, 98},

		// Test with empty content:
		{"bytes=-1", 0, http.StatusOK, 0, 0},
		{"bytes=-10", 0, http.StatusOK, 0, 0},
		{"bytes=0-0", 0, http.StatusRequestedRangeNotSatisfiable, 0, 0},
		{"bytes=0-49", 0, http.StatusRequestedRangeNotSatisfiable, 0, 0},
		{"bytes=1-1", 0, http.StatusRequestedRangeNotSatisfiable, 0, 0},
		{"bytes=-0", 0, http.StatusRequestedRangeNotSatisfiable, 0, 0},
	}

	for _, expected := range testcases {
		status, start, end := parseHTTPRangeHeader(expected.header, expected.contentLength)
		t.Logf("*** Range: %s  --> %d %d-%d", expected.header, status, start, end)
		assert.Equals(t, status, expected.status)
		if status == http.StatusPartialContent {
			assert.Equals(t, start, expected.start)
			assert.Equals(t, end, expected.end)
		}
	}
}


text:
package eu.ydp.empiria.player.client.controller.feedback;

import com.google.common.collect.Maps;
import eu.ydp.empiria.player.client.controller.variables.objects.outcome.Outcome;

import java.util.Map;

public class OutcomeListBuilder {

    private final Map<String, Outcome> map;

    public OutcomeListBuilder() {
        this.map = Maps.newHashMap();
    }

    public static OutcomeListBuilder init() {
        return new OutcomeListBuilder();
    }

    public OutcomeListBuilder put(Outcome outcome) {
        map.put(outcome.identifier, outcome);
        return this;
    }

    public Map<String, Outcome> getMap() {
        return map;
    }
}


text:
var app = angular.module("myApp", []);

'use strict';

app.controller("formCtrl", ["$scope", function ($scope) {

    $scope.submit = function () {
        console.log($scope.form1);
        console.log($scope.form1.username);
        console.log($scope.form1.password);
        console.log($scope.form1.email);
    }
}]);


text:
jcmp.events.AddRemoteCallable('adminsys_server_doAction', function(player, action, data) {

  //console.log(action);

  if(Object.keys(adminsys.actions).indexOf(action) >= 0) {
    // Do action
    //console.log(data);
    //console.log(typeof(data));
    adminsys.actions[action](player, JSON.parse(data)); // FIXME
  } else {

    // Toast with error
    jcmp.events.Call('toast_show', player,  {
        heading: 'Error',
        text: "Was an error trying to execute the action required, action not found",
        icon: 'error',
        loader: true,
        loaderBg: '#9EC600',
        position: 'top-right',
        hideAfter: 5000
    });

  }
});

/*jcmp.events.AddRemoteCallable('adminsys_server_doAction', function(player, action, data) {
  console.log(action);
  jcmp.events.Call(player, action, JSON.parse(data));
});*/

jcmp.events.AddRemoteCallable('adminsys/server/client_request_update_playerList', function(player) {
  var playerList = jcmp.players.map(function(x) {
    return {networkId: x.networkId, name: x.escapedNametagName, adminlevel: x.admin.rank, steamId: x.client.steamId }
  });

  //console.log(playerList);
  jcmp.events.CallRemote('adminsys/client/response_update_playerList', player, JSON.stringify(playerList));
});

jcmp.events.AddRemoteCallable('adminsys/client/req/update_banlist', function(player) {

  adminsys.mongodb.connect(adminsys.config.mongodb.url, function(err, db) {
    var collection = db.collection('banlist');

    collection.find({}).sort({ date_start: -1 }).limit(35).toArray(function(err, result) {
      if(!err) {
        /*console.log("BanList result:");
        console.log(result);*/

        jcmp.events.CallRemote('adminsys/server/res/update_banlist', player, JSON.stringify(result));
      }
      db.close();
    });
  });

});

/*
jcmp.events.AddRemoteCallable('adminsys/server/request_unban_player', function(player, targetData) {
  adminsys.actions.unbanPlayer(player, targetData);
});
*/

jcmp.events.AddRemoteCallable('adminsys/server/searchBanPlayer', function(player, data) {

  if(player.admin.rank < 1) { // Avoid DDOS
    return;
  }

  var validFilters = ['name', 'steamid'];
  data = JSON.parse(data);
  console.log(data)

  if(validFilters.indexOf(data.filter) === -1) {
    return adminsys.chat.send(player, "Error: invalid search filter");
  }

  if(data.filter === 'steamid') {
    data.filter = 'steamId';
  }

  adminsys.mongodb.connect(adminsys.config.mongodb.url, function(err, db) {

    var collection = db.collection('banlist');

    var findQuery = {};
    // '' + data.filter + '': new RegExp('^' + data.value, 'i')
    findQuery[data.filter] = new RegExp('^' + data.value, 'i');
    //console.log(findQuery);

    collection.find(findQuery).sort({ date_start: -1 }).limit(35).toArray(function(err, result) { // Limited to 35 more can crash server
      //console.log(result);
      if(!err) {
        jcmp.events.CallRemote('adminsys/server/res/update_banlist', player, JSON.stringify(result));
      }
      db.close();
    });
  });

});

// Spawn things

jcmp.events.AddRemoteCallable('adminsys/server/spawnVehicle', function(player, hash) {

  console.log(hash);

  if(player.admin.rank < 1) {
    // Toast with error
    jcmp.events.Call('toast_show', player,  {
        heading: 'Error',
        text: "You're not allowed to use this command",
        icon: 'error',
        loader: true,
        loaderBg: '#9EC600',
        position: 'top-right',
        hideAfter: 5000
    });
  }

  var vehicle = new Vehicle(hash, player.position, player.rotation);

});


text:
// Copyright (c) Umbraco.
// See LICENSE for more details.

using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Web.Common.DependencyInjection;

namespace Umbraco.Cms.Core.PropertyEditors
{
    /// <summary>
    /// Represents the configuration editor for the media picker value editor.
    /// </summary>
    public class MediaPickerConfigurationEditor : ConfigurationEditor<MediaPickerConfiguration>
    {
        // Scheduled for removal in v12
        [Obsolete("Please use constructor that takes an IEditorConfigurationParser instead")]
        public MediaPickerConfigurationEditor(IIOHelper ioHelper)
            : this(ioHelper, StaticServiceProvider.Instance.GetRequiredService<IEditorConfigurationParser>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MediaPickerConfigurationEditor"/> class.
        /// </summary>
        public MediaPickerConfigurationEditor(IIOHelper ioHelper, IEditorConfigurationParser editorConfigurationParser) : base(ioHelper, editorConfigurationParser)
        {
            // configure fields
            // this is not part of ContentPickerConfiguration,
            // but is required to configure the UI editor (when editing the configuration)
            Field(nameof(MediaPickerConfiguration.StartNodeId))
                .Config = new Dictionary<string, object> { { "idType", "udi" } };
        }

        public override IDictionary<string, object> ToValueEditor(object? configuration)
        {
            // get the configuration fields
            var d = base.ToValueEditor(configuration);

            // add extra fields
            // not part of ContentPickerConfiguration but used to configure the UI editor
            d["idType"] = "udi";

            return d;
        }
    }
}


text:
#include <Firmata.h>
#include <DigitalInputFirmata.h>

DigitalInputFirmata *DigitalInputFirmataInstance;

void reportDigitalInputCallback(byte port, int value)
{
  DigitalInputFirmataInstance->reportDigital(port,value);
}

DigitalInputFirmata::DigitalInputFirmata()
{
  DigitalInputFirmataInstance = this;
  Firmata.attach(REPORT_DIGITAL, reportDigitalInputCallback);
}

boolean DigitalInputFirmata::handleSysex(byte command, byte argc, byte* argv)
{
  return false;
}

void DigitalInputFirmata::outputPort(byte portNumber, byte portValue, byte forceSend)
{
  // pins not configured as INPUT are cleared to zeros
  portValue = portValue & portConfigInputs[portNumber];
  // only send if the value is different than previously sent
  if(forceSend || previousPINs[portNumber] != portValue) {
    Firmata.sendDigitalPort(portNumber, portValue);
    previousPINs[portNumber] = portValue;
  }
}

/* -----------------------------------------------------------------------------
 * check all the active digital inputs for change of state, then add any events
 * to the Serial output queue using Serial.print() */
void DigitalInputFirmata::report(void)
{
  /* Using non-looping code allows constants to be given to readPort().
   * The compiler will apply substantial optimizations if the inputs
   * to readPort() are compile-time constants. */
  if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false);
  if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false);
  if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false);
  if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false);
  if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false);
  if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false);
  if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false);
  if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false);
  if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false);
  if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false);
  if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false);
  if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false);
  if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false);
  if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false);
  if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false);
  if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false);
}

void DigitalInputFirmata::reportDigital(byte port, int value)
{
  if (port < TOTAL_PORTS) {
    reportPINs[port] = (byte)value;
    if (value) outputPort(port, readPort(port, portConfigInputs[port]), true);
  }
  // do not disable analog reporting on these 8 pins, to allow some
  // pins used for digital, others analog.  Instead, allow both types
  // of reporting to be enabled, but check if the pin is configured
  // as analog when sampling the analog inputs.  Likewise, while
  // scanning digital pins, portConfigInputs will mask off values from any
  // pins configured as analog
}

boolean DigitalInputFirmata::handlePinMode(byte pin, int mode)
{
  if (IS_PIN_DIGITAL(pin)) {
    if (mode == INPUT) {
      portConfigInputs[pin/8] |= (1 << (pin & 7));
      pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver
      digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
      return true;
    } else {
      portConfigInputs[pin/8] &= ~(1 << (pin & 7));
    }
  }
  return false;
}

void DigitalInputFirmata::handleCapability(byte pin)
{
  if (IS_PIN_DIGITAL(pin)) {
    Firmata.write((byte)INPUT);
    Firmata.write(1);
  }
}

void DigitalInputFirmata::reset()
{
  for (byte i=0; i < TOTAL_PORTS; i++) {
    reportPINs[i] = false;      // by default, reporting off
    portConfigInputs[i] = 0;    // until activated
    previousPINs[i] = 0;
  }
}


text:
CKEDITOR.editorConfig = function( config ) {
	// Define changes to default configuration here.
	// For complete reference see:
	// http://docs.ckeditor.com/#!/api/CKEDITOR.config

	// The toolbar groups arrangement, optimized for two toolbar rows.
	config.toolbarGroups = [
		{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
		{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
		{ name: 'links' },
		{ name: 'insert'},
		{ name: 'forms' },
		{ name: 'wuSlick' },
		{ name: 'tools' },
		{ name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
		{ name: 'others' },
		'/',
		{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
		{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
		{ name: 'styles' },
		{ name: 'colors' },
		{ name: 'about' }
	];

	// Remove some buttons provided by the standard plugins, which are
	// not needed in the Standard(s) toolbar.
	config.removeButtons = 'Underline,Subscript,Superscript';

	// Set the most common block elements.
	config.format_tags = 'p;h1;h2;h3;pre;div';

	// Simplify the dialog windows.
	config.removeDialogTabs = 'image:advanced;link:advanced';
	config.extraPlugins = 'slick';
	config.allowedContent = true;
	config.embed_provider = '//ckeditor.iframe.ly/api/oembed?url={url}&callback={callback}';

	// load external css into iframe
	config.contentsCss = ['/css/style.css'];
	config.bodyClass = 'editor long-text container';
};

// we don't need to set & store image height, for images
CKEDITOR.on( 'dialogDefinition', function( ev ) {
    var dialogName = ev.data.name;
	var dialogDefinition = ev.data.definition;
    if ( dialogName == 'image' || dialogName == 'image2' ) {
        var infoTab = dialogDefinition.getContents( 'info' );

        if( dialogName == 'image' ){
            infoTab.remove('txtHeight');
            infoTab.remove('ratioLock');
        }
        else{
            infoTab.remove('height');
            infoTab.remove('lock');
        }
    }
});


text:
import Math_turnsPerDegrees from './turnsPerDegrees';

export default function(n) {
	return n * Math_turnsPerDegrees;
}


text:
package emlab.gen.domain.market.electricity;

import org.neo4j.graphdb.Direction;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;

import emlab.gen.domain.technology.PowerGeneratingTechnology;
import emlab.gen.domain.technology.PowerGridNode;

/**
 * @author jrichstein
 *
 */
@NodeEntity
public class IntermittentTechnologyNodeLoadFactor {

    @RelatedTo(type = "LOADFACTOR_TECHNOLOGY", elementClass = PowerGeneratingTechnology.class, direction = Direction.OUTGOING)
    private PowerGeneratingTechnology technology;

    @RelatedTo(type = "LOADFACTOR_NODE", elementClass = PowerGridNode.class, direction = Direction.OUTGOING)
    private PowerGridNode node;

    private double[] loadFactors;

    public PowerGeneratingTechnology getTechnology() {
        return technology;
    }

    public void setTechnology(PowerGeneratingTechnology technology) {
        this.technology = technology;
    }

    public PowerGridNode getNode() {
        return node;
    }

    public void setNode(PowerGridNode node) {
        this.node = node;
    }

    public double[] getLoadFactors() {
        return loadFactors;
    }

    public void setLoadFactors(double[] loadFactors) {
        this.loadFactors = loadFactors;
    }

    public double getLoadFactorForSegmentId(int segmentId) {
        return loadFactors[segmentId - 1];
    }

    public double getLoadFactorForSegment(Segment segment) {
        return getLoadFactorForSegmentId(segment.getSegmentID());
    }

    public void setLoadFactorForSegmentId(int segmentId, double loadFactor) {
        loadFactors[segmentId - 1] = loadFactor;
    }

    public void setLoadFactorForSegment(Segment segment, double loadFactor) {
        setLoadFactorForSegmentId(segment.getSegmentID(), loadFactor);
    }

}


text:
/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://visualizationlibrary.org                                                   */
/*                                                                                */
/*  Copyright (c) 2005-2017, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef VL_GL_FUNCTION_WRAPPERS
#define VL_GL_FUNCTION_WRAPPERS

#ifndef VL_UNSUPPORTED_FUNC
  #define VL_UNSUPPORTED_FUNC() { Log::error( String().printf("The function \"%s\" is not supported by the current OpenGL implementation! (%s:%d).\n", __FUNCTION__, __FILE__, __LINE__) ); VL_TRAP(); }
#endif

namespace vl
{

  inline void VL_glBindBuffer( GLenum target, GLuint buffer )
  {
    if (glBindBuffer)
      glBindBuffer(target,buffer);
    else
    if (glBindBufferARB)
      glBindBufferARB(target,buffer);
    else
    {
      VL_CHECK( buffer == 0 );
    }
  }

  inline void VL_glGenBuffers( GLsizei n, GLuint * buffers)
  {
    if (glGenBuffers)
      glGenBuffers( n, buffers);
    else
    if (glGenBuffersARB)
      glGenBuffersARB( n, buffers);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glDeleteBuffers( GLsizei n, const GLuint * buffers)
  {
    if (glDeleteBuffers)
      glDeleteBuffers( n, buffers);
    else
    if (glDeleteBuffersARB)
      glDeleteBuffersARB( n, buffers);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glBufferData( GLenum target, GLsizeiptr size, const GLvoid * data, GLenum usage)
  {
    if (glBufferData)
      glBufferData( target, size, data, usage);
    else
    if (glBufferDataARB)
      glBufferDataARB( target, size, data, usage);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glBufferSubData( GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid * data)
  {
    if (glBufferSubData)
      glBufferSubData( target, offset, size, data );
    else
    if (glBufferSubDataARB)
      glBufferSubDataARB( target, offset, size, data);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void* VL_glMapBuffer( GLenum target, GLenum access)
  {
    if (glMapBuffer)
      return glMapBuffer( target, access);
    else
    if (glMapBufferARB)
      return glMapBufferARB( target, access);
    else
      VL_UNSUPPORTED_FUNC();
    return 0;
  }

  inline GLboolean VL_glUnmapBuffer(GLenum target)
  {
    if (glUnmapBuffer)
      return glUnmapBuffer( target );
    else
    if (glUnmapBufferARB)
      return glUnmapBufferARB( target );
    else
      VL_UNSUPPORTED_FUNC();
    return GL_FALSE;
  }

  //-----------------------------------------------------------------------------

  inline void VL_glSecondaryColor3f(float r, float g, float b)
  {
    if(glSecondaryColor3f)
      glSecondaryColor3f(r,g,b);
    else
    if(glSecondaryColor3fEXT)
      glSecondaryColor3fEXT(r,g,b);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glSecondaryColorPointer( GLint size, GLenum type, GLsizei stride, const GLvoid* pointer)
  {
    if(glSecondaryColorPointer)
      glSecondaryColorPointer(size, type, stride, (GLvoid*)pointer);
    else
    if(glSecondaryColorPointerEXT)
      glSecondaryColorPointerEXT(size, type, stride, (GLvoid*)pointer);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glFogCoordPointer( GLenum type, GLsizei stride, GLvoid* pointer )
  {
    if (glFogCoordPointer)
      glFogCoordPointer(type,stride,pointer);
    else
    if (glFogCoordPointerEXT)
      glFogCoordPointerEXT(type,stride,pointer);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glEnableVertexAttribArray( GLuint index )
  {
    if (glEnableVertexAttribArray)
      glEnableVertexAttribArray(index);
    else
    if (glEnableVertexAttribArrayARB)
      glEnableVertexAttribArrayARB(index);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glDisableVertexAttribArray( GLuint index )
  {
    if (glDisableVertexAttribArray)
      glDisableVertexAttribArray(index);
    else
    if (glDisableVertexAttribArrayARB)
      glDisableVertexAttribArrayARB(index);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glVertexAttribPointer( GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid * pointer)
  {
    if (glVertexAttribPointer) {
      glVertexAttribPointer(index, size, type, normalized, stride, pointer);
    }
    else
    if (glVertexAttribPointerARB) {
      glVertexAttribPointerARB(index, size, type, normalized, stride, pointer);
    }
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glVertexAttribIPointer(GLuint name, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer)
  {
    if(glVertexAttribIPointer)
      glVertexAttribIPointer(name, size, type, stride, pointer);
    else
    if (glVertexAttribIPointerEXT)
      glVertexAttribIPointerEXT(name, size, type, stride, pointer);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glVertexAttribLPointer(GLuint name, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer)
  {
    if(glVertexAttribLPointer)
      glVertexAttribLPointer(name, size, type, stride, pointer);
    else
    if(glVertexAttribLPointerEXT)
      glVertexAttribLPointerEXT(name, size, type, stride, pointer);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glClientActiveTexture(GLenum texture)
  {
    if(glClientActiveTexture)
      glClientActiveTexture(texture);
    else
    if (glClientActiveTextureARB)
      glClientActiveTextureARB(texture);
    else
    {
      VL_CHECK(texture == GL_TEXTURE0);
    }
  }

  inline void VL_glActiveTexture(GLenum texture)
  {
    if(glActiveTexture)
      glActiveTexture(texture);
    else
    if (glActiveTextureARB)
      glActiveTextureARB(texture);
    else
    {
      VL_CHECK(texture == GL_TEXTURE0);
    }
  }

  //-----------------------------------------------------------------------------

  inline void VL_glBlendFuncSeparate( GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
  {
    if (glBlendFuncSeparate)
      glBlendFuncSeparate( srcRGB, dstRGB, srcAlpha, dstAlpha);
    else
    if (glBlendFuncSeparateEXT)
      glBlendFuncSeparateEXT( srcRGB, dstRGB, srcAlpha, dstAlpha);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glBlendEquationSeparate( GLenum modeRGB, GLenum modeAlpha)
  {
    if (glBlendEquationSeparate)
      glBlendEquationSeparate(modeRGB, modeAlpha);
    else
    if(glBlendEquationSeparateEXT)
      glBlendEquationSeparateEXT(modeRGB, modeAlpha);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glBlendEquation(GLenum mode)
  {
    if (glBlendEquation)
      glBlendEquation(mode);
    else
    if (glBlendEquationEXT)
      glBlendEquationEXT(mode);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glBlendColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
  {
    if(glBlendColor)
      glBlendColor(red,green,blue,alpha);
    else
    if (glBlendColorEXT)
      glBlendColorEXT(red,green,blue,alpha);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glPointParameterfv( GLenum pname, const GLfloat* params)
  {
    if (glPointParameterfv)
      glPointParameterfv(pname,(GLfloat*)params);
    else
    if (glPointParameterfvARB)
      glPointParameterfvARB(pname,(GLfloat*)params);
    else
    if (glPointParameterfvEXT)
      glPointParameterfvEXT(pname,(GLfloat*)params);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glPointParameterf( GLenum pname, GLfloat param)
  {
    if (glPointParameterf)
      glPointParameterf(pname,param);
    else
    if (glPointParameterfARB)
      glPointParameterfARB(pname,param);
    else
    if (glPointParameterfEXT)
      glPointParameterfEXT(pname,param);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glPointParameteri( GLenum pname, GLenum param)
  {
    if (glPointParameteri)
      glPointParameteri(pname,param);
    else
    if (glPointParameteriNV)
      glPointParameteriNV(pname,param);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glStencilFuncSeparate( GLenum face, GLenum func, GLint ref, GLuint mask)
  {
    if (glStencilFuncSeparate)
      glStencilFuncSeparate( face, func, ref, mask );
    else
      VL_UNSUPPORTED_FUNC();
    // NOT SUPPORTED
    // see also http://www.opengl.org/registry/specs/ATI/separate_stencil.txt
    /*else
    if ( Has_GL_ATI_separate_stencil )
      glStencilFuncSeparateATI( GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask ) */
  }

  inline void VL_glStencilOpSeparate( GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)
  {
    if (glStencilOpSeparate)
      glStencilOpSeparate( face, sfail, dpfail, dppass );
    else
      VL_UNSUPPORTED_FUNC();
    // NOT SUPPORTED
    // see also http://www.opengl.org/registry/specs/ATI/separate_stencil.txt
    /*else
    if ( Has_GL_ATI_separate_stencil )
      glStencilOpSeparateATI( GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass )*/
  }

  //-----------------------------------------------------------------------------

  inline void VL_glSampleCoverage( GLclampf value, GLboolean invert)
  {
    if (glSampleCoverage)
      glSampleCoverage(value,invert);
    else
    if (glSampleCoverageARB)
      glSampleCoverageARB(value,invert);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glBindRenderbuffer(GLenum target, GLuint renderbuffer)
  {
    if (glBindRenderbuffer)
      glBindRenderbuffer(target, renderbuffer);
    else
    if (glBindRenderbufferEXT)
      glBindRenderbufferEXT(target, renderbuffer);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers)
  {
    if (glDeleteRenderbuffers)
      glDeleteRenderbuffers(n, renderbuffers);
    else
    if (glDeleteRenderbuffersEXT)
      glDeleteRenderbuffersEXT(n, renderbuffers);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glGenRenderbuffers(GLsizei n, GLuint *renderbuffers)
  {
    if (glGenRenderbuffers)
      glGenRenderbuffers(n, renderbuffers);
    else
    if (glGenRenderbuffersEXT)
      glGenRenderbuffersEXT(n, renderbuffers);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
  {
    if (glRenderbufferStorage)
      glRenderbufferStorage(target, internalformat, width, height);
    else
    if (glRenderbufferStorageEXT)
      glRenderbufferStorageEXT(target, internalformat, width, height);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint *params)
  {
    if (glGetRenderbufferParameteriv)
      glGetRenderbufferParameteriv(target, pname, params);
    else
    if (glGetRenderbufferParameterivEXT)
      glGetRenderbufferParameterivEXT(target, pname, params);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline GLboolean VL_glIsFramebuffer(GLuint framebuffer)
  {
    if (glIsFramebuffer)
      return glIsFramebuffer(framebuffer);
    else
    if (glIsFramebufferEXT)
      return glIsFramebufferEXT(framebuffer);
    else
      VL_UNSUPPORTED_FUNC();
    return GL_FALSE;
  }

  inline void VL_glBindFramebuffer(GLenum target, GLuint framebuffer)
  {
    if (glBindFramebuffer)
      glBindFramebuffer(target, framebuffer);
    else
    if (glBindFramebufferEXT)
      glBindFramebufferEXT(target, framebuffer);
    else
    {
      VL_CHECK(framebuffer == 0);
    }
  }

  inline void VL_glDeleteFramebuffers(GLsizei n, const GLuint *framebuffers)
  {
    if (glDeleteFramebuffers)
      glDeleteFramebuffers(n, framebuffers);
    else
    if (glDeleteFramebuffersEXT)
      glDeleteFramebuffersEXT(n, framebuffers);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glGenFramebuffers(GLsizei n, GLuint *framebuffers)
  {
    if (glGenFramebuffers)
      glGenFramebuffers(n, framebuffers);
    else
    if (glGenFramebuffersEXT)
      glGenFramebuffersEXT(n, framebuffers);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline GLenum VL_glCheckFramebufferStatus(GLenum target)
  {
    if (glCheckFramebufferStatus)
      return glCheckFramebufferStatus(target);
    else
    if (glCheckFramebufferStatusEXT)
      return glCheckFramebufferStatusEXT(target);
    else
      VL_UNSUPPORTED_FUNC();

    return GL_FRAMEBUFFER_UNSUPPORTED;
  }

  inline void VL_glFramebufferTexture1D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
  {
    if (glFramebufferTexture1D)
      glFramebufferTexture1D(target, attachment, textarget, texture, level);
    else
    if (glFramebufferTexture1DEXT)
      glFramebufferTexture1DEXT(target, attachment, textarget, texture, level);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
  {
    if (glFramebufferTexture2D)
      glFramebufferTexture2D(target, attachment, textarget, texture, level);
    else
    if (glFramebufferTexture2DEXT)
      glFramebufferTexture2DEXT(target, attachment, textarget, texture, level);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //inline void VL_glFramebufferTexture3D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset)
  //{
  //  if (glFramebufferTexture3D)
  //    glFramebufferTexture3D(target, attachment, textarget, texture, level, zoffset);
  //  else
  //  if (glFramebufferTexture3DEXT)
  //    glFramebufferTexture3DEXT(target, attachment, textarget, texture, level, zoffset);
  //  else
  //    VL_UNSUPPORTED_FUNC();
  //}

  inline void VL_glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
  {
    if (glFramebufferRenderbuffer)
      glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer);
    else
    if (glFramebufferRenderbufferEXT)
      glFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint *params)
  {
    if (glGetFramebufferAttachmentParameteriv)
      glGetFramebufferAttachmentParameteriv(target,attachment,pname,params);
    else
    if (glGetFramebufferAttachmentParameterivEXT)
      glGetFramebufferAttachmentParameterivEXT(target,attachment,pname,params);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glGenerateMipmap(GLenum target)
  {
    if (glGenerateMipmap)
      glGenerateMipmap(target);
    else
    if (glGenerateMipmapEXT)
      glGenerateMipmapEXT(target);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glFramebufferTexture(GLenum target, GLenum attachment, GLuint texture, GLint level)
  {
    // even if this extension is signed ad ARB it does not appear in the GL 3.0 specs
    if (glFramebufferTextureARB)
      glFramebufferTextureARB(target,attachment,texture,level);
    else
    if (glFramebufferTextureEXT)
      glFramebufferTextureEXT(target,attachment,texture,level);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glFramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)
  {
    if (glFramebufferTextureLayer)
      glFramebufferTextureLayer(target, attachment, texture, level, layer);
    else
    if (glFramebufferTextureLayerARB)
      glFramebufferTextureLayerARB(target, attachment, texture, level, layer);
    else
    if (glFramebufferTextureLayerEXT)
      glFramebufferTextureLayerEXT(target, attachment, texture, level, layer);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glRenderbufferStorageMultisample( GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height )
  {
    if (glRenderbufferStorageMultisample)
      glRenderbufferStorageMultisample(target, samples, internalformat, width, height);
    else
    if (glRenderbufferStorageMultisampleEXT)
      glRenderbufferStorageMultisampleEXT(target, samples, internalformat, width, height);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
  {
    if (glBlitFramebuffer)
      glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
    else
    if (glBlitFramebufferEXT)
      glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount)
  {
    if (glDrawElementsInstanced)
      glDrawElementsInstanced(mode, count, type, indices, primcount);
    else
    if (glDrawElementsInstancedARB)
      glDrawElementsInstancedARB(mode, count, type, indices, primcount);
    else
    if (glDrawElementsInstancedEXT)
      glDrawElementsInstancedEXT(mode, count, type, indices, primcount);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glDrawElementsInstancedBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount, int basevertex)
  {
    if (glDrawElementsInstancedBaseVertex)
      glDrawElementsInstancedBaseVertex(mode, count, type, indices, primcount, basevertex);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glDrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, int basevertex)
  {
    if (glDrawElementsBaseVertex)
      glDrawElementsBaseVertex(mode, count, type, (void*)indices, basevertex);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glDrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices, int basevertex)
  {
    if (glDrawRangeElementsBaseVertex)
      glDrawRangeElementsBaseVertex(mode, start, end, count, type, (void*)indices, basevertex);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
  {
    if (glDrawArraysInstanced)
      glDrawArraysInstanced(mode, first, count, primcount);
    else
    if (glDrawArraysInstancedARB)
      glDrawArraysInstancedARB(mode, first, count, primcount);
    else
    if (glDrawArraysInstancedEXT)
      glDrawArraysInstancedEXT(mode, first, count, primcount);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline void VL_glProgramParameteri(GLuint program, GLenum pname, GLint value)
  {
    if (glProgramParameteriARB)
      glProgramParameteriARB(program, pname, value);
    else
    if (glProgramParameteriEXT)
      glProgramParameteriEXT(program, pname, value);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glBindFragDataLocation(GLuint program, GLuint colorNumber, const GLchar *name)
  {
    if (glBindFragDataLocation)
      glBindFragDataLocation(program, colorNumber, name);
    else
    if (glBindFragDataLocationEXT)
      glBindFragDataLocationEXT(program, colorNumber, name);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glUniform1uiv(GLint location, GLsizei count, const GLuint *value)
  {
    if (glUniform1uiv)
      glUniform1uiv(location, count, value);
    else
    if (glUniform1uivEXT)
      glUniform1uivEXT(location, count, value);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glUniform2uiv(GLint location, GLsizei count, const GLuint *value)
  {
    if (glUniform2uiv)
      glUniform2uiv(location, count, value);
    else
    if (glUniform2uivEXT)
      glUniform2uivEXT(location, count, value);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glUniform3uiv(GLint location, GLsizei count, const GLuint *value)
  {
    if (glUniform3uiv)
      glUniform3uiv(location, count, value);
    else
    if (glUniform3uivEXT)
      glUniform3uivEXT(location, count, value);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glUniform4uiv(GLint location, GLsizei count, const GLuint *value)
  {
    if (glUniform4uiv)
      glUniform4uiv(location, count, value);
    else
    if (glUniform4uivEXT)
      glUniform4uivEXT(location, count, value);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glGetProgramBinary(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary)
  {
    if (glGetProgramBinary)
      glGetProgramBinary(program, bufSize, length, binaryFormat, binary);
    else
      VL_UNSUPPORTED_FUNC();
  }
  inline void VL_glProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid *binary, GLint length)
  {
    if (glProgramBinary)
      glProgramBinary(program, binaryFormat, binary, length);
    else
      VL_UNSUPPORTED_FUNC();
  }

  inline void VL_glTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels)
  {
    if (glTexImage3D)
      glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels);
    else
      VL_UNSUPPORTED_FUNC();
  }
  inline void VL_glTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels)
  {
    if (glTexSubImage3D)
      glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
    else
      VL_UNSUPPORTED_FUNC();
  }
  inline void VL_glCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
  {
    if (glCopyTexSubImage3D)
      glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);
    else
      VL_UNSUPPORTED_FUNC();
  }
  inline void VL_glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data)
  {
    if (glCompressedTexImage3D)
      glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data);
    else
      VL_UNSUPPORTED_FUNC();
  }
  inline void VL_glCompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data)
  {
    if (glCompressedTexSubImage3D)
      glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
    else
      VL_UNSUPPORTED_FUNC();
  }
  inline void VL_glFramebufferTexture3D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset)
  {
    if (glFramebufferTexture3D)
      glFramebufferTexture3D(target, attachment, textarget, texture, level, zoffset);
    else
      VL_UNSUPPORTED_FUNC();
  }

  //-----------------------------------------------------------------------------

  inline std::string getOpenGLExtensions()
  {
    std::string ext;
    if (Has_GL_Version_3_0||Has_GL_Version_4_0)
    {
      int count = 0;
      glGetIntegerv(GL_NUM_EXTENSIONS, &count);
      for( int i=0; i<count; ++i )
      {
        ext += std::string((char*)glGetStringi(GL_EXTENSIONS, i)) + " ";
        VL_CHECK_OGL();
      }
    }
    else
    {
      VL_CHECK(glGetString(GL_EXTENSIONS));
      ext = (const char*)glGetString(GL_EXTENSIONS);
      // make sure also the last extension ends with a space
      ext.push_back(' ');
    }

    return ext;
  }

}

#endif


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = isVar;

var _generated = require("./generated");

var _constants = require("../constants");

function isVar(node) {
  return (0, _generated.isVariableDeclaration)(node, {
    kind: "var"
  }) && !node[_constants.BLOCK_SCOPED_SYMBOL];
}


text:
# Microsoft Application Insights JavaScript SDK

[Application Insights](https://azure.microsoft.com/services/application-insights/) tells you about your app's performance and usage. By adding a few lines of code to your web pages, you get data about how many users you have, which pages are most popular, how fast pages load, whether they throw exceptions, and more. And you can add code to track more detailed user activity.

## Try Application Insights with JavaScript SDK - no Azure subscription required
If you don't have an Azure subscription and would like to try Application Insights on one of your own web pages, visit [Try Application Insights Now](http://aka.ms/ainow).

## Get started

To use this SDK, you'll need a subscription to [Microsoft Azure](https://azure.com). (There's a free package.)

In the [Azure Preview Portal](https://portal.azure.com), open an Application Insights resource.

Get "code to monitor my web pages" from the Quick Start page, and insert it in the head of your web pages.

Use your web pages, and then look for user and page view results in the Application Insights resource.

[Learn more.](https://azure.microsoft.com/documentation/articles/app-insights-javascript/)

## API reference

Data on users, page views, and exceptions are provided out of the box. You can write your own code to track specific events and metrics.

* Check out https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md

## To build:

* Visual Studio 2013 Ultimate with Update 4
* Clone the Git repository
* Open Visual Studio solution (devenv JavaScript\Microsoft.ApplicationInsights.JavaScript.sln)
* Build solution in Visual Studio

## To run check-in tests
* `powershell "& .\RunTestsInBrowser.ps1"` to run `Tests.html` in a browser (you might need to call Set-ExecutionPolicy to be able to execute the script)
* Don't forget to build the solution after changing TypeScript files
* Refresh Tests.html in the browser to re-run tests

## Check out the Wiki for other useful info

https://github.com/Microsoft/ApplicationInsights-JS/wiki


text:
package org.bouncycastle.jce.provider;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.EllipticCurve;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DEROctetString;
// BEGIN android-removed
// import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
// import org.bouncycastle.asn1.cryptopro.ECGOST3410NamedCurves;
// import org.bouncycastle.asn1.cryptopro.GOST3410PublicKeyAlgParameters;
// END android-removed
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X962Parameters;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9ECPoint;
import org.bouncycastle.asn1.x9.X9IntegerConverter;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util;
import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil;
import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil;
// BEGIN android-removed
// import org.bouncycastle.jce.ECGOST3410NamedCurveTable;
// END android-removed
import org.bouncycastle.jce.interfaces.ECPointEncoder;
// BEGIN android-removed
// import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
// END android-removed
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.math.ec.ECCurve;

public class JCEECPublicKey
    implements ECPublicKey, org.bouncycastle.jce.interfaces.ECPublicKey, ECPointEncoder
{
    private String                  algorithm = "EC";
    private org.bouncycastle.math.ec.ECPoint q;
    private ECParameterSpec         ecSpec;
    private boolean                 withCompression;
    // BEGIN android-removed
    // private GOST3410PublicKeyAlgParameters       gostParams;
    // END android-removed

    public JCEECPublicKey(
        String              algorithm,
        JCEECPublicKey      key)
    {
        this.algorithm = algorithm;
        this.q = key.q;
        this.ecSpec = key.ecSpec;
        this.withCompression = key.withCompression;
        // BEGIN android-removed
        // this.gostParams = key.gostParams;
        // END android-removed
    }

    public JCEECPublicKey(
        String              algorithm,
        ECPublicKeySpec     spec)
    {
        this.algorithm = algorithm;
        this.ecSpec = spec.getParams();
        this.q = EC5Util.convertPoint(ecSpec, spec.getW(), false);
    }

    public JCEECPublicKey(
        String              algorithm,
        org.bouncycastle.jce.spec.ECPublicKeySpec     spec)
    {
        this.algorithm = algorithm;
        this.q = spec.getQ();

        if (spec.getParams() != null) // can be null if implictlyCa
        {
            ECCurve curve = spec.getParams().getCurve();
            EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

            this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
        }
        else
        {
            if (q.getCurve() == null)
            {
                org.bouncycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();

                q = s.getCurve().createPoint(q.getX().toBigInteger(), q.getY().toBigInteger(), false);
            }
            this.ecSpec = null;
        }
    }

    public JCEECPublicKey(
        String                  algorithm,
        ECPublicKeyParameters   params,
        ECParameterSpec         spec)
    {
        ECDomainParameters      dp = params.getParameters();

        this.algorithm = algorithm;
        this.q = params.getQ();

        if (spec == null)
        {
            EllipticCurve ellipticCurve = EC5Util.convertCurve(dp.getCurve(), dp.getSeed());

            this.ecSpec = createSpec(ellipticCurve, dp);
        }
        else
        {
            this.ecSpec = spec;
        }
    }

    public JCEECPublicKey(
        String                  algorithm,
        ECPublicKeyParameters   params,
        org.bouncycastle.jce.spec.ECParameterSpec         spec)
    {
        ECDomainParameters      dp = params.getParameters();

        this.algorithm = algorithm;
        this.q = params.getQ();

        if (spec == null)
        {
            EllipticCurve ellipticCurve = EC5Util.convertCurve(dp.getCurve(), dp.getSeed());

            this.ecSpec = createSpec(ellipticCurve, dp);
        }
        else
        {
            EllipticCurve ellipticCurve = EC5Util.convertCurve(spec.getCurve(), spec.getSeed());

            this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec);
        }
    }

    /*
     * called for implicitCA
     */
    public JCEECPublicKey(
        String                  algorithm,
        ECPublicKeyParameters   params)
    {
        this.algorithm = algorithm;
        this.q = params.getQ();
        this.ecSpec = null;
    }

    private ECParameterSpec createSpec(EllipticCurve ellipticCurve, ECDomainParameters dp)
    {
        return new ECParameterSpec(
                ellipticCurve,
                new ECPoint(
                        dp.getG().getX().toBigInteger(),
                        dp.getG().getY().toBigInteger()),
                        dp.getN(),
                        dp.getH().intValue());
    }

    public JCEECPublicKey(
        ECPublicKey     key)
    {
        this.algorithm = key.getAlgorithm();
        this.ecSpec = key.getParams();
        this.q = EC5Util.convertPoint(this.ecSpec, key.getW(), false);
    }

    JCEECPublicKey(
        SubjectPublicKeyInfo    info)
    {
        populateFromPubKeyInfo(info);
    }

    private void populateFromPubKeyInfo(SubjectPublicKeyInfo info)
    {
        // BEGIN android-removed
        // if (info.getAlgorithmId().getObjectId().equals(CryptoProObjectIdentifiers.gostR3410_2001))
        // {
        //     DERBitString bits = info.getPublicKeyData();
        //     ASN1OctetString key;
        //     this.algorithm = "ECGOST3410";
        //
        //     try
        //     {
        //         key = (ASN1OctetString) ASN1Primitive.fromByteArray(bits.getBytes());
        //     }
        //     catch (IOException ex)
        //     {
        //         throw new IllegalArgumentException("error recovering public key");
        //     }
        //
        //     byte[]          keyEnc = key.getOctets();
        //     byte[]          x = new byte[32];
        //     byte[]          y = new byte[32];
        //
        //     for (int i = 0; i != x.length; i++)
        //     {
        //         x[i] = keyEnc[32 - 1 - i];
        //     }
        //
        //     for (int i = 0; i != y.length; i++)
        //     {
        //         y[i] = keyEnc[64 - 1 - i];
        //     }
        //
        //     gostParams = new GOST3410PublicKeyAlgParameters((ASN1Sequence)info.getAlgorithmId().getParameters());
        //
        //     ECNamedCurveParameterSpec spec = ECGOST3410NamedCurveTable.getParameterSpec(ECGOST3410NamedCurves.getName(gostParams.getPublicKeyParamSet()));
        //
        //     ECCurve curve = spec.getCurve();
        //     EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getSeed());
        //
        //     this.q = curve.createPoint(new BigInteger(1, x), new BigInteger(1, y), false);
        //
        //     ecSpec = new ECNamedCurveSpec(
        //             ECGOST3410NamedCurves.getName(gostParams.getPublicKeyParamSet()),
        //             ellipticCurve,
        //             new ECPoint(
        //                     spec.getG().getX().toBigInteger(),
        //                     spec.getG().getY().toBigInteger()),
        //                     spec.getN(), spec.getH());
        //
        // }
        // else
        // END android-removed
        {
            X962Parameters params = new X962Parameters((ASN1Primitive)info.getAlgorithmId().getParameters());
            ECCurve                 curve;
            EllipticCurve           ellipticCurve;

            if (params.isNamedCurve())
            {
                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)params.getParameters();
                X9ECParameters ecP = ECUtil.getNamedCurveByOid(oid);

                curve = ecP.getCurve();
                ellipticCurve = EC5Util.convertCurve(curve, ecP.getSeed());

                ecSpec = new ECNamedCurveSpec(
                        ECUtil.getCurveName(oid),
                        ellipticCurve,
                        new ECPoint(
                                ecP.getG().getX().toBigInteger(),
                                ecP.getG().getY().toBigInteger()),
                        ecP.getN(),
                        ecP.getH());
            }
            else if (params.isImplicitlyCA())
            {
                ecSpec = null;
                curve = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getCurve();
            }
            else
            {
                X9ECParameters          ecP = X9ECParameters.getInstance(params.getParameters());

                curve = ecP.getCurve();
                ellipticCurve = EC5Util.convertCurve(curve, ecP.getSeed());

                this.ecSpec = new ECParameterSpec(
                        ellipticCurve,
                        new ECPoint(
                                ecP.getG().getX().toBigInteger(),
                                ecP.getG().getY().toBigInteger()),
                        ecP.getN(),
                        ecP.getH().intValue());
            }

            DERBitString    bits = info.getPublicKeyData();
            byte[]          data = bits.getBytes();
            ASN1OctetString key = new DEROctetString(data);

            //
            // extra octet string - one of our old certs...
            //
            if (data[0] == 0x04 && data[1] == data.length - 2
                && (data[2] == 0x02 || data[2] == 0x03))
            {
                int qLength = new X9IntegerConverter().getByteLength(curve);

                if (qLength >= data.length - 3)
                {
                    try
                    {
                        key = (ASN1OctetString) ASN1Primitive.fromByteArray(data);
                    }
                    catch (IOException ex)
                    {
                        throw new IllegalArgumentException("error recovering public key");
                    }
                }
            }
            X9ECPoint derQ = new X9ECPoint(curve, key);

            this.q = derQ.getPoint();
        }
    }

    public String getAlgorithm()
    {
        return algorithm;
    }

    public String getFormat()
    {
        return "X.509";
    }

    public byte[] getEncoded()
    {
        ASN1Encodable        params;
        SubjectPublicKeyInfo info;

        // BEGIN android-removed
        // if (algorithm.equals("ECGOST3410"))
        // {
        //     if (gostParams != null)
        //     {
        //         params = gostParams;
        //     }
        //     else
        //     {
        //         if (ecSpec instanceof ECNamedCurveSpec)
        //         {
        //             params = new GOST3410PublicKeyAlgParameters(
        //                            ECGOST3410NamedCurves.getOID(((ECNamedCurveSpec)ecSpec).getName()),
        //                            CryptoProObjectIdentifiers.gostR3411_94_CryptoProParamSet);
        //         }
        //         else
        //         {   // strictly speaking this may not be applicable...
        //             ECCurve curve = EC5Util.convertCurve(ecSpec.getCurve());
        //
        //             X9ECParameters ecP = new X9ECParameters(
        //                 curve,
        //                 EC5Util.convertPoint(curve, ecSpec.getGenerator(), withCompression),
        //                 ecSpec.getOrder(),
        //                 BigInteger.valueOf(ecSpec.getCofactor()),
        //                 ecSpec.getCurve().getSeed());
        //
        //             params = new X962Parameters(ecP);
        //         }
        //     }
        //
        //     BigInteger      bX = this.q.getX().toBigInteger();
        //     BigInteger      bY = this.q.getY().toBigInteger();
        //     byte[]          encKey = new byte[64];
        //
        //     extractBytes(encKey, 0, bX);
        //     extractBytes(encKey, 32, bY);
        //
        //     try
        //     {
        //         info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(CryptoProObjectIdentifiers.gostR3410_2001, params), new DEROctetString(encKey));
        //     }
        //     catch (IOException e)
        //     {
        //         return null;
        //     }
        // }
        // else
        // END android-removed
        {
            if (ecSpec instanceof ECNamedCurveSpec)
            {
                ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveSpec)ecSpec).getName());
                if (curveOid == null)
                {
                    curveOid = new ASN1ObjectIdentifier(((ECNamedCurveSpec)ecSpec).getName());
                }
                params = new X962Parameters(curveOid);
            }
            else if (ecSpec == null)
            {
                params = new X962Parameters(DERNull.INSTANCE);
            }
            else
            {
                ECCurve curve = EC5Util.convertCurve(ecSpec.getCurve());

                X9ECParameters ecP = new X9ECParameters(
                    curve,
                    EC5Util.convertPoint(curve, ecSpec.getGenerator(), withCompression),
                    ecSpec.getOrder(),
                    BigInteger.valueOf(ecSpec.getCofactor()),
                    ecSpec.getCurve().getSeed());

                params = new X962Parameters(ecP);
            }

            ECCurve curve = this.engineGetQ().getCurve();
            ASN1OctetString p = (ASN1OctetString)
                new X9ECPoint(curve.createPoint(this.getQ().getX().toBigInteger(), this.getQ().getY().toBigInteger(), withCompression)).toASN1Primitive();

            info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), p.getOctets());
        }

        return KeyUtil.getEncodedSubjectPublicKeyInfo(info);
    }

    private void extractBytes(byte[] encKey, int offSet, BigInteger bI)
    {
        byte[] val = bI.toByteArray();
        if (val.length < 32)
        {
            byte[] tmp = new byte[32];
            System.arraycopy(val, 0, tmp, tmp.length - val.length, val.length);
            val = tmp;
        }

        for (int i = 0; i != 32; i++)
        {
            encKey[offSet + i] = val[val.length - 1 - i];
        }
    }

    public ECParameterSpec getParams()
    {
        return ecSpec;
    }

    public org.bouncycastle.jce.spec.ECParameterSpec getParameters()
    {
        if (ecSpec == null)     // implictlyCA
        {
            return null;
        }

        return EC5Util.convertSpec(ecSpec, withCompression);
    }

    public ECPoint getW()
    {
        return new ECPoint(q.getX().toBigInteger(), q.getY().toBigInteger());
    }

    public org.bouncycastle.math.ec.ECPoint getQ()
    {
        if (ecSpec == null)
        {
            if (q instanceof org.bouncycastle.math.ec.ECPoint.Fp)
            {
                return new org.bouncycastle.math.ec.ECPoint.Fp(null, q.getX(), q.getY());
            }
            else
            {
                return new org.bouncycastle.math.ec.ECPoint.F2m(null, q.getX(), q.getY());
            }
        }

        return q;
    }

    public org.bouncycastle.math.ec.ECPoint engineGetQ()
    {
        return q;
    }

    org.bouncycastle.jce.spec.ECParameterSpec engineGetSpec()
    {
        if (ecSpec != null)
        {
            return EC5Util.convertSpec(ecSpec, withCompression);
        }

        return BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();
    }

    public String toString()
    {
        StringBuffer    buf = new StringBuffer();
        String          nl = System.getProperty("line.separator");

        buf.append("EC Public Key").append(nl);
        buf.append("            X: ").append(this.q.getX().toBigInteger().toString(16)).append(nl);
        buf.append("            Y: ").append(this.q.getY().toBigInteger().toString(16)).append(nl);

        return buf.toString();

    }

    public void setPointFormat(String style)
    {
       withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style));
    }

    public boolean equals(Object o)
    {
        if (!(o instanceof JCEECPublicKey))
        {
            return false;
        }

        JCEECPublicKey other = (JCEECPublicKey)o;

        return engineGetQ().equals(other.engineGetQ()) && (engineGetSpec().equals(other.engineGetSpec()));
    }

    public int hashCode()
    {
        return engineGetQ().hashCode() ^ engineGetSpec().hashCode();
    }

    private void readObject(
        ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        byte[] enc = (byte[])in.readObject();

        populateFromPubKeyInfo(SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(enc)));

        this.algorithm = (String)in.readObject();
        this.withCompression = in.readBoolean();
    }

    private void writeObject(
        ObjectOutputStream out)
        throws IOException
    {
        out.writeObject(this.getEncoded());
        out.writeObject(algorithm);
        out.writeBoolean(withCompression);
    }
}


text:
namespace Bridge.jQuery2
{
    [Ignore]
    public enum JqueryEventTarget
    {
        [Template("{0}")]
        Raw = 0,

        [Template("'{0}'")]
        Value
    }

    [Ignore]
    public abstract class AdapterAttribute : Bridge.AdapterAttribute
    {
        public const string Format = "$({1}).on('{0}', this.{2});";
    }

    [Ignore]
    public class jQueryEventAttribute : AdapterAttribute
    {
        public const bool IsCommonEvent = true;

        public jQueryEventAttribute(string eventName, string selector, JqueryEventTarget target = JqueryEventTarget.Value)
        {
        }
    }

    [Ignore]
    public class ClickAttribute : AdapterAttribute
    {
        public const string Event = "click";

        public ClickAttribute(string selector, JqueryEventTarget target = JqueryEventTarget.Value)
        {
        }
    }
}


text:
Configuration Guide
===================
This document describes how to configure vNIOS and the IPAM driver.

Introduction
------------
vNIOS is the Infoblox virtual appliance that you can download from the Infoblox Download Center:

- Point your browser to https://www.infoblox.com/infoblox-download-center
- Scroll down to the section "Network Service(DNS, DHCP, IPAM)"
- The product to download is "Infoblox DDI (DNS, DHCP, IPAM)". Click "Try it Now"
- This will take you through a brief registration screen.
- After registration is complete you will receive an email which includes a link that takes you to the "Product Evaluation Portal".

Setting up vNIOS
----------------
Once you're in the "Product Evaluation Portal", you can find download links as well as instructional videos. It is
strongly recommended that you download the VMware version of the product as VMware is the platform on which the videos
are based.

- Under section "Required Downloads", download "Infoblox DDI" for VMware.
- After download is complete, scroll down to section "Setup and Installation Videos"
- Follow the video instruction: "Video 1: Infoblox Cloud Network Automation Installation and Setup"
- Follow the video to completion, as the instruction to activate vNIOS "Cloud Network Automation" feature is in the later part of the video. (You can however skip over section on configuring DHCP and DNS, as well as section on "vRealization Orchestrator".

The following additional steps are required:
- You need to give cloud-api admin user permission to create and modify DNS Views. Instructions on how to add permission to "cloud-api-only" group is included in the video. Follow the same instructions to add "All DNS Views" permission under the "DNS Permissions" Permssion Type.

Manual Configuration of Cloud Extensible Attributes
---------------------------------------------------
If the "Cloud Network Automation" licensed feature is not activiated, the following Cloud Extensible Attributes must
be manually defined in Infoblox:

- ```Cloud API Owned``` - Type: List; Values: True, False

- ```CMP Type``` - Type: String

- ```Tenant ID``` - Type: String

The User Interface to add Extensible Attribute definitions can be found under the main tab "Administration" and under the
sub-tab "Extensible Attributes".

IPAM Driver Configuration
-------------------------
Based on the vNIOS configuration, update the following driver configuration:
- Set grid-host to the management IP address of vNIOS
- Set username and password to that for the Cloud Admin user on vNIOS.

These configurations can be applied by editing the "run.sh" and "run-container.sh" shell scripts.


text:
import * as React from 'react';
import PropTypes from 'prop-types';

import Portal from '@material-ui/core/Portal';
import CreateIcon from '@material-ui/icons/Create';
import Button from '@material-ui/core/Button';

class EditButton extends React.Component {
  static propTypes = {
    isOpened: PropTypes.bool,
    href: PropTypes.string,
    onClick: PropTypes.func,
  };

  static defaultProps = {
    isOpened: true,
    iconType: 'create',
    href: '',
    onClick: () => {},
  };

  onClick = e => {
    e.preventDefault();
    if (this.props.onClick) {
      this.props.onClick(e);
    }
  };

  render() {
    const { style, isOpened, iconType, href, onTouchTap, onClick, ...other } = this.props;
    const _style = {
      position: 'fixed',
      bottom: 20,
      right: 20,
    };
    const finalStyle = Object.assign(_style, style || {});
    return (
      <Portal>
        <Button {...other} variant="fab" style={finalStyle} href={href} onClick={this.onClick}>
          <CreateIcon />
        </Button>
      </Portal>
    );
  }
}

export default EditButton;


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.model.impl;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import com.archimatetool.model.IArchimatePackage;
import com.archimatetool.model.IInfluenceRelationship;
import org.eclipse.emf.common.notify.Notification;

/**
 *
 * An implementation of the model object 'Influence Relationship'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link com.archimatetool.model.impl.InfluenceRelationship#getStrength Strength}

 *

 *
 * @generated
 */
public class InfluenceRelationship extends ArchimateRelationship implements IInfluenceRelationship {
    /**
     * The default value of the '{@link #getStrength() Strength}' attribute.
     *
     *
     * @see #getStrength()
     * @generated
     * @ordered
     */
    protected static final String STRENGTH_EDEFAULT = ""; //$NON-NLS-1$
    /**
     * The cached value of the '{@link #getStrength() Strength}' attribute.
     *
     *
     * @see #getStrength()
     * @generated
     * @ordered
     */
    protected String strength = STRENGTH_EDEFAULT;

    /**
     *
     *
     * @generated
     */
    protected InfluenceRelationship() {
        super();
    }

    /**
     *
     *
     * @generated
     */
    @Override
    protected EClass eStaticClass() {
        return IArchimatePackage.Literals.INFLUENCE_RELATIONSHIP;
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public String getStrength() {
        return strength;
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public void setStrength(String newStrength) {
        String oldStrength = strength;
        strength = newStrength;
        if (eNotificationRequired())
            eNotify(new ENotificationImpl(this, Notification.SET, IArchimatePackage.INFLUENCE_RELATIONSHIP__STRENGTH, oldStrength, strength));
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public Object eGet(int featureID, boolean resolve, boolean coreType) {
        switch (featureID) {
            case IArchimatePackage.INFLUENCE_RELATIONSHIP__STRENGTH:
                return getStrength();
        }
        return super.eGet(featureID, resolve, coreType);
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public void eSet(int featureID, Object newValue) {
        switch (featureID) {
            case IArchimatePackage.INFLUENCE_RELATIONSHIP__STRENGTH:
                setStrength((String)newValue);
                return;
        }
        super.eSet(featureID, newValue);
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public void eUnset(int featureID) {
        switch (featureID) {
            case IArchimatePackage.INFLUENCE_RELATIONSHIP__STRENGTH:
                setStrength(STRENGTH_EDEFAULT);
                return;
        }
        super.eUnset(featureID);
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public boolean eIsSet(int featureID) {
        switch (featureID) {
            case IArchimatePackage.INFLUENCE_RELATIONSHIP__STRENGTH:
                return STRENGTH_EDEFAULT == null ? strength != null : !STRENGTH_EDEFAULT.equals(strength);
        }
        return super.eIsSet(featureID);
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public String toString() {
        if (eIsProxy()) return super.toString();

        StringBuilder result = new StringBuilder(super.toString());
        result.append(" (strength: "); //$NON-NLS-1$
        result.append(strength);
        result.append(')');
        return result.toString();
    }

} //InfluenceRelationship


text:
To run this demo you __need__ to start a special development server. To do that all you need to do is run the following commands:

```bash
npm install -g packin
make
```

This server just rebuilds the project when requested over http meaning you only need to refresh your browser after making changes. The underlying build tool is similar to browserify.

### windows

Unless however your on windows in which case your best hope is to run:

```bash
npm install -g packin
npm install -g jkroso/serve
packin install -e --folder node_modules --meta deps.json,component.json,package.json
serve
```

### component

Because I'm a fan of the component community (just not component(1) itself) I've also included "./demo/component.html" which works using normal component tooling. To run that:

```bash
component install
component build
open ./demo/component.html
```


text:
'''
Description:
    Given a binary tree, return the zigzag level order traversal of its nodes' values.
    (ie, from left to right, then right to left for the next level and alternate between).
    For example:
        Given binary tree {3,9,20,#,#,15,7},
            3
           / \
          9  20
            /  \
           15   7
        return its zigzag level order traversal as:
        [
          [3],
          [20,9],
          [15,7]
        ]

Tags: Tree, Breadth-first Search, Stack
Time: O(n); Space: O(n)
'''

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root is None:
            return []

        result = []
        current = [root]
        level = 1
        while current:
            next_level, vals = [], []
            for node in current:
                vals.append(node.val)
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)

            if level % 2 == 1:
                result.append(vals)
            else:
                result.append(vals[::-1])

            current = next_level
            level += 1
        return result

if __name__ == "__main__":
    root = TreeNode(3)
    root.left = TreeNode(9)
    root.right = TreeNode(20)
    root.right.left = TreeNode(15)
    root.right.right = TreeNode(7)
    print Solution().zigzagLevelOrder(root)


text:
*Harmonic average* of $n_1, n_2,\dots,n_k$ is

$\frac{k}{\frac{1}{n_1} + \cdots + \frac{1}{n_k}}$

For example, the harmonic average of 2, 2, 2 is 2,
and harmonic average of 1, 2, 3 is $18/11 \approx 1.636$

--

## HyperLogLog Algorithm

```python

class HyperLogLog(LogLog):
    # Everything else the same as LogLog except...

    # When sizing, use harmonic average instead
    def size(self):
        sizes = []
        for register in self.__registers:
            # count the number of consecutive 1's
            exp = first_zero(register) - 1
            sizes.push(floor(2 ** exp))

        return HLL_BIAS * harmonic_mean(sizes)
```

--

## Why does HLL work better?

LogLog's average puts too much weight on large values; solved
by using harmonic means.

--

## What are the benefits?

LogLog computation space

Linear algorithm

Much smaller variance: 96% confident that error is within
  $1.04/\sqrt{4m}$

--

## How about some benchmarks?

Setup: Redis HLL, input: Lorem Ipsum

```python
import redis

SET = set([])
REDIS_CLIENT = redis.StrictRedis(host="localhost",
                                 port=6379,
                                 db=0)
with open("lorem") as lorem_file:
    LOREM = lorem_file.read()

for word in LOREM.split(" "):
    word.strip(".,:;").lower()
    SET.add(word)
    REDIS_CLIENT.pfadd("lorem", word)

actual_size, hll_size = len(SET), REDIS_CLIENT.pfcount("lorem")

print actual_size, hll_size
print "Error: %s%" % (100 * actual_size - hll_size) / actual_size
```

--

## Results*

Lorem Size | Actual | HLL Size | Error
-----------|--------|----------|--------
   10,000  | 189    | 188      | 0.529 %
  100,000  | 843    | 821      | 2.610 %
1,000,000  | 1,302  | 1,294    | 0.614 %

*3 points don't a trend make


text:
import Phaser from 'phaser'

class BlockSprite extends Phaser.Sprite {

  constructor ({ game, x, y, asset }) {
    super(game, x, y, asset)
    this.anchor.setTo(0.5)
    this.inputEnabled = true
    this.setupDragEvents()
  }

  update () {}

  setBoundary (sprite) {
    this.input.boundsSprite = sprite
  }

  setupDragEvents () {
    this.events.onDragStart.add((...args) => {
      this.isDragging = true
    })

    this.events.onDragStop.add((...args) => {
      this.isDragging = false
    })
  }

  allowDrag (allowedDirections) {
    if (typeof allowedDirections === 'object') {
      this.input.allowVerticalDrag = !!allowedDirections.vertical
      this.input.allowHorizontalDrag = !!allowedDirections.horizontal

      if (allowedDirections.vertical || allowedDirections.horizontal) {
        this.input.enableDrag()
      } else {
        this.input.disableDrag()
      }
    } else {
      this.input.allowVerticalDrag = !!allowedDirections
      this.input.allowHorizontalDrag = !!allowedDirections

      if (allowedDirections) {
        this.input.enableDrag()
      } else {
        this.input.disableDrag()
      }
    }

    return this
  }

}

export default BlockSprite