text:
**Project Description**
Visual Studio extension for integrating MetaEdit+ and Visual Studio. This extension allows you to browse MetaEdit+ models and use the main MetaEdit+ functions from Visual Studio. It can also automatically import into Visual Studio the source code generated from MetaEdit+.

The integration between MetaEdit+ models and Visual Studio includes:

* One-click access to your {"MetaEdit+"} repository from Visual Studio
* Live tree view in Visual Studio of all your {"MetaEdit+"} models
* Double-click to open and edit {"MetaEdit+"} models from Visual Studio
* Autobuild: generate code from MetaEdit+ models, import into a Visual Studio solution, build and run
* Trace and debug on both the code and model levels simultaneously
Watch a [video (5min)](http://www.metacase.com/webcasts/IntegratingVisualStudioAndMetaEdit.html) demonstrating the use of the MetaEdit+ extension for Visual Studio.

See [installation instructions](InstallingInstructions), [getting started](GettingStarted) and the [plugin guide](AdvancedInstructions) for details. See the [plugin guide for developers](ExtendingThePluginGuide) and the [source code](http://graphbrowser.codeplex.com/SourceControl/list/changesets) for extending the plugin further.

![](Home_http://www.metacase.com/images/visual_studio_extension_with_metaedit.png)


text:
.panel-body {
	padding: inherit;
}

.panel-body .table {
	margin-bottom: inherit;
}

.tab-row {
	cursor: pointer;
}

redpajama_set_name: RedPajamaGithub


text:
package com.jagrosh.jdautilities.commons.utils;

/**
 * A Utilities class for safely checking and converting String IDs to longs usable with
 * {@link net.dv8tion.jda.api.utils.MiscUtil#parseSnowflake(String) MiscUtil.parseSnowflake(String)}, a utility used in
 * several {@code Object#getXById(String)} methods.
 *
 *
This class contains two static methods:
 *

 *
{@link SafeIdUtil#safeConvert(String) SafeIdUtil.safeConvert(String)} - Safely converts a String
 *     to a format usable with {@code MiscUtil.parseSnowflake(String)}.

 *
 *
{@link SafeIdUtil#checkId(String) SafeIdUtil.checkId(String)} - Checks if a String is safe to use
 *     with {@code MiscUtil.parseSnowflake(String)} as it is.

 *

 *
 * @since  1.2
 * @author Kaidan Gustave
 */
public final class SafeIdUtil
{
    /**
     * Safely convert the provided String ID to a {@code long} usable with
     * {@link net.dv8tion.jda.api.utils.MiscUtil#parseSnowflake(String) MiscUtil.parseSnowflake(String)}.
     *
     * @param  id
     *         The String ID to be converted
     *
     * @return If the String can be converted into a non-negative {@code long}, then it will return the conversion.
     *
However, if one of the following criteria is met, then this method will return {@code 0L}:
     *

     *
If the provided String throws a {@link java.lang.NumberFormatException NumberFormatException} when used with
     *             {@link java.lang.Long#parseLong(String) Long.parseLong(String)}.

     *
     *
If the provided String is converted, but the returned {@code long} is negative.

     *

     */
    public static long safeConvert(String id)
    {
        try {
            long l = Long.parseLong(id.trim());
            if(l<0)
                return 0L;
            return l;
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    /**
     * Checks if the provided String ID is usable with {@link net.dv8tion.jda.api.utils.MiscUtil#parseSnowflake(String) MiscUtil.parseSnowflake(String)}.
     *
     * @param  id
     *         The String ID to be converted
     *
     * @return {@code true} if both of the following criteria are not met:
     *

     *
If the provided String throws a {@link java.lang.NumberFormatException NumberFormatException} when used with
     *             {@link java.lang.Long#parseLong(String) Long.parseLong(String)}.

     *
     *
If the provided String is converted, but the returned {@code long} is negative.

     *

     */
    public static boolean checkId(String id)
    {
        try {
            long l = Long.parseLong(id.trim());
            return l >= 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    // Prevent instantiation
    private SafeIdUtil(){}
}


text:
'use strict';

var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var LinkedinStrategy = require('passport-linkedin-oauth2').Strategy;
var RememberMeStrategy = require('passport-remember-me').Strategy;
var config = require('application-config');

var debug = require('debug')('bon-in-a-box-frontend:passport');

exports = module.exports = function(passport, authentication, models) {
	passport.serializeUser(function(user, done) {
		done(null, user.id); // this is what gets attached to the session
	});

	passport.deserializeUser(function(id, done) {
		models.User.findById(id, function(err, user) {
			done(err, user);
		});
	});

	passport.use('local-signup', new LocalStrategy({
		usernameField: 'email', // by default, local strategy uses username and password, we will override with email
		passwordField: 'password',
		passReqToCallback: true // allows us to pass back the entire request to the callback
	}, authentication.local.signup));

	passport.use('local-login', new LocalStrategy({
		usernameField: 'email', // by default, local strategy uses username and password, we will override with email
		passwordField: 'password',
		passReqToCallback: true // allows us to pass back the entire request to the callback
	}, authentication.local.login));

	passport.use(new FacebookStrategy({
		clientID: config.get('facebook.client.id'),
		clientSecret: config.get('facebook.client.secret'),
		callbackURL: config.get('facebook.callback.url'),
		passReqToCallback: true
	}, authentication.facebook.auth));

	passport.use(new GoogleStrategy({
		clientID: config.get('google.client.id'),
		clientSecret: config.get('google.client.secret'),
		callbackURL: config.get('google.callback.url'),
		passReqToCallback: true
	}, authentication.google.auth));

	passport.use(new LinkedinStrategy({
		clientID: config.get('linkedin.client.id'),
		clientSecret: config.get('linkedin.client.secret'),
		callbackURL: config.get('linkedin.callback.url'),
		passReqToCallback: true
	}, authentication.linkedin.auth));

	passport.use(new RememberMeStrategy(function(token, done) {
		models.User.findOne({accesstoken: token}, function(err, user) {
			if (err) {
				return done(err);
			}
			if (user === null) {
				return done(null, false);
			}
			return done(null, user);
		});
	}, authentication.local.rememberme));
};


text:
import { CodeMapBuilding } from "./codeMapBuilding"
import { TEST_NODE_ROOT } from "../../../util/dataMocks"
import { Vector3 } from "three"
import { ColorConverter } from "../../../util/color/colorConverter"

function mockColorConverter() {
	ColorConverter.colorToVector3 = jest.fn().mockReturnValue(new Vector3(0, 1, 2))
}

describe("CodeMapBuilding", () => {
	let building: CodeMapBuilding
	let building1: CodeMapBuilding
	let building2: CodeMapBuilding

	const MAP_SIZE = 250

	beforeEach(() => {
		mockColorConverter()

		building = new CodeMapBuilding(0, null, TEST_NODE_ROOT, "#00BFFF")
		building1 = new CodeMapBuilding(0, null, TEST_NODE_ROOT, "#DDCC00")
		building2 = new CodeMapBuilding(1, null, TEST_NODE_ROOT, "#820E0E")
	})

	describe("getCenterPoint", () => {
		it("should return the center point of a building", () => {
			const result = building.getCenterPoint(MAP_SIZE)
			const expected = new Vector3(-244.5, 8, -241.5)

			expect(result.x).toBe(expected.x)
			expect(result.y).toBe(expected.y)
			expect(result.z).toBe(expected.z)
		})
	})

	describe("decreaseLightness", () => {
		it("should set color correctly", () => {
			building.decreaseLightness(5)

			expect(building.color).toEqual("#00ACE6")
		})

		it("should set color correctly and not keep lightness at 10", () => {
			building.decreaseLightness(100)

			expect(building.color).toEqual("#002633")
		})

		it("should set deltaColor correctly when delta is enabled", () => {
			building["_node"].deltas = {}
			building["_defaultDeltaColor"] = "#ABCDEF"

			building.decreaseLightness(100)

			expect(building.deltaColor).toEqual("#08192B")
		})
	})

	describe("getColorVector", () => {
		it("should call colorToVector3 and return it's value", () => {
			building.setColor("#ABCDEF")
			const result = building.getColorVector()

			expect(result.x).toBe(0)
			expect(result.y).toBe(1)
			expect(result.z).toBe(2)
			expect(ColorConverter.colorToVector3).toHaveBeenCalledWith("#ABCDEF")
		})
	})

	describe("getDefaultColorVector", () => {
		it("should call colorToVector3 and return it's value", () => {
			const result = building.getDefaultColorVector()

			expect(result.x).toBe(0)
			expect(result.y).toBe(1)
			expect(result.z).toBe(2)
			expect(ColorConverter.colorToVector3).toHaveBeenCalledWith("#00BFFF")
		})
	})

	describe("resetColor", () => {
		it("should reset the colors back to their defaultColors", () => {
			building.setColor("#ABCDEF")
			building["_defaultDeltaColor"] = "#ABCDEF"

			building.resetColor()

			expect(building.color).toEqual("#00BFFF")
			expect(building.deltaColor).toEqual("#ABCDEF")
		})
	})

	describe("equals", () => {
		it("should return true if two buildings have the same id", () => {
			expect(building.equals(building1)).toBeTruthy()
		})

		it("should return false if two buildings have different ids", () => {
			expect(building.equals(building2)).toBeFalsy()
		})
	})

	describe("setColor", () => {
		it("should set the color", () => {
			building1.setColor("#A0B1C2")

			expect(building1.color).toEqual("#A0B1C2")
		})
	})
})


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var settings = require('../../app/controllers/settings.server.controller');

	// Settings Routes
	app.route('/settings')
		.get(settings.list)
		.post(users.requiresLogin, settings.create);

	app.route('/settings/:settingId')
		.get(settings.read)
		.put(users.requiresLogin, settings.hasAuthorization, settings.update)
		.delete(users.requiresLogin, settings.hasAuthorization, settings.delete);

	// Finish by binding the Setting middleware
	app.param('settingId', settings.settingByID);
};


text:
/*
 * @file reducers for entries' list
 */

import * as ActionTypes from 'actions';

const initialState = {
  isFetching: false,
  data: [],
};

const { pendingOf, fulfilledOf } = ActionTypes;

export default function (state = initialState, action) {
  const { type, payload } = action;

  switch (type) {

    case pendingOf(ActionTypes.FETCH_ENTRY_LIST):
      return {
        ...state,
        isFetching: true,
      };

    case fulfilledOf(ActionTypes.FETCH_ENTRY_LIST):
      return {
        ...state,
        isFetching: false,
        data: payload,
      };

    default:
      return state;
  }
}


text:
describe("Controller", function(){
  var Users;
  var element;

  beforeEach(function(){
    Users = Spine.Controller.sub();
    element = $("
");
  });

  it("should be configurable", function(){
    element.addClass("testy");
    var users = new Users({el: element});
    expect(users.el.hasClass("testy")).toBeTruthy();

    users = new Users({item: "foo"});
    expect(users.item).toEqual("foo");
  });

  it("should generate element", function(){
    var users = new Users();
    expect(users.el).toBeTruthy();
  });

  it("can replace generated element", function(){
    element.addClass('new').html('before');
    var users = new Users({el: element});
    expect(users.el.hasClass('new')).toBeTruthy();
    expect(users.el.html()).toBe('before');
    //expect(users.$el.html()).toBe('before');
    var newElement = $('
replaced
');
    users.replace(newElement);
    expect(users.el.hasClass('newer')).toBeTruthy();
    expect(users.el.html()).toBe('replaced');
    //expect(users.$el.html()).toBe('replaced');
  });

  it("should populate elements", function(){
    Users.include({
      elements: {".foo": "foo"}
    });

    element.append($("
").addClass("foo"));
    var users = new Users({el: element});

    expect(users.foo).toBeTruthy();
    expect(users.foo.hasClass("foo")).toBeTruthy();
  });

  it("should remove element upon release event", function(){
    var parent = $('
');
    parent.append(element);

    var users = new Users({el: element});
    expect(parent.children().length).toBe(1);

    users.release();
    expect(parent.children().length).toBe(0);
  });

  it("should set attributes on el", function(){
    Users.include({
      attributes: {"style": "width: 100%"}
    });
    var users = new Users();
    expect(users.el.attr("style")).toMatch("width: 100%");
  });

  describe("When binding DOM events", function(){
    var spy;

    beforeEach(function(){
      spy = jasmine.createSpy();
    });

    it("should add events", function(){
      Users.include({
        events: {"click": "wasClicked"},
        // Context change confuses Spy
        wasClicked: $.proxy(spy, jasmine)
      });
      var users = new Users({el: element});
      element.click();
      expect(spy).toHaveBeenCalled();
    });

    it("should delegate events", function(){
      Users.include({
        events: {"click .foo": "wasClicked"},
        wasClicked: $.proxy(spy, jasmine)
      });
      var child = $("
").addClass("foo");
      element.append(child);
      var users = new Users({el: element});
      child.click();
      expect(spy).toHaveBeenCalled();
    });
  });

  /*
    tests related to .listenTo(), .listenToOnce(), and .stopListening()
  */

  describe("When using event listener methods", function(){
    var spy, spy2, Asset, Users, asset, users;

    beforeEach(function(){
      Asset = Spine.Model.setup("Asset", ["name"]);
      asset = Asset.create({name: "test.pdf"});
      Users = Spine.Controller.sub();
      users = new Users();
      spy = jasmine.createSpy();
      spy2 = jasmine.createSpy();
    });

    it("can listen to one event on a model instance", function(){
      users.listenTo(asset, 'event1', spy);
      asset.trigger("event1");
      expect(spy).toHaveBeenCalled();
    });

    it("wont listen to events of the same name on unlistened to model instances", function(){
      users.listenTo(asset, 'event1', spy);
      var asset2 = Asset.create({name: "scooby.pdf"});
      var asset3 = Asset.create({name: "shaggy.pdf"});
      asset3.trigger("event1");
      asset2.trigger("evemt1")
      expect(spy).not.toHaveBeenCalled();
    });

    it("can listen to many events on a model instance", function(){
      users.listenTo(asset, 'event1 event2 event3', spy);
      asset.trigger("event1");
      asset.trigger("event2");
      asset.trigger("event3");
      expect(spy).toHaveBeenCalled();
      expect(spy.calls.count()).toBe(3);
    });

    it("can listen once for an event on a model instance", function(){
      users.listenToOnce(asset, 'event1', spy);
      asset.trigger("event1");
      expect(spy).toHaveBeenCalled();
      spy.calls.reset();
      asset.trigger("event1");
      expect(spy).not.toHaveBeenCalled();
    });

    it("can stop listening to a specific event on a model instance while maintaining listeners on other events", function(){
      users.listenTo(asset, 'event1 event2 event3', spy);
      asset.trigger("event1");
      expect(spy).toHaveBeenCalled();
      spy.calls.reset();
      users.stopListening(asset, 'event1');
      asset.trigger("event1");
      expect(spy).not.toHaveBeenCalled();
      spy.calls.reset();
      asset.trigger("event2");
      expect(spy).toHaveBeenCalled();
      spy.calls.reset();
      asset.trigger("event3");
      expect(spy).toHaveBeenCalled();
    });

    it("can stop listening to all events on a model instance", function(){
      users.listenTo(asset, 'event1 event2 event3', spy);
      asset.trigger("event2");
      expect(spy).toHaveBeenCalled();
      spy.calls.reset();
      users.stopListening(asset);
      asset.trigger("event1");
      asset.trigger("event2");
      asset.trigger("event3");
      expect(spy).not.toHaveBeenCalled();
    });

    it("should stop listening to events on a model instance, without canceling out other binders on that model instance", function(){
      Asset.bind('event1', spy2)
      users.listenTo(asset, 'event1', spy);
      asset.trigger("event1");
      expect(spy).toHaveBeenCalled();
      expect(spy2).toHaveBeenCalled();
      spy.calls.reset();
      spy2.calls.reset();
      users.stopListening(asset, 'event1');
      asset.trigger("event1");
      expect(spy).not.toHaveBeenCalled();
      expect(spy2).toHaveBeenCalled();
    });

    // this is the major benefit of the listeners. helps manage cleanup of obsolete binders

    it("should stop listening if the controller is released", function(){
      users.listenTo(asset, 'event1', spy);
      asset.trigger("event1");
      expect(spy).toHaveBeenCalled();
      spy.calls.reset();
      users.release();
      asset.trigger("event1");
      expect(spy).not.toHaveBeenCalled();
    });

    it("should stop listening to events on a model instance if the controller is released, without canceling out other binders on that model instance", function(){
      asset.bind('event1', spy2)
      users.listenTo(asset, 'event1', spy);
      asset.trigger("event1");
      expect(spy).toHaveBeenCalled();
      expect(spy2).toHaveBeenCalled();
      spy.calls.reset();
      spy2.calls.reset();
      users.release();
      asset.trigger("event1");
      expect(spy).not.toHaveBeenCalled();
      expect(spy2).toHaveBeenCalled();
    });

  });

  describe("When using inheritance", function() {
    beforeEach(function() {
      element = $('
').html('

');
      A = Spine.Controller.sub({
        events: {"click .a-el": "aEventHandler"},
        elements: {".a-el": "elA"},
        aEventHandler: function() {}
      });

      B = A.sub({
        el: element,
        events: {"click .b-el": "bEventHandler"},
        elements: {".b-el": "elB"},
        bEventHandler: function() {}
      });

      C = B.sub({
        el: element,
        events: {"click .c-el": "cEventHandler"},
        elements: {".c-el": "elC"},
        cEventHandler: function() {}
      });

      c = new C();
    });

    it("should inherit elements from parent controllers", function(){
      expect(c.elA).toBeDefined();
      expect(c.elB).toBeDefined();
      expect(c.elC).toBeDefined();
    });

    it("should inherit events from parent controllers", function(){
      spyOn(c, 'aEventHandler');
      spyOn(c, 'bEventHandler');
      spyOn(c, 'cEventHandler');
      c.el.find('.a-el').click();
      c.el.find('.b-el').click();
      c.el.find('.c-el').click();

      expect(c.aEventHandler).toHaveBeenCalled();
      expect(c.bEventHandler).toHaveBeenCalled();
      expect(c.cEventHandler).toHaveBeenCalled();
    });
  });
});


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>DarknessMap</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="css/foundation.css">
        <link rel="stylesheet" href="js/vendor/leaflet/leaflet.css" />
        <link rel="stylesheet" href="css/app.css">

        <link rel="stylesheet/less" type="text/css" href="css/styles.less">

        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,600,300' rel='stylesheet' type='text/css'>

Home

About

Legal

Open Source

Contact

DarknessMap

An experiment
in mapping
darkness.

                        Download App

Download the App:

The Darkness Map is a visualization of light levels in the city at night. To collect this data, we made a custom mobile app that computes the average brightness for each frame of your phone's camera preview, and graphs that value according to the frame's GPS location.

Add to the Map:

Once the Darkness Map App is downloaded to your mobile device (beta version coming soon for the Android OS), activate it at night as you walk around your neighborhood. Video is GPS tagged and processed to output data that is uploaded to the Darkness Map servers and added to the map.

How it Works:

The Darkness Map App finds the average brightness of each frame of video then graphs that value as a vertical line to create a histogram. Each frame is tagged with a GPS location so it can easily be added to the map.

About

A project by Emiliano Burgos and Genevieve Hoffman, conceived with Scott Wayne Indiana, and Rune Madsen.

We have all seen satellite images of planet Earth at night, but aside from expressing that cities are bright, or that nighttime power is primarily a first-world commodity, these images do not portray much practical information. The Darkness Map aims to communicate dark and light levels within the nighttime urban environment on a human scale.

Inspired by a desire to find dark areas (in order to determine the best locations for outdoor projection) in a city dominated by lighting for commerce, entertainment and public safety, the Darkness Map was conceived of to visualize the nighttime light levels on New York City's sidewalks. Data is collected by capturing video of each city block, tagging it with a GPS location, then analyzing it algorithmically to compute the average brightness of each frame. This data is displayed as a map visualization that depicts the lightness and darkness of city streets at night. Beta versions of the Darkness Map are active in New York City and the San Francisco Bay Area.

Possible extensions of the Darkness map could be data mashing to see whether light levels in the city at night correlate with other location-specific data, like public safety records, traffic incidents, or unauthorized interventions in public space (graffiti).

The Darkness Map was part of the San Francisco Urban Prototyping Festival in October 2012, and is made possible in part by the Gray Area Foundation for the Arts.

Legal

The Darkness Map is an open-source project that uses crowd-sourced data to visualize the urban environment at night. The Darkness Map app provides a way for users to contribute to the Darkness Map visualization. The Darkness Map app does not maintain any personal information about users. The data users collect and send to our servers consists of a light level reading, timestamp, GPS coordinate, and session ID. There is no way to trace back to an individual or phone. By using the Darkness Map app users are contributing to an open-source project, and the data collected will be added to the Darkness Map database, and made available as an open source dataset.

Open Source

All code for the Darkness Map is open source and available to use under an MIT License. All of the code components of the Darkness Map are hosted on github.

Darkness Map code repositories include:

Mobile app for Android - native Android/Java. The mobile app uses the phone camera preview as a light sensor. After receiving a GPS signal, the app captures the brightness of each frame, and sends this data to the Darkness Map server. The iPhone app is currently in development stage, and has not yet been submitted to the App Store. Future versions will have variable sampling rates -- for walking, biking and driving.

Mobile app for iPhone - made with OpenFrameworks for iPhone and Objective-C. The mobile app uses the phone camera preview as a light sensor. After receiving a GPS signal, the app captures the brightness of each frame, and sends this data to the Darkness Map server. The Android app is currently a prototype, and available to download from the Darkness Map website if you navigate to the homepage on an Android device. Future versions will have variable sampling rates -- for walking, biking and driving.

Data Collection Device - basic electronics tutorial for building your own data logger. The Data Collection Device was the initial prototype for the Darkness Map, before we decided to make a mobile app as the data collection tool. These instructions go over how to connect an Arduino, GPS module, and light sensor, and how to save this data to an SD card. Currently, there is no way to integrate the data collected with the Darkness Map web-based visualization, but we are hoping to develop an upload system in the future. Currently, you can use make your own visualizations from the data saved to the CSV file, and I will be uploading code to demonstrate how to get started with that soon. Hopefully you can use this tutorial as the basis for other projects, and swap out the light sensor for other environmental sensors.

Arduino Data Collection Device - made with Arduino. Repository for Arduino code that works with the Data Collection Device. In addition to a few core Arduino libraries (Wire, SD, and Software Serial), the code uses the TinyGPS Library, by Mikal Hart, the TSL2561 Library, by Ladyada (Limor Fried), and the RTClib, by Ladyada. The RTClib was originally developed by Jeelabs. Before using the code, download the additional libraries and drop them into the libraries folder inside your Arduino projects folder. For best results, follow the steps in the Data Collection Device tutorial when using this code.

Dataviz Projection - made with Processing. This is a short sketch that pulls data from the Darkness Map API and visualizes the brightness values as animating grayscale bars. The code was developed for a projection installation at the Urban Prototyping Festival in San Francisco, which was displayed at the entrance to the Intersection for the Arts on Mission Street.

Website - made with HTML, CSS and Javascript. Code for the Darkness Map website and map based visualization. The map visualization utilizes the Leaflet library for JS, and incorporates map tiles made with data from the <a href="http://www.openstreetmap.org"OpenStreetMap project, and styled by TileMill.

Server - made with NodeJS. Code for the Darkness Map Server, which hosts the data collected by the Darkness Map mobile app, and powers the map visualization.

Client - made with Javascript.

All code for the Darkness Map is open source and available to use under an MIT License.

Copyright (c) 2012-13 Emiliano Burgos and Genevieve Hoffman.

                    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

                    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

                    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Contact

For all inquiries and questions about the Darkness Map project, including questions about the Darkness Map mobile app, please send an email to hello (at) darknessmap (dot) com.

Home

About

Legal

Open Source

Contact


text:
SET DEFINE OFF;
CREATE UNIQUE INDEX AFW_12_GROUP_APROB_UK1 ON AFW_12_GROUP_APROB
(CODE, REF_GROUP_STAT)
LOGGING
/


text:
<?php

namespace CrudGenerator\Generators\Installer;

/**
 * @author Stéphane Demonchaux
 */
interface GeneratorInstallerInterface
{
    /**
     * @param  string  $package
     * @param  string  $version
     * @return integer
     */
    public function install($package, $version = 'dev-master');
}


text:
Education

BSc in Computer Engineering

Federal University of Espírito Santo

April 2005 - January 2012

Fundamentals of Data Science I

Udacity

September 2017 - November 2017

Fundamentals of Data Science II

Udacity

September 2017 - December 2017


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;

namespace Microsoft.CodeAnalysis.FindUsages
{
    internal interface IFindUsagesContext
    {
        /// <summary>
        /// Used for clients that are finding usages to push information about how far along they
        /// are in their search.
        /// </summary>
        IStreamingProgressTracker ProgressTracker { get; }

        /// <summary>
        /// Report a message to be displayed to the user.
        /// </summary>
        ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken);

        /// <summary>
        /// Set the title of the window that results are displayed in.
        /// </summary>
        ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken);

        ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken);
        ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken);
    }
}


text:
import angular from 'angular';

angular.module("app").directive(
  'jjSidenav',
  ["$mdSidenav", "$timeout", function($mdSidenav, $timeout) {
  return {
    template: require('./sideNav.html'),
    scope: {
        menuItems: '=',
        current: '=',
        color: "@color"
    },
    link: function (scope, element, attrs) {
      scope.toggleMenu = toggleMenu;

      function toggleMenu() {
        toggleIcon();
        toggleSideNav();
      };

      function toggleIcon() {
        var icon = element[0].getElementsByClassName('menu-icon');
        angular.element(icon).toggleClass('active');
        element.find('div').removeClass('no-animation');
      }

      function toggleSideNav() {
          $mdSidenav('left').toggle();
      }
    }
  };
}]);


text:
* [Private Key Store Interfaces](#private-key-store-interfaces)
* [Configuration](#configuration)
* [Provided Implementation](#provided-implementation)
    * [File Based Private Key Store](#file-based-private-key-store)

Athenz servers (both ZMS and ZTS) require a unique private key
to sign their respective tokens. There are 2 distinct operations
that require the use of signatures:

* NToken/ZToken signatures
* Policy Document signatures

The private key could be unique per host (if you have multiple
ZMS and/or ZTS servers in your production environment) or per
data center location. By default the server ships with a file
based private key store which expects to find the private key
in PEM format in the configured file. The system administrator
may decide to configure and use this implementation or otherwise
implement a completely new one to satisfy their requirements
(e.g. the private keys are to be stored in some external system
rather than a file).

## Private Key Store Interfaces
-------------------------------

To provide ZMS/ZTS servers with private keys, the following two
interfaces must be implemented:

* [PrivateKeyStoreFactory](https://github.com/yahoo/athenz/blob/master/libs/java/auth_core/src/main/java/com/yahoo/athenz/auth/PrivateKeyStoreFactory.java)

The job of the PrivateKeyStoreFactory class is to implement a single
`create()` method which returns an instance of `PrivateKeyStore` class
implementation.

* [PrivateKeyStore](https://github.com/yahoo/athenz/blob/master/libs/java/auth_core/src/main/java/com/yahoo/athenz/auth/PrivateKeyStore.java)

The job of the PrivateKeyStore class is to return a private key
for a given host in a PEM format. The hostname is passed as the first
argument to the `getPrivateKey()` method. Each private key in Athenz
is identified by a unique key identifier. This allows each service to
have multiple active private/public key pairs to support per host
keys with key rotation capability. The `getPrivateKey()` method is
passed a `StringBuilder` object that the implementation must update
and return the corresponding key identifier for the public key
returned from this method.

During server startup, Athenz servers will load the configured
private key store factory class and invoke the create method.
Then it will use the PrivateKeyStore object returned to retrieve
the private key for the host.

If the private key store does not return a PrivateKey (returns null),
then the server will continue to run. This is necessary since it's
possible that an environment may choose to run only ZMS Servers
for centralized authorization thus no need to sign and distribute
policy documents and only supports TLS certificates for principal
authentication thus no need to sign and issue NTokens.

## Configuration
----------------

Both ZMS and ZTS Servers expect to find the configured private key
store factory class names in their respective system properties:

* ZMS: athenz.zms.private_key_store_factory_class
* ZTS: athenz.zts.private_key_store_factory_class

For example,

```
-Dathenz.zms.private_key_store_factory_class=com.yahoo.athenz.zms.pkey.file.FilePrivateKeyStoreFactory
```

If you're installing and running Athenz services using the binary
packages provided, you can configure the private key store factory
class in the conf/zms_server/zms.properties or conf/zts_server/zts.properties
files for ZMS and ZTS servers respectively:

```
athenz.zms.private_key_store_factory_class=com.yahoo.athenz.auth.impl.FilePrivateKeyStoreFactory

athenz.zts.private_key_store_factory_class=com.yahoo.athenz.auth.impl.FilePrivateKeyStoreFactory
```

## Provided Implementation
--------------------------

Here is the list of Athenz provided private key store implementations with
brief description of each one.

### File Based Private Key Store
--------------------------------

Class: com.yahoo.athenz.auth.impl.FilePrivateKeyStoreFactory

This factory class creates and returns a single private key
regardless of the hostname passed to the `getPrivateKey()` method.
The private key file and its corresponding id can be configured by
using the following system properties:

* Key File: athenz.auth.private_key_store.private_key
* Key-Id: athenz.auth.private_key_store.private_key_id

The key file must be a PEM encoded either RSA or EC
private key.


text:
namespace task
{
bool ProtobufFileCrcTask::check() const
{
    return protobufFile() != nullptr && protobufFile()->isUnique();
}

static doim::TagSetSPtr gTags =
    doim::TagSet::global({&doim::gCrcTag, &doim::gInspectTag, &doim::gProtobufTag},
                         gTags);

doim::TagSetSPtr ProtobufFileCrcTask::tags() const
{
    return gTags;
}

ECode ProtobufFileCrcTask::operator()()
{
    std::ifstream fstream(protobufFile()->file()->path().c_str());
    string content((std::istreambuf_iterator<char>(fstream)),
                   std::istreambuf_iterator<char>());

    math::CrcProcessor crcProcessor;
    crcProcessor.process_bytes(content.data(), content.size());
    mCrcsum = crcProcessor.checksum();

    DLOG("Crc for {0} is {1:x}", protobufFile()->file()->name(), mCrcsum);
    EHEnd;
}

string ProtobufFileCrcTask::description() const
{
    return "Cxx file crc " + protobufFile()->file()->path();
}

} // namespace task


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Net;

namespace WebTester
{
    public partial class Service1 : ServiceBase
    {
        System.Timers.Timer _timer = new System.Timers.Timer(1 * 60 * 1000);
        string log;
        Runner runner = new Runner();

        public Service1()
        {
            InitializeComponent();
            _timer.Elapsed += _timer_Elapsed;
        }

        void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //call the singleton class.
            if (!runner.isRunning)
            {
                log = Utilities.CreateLogFile("Application", true);
                runner.start();
            }
        }

        /// <summary>
        /// when windows service starts
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            log = Utilities.CreateLogFile("Application", true);
            string errorlog = Utilities.CreateLogFile("Error", true);
            Utilities.Log(log,"WebTester Started");

            _timer.Start();

            //DBOps db = new DBOps();
            DBOps.Query = "update inputUrl set engaged = 0";
            DBOps.WriteToDB();
        }

        /// <summary>
        /// when windows service stops
        /// </summary>
        protected override void OnStop()
        {
            _timer.Stop();
            _timer.Dispose();
            if (Fiddler.FiddlerApplication.IsStarted())
            {
                Fiddler.FiddlerApplication.Shutdown();
                Utilities.Log(log, "Fiddler stopped");
            }

            Utilities.Log(log,"WebTester Stopped");
        }
    }
}


text:
#ifndef RTTR_TYPE_REGISTER_H_
#define RTTR_TYPE_REGISTER_H_

#include "rttr/detail/base/core_prerequisites.h"

#include "rttr/string_view.h"

#include <memory>
#include <string>
#include <vector>

namespace rttr
{
class variant;
class type;
class argument;

template<typename T>
class class_;

namespace detail
{

class constructor_wrapper_base;
class destructor_wrapper_base;
class enumeration_wrapper_base;
class method_wrapper_base;
class property_wrapper_base;

struct type_converter_base;
struct type_comparator_base;
struct base_class_info;
struct derived_info;

using variant_create_func   = variant(*)(const argument&);
using get_derived_func      = derived_info(*)(void*);

template<typename T, typename Enable>
struct type_getter;

struct type_data;

class metadata;

/*!
 * This class contains all functions to register properties, methods etc.. for a specific type.
 * This is a static pimpl, it will just forward the data to the \ref type_register_private class.
 */
class RTTR_API type_register
{
public:
    // no copy
    type_register(const type_register&) = delete;
    // no assign
    type_register& operator=(const type_register&) = delete;

    static void property(const type& t, std::unique_ptr<property_wrapper_base> prop);

    static void method(const type& t, std::unique_ptr<method_wrapper_base> meth);

    static void constructor(const type& t, std::unique_ptr<constructor_wrapper_base> ctor);

    static void destructor(const type& t, std::unique_ptr<destructor_wrapper_base> dtor);

    static void enumeration(const type& t, std::unique_ptr<enumeration_wrapper_base> enum_data);

    static void custom_name(type& t, string_view name);

    static void metadata( const type& t, std::vector<metadata> data);

    static void converter(const type& t, std::unique_ptr<type_converter_base> converter);

    static void comparator(const type& t, type_comparator_base* comparator);

    static void equal_comparator(const type& t, type_comparator_base* comparator);

    static void less_than_comparator(const type& t, type_comparator_base* comparator);

    static void register_base_class(const type& derived_type, const base_class_info& base_info);

    /*!
     * \brief Register the type info for the given name
     *
     * \remark When a type with the given name is already registered,
     *         then the type for the already registered type will be returned.
     *
     * \return A valid type object.
     */
    static type type_reg(type_data& info) RTTR_NOEXCEPT;

private:

    friend class type;
    template<typename T>
    friend class class_;

    template<typename T, typename Enable>
    friend struct detail::type_getter;
};

} // end namespace detail
} // end namespace rttr

#endif // RTTR_TYPE_REGISTER_H_


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>enet: callbacks.c File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

enet

Main Page

Related Pages

Modules

Data Structures

Files

File List

Globals

Macros |
Functions

callbacks.c File Reference

ENet callback functions.
More...

#include "enet/enet.h"

Macros

#define 	ENET_BUILDING_LIB   1

Functions

int 	enet_initialize_with_callbacks (ENetVersion version, const ENetCallbacks *inits)

 	Initializes ENet globally and supplies user-overridden callbacks.  More...

ENetVersion 	enet_linked_version (void)

 	Gives the linked version of the ENet library.  More...

void * 	enet_malloc (size_t size)

void 	enet_free (void *memory)

<address class="footer">
Generated on Thu Dec 26 2013 15:53:49 for enet by

 1.8.5
</address>


text:
package newrelic

import (
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/newrelic/go-agent/internal"
)

var (
	singleCount = []float64{1, 0, 0, 0, 0, 0, 0}
	webMetrics  = []internal.WantMetric{
		{Name: "WebTransaction/Go/hello", Scope: "", Forced: true, Data: nil},
		{Name: "WebTransaction", Scope: "", Forced: true, Data: nil},
		{Name: "HttpDispatcher", Scope: "", Forced: true, Data: nil},
		{Name: "Apdex", Scope: "", Forced: true, Data: nil},
		{Name: "Apdex/Go/hello", Scope: "", Forced: false, Data: nil},
	}
	webErrorMetrics = append([]internal.WantMetric{
		{Name: "Errors/all", Scope: "", Forced: true, Data: singleCount},
		{Name: "Errors/allWeb", Scope: "", Forced: true, Data: singleCount},
		{Name: "Errors/WebTransaction/Go/hello", Scope: "", Forced: true, Data: singleCount},
	}, webMetrics...)
	backgroundMetrics = []internal.WantMetric{
		{Name: "OtherTransaction/Go/hello", Scope: "", Forced: true, Data: nil},
		{Name: "OtherTransaction/all", Scope: "", Forced: true, Data: nil},
	}
	backgroundErrorMetrics = append([]internal.WantMetric{
		{Name: "Errors/all", Scope: "", Forced: true, Data: singleCount},
		{Name: "Errors/allOther", Scope: "", Forced: true, Data: singleCount},
		{Name: "Errors/OtherTransaction/Go/hello", Scope: "", Forced: true, Data: singleCount},
	}, backgroundMetrics...)
)

// compatibleResponseRecorder wraps ResponseRecorder to ensure consistent behavior
// between different versions of Go.
//
// Unfortunately, there was a behavior change in go1.6:
//
// "The net/http/httptest package's ResponseRecorder now initializes a default
// Content-Type header using the same content-sniffing algorithm as in
// http.Server."
type compatibleResponseRecorder struct {
	*httptest.ResponseRecorder
	wroteHeader bool
}

func newCompatibleResponseRecorder() *compatibleResponseRecorder {
	return &compatibleResponseRecorder{
		ResponseRecorder: httptest.NewRecorder(),
	}
}

func (rw *compatibleResponseRecorder) Header() http.Header {
	return rw.ResponseRecorder.Header()
}

func (rw *compatibleResponseRecorder) Write(buf []byte) (int, error) {
	if !rw.wroteHeader {
		rw.WriteHeader(200)
		rw.wroteHeader = true
	}
	return rw.ResponseRecorder.Write(buf)
}

func (rw *compatibleResponseRecorder) WriteHeader(code int) {
	rw.wroteHeader = true
	rw.ResponseRecorder.WriteHeader(code)
}

var (
	sampleLicense = "0123456789012345678901234567890123456789"
	validParams   = map[string]interface{}{"zip": 1, "zap": 2}
)

var (
	helloResponse    = []byte("hello")
	helloPath        = "/hello"
	helloQueryParams = "?secret=hideme"
	helloRequest     = func() *http.Request {
		r, err := http.NewRequest("GET", helloPath+helloQueryParams, nil)
		if nil != err {
			panic(err)
		}

		r.Header.Add(`Accept`, `text/plain`)
		r.Header.Add(`Content-Type`, `text/html; charset=utf-8`)
		r.Header.Add(`Content-Length`, `753`)
		r.Header.Add(`Host`, `my_domain.com`)
		r.Header.Add(`User-Agent`, `Mozilla/5.0`)
		r.Header.Add(`Referer`, `http://en.wikipedia.org/zip?secret=password`)

		return r
	}()
)

func TestNewApplicationNil(t *testing.T) {
	cfg := NewConfig("appname", "wrong length")
	cfg.Enabled = false
	app, err := NewApplication(cfg)
	if nil == err {
		t.Error("error expected when license key is short")
	}
	if nil != app {
		t.Error("app expected to be nil when error is returned")
	}
}

func handler(w http.ResponseWriter, req *http.Request) {
	w.Write(helloResponse)
}

func testApp(replyfn func(*internal.ConnectReply), cfgfn func(*Config), t testing.TB) expectApp {
	cfg := NewConfig("my app", "0123456789012345678901234567890123456789")

	if nil != cfgfn {
		cfgfn(&cfg)
	}

	app, err := newTestApp(replyfn, cfg)
	if nil != err {
		t.Fatal(err)
	}
	return app
}

func TestRecordCustomEventSuccess(t *testing.T) {
	app := testApp(nil, nil, t)
	err := app.RecordCustomEvent("myType", validParams)
	if nil != err {
		t.Error(err)
	}
	app.ExpectCustomEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"type":      "myType",
			"timestamp": internal.MatchAnything,
		},
		UserAttributes: validParams,
	}})
}

func TestRecordCustomEventHighSecurityEnabled(t *testing.T) {
	cfgfn := func(cfg *Config) { cfg.HighSecurity = true }
	app := testApp(nil, cfgfn, t)
	err := app.RecordCustomEvent("myType", validParams)
	if err != errHighSecurityEnabled {
		t.Error(err)
	}
	app.ExpectCustomEvents(t, []internal.WantEvent{})
}

func TestRecordCustomEventEventsDisabled(t *testing.T) {
	cfgfn := func(cfg *Config) { cfg.CustomInsightsEvents.Enabled = false }
	app := testApp(nil, cfgfn, t)
	err := app.RecordCustomEvent("myType", validParams)
	if err != errCustomEventsDisabled {
		t.Error(err)
	}
	app.ExpectCustomEvents(t, []internal.WantEvent{})
}

func TestRecordCustomEventBadInput(t *testing.T) {
	app := testApp(nil, nil, t)
	err := app.RecordCustomEvent("????", validParams)
	if err != internal.ErrEventTypeRegex {
		t.Error(err)
	}
	app.ExpectCustomEvents(t, []internal.WantEvent{})
}

func TestRecordCustomEventRemoteDisable(t *testing.T) {
	replyfn := func(reply *internal.ConnectReply) { reply.CollectCustomEvents = false }
	app := testApp(replyfn, nil, t)
	err := app.RecordCustomEvent("myType", validParams)
	if err != errCustomEventsRemoteDisabled {
		t.Error(err)
	}
	app.ExpectCustomEvents(t, []internal.WantEvent{})
}

type sampleResponseWriter struct {
	code    int
	written int
	header  http.Header
}

func (w *sampleResponseWriter) Header() http.Header       { return w.header }
func (w *sampleResponseWriter) Write([]byte) (int, error) { return w.written, nil }
func (w *sampleResponseWriter) WriteHeader(x int)         { w.code = x }

func TestTxnResponseWriter(t *testing.T) {
	// NOTE: Eventually when the ResponseWriter is instrumented, this test
	// should be expanded to make sure that calling ResponseWriter methods
	// after the transaction has ended is not problematic.
	w := &sampleResponseWriter{
		header: make(http.Header),
	}
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", w, nil)
	w.header.Add("zip", "zap")
	if out := txn.Header(); out.Get("zip") != "zap" {
		t.Error(out.Get("zip"))
	}
	w.written = 123
	if out, _ := txn.Write(nil); out != 123 {
		t.Error(out)
	}
	if txn.WriteHeader(503); w.code != 503 {
		t.Error(w.code)
	}
}

func TestTransactionEventWeb(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	err := txn.End()
	if nil != err {
		t.Error(err)
	}
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":             "WebTransaction/Go/hello",
			"nr.apdexPerfZone": "S",
		},
	}})
}

func TestTransactionEventBackground(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	err := txn.End()
	if nil != err {
		t.Error(err)
	}
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name": "OtherTransaction/Go/hello",
		},
	}})
}

func TestTransactionEventLocallyDisabled(t *testing.T) {
	cfgFn := func(cfg *Config) { cfg.TransactionEvents.Enabled = false }
	app := testApp(nil, cfgFn, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	err := txn.End()
	if nil != err {
		t.Error(err)
	}
	app.ExpectTxnEvents(t, []internal.WantEvent{})
}

func TestTransactionEventRemotelyDisabled(t *testing.T) {
	replyfn := func(reply *internal.ConnectReply) { reply.CollectAnalyticsEvents = false }
	app := testApp(replyfn, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	err := txn.End()
	if nil != err {
		t.Error(err)
	}
	app.ExpectTxnEvents(t, []internal.WantEvent{})
}

func myErrorHandler(w http.ResponseWriter, req *http.Request) {
	w.Write([]byte("my response"))
	if txn, ok := w.(Transaction); ok {
		txn.NoticeError(myError{})
	}
}

func TestWrapHandleFunc(t *testing.T) {
	app := testApp(nil, nil, t)
	mux := http.NewServeMux()
	mux.HandleFunc(WrapHandleFunc(app, helloPath, myErrorHandler))
	w := newCompatibleResponseRecorder()
	mux.ServeHTTP(w, helloRequest)

	out := w.Body.String()
	if "my response" != out {
		t.Error(out)
	}

	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "WebTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.myError",
		Caller:  "go-agent.myErrorHandler",
		URL:     "/hello",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, webErrorMetrics)
}

func TestWrapHandle(t *testing.T) {
	app := testApp(nil, nil, t)
	mux := http.NewServeMux()
	mux.Handle(WrapHandle(app, helloPath, http.HandlerFunc(myErrorHandler)))
	w := newCompatibleResponseRecorder()
	mux.ServeHTTP(w, helloRequest)

	out := w.Body.String()
	if "my response" != out {
		t.Error(out)
	}

	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "WebTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.myError",
		Caller:  "go-agent.myErrorHandler",
		URL:     "/hello",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, webErrorMetrics)
}

func TestSetName(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("one", nil, nil)
	if err := txn.SetName("hello"); nil != err {
		t.Error(err)
	}
	txn.End()
	if err := txn.SetName("three"); err != errAlreadyEnded {
		t.Error(err)
	}

	app.ExpectMetrics(t, backgroundMetrics)
}

func deferEndPanic(txn Transaction, panicMe interface{}) (r interface{}) {
	defer func() {
		r = recover()
	}()

	defer txn.End()

	panic(panicMe)
}

func TestPanicError(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)

	e := myError{}
	r := deferEndPanic(txn, e)
	if r != e {
		t.Error("panic not propagated", r)
	}

	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   internal.PanicErrorKlass,
		Caller:  "go-agent.(*txn).End",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     internal.PanicErrorKlass,
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestPanicString(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)

	e := "my string"
	r := deferEndPanic(txn, e)
	if r != e {
		t.Error("panic not propagated", r)
	}

	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my string",
		Klass:   internal.PanicErrorKlass,
		Caller:  "go-agent.(*txn).End",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     internal.PanicErrorKlass,
			"error.message":   "my string",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestPanicInt(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)

	e := 22
	r := deferEndPanic(txn, e)
	if r != e {
		t.Error("panic not propagated", r)
	}

	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "22",
		Klass:   internal.PanicErrorKlass,
		Caller:  "go-agent.(*txn).End",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     internal.PanicErrorKlass,
			"error.message":   "22",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
}

