text:
using Xunit;

namespace FlexProviders.Tests.Integration.Raven.OAuth
{
    public class DeleteAccountTests : IntegrationTest
    {
        [Fact]
        public void Can_Delete_OAuthAccount()
        {
            MembershipProvider.CreateOAuthAccount("Microsoft", "bitmask", new User { Username = "sallen"});
            MembershipProvider.CreateOAuthAccount("Google", "bitmask", new User { Username = "sallen"});

            var result = MembershipProvider.DisassociateOAuthAccount("Google", "bitmask");

            Assert.True(result);
        }

        [Fact]
        public void Can_Not_Delete_Last_Account()
        {
            MembershipProvider.CreateOAuthAccount("Google", "bitmask", new User { Username = "sallen" });

            var result = MembershipProvider.DisassociateOAuthAccount("Google", "bitmask");

            Assert.False(result);
        }

        [Fact]
        public void Does_Not_Leave_Orphan_Records()
        {
            MembershipProvider.CreateOAuthAccount("Microsoft", "bitmask", new User { Username = "sallen" });
            MembershipProvider.CreateOAuthAccount("Google", "bitmask", new User { Username = "sallen" });
            MembershipProvider.DisassociateOAuthAccount("Google", "bitmask");

            Assert.DoesNotThrow(() => MembershipProvider.CreateOAuthAccount("Google", "bitmask", new User { Username = "sallen" }));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
function deg = rad2deg(rad)
% RAD2DEG Convert radians to degrees.
	deg = rad./(pi/180);
end


text:
package org.zaproxy.zap.extension.websocket.pscan;

import org.zaproxy.zap.extension.websocket.WebSocketMessageDTO;
import org.zaproxy.zap.extension.websocket.alerts.WebSocketAlertRaiser;

/**
 * This interface implemented by {@link WebSocketScanHelper} and is used in {@link
 * WebSocketPassiveScanner#scanMessage(WebSocketScanHelper, WebSocketMessageDTO)} in order to
 * provide some useful utilities at WebSocketPlugin.
 */
public interface WebSocketScanHelper {

    /** Use this method to build and raise an Alert. */
    WebSocketAlertRaiser newAlert();
}


text:
.. currentmodule:: zsensor

:mod:`zsensor` --- Zephyr sensor bindings
=========================================

.. module:: zsensor
    :synopsis: zephyr sensor bindings

The ``zsensor`` module contains a class for using sensors with Zephyr.

.. _zsensor.Sensor:

class Sensor --- sensor control for the Zephyr port
---------------------------------------------------

Use this class to access data from sensors on your board.
See Zephyr documentation for sensor usage here: `Sensors
<https://docs.zephyrproject.org/latest/reference/peripherals/sensor.html?highlight=sensor#sensors>`_.

Sensors are defined in the Zephyr devicetree for each board. The quantities that a given sensor can
measure are called a sensor channels. Sensors can have multiple channels to represent different axes
of one property or different properties a sensor can measure. See `Channels`_ below for defined sensor
channels.

Constructor
~~~~~~~~~~~

.. class:: Sensor(device_name)

    Device names are defined in the devicetree for your board.
    For example, the device name for the accelerometer in the FRDM-k64f board is "FXOS8700".

Methods
~~~~~~~

.. method:: Sensor.measure()

    Obtains a measurement sample from the sensor device using Zephyr sensor_sample_fetch and
    stores it in an internal driver buffer as a useful value, a pair of (integer part of value,
    fractional part of value in 1-millionths).
    Returns none if successful or OSError value if failure.

.. method:: Sensor.get_float(sensor_channel)

    Returns the value of the sensor measurement sample as a float.

.. method:: Sensor.get_micros(sensor_channel)

    Returns the value of the sensor measurement sample in millionths.
    (Ex. value of ``(1, 500000)`` returns as ``1500000``)

.. method:: Sensor.get_millis(sensor_channel)

    Returns the value of sensor measurement sample in thousandths.
    (Ex. value of ``(1, 500000)`` returns as ``1500``)

.. method:: Sensor.get_int(sensor_channel)

    Returns only the integer value of the measurement sample.
    (Ex. value of ``(1, 500000)`` returns as ``1``)

Channels
~~~~~~~~

.. data:: ACCEL_X

    Acceleration on the X axis, in m/s^2.

.. data:: ACCEL_Y

    Acceleration on the Y axis, in m/s^2.

.. data:: ACCEL_Z

    Acceleration on the Z axis, in m/s^2.

.. data:: GYRO_X

    Angular velocity around the X axis, in radians/s.

.. data:: GYRO_Y

    Angular velocity around the Y axis, in radians/s.

.. data:: GYRO_Z

    Angular velocity around the Z axis, in radians/s.

.. data:: MAGN_X

    Magnetic field on the X axis, in Gauss.

.. data:: MAGN_Y

    Magnetic field on the Y axis, in Gauss.

.. data:: MAGN_Z

    Magnetic field on the Z axis, in Gauss.

.. data:: DIE_TEMP

    Device die temperature in degrees Celsius.

.. data:: PRESS

    Pressure in kilopascal.

.. data:: PROX

    Proximity. Dimensionless. A value of 1 indicates that an object is close.

.. data:: HUMIDITY

    Humidity, in percent.

.. data:: LIGHT

    Illuminance in visible spectrum, in lux.

.. data:: ALTITUDE

    Altitude, in meters.


text:
set -eo pipefail
mkdir -p phyloP && cd phyloP
wget -c http://hgdownload-test.cse.ucsc.edu/goldenPath/ce10/phyloP9way/ce10.phyloP9way.bw


text:
package org.apache.struts2.dispatcher;

import org.apache.struts2.StrutsInternalTestCase;

import java.util.List;

public class DefaultStaticContentLoaderTest extends StrutsInternalTestCase {

    public void testParsePackages() throws Exception {

        DefaultStaticContentLoader filterDispatcher = new DefaultStaticContentLoader();
        List<String> result1 = filterDispatcher.parse("foo.bar.package1 foo.bar.package2 foo.bar.package3");
        List<String> result2 = filterDispatcher.parse("foo.bar.package1\tfoo.bar.package2\tfoo.bar.package3");
        List<String> result3 = filterDispatcher.parse("foo.bar.package1,foo.bar.package2,foo.bar.package3");
        List<String> result4 = filterDispatcher.parse("foo.bar.package1    foo.bar.package2  \t foo.bar.package3   , foo.bar.package4");

        assertEquals(result1.get(0), "foo/bar/package1/");
        assertEquals(result1.get(1), "foo/bar/package2/");
        assertEquals(result1.get(2), "foo/bar/package3/");

        assertEquals(result2.get(0), "foo/bar/package1/");
        assertEquals(result2.get(1), "foo/bar/package2/");
        assertEquals(result2.get(2), "foo/bar/package3/");

        assertEquals(result3.get(0), "foo/bar/package1/");
        assertEquals(result3.get(1), "foo/bar/package2/");
        assertEquals(result3.get(2), "foo/bar/package3/");

        assertEquals(result4.get(0), "foo/bar/package1/");
        assertEquals(result4.get(1), "foo/bar/package2/");
        assertEquals(result4.get(2), "foo/bar/package3/");
        assertEquals(result4.get(3), "foo/bar/package4/");
    }

}


text:
#ifndef LWIP_HDR_TEST_SOCKETS_STRESSTEST
#define LWIP_HDR_TEST_SOCKETS_STRESSTEST

void sockets_stresstest_init_loopback(int addr_family);
void sockets_stresstest_init_server(int addr_family, u16_t server_port);
void sockets_stresstest_init_client(const char *remote_ip, u16_t remote_port);

#endif /* LWIP_HDR_TEST_SOCKETS_STRESSTEST */


text:
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import config from '@/config'

async function execute({layout, assets}) {

	let layoutData = JSON.stringify(layout, 4, 4);
	let layoutObj = JSON.parse(layoutData);

	// @TODO check if asset validation/filtering

	let ext, blob;
	if (assets && Object.keys(assets).length) {

		let zip = new JSZip();
		for (let name in assets) {

			let file = assets[name];
			await zip.file(name, file);
		}

		ext = 'taction-bundle';
		await zip.file('layout.json', layoutData);
		blob = await zip.generateAsync({type: 'blob'});

	} else {

		ext = 'json';
		blob = new Blob([layoutData], {type: 'application/json;charset=utf-8'});
	}

	let name = layoutObj.name || 'Untitled';
	name = name.substr(0, config.maximumExportFileNameLength - 1 - ext.length) + '.' + ext;
	FileSaver.saveAs(blob, name);
}

export default execute;


text:
// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using Cci = Microsoft.Cci;

// ^ using Microsoft.Contracts;

namespace Microsoft.Cci
{
    /// <summary>
    /// An object corresponding to a metadata entity such as a type or a field.
    /// </summary>
    internal interface IDefinition : IReference
    {
    }

    /// <summary>
    /// An object corresponding to reference to a metadata entity such as a type or a field.
    /// </summary>
    internal interface IReference
    {
        /// <summary>
        /// A collection of metadata custom attributes that are associated with this definition.
        /// </summary>
        IEnumerable<ICustomAttribute> GetAttributes(Microsoft.CodeAnalysis.Emit.Context context); // TODO: consider moving this to IDefinition, we shouldn't need to examine attributes on references.

        /// <summary>
        /// Calls the visitor.Visit(T) method where T is the most derived object model node interface type implemented by the concrete type
        /// of the object implementing IDefinition. The dispatch method does not invoke Dispatch on any child objects. If child traversal
        /// is desired, the implementations of the Visit methods should do the subsequent dispatching.
        /// </summary>
        void Dispatch(MetadataVisitor visitor);

        /// <summary>
        /// Gets the definition object corresponding to this reference within the given context,
        /// or null if the referenced entity isn't defined in the context.
        /// </summary>
        IDefinition AsDefinition(Microsoft.CodeAnalysis.Emit.Context context);
    }

    /// <summary>
    /// An object that represents a document. This can be either source or binary or designer surface etc
    /// </summary>
    internal interface Document
    {
        /// <summary>
        /// The location where this document was found, or where it should be stored.
        /// This will also uniquely identify the source document within an instance of compilation host.
        /// </summary>
        string Location { get; }

        /// <summary>
        /// The name of the document. For example the name of the file if the document corresponds to a file.
        /// </summary>
        string Name { get; }
    }
}


text:
//>>built
define("dojox/charting/plot2d/ClusteredColumns", ["dojo/_base/array", "dojo/_base/declare", "./Columns", "./common",
		"dojox/lang/functional", "dojox/lang/functional/reversed", "dojox/lang/utils"],
	function(arr, declare, Columns, dc, df, dfr, du){
/*=====
var Columns = dojox.charting.plot2d.Columns;
=====*/

	var purgeGroup = dfr.lambda("item.purgeGroup()");

	return declare("dojox.charting.plot2d.ClusteredColumns", Columns, {
		//	summary:
		//		A plot representing grouped or clustered columns (vertical bars).
		render: function(dim, offsets){
			//	summary:
			//		Run the calculations for any axes for this plot.
			//	dim: Object
			//		An object in the form of { width, height }
			//	offsets: Object
			//		An object of the form { l, r, t, b}.
			//	returns: dojox.charting.plot2d.ClusteredColumns
			//		A reference to this plot for functional chaining.
			if(this.zoom && !this.isDataDirty()){
				return this.performZoom(dim, offsets);
			}
			this.resetEvents();
			this.dirty = this.isDirty();
			if(this.dirty){
				arr.forEach(this.series, purgeGroup);
				this._eventSeries = {};
				this.cleanGroup();
				var s = this.group;
				df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
			}
			var t = this.chart.theme, f, gap, width, thickness,
				ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
				vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
				baseline = Math.max(0, this._vScaler.bounds.lower),
				baselineHeight = vt(baseline),
				events = this.events();
			f = dc.calculateBarSize(this._hScaler.bounds.scale, this.opt, this.series.length);
			gap = f.gap;
			width = thickness = f.size;
			for(var i = 0; i < this.series.length; ++i){
				var run = this.series[i], shift = thickness * i;
				if(!this.dirty && !run.dirty){
					t.skip();
					this._reconnectEvents(run.name);
					continue;
				}
				run.cleanGroup();
				var theme = t.next("column", [this.opt, run]), s = run.group,
					eventSeries = new Array(run.data.length);
				for(var j = 0; j < run.data.length; ++j){
					var value = run.data[j];
					if(value !== null){
						var v = typeof value == "number" ? value : value.y,
							vv = vt(v),
							height = vv - baselineHeight,
							h = Math.abs(height),
							finalTheme = typeof value != "number" ?
								t.addMixin(theme, "column", value, true) :
								t.post(theme, "column");
						if(width >= 1 && h >= 0){
							var rect = {
								x: offsets.l + ht(j + 0.5) + gap + shift,
								y: dim.height - offsets.b - (v > baseline ? vv : baselineHeight),
								width: width, height: h
							};
							var specialFill = this._plotFill(finalTheme.series.fill, dim, offsets);
							specialFill = this._shapeFill(specialFill, rect);
							var shape = s.createRect(rect).setFill(specialFill).setStroke(finalTheme.series.stroke);
							run.dyn.fill   = shape.getFill();
							run.dyn.stroke = shape.getStroke();
							if(events){
								var o = {
									element: "column",
									index:   j,
									run:     run,
									shape:   shape,
									x:       j + 0.5,
									y:       v
								};
								this._connectEvents(o);
								eventSeries[j] = o;
							}
							if(this.animate){
								this._animateColumn(shape, dim.height - offsets.b - baselineHeight, h);
							}
						}
					}
				}
				this._eventSeries[run.name] = eventSeries;
				run.dirty = false;
			}
			this.dirty = false;
			return this;	//	dojox.charting.plot2d.ClusteredColumns
		}
	});
});


text: var app = angular.module('Wop', []);


text:
package unicom

import (
	"context"
	"fmt"
	"time"

	"go-common/app/job/main/app-wall/model/unicom"
	"go-common/library/cache/memcache"
	"go-common/library/log"
)

const (
	_prefix          = "unicoms_user_%v"
	_userbindkey     = "unicoms_user_bind_%d"
	_userbindreceive = "unicom_pack_receives_%d"
	_userflowkey     = "unicom_user_flow_%v"
	_userflowlistkey = "unicom_user_flow_list"
)

func keyUserBind(mid int64) string {
	return fmt.Sprintf(_userbindkey, mid)
}

func keyUserBindReceive(mid int64) string {
	return fmt.Sprintf(_userbindreceive, mid)
}

func keyUnicom(usermob string) string {
	return fmt.Sprintf(_prefix, usermob)
}

func keyUserFlow(key string) string {
	return fmt.Sprintf(_userflowkey, key)
}

// UserBindCache user bind cache
func (d *Dao) UserBindCache(c context.Context, mid int64) (ub *unicom.UserBind, err error) {
	var (
		key  = keyUserBind(mid)
		conn = d.mc.Get(c)
		r    *memcache.Item
	)
	defer conn.Close()
	if r, err = conn.Get(key); err != nil {
		if err != memcache.ErrNotFound {
			log.Error("UserBindCache error(%v) or mid(%v)", err, mid)
		}
		return
	}
	if err = conn.Scan(r, &ub); err != nil {
		log.Error("r.Scan(%s) error(%v)", r.Value, err)
	}
	return
}

// AddUserBindCache add user user bind cache
func (d *Dao) AddUserBindCache(c context.Context, mid int64, ub *unicom.UserBind) (err error) {
	var (
		key  = keyUserBind(mid)
		conn = d.mc.Get(c)
	)
	if err = conn.Set(&memcache.Item{Key: key, Object: ub, Flags: memcache.FlagJSON, Expiration: 0}); err != nil {
		log.Error("AddUserBindCache d.mc.Set(%s,%v) error(%v)", key, ub, err)
	}
	conn.Close()
	return
}

// DeleteUserBindCache delete user bind cache
func (d *Dao) DeleteUserBindCache(c context.Context, mid int64) (err error) {
	var (
		key  = keyUserBind(mid)
		conn = d.mc.Get(c)
	)
	defer conn.Close()
	if err = conn.Delete(key); err != nil {
		if err == memcache.ErrNotFound {
			err = nil
			return
		}
		log.Error("DeleteUserBindCache MemchDB.Delete(%s) error(%v)", key, err)
		return
	}
	return
}

// UserPackReceiveCache user pack cache
func (d *Dao) UserPackReceiveCache(c context.Context, mid int64) (count int, err error) {
	var (
		key  = keyUserBindReceive(mid)
		conn = d.mc.Get(c)
		r    *memcache.Item
	)
	defer conn.Close()
	if r, err = conn.Get(key); err != nil {
		if err == memcache.ErrNotFound {
			err = nil
			return
		}
		log.Error("UserBindCache MemchDB.Get(%s) error(%v)", key, err)
		return
	}
	if err = conn.Scan(r, &count); err != nil {
		log.Error("r.Scan(%s) error(%v)", r.Value, err)
	}
	return
}

// AddUserPackReceiveCache add user pack cache
func (d *Dao) AddUserPackReceiveCache(c context.Context, mid int64, count int, now time.Time) (err error) {
	var (
		key            = keyUserBindReceive(mid)
		conn           = d.mc.Get(c)
		currenttimeSec = int32((now.Hour() * 60 * 60) + (now.Minute() * 60) + now.Second())
		overtime       int32
	)
	if overtime = d.expire - currenttimeSec; overtime < 1 {
		overtime = d.expire
	}
	log.Info("AddUserPackReceiveCache mid(%d) overtime(%d)", mid, overtime)
	if err = conn.Set(&memcache.Item{Key: key, Object: count, Flags: memcache.FlagJSON, Expiration: overtime}); err != nil {
		log.Error("AddUserPackReceiveCache d.mc.Set(%s,%v) error(%v)", key, count, err)
	}
	conn.Close()
	return
}

// DeleteUserPackReceiveCache delete user pack cache
func (d *Dao) DeleteUserPackReceiveCache(c context.Context, mid int64) (err error) {
	var (
		key  = keyUserBindReceive(mid)
		conn = d.mc.Get(c)
	)
	defer conn.Close()
	if err = conn.Delete(key); err != nil {
		if err == memcache.ErrNotFound {
			err = nil
			return
		}
		log.Error("DeleteUserPackReceiveCache MemchDB.Delete(%s) error(%v)", key, err)
		return
	}
	return
}

// UnicomCache
func (d *Dao) UnicomCache(c context.Context, usermob string) (u []*unicom.Unicom, err error) {
	var (
		key  = keyUnicom(usermob)
		conn = d.mc.Get(c)
		r    *memcache.Item
	)
	defer conn.Close()
	if r, err = conn.Get(key); err != nil {
		log.Error("unicomCache MemchDB.Get(%s) error(%v)", key, err)
		return
	}
	if err = conn.Scan(r, &u); err != nil {
		log.Error("r.Scan(%s) error(%v)", r.Value, err)
	}
	return
}

//UserFlowCache unicom flow cache
func (d *Dao) UserFlowCache(c context.Context, keyStr string) (err error) {
	var (
		key  = keyUserFlow(keyStr)
		conn = d.mc.Get(c)
		r    *memcache.Item
		res  struct{}
	)
	defer conn.Close()
	if r, err = conn.Get(key); err != nil {
		log.Error("UserFlowCache MemchDB.Get(%s) error(%v)", key, err)
		return
	}
	if err = conn.Scan(r, &res); err != nil {
		log.Error("r.Scan(%s) error(%v)", r.Value, err)
	}
	return
}

// AddUserFlowCache add user pack cache
func (d *Dao) AddUserFlowCache(c context.Context, keyStr string) (err error) {
	var (
		key  = keyUserFlow(keyStr)
		conn = d.mc.Get(c)
	)
	if err = conn.Set(&memcache.Item{Key: key, Object: struct{}{}, Flags: memcache.FlagJSON, Expiration: d.flowKeyExpired}); err != nil {
		log.Error("AddUserPackCache d.mc.Set(%s) error(%v)", key, err)
	}
	conn.Close()
	return
}

// DeleteUserPackCache delete user pack cache
func (d *Dao) DeleteUserFlowCache(c context.Context, keyStr string) (err error) {
	var (
		key  = keyUserFlow(keyStr)
		conn = d.mc.Get(c)
	)
	defer conn.Close()
	if err = conn.Delete(key); err != nil {
		if err == memcache.ErrNotFound {
			err = nil
			return
		}
		log.Error("DeleteUserFlowCache MemchDB.Delete(%s) error(%v)", key, err)
		return
	}
	return
}

//UserFlowListCache unicom flow cache
func (d *Dao) UserFlowListCache(c context.Context) (res map[string]*unicom.UnicomUserFlow, err error) {
	var (
		key  = _userflowlistkey
		conn = d.mc.Get(c)
		r    *memcache.Item
	)
	defer conn.Close()
	if r, err = conn.Get(key); err != nil {
		if err == memcache.ErrNotFound {
			err = nil
			return
		}
		log.Error("UserFlowListCache MemchDB.Get(%s) error(%v)", key, err)
		return
	}
	if err = conn.Scan(r, &res); err != nil {
		log.Error("r.Scan(%s) error(%v)", r.Value, err)
	}
	return
}

// AddUserFlowListCache add user pack cache
func (d *Dao) AddUserFlowListCache(c context.Context, list map[string]*unicom.UnicomUserFlow) (err error) {
	var (
		key  = _userflowlistkey
		conn = d.mc.Get(c)
	)
	if err = conn.Set(&memcache.Item{Key: key, Object: list, Flags: memcache.FlagJSON, Expiration: d.flowKeyExpired}); err != nil {
		log.Error("AddUserFlowListCache d.mc.Set(%s,%v) error(%v)", key, list, err)
	}
	conn.Close()
	return
}


text:
Following up on yesterday's Karma and Jasmine TIL, today I found out how to test Browserify modules with Karma and Jasmine.

The setup includes a number of NPM modules i.e. `browserify`, `jasmine-core`, `karma`, `karma-browserify` and `watchify`, along with browser launchers such as `karma-chrome-launcher`.

The `package.json` for this setup can be seen below. Type `npm install` to set up the project.

```javascript
{
  "name": "karma-browserify-example",
  "version": "0.0.1",
  "description": "Karma with Browserify example",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Karolis Ramanauskas",
  "license": "ISC",
  "devDependencies": {
    "browserify": "^13.0.0",
    "jasmine-core": "^2.4.1",
    "karma": "^0.13.22",
    "karma-browserify": "^5.0.3",
    "karma-chrome-launcher": "^0.2.3",
    "karma-jasmine": "^0.3.8",
    "watchify": "^3.7.0"
  }
}
```

Now, let's define an examplary Browserify module in root of the project directory in `calculations.js`.

```javascript
let calculations = {
	add: function (a, b) {
		return a + b;
	},

	subtract: function (a, b) {
		return a - b;
	},

	multiply: function (a, b) {
		return a * b;
	},

	power: function (a, b) {
		return Math.pow(a, b);
	}
};

module.exports = calculations;
```

To test the module, create `tests/calculationsSpec.js` file, import the module and test it as usual:

```javascript
var calculations = require("../calculations");

describe('JavaScript calculations module', function () {
  it('adds two numbers together', function () {
    expect(calculations.add(1, 2)).toEqual(3);
  });

  it('subtracts two numbers together', function () {
    expect(calculations.subtract(1, 2)).toEqual(-1);
  });

  it('multiplies two numbers together', function () {
    expect(calculations.multiply(1, 2)).toEqual(2);
  });

  it('power of a number', function () {
    expect(calculations.power(1, 2)).toEqual(1);
  });
});
```

The above setup works flawlessly. The only problem I found is that now if you have a function not declared as a module, it will not get picked up automatically by Karma anymore. Anyway, it's not a big issue since all the functionality is going to be defined as modules anyway.

## Resources

- [karma-browserify plugin](https://github.com/nikku/karma-browserify)


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.automon</groupId>
    <artifactId>automon_parent</artifactId>
    <version>1.0.1-SNAPSHOT</version>
  </parent>

  <groupId>org.automon</groupId>
  <artifactId>automon</artifactId>
  <version>1.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>automon</name>
  <description>Automon combines the power of AOP (AspectJ) with any monitoring or logging tools you already use to declaratively monitor
    your Java code, the JDK, and dependent libraries.  This module generates the core automon aspect library.
  </description>

  <properties>
      <metrics.version>3.1.0</metrics.version>
      <jamonapi.version>2.81</jamonapi.version>
      <javasimon.version>4.0.1</javasimon.version>
      <assertj.version>1.7.0</assertj.version>
      <aspectj.version>1.8.2</aspectj.version>
      <mojo.ajc.version>1.7</mojo.ajc.version>
      <mojo.execution.version>1.3.2</mojo.execution.version>
      <mockito.version>1.9.5</mockito.version>
      <junit.version>4.11</junit.version>
      <perf4j.version>0.9.16</perf4j.version>
      <newrelic.version>3.14.0</newrelic.version>
      <ejb.version>3.2</ejb.version>
      <spring.version>4.0.2.RELEASE</spring.version>
      <jaxrs.version>2.0.1</jaxrs.version>
      <jpa.version>1.0.1.Final</jpa.version>
  </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>${mojo.ajc.version}</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                    <complianceLevel>${jdk.version}</complianceLevel>
                    <!-- generates META-INF/aop-ajc.xml file and puts it in jar.  Recommended for aspectj libraries. -->
                    <outxml>true</outxml>
                    <showWeaveInfo>true</showWeaveInfo>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>       <!-- use this goal to weave constructor your main classes -->
                            <goal>test-compile</goal> <!-- use this goal to weave constructor your test classes -->
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>${mojo.execution.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>exec</goal>
                        </goals>

                    </execution>
                </executions>
                <configuration>
                    <!-- generates class path with constructor dependencies as well as generated class -->
                    <classpathScope>runtime</classpathScope>
                   <!-- <mainClass>org.automon.delme.MyClass</mainClass> -->
                </configuration>
            </plugin>
    <!-- The Surefire Plugin is used during the test phase of the build lifecycle to execute the unit tests of an application. -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
            </plugin>
        </plugins>
    </build>

  <dependencies>

    <!-- test dependencies -->
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>${assertj.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>${mockito.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- runtime dependencies -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.jamonapi</groupId>
        <artifactId>jamon</artifactId>
        <version>${jamonapi.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.javasimon</groupId>
        <artifactId>javasimon-core</artifactId>
        <version>${javasimon.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>io.dropwizard.metrics</groupId>
        <artifactId>metrics-core</artifactId>
        <version>${metrics.version}</version>
        <scope>provided</scope>
    </dependency>

      <dependency>
          <groupId>io.dropwizard.metrics</groupId>
          <artifactId>metrics-annotation</artifactId>
          <version>${metrics.version}</version>
          <scope>provided</scope>
      </dependency>

      <dependency>
          <groupId>org.perf4j</groupId>
          <artifactId>perf4j</artifactId>
          <version>${perf4j.version}</version>
          <scope>provided</scope>
      </dependency>

      <dependency>
          <groupId>com.newrelic.agent.java</groupId>
          <artifactId>newrelic-api</artifactId>
          <version>${newrelic.version}</version>
          <scope>provided</scope>
      </dependency>

      <dependency>
          <groupId>javax.ejb</groupId>
          <artifactId>javax.ejb-api</artifactId>
          <version>${ejb.version}</version>
          <scope>provided</scope>
      </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
          <scope>provided</scope>
      </dependency>

      <dependency>
          <groupId>javax.ws.rs</groupId>
          <artifactId>javax.ws.rs-api</artifactId>
          <version>${jaxrs.version}</version>
          <scope>provided</scope>
      </dependency>

      <dependency>
          <groupId>org.hibernate.javax.persistence</groupId>
          <artifactId>hibernate-jpa-2.0-api</artifactId>
          <version>${jpa.version}</version>
          <scope>provided</scope>
      </dependency>

  </dependencies>
</project>


text:
<?php
/**
 * Created by PhpStorm.
 * User: sam
 * Date: 27/07/17
 * Time: 11:27
 */

namespace Tests\Unit\Models\APICommands;

use App\Models\APICommands\AddPage;
use App\Models\APICommands\CreateSite;

use App\Models\Page;
use App\Models\Revision;
use App\Models\RevisionSet;
use App\Models\Site;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Config;

class CreateSiteTest extends APICommandTestCase
{
    public function command()
    {
        return new CreateSite();
    }

    public function getValidData()
    {
        return [
            'name' => 'A Valid Name',
            'host' => 'example.com',
            'path' => '',
            'site_definition' => [
                'name' => 'one-page-site',
                'version' => 1
            ]
        ];
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenInputIsValid_passes()
    {
        $validator = $this->validator($this->input(null));
        $validator->passes();
        $this->assertTrue($validator->passes());
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenNameIsMissingOrTooLong_fails()
    {
        $data = $this->input([], 'name');
        $this->assertTrue( $this->validator($data)->fails());
        $data['name'] = '';
        $this->assertTrue( $this->validator($data)->fails());
        $data['name'] = str_repeat('a',200);
        $this->assertTrue( $this->validator($data)->fails());
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenHostIsMissingOrInvalid_fails()
    {
        $data = $this->input([], 'host');
        $this->assertTrue( $this->validator($data)->fails());
        $data['host'] = '';
        $this->assertTrue( $this->validator($data)->fails());
        $data['host'] = str_repeat('/',200);
        $this->assertTrue( $this->validator($data)->fails());
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenPathIsEmpty_succeeds()
    {
        $data = $this->input(['path' => '']);
        $this->assertTrue($this->validator($data)->passes());
        $data = $this->input(['path' => null]);
        $this->assertFalse($this->validator($data)->fails());
        $data = $this->input(null, ['path']);
        $this->assertFalse($this->validator($data)->fails());
    }

    /**
     * Paths must be empty or:
     * begin with a /, followed by one or more alphanumeric characters, hyphens or underscores, followed by more of the same.
     * @return array Invalid paths
     */
    public function invalidPathProvider()
    {
        return [
          ['/'],
            ['/foo/'],
            ['/foo/bar/'],
            ['foo'],
            ['foo/'],
            ['/@"']
        ];
    }

    /**
     * @test
     * @group APICommands
     * @dataProvider invalidPathProvider
     */
    public function validation_whenPathIsNotValid_fails($path)
    {
        $data = $this->input(['path' => $path]);
        $this->assertTrue( $this->validator($data)->fails());
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenHostAndPathAreNotUnique_fails()
    {
        // create a site
        $existing = $this->execute(CreateSite::class, $this->getValidData());
        // attempt to create another site with the same input
        $this->assertTrue($this->validator($this->input([]))->fails());

        // add subpages to the created site
        $pageone = $this->execute(AddPage::class, [
            'site_id' => $existing->id,
            'parent_id' => $existing->draftHomepage->id,
            'slug' => 'one',
            'title' => 'Page One',
            'layout' => [
                'name' => 'test-layout',
                'version' => 1
            ]
        ]);
        $pagetwo = $this->execute(AddPage::class, [
            'site_id' => $existing->id,
            'parent_id' => $pageone->id,
            'slug' => 'two',
            'title' => 'Page Two',
            'layout' => [
                'name' => 'test-layout',
                'version' => 1
            ]
        ]);
        $this->assertTrue($this->validator($this->input(['path' => '/one']))->fails());
        $this->assertTrue($this->validator($this->input(['path' => '/one/two']))->fails());
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenHostExistsButPathDoesNotClash_passes()
    {
        // create a site
        $existing = $this->execute(CreateSite::class, $this->getValidData());

        // add subpages to the created site
        $pageone = $this->execute(AddPage::class, [
            'site_id' => $existing->id,
            'parent_id' => $existing->draftHomepage->id,
            'slug' => 'one',
            'title' => 'Page One',
            'layout' => [
                'name' => 'test-layout',
                'version' => 1
            ]
        ]);
        $pagetwo = $this->execute(AddPage::class, [
            'site_id' => $existing->id,
            'parent_id' => $pageone->id,
            'slug' => 'two',
            'title' => 'Page Two',
            'layout' => [
                'name' => 'test-layout',
                'version' => 1
            ]
        ]);
        $this->assertTrue($this->validator($this->input(['path' => '/food']))->passes());
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenSiteDefinitionNameIsMissingOrInvalid_fails()
    {
        $data = $this->input(['site_definition' => ['name' => '', 'version' => 1]]);
        $this->assertTrue($this->validator($data)->fails());
        $data = $this->input(['site_definition' => ['name' => '//£*', 'version' => 1]]);
        $this->assertTrue($this->validator($data)->fails());
        $data = $this->input(['site_definition' => null ]);
        $this->assertTrue($this->validator($data)->fails());
        $data = $this->input(null,['site_definition']);
        $this->assertTrue($this->validator($data)->fails());
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenSiteDefinitionVersionIsMissingOrInvalid_fails()
    {
        $data = $this->input([]);
        unset($data['site_definition']['version']);
        $this->assertTrue($this->validator($data)->fails());
        $data['site_definition']['version'] = 'v1';
        $this->assertTrue($this->validator($data)->fails());
        $data['site_definition']['version'] = '';
        $this->assertTrue($this->validator($data)->fails());
    }

    /**
     * @test
     * @group APICommands
     */
    public function validation_whenSiteDefinitionNotFound_fails()
    {
        $data = $this->input([]);
        $data['site_definition']['name'] = 'missing-layout-name';
        $this->assertTrue($this->validator($data)->fails());
        $data['site_definition']['name'] = 'one-page-site';
        $data['site_definition']['version'] = 22;
        $this->assertTrue($this->validator($data)->fails());
    }

    /**
     * @test
     * @group APICommands
     */
    public function createHomePage_creates_APageARevisionAndARevisionSet_withCorrectFields()
    {
        $site = factory(Site::class)->create();
        $user = factory(User::class)->create();
        $title = 'Test Title';
        $layout = ['name' => 'test-layout', 'version' => 1];
        $homepage = $this->command()->createHomePage($site, $title, $layout, $user);

        $this->assertInstanceOf(Page::class, $homepage);
        $this->assertEquals($homepage->id, $site->draftHomepage->id);
        $this->assertEquals(null, $site->draftHomepage->parent_id);
        $this->assertEquals($site->id, $site->draftHomepage->site_id);
        $this->assertInstanceOf(Revision::class, $homepage->revision);
        $this->assertEquals($title, $homepage->revision->title);
        $this->assertEquals($layout['name'], $homepage->revision->layout_name);
        $this->assertEquals($layout['version'], $homepage->revision->layout_version);
        $this->assertEquals($user->id, $homepage->created_by);
        $this->assertEquals($user->id, $homepage->updated_by);
        $this->assertInstanceOf(RevisionSet::class, $homepage->revision->set);
    }

    /**
     * @test
     * @group APICommands
     */
    public function execute_createsASite_WithADraftHomePage()
    {
        $site = $this->command()->execute(new Collection($this->input(null)), factory(User::class)->create());
        $this->assertEquals(Page::STATE_DRAFT, $site->draftHomepage->version);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (c) 2014-2015 Oracle and/or its affiliates. All rights reserved.
    Copyright (c) 2018, 2020 Eclipse Krazo committers and contributors

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    SPDX-License-Identifier: Apache-2.0

-->
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd"
       bean-discovery-mode="all">
</beans>


text:
"""
Automatic compilation of ptx files, useful for differential analysis
"""
# W.J. van der Laan 2007
from subprocess import Popen,PIPE
from Disass import load
from tempfile import mkstemp
from os import remove,fdopen,close

ptxas = "ptxas"

class CompilationError(Exception):
    def __init__(self, msg):
        Exception.__init__(self, msg)
        self.message = msg

class PTX:
    def __init__(self, ptx):
        ptxout = mkstemp(suffix=".ptx")
        binout = mkstemp(suffix=".cubin")
        try:
            close(binout[0]) # we are only interested in the name
            # Write ptx
            f = fdopen(ptxout[0], "w")
            f.write(ptx)
            f.close()

            # Compile ptx
            sub = Popen([ptxas,ptxout[1],'-o',binout[1]], stdout=PIPE, stderr=PIPE)
            rv = sub.communicate()
            if sub.returncode:
                raise CompilationError(rv[1])

            # Open cubin
            self.bin = load(binout[1])
        finally:
            # Remove temp files
            remove(ptxout[1])
            remove(binout[1])


text:
/*
 * ANMProteinRRTExpansionAlgorithm.h
 *
 *  Created on: 12/06/2011
 *      Author: vgil
 */

#ifndef ANMPROTEINRRTEXPANSIONALGORITHM_H_
#define ANMPROTEINRRTEXPANSIONALGORITHM_H_

#include "../../ProteinRRT/RRTProteinExpansionAlgorithm.h"
#include "../../ProteinRRT/RRTProteinConfiguration.h"
#include "../BaseAlgorithms/UsesEigenvectorsAndEigenvalues.h"
#include "../../../../../Energy/EnergyCalculator.h"
#include "../../../../../ANM/ANMCalculator.h"
#include "ANMProteinConfiguration.h"
#include "../../../../Tools/Math/Solver.h"
#include "../../../../Tools/PathPlanningGeneralTools.h"

class ANMProteinRRTExpansionAlgorithm: public RRTProteinExpansionAlgorithm{

	public:
								ANMProteinRRTExpansionAlgorithm		( PathPlanning::Tools::ANMObjectsPackage* pack, Solver* s);
			virtual 			~ANMProteinRRTExpansionAlgorithm	();

			ANMCalculator*		getANMCalculator					();
			EnergyCalculator*	getEnergyCalculator					() const;
			MinParams*			getMinimParameters					() const;
			Minimizer*			getMinimizer						() const;
			Solver*				getSolver							() const;

	protected:
			void				set_ANM_calculator					(ANMCalculator*);
			void 				set_energy_calculator				(EnergyCalculator *energyCalculator);
			void 				set_minimization_params				(MinParams *minimParameters);
			void 				set_minimizer						(Minimizer *minimizer);
			void 				set_solver							(Solver *solver);

			virtual RRTNode*	do_expansion						(RRTNode* from, RRTNode* to);

			ANMCalculator* 		anmcalc;
			Minimizer * 		minimizer;
			MinParams * 		minim_parameters;
			EnergyCalculator *	energy_calculator;
			Solver* 			solver;

};

#endif /* ANMPROTEINRRTEXPANSIONALGORITHM_H_ */


text:
/*! Interrupt handling - 'arch' layer (only basic operations) */
#pragma once

/*! Initialize interrupt subsystem (in 'arch' layer) */
void arch_init_interrupts ();

/*! Register handler function for particular interrupt number */
void arch_register_interrupt_handler (
	unsigned int inum,
	void *handler,
	void *device
);

/*! Unregister handler function for particular interrupt number */
void arch_unregister_interrupt_handler (
	unsigned int irq_num,
	void *handler,
	void *device
);

/*! Quit startup thread and start with created one (=> arch_select_thread) */
void arch_return_to_thread ();

/*!
 * enable and disable interrupts generated outside processor, controller by
 * interrupt controller (PIC or APIC or ...)
 */
void arch_irq_enable ( unsigned int irq );
void arch_irq_disable ( unsigned int irq );

/*! detecting segmentation faults - from threads or kernel */

/*! return current processor operating mode (KERNEL_MODE or USER_MODE) */
int arch_new_mode ();

/*! return previous processor operating mode (KERNEL_MODE or USER_MODE) */
int arch_prev_mode ();

#define KERNEL_MODE		0
#define USER_MODE		-1

#include <ARCH/interrupt.h>	/* for SOFT_IRQ */
#define SOFTWARE_INTERRUPT	SOFT_IRQ


text:
package eu.modernmt.processing.xml;

import eu.modernmt.lang.Language;
import eu.modernmt.model.*;
import eu.modernmt.processing.string.SentenceBuilder;
import eu.modernmt.processing.tags.projection.TagProjector;
import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class XMLTagProjectorSpacingTest {

    private static Translation translation(Word[] tokens, Tag[] tags) {
        return new Translation(tokens, tags, null, null);
    }

    @Test
    public void testTranslationWithTags() {
        Translation translation = translation(new Word[]{
                new Word("Hello", null, " ", false, true),
                new Word("world", " ", " ", true, false),
                new Word("!", " ", null, false, false),
        }, new Tag[]{
                XMLTag.fromText("", " ", null, 1),
                XMLTag.fromText("", null, null, 2),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("Hello world!", translation.toString(false, false));
        assertEquals("Hello world!", translation.toString());
        Assertions.assertCoherentSpacing(translation);
    }

    @Test
    public void testTranslationWithDiscordantTagSpacing_FalseTrue() {
        Translation translation = translation(new Word[]{
                new Word("Hello", null, " ", true, true),
                new Word("world", " ", " ", true,false),
                new Word("!", " ", null, false, false),
        }, new Tag[]{
                XMLTag.fromText("", " ", null, 1),
                XMLTag.fromText("", null, null, 2),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("Hello world!", translation.toString(false, false));
        assertEquals("Hello world!", translation.toString());
        Assertions.assertCoherentSpacing(translation);
    }

    @Test
    public void testTranslationWithDiscordantTagSpacing_TrueFalse() {
        Translation translation = translation(new Word[]{
                new Word("Hello", null, " ", true, true),
                new Word("world", " "," ",true, false),
                new Word("!", " ", null, false, true),
        }, new Tag[]{
                XMLTag.fromText("", " ", null, 1),
                XMLTag.fromText("", null, null, 2),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("Hello world!", translation.toString(false, false));
        assertEquals("Hello world!", translation.toString());
        Assertions.assertCoherentSpacing(translation);
    }

    @Test
    public void testTranslationWithSpacedTagList() {
        Translation translation = translation(new Word[]{
                new Word("Hello", null," ", false, true),
                new Word("world", " ", " ", true, false),
                new Word("!", " ", null, false, false),
        }, new Tag[]{
                XMLTag.fromText("", " ", " ", 1),
                XMLTag.fromText("", " ", " ", 1),
                XMLTag.fromText("", " ", " ", 1),
                XMLTag.fromText("", " ", " ", 1),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("Hello     world!", translation.toString());
        assertEquals("Hello world!", translation.toString(false, false));
        Assertions.assertCoherentSpacing(translation);
    }

    @Test
    public void testTranslationWithTagListSpaceInMiddle() {
        Translation translation = translation(new Word[]{
                new Word("Hello", null, " ", false, true),
                new Word("world", " ", " ", true, false),
                new Word("!", " ", null, false, false),
        }, new Tag[]{
                XMLTag.fromText("", " ", " ", 1),
                XMLTag.fromText("", " ", " ", 1),
                XMLTag.fromText("", " ", " ", 1),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("Hello world!", translation.toString(false, false));
        assertEquals("Hello    world!", translation.toString());
        Assertions.assertCoherentSpacing(translation);
    }

    @Test
    public void testTranslationWithTagInUnbreakableTokenList() {
        Translation translation = translation(new Word[]{
                new Word("That", null," ", false, false),
                new Word("'s", " "," ", false, true),
                new Word("it", " ", " ", true, false),
                new Word("!", " ", null, false, false),
        }, new Tag[]{
                XMLTag.fromText("", null, null, 1),
                XMLTag.fromText("", null, " ", 2),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("That's it!", translation.toString(false, false));
        assertEquals("That's it!", translation.toString());
        Assertions.assertCoherentSpacing(translation);
    }

    @Test
    public void testTranslationWithSpacedCommentTag() {
        Translation translation = translation(new Word[]{
                new Word("This", null, " ", false, true),
                new Word("is", " ", " ", true, true),
                new Word("XML", " ", " ", true, true),
                new Word("comment", " ", null, true, false),
        }, new Tag[]{
                XMLTag.fromText("", " ", null, 4),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("This is XML comment", translation.toString(false, false));
        assertEquals("This is ", translation.toString());
        Assertions.assertCoherentSpacing(translation);
    }

    @Test
    public void testTranslationWithSpacedCommentTag_NoLeadingSpace() {
        Translation translation = translation(new Word[]{
                new Word("This", null, " ", false, true),
                new Word("is", " ", " ", true, true),
                new Word("XML", " ", " ", true, true),
                new Word("comment", " ", null, true, false),
        }, new Tag[]{
                XMLTag.fromText("", " ", null, 4),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("This is XML comment", translation.toString(false, false));
        assertEquals("This is", translation.toString());
        Assertions.assertCoherentSpacing(translation);
    }

    @Test
    public void testTranslationWithSpacedCommentTag_TrailingSpace() {
        Translation translation = translation(new Word[]{
                new Word("This", null, " ", false, true),
                new Word("is", " ", " ", true, true),
                new Word("XML", " ", " ", true, true),
                new Word("comment", " ", null, true, false),
        }, new Tag[]{
                XMLTag.fromText("", " ", " ", 4),
        });

        translation.fixWordSpacing();
        TagProjector.simpleSpaceAnalysis(translation);

        assertEquals("This is XML comment", translation.toString(false, false));
        assertEquals("This is", translation.toString());
        Assertions.assertCoherentSpacing(translation);
    }

}


text:
assert.isTrue('Hello World!'.startsWith('Hello '));
assert.isFalse('Hello World!'.startsWith('World!'));
assert.isTrue('Hello World!'.startsWith(''));
assert.isFalse('Hello World!'.startsWith('h'));


text:
import { globals } from 'vs/base/common/platform';
import { IWorker, IWorkerCallback, IWorkerFactory, logOnceWebWorkerWarning } from 'vs/base/common/worker/simpleWorker';

function getWorker(workerId: string, label: string): Worker | Promise<Worker> {
	// Option for hosts to overwrite the worker script (used in the standalone editor)
	if (globals.MonacoEnvironment) {
		if (typeof globals.MonacoEnvironment.getWorker === 'function') {
			return globals.MonacoEnvironment.getWorker(workerId, label);
		}
		if (typeof globals.MonacoEnvironment.getWorkerUrl === 'function') {
			return new Worker(globals.MonacoEnvironment.getWorkerUrl(workerId, label));
		}
	}
	// ESM-comment-begin
	if (typeof require === 'function') {
		// check if the JS lives on a different origin
		const workerMain = require.toUrl('./' + workerId);
		const workerUrl = getWorkerBootstrapUrl(workerMain, label);
		return new Worker(workerUrl, { name: label });
	}
	// ESM-comment-end
	throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);
}

// ESM-comment-begin
export function getWorkerBootstrapUrl(scriptPath: string, label: string): string {
	if (/^(http:)|(https:)|(file:)/.test(scriptPath)) {
		const currentUrl = String(window.location);
		const currentOrigin = currentUrl.substr(0, currentUrl.length - window.location.hash.length - window.location.search.length - window.location.pathname.length);
		if (scriptPath.substring(0, currentOrigin.length) !== currentOrigin) {
			// this is the cross-origin case
			// i.e. the webpage is running at a different origin than where the scripts are loaded from
			const myPath = 'vs/base/worker/defaultWorkerFactory.js';
			const workerBaseUrl = require.toUrl(myPath).slice(0, -myPath.length);
			const js = `/*${label}*/self.MonacoEnvironment={baseUrl: '${workerBaseUrl}'};importScripts('${scriptPath}');/*${label}*/`;
			const url = `data:text/javascript;charset=utf-8,${encodeURIComponent(js)}`;
			return url;
		}
	}
	return scriptPath + '#' + label;
}
// ESM-comment-end

function isPromiseLike<T>(obj: any): obj is PromiseLike<T> {
	if (typeof obj.then === 'function') {
		return true;
	}
	return false;
}

/**
 * A worker that uses HTML5 web workers so that is has
 * its own global scope and its own thread.
 */
class WebWorker implements IWorker {

	private id: number;
	private worker: Promise<Worker> | null;

	constructor(moduleId: string, id: number, label: string, onMessageCallback: IWorkerCallback, onErrorCallback: (err: any) => void) {
		this.id = id;
		const workerOrPromise = getWorker('workerMain.js', label);
		if (isPromiseLike(workerOrPromise)) {
			this.worker = workerOrPromise;
		} else {
			this.worker = Promise.resolve(workerOrPromise);
		}
		this.postMessage(moduleId, []);
		this.worker.then((w) => {
			w.onmessage = function (ev: any) {
				onMessageCallback(ev.data);
			};
			(<any>w).onmessageerror = onErrorCallback;
			if (typeof w.addEventListener === 'function') {
				w.addEventListener('error', onErrorCallback);
			}
		});
	}

	public getId(): number {
		return this.id;
	}

	public postMessage(message: any, transfer: Transferable[]): void {
		if (this.worker) {
			this.worker.then(w => w.postMessage(message, transfer));
		}
	}

	public dispose(): void {
		if (this.worker) {
			this.worker.then(w => w.terminate());
		}
		this.worker = null;
	}
}

export class DefaultWorkerFactory implements IWorkerFactory {

	private static LAST_WORKER_ID = 0;

	private _label: string | undefined;
	private _webWorkerFailedBeforeError: any;

	constructor(label: string | undefined) {
		this._label = label;
		this._webWorkerFailedBeforeError = false;
	}

	public create(moduleId: string, onMessageCallback: IWorkerCallback, onErrorCallback: (err: any) => void): IWorker {
		let workerId = (++DefaultWorkerFactory.LAST_WORKER_ID);

		if (this._webWorkerFailedBeforeError) {
			throw this._webWorkerFailedBeforeError;
		}

		return new WebWorker(moduleId, workerId, this._label || 'anonymous' + workerId, onMessageCallback, (err) => {
			logOnceWebWorkerWarning(err);
			this._webWorkerFailedBeforeError = err;
			onErrorCallback(err);
		});
	}
}


text:
/*
 * ViewYatesResultAction.java
 * Created on Sep 13, 2004
 * Created by Michael Riffle <mriffle@u.washington.edu>
 */

package org.yeastrc.www.yates;

import org.yeastrc.yates.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.yeastrc.data.InvalidIDException;
import org.yeastrc.project.Project;
import org.yeastrc.www.user.User;
import org.yeastrc.www.user.UserUtils;
import org.yeastrc.yates.YatesResult;
import org.yeastrc.bio.protein.*;
/**
 * Description of class goes here.
 *
 * @author Michael Riffle <mriffle@u.washington.edu>
 * @version Sep 13, 2004
 */

public class ViewYatesResultAction extends Action {

	public ActionForward execute( ActionMapping mapping,
								  ActionForm form,
								  HttpServletRequest request,
								  HttpServletResponse response )
	throws Exception {

		// The run we're viewing
		int resultID;

		// User making this request
		User user = UserUtils.getUser(request);
		if (user == null) {
			ActionErrors errors = new ActionErrors();
			errors.add("username", new ActionMessage("error.login.notloggedin"));
			saveErrors( request, errors );
			return mapping.findForward("authenticate");
		}

		YatesResult yr = null;
		try {
			String strID = request.getParameter("id");

			if (strID == null || strID.equals("")) {
				ActionErrors errors = new ActionErrors();
				errors.add("yates", new ActionMessage("error.yates.result.invalidid"));
				saveErrors( request, errors );
				return mapping.findForward("Failure");
			}

			resultID = Integer.parseInt(strID);

			// Load our screen
			yr = new YatesResult();
			yr.load(resultID);

			Project project = yr.getProject();
			if (!project.checkReadAccess(user.getResearcher())) {

				// This user doesn't have access to this project.
				ActionErrors errors = new ActionErrors();
				errors.add("username", new ActionMessage("error.project.noaccess"));
				saveErrors( request, errors );
				return mapping.findForward("Failure");
			}
		} catch (NumberFormatException nfe) {
			ActionErrors errors = new ActionErrors();
			errors.add("yates", new ActionMessage("error.project.invalidid"));
			saveErrors( request, errors );
			return mapping.findForward("Failure");
		} catch (InvalidIDException iie) {
			ActionErrors errors = new ActionErrors();
			errors.add("yates", new ActionMessage("error.yates.result.invalidid"));
			saveErrors( request, errors );
			return mapping.findForward("Failure");
		}

		catch (Exception e) {
			ActionErrors errors = new ActionErrors();
			errors.add("username", new ActionMessage("error.project.projectnotfound"));
			saveErrors( request, errors );
			return mapping.findForward("Failure");
		}

		// Save the Run object for this result to the request
		YatesRun run = (YatesRun)(yr.getRun());
		request.setAttribute("run", run);

		//test
		yr.getFormatedSequenceCoverageMap();

		// Get the bait protein and save it to the request
		Protein protein = yr.getRun().getBaitProtein();
		request.setAttribute("baitProtein", protein);

		// Set this project in the request, as a bean to be displayed on the view
		request.setAttribute("result", yr);

		// THIS IS TEMPORARY -- BEGIN
		// We are still dealing with legacy data in tblYatesCycle etc table.
		// The "Spectra" link will be visible if the hasYatesCycle attribute is set.
		if (YatesCycleFactory.getInstance().hasCyclesForRun(yr.getRunID()))
		    request.setAttribute("hasYatesCycles", true);
		// THIS IS TEMPORARY -- END

		return mapping.findForward("Success");
	}

}


text:
package com.solambda.swiffer.api.internal.activities;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.model.ActivityTask;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
import com.amazonaws.services.simpleworkflow.model.GetWorkflowExecutionHistoryRequest;
import com.amazonaws.services.simpleworkflow.model.History;
import com.amazonaws.services.simpleworkflow.model.HistoryEvent;
import com.solambda.swiffer.api.internal.VersionedName;
import com.solambda.swiffer.api.internal.decisions.WorkflowHistory;
import com.solambda.swiffer.api.internal.decisions.WorkflowHistoryImpl;

public class ActivityTaskContextImpl implements ActivityTaskContext {

	private AmazonSimpleWorkflow swf;
	private ActivityTask task;
	private String domain;

	public ActivityTaskContextImpl(final AmazonSimpleWorkflow client, final ActivityTask task) {
		super();
		this.swf = client;
		this.task = task;
	}

	@Override
	public String taskToken() {
		return this.task.getTaskToken();
	}

	@Override
	public String input() {
		return this.task.getInput();
	}

	@Override
	public String activityId() {
		return this.task.getActivityId();
	}

	@Override
	public VersionedName activityType() {
		final ActivityType activityType = this.task.getActivityType();
		return new VersionedName(activityType.getName(), activityType.getVersion());
	}

	@Override
	public WorkflowHistory history() {
		WorkflowHistory history = null;
		do {
			history = fetchHistory();
		} while (taskIsNotInHistory(history) && sleep(Duration.ofSeconds(2)));
		return history;
	}

	private boolean sleep(final Duration duration) {
		try {
			Thread.sleep(duration.toMillis());
		} catch (final InterruptedException e) {
		}
		return true;
	}

	private boolean taskIsNotInHistory(final WorkflowHistory history) {
		return history.getEventById(this.task.getStartedEventId()) == null;
	}

	private WorkflowHistory fetchHistory() {
		final List<HistoryEvent> allEvents = new ArrayList<HistoryEvent>();
		String nextPageToken = null;
		do {
			final History history = this.swf.getWorkflowExecutionHistory(new GetWorkflowExecutionHistoryRequest()
					.withDomain(this.domain)
					.withExecution(this.task.getWorkflowExecution())
					.withReverseOrder(true)
					.withNextPageToken(nextPageToken));
			allEvents.addAll(history.getEvents());
			nextPageToken = history.getNextPageToken();
		} while (nextPageToken != null);
		return new WorkflowHistoryImpl(allEvents);
	}
}


text:
from __future__ import print_function
from peyotl.phylesystem.phylesystem_umbrella import Phylesystem
from peyotl.nexson_syntax import extract_tree_nexson
import sys
try:
    phylsys = Phylesystem()
except Exception as e:
    sys.stderr.write('count_trees.py: Exception: {}\n'.format(e.message))
    sys.exit('count_trees.py: There was a problem creating a wrapper around your phylesystem '
             'instance. Double check your configuration (see '
             'http://opentreeoflife.github.io/peyotl/configuration/ for info).')
try:
    print_freq = 500
    num_trees = 0
    num_studies = 0
    max_trees_per_study = 0
    biggest_study = None
    studies_without_trees = []
    sys.stderr.write('count_trees.py: beginning loop over studies...\n')
    for study_id, nexson in phylsys.iter_study_objs():
        num_studies += 1
        try:
            nt = len(extract_tree_nexson(nexson, tree_id=None))
        except:
            sys.stderr.write('Problem extracting trees from study {}'.format(study_id))
            raise
        if nt == 0:
            studies_without_trees.append(study_id)
        else:
            num_trees += nt
            if nt > max_trees_per_study:
                biggest_study = study_id
                max_trees_per_study = nt
        if num_studies % print_freq == 0:
            sys.stderr.write('   ...{d} studies read. Still going...\n'.format(d=num_studies))

except:
    sys.exit('Unexpected error in iteration, please report this bug.')

output = '''{s:d} = # studies
{e:d} = # studies without any trees
{t:d} = # trees total
{m:d} = maximum # trees in any study ({b})
The tree-less studies are: {a}
'''.format(s=num_studies,
           e=len(studies_without_trees),
           t=num_trees,
           m=max_trees_per_study,
           b=biggest_study,
           a=studies_without_trees)
print(output)


text:
/*

•AT&T: number@txt.att.net[1] for a normal text message (SMS), or number@mms.att.net[2] for a multimedia message (MMS)
•Verizon: number@vtext.com[3] for both SMS and MMS messages
•Sprint PCS: number@messaging.sprintpcs.com for both SMS and MMS messages
•T-Mobile: number@tmomail.net for both SMS and MMS messages
•Virgin Mobile: number@vmobl.com[4] for both SMS and MMS messages
•These gateways do change periodically, and are not always published for non-subscribers. For a comprehensive and up-to-date list of current gateway addresses and the format to use for various phone companies around the world, visit http://martinfitzpatrick.name/list-of-email-to-sms-gateways
*/

/*
EXEC msdb.dbo.sp_send_dbmail
  @recipients= '5555555555@txt.att.net'
  ,@subject = 'Test'
  ,@body = 'Test'
  ,@body_format = 'TEXT';
*/


text:
const mongoose = require('mongoose');

const sportSchema = new mongoose.Schema({
    name: {type: String,unique:true},
    type: String
}, { timestamps: true });

const Sport = mongoose.model('Sport', sportSchema);

module.exports = Sport;


text:
require 'serialport'

$port = '/dev/cu.usbmodemfa131'

$serial = SerialPort.new $port, 9600, 8, 1
$serial.read_timeout = 2000
$serial.read

def read_write request
  $serial.puts request
  $serial.gets.chomp
end

def write request
  read_write request
end

at_exit do
  $serial.close
end


text:
.. currentmodule:: PyQt5.QtWinExtras

QWinTaskbarButton
-----------------

.. class:: QWinTaskbarButton

    `C++ documentation <http://doc.qt.io/qt-5/qwintaskbarbutton.html>`_


text:
#ifndef HeapLinkedStack_h
#define HeapLinkedStack_h

#include "platform/heap/Heap.h"
#include "platform/heap/Visitor.h"
#include "wtf/Allocator.h"

namespace blink {

template <typename T>
class HeapLinkedStack : public GarbageCollected<HeapLinkedStack<T>> {
public:
    HeapLinkedStack() : m_size(0) { }

    bool isEmpty();

    void push(const T&);
    const T& peek();
    void pop();

    size_t size();

    DEFINE_INLINE_TRACE()
    {
        for (Node* current = m_head; current; current = current->m_next)
            visitor->trace(current);
    }

private:
    class Node : public GarbageCollected<Node> {
    public:
        Node(const T&, Node* next);

        DEFINE_INLINE_TRACE() { visitor->trace(m_data); }

        T m_data;
        Member<Node> m_next;
    };

    Member<Node> m_head;
    size_t m_size;
};

template <typename T>
HeapLinkedStack<T>::Node::Node(const T& data, Node* next)
    : m_data(data)
    , m_next(next)
{
}

template <typename T>
inline bool HeapLinkedStack<T>::isEmpty()
{
    return !m_head;
}

template <typename T>
inline void HeapLinkedStack<T>::push(const T& data)
{
    m_head = new Node(data, m_head);
    ++m_size;
}

template <typename T>
inline const T& HeapLinkedStack<T>::peek()
{
    return m_head->m_data;
}

template <typename T>
inline void HeapLinkedStack<T>::pop()
{
    ASSERT(m_head && m_size);
    m_head = m_head->m_next;
    --m_size;
}

template <typename T>
inline size_t HeapLinkedStack<T>::size()
{
    return m_size;
}

template<typename T>
class TraceEagerlyTrait<HeapLinkedStack<T>> {
    STATIC_ONLY(TraceEagerlyTrait);
public:
    static const bool value = TraceEagerlyTrait<T>::value;
};

} // namespace blink

#endif // HeapLinkedStack_h


text:
Sets the logging condition of a librarian breakpoint. When log condition is not specified, log text always be logged regardless of the break condition, otherwise it will be logged when the logging condition is satisfied.

## arguments

`arg1` The DLL name.

`[arg2]` The logging condition (default condition when not specified).

## result

This command does not set any result variables.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/listview_drawer"
       android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="320dp"
    android:orientation="vertical"
    android:layout_gravity="start"
    android:background="#ffffff"
        android:minHeight="64dip"
       android:layout_alignBottom="@+id/Person"
        android:choiceMode="singleChoice"
        android:dividerHeight="0dp"
		android:divider="@null"
        android:listSelector="@drawable/list_selector"
        />

</RelativeLayout>


text:
from vida.celery import app
# import brpy2
import logging
# import fileservice.helpers
import sys
logger = logging.getLogger(__name__)

@app.task
# def index_face(image):
#    logger.debug("Calling index_face on " + image)

# Re-index all of the files, need to do this on startup since we are maintaining the gallery in memory now
# This would be used for an admin, create a new end point so that the templates can be regenerated in case
# something goes wrong, all the templates can be cleared from DB, then re-created
@app.task
def reindex_files():
    # TODO: I am not absolutely sold that the __init.py__ code runs only once, so add some checking to save time
    # If the gallery has not been populated, or if the gallery has fewer files than in the folder we need to re-index
    result = []
    try:
 #       brpy2.initialize()
 #       brpy2.setAlgorithm("Read(Grayscale)+Cascade")
 #       brpy2.setGlobal("enrollAll", "true")
        file_names = fileservice.helpers.get_fileservice_files()
        for currFile in file_names:
            logger.debug("Indexing:" + currFile)
 #           result.append(brpy2.Template(currFile))
 #       brpy2.finalize()

    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise
    return result

@app.task
def index_face(filename):
    # whenever a file is uploaded (in fileservice upload)
    # generate a template in openbr
    # write templet to posgres (somehow serialize as a blob)
    i=0

@app.task
def load_gallery():
    # Pull all templates from postgres and return
    # as an array of templates, and an array of corresponding filenames
    i=0


text:
package org.apache.bigtop.datagenerators.bigpetstore.generators.purchase;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.apache.bigtop.datagenerators.bigpetstore.Constants;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.PetSpecies;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.Product;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.inputs.ProductCategory;
import org.apache.bigtop.datagenerators.bigpetstore.generators.products.ProductCategoryBuilder;
import org.apache.bigtop.datagenerators.bigpetstore.generators.purchase.MarkovPurchasingModel;
import org.apache.bigtop.datagenerators.bigpetstore.generators.purchase.PurchasingModelSamplerBuilder;
import org.apache.bigtop.datagenerators.samplers.SeedFactory;
import org.apache.bigtop.datagenerators.samplers.samplers.Sampler;
import org.junit.Test;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

public class TestPurchasingModelSampler
{

	private List<ProductCategory> createProducts()
	{
		List<ProductCategory> productCategories = Lists.newArrayList();

		ProductCategoryBuilder foodBuilder = new ProductCategoryBuilder();
		foodBuilder.addApplicableSpecies(PetSpecies.DOG);
		foodBuilder.setAmountUsedPetPetAverage(1.0);
		foodBuilder.setAmountUsedPetPetVariance(1.0);
		foodBuilder.setDailyUsageRate(2.0);
		foodBuilder.setCategory("dogFood");
		foodBuilder.addProduct(new Product(ImmutableMap.of(Constants.PRODUCT_CATEGORY, (Object) "dogFood",
				Constants.PRODUCT_QUANTITY, (Object) 60.0, "Flavor", "Fish & Potato")));
		foodBuilder.addProduct(new Product(ImmutableMap.of(Constants.PRODUCT_CATEGORY, (Object) "dogFood",
				Constants.PRODUCT_QUANTITY, (Object) 30.0, "Flavor", "Chicken & Rice")));
		foodBuilder.addProduct(new Product(ImmutableMap.of(Constants.PRODUCT_CATEGORY, (Object) "dogFood",
				Constants.PRODUCT_QUANTITY, (Object) 15.0, "Flavor", "Lamb & Barley")));
		productCategories.add(foodBuilder.build());

		ProductCategoryBuilder bagBuilder = new ProductCategoryBuilder();
		bagBuilder.addApplicableSpecies(PetSpecies.DOG);
		bagBuilder.setAmountUsedPetPetAverage(1.0);
		bagBuilder.setAmountUsedPetPetVariance(1.0);
		bagBuilder.setDailyUsageRate(2.0);
		bagBuilder.setCategory("Poop Bags");
		bagBuilder.addProduct(new Product(ImmutableMap.of(Constants.PRODUCT_CATEGORY, (Object) "Poop Bags",
				Constants.PRODUCT_QUANTITY, (Object) 60.0, "Color", "Blue")));
		bagBuilder.addProduct(new Product(ImmutableMap.of(Constants.PRODUCT_CATEGORY, (Object) "Poop Bags",
				Constants.PRODUCT_QUANTITY, (Object) 30.0, "Color", "Red")));
		bagBuilder.addProduct(new Product(ImmutableMap.of(Constants.PRODUCT_CATEGORY, (Object) "Poop Bags",
				Constants.PRODUCT_QUANTITY, (Object) 120.0, "Color", "Multicolor")));
		productCategories.add(bagBuilder.build());

		return productCategories;
	}

	@Test
	public void testSample() throws Exception
	{
		SeedFactory seedFactory = new SeedFactory(1245);

		List<ProductCategory> productCategories = createProducts();

		PurchasingModelSamplerBuilder builder = new PurchasingModelSamplerBuilder(productCategories, seedFactory);
		Sampler<MarkovPurchasingModel> sampler = builder.buildMarkovPurchasingModel();
		MarkovPurchasingModel profile = sampler.sample();

		assertNotNull(profile);
		assertNotNull(profile.getProductCategories());
		assertTrue(profile.getProductCategories().size() > 0);

		for(String label : profile.getProductCategories())
		{
			assertNotNull(profile.getProfile(label));
			assertNotNull(profile.getProfile(label).getStartWeights());
			assertTrue(profile.getProfile(label).getStartWeights().size() > 0);
			assertNotNull(profile.getProfile(label).getTransitionWeights());
			assertTrue(profile.getProfile(label).getTransitionWeights().size() > 0);
		}
	}

}


text:
{% extends "base.html" %}

{% block content %}

  {% if form.errors %}

Sorry, that's not a valid username or password

  {% endif %}

 Enter your Username and Password.

  <form action="/accounts/auth/" method="post">{% csrf_token %}
    Username:
    <input type="text" name="username" value="" id="username">
    Password:
    <input type="password" name="password" value="" id="password">

    <input id="button" type="submit" value="Login"/>
  </form>
{% endblock %}


text:
#ifndef MXNET_OPERATOR_SOFTMAX_OUTPUT_INL_H_
#define MXNET_OPERATOR_SOFTMAX_OUTPUT_INL_H_

#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <mxnet/operator.h>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <utility>
#include "./operator_common.h"

namespace mxnet {
namespace op {

namespace softmaxout_enum {
enum SoftmaxOutputOpInputs {kData, kLabel};
enum SoftmaxOutputOpOutputs {kOut};
enum SoftmaxOutputNormType {kNull, kBatch, kValid};
enum SoftmaxOutputOpResource {kTempSpace};
}  // namespace softmaxout_enum

struct SoftmaxOutputParam : public dmlc::Parameter<SoftmaxOutputParam> {
  float grad_scale;
  float ignore_label;
  bool multi_output;
  bool use_ignore;
  bool preserve_shape;
  int normalization;
  bool out_grad;
  DMLC_DECLARE_PARAMETER(SoftmaxOutputParam) {
    DMLC_DECLARE_FIELD(grad_scale).set_default(1.0f)
    .describe("Scales the gradient by a float factor.");
    DMLC_DECLARE_FIELD(ignore_label).set_default(-1.0f)
    .describe("The instances whose `labels` == `ignore_label` will be ignored "
              "during backward, if `use_ignore` is set to ``true``).");
    DMLC_DECLARE_FIELD(multi_output).set_default(false)
    .describe("If set to ``true``, the softmax function will be computed along "
              "the second axis.");
    DMLC_DECLARE_FIELD(use_ignore).set_default(false)
    .describe("If set to ``true``, the `ignore_label` value will not contribute "
              "to the backward gradient.");
    DMLC_DECLARE_FIELD(preserve_shape).set_default(false)
    .describe("If set to ``true``, the softmax function will be computed along "
              "the last axis.");
    DMLC_DECLARE_FIELD(normalization)
    .add_enum("null", softmaxout_enum::kNull)
    .add_enum("batch", softmaxout_enum::kBatch)
    .add_enum("valid", softmaxout_enum::kValid)
    .set_default(softmaxout_enum::kNull)
    .describe("Normalizes the gradient.");
    DMLC_DECLARE_FIELD(out_grad)
    .set_default(false)
    .describe("Multiplies gradient with output gradient element-wise.");
  };
};

template<typename xpu, typename DType>
class SoftmaxOutputOp : public Operator {
 public:
  explicit SoftmaxOutputOp(SoftmaxOutputParam param) : param_(param) {}

  virtual void Forward(const OpContext &ctx,
                       const std::vector<TBlob> &in_data,
                       const std::vector<OpReqType> &req,
                       const std::vector<TBlob> &out_data,
                       const std::vector<TBlob> &aux_args) {
    using namespace mshadow;
    using namespace mshadow::expr;
    CHECK_EQ(in_data.size(), 2U) << "SoftmaxOutput Input: [data, label]";
    CHECK_EQ(out_data.size(), 1U) << "SoftmaxOutput Output: [output]";
    Stream<xpu> *s = ctx.get_stream<xpu>();
    if (param_.multi_output) {
      int n = in_data[softmaxout_enum::kData].size(0);
      int k = in_data[softmaxout_enum::kData].size(1);
      Shape<3> s3 = Shape3(n, k, static_cast<int>(in_data[softmaxout_enum::kData].Size()/n/k));
      Tensor<xpu, 3, DType> data =
          in_data[softmaxout_enum::kData].get_with_shape<xpu, 3, DType>(s3, s);
      Tensor<xpu, 3, DType> out =
          out_data[softmaxout_enum::kOut].get_with_shape<xpu, 3, DType>(s3, s);
      Softmax(out, data);
    } else {
      if (param_.preserve_shape) {
        Tensor<xpu, 2, DType> data = in_data[softmaxout_enum::kData].FlatTo2D<xpu, DType>(s);
        Tensor<xpu, 2, DType> out = out_data[softmaxout_enum::kOut].FlatTo2D<xpu, DType>(s);
        Softmax(out, data);
      } else {
        int n = in_data[softmaxout_enum::kData].size(0);
        int k = in_data[softmaxout_enum::kData].Size()/n;
        Shape<2> s2 = Shape2(n, k);
        Tensor<xpu, 2, DType> data =
            in_data[softmaxout_enum::kData].get_with_shape<xpu, 2, DType>(s2, s);
        Tensor<xpu, 2, DType> out =
            out_data[softmaxout_enum::kOut].get_with_shape<xpu, 2, DType>(s2, s);
        Softmax(out, data);
      }
    }
  }

  virtual void Backward(const OpContext &ctx,
                        const std::vector<TBlob> &out_grad,
                        const std::vector<TBlob> &in_data,
                        const std::vector<TBlob> &out_data,
                        const std::vector<OpReqType> &req,
                        const std::vector<TBlob> &in_grad,
                        const std::vector<TBlob> &aux_args) {
    using namespace mshadow;
    using namespace mshadow::expr;
    CHECK_EQ(in_data.size(), 2U);
    CHECK_EQ(out_grad.size(), 1U);
    CHECK_GE(in_grad.size(), 1U);
    CHECK_GE(req.size(), 1U);
    Stream<xpu> *s = ctx.get_stream<xpu>();

    if (out_data[softmaxout_enum::kOut].shape_ ==
        in_data[softmaxout_enum::kLabel].shape_) {
      // use probability as label
      Tensor<xpu, 2, DType> label = in_data[softmaxout_enum::kLabel].FlatTo2D<xpu, DType>(s);
      Tensor<xpu, 2, DType> out = out_data[softmaxout_enum::kOut].FlatTo2D<xpu, DType>(s);
      Tensor<xpu, 2, DType> grad = in_grad[softmaxout_enum::kData].FlatTo2D<xpu, DType>(s);
      if (param_.out_grad) {
        Tensor<xpu, 2, DType> ograd = out_grad[softmaxout_enum::kOut].FlatTo2D<xpu, DType>(s);
        grad = scalar<DType>(param_.grad_scale) * (out - label) * ograd;
      } else {
        grad = (out - label) * scalar<DType>(param_.grad_scale);
      }
    } else if (param_.multi_output) {
      int n = out_data[softmaxout_enum::kOut].size(0);
      int k = out_data[softmaxout_enum::kOut].size(1);
      Shape<3> s3 = Shape3(n, k, static_cast<int>(out_data[softmaxout_enum::kOut].Size()/n/k));
      Shape<2> s2 = Shape2(s3[0], s3[2]);
      Tensor<xpu, 2, DType> label =
          in_data[softmaxout_enum::kLabel].get_with_shape<xpu, 2, DType>(s2, s);
      Tensor<xpu, 3, DType> out =
          out_data[softmaxout_enum::kOut].get_with_shape<xpu, 3, DType>(s3, s);
      Tensor<xpu, 3, DType> grad =
          in_grad[softmaxout_enum::kData].get_with_shape<xpu, 3, DType>(s3, s);

      index_t valid_cnt = label.shape_.Size();
      if (param_.use_ignore) {
          SoftmaxGrad(grad, out, label, static_cast<DType>(param_.ignore_label));
      } else {
          SoftmaxGrad(grad, out, label);
      }
      if (param_.normalization == softmaxout_enum::kBatch) {
        valid_cnt = label.size(0);
      } else if (param_.normalization == softmaxout_enum::kValid) {
        int i_label = static_cast<int>(param_.ignore_label);
        Tensor<cpu, 2, DType> workspace =
          ctx.requested[softmaxout_enum::kTempSpace].get_host_space_typed<2, DType>(
          label.shape_);
        Copy(workspace, label, label.stream_);
        for (index_t i = 0; i < workspace.size(0); ++i) {
          for (index_t j = 0; j < workspace.size(1); ++j) {
            if (static_cast<int>(workspace[i][j]) == i_label) {
              valid_cnt--;
            }
          }
        }
        valid_cnt = valid_cnt == 0 ? 1 : valid_cnt;
      } else {
        valid_cnt = 1;
      }
      grad *= DType(param_.grad_scale /
                    (param_.normalization == softmaxout_enum::kValid ? 1 : s3[2]) /
                    valid_cnt);
      if (param_.out_grad) {
        Tensor<xpu, 3, DType> ograd =
          out_grad[softmaxout_enum::kOut].get_with_shape<xpu, 3, DType>(s3, s);
        grad *= ograd;
      }
    } else {
      Shape<1> label_shape = Shape1(in_data[softmaxout_enum::kLabel].Size());
      Shape<2> data_shape;
      if (param_.preserve_shape) {
        data_shape = out_data[softmaxout_enum::kOut].shape_.FlatTo2D();
//        Tensor<xpu, 1, DType> label = in_data[softmaxout_enum::kLabel].FlatTo1D<xpu, DType>(s);
//        Tensor<xpu, 2, DType> out = out_data[softmaxout_enum::kOut].FlatTo2D<xpu, DType>(s);
//        Tensor<xpu, 2, DType> grad = in_grad[softmaxout_enum::kData].FlatTo2D<xpu, DType>(s);
      } else {
        int n = out_data[softmaxout_enum::kOut].size(0);
        data_shape = Shape2(n, out_data[softmaxout_enum::kOut].Size()/n);
      }
      Tensor<xpu, 1, DType> label = in_data[softmaxout_enum::kLabel].get_with_shape<xpu, 1, DType>(
          label_shape, s);
      Tensor<xpu, 2, DType> out =
          out_data[softmaxout_enum::kOut].get_with_shape<xpu, 2, DType>(data_shape, s);
      Tensor<xpu, 2, DType> grad =
          in_grad[softmaxout_enum::kData].get_with_shape<xpu, 2, DType>(data_shape, s);
      index_t valid_cnt = label.shape_.Size();
      if (param_.use_ignore) {
        SoftmaxGrad(grad, out, label, static_cast<DType>(param_.ignore_label));
      } else {
        SoftmaxGrad(grad, out, label);
      }
      if (param_.normalization == softmaxout_enum::kBatch) {
        valid_cnt = label.size(0);
      } else if (param_.normalization == softmaxout_enum::kValid) {
        int i_label = static_cast<int>(param_.ignore_label);
        Tensor<cpu, 1, DType> workspace =
          ctx.requested[softmaxout_enum::kTempSpace].get_host_space_typed<1, DType>(
          label.shape_);
        Copy(workspace, label, label.stream_);
        for (index_t i = 0; i < label.size(0); ++i) {
          if (static_cast<int>(workspace[i]) == i_label) {
            valid_cnt--;
          }
        }
        valid_cnt = valid_cnt == 0 ? 1 : valid_cnt;
      } else {
        valid_cnt = 1;
      }
      grad *= DType(param_.grad_scale / valid_cnt);
      if (param_.out_grad) {
        Tensor<xpu, 2, DType> ograd =
          out_grad[softmaxout_enum::kOut].get_with_shape<xpu, 2, DType>(data_shape, s);
        grad *= ograd;
      }
    }
  }

 private:
  SoftmaxOutputParam param_;
};  // class SoftmaxOutputOp

// Decalre Factory function, used for dispatch specialization
template<typename xpu>
Operator* CreateOp(SoftmaxOutputParam param, int dtype);

#if DMLC_USE_CXX11
class SoftmaxOutputProp : public OperatorProperty {
 public:
  std::vector<std::string> ListArguments() const override {
    return {"data", "label"};
  }

  void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) override {
    param_.Init(kwargs);
  }

  std::map<std::string, std::string> GetParams() const override {
    return param_.__DICT__();
  }

  bool InferShape(std::vector<TShape> *in_shape,
                  std::vector<TShape> *out_shape,
                  std::vector<TShape> *aux_shape) const override {
    using namespace mshadow;
    CHECK_EQ(in_shape->size(), 2U) << "Input:[data, label]";
    const TShape &dshape = in_shape->at(0);
    if (dshape.ndim() == 0) return false;

    // label.shape == data.shape: use probability as label
    if (dshape != (*in_shape)[softmaxout_enum::kLabel]) {
      if (param_.multi_output) {
        TShape lshape1 = Shape2(dshape[0], dshape.Size()/dshape[0]/dshape[1]);
        TShape lshape2(dshape.ndim() - 1);
        lshape2[0] = dshape[0];
        for (index_t i = 2; i < dshape.ndim(); ++i)
          lshape2[i-1] = dshape[i];
        TShape lshape3 = dshape;
        lshape3[1] = 1;
        if (in_shape->at(softmaxout_enum::kLabel).ndim() == 0) {
          in_shape->at(softmaxout_enum::kLabel) = lshape1;
        } else if (in_shape->at(softmaxout_enum::kLabel) == lshape1) {
        } else if (in_shape->at(softmaxout_enum::kLabel) == lshape2) {
        } else if (in_shape->at(softmaxout_enum::kLabel) == lshape3) {
        } else {
          std::ostringstream os;
          os << "Expecting " << lshape1 << " or " << lshape2
             << ". But got " << in_shape->at(softmaxout_enum::kLabel);
          throw InferShapeError(os.str(), softmaxout_enum::kLabel);
        }
      } else {
        TShape label_shape(dshape.ndim() - 1);
        for (index_t i = 0; i + 1 < dshape.ndim(); ++i)
          label_shape[i] = dshape[i];
        SHAPE_ASSIGN_CHECK(*in_shape, softmaxout_enum::kLabel, label_shape);
      }
    }
    out_shape->clear();
    out_shape->push_back(dshape);
    return true;
  }

  bool InferType(std::vector<int> *in_type,
                 std::vector<int> *out_type,
                 std::vector<int> *aux_type) const override {
    CHECK_GE(in_type->size(), 1U);
    int dtype = (*in_type)[0];
    CHECK_NE(dtype, -1) << "First input must have specified type";
    for (index_t i = 0; i < in_type->size(); ++i) {
      if ((*in_type)[i] == -1) {
        (*in_type)[i] = dtype;
      } else {
        CHECK_EQ((*in_type)[i], dtype) << "This layer requires uniform type. "
                                       << "Expected " << dtype << " v.s. given "
                                       << (*in_type)[i] << " at " << ListArguments()[i];
      }
    }
    out_type->clear();
    out_type->push_back(dtype);
    return true;
  }

  OperatorProperty* Copy() const override {
    auto ptr = new SoftmaxOutputProp();
    ptr->param_ = param_;
    return ptr;
  }

  std::string TypeString() const override {
    return "SoftmaxOutput";
  }

  std::vector<int> DeclareBackwardDependency(
    const std::vector<int> &out_grad,
    const std::vector<int> &in_data,
    const std::vector<int> &out_data) const override {
    if (param_.out_grad) {
      return {in_data[softmaxout_enum::kLabel], out_data[softmaxout_enum::kOut],
              out_grad[softmaxout_enum::kOut]};
    } else {
      return {in_data[softmaxout_enum::kLabel], out_data[softmaxout_enum::kOut]};
    }
  }

  std::vector<std::pair<int, void*> > BackwardInplaceOption(
    const std::vector<int> &out_grad,
    const std::vector<int> &in_data,
    const std::vector<int> &out_data,
    const std::vector<void*> &in_grad) const override {
    return {{out_data[softmaxout_enum::kOut], in_grad[softmaxout_enum::kData]}};
  }

  std::vector<std::pair<int, void*> > ForwardInplaceOption(
    const std::vector<int> &in_data,
    const std::vector<void*> &out_data) const override {
    return {{in_data[softmaxout_enum::kData], out_data[softmaxout_enum::kOut]}};
  }

  std::vector<ResourceRequest> BackwardResource(
      const std::vector<TShape> &in_shape) const override {
    return {ResourceRequest::kTempSpace};
  }

  Operator* CreateOperator(Context ctx) const override {
    LOG(FATAL) << "Not Implemented.";
    return NULL;
  }

  Operator* CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape,
                             std::vector<int> *in_type) const override;

 protected:
  SoftmaxOutputParam param_;
};  // class SoftmaxOutputProp

class DeprecatedSoftmaxProp : public SoftmaxOutputProp {
 public:
  void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) override {
    LOG(INFO) << "Softmax symbol is renamed to SoftmaxOutput. "
      << "This API will be deprecated in Dec, 2015";
    SoftmaxOutputProp::param_.Init(kwargs);
  }

  std::string TypeString() const override {
    return "Softmax";
  }
};
#endif  // DMLC_USE_CXX11

}  // namespace op
}  // namespace mxnet
#endif  // MXNET_OPERATOR_SOFTMAX_OUTPUT_INL_H_


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

namespace AdferoVideoDotNet.AdferoArticles.Feeds
{
    public class AdferoFeedList : AdferoListBase
    {
        private List<AdferoFeedListItem> _items;

        public List<AdferoFeedListItem> Items { get { return _items; } }

        public AdferoFeedList()
        {
            _items = new List<AdferoFeedListItem>();
        }
    }
}


text:
"""
test_lifecycle_single_standalone.py

In general, our approach to using ansible is to first progamatically
create the ansible inventory files for a deployment.  We do this using
the 'inventory_manager' role.  In some sense, the inventory provides a
"definition" of what is to be deployed. Various provisioning workflows
are executed given this environment inventory.

This test module executes a subset of provisioning workflows can code branches
for *one* of these definitions, specifically the single-standalone
deployment mode:

This should exercise the following codepaths:
-deployment_model=lb_only
-deploy_analytics=false

"""

import sys
import json
import pytest
from time import time
from f5_aws.config import Config
from f5_aws.environment_manager import EnvironmentManager, EnvironmentManagerFactory

config = Config().config
region_for_lifecyle_tests = config['regions'][0]
deployment_models = config['deployment_models']

# class TestLifecycleSingleStandalone(object):
#     @classmethod
#     # def setup_class(cls):
#     #     """ setup any state specific to the execution of the given class (which
#     #     usually contains tests).
#     #     """
#     #     timestamp = int(time())
#     #     # first, we need to initialize the environment we are going to deploy
#     #     # initialize the inventory
#     #     cls.init_inputs = {
#     #         "env_name": "ut-standalone-{}".format(timestamp),
#     #         "extra_vars": {
#     #             "deployment_model": "single-standalone",
#     #             "deployment_type": "lb_only",
#     #             "region": region_for_lifecyle_tests,
#     #             "zone": region_for_lifecyle_tests + "b"
#     #         },
#     #         "cmd": "init"
#     #     }
#     #     cls.deploy_inputs = {
#     #         "env_name": "ut-standalone-{}".format(timestamp),
#     #         "cmd":"deploy"
#     #     }
#     #     cls.teardown_inputs = {
#     #         "env_name": "ut-standalone-{}".format(timestamp),
#     #         "cmd":"teardown"
#     #     }
#     #     cls.remove_inputs = {
#     #         "env_name": "ut-standalone-{}".format(timestamp),
#     #         "cmd":"remove"
#     #     }
#     def setup_class(cls):
#         """ setup any state specific to the execution of the given class (which
#         usually contains tests).
#         """
#         timestamp = int(time())
#         # first, we need to initialize the environment we are going to deploy
#         # initialize the inventory
#         cls.init_inputs = {
#             "env_name": "ut-standalone-1447974075",
#             "extra_vars": {
#                 "deployment_model": "single-standalone",
#                 "deployment_type": "lb_only",
#                 "region": region_for_lifecyle_tests,
#                 "zone": region_for_lifecyle_tests + "b"
#             },
#             "cmd": "init"
#         }
#         cls.deploy_inputs = {
#             "env_name": "ut-standalone-1447974075",
#             "cmd":"deploy"
#         }
#         cls.teardown_inputs = {
#             "env_name": "ut-standalone-1447974075",
#             "cmd":"teardown"
#         }
#         cls.remove_inputs = {
#             "env_name": "ut-standalone-1447974075",
#             "cmd":"remove"
#         }

#     @classmethod
#     def teardown_class(cls):
#         """ teardown any state that was previously setup with a call to
#         setup_class.
#         """
#         em = EnvironmentManagerFactory(**self.teardown_inputs)
#         outputs = getattr(em, "teardown")()
#         em.remove()

#     def test_init_environment(self):
#         """ initialize the ansible inventory"""
#         em = EnvironmentManagerFactory(**self.init_inputs)
#         outputs = getattr(em, "init")()
#         assert (len(outputs["playbook_results"].playbooks) > 0 and
#                 outputs["playbook_results"].statuscode == 0)

#     def test_deploy_environment(self):
#         """
#         Use ansible to deploy the environment - this is long
#         running, as long as 25 minutes
#         """
#         em = EnvironmentManagerFactory(**self.deploy_inputs)
#         outputs = getattr(em, "deploy")()
#         assert (len(outputs["playbook_results"].playbooks) > 0 and
#                 outputs["playbook_results"].statuscode == 0)

#         # once the environment is deployed, we can check for a number
#         #  items we are expecting in the CLI output
#         login_info = em.login_info()

#         app = ''
#         virtual_server = ''

#         assert len(login_info['bigip']) == 1
#         for host, variables in login_info['bigip'].iteritems():
#             virtual_server_ip = variables["elastic_ips"][0]
#             assert len(variables["elastic_ips"]) > 0
#             assert len(variables["virtual_servers"]) > 0
#             assert variables["https"]
#             assert variables["ssh"]

#         assert len(login_info['apphost']) == 1
#         for host, variables in login_info['apphost'].iteritems():
#             app_ip = variables['http'][0]
#             assert variables["http"]
#             assert variables["ssh"]

#         assert len(login_info['gtm']) == 1
#         for host, variables in login_info['gtm'].iteritems():
#             assert len(variables["elastic_ips"]) > 0
#             assert len(variables["wideips"]) > 0
#             assert variables["https"]
#             assert variables["ssh"]

#         # finally, we can do a simple curl against the http address of the app
#         #  and the https address of the virtual server
#         r = requests.get('https://{}'.format(virtual_server))
#         assert re.match('20[0-9]', string(r.status_code))

#         r = requests.get('{}'.format(app))
#         assert re.match('20[0-9]', string(r.status_code))


text:
This repo contains my .dotfiles and others customized to my liking.

Feel free to fork if you like.

## .bashrc
![Terminal Screenshot](http://i.imgur.com/tbRJoQb.png)

## tmpz.zsh-theme
![Zsh Theme](https://i.imgur.com/WiOHkcS.png)