func TestPanicNil(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)

	r := deferEndPanic(txn, nil)
	if nil != r {
		t.Error(r)
	}

	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, backgroundMetrics)
}

func TestResponseCodeError(t *testing.T) {
	app := testApp(nil, nil, t)
	w := newCompatibleResponseRecorder()
	txn := app.StartTransaction("hello", w, helloRequest)

	txn.WriteHeader(http.StatusBadRequest)   // 400
	txn.WriteHeader(http.StatusUnauthorized) // 401

	txn.End()

	if http.StatusBadRequest != w.Code {
		t.Error(w.Code)
	}

	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "WebTransaction/Go/hello",
		Msg:     "Bad Request",
		Klass:   "400",
		Caller:  "go-agent.(*txn).WriteHeader",
		URL:     "/hello",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "400",
			"error.message":   "Bad Request",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, webErrorMetrics)
}

func TestResponseCode404Filtered(t *testing.T) {
	app := testApp(nil, nil, t)
	w := newCompatibleResponseRecorder()
	txn := app.StartTransaction("hello", w, helloRequest)

	txn.WriteHeader(http.StatusNotFound)

	txn.End()

	if http.StatusNotFound != w.Code {
		t.Error(w.Code)
	}

	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, webMetrics)
}

func TestResponseCodeCustomFilter(t *testing.T) {
	cfgFn := func(cfg *Config) {
		cfg.ErrorCollector.IgnoreStatusCodes =
			append(cfg.ErrorCollector.IgnoreStatusCodes,
				http.StatusNotFound)
	}
	app := testApp(nil, cfgFn, t)
	w := newCompatibleResponseRecorder()
	txn := app.StartTransaction("hello", w, helloRequest)

	txn.WriteHeader(http.StatusNotFound)

	txn.End()

	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, webMetrics)
}

func TestResponseCodeAfterEnd(t *testing.T) {
	app := testApp(nil, nil, t)
	w := newCompatibleResponseRecorder()
	txn := app.StartTransaction("hello", w, helloRequest)

	txn.End()
	txn.WriteHeader(http.StatusBadRequest)

	if http.StatusBadRequest != w.Code {
		t.Error(w.Code)
	}

	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, webMetrics)
}

func TestResponseCodeAfterWrite(t *testing.T) {
	app := testApp(nil, nil, t)
	w := newCompatibleResponseRecorder()
	txn := app.StartTransaction("hello", w, helloRequest)

	txn.Write([]byte("zap"))
	txn.WriteHeader(http.StatusBadRequest)

	txn.End()

	if out := w.Body.String(); "zap" != out {
		t.Error(out)
	}

	if http.StatusOK != w.Code {
		t.Error(w.Code)
	}

	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, webMetrics)
}

func TestQueueTime(t *testing.T) {
	app := testApp(nil, nil, t)
	req, err := http.NewRequest("GET", helloPath+helloQueryParams, nil)
	req.Header.Add("X-Queue-Start", "1465793282.12345")
	if nil != err {
		t.Fatal(err)
	}
	txn := app.StartTransaction("hello", nil, req)
	txn.NoticeError(myError{})
	txn.End()

	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "WebTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.myError",
		Caller:  "go-agent.TestQueueTime",
		URL:     "/hello",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
			"queueDuration":   internal.MatchAnything,
		},
	}})
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "WebFrontend/QueueTime", Scope: "", Forced: true, Data: nil},
	}, webErrorMetrics...))
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":             "WebTransaction/Go/hello",
			"nr.apdexPerfZone": "F",
			"queueDuration":    internal.MatchAnything,
		},
		AgentAttributes: nil,
	}})
}

func TestIgnore(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	txn.NoticeError(myError{})
	err := txn.Ignore()
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectErrors(t, []internal.WantError{})
	app.ExpectErrorEvents(t, []internal.WantEvent{})
	app.ExpectMetrics(t, []internal.WantMetric{})
	app.ExpectTxnEvents(t, []internal.WantEvent{})
}

func TestIgnoreAlreadyEnded(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	txn.NoticeError(myError{})
	txn.End()
	err := txn.Ignore()
	if err != errAlreadyEnded {
		t.Error(err)
	}
	app.ExpectErrors(t, []internal.WantError{{
		TxnName: "OtherTransaction/Go/hello",
		Msg:     "my msg",
		Klass:   "newrelic.myError",
		Caller:  "go-agent.TestIgnoreAlreadyEnded",
		URL:     "",
	}})
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "OtherTransaction/Go/hello",
		},
	}})
	app.ExpectMetrics(t, backgroundErrorMetrics)
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name": "OtherTransaction/Go/hello",
		},
	}})
}

func TestResponseCodeIsError(t *testing.T) {
	cfg := NewConfig("my app", "0123456789012345678901234567890123456789")

	if is := responseCodeIsError(&cfg, 200); is {
		t.Error(is)
	}
	if is := responseCodeIsError(&cfg, 400); !is {
		t.Error(is)
	}
	if is := responseCodeIsError(&cfg, 404); is {
		t.Error(is)
	}
	if is := responseCodeIsError(&cfg, 503); !is {
		t.Error(is)
	}
}

func TestExternalSegmentURL(t *testing.T) {
	rawURL := "http://url.com"
	req, err := http.NewRequest("GET", "http://request.com/", nil)
	if err != nil {
		t.Fatal(err)
	}
	responsereq, err := http.NewRequest("GET", "http://response.com/", nil)
	if err != nil {
		t.Fatal(err)
	}
	response := &http.Response{Request: responsereq}

	// empty segment
	u, err := externalSegmentURL(ExternalSegment{})
	host := internal.HostFromURL(u)
	if nil != err || nil != u || "" != host {
		t.Error(u, err, internal.HostFromURL(u))
	}
	// segment only containing url
	u, err = externalSegmentURL(ExternalSegment{URL: rawURL})
	host = internal.HostFromURL(u)
	if nil != err || host != "url.com" {
		t.Error(u, err, internal.HostFromURL(u))
	}
	// segment only containing request
	u, err = externalSegmentURL(ExternalSegment{Request: req})
	host = internal.HostFromURL(u)
	if nil != err || "request.com" != host {
		t.Error(host)
	}
	// segment only containing response
	u, err = externalSegmentURL(ExternalSegment{Response: response})
	host = internal.HostFromURL(u)
	if nil != err || "response.com" != host {
		t.Error(host)
	}
	// segment containing request and response
	u, err = externalSegmentURL(ExternalSegment{
		Request:  req,
		Response: response,
	})
	host = internal.HostFromURL(u)
	if nil != err || "response.com" != host {
		t.Error(host)
	}
	// segment containing url, request, and response
	u, err = externalSegmentURL(ExternalSegment{
		URL:      rawURL,
		Request:  req,
		Response: response,
	})
	host = internal.HostFromURL(u)
	if nil != err || "url.com" != host {
		t.Error(err, host)
	}
}

func TestZeroSegmentsSafe(t *testing.T) {
	s := Segment{}
	s.End()

	StartSegmentNow(nil)

	ds := DatastoreSegment{}
	ds.End()

	es := ExternalSegment{}
	es.End()

	StartSegment(nil, "").End()

	StartExternalSegment(nil, nil).End()
}

func TestTraceSegmentDefer(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	func() {
		defer StartSegment(txn, "segment").End()
	}()
	txn.End()
	scope := "WebTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "Custom/segment", Scope: "", Forced: false, Data: nil},
		{Name: "Custom/segment", Scope: scope, Forced: false, Data: nil},
	}, webMetrics...))
}

func TestTraceSegmentNilErr(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	err := StartSegment(txn, "segment").End()
	if nil != err {
		t.Error(err)
	}
	txn.End()
	scope := "WebTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "Custom/segment", Scope: "", Forced: false, Data: nil},
		{Name: "Custom/segment", Scope: scope, Forced: false, Data: nil},
	}, webMetrics...))
}

func TestTraceSegmentOutOfOrder(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s1 := StartSegment(txn, "s1")
	s2 := StartSegment(txn, "s1")
	err1 := s1.End()
	err2 := s2.End()
	if nil != err1 {
		t.Error(err1)
	}
	if nil == err2 {
		t.Error(err2)
	}
	txn.End()
	scope := "WebTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "Custom/s1", Scope: "", Forced: false, Data: nil},
		{Name: "Custom/s1", Scope: scope, Forced: false, Data: nil},
	}, webMetrics...))
}

func TestTraceSegmentEndedBeforeStartSegment(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	txn.End()
	s := StartSegment(txn, "segment")
	err := s.End()
	if err != errAlreadyEnded {
		t.Error(err)
	}
	app.ExpectMetrics(t, webMetrics)
}

func TestTraceSegmentEndedBeforeEndSegment(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s := StartSegment(txn, "segment")
	txn.End()
	err := s.End()
	if err != errAlreadyEnded {
		t.Error(err)
	}

	app.ExpectMetrics(t, webMetrics)
}

func TestTraceSegmentPanic(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	func() {
		defer func() {
			recover()
		}()

		func() {
			defer StartSegment(txn, "f1").End()

			func() {
				t := StartSegment(txn, "f2")

				func() {
					defer StartSegment(txn, "f3").End()

					func() {
						StartSegment(txn, "f4")

						panic(nil)
					}()
				}()

				t.End()
			}()
		}()
	}()

	txn.End()
	scope := "WebTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "Custom/f1", Scope: "", Forced: false, Data: nil},
		{Name: "Custom/f1", Scope: scope, Forced: false, Data: nil},
		{Name: "Custom/f3", Scope: "", Forced: false, Data: nil},
		{Name: "Custom/f3", Scope: scope, Forced: false, Data: nil},
	}, webMetrics...))
}

func TestTraceSegmentNilTxn(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s := Segment{Name: "hello"}
	err := s.End()
	if err != nil {
		t.Error(err)
	}
	txn.End()
	app.ExpectMetrics(t, webMetrics)
}

func TestTraceDatastore(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s := DatastoreSegment{}
	s.StartTime = txn.StartSegmentNow()
	s.Product = DatastoreMySQL
	s.Collection = "my_table"
	s.Operation = "SELECT"
	err := s.End()
	if nil != err {
		t.Error(err)
	}
	txn.NoticeError(myError{})
	txn.End()
	scope := "WebTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "Datastore/all", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/allWeb", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/MySQL/all", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/MySQL/allWeb", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/operation/MySQL/SELECT", Scope: "", Forced: false, Data: nil},
		{Name: "Datastore/statement/MySQL/my_table/SELECT", Scope: "", Forced: false, Data: nil},
		{Name: "Datastore/statement/MySQL/my_table/SELECT", Scope: scope, Forced: false, Data: nil},
	}, webErrorMetrics...))
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":       "newrelic.myError",
			"error.message":     "my msg",
			"transactionName":   "WebTransaction/Go/hello",
			"databaseCallCount": 1,
			"databaseDuration":  internal.MatchAnything,
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":              "WebTransaction/Go/hello",
			"nr.apdexPerfZone":  "F",
			"databaseCallCount": 1,
			"databaseDuration":  internal.MatchAnything,
		},
	}})
}

func TestTraceDatastoreBackground(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	s := DatastoreSegment{
		StartTime:  txn.StartSegmentNow(),
		Product:    DatastoreMySQL,
		Collection: "my_table",
		Operation:  "SELECT",
	}
	err := s.End()
	if nil != err {
		t.Error(err)
	}
	txn.NoticeError(myError{})
	txn.End()
	scope := "OtherTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "Datastore/all", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/allOther", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/MySQL/all", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/MySQL/allOther", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/operation/MySQL/SELECT", Scope: "", Forced: false, Data: nil},
		{Name: "Datastore/statement/MySQL/my_table/SELECT", Scope: "", Forced: false, Data: nil},
		{Name: "Datastore/statement/MySQL/my_table/SELECT", Scope: scope, Forced: false, Data: nil},
	}, backgroundErrorMetrics...))
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":       "newrelic.myError",
			"error.message":     "my msg",
			"transactionName":   "OtherTransaction/Go/hello",
			"databaseCallCount": 1,
			"databaseDuration":  internal.MatchAnything,
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":              "OtherTransaction/Go/hello",
			"databaseCallCount": 1,
			"databaseDuration":  internal.MatchAnything,
		},
	}})
}

func TestTraceDatastoreMissingProductOperationCollection(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s := DatastoreSegment{
		StartTime: txn.StartSegmentNow(),
	}
	err := s.End()
	if nil != err {
		t.Error(err)
	}
	txn.NoticeError(myError{})
	txn.End()
	scope := "WebTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "Datastore/all", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/allWeb", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/Unknown/all", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/Unknown/allWeb", Scope: "", Forced: true, Data: nil},
		{Name: "Datastore/operation/Unknown/other", Scope: "", Forced: false, Data: nil},
		{Name: "Datastore/operation/Unknown/other", Scope: scope, Forced: false, Data: nil},
	}, webErrorMetrics...))
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":       "newrelic.myError",
			"error.message":     "my msg",
			"transactionName":   "WebTransaction/Go/hello",
			"databaseCallCount": 1,
			"databaseDuration":  internal.MatchAnything,
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":              "WebTransaction/Go/hello",
			"nr.apdexPerfZone":  "F",
			"databaseCallCount": 1,
			"databaseDuration":  internal.MatchAnything,
		},
	}})
}

func TestTraceDatastoreNilTxn(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	var s DatastoreSegment
	s.Product = DatastoreMySQL
	s.Collection = "my_table"
	s.Operation = "SELECT"
	err := s.End()
	if nil != err {
		t.Error(err)
	}
	txn.NoticeError(myError{})
	txn.End()
	app.ExpectMetrics(t, webErrorMetrics)
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":             "WebTransaction/Go/hello",
			"nr.apdexPerfZone": "F",
		},
	}})
}

func TestTraceDatastoreTxnEnded(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	txn.NoticeError(myError{})
	s := DatastoreSegment{
		StartTime:  txn.StartSegmentNow(),
		Product:    DatastoreMySQL,
		Collection: "my_table",
		Operation:  "SELECT",
	}
	txn.End()
	err := s.End()
	if errAlreadyEnded != err {
		t.Error(err)
	}
	app.ExpectMetrics(t, webErrorMetrics)
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":             "WebTransaction/Go/hello",
			"nr.apdexPerfZone": "F",
		},
	}})
}

func TestTraceExternal(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s := ExternalSegment{
		StartTime: txn.StartSegmentNow(),
		URL:       "http://example.com/",
	}
	err := s.End()
	if nil != err {
		t.Error(err)
	}
	txn.NoticeError(myError{})
	txn.End()
	scope := "WebTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "External/all", Scope: "", Forced: true, Data: nil},
		{Name: "External/allWeb", Scope: "", Forced: true, Data: nil},
		{Name: "External/example.com/all", Scope: "", Forced: false, Data: nil},
		{Name: "External/example.com/all", Scope: scope, Forced: false, Data: nil},
	}, webErrorMetrics...))
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":       "newrelic.myError",
			"error.message":     "my msg",
			"transactionName":   "WebTransaction/Go/hello",
			"externalCallCount": 1,
			"externalDuration":  internal.MatchAnything,
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":              "WebTransaction/Go/hello",
			"nr.apdexPerfZone":  "F",
			"externalCallCount": 1,
			"externalDuration":  internal.MatchAnything,
		},
	}})
}

func TestTraceExternalBadURL(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s := ExternalSegment{
		StartTime: txn.StartSegmentNow(),
		URL:       ":example.com/",
	}
	err := s.End()
	if nil == err {
		t.Error(err)
	}
	txn.NoticeError(myError{})
	txn.End()
	app.ExpectMetrics(t, webErrorMetrics)
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":             "WebTransaction/Go/hello",
			"nr.apdexPerfZone": "F",
		},
	}})
}

func TestTraceExternalBackground(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	s := ExternalSegment{
		StartTime: txn.StartSegmentNow(),
		URL:       "http://example.com/",
	}
	err := s.End()
	if nil != err {
		t.Error(err)
	}
	txn.NoticeError(myError{})
	txn.End()
	scope := "OtherTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "External/all", Scope: "", Forced: true, Data: nil},
		{Name: "External/allOther", Scope: "", Forced: true, Data: nil},
		{Name: "External/example.com/all", Scope: "", Forced: false, Data: nil},
		{Name: "External/example.com/all", Scope: scope, Forced: false, Data: nil},
	}, backgroundErrorMetrics...))
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":       "newrelic.myError",
			"error.message":     "my msg",
			"transactionName":   "OtherTransaction/Go/hello",
			"externalCallCount": 1,
			"externalDuration":  internal.MatchAnything,
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":              "OtherTransaction/Go/hello",
			"externalCallCount": 1,
			"externalDuration":  internal.MatchAnything,
		},
	}})
}

func TestTraceExternalMissingURL(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s := ExternalSegment{
		StartTime: txn.StartSegmentNow(),
	}
	err := s.End()
	if nil != err {
		t.Error(err)
	}
	txn.NoticeError(myError{})
	txn.End()
	scope := "WebTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "External/all", Scope: "", Forced: true, Data: nil},
		{Name: "External/allWeb", Scope: "", Forced: true, Data: nil},
		{Name: "External/unknown/all", Scope: "", Forced: false, Data: nil},
		{Name: "External/unknown/all", Scope: scope, Forced: false, Data: nil},
	}, webErrorMetrics...))
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":       "newrelic.myError",
			"error.message":     "my msg",
			"transactionName":   "WebTransaction/Go/hello",
			"externalCallCount": 1,
			"externalDuration":  internal.MatchAnything,
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":              "WebTransaction/Go/hello",
			"nr.apdexPerfZone":  "F",
			"externalCallCount": 1,
			"externalDuration":  internal.MatchAnything,
		},
	}})
}

func TestTraceExternalNilTxn(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	txn.NoticeError(myError{})
	var s ExternalSegment
	err := s.End()
	if nil != err {
		t.Error(err)
	}
	txn.End()
	app.ExpectMetrics(t, webErrorMetrics)
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":             "WebTransaction/Go/hello",
			"nr.apdexPerfZone": "F",
		},
	}})
}

func TestTraceExternalTxnEnded(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	txn.NoticeError(myError{})
	s := ExternalSegment{
		StartTime: txn.StartSegmentNow(),
		URL:       "http://example.com/",
	}
	txn.End()
	err := s.End()
	if err != errAlreadyEnded {
		t.Error(err)
	}
	app.ExpectMetrics(t, webErrorMetrics)
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":     "newrelic.myError",
			"error.message":   "my msg",
			"transactionName": "WebTransaction/Go/hello",
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":             "WebTransaction/Go/hello",
			"nr.apdexPerfZone": "F",
		},
	}})
}

func TestRoundTripper(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	url := "http://example.com/"
	client := &http.Client{}
	inner := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
		// TODO test that request headers have been set here.
		if r.URL.String() != url {
			t.Error(r.URL.String())
		}
		return nil, errors.New("hello")
	})
	client.Transport = NewRoundTripper(txn, inner)
	resp, err := client.Get(url)
	if resp != nil || err == nil {
		t.Error(resp, err.Error())
	}
	txn.NoticeError(myError{})
	txn.End()
	scope := "OtherTransaction/Go/hello"
	app.ExpectMetrics(t, append([]internal.WantMetric{
		{Name: "External/all", Scope: "", Forced: true, Data: nil},
		{Name: "External/allOther", Scope: "", Forced: true, Data: nil},
		{Name: "External/example.com/all", Scope: "", Forced: false, Data: nil},
		{Name: "External/example.com/all", Scope: scope, Forced: false, Data: nil},
	}, backgroundErrorMetrics...))
	app.ExpectErrorEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"error.class":       "newrelic.myError",
			"error.message":     "my msg",
			"transactionName":   "OtherTransaction/Go/hello",
			"externalCallCount": 1,
			"externalDuration":  internal.MatchAnything,
		},
	}})
	app.ExpectTxnEvents(t, []internal.WantEvent{{
		Intrinsics: map[string]interface{}{
			"name":              "OtherTransaction/Go/hello",
			"externalCallCount": 1,
			"externalDuration":  internal.MatchAnything,
		},
	}})
}

func TestTraceBelowThreshold(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	txn.End()
	app.ExpectTxnTraces(t, []internal.WantTxnTrace{})
}

func TestTraceBelowThresholdBackground(t *testing.T) {
	app := testApp(nil, nil, t)
	txn := app.StartTransaction("hello", nil, nil)
	txn.End()
	app.ExpectTxnTraces(t, []internal.WantTxnTrace{})
}

func TestTraceNoSegments(t *testing.T) {
	cfgfn := func(cfg *Config) {
		cfg.TransactionTracer.Threshold.IsApdexFailing = false
		cfg.TransactionTracer.Threshold.Duration = 0
		cfg.TransactionTracer.SegmentThreshold = 0
	}
	app := testApp(nil, cfgfn, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	txn.End()
	app.ExpectTxnTraces(t, []internal.WantTxnTrace{{
		MetricName:  "WebTransaction/Go/hello",
		CleanURL:    "/hello",
		NumSegments: 0,
	}})
}

func TestTraceDisabledLocally(t *testing.T) {
	cfgfn := func(cfg *Config) {
		cfg.TransactionTracer.Threshold.IsApdexFailing = false
		cfg.TransactionTracer.Threshold.Duration = 0
		cfg.TransactionTracer.SegmentThreshold = 0
		cfg.TransactionTracer.Enabled = false
	}
	app := testApp(nil, cfgfn, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	txn.End()
	app.ExpectTxnTraces(t, []internal.WantTxnTrace{})
}

func TestTraceDisabledRemotely(t *testing.T) {
	cfgfn := func(cfg *Config) {
		cfg.TransactionTracer.Threshold.IsApdexFailing = false
		cfg.TransactionTracer.Threshold.Duration = 0
		cfg.TransactionTracer.SegmentThreshold = 0
	}
	replyfn := func(reply *internal.ConnectReply) {
		reply.CollectTraces = false
	}
	app := testApp(replyfn, cfgfn, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	txn.End()
	app.ExpectTxnTraces(t, []internal.WantTxnTrace{})
}

func TestTraceWithSegments(t *testing.T) {
	cfgfn := func(cfg *Config) {
		cfg.TransactionTracer.Threshold.IsApdexFailing = false
		cfg.TransactionTracer.Threshold.Duration = 0
		cfg.TransactionTracer.SegmentThreshold = 0
	}
	app := testApp(nil, cfgfn, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s1 := StartSegment(txn, "s1")
	s1.End()
	s2 := ExternalSegment{
		StartTime: StartSegmentNow(txn),
		URL:       "http://example.com",
	}
	s2.End()
	s3 := DatastoreSegment{
		StartTime:  StartSegmentNow(txn),
		Product:    DatastoreMySQL,
		Collection: "my_table",
		Operation:  "SELECT",
	}
	s3.End()
	txn.End()
	app.ExpectTxnTraces(t, []internal.WantTxnTrace{{
		MetricName:  "WebTransaction/Go/hello",
		CleanURL:    "/hello",
		NumSegments: 3,
	}})
}

func TestTraceSegmentsBelowThreshold(t *testing.T) {
	cfgfn := func(cfg *Config) {
		cfg.TransactionTracer.Threshold.IsApdexFailing = false
		cfg.TransactionTracer.Threshold.Duration = 0
		cfg.TransactionTracer.SegmentThreshold = 1 * time.Hour
	}
	app := testApp(nil, cfgfn, t)
	txn := app.StartTransaction("hello", nil, helloRequest)
	s1 := StartSegment(txn, "s1")
	s1.End()
	s2 := ExternalSegment{
		StartTime: StartSegmentNow(txn),
		URL:       "http://example.com",
	}
	s2.End()
	s3 := DatastoreSegment{
		StartTime:  StartSegmentNow(txn),
		Product:    DatastoreMySQL,
		Collection: "my_table",
		Operation:  "SELECT",
	}
	s3.End()
	txn.End()
	app.ExpectTxnTraces(t, []internal.WantTxnTrace{{
		MetricName:  "WebTransaction/Go/hello",
		CleanURL:    "/hello",
		NumSegments: 0,
	}})
}


text:
import {
    AmbientLight,
    Camera,
    OrthographicCamera,
    PerspectiveCamera,
    SpotLight,
} from "three";
import { ThreeRenderView } from "../../../engine/renderer/render-view/ThreeRenderView";
import { PlayState } from "../PlayState";
import { Dimension } from "../../../engine/math/Dimension";

export class PlayRenderView extends ThreeRenderView {
    public camera?: PerspectiveCamera = undefined;
    private state: PlayState;
    private map: any;
    private _cameraFollowView?: any;
    private _cameraFollowLight?: SpotLight;

    constructor(state: PlayState) {
        super();

        this.state = state;
        this.map = this.state.map;
    }

    get cameraFollowView(): any {
        return this._cameraFollowView as any;
    }

    get cameraFollowLight(): SpotLight {
        return this._cameraFollowLight as SpotLight;
    }

    changeSize(size: Dimension) {
        super.changeSize(size);

        this.init();
    }

    init() {
        super.init();

        this.camera = new PerspectiveCamera(
            75,
            this.map.width / this.map.height,
            100,
            1000
        );

        this.getCamera().position.x =
            (this.map.width / 2) * this.map.blockWidth;
        this.getCamera().position.y =
            (this.map.height / 2) * this.map.blockHeight;
        this.getCamera().position.z = this.map.blockDepth * 6;

        const ambientLight = new AmbientLight(0x030303);

        this.scene.add(ambientLight);

        this._cameraFollowLight = new SpotLight(0xfffffff, 2, 800);
        this._cameraFollowLight.angle = 135 * (Math.PI / 180);
        this._cameraFollowLight.exponent = 10;
        this._cameraFollowLight.target = this._cameraFollowView.mesh;

        this.scene.add(this._cameraFollowLight);

        this._initialized = true;
    }

    update(delta: number) {
        if (this.state.paused) {
            return;
        }

        super.update(delta);

        if (this.cameraFollowView) {
            this.getCamera().position.setX(this.cameraFollowView.position.x);
            this.getCamera().position.setY(this.cameraFollowView.position.y);

            this.cameraFollowLight.position.setX(
                this.cameraFollowView.position.x
            );
            this.cameraFollowLight.position.setY(
                this.cameraFollowView.position.y
            );
            this.cameraFollowLight.position.setZ(
                this.cameraFollowView.position.z + 400
            );
        }
    }

    getCamera(): Camera | OrthographicCamera | PerspectiveCamera {
        return this.camera as PerspectiveCamera;
    }
}


text:
$(document).ready(function () {
  window.resetVotes = function () {
    localStorage.votedArray = "";
	  if (localStorage.host) {
    localStorage.setItem("STOP", "true");
    var object = {};
    object["userName"] = localStorage.userID;
     $.ajax({
         async: false,
         type: "POST",
         url: "http://spartify.herokuapp.com/clearVotes",
         dataType: "json",
         data: object,
         success: function (clearedData) {
           localStorage.STOP = "false";
           localStorage.votedArray = "";
	   location.reload();
         }
    });
	  }
}
    if (!document.hidden) {
    var userID;
    var baseURL;
    var searchQry;
    var myDataLength;
    var partyPlaylist;
    var listOfTracks = [];
    $("#filename").on('blur', function () {
	        $("#searchBoxContainer").css("margin-top", "0px !important");
	    	        $("#searchBoxContainer").css("position", "fixed");
	    	        $("#albumArt").css("position", "fixed");
	    	        $("#all").css("display", "block");
	    $("#html").scrollTop(0);
    });
    $("#searchBoxContainer").focus(function () {
       $("#html").scrollTop(0);
	    newToken();
    });
    $("#filename").on('focus', function () {
	        $("#searchBoxContainer").css("margin-top", "0px !important");
	    	        $("#searchBoxContainer").css("position", "absolute");
	    	        $("#albumArt").css("position", "absolute");
	    	        $("#all").css("display", "none");
	    $("#html").scrollTop(0);
	    $("#html").scroll(function(e){ e.preventDefault(); e.stopPropogagtion();});
    });
    $('#filename').on('keypress', function () {
	    $("#html").scroll(function(e){ e.preventDefault(); e.stopPropogagtion();});
   // $("#filename").keydown(function (event) {
       if (event.which === 13) {
	    $("#filename").blur();
            if (document.getElementById('filename').value.toLowerCase() == "logout." && localStorage["complete_access"] != "false" && localStorage["complete_access"] != false)
            {
		function closeWin() {
		    setTimeout(function()
		    {
			localStorage.clear();
    }, 2000);
		}
closeWin();
            }
            else if (document.getElementById('filename').value.toLowerCase() == "fullscreen." || document.getElementById('filename').value.toLowerCase() == "fs.") {
		var elem = document.getElementById("html");
		function toggleFullScreen() {
		  if ((document.fullScreenElement && document.fullScreenElement !== null) ||
		   (!document.mozFullScreen && !document.webkitIsFullScreen)) {
		    if (document.documentElement.requestFullScreen) {
		      document.documentElement.requestFullScreen();
		    } else if (document.documentElement.mozRequestFullScreen) {
		      document.documentElement.mozRequestFullScreen();
		    } else if (document.documentElement.webkitRequestFullScreen) {
		      document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
		    }
		  } else {
		    if (document.cancelFullScreen) {
		      document.cancelFullScreen();
		    } else if (document.mozCancelFullScreen) {
		      document.mozCancelFullScreen();
		    } else if (document.webkitCancelFullScreen) {
		      document.webkitCancelFullScreen();
		    }
		  }
		}
		toggleFullScreen();
		document.getElementById('filename').value = "";
		nextSongs();
            }
		else if (document.getElementById('filename').value.toLowerCase() == "c.") {
			localStorage.votedArray = "";
			window.location.reload();
		}
    else if (document.getElementById('filename').value.toLowerCase() == "clear votes.") {
resetVotes();
}
else if (document.getElementById('filename').value.toLowerCase() == "temp.") {
localStorage.setItem("temp", true);
}
else if (document.getElementById('filename').value.toLowerCase() == localStorage.password + "." || document.getElementById('filename').value.toLowerCase() == "i really want unlimited voting." || document.getElementById('filename').value.toLowerCase() == "uv.") {
resetVotes(1);
                localStorage.setItem("uv", "true");
                $("#filename").val("");
                nextSongs();
}
else if (document.getElementById('filename').value.toLowerCase() == "reload.") {
            	loading();
            	setTimeout(function(){
		window.location.reload();
		}, 1000);
            }
            else if (document.getElementById('filename').value.toLowerCase() == "leave party.") {
            	loading();
                window.localStorage.clear("CT");
                window.localStorage.clear("Snapster");
                window.localStorage.clear("clicked");
                window.localStorage.clear("currentTrack");
                window.localStorage.clear("current_token");
                window.localStorage.clear("complete_access");
                window.localStorage.clear("currentlyPlaying");
                window.localStorage.clear("currentlyPlayingID");
                window.localStorage.clear("currentlyPlayingWC");
                window.localStorage.clear("explicit");
                window.localStorage.clear("host");
                window.localStorage.clear("myData");
                window.localStorage.clear("lastFM");
                window.localStorage.clear("partyid");
                window.localStorage.clear("offsetNumber");
                window.localStorage.clear("totalSongs");
                window.localStorage.clear("url");
                window.localStorage.clear("userID");
                window.location.href = "http://spartify.herokuapp.com/thank-you-host.html";
            }
            else if (document.getElementById('filename').value.toLowerCase() == localStorage["password"].toString().toLowerCase() + ".") {
            	 localStorage["power_voter"] = "yes";
               location.reload();
       	    }
            else if (document.getElementById('filename').value == "") {
		nextSongs();
		$("#albumart").show();
		$("#results").attr("style", "");
		}
            else if (localStorage.Snapster) {
                try {
                    partyPlaylist = [];
                    baseURL = "https://api.spotify.com/v1/users/";
                    userID = localStorage.userID;
                    searchQry = document.getElementById('filename').value.toLowerCase();
                    $.ajax({
                        type: "GET",
                        url: "https://api.spotify.com/v1/search?q=" + searchQry + "&type=track,artist&market=us&limit=50&offset=0",
                        headers: { 'Authorization': 'Bearer ' + localStorage.current_token  },
                        dataType: "json",
                        data: "formdata",
                        success: function (myData) {
                            $("#albumart").hide();
                            $("#results").empty();
                            myDataLength = myData.tracks.items.length;
                            for (i = 0; i < myData.tracks.items.length; i++) {
                                if (localStorage["explicit"] != "true" && localStorage["explicit"] != true) {
                                    if (myData.tracks.items[i].explicit == false || myData.tracks.items[i].explicit == "false" && localStorage.CT.indexOf(myData.items[i].track.id) == -1) {
                                        $("#results").append("" + "

" + myData.tracks.items[i].artists[0].name + "

" + myData.tracks.items[i].name + "

 +
 ");
                                    }
                                }
                                else if (localStorage.CT.indexOf(myData.tracks.items[i].id) == -1) {
                                    $("#results").append("" + "

" + myData.tracks.items[i].artists[0].name + "

" + myData.tracks.items[i].name + "

 +
 ");
                                }
                            }
                            $("#results").css("padding-top", "86px");
                            $("#all").fadeIn(1000);
                        }
                    });
            }

                catch (exception) {
					// console.log(exception);
}

}
}
});
window.newSong = function(i) {
    $.ajax({
        type: "POST",
        url: $("#songLink" + i)[0].attributes[4].value,
        headers: { 'Authorization': 'Bearer ' + access_token  },
        dataType: "json",
        data: "formdata",
        success: function (dataFirst) {
            $("#filename").val("");
            $("#results").css("padding-top", "");
            $("#results").hide().fadeIn('fast');
            nextSongs();
            partyPlaylist = [];
            $("#albumart").show();
            $("#albumart").fadeIn(1000);
            $("#results").empty();
            $("#results").css("text-align", "center");
            $("#results").css("padding-top", "298px");
            $.ajax({
                type: "GET",
                url: "https://api.spotify.com/v1/users/" + localStorage['userID'] + "/playlists/" + localStorage['Snapster'] + "/tracks",
                headers: { 'Authorization': 'Bearer ' + access_token  },
                dataType: "json",
                data: "formdata",
                success: function (currentPLData) {
                    $("#filename").val("");
                    $("#results").css("padding-top", "");
                    $("#results").hide().fadeIn('fast');
                    nextSongs();
                }
            });
        }
    });
}

               }
});


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Jasmine Spec Runner v4.0.1</title>

    <link rel="stylesheet" href="./jasmine/jasmine.css" />

    <script src="./jasmine/jasmine.js"></script>
    <script src="./jasmine/jasmine-html.js"></script>
    <script src="./jasmine/boot0.js"></script>
    <script type="module" src="./spec-main.js"></script>
    <script src="./jasmine/boot1.js"></script>
  </head>
  <body>
    <script>
      if (window.location.search.indexOf("built") !== -1) {
        if (window.location.search.indexOf("release") !== -1) {
          document.write('<script src="../Build/Cesium/Cesium.js"><\/script>');
        } else {
          document.write(
            '<script src="../Build/CesiumUnminified/Cesium.js"><\/script>'
          );
        }
        document.write('<script src="../Build/Specs/Specs.js"><\/script>');
      } else {
        window.CESIUM_BASE_URL = "../Source/";
        document.write('<script type="module" src="./SpecList.js"><\/script>');
      }
    </script>
  </body>
</html>