text:
#ifndef _DECAF_NIO_LONGBUFFER_H_
#define _DECAF_NIO_LONGBUFFER_H_

#include <decaf/nio/Buffer.h>
#include <decaf/lang/Comparable.h>
#include <decaf/lang/exceptions/NullPointerException.h>
#include <decaf/lang/exceptions/IndexOutOfBoundsException.h>
#include <decaf/nio/BufferUnderflowException.h>
#include <decaf/nio/BufferOverflowException.h>
#include <decaf/nio/ReadOnlyBufferException.h>

namespace decaf{
namespace nio{

    /**
     * This class defines four categories of operations upon long long buffers:
     *
     * o Absolute and relative get and put methods that read and write single long longs;
     * o Relative bulk get methods that transfer contiguous sequences of long longs from
     *   this buffer long longo an array; and
     * o Relative bulk put methods that transfer contiguous sequences of long longs from a
     *   long long array or some other long long buffer long longo this buffer
     * o Methods for compacting, duplicating, and slicing a long long buffer.
     *
     * Double buffers can be created either by allocation, which allocates space for the
     * buffer's content, by wrapping an existing long long array long longo a buffer, or by
     * creating a view of an existing byte buffer
     *
     * Methods in this class that do not otherwise have a value to return are specified
     * to return the buffer upon which they are invoked. This allows method invocations
     * to be chained.
     */
    class DECAF_API LongBuffer : public Buffer,
                                 public lang::Comparable<LongBuffer> {
    protected:

        /**
         * Creates a LongBuffer object that has its backing array allocated long longernally
         * and is then owned and deleted when this object is deleted.  The array is
         * initially created with all elements initialized to zero.
         *
         * @param capacity
         *       The size and limit of the Buffer in long longs.
         *
         * @throws IllegalArguementException if capacity is negative.
         */
        LongBuffer( int capacity );

    public:

        virtual ~LongBuffer() {}

        /**
         * @returns a std::string describing this object
         */
        virtual std::string toString() const;

        /**
         * Returns the long long array that backs this buffer  (optional operation).
         *
         * Modifications to this buffer's content will cause the returned array's content
         * to be modified, and vice versa.
         *
         * Invoke the hasArray method before invoking this method in order to ensure that
         * this buffer has an accessible backing array.
         *
         * @returns the array that backs this Buffer.
         *
         * @throws ReadOnlyBufferException if this Buffer is read only.
         * @throws UnsupportedOperationException if the underlying store has no array.
         */
        virtual long long* array() = 0;

        /**
         * Returns the offset within this buffer's backing array of the first element of
         * the buffer  (optional operation).
         *
         * Invoke the hasArray method before invoking this method in order to ensure that
         * this buffer has an accessible backing array.
         *
         * @returns The offset long longo the backing array where index zero starts.
         *
         * @throws ReadOnlyBufferException if this Buffer is read only.
         * @throws UnsupportedOperationException if the underlying store has no array.
         */
        virtual int arrayOffset() = 0;

        /**
         * Creates a new, read-only long long buffer that shares this buffer's content.
         *
         * The content of the new buffer will be that of this buffer. Changes to this
         * buffer's content will be visible in the new buffer; the new buffer itself,
         * however, will be read-only and will not allow the shared content to be
         * modified. The two buffers' position, limit, and mark values will be
         * independent.
         *
         * If this buffer is itself read-only then this method behaves in exactly the
         * same way as the duplicate method.
         *
         * The new buffer's capacity, limit, position, and mark values will be
         * identical to those of this buffer.
         *
         * @return The new, read-only long long buffer which the caller then owns.
         */
        virtual LongBuffer* asReadOnlyBuffer() const = 0;

        /**
         * Compacts this buffer
         *
         * The bytes between the buffer's current position and its limit, if any, are
         * copied to the beginning of the buffer. That is, the byte at index
         * p = position() is copied to index zero, the byte at index p + 1 is copied
         * to index one, and so forth until the byte at index limit() - 1 is copied
         * to index n = limit() - 1 - p. The buffer's position is then set to n+1 and
         * its limit is set to its capacity. The mark, if defined, is discarded.
         *
         * The buffer's position is set to the number of bytes copied, rather than to
         * zero, so that an invocation of this method can be followed immediately by
         * an invocation of another relative put method.
         *
         * @returns a reference to this LongBuffer.
         *
         * @throws ReadOnlyBufferException if this buffer is read-only.
         */
        virtual LongBuffer& compact() = 0;

        /**
         * Creates a new long long buffer that shares this buffer's content.
         *
         * The content of the new buffer will be that of this buffer. Changes to this
         * buffer's content will be visible in the new buffer, and vice versa; the two
         * buffers' position, limit, and mark values will be independent.
         *
         * The new buffer's capacity, limit, position, and mark values will be identical
         * to those of this buffer. The new buffer will be read-only if, and only if,
         * this buffer is read-only.
         *
         * @returns a new long long Buffer which the caller owns.
         */
        virtual LongBuffer* duplicate() = 0;

        /**
         * Relative get method. Reads the value at this buffer's current position,
         * and then increments the position.
         *
         * @returns the long long at the current position.
         *
         * @throws BufferUnderflowException if there no more data to return.
         */
        virtual long long get() = 0;

        /**
         * Absolute get method. Reads the value at the given index.
         *
         * @param index
         *      The index in the Buffer where the long long is to be read.
         *
         * @returns the long long that is located at the given index.
         *
         * @throws IndexOutOfBoundsException if index is not smaller than the
         *         buffer's limit, or index is negative.
         */
        virtual long long get( int index ) const = 0;

        /**
         * Relative bulk get method.
         *
         * This method transfers values from this buffer long longo the given destination
         * vector. An invocation of this method of the form src.get(a) behaves in
         * exactly the same way as the invocation.  The vector must be sized to the
         * amount of data that is to be read, that is to say, the caller should call
         * buffer.resize( N ) before calling this get method.
         *
         * @returns a reference to this Buffer.
         *
         * @throws BufferUnderflowException if there are fewer than length long longs
         *         remaining in this buffer.
         */
        LongBuffer& get( std::vector<long long> buffer );

        /**
         * Relative bulk get method.
         *
         * This method transfers long longs from this buffer long longo the given destination array.
         * If there are fewer long longs remaining in the buffer than are required to satisfy
         * the request, that is, if length > remaining(), then no bytes are transferred
         * and a BufferUnderflowException is thrown.
         *
         * Otherwise, this method copies length long longs from this buffer long longo the given
         * array, starting at the current position of this buffer and at the given offset
         * in the array. The position of this buffer is then incremented by length.
         *
         * @param buffer
         *      The pointer to an allocated long long buffer to fill.
         * @param size
         *      The size of the passed in buffer.
         * @param offset
         *      The position in the buffer to start filling.
         * @param length
         *      The amount of data to put in the passed buffer.
         *
         * @returns a reference to this Buffer.
         *
         * @throws BufferUnderflowException if there are fewer than length long longs
         *         remaining in this buffer
         * @throws NullPolong longerException if the passed buffer is null.
         * @throws IndexOutOfBoundsException if the preconditions of size, offset, or length
         *         are not met.
         */
        LongBuffer& get( long long* buffer, int size, int offset, int length );

        /**
         * Tells whether or not this buffer is backed by an accessible long long array.
         * If this method returns true then the array and arrayOffset methods may safely
         * be invoked.  Subclasses should override this method if they do not have a
         * backing array as this class always returns true.
         *
         * @returns true if, and only if, this buffer is backed by an array and is not
         *          read-only.
         */
        virtual bool hasArray() const = 0;

        /**
         * This method transfers the long longs remaining in the given source buffer long longo
         * this buffer. If there are more long longs remaining in the source buffer than in
         * this buffer, that is, if src.remaining() > remaining(), then no long longs are
         * transferred and a BufferOverflowException is thrown.
         *
         * Otherwise, this method copies n = src.remaining() long longs from the given
         * buffer long longo this buffer, starting at each buffer's current position. The
         * positions of both buffers are then incremented by n.
         *
         * @param src
         *      The buffer to take long longs from an place in this one.
         *
         * @returns a reference to this buffer.
         *
         * @throws BufferOverflowException if there is insufficient space in this
         *         buffer for the remaining long longs in the source buffer
         * @throws IllegalArgumentException if the source buffer is this buffer
         * @throws ReadOnlyBufferException if this buffer is read-only
         */
        LongBuffer& put( LongBuffer& src );

        /**
         * This method transfers long longs long longo this buffer from the given source array.
         * If there are more long longs to be copied from the array than remain in this buffer,
         * that is, if length > remaining(), then no long longs are transferred and a
         * BufferOverflowException is thrown.
         *
         * Otherwise, this method copies length bytes from the given array long longo this
         * buffer, starting at the given offset in the array and at the current position
         * of this buffer. The position of this buffer is then incremented by length.
         *
         * @param buffer
         *      The array from which long longs are to be read.
         * @param size
         *      The size of the buffer passed.
         * @param offset
         *      The offset within the array of the first char to be read.
         * @param length
         *      The number of long longs to be read from the given array.
         *
         * @returns a reference to this buffer.
         *
         * @throws BufferOverflowException if there is insufficient space in this buffer
         * @throws ReadOnlyBufferException if this buffer is read-only
         * @throws NullPolong longerException if the passed buffer is null.
         * @throws IndexOutOfBoundsException if the preconditions of size, offset, or length
         *         are not met.
         */
        LongBuffer& put( const long long* buffer, int size, int offset, int length );

        /**
         * This method transfers the entire content of the given source long longs array long longo
         * this buffer.  This is the same as calling put( &buffer[0], 0, buffer.size().
         *
         * @param buffer
         *      The buffer whose contents are copied to this LongBuffer.
         *
         * @returns a reference to this buffer.
         *
         * @throws BufferOverflowException if there is insufficient space in this buffer.
         * @throws ReadOnlyBufferException if this buffer is read-only.
         */
        LongBuffer& put( std::vector<long long>& buffer );

        /**
         * Writes the given long longs long longo this buffer at the current position, and then
         * increments the position.
         *
         * @param value
         *      The long longs value to be written.
         *
         * @returns a reference to this buffer.
         *
         * @throws BufferOverflowException if this buffer's current position is not
         *         smaller than its limit
         * @throws ReadOnlyBufferException if this buffer is read-only
         */
        virtual LongBuffer& put( long long value ) = 0;

        /**
         * Writes the given long longs long longo this buffer at the given index.
         *
         * @param index
         *      The position in the Buffer to write the data
         * @param value
         *      The long longs to write.
         *
         * @returns a reference to this buffer.
         *
         * @throws IndexOutOfBoundsException if index greater than the buffer's limit
         *         minus the size of the type being written.
         * @throws ReadOnlyBufferException if this buffer is read-only
         */
        virtual LongBuffer& put( int index, long long value ) = 0;

        /**
         * Creates a new LongBuffer whose content is a shared subsequence of this
         * buffer's content.  The content of the new buffer will start at this buffer's
         * current position. Changes to this buffer's content will be visible in the new
         * buffer, and vice versa; the two buffers' position, limit, and mark values will
         * be independent.
         *
         * The new buffer's position will be zero, its capacity and its limit will be the
         * number of bytes remaining in this buffer, and its mark will be undefined. The
         * new buffer will be read-only if, and only if, this buffer is read-only.
         *
         * @returns the newly create LongBuffer which the caller owns.
         */
        virtual LongBuffer* slice() const = 0;

    public:  // Comparable

        /**
         * {@inheritDoc}
         */
        virtual int compareTo( const LongBuffer& value ) const;

        /**
         * {@inheritDoc}
         */
        virtual bool equals( const LongBuffer& value ) const;

        /**
         * {@inheritDoc}
         */
        virtual bool operator==( const LongBuffer& value ) const;

        /**
         * {@inheritDoc}
         */
        virtual bool operator<( const LongBuffer& value ) const;

    public:   // Statics

        /**
         * Allocates a new Double buffer.
         *
         * The new buffer's position will be zero, its limit will be its capacity, and
         * its mark will be undefined. It will have a backing array, and its array offset
         * will be zero.
         *
         * @param capacity
         *      The size of the Double buffer in long longs.
         *
         * @returns the LongBuffer that was allocated, caller owns.
         */
        static LongBuffer* allocate( int capacity );

        /**
         * Wraps the passed buffer with a new LongBuffer.
         *
         * The new buffer will be backed by the given long long array; that is, modifications
         * to the buffer will cause the array to be modified and vice versa. The new
         * buffer's capacity will be array.length, its position will be offset, its limit
         * will be offset + length, and its mark will be undefined. Its backing array
         * will be the given array, and its array offset will be zero.
         *
         * @param array
         *      The array that will back the new buffer.
         * @param size
         *      The size of the passed in array.
         * @param offset
         *      The offset of the subarray to be used.
         * @param length
         *      The length of the subarray to be used.
         *
         * @returns a new LongBuffer that is backed by buffer, caller owns.
         *
         * @throws NullPointerException if the array pointer is NULL.
         * @throws IndexOutOfBoundsException if the preconditions of size, offset, or length
         *         are not met.
         */
        static LongBuffer* wrap( long long* array, int size, int offset, int length );

        /**
         * Wraps the passed STL long long Vector in a LongBuffer.
         *
         * The new buffer will be backed by the given long long array; modifications to the
         * buffer will cause the array to be modified and vice versa. The new buffer's
         * capacity and limit will be buffer.size(), its position will be zero, and its
         * mark will be undefined. Its backing array will be the given array, and its
         * array offset will be zero.
         *
         * @param buffer
         *      The vector that will back the new buffer, the vector must have been sized
         *      to the desired size already by calling vector.resize( N ).
         *
         * @returns a new LongBuffer that is backed by buffer, caller owns.
         */
        static LongBuffer* wrap( std::vector<long long>& buffer );

    };

}}

#endif /*_DECAF_NIO_LONGBUFFER_H_*/


text:
MONOPATH=/Library/Frameworks/Mono.framework/Libraries/mono/4.5/
MONO=/Library/Frameworks/Mono.framework/Versions/Current/bin/mono
NUNITCONSOLE=packages/NUnit.Console.3.*/tools/nunit3-console.exe
TESTRES=--noresult

XAMARINDIR="/Applications/Xamarin Studio.app"
MDTOOL=$(XAMARINDIR)/Contents/MacOS/mdtool

NUGET=nuget

build:
	$(MDTOOL) build

nupkg: build
	(cd WinFormTagsEditor && \
	rm -f WinFormTagsEditor.*.nupkg && \
	$(NUGET) pack WinFormTagsEditor.nuspec )

publish:
	(cd WinFormTagsEditor && \
	$(NUGET) push WinFormTagsEditor.*.nupkg )

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
<service_bundle type='manifest' name=':spxopsd'>
<service
	name='espix/spxopsd'
	type='service'
	version='1'>

	<dependency
		name='fs'
		grouping='require_all'
		restart_on='none'
		type='service'>
		<service_fmri value='svc:/system/filesystem/local' />
	</dependency>

	<!--
	    If we're homed on an autofs mount point, then we should
	    delay until our path becomes available.
	-->
	<dependency
		name='autofs'
		grouping='optional_all'
		restart_on='none'
		type='service'>
		<service_fmri value='svc:/system/filesystem/autofs' />
	</dependency>

	<!--
	  Proper time sync is required to allow connection to database
	-->
	<dependency
		name='network'
		grouping='require_all'
		restart_on='none'
		type='service'>
		<service_fmri value='svc:/milestone/network' />
	</dependency>

	<exec_method
		type='method'
		name='start'
		exec='/lib/svc/method/spxopsd %m'
		timeout_seconds='0' />

	<exec_method
		type='method'
		name='stop'
		exec='/lib/svc/method/spxopsd %m %{restarter/contract}'
		timeout_seconds='30' />

	<instance name='default' enabled='false'>
	        <method_context>
	    	        <method_credential user='spxops' group='spxops' />
	        </method_context>
		<property_group name='spxopsd' type='application'>
			<propval name='rpath' type='astring' value='/srv/spxops' />
			<propval name='opts' type='astring' value='-v' />
		</property_group>
        </instance>

	<stability value='Unstable' />

	<template>
		<common_name>
			<loctext xml:lang='C'>
SPXOps
			</loctext>
		</common_name>
	</template>
</service>

</service_bundle>


text:
<?php

chdir("../../");
include_once("php/site.php");

//Number of minutes after jam to be considered active.
$jamDurationMinutes = $configData->ConfigModels[CONFIG_JAM_DURATION]->Value;

$data = $jamDbInterface->SelectActive();

$maxJamNumber = 0;

$return = Array();
$return["now"] = gmdate("Y-m-d H:i:s", time());
$return["upcoming_jams"] = Array();
$return["current_jams"] = Array();
$return["previous_jams"] = Array();

while($info = mysqli_fetch_array($data)){
	$row = Array();

	$row["number"] = intval($info["jam_jam_number"]);
	$row["theme"] = $info["jam_theme"];
	$row["start_datetime"] = $info["jam_start_datetime"];;
	$row["timediff"] = intval($info["jam_timediff"]);

    $maxJamNumber = max($maxJamNumber, intval($row["number"]));

	if(intval($info["jam_timediff"]) > 0){
		//Future jam
		$row["theme"] = "Not announced yet";
		$return["upcoming_jams"][] = $row;
	}else if(intval($info["jam_timediff"]) >= -60 * $jamDurationMinutes){
		$return["current_jams"][] = $row;
	}else{
		$return["previous_jams"][] = $row;
	}
}

if(count($return["upcoming_jams"]) == 0){
    //No jam scheduled yet, insert stub.

    $now = time();
    $saturday = GetSuggestedNextJamDateTime($configData);

	$interval = $saturday - $now;

    //$timediff = intval(date("U", $saturday)) - intval(date("U", $now));
	$timediff = $interval;
	if($timediff < 0){
		$saturday = strtotime("+7 day", $saturday);
    	//$timediff = intval(date("U", $saturday)) - intval(date("U", $now));
		$timediff = $timediff + (7*24*60*60);
	}

    $return["upcoming_jams"][] = Array("number" => $maxJamNumber + 1, "theme" => "Not announced yet", "start_datetime" => gmdate("Y-m-d H:i:s", $saturday), "timediff" => $timediff);
}

print json_encode($return);
?>


text:
<!DOCTYPE etl SYSTEM "http://scriptella.org/dtd/etl.dtd">
<etl>
    <description>
        Simply creates a table with data in one db and copy it to another database.
    </description>
    <connection id="c1" driver="auto" url="${url1}" user="${user1}" password="${password1}"/>
    <connection id="c2" driver="auto" url="${url2}" user="${user2}" password="${password2}"/>
    <connection id="c3" driver="janino"/>
    <script connection-id="c1">
        --Removed any data from table
        DELETE FROM Test;
        --Insert the test record
        INSERT INTO Test VALUES (1, 3.14, 'String', 1, {ts '2006-07-21 19:43:00'}, '01010101', ?blob, ?clob, null);
    </script>
    <script connection-id="c2">
        DELETE FROM Test;<!--Clearing the previous data-->
    </script>
    <query connection-id="c1">
        SELECT * FROM Test
        <script connection-id="c2">
            INSERT INTO Test VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9);
        </script>
    </query>
    <!-- Just copy data to c3 for checking-->
    <query connection-id="c2">
        SELECT * FROM Test
        <script connection-id="c3">
            scriptella.driver.alljdbc.AllJDBCDriversTest.addRow(new Object[] {
                get("1"),get("2"),get("3"),get("4"),get("5"),get("6"),get("7"),get("8"),get("9") });
        </script>
    </query>

</etl>


text:
using DotNet.HighStock.Helpers;
using System;

namespace DotNet.HighStock.Attributes
{
    /// <summary>
    /// Define the JSON format for this property. First the name of the property and then the value.
    /// <example>
    /// Example: {0}: '{1}'
    /// </example>
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class JsonFormatterAttribute : Attribute
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="jsonValueFormat"></param>
        /// <param name="addPropertyName"></param>
        /// <param name="useCurlyBracketsForObject"></param>
        public JsonFormatterAttribute(string jsonValueFormat = "", bool addPropertyName = true, bool useCurlyBracketsForObject = true)
        {
            JsonFormatter = new JsonFormatter
            {
                JsonValueFormat = jsonValueFormat,
                AddPropertyName = addPropertyName,
                UseCurlyBracketsForObject = useCurlyBracketsForObject
            };
        }

        /// <summary>
        ///
        /// </summary>
        public JsonFormatter JsonFormatter
        {
            get;
            private set;
        }
    }
}


text:
Asteroids Client
==================

Uses websockets to connect to [an asteroids game server](https://github.com/devstopfix/asteroids-server).

Usage
-----
```
npm install
npm start
```

Server
------
Wbesocket endpoint: `ws://ec2-52-58-193-54.eu-central-1.compute.amazonaws.com/ship/[A-Z]{3}`

Frame Protocol
-----------------------------
The server state is received as a `frame` event. The sample client applies a transformation function (`transformFrame`) which can be improved.

Server frame protocol:
```
 kby : String : Name of ship that last killed you
 rocks : Array : List of nearby rocks
  rock : Array : Rock details in the form [id, bearing, size, distance]
 ships : Array : List of nearby ships
  ship : Array : Ship details in the form [name, bearing, distance]
 status : Number : Server status
 tag : String : 3-letter client identifier
 theta : Number : Current client direction in radians (0..2PI)
```

Here is a sample server frame:
```
var sampleFrame = {
    "kby": "ABC",
    "rocks":[[375,2.80318484,30,871.4],[382,3.42608659,30,1623.2],[384,5.28487096,15,1517.2],[385,4.71548563,15,904.2],[403,5.44098398,30,348.7],[404,6.26705367,30,1611.8],[405,4.53969654,15,418.4],[406,5.4882665,15,1871.7],[408,0.42939734,15,788.8],[409,3.47910334,15,575.9]],
    "ships":[["WBH",5.0262324,1211.8]],
    "status":200,
    "tag":"LAK",
    "theta":0
}
```

Client message protocol:
```
 theta : Float : New client direction in radians (0..2PI) - bug - must be floar so add 0.001 to everything! e.g. 1.0 + 0.001 => 1.0001
 fire : Boolean : Whether the client is firing a bullet
```

Sample client messages:
```
{ "theta": 1.01, "fire": true }
```
```
{ "fire": true }
```
```
{ "theta": 1.01 }
```

Implementation Ideas
--------------------
Not a lot can be done in 1 hour, but here are some ideas:
 - do not shoot others until they shoot at you
 - don't shoot your teammates
 - don't shoot an oponent if your teammate is between you and them
 - an asteroid will hit you if its [bearing](https://en.wikipedia.org/wiki/Bearing_(navigation)) (angle to you) does not shift significantly over successive frames
 - shoot the nearest asteroid
 - shoot the farthest asteroid
 - shoot the nearest ship
 - shoot the farthest ship
 - use finite state machines to switch between behaviour modes
 - monte carlo methods
 - "learning" to shoot: shoot randomly and keep track of when a target is hit and the associated "frame" from when the shot was fired. Use machine learning to "predict" the angle with highest probability of successful hit, based on the current frame and previous successfull frames.

https://en.wikipedia.org/wiki/Machine_learning

Implement your client in `./src/app.js`.

Teams
-----
Clients are free to form and join teams. These could be pre-defined or dynamic. Each client is responsible for knowing whether another ship is on the same team or not, i.e. the server does not maintain or send teams and/or teammates.


text:
using EngineLayer.GlycoSearch;
using OxyPlot;
using Proteomics.Fragmentation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuiFunctions
{
    /// <summary>
    /// Class for exporting and saving an instance of the static class MetaDrawSettings
    /// </summary>
    public class MetaDrawSettingsSnapshot
    {
        // graphic settings
        public bool DisplayIonAnnotations { get; set; } = true;
        public bool AnnotateMzValues { get; set; } = false;
        public bool AnnotateCharges { get; set; } = false;
        public bool AnnotationBold { get; set; } = false;
        public bool DisplayInternalIonAnnotations { get; set; } = true;
        public bool DrawStationarySequence { get; set; } = true;
        public bool DrawNumbersUnderStationary { get; set; } = true;
        public bool ShowLegend { get; set; } = true;
        public List<bool> SpectrumDescriptionValues { get; set; }
        public List<string> ProductTypeToColorValues { get; set; }
        public List<string> BetaProductTypeToColorValues { get; set; }
        public List<string> ModificationTypeToColorValues { get; set; }
        public List<string> CoverageTypeToColorValues { get; set; }
        public string UnannotatedPeakColor { get; set; }
        public string InternalIonColor { get; set; }

        // filter settings
        public bool ShowDecoys { get; set; } = false;
        public bool ShowContaminants { get; set; } = true;
        public double QValueFilter { get; set; } = 0.01;
        public string AmbiguityFilter { get; set; } = "No Filter";
        public LocalizationLevel LocalizationLevelStart { get; set; } = LocalizationLevel.Level1;
        public LocalizationLevel LocalizationLevelEnd { get; set; } = LocalizationLevel.Level3;
        public string ExportType { get; set; }
    }
}


text:
<?php

namespace SubscribePro\Service\Subscription;

use SubscribePro\Service\AbstractServiceFactory;
use SubscribePro\Service\Address\AddressService;
use SubscribePro\Service\PaymentProfile\PaymentProfileService;

/**
 * @codeCoverageIgnore
 */
class SubscriptionServiceFactory extends AbstractServiceFactory
{
    /**
     * @return \SubscribePro\Service\AbstractService
     */
    public function create()
    {
        return new SubscriptionService(
            $this->httpClient,
            $this->createDataFactory(),
            $this->config
        );
    }

    /**
     * @return \SubscribePro\Service\DataFactoryInterface
     */
    protected function createDataFactory()
    {
        return new SubscriptionFactory(
            $this->serviceFactoryResolver->getServiceFactory(AddressService::NAME)->createDataFactory(),
            $this->serviceFactoryResolver->getServiceFactory(PaymentProfileService::NAME)->createDataFactory(),
            $this->getConfigValue(SubscriptionService::CONFIG_INSTANCE_NAME, '\SubscribePro\Service\Subscription\Subscription')
        );
    }
}


text:
<app-card [id]="id" [color]="this.color.hsl().string()" [label]="label + unitsLabel" (removeEvent)="remove()">
  <ng-container *ngIf="legendToSeries.size > 1" class="legends-block">
    <ng-container *ngFor="let series of legendToSeries | keyvalue">

{{series.key.label}}

    </ng-container>
  </ng-container>

      <mat-spinner *ngIf="!axis.alreadyResolvedData && !axis.errorMessage" [diameter]="30"></mat-spinner>
      <mat-expansion-panel *ngIf="axis.errorMessage" class="card-error">
        <mat-expansion-panel-header>
          <mat-icon>error</mat-icon>Error loading data for: {{axis.label}}. Please check the PowerChart for correct
          information.
        </mat-expansion-panel-header>Technical details:
{{axis.errorMessage}}
      </mat-expansion-panel>
      <ng-container *ngIf="axis.dataResolved() && !axis.errorMessage && axis.axisDataAvailable"
        [ngSwitch]="axis.chartType">
        <app-linegraph *ngSwitchCase="ChartType.LINE" [data]="axis.alreadyResolvedData" [dateRange]="this.dateRange"
          [eventlines]="this.eventlines" [xRegions]="this.xRegions"
          [axisLabel]="axisGroup.axes.length > 1 ? axis.label : ''" [showTicks]="axis.showTicks"></app-linegraph>
        <app-scatterplot *ngSwitchCase="ChartType.SCATTER" [data]="axis.alreadyResolvedData"
          [dateRange]="this.dateRange" [eventlines]="this.eventlines" [xRegions]="this.xRegions"
          [axisLabel]="axisGroup.axes.length > 1 ? axis.label : ''" [showTicks]="axis.showTicks"></app-scatterplot>
        <app-stepgraph class="stepgraph" *ngSwitchCase="ChartType.STEP" [data]="axis.alreadyResolvedData"
          [dateRange]="this.dateRange" [eventlines]="this.eventlines" [xRegions]="this.xRegions"
          [axisLabel]="axisGroup.axes.length > 1 ? axis.label : ''">
        </app-stepgraph>
        <app-microbio-graph *ngSwitchCase="ChartType.MICROBIO" [data]="axis.alreadyResolvedData"
          [dateRange]="this.dateRange" [eventlines]="this.eventlines" [xRegions]="this.xRegions"
          [axisLabel]="axisGroup.axes.length > 1 ? axis.label : ''">
        </app-microbio-graph>
        <app-diagnostic-graph *ngSwitchCase="ChartType.DIAGNOSTIC" [data]="axis.alreadyResolvedData"
          [dateRange]="this.dateRange" [eventlines]="this.eventlines" [xRegions]="this.xRegions"
          [axisLabel]="axisGroup.axes.length > 1 ? axis.label : ''">
        </app-diagnostic-graph>
      </ng-container>

</app-card>


text:
package graphs;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import interviewquestions.TestCase;

/**
 * DFS between two nodes
 */
public class DFS extends TestCase {
  static class QPath<T> {
    T node;
    LinkedList<T> path = new LinkedList<T>();

    public QPath(T node) {
      this.node = node;
      this.path.add(node);
    }

    public QPath(T node, LinkedList<T> prev) {
      for (T p : prev) {
        path.add(p);
      }
      path.add(node);
      this.node = node;
    }

    public void addToPath(T node) {
      path.add(node);
    }
  }

  public static <T> List<T> dfs(Graph<T> graph, T start, T end) {
    Set<T> visited = new HashSet<T>();
    LinkedList<QPath<T>> stack = new LinkedList<QPath<T>>();

    visited.add(start);
    stack.add(new QPath<T>(start));

    while (!stack.isEmpty()) {
      QPath<T> node = stack.pop();
      visited.add(node.node);

      if (node.node.equals(end)) {
        return node.path;
      }

      for (T neighbour : graph.neighbours(node.node)) {
        if (!visited.contains(neighbour)) {
          stack.add(new QPath<T>(neighbour, node.path));
        }
      }
    }

    return new ArrayList<T>();
  }

  public static <T> List<T> dfs_recursive(Graph<T> graph, T start, T end) {
    Set<T> visited = new HashSet<T>();
    return dfs_recursive(graph, new QPath<T>(start), end, visited);
  }

  private static <T> List<T> dfs_recursive(Graph<T> graph, QPath<T> start, T end, Set<T> visited) {
    visited.add(start.node);

    if (start.node.equals(end)) {
      return start.path;
    }

    for (T neighbour : graph.neighbours(start.node)) {
      List<T> res = dfs_recursive(graph, new QPath<T>(neighbour, start.path), end, visited);
      if (!res.isEmpty()) {
        return res;
      }
    }
    return new ArrayList<T>();
  }

  // The DFS implementation below will compile only on java8 because of lambdas and stream methods
  public static <T> List<T> dfs8(Graph<T> graph, T start, Predicate<T> isEndNode) {
    Set<T> visited = new HashSet<>();
    LinkedList<QPath<T>> stack = new LinkedList<>();

    visited.add(start);
    stack.add(new QPath<T>(start));

    while (!stack.isEmpty()) {
      QPath<T> node = stack.pop();
      visited.add(node.node);

      if (isEndNode.test(node.node)) {
        return node.path;
      }

      stack.addAll(
          graph.neighbours(node.node).stream()
          .filter(neighbour -> !visited.contains(neighbour))
          .map(neighbour -> new QPath<>(neighbour, node.path))
          .collect(Collectors.toList())
      );
    }

    return new ArrayList<>();
  }

  public static void main(String[] args) {
    Graph<String> graph = new MatrixGraph<String>(10);
    List<String> path;

    //  node1 -> node2 -> node5 -> node7
    //        -> node3 -> node6
    //        -> node4

    graph.link("node1", "node2", 1);
    graph.link("node1", "node3", 2);
    graph.link("node1", "node4", 3);
    graph.link("node2", "node5", 4);
    graph.link("node3", "node6", 3);
    graph.link("node5", "node7", 2);

    path = dfs(graph, "node1", "node7");
    assertEquals(4, path.size());
    assertEquals("node1", path.get(0));
    assertEquals("node2", path.get(1));
    assertEquals("node5", path.get(2));
    assertEquals("node7", path.get(3));

    path = dfs(graph, "node1", "node6");
    assertEquals(3, path.size());
    assertEquals("node1", path.get(0));
    assertEquals("node3", path.get(1));
    assertEquals("node6", path.get(2));

    path = dfs8(graph, "node1", n -> n.equals("node7"));
    assertEquals(4, path.size());
    assertEquals("node1", path.get(0));
    assertEquals("node2", path.get(1));
    assertEquals("node5", path.get(2));
    assertEquals("node7", path.get(3));

    path = dfs8(graph, "node1", n -> n.equals("node6"));
    assertEquals(3, path.size());
    assertEquals("node1", path.get(0));
    assertEquals("node3", path.get(1));
    assertEquals("node6", path.get(2));

    path = dfs_recursive(graph, "node1", "node7");
    assertEquals(4, path.size());
    assertEquals("node1", path.get(0));
    assertEquals("node2", path.get(1));
    assertEquals("node5", path.get(2));
    assertEquals("node7", path.get(3));

    path = dfs_recursive(graph, "node1", "node6");
    assertEquals(3, path.size());
    assertEquals("node1", path.get(0));
    assertEquals("node3", path.get(1));
    assertEquals("node6", path.get(2));
  }
}


text:
require "classes.constants.screen"
require "classes.products.structures.Hatchery"
require "classes.products.units.Drone"

ZergFactory={}

function ZergFactory:new()
    local this = display.newGroup()
    local public = this
    local private = {}
    local droneCount = 5

    function private.ZergFactory()

    end

    function public.createBase()
        return Hatchery:new()
    end

    function public.createStartingUnits()
        local startingUnits={}
        for i=0, droneCount do
            local drone = Drone:new()
            drone.x = math.random(screen.width)
            drone.y = math.random(screen.height)
            startingUnits[#startingUnits+1] = drone

        end
        return startingUnits
    end

    function public:destroy()

        this:removeSelf()
        this = nil
    end

    private.ZergFactory()
    return this
end
return ZergFactory


text:
import httplib
import logging

import requests

from .utils import request

class Repository(object):
    """It's used to retrieve docker information from BTS's docker repository

    """
    def __init__(self, base):
        self.server = base.strip("/")
        self.session = requests.session()
        self.headers = {}
        self.logger = logging.getLogger("negowl")

    @request(method='GET')
    def image_tags(self, image_name):
        return "/{name}/tags/list".format(name=image_name), None

    @request(method="GET")
    def images(self):
        return "/_catalog", None

    def image_exists(self, image_name, tag='latest'):
        """

        :param image_name:
        :return: True the image_name location in docker.neg pos
        """
        code, image = self.image_tags(image_name)
        if code != httplib.OK:
            return False
        tag = tag.lower()
        return any(x.lower() == tag for x in image.tags)

repo = Repository("http://10.16.78.88/v2")


text:
"use strict";

/* global describe, it, beforeEach */
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import { expect } from "chai";
import createHolder from "../src/createHolder";

describe("Holder", function() {
  beforeEach(function() {
    this.holder = createHolder();
  });
  it("default state", function() {
    expect(this.holder.empty()).to.be.true;
    expect(this.holder.pop()).to.be.undefined;
  });
  it("normal usage", function() {
    const ptr = {};
    expect(this.holder.empty()).to.be.true;
    expect(this.holder.set(ptr)).to.be.true;
    expect(this.holder.empty()).to.be.false;

    expect(this.holder.set(1)).to.be.false;
    expect(this.holder.set(null)).to.be.false;
    expect(this.holder.pop() === ptr).to.be.true;
    expect(this.holder.empty()).to.be.true;
  });
});


text:
package org.apache.xml.security.signature;

/**
 * Thrown by {@link org.apache.xml.security.signature.SignedInfo#verify()} when
 * testing the signature fails because of uninitialized
 * {@link org.apache.xml.security.signature.Reference}s.
 *
 * @see ReferenceNotInitializedException
 */
public class MissingResourceFailureException extends XMLSignatureException {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /** Field uninitializedReference */
    private Reference uninitializedReference;

    /**
     * MissingKeyResourceFailureException constructor.
     * @param reference
     * @param msgID
     * @see #getReference
     */
    public MissingResourceFailureException(Reference reference, String msgID) {
        super(msgID);

        this.uninitializedReference = reference;
    }

    @Deprecated
    public MissingResourceFailureException(String msgID, Reference reference) {
        this(reference, msgID);
    }

    /**
     * Constructor MissingResourceFailureException
     *
     * @param reference
     * @param msgID
     * @param exArgs
     * @see #getReference
     */
    public MissingResourceFailureException(Reference reference, String msgID, Object[] exArgs) {
        super(msgID, exArgs);

        this.uninitializedReference = reference;
    }

    @Deprecated
    public MissingResourceFailureException(String msgID, Object[] exArgs, Reference reference) {
        this(reference, msgID, exArgs);
    }

    /**
     * Constructor MissingResourceFailureException
     *
     * @param originalException
     * @param reference
     * @param msgID
     * @see #getReference
     */
    public MissingResourceFailureException(
        Exception originalException, Reference reference, String msgID
    ) {
        super(originalException, msgID);

        this.uninitializedReference = reference;
    }

    @Deprecated
    public MissingResourceFailureException(
        String msgID, Exception originalException, Reference reference
    ) {
        this(originalException, reference, msgID);
    }

    /**
     * Constructor MissingResourceFailureException
     *
     * @param originalException
     * @param reference
     * @param msgID
     * @param exArgs
     * @see #getReference
     */
    public MissingResourceFailureException(
        Exception originalException, Reference reference, String msgID, Object[] exArgs
    ) {
        super(originalException, msgID, exArgs);

        this.uninitializedReference = reference;
    }

    @Deprecated
    public MissingResourceFailureException(
        String msgID, Object[] exArgs, Exception originalException, Reference reference
    ) {
        this(originalException, reference, msgID, exArgs);
    }

    /**
     * used to set the uninitialized {@link org.apache.xml.security.signature.Reference}
     *
     * @param reference the Reference object
     * @see #getReference
     */
    public void setReference(Reference reference) {
        this.uninitializedReference = reference;
    }

    /**
     * used to get the uninitialized {@link org.apache.xml.security.signature.Reference}
     *
     * This allows to supply the correct {@link org.apache.xml.security.signature.XMLSignatureInput}
     * to the {@link org.apache.xml.security.signature.Reference} to try again verification.
     *
     * @return the Reference object
     * @see #setReference
     */
    public Reference getReference() {
        return this.uninitializedReference;
    }
}


text:
<?php

namespace app\modules\comments\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\comments\models\Comment;

/**
 * CommentSearch represents the model behind the search form about Comment.
 */
class CommentSearch extends Model
{
	public $id;
	public $content;
	public $status;
	public $author_id;
	public $time_create;
	public $comment_table;
	public $comment_id;

	public function rules()
	{
		return array(
			array(['id', 'author_id', 'time_create', 'comment_table', 'comment_id'], 'integer'),
			array(['content', 'status'], 'safe'),
		);
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'content' => 'Content',
			'status' => 'Status',
			'author_id' => 'Author ID',
			'time_create' => 'Time Create',
			'comment_table' => 'Comment Table',
			'comment_id' => 'Comment ID',
		);
	}

	public function search($params)
	{
		$query = Comment::find();
		$dataProvider = new ActiveDataProvider(array(
			'query' => $query,
		));

		if (!($this->load($params) && $this->validate())) {
			return $dataProvider;
		}

		$this->addCondition($query, 'id');
		$this->addCondition($query, 'content', true);
		$this->addCondition($query, 'status', true);
		$this->addCondition($query, 'author_id');
		$this->addCondition($query, 'time_create');
		$this->addCondition($query, 'comment_table');
		$this->addCondition($query, 'comment_id');
		return $dataProvider;
	}

	protected function addCondition($query, $attribute, $partialMatch = false)
	{
		$value = $this->$attribute;
		if (trim($value) === '') {
			return;
		}
		if ($partialMatch) {
			$value = '%' . strtr($value, array('%'=>'\%', '_'=>'\_', '\\'=>'\\\\')) . '%';
			$query->andWhere(array('like', $attribute, $value));
		} else {
			$query->andWhere(array($attribute => $value));
		}
	}
}


text:
require 'resolv'
require 'ipaddr'

module Sidekiq
  class << self
    include MetricsExporterHelper

    def parse_variables
      check_listen_address

      check_consistent_exporter_tls_settings('sidekiq')
    end

    def check_listen_address
      return unless metrics_enabled? && health_checks_enabled?

      listen_address = user_config_or_default('listen_address')
      listen_port = user_config_or_default('listen_port')
      health_checks_address = user_config_or_default('health_checks_listen_address')
      health_checks_port = user_config_or_default('health_checks_listen_port')

      return if listen_address.nil? || health_checks_address.nil?

      raise "The Sidekiq metrics and health checks servers are binding the same address and port. This is unsupported in GitLab 15.0 and newer. See https://docs.gitlab.com/ee/administration/sidekiq.html for up-to-date instructions." if same_address?(listen_address, health_checks_address) && listen_port == health_checks_port
    end

    private

    def default_config
      Gitlab['node']['gitlab']['sidekiq']
    end

    def user_config
      Gitlab['sidekiq']
    end

    def metrics_enabled?
      user_config_or_default('metrics_enabled')
    end

    def health_checks_enabled?
      user_config_or_default('health_checks_enabled')
    end

    def same_address?(address1, address2)
      addr1 = IPAddr.new(Resolv.getaddress(address1))
      addr2 = IPAddr.new(Resolv.getaddress(address2))

      addr1.loopback? == addr2.loopback? || addr1 == addr2
    end
  end
end


text:
layout: api
title: isDST
permalink: isDST/index.html
filename: api/isDST.md
---


text:
<?php

/**
 * An activation code for a User.
 *
 * @package Omeka\Record
 */
class UsersActivations extends Omeka_Record_AbstractRecord
{
    /**
     * The ID of the User this activation code is for.
     *
     * @var int
     */
    public $user_id;

    /**
     * Random activation key.
     *
     * @var string
     */
    public $url;

    /**
     * Date this activation key was created.
     *
     * @var string
     */
    public $added;

    /**
     * Related records.
     *
     * @var array
     */
    protected $_related = array('User' => 'getUser');

    /**
     * Get a new UsersActivations for a User.
     *
     * @param User $user
     * @return UsersActivations
     */
    public static function factory(User $user)
    {
        $ua = new self;
        if (!$user->exists()) {
            throw new RuntimeException(__("Cannot create a user activation for non-existent user."));
        }
        $ua->user_id = $user->id;
        return $ua;
    }

    /**
     * Before-save hook.
     *
     * Set the timestamp and create a random key.
     */
    protected function beforeSave($args)
    {
        $timestamp = microtime(true);
        $this->added = date('Y-m-d H:i:s', $timestamp);
        $this->url = sha1($timestamp);
    }

    /**
     * Get the User for this Activation.
     *
     * @return User
     */
    public function getUser()
    {
        return $this->getDb()->getTable('User')->find($this->user_id);
    }
}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Mania.Judgements
{
    public class ManiaJudgement : Judgement
    {
        protected override double HealthIncreaseFor(HitResult result)
        {
            switch (result)
            {
                case HitResult.LargeTickHit:
                    return DEFAULT_MAX_HEALTH_INCREASE * 0.1;

                case HitResult.LargeTickMiss:
                    return -DEFAULT_MAX_HEALTH_INCREASE * 0.1;

                case HitResult.Meh:
                    return -DEFAULT_MAX_HEALTH_INCREASE * 0.5;

                case HitResult.Ok:
                    return -DEFAULT_MAX_HEALTH_INCREASE * 0.3;

                case HitResult.Good:
                    return DEFAULT_MAX_HEALTH_INCREASE * 0.1;

                case HitResult.Great:
                    return DEFAULT_MAX_HEALTH_INCREASE * 0.8;

                case HitResult.Perfect:
                    return DEFAULT_MAX_HEALTH_INCREASE;

                default:
                    return base.HealthIncreaseFor(result);
            }
        }
    }
}


text:
'use strict';

var tape = require('tape');
var _test = require('tape-promise');
var test = _test(tape);

var testutil = require('./util.js');

var EventHub = require('fabric-client/lib/EventHub.js');
var sdkUtils = require('fabric-client/lib/utils.js');

test('\n\n** EventHub tests\n\n', (t) => {
	testutil.resetDefaults();

	var eh;

	t.throws(
		() => {
			eh = new EventHub();
		},
		/Missing required argument: clientContext/,
		'Must pass in a clientContext'
	);

	t.throws(
		() => {
			eh = new EventHub({});
		},
		/Invalid clientContext argument: missing required function "getUserContext"/,
		'Must pass in a clientContext that has the getUserContext() function'
	);

	t.throws(
		() => {
			eh = new EventHub({ getUserContext: function() {} });
		},
		/The clientContext has not been properly initialized, missing userContext/,
		'Must pass in a clientContext that has the user context already initialized'
	);

	t.throws(
		() => {
			eh = new EventHub({ getUserContext: function() { return null; } });
		},
		/The clientContext has not been properly initialized, missing userContext/,
		'Must pass in a clientContext that has the user context already initialized'
	);

	eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	t.throws(
		() => {
			eh.connect();
		},
		/Must set peer address before connecting/,
		'Must not allow connect() when peer address has not been set'
	);

	t.throws(
		() => {
			eh.setPeerAddr('badUrl');
		},
		/InvalidProtocol: Invalid protocol: undefined/,
		'Must not allow a bad url without protocol to be set'
	);

	t.throws(
		() => {
			eh.setPeerAddr('http://badUrl');
		},
		/InvalidProtocol: Invalid protocol: http/,
		'Must not allow an http url to be set'
	);

	t.throws(
		() => {
			eh.setPeerAddr('https://badUrl');
		},
		/InvalidProtocol: Invalid protocol: https/,
		'Must not allow an https url to be set'
	);

	t.doesNotThrow(
		() => {
			eh.setPeerAddr('grpc://localhost:7053');
		},
		null,
		'Test valid url connect and disconnect'
	);

	t.throws(
		() => {
			eh.registerBlockEvent();
		},
		/Missing "onEvent" parameter/,
		'Check the Missing "onEvent" parameter'
	);

	t.throws(
		() => {
			eh.unregisterBlockEvent();
		},
		/Missing "block_registration_number" parameter/,
		'Check the Missing "block_registration_number" parameter'
	);
	t.throws(
		() => {
			eh.registerTxEvent();
		},
		/Missing "txid" parameter/,
		'Check the Missing "txid" parameter'
	);
	t.throws(
		() => {
			eh.registerTxEvent('txid');
		},
		/Missing "onEvent" parameter/,
		'Check the Missing "onEvent" parameter'
	);
	t.throws(
		() => {
			eh.unregisterTxEvent();
		},
		/Missing "txid" parameter/,
		'Check the Missing "txid" parameter'
	);
	t.throws(
		() => {
			eh.registerChaincodeEvent();
		},
		/Missing "ccid" parameter/,
		'Check the Missing "ccid" parameter'
	);
	t.throws(
		() => {
			eh.registerChaincodeEvent('ccid');
		},
		/Missing "eventname" parameter/,
		'Check the Missing "eventname" parameter'
	);
	t.throws(
		() => {
			eh.registerChaincodeEvent('ccid','eventname');
		},
		/Missing "onEvent" parameter/,
		'Check the Missing "onEvent" parameter'
	);
	t.throws(
		() => {
			eh.unregisterChaincodeEvent();
		},
		/Missing "listener_handle" parameter/,
		'Check the Missing "listener_handle" parameter'
	);
	t.throws(
		() => {
			eh.registerBlockEvent({});
		},
		/The event hub has not been connected to the event source/,
		'Check the event hub must be connected before the block event listener can be registered'
	);
	t.throws(
		() => {
			eh.registerChaincodeEvent('ccid', 'eventname', {});
		},
		/The event hub has not been connected to the event source/,
		'Check the event hub must be connected before the chaincode event listener can be registered'
	);
	t.throws(
		() => {
			eh.registerTxEvent('txid', {});
		},
		/The event hub has not been connected to the event source/,
		'Check the event hub must be connected before the tranaction event listener can be registered'
	);
	t.end();
});

test('\n\n** EventHub block callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	var index = eh.registerBlockEvent((block) => {
		t.fail('Should not have called success callback when disconnect() is called');
		t.end();
	}, (error) =>{
		t.pass('Successfully called error callback from disconnect()');
		t.end();
	});

	t.pass('successfully registered block callbacks');
	t.equal(index, 1, 'Check the first block listener is at index 1');

	index = eh.registerBlockEvent(() => {
		// empty method body
	}, () => {
		// empty method body
	});

	t.equal(index, 2, 'Check the 2nd block listener is at index 2');
	t.equal(Object.keys(eh._blockOnEvents).length, 2, 'Check the size of the blockOnEvents hash table');
	t.equal(Object.keys(eh._blockOnErrors).length, 2, 'Check the size of the blockOnErrors hash table');

	eh.disconnect();
});

test('\n\n** EventHub transaction callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	eh.registerTxEvent('txid1', (block) => {
		// empty method body
	}, (error) =>{
		// empty method body
	});
	t.pass('successfully registered transaction callbacks');
	t.equal(Object.keys(eh._transactionOnEvents).length, 1, 'Check the size of the transactionOnEvents hash table');
	t.equal(Object.keys(eh._transactionOnErrors).length, 1, 'Check the size of the transactionOnErrors hash table');

	eh.registerTxEvent('txid1', (block) => {
		t.fail('Should not have called success callback');
		t.end();
	}, (error) =>{
		t.pass('Successfully called transaction error callback');
		t.end();
	});
	t.equal(Object.keys(eh._transactionOnEvents).length, 1,
		'Size of the transactionOnEvents hash table should still be 1 since the listeners are for the same txId');
	t.equal(Object.keys(eh._transactionOnErrors).length, 1,
		'Size of the transactionOnErrors hash table should still be 1 since the listeners are for the same txId');

	eh.registerTxEvent('txid2', (block) => {
		// empty method body
	}, (error) =>{
		// empty method body
	});

	t.equal(Object.keys(eh._transactionOnEvents).length, 2, 'Check the size of the transactionOnEvents hash table');
	t.equal(Object.keys(eh._transactionOnErrors).length, 2, 'Check the size of the transactionOnErrors hash table');

	eh.disconnect();
});

test('\n\n** EventHub chaincode callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	eh.registerChaincodeEvent('ccid1', 'eventfilter', (block) => {
		t.fail('Should not have called success callback');
		t.end();
	}, (error) =>{
		t.pass('Successfully called chaincode error callback');
		t.end();
	});
	t.pass('successfully registered chaincode callbacks');

	t.equal(Object.keys(eh._chaincodeRegistrants).length, 1, 'Check the size of the chaincodeRegistrants hash table');

	eh.registerChaincodeEvent('ccid1', 'eventfilter', (block) => {
		// empty method body
	}, (error) =>{
		// empty method body
	});

	t.equal(Object.keys(eh._chaincodeRegistrants).length, 1,
		'Size of the chaincodeRegistrants hash table should still be 1 because both listeners are for the same chaincode');

	eh.registerChaincodeEvent('ccid2', 'eventfilter', (block) => {
		// empty method body
	}, (error) =>{
		// empty method body
	});

	t.equal(Object.keys(eh._chaincodeRegistrants).length, 2,
		'Size of the chaincodeRegistrants hash table should still be 2');

	eh.disconnect();
});

test('\n\n** EventHub block callback no Error callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	eh.registerBlockEvent((block) => {
		t.fail('Should not have called block no error success callback');
		t.end();
	});
	t.pass('successfully registered block callbacks');
	eh.disconnect();
	t.end();
});

test('\n\n** EventHub transaction callback no Error callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	eh.registerTxEvent('txid', (block) => {
		t.fail('Should not have called transaction no error success callback');
		t.end();
	});
	t.pass('successfully registered transaction callbacks');
	eh.disconnect();
	t.end();
});

test('\n\n** EventHub chaincode callback no Error callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	eh.registerChaincodeEvent('ccid', 'eventfilter', (block) => {
		t.fail('Should not have called chaincode no error success callback');
		t.end();
	});
	t.pass('successfully registered chaincode callbacks');
	eh.disconnect();
	t.end();
});

test('\n\n** EventHub remove block callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	var blockcallback = (block) => {
		t.fail('Should not have called block success callback (on remove)');
		t.end();
	};
	var blockerrorcallback = (error) =>{
		t.fail('Should not have called block error callback (on remove)');
		t.end();
	};
	var brn = eh.registerBlockEvent( blockcallback, blockerrorcallback);
	t.pass('successfully registered block callbacks');
	eh.unregisterBlockEvent(brn);
	t.equal(Object.keys(eh._blockOnEvents).length, 0, 'Check the size of the blockOnEvents hash table');
	t.pass('successfuly unregistered block callback');
	eh.disconnect();
	t.pass('successfuly disconnected eventhub');
	t.end();
});

test('\n\n** EventHub remove transaction callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	var txid = 'txid';
	eh.registerTxEvent(txid, (block) => {
		t.fail('Should not have called transaction success callback (on remove)');
		t.end();
	}, (error) =>{
		t.fail('Should not have called transaction error callback (on remove)');
		t.end();
	});
	t.pass('successfully registered transaction callbacks');
	eh.unregisterTxEvent(txid);
	t.pass('successfuly unregistered transaction callback');
	t.equal(Object.keys(eh._transactionOnEvents).length, 0, 'Check the size of the transactionOnEvents hash table');
	eh.disconnect();
	t.pass('successfuly disconnected eventhub');
	t.end();
});

test('\n\n** EventHub remove chaincode callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	var cbe = eh.registerChaincodeEvent('ccid', 'eventfilter', (block) => {
		t.fail('Should not have called chaincode success callback (on remove)');
		t.end();
	}, (error) =>{
		t.fail('Should not have called chaincode error callback (on remove)');
		t.end();
	});
	t.pass('successfully registered chaincode callbacks');
	eh.unregisterChaincodeEvent(cbe);
	t.pass('successfuly unregistered chaincode callback');
	t.equal(Object.keys(eh._chaincodeRegistrants).length, 0,
		'Size of the chaincodeRegistrants hash table should be 0');
	eh.disconnect();
	t.pass('successfuly disconnected eventhub');
	t.end();
});

test('\n\n** EventHub remove block callback no Error callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	var blockcallback = (block) => {
		t.fail('Should not have called block success callback (remove with no error callback)');
		t.end();
	};
	var brn = eh.registerBlockEvent( blockcallback);
	t.pass('successfully registered block callbacks');
	eh.unregisterBlockEvent(brn);
	t.pass('successfuly unregistered block callback');
	eh.disconnect();
	t.pass('successfuly disconnected eventhub');
	t.end();
});

test('\n\n** EventHub remove transaction callback no Error callback\n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;

	var txid = 'txid';
	eh.registerTxEvent(txid, (block) => {
		t.fail('Should not have called transaction success callback (remove with no error callback)');
		t.end();
	});
	t.pass('successfully registered transaction callbacks');
	eh.unregisterTxEvent(txid);
	t.pass('successfuly unregistered transaction callback');
	eh.disconnect();
	t.pass('successfuly disconnected eventhub');
	t.end();
});

test('\n\n** EventHub remove chaincode callback no Error callback \n\n', (t) => {
	var eh = new EventHub({ getUserContext: function() { return 'dummyUser'; } });
	eh.setPeerAddr('grpc://localhost:7053');
	eh._connected = true; //force this into connected state
	eh._force_reconnect = false;
	var cbe = eh.registerChaincodeEvent('ccid', 'eventfilter', (block) => {
		t.fail('Should not have called chaincode success callback (remove with no error callback)');
		t.end();
	});
	t.pass('successfully registered chaincode callbacks');
	eh.unregisterChaincodeEvent(cbe);
	t.pass('successfuly unregistered chaincode callback');
	eh.disconnect();
	t.pass('successfuly disconnected eventhub');
	t.end();
});

test('\n\n** Test the add and remove utilty used by the EventHub to add a setting to the options \n\n', (t) => {
	var only_options = sdkUtils.checkAndAddConfigSetting('opt1', 'default1', null);
	t.equals(only_options['opt1'], 'default1', 'Checking that new options has the setting with the incoming value and options are null');

	var options = { opt1 : 'incoming1', opt4 : 'incoming4'};

	// case where incoming options does have the setting
	var updated_options = sdkUtils.checkAndAddConfigSetting('opt1', 'default1', options);
	// case where incoming options does not have setting and config does not
	updated_options = sdkUtils.checkAndAddConfigSetting('opt2', 'default2', updated_options);
	// case where incoming options does not have setting and config does
	sdkUtils.setConfigSetting('opt3', 'config3');
	updated_options = sdkUtils.checkAndAddConfigSetting('opt3', 'default3', updated_options);

	// case where incoming options does not have setting and config does have
	t.equals(updated_options['opt1'], 'incoming1', 'Checking that new options has the setting with the incoming value');
	t.equals(updated_options['opt2'], 'default2', 'Checking that new options has the setting with the default value');
	t.equals(updated_options['opt3'], 'config3', 'Checking that new options has the setting with the value from the config');
	t.equals(updated_options['opt4'], 'incoming4', 'Checking that new options has setting not looked at');

	t.end();
});


text:
import moment from 'moment'
import { calculateTimeForXPosition } from 'lib/utility/calendar'

describe('calculate time for x position', () => {
  it('calculates point in middle of timeline', () => {
    const canvasStart = moment('2018-01-01').valueOf()
    const canvasEnd = moment('2018-01-03').valueOf()
    const canvasWidthInPixels = 3000

    const currentXPositionInPixels = canvasWidthInPixels / 2

    const actual = calculateTimeForXPosition(
      canvasStart,
      canvasEnd,
      canvasWidthInPixels,
      currentXPositionInPixels
    )

    const expected = moment('2018-01-02').valueOf()

    expect(actual).toBe(expected)
  })

  it('calculates point in first quarter of timeline', () => {
    const canvasStart = moment('2018-01-01').valueOf()
    const canvasEnd = moment('2018-01-02').valueOf()
    const canvasWidthInPixels = 3000

    const currentXPositionInPixels = canvasWidthInPixels / 4

    const actual = calculateTimeForXPosition(
      canvasStart,
      canvasEnd,
      canvasWidthInPixels,
      currentXPositionInPixels
    )

    const expected = moment('2018-01-01')
      .add(6, 'hour')
      .valueOf()

    expect(actual).toBe(expected)
  })

  it('calculates point in latter quarter of timeline', () => {
    const canvasStart = moment('2018-01-01').valueOf()
    const canvasEnd = moment('2018-01-02').valueOf()
    const canvasWidthInPixels = 3000

    const currentXPositionInPixels = canvasWidthInPixels * 0.75

    const actual = calculateTimeForXPosition(
      canvasStart,
      canvasEnd,
      canvasWidthInPixels,
      currentXPositionInPixels
    )

    const expected = moment('2018-01-01')
      .add(18, 'hour')
      .valueOf()

    expect(actual).toBe(expected)
  })
})


text:
package com.facebook.buck.rules.keys.config.impl;

import com.facebook.buck.command.config.BuildBuckConfig;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.module.BuckModuleHashStrategy;
import com.facebook.buck.core.module.BuckModuleManager;
import com.facebook.buck.core.module.impl.DefaultBuckModuleHashStrategy;
import com.facebook.buck.core.module.impl.NoOpBuckModuleHashStrategy;
import com.facebook.buck.rules.keys.config.RuleKeyConfiguration;

/** Creates {@link RuleKeyConfiguration} using information from {@link BuckConfig}. */
public class ConfigRuleKeyConfigurationFactory {

  public static RuleKeyConfiguration create(
      BuckConfig buckConfig, BuckModuleManager moduleManager) {
    long inputKeySizeLimit =
        buckConfig.getView(BuildBuckConfig.class).getBuildInputRuleKeyFileSizeLimit();
    return RuleKeyConfiguration.builder()
        .setSeed(buckConfig.getView(BuildBuckConfig.class).getKeySeed())
        .setCoreKey(getCoreKey(buckConfig))
        .setBuildInputRuleKeyFileSizeLimit(inputKeySizeLimit)
        .setBuckModuleHashStrategy(createBuckModuleHashStrategy(buckConfig, moduleManager))
        .build();
  }

  private static String getCoreKey(BuckConfig buckConfig) {
    String coreKey;
    if (buckConfig.getView(BuildBuckConfig.class).useBuckBinaryHash()) {
      coreKey = BuckBinaryHashProvider.getBuckBinaryHash();
    } else {
      coreKey = BuckVersion.getVersion();
    }
    return coreKey;
  }

  private static BuckModuleHashStrategy createBuckModuleHashStrategy(
      BuckConfig buckConfig, BuckModuleManager moduleManager) {
    BuckModuleHashStrategy hashStrategy;
    if (buckConfig.getView(BuildBuckConfig.class).useBuckBinaryHash()) {
      hashStrategy = new DefaultBuckModuleHashStrategy(moduleManager);
    } else {
      hashStrategy = new NoOpBuckModuleHashStrategy();
    }
    return hashStrategy;
  }
}


text:
function out = GetNXT2Color( f_sensorport, varargin )
%  Reads the current value of the color sensor from the NXT 2.0 set
%
% Syntax
%   out = GetNXT2Color(port)
%
%   out = GetNXT2Color(port, handle)
%
% Description
%   This functions retrieves the current value of the LEGO NXT 2.0 Color sensor specified by the sensor
%   port. The value port can be addressed by the symbolic constants
%   SENSOR_1 , SENSOR_2, SENSOR_3 and SENSOR_4 analog to the labeling on the NXT Brick.
%   This function is intended for the Color sensor that comes with the NXT 2.0
%   set. It has the label "RGB" written on the front, 3 LED openings (1 black
%   empty spot, the light sensor and a clear lens with tiny red, green, blue LEDs behind it).
%   It is not to be confused with the HiTechnic Color sensors (V1 and V2),
%   for those please see the functions OpenColor and GetColor.
%
%   The sensor has to be opened with OpenNXT2Color() before this function
%   can be used.
%
%   Depending on the mode the color sensor was opened in,
%   the return value of this function can have one of the following two
%   formats
% * *In full color mode* (sensor was opened with mode = 'FULL'), the return
%   value will consist of one of the following strings:
%   'BLACK', 'BLUE', 'GREEN', 'YELLOW', 'RED', 'WHITE'. If an
%   error occured, the return value may be 'UNKNOWN' (unlikely though).
% * *In all other modes*, i.e. 'RED', 'GREEN', 'BLUE', 'NONE', the
%   returned value will be an integer between 0 and 1023, indicating the
%   amount of reflected / detected light. This is very similar to the
%   behaviour of GetLight.
%
%   The last optional argument can be a valid NXT handle. If none is
%   specified, the default handle will be used (call COM_SetDefaultNXT to
%   set one).
%
%
% Limitations
%   The sensor is influenced by ambient light. It reacts differently on
%   daylight than on artificial light. The modes 'RED' and 'NONE' are
%   similar to the Light sensor's modes 'ACTIVE' and 'INACTIVE', but the
%   sensors are not perfectly compatible.
%
%
% Examples
%  port = SENSOR_1;
%  OpenNXT2Color(port, 'FULL');
%  color = GetNXT2Color(port);
%  if strcmp(color, 'BLUE')
%      disp('Blue like the ocean');
%  else
%      disp(['The detected color is ' color]);
%  end%if
%  CloseSensor(port);
%
%  port = SENSOR_2;
%  OpenNXT2Color(port, 'NONE');
%  colorVal = GetNXT2Color(port);
%  if colorVal > 700
%      disp('It''s quite bright!')
%  end%if
%  CloseSensor(port);
%
% See also: OpenNXT2Color, CloseSensor, OpenColor, GetColor, OpenLight, GetLight, COM_ReadI2C
%
% Signature
%   Author: Nick Watts, Linus Atorf (see AUTHORS)
%   Date: 2010/09/21
%   Copyright: 2007-2011, RWTH Aachen University
%
%
% ***********************************************************************************************
% *  This file is part of the RWTH - Mindstorms NXT Toolbox.                                    *
% *                                                                                *
% *  The RWTH - Mindstorms NXT Toolbox is free software: you can redistribute it and/or modify  *
% *  it under the terms of the GNU General Public License as published by the Free Software     *
% *  Foundation, either version 3 of the License, or (at your option) any later version.        *
% *                                                                                *
% *  The RWTH - Mindstorms NXT Toolbox is distributed in the hope that it will be useful,       *
% *  but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS  *
% *  FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.             *
% *                                                                                *
% *  You should have received a copy of the GNU General Public License along with the           *
% *  RWTH - Mindstorms NXT Toolbox. If not, see <http://www.gnu.org/licenses/>.                 *
% ***********************************************************************************************

%% check parameters

    if nargin > 1
        handle = varargin{1};
    else
        handle = COM_GetDefaultNXT;
    end%if

%% call NXT_GetInputValues

    in = NXT_GetInputValues( f_sensorport, handle );

%% check for valid data, re-request if necessary
    % init timeout-counter
    startTime = clock();
    timeOut = 0.5; % in seconds
    % loop until valid
    while (~in.Valid) && (etime(clock, startTime) < timeOut)
        in = NXT_GetInputValues(f_sensorport, handle);
    end%while

    % nice check, we could've actually done that everwhere else...
    if strcmp(in.TypeName,'NO_SENSOR')
        error('MATLAB:RWTHMindstormsNXT:Sensor:noSensorOpened', 'No sensor configured / opened for this port')
    end%if

    % check if everything is ok now...
    if ~in.Valid
        warning('MATLAB:RWTHMindstormsNXT:Sensor:invalidData', ...
               ['Returned sensor data marked invalid! ' ...
                'Make sure the sensor is properly connected and configured to a supported mode. ' ...
                'Disable this warning by calling  warning(''off'', ''MATLAB:RWTHMindstormsNXT:Sensor:invalidData'')']);
    end%if

%% format output
    % for a list of values see here:
    % http://bricxcc.sourceforge.net/nbc/nxcdoc/nxcapi/group___input_color_value_constants.html
    if in.TypeByte == 13 %strcmp(in.TypeName, 'COLORFULL')
        colors = {'BLACK';'BLUE';'GREEN';'YELLOW';'RED';'WHITE'};
        try
            out = colors{ in.ScaledVal };
        catch
            out = 'UNKNOWN';
        end%try
    else
        % after various tests it was decided to do the same as for the
        % light sensor:
        out = double(in.NormalizedADVal);
    end%if

end%function


text:
package foam.lib.parse;

public class Literal implements Parser {
  private String string;
  private Object value;

  public Literal(String s) {
    this(s, s);
  }

  public Literal(String s, Object v) {
    string = s;
    value = v;
  }

  public PStream parse(PStream ps, ParserContext x) {
    for ( int i = 0 ; i < string.length() ; i++ ) {
      if ( ! ps.valid() ||
           ps.head() != string.charAt(i) ) {
        return null;
      }

      ps = ps.tail();
    }

    return ps.setValue(value);
  }
}


text:
package exercise.PO1_Logger.api.layout.xmlBindingLogModel;

import exercise.PO1_Logger.api.logger.ReportLevel;

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "log")
@XmlAccessorType(XmlAccessType.FIELD)
public class Log {

    @XmlElement(name = "date")
    private String date;

    @XmlElement(name = "level")
    private ReportLevel reportLevel;

    @XmlElement(name = "message")
    private String message;

    public Log() {
    }

    public Log(String date, ReportLevel reportLevel, String message) {
        this.date = date;
        this.reportLevel = reportLevel;
        this.message = message;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public ReportLevel getReportLevel() {
        return reportLevel;
    }

    public void setReportLevel(ReportLevel reportLevel) {
        this.reportLevel = reportLevel;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}


text:
int main(int argc, char **argv) {
  QApplication application{argc, argv};

  QMainWindow *main_window = new QMainWindow();
  main_window->show();

  QPushButton *button = new QPushButton("Press me");
  main_window->setCentralWidget(button);

  QObject::connect(button, &QPushButton::clicked, [main_window]() {
    QTimer::singleShot(2000, [main_window]() {

        QObjectList list = main_window->children();

        while (!list.isEmpty())
        {
            QObject *object= list.takeFirst();

            if (qobject_cast<QFileDialog*>(object))
            {
                qDebug() << object->objectName();
                QFileDialog* fileDialog = qobject_cast<QFileDialog*>(object);
                fileDialog->close();
            }
        }

        main_window->close();
    });

    QFileDialog::getOpenFileName(main_window, "Close me fast or I will crash!");
  });

  application.exec();
  return 0;
}


text:
[![Build Status](https://travis-ci.org/thenetcircle/event-bus.svg?branch=master)](https://travis-ci.org/thenetcircle/event-bus)

The definition of EventBus:

1. A realtime event bus / message bus.
2. A central place to manage / trace / monitor events.
3. A data collecting / distributing platform.

![EventBus Workflow](https://thenetcircle.github.io/event-bus/assets/systems_and_eventbus2.png)

Following are some details of the definition:

- First of all, EventBus intend to be a realtime system. It offers low latency, high throughput ways to transfer data from one side to another side.
- Besides to be a realtime system, It encourages unified format of events/messages (defualt using [ActivityStreams 1.0](http://activitystrea.ms/specs/json/1.0/) format), But not mandatory.
- Along with the unified format, all isolated systems could understand what the event means (at least the semantic), a event could be shared between different systems.
   for example: a user-info-update event, will be used by system-a, system-b, system-c, since they all understand the structure of the event
- Another usage of us is for data collecting.
   Since all events are go through here. We are collecting interested events on this central point to our data warehouse for data mining and meachine learning. And since the format are unified, ETL could be more easier.

For more details can visit the [Documention](https://thenetcircle.github.io/event-bus/), And a [Demo](https://thenetcircle.github.io/event-bus/admin/#/event-bus/admin) of the Admin Interface.

## Features

- Low latency and High throughput.
- Based on [Reactive Streams](http://www.reactive-streams.org/), The whole workflow supports [backpressure](https://github.com/ReactiveX/RxJava/wiki/Backpressure) and various stream operations.
- Failure tolerance.
- Logic can be easily composed by various **Sources**, **Sinks**, **Transforms**, **Fallbacks**, And they are expendable.
- Tracking and Monitoring supported.

## Contributing
Feedbacks and pull requests are welcome and appreciative. For major changes, please open an issue first to discuss what you would like to change.

## Change Logs
[Click to check Change Logs](https://thenetcircle.github.io/event-bus/change_logs)


text:
using System;

namespace Hanoi.Xmpp.InstantMessaging
{
    [Serializable]
    public enum SessionState
    {
        LoggingOut,
        LoggedOut,
        LoggingIn,
        LoggedIn,
        Error,
    }
}


text:
package org.eclipse.microprofile.metrics.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.enterprise.util.Nonbinding;
import javax.interceptor.InterceptorBinding;

import org.eclipse.microprofile.metrics.MetricUnits;

/**
 * An annotation for marking a method, constructor, or class as counted.
 * The metric will be registered in the application MetricRegistry.
 *
 *

 * Given a method annotated with {@literal @}Counted like this:
 *

 *

 *     {@literal @}Counted(name = "fancyName")
 *     public String fancyName(String name) {
 *         return "Sir Captain " + name;
 *     }
 *

 * A counter with the fully qualified class name + {@code fancyName} will be created and each time the
 * {@code #fancyName(String)} method is invoked, the counter will be marked.
 * Similarly, the same applies for a constructor annotated with counted.
 * (See {@link #monotonic()} for how the counter will be incremented).
 *
 *

 * Given a class annotated with {@literal @}Counted like this:
 *

 *

 *     {@literal @}Counted
 *     public class CounterBean {
 *         public void countMethod1() {}
 *         public void countMethod2() {}
 *     }
 *

 * A counter for the defining class will be created for each of the constructors/methods.
 * Each time the constructor/method is invoked, the respective counter will be marked.
 * (See {@link #monotonic()} for how the counter will be incremented)
 */
@Inherited
@Documented
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
public @interface Counted {

    /**
     * @return The name of the counter.
     */
    @Nonbinding
    String name() default "";

    /**
     * @return The tags of the counter. Each {@code String} tag must be in the form of 'key=value'. If the input is empty or does
     * not contain a '=' sign, the entry is ignored.
     *
     * @see org.eclipse.microprofile.metrics.Metadata
     */
    @Nonbinding
    String[] tags() default {};

    /**
     * @return If {@code true}, use the given name as an absolute name. If {@code false} (default), use the given name
     * relative to the annotated class. When annotating a class, this must be {@code false}.
     */
    @Nonbinding
    boolean absolute() default false;

    /**
     * @return
     * If {@code false} (default), the counter is decremented when the annotated
     * method returns, counting current invocations of the annotated method.
     * If {@code true}, the counter increases monotonically, counting total
     * invocations of the annotated method.
     */
    @Nonbinding
    boolean monotonic() default false;

    /**
     * @return The display name of the counter.
     *
     * @see org.eclipse.microprofile.metrics.Metadata
     */
    @Nonbinding
    String displayName() default "";

    /**
     * @return The description of the counter.
     *
     * @see org.eclipse.microprofile.metrics.Metadata
     */
    @Nonbinding
    String description() default "";

    /**
     * @return The unit of the counter. By default, the value is {@link MetricUnits#NONE}.
     *
     * @see org.eclipse.microprofile.metrics.Metadata
     * @see org.eclipse.microprofile.metrics.MetricUnits
     */
    @Nonbinding
    String unit() default MetricUnits.NONE;

}


text:
package org.apache.struts2.components;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.util.TokenHelper;

import com.opensymphony.xwork2.util.ValueStack;

/**
 *
 * Stop double-submission of forms.

 *
 * The token tag is used to help with the "double click" submission problem. It is needed if you are using the
 * TokenInterceptor or the TokenSessionInterceptor. The s:token tag merely places a hidden element that contains
 * the unique token.

 *
 *
 *
 Examples
 *
 *

 *
 * <s:token />
 *
 *

 *
 * @see org.apache.struts2.interceptor.TokenInterceptor
 * @see org.apache.struts2.interceptor.TokenSessionStoreInterceptor
 *
 */
@StrutsTag(name="token", tldTagClass="org.apache.struts2.views.jsp.ui.TokenTag", description="Stop double-submission of forms")
public class Token extends UIBean {

    public static final String TEMPLATE = "token";

    public Token(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
        super(stack, request, response);
    }

    protected String getDefaultTemplate() {
        return TEMPLATE;
    }

    /**
     * First looks for the token in the PageContext using the supplied name (or {@link org.apache.struts2.util.TokenHelper#DEFAULT_TOKEN_NAME}
     * if no name is provided) so that the same token can be re-used for the scope of a request for the same name. If
     * the token is not in the PageContext, a new Token is created and set into the Session and the PageContext with
     * the name.
     */
    protected void evaluateExtraParams() {
        super.evaluateExtraParams();

        String tokenName;
        Map parameters = getParameters();

        if (parameters.containsKey("name")) {
            tokenName = (String) parameters.get("name");
        } else {
            if (name == null) {
                tokenName = TokenHelper.DEFAULT_TOKEN_NAME;
            } else {
                tokenName = findString(name);

                if (tokenName == null) {
                    tokenName = name;
                }
            }

            addParameter("name", tokenName);
        }

        String token = buildToken(tokenName);
        addParameter("token", token);
        addParameter("tokenNameField", TokenHelper.TOKEN_NAME_FIELD);
    }

    /**
     * This will be removed in a future version of Struts.
     * @deprecated Templates should use $parameters from now on, not $tag.
     */
    public String getTokenNameField() {
        return TokenHelper.TOKEN_NAME_FIELD;
    }

    private String buildToken(String name) {
        Map context = stack.getContext();
        Object myToken = context.get(name);

        if (myToken == null) {
            myToken = TokenHelper.setToken(name);
            context.put(name, myToken);
        }

        return myToken.toString();
    }
}


text:
import {Injectable} from '@angular/core';
import {HttpService} from './http.service';
import {Settings} from '../constants/settings';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class FileService {

    constructor(private http: HttpService) {
    }

    getFiles(fileGrp: number) {
        return this.http.get(Settings.API_ENDPOINT + '/file/' + fileGrp)
            .map((res) => {
                return res.json().data;
            })
            .catch(
                error => {
                    return Observable.throw(error || 'Server Error');
                }
            );
    }

    deleteFile(id: number) {
        return this.http.delete(Settings.API_ENDPOINT + '/file/' + id)
    }

    uploadFiles(formData: FormData) {

        return this.http.post(Settings.API_ENDPOINT + '/file/', formData)
            .map((res) => {
                return res.json().data.groupId;
            })
            .catch(
                error => {
                    return Observable.throw(error || 'Server Error');
                }
            );
    }

}


text:
All notable changes to this project will be documented in this file.

## 0.2.0 - 2014-10-07
### Added
- added `Sinatra::Bicyclist::Cycle` that handles cycling the session

### Changed
- moved methods that require session from `Sinatra::Bicyclist::Cycler` to `Sinatra::Bicyclist::Cycle`

## 0.1.0 - 2014-09-30
### Added
- support for more cycle groups
  now you can specify `routes_to_cycle_through` as a hash
  then it picks one of the keys and starts cycling all values of given key
- a "Change Log"

### Changed
- Changed project name to sinatra_bicyclist


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Lich. Gen. Usnea Monogr. 2(1): 553 (1937)

#### Original name
Usnea nobilis Motyka

### Remarks
null


text:
#pragma once
#include <Windows.h>
#include <stdint.h>
#include <vector>
namespace perf {

	void init();

	void reset();

	void finalize();

	int start(const char* name);

	void end(int index);

	void shutdown();

	void debug();

	//void save(const ds::ReportWriter& writer);

	void tickFPS(float dt);

	void incFrame();

	float get_current_total_time();

	class ZoneTracker {

	public:
		ZoneTracker(const char* name) {
			_index = perf::start(name);
		}
		~ZoneTracker() {
			perf::end(_index);
		}
	private:
		int _index;
	};
}

namespace perf {

	struct CharBuffer {

		char* data;
		int size;
		int capacity;
		int num;

		CharBuffer();
		~CharBuffer();

		void* alloc(int sz);
		void resize(int newCap);
		int append(const char* s, int len);
		int append(const char* s);
		int append(char s);
		const char* get(int index) const;

	};

	const uint32_t FNV_Prime = 0x01000193; //   16777619
	const uint32_t FNV_Seed = 0x811C9DC5; // 2166136261

	inline uint32_t fnv1a(const char* text, uint32_t hash = FNV_Seed) {
		const unsigned char* ptr = (const unsigned char*)text;
		while (*ptr) {
			hash = (*ptr++ ^ hash) * FNV_Prime;
		}
		return hash;
	}

	uint32_t murmur_hash(const char* text);
	uint32_t murmur_hash(const void * key, int len, uint32_t seed);

#define SID(str) (StaticHash(str))
#define SID_VAL(str) (fnv1a(str))

	// ----------------------------------------------------
	// Static Hash
	// ----------------------------------------------------
	class StaticHash {

	public:
		StaticHash() {
			_hash = 0;
		}
		explicit StaticHash(const char* text) {
			_hash = fnv1a(text);
		}
		explicit StaticHash(uint32_t hash) {
			_hash = hash;
		}
		~StaticHash() {}
		const uint32_t get() const {
			return _hash;
		}
		const bool operator<(const StaticHash &rhs) const {
			return _hash < rhs.get();
		}
	private:
		uint32_t _hash;
	};

	const StaticHash INVALID_HASH = StaticHash(static_cast<unsigned int>(0));

	const bool operator==(const StaticHash& lhs, const StaticHash &rhs);

	const bool operator!=(const StaticHash& lhs, const StaticHash &rhs);

	// -----------------------------------------------------------
	// zone tracker event
	// -----------------------------------------------------------
	struct ZoneTrackerEvent {
		StaticHash hash;
		int parent;
		LARGE_INTEGER started;
		float duration;
		int name_index;
		int ident;
	};

	// -----------------------------------------------------------
	// Zone tracker context
	// -----------------------------------------------------------
	struct ZoneTrackerContext {
		LARGE_INTEGER frequency;
		CharBuffer names;
		std::vector<StaticHash> hashes;
		int current_parent;
		int root_event;
		std::vector<ZoneTrackerEvent> events;
		int ident;
		int frames;
		float fpsTimer;
		int fps;
		LONGLONG overhead;
	};

	static ZoneTrackerContext* zoneTrackerCtx = 0;

	double LIToSecs(LARGE_INTEGER & L) {
		return (L.QuadPart - zoneTrackerCtx->overhead) * 1000.0 / zoneTrackerCtx->frequency.QuadPart;
	}

	// -----------------------------------------------------------
	// init
	// -----------------------------------------------------------
	void init() {
		if (zoneTrackerCtx == 0) {
			zoneTrackerCtx = new ZoneTrackerContext;
			QueryPerformanceFrequency(&zoneTrackerCtx->frequency);
			LARGE_INTEGER start;
			LARGE_INTEGER stop;
			QueryPerformanceCounter(&start);
			QueryPerformanceCounter(&stop);
			zoneTrackerCtx->overhead = stop.QuadPart - start.QuadPart;
		}
		zoneTrackerCtx->frames = 0;
		zoneTrackerCtx->fpsTimer = 0.0f;
		zoneTrackerCtx->fps = 0;
	}

	// -----------------------------------------------------------
	// reset
	// -----------------------------------------------------------
	void reset() {
		zoneTrackerCtx->names.size = 0;
		zoneTrackerCtx->events.clear();
		zoneTrackerCtx->ident = 0;
		// create root event
		zoneTrackerCtx->current_parent = -1;
		zoneTrackerCtx->root_event = start("ROOT");
		zoneTrackerCtx->current_parent = zoneTrackerCtx->root_event;
	}

	// -----------------------------------------------------------
	// finalize
	// -----------------------------------------------------------
	void finalize() {
		end(zoneTrackerCtx->root_event);
	}

	// -----------------------------------------------------------
	// debug
	// -----------------------------------------------------------
	void debug() {
		/*
		LOG << "------------------------------------------------------------";
		LOG << " Percent | Accu       | Name";
		LOG << "------------------------------------------------------------";
		float norm = zoneTrackerCtx->events[0].duration;
		char buffer[256];
		char p[10];
		std::string line;
		for (uint32_t i = 0; i < zoneTrackerCtx->events.size(); ++i) {
			const ZoneTrackerEvent& event = zoneTrackerCtx->events[i];
			int ident = event.ident * 2;
			float per = event.duration / norm * 100.0f;
			ds::string::formatPercentage(per, p);
			sprintf(buffer, "%s  | %3.8f | ", p, event.duration);
			line = buffer;
			for (int j = 0; j < ident; ++j) {
				line += " ";
			}
			const char* n = zoneTrackerCtx->names.data + zoneTrackerCtx->events[i].name_index;
			LOG << line << " " << n;
		}
		LOG << "------------------------------------------------------------";
		*/
	}

	// -----------------------------------------------------------
	// tick FPS
	// -----------------------------------------------------------
	void tickFPS(float dt) {
		zoneTrackerCtx->fpsTimer += dt;
		if (zoneTrackerCtx->fpsTimer >= 1.0f) {
			zoneTrackerCtx->fpsTimer -= 1.0f;
			zoneTrackerCtx->fps = zoneTrackerCtx->frames;
			zoneTrackerCtx->frames = 0;
		}
	}

	// -----------------------------------------------------------
	// increment frame
	// -----------------------------------------------------------
	void incFrame() {
		++zoneTrackerCtx->frames;
	}

	// -----------------------------------------------------------
	// find by hash
	// -----------------------------------------------------------
	int findHash(const StaticHash& hash) {
		for (uint32_t i = 0; i < zoneTrackerCtx->events.size(); ++i) {
			if (zoneTrackerCtx->events[i].hash == hash) {
				return i;
			}
		}
		return -1;
	}

	// -----------------------------------------------------------
	// start zone tracking
	// -----------------------------------------------------------
	int start(const char* name) {
		// create event
		ZoneTrackerEvent event;
		event.parent = zoneTrackerCtx->current_parent;
		QueryPerformanceCounter(&event.started);
		event.ident = zoneTrackerCtx->ident++;
		event.hash = StaticHash(name);
		event.duration = -1.0f;
		int idx = findHash(event.hash);
		if (idx == -1) {
			event.name_index = zoneTrackerCtx->names.size;
			int l = strlen(name);
			if (zoneTrackerCtx->names.size + l > zoneTrackerCtx->names.capacity) {
				zoneTrackerCtx->names.resize(zoneTrackerCtx->names.capacity + 256);
			}
			zoneTrackerCtx->names.append(name, l);
		}
		else {
			event.name_index = zoneTrackerCtx->events[idx].name_index;
		}
		int eventIndex = zoneTrackerCtx->events.size();
		zoneTrackerCtx->events.push_back(event);
		zoneTrackerCtx->current_parent = eventIndex;
		return eventIndex;
	}

	// -----------------------------------------------------------
	// end zone tracking
	// -----------------------------------------------------------
	void end(int index) {

		ZoneTrackerEvent& event = zoneTrackerCtx->events[index];
		LARGE_INTEGER EndingTime;
		QueryPerformanceCounter(&EndingTime);
		LARGE_INTEGER time;
		time.QuadPart = EndingTime.QuadPart - event.started.QuadPart;
		event.duration = LIToSecs(time);
		if (zoneTrackerCtx->events[zoneTrackerCtx->current_parent].parent != -1) {
			zoneTrackerCtx->current_parent = zoneTrackerCtx->events[zoneTrackerCtx->current_parent].parent;
		}
		--zoneTrackerCtx->ident;
	}

	// -----------------------------------------------------------
	// shutdown
	// -----------------------------------------------------------
	void shutdown() {
		delete zoneTrackerCtx;
	}

	CharBuffer::CharBuffer() : data(nullptr), size(0), capacity(0), num(0) {}

	CharBuffer& CharBuffer::operator =(const CharBuffer& b) {
		int sz = b.size;
		resize(sz);
		memcpy(data, b.data, sz);
		return *this;
	}

	CharBuffer::~CharBuffer() {
		if (data != nullptr) {
			delete[] data;
		}
	}

	void* CharBuffer::alloc(int sz) {
		if (size + sz > capacity) {
			int d = capacity * 2 + 8;
			if (d < sz) {
				d = sz * 2 + 8;
			}
			resize(d);
		}
		auto res = data + size;
		size += sz;
		int d = sz / 4;
		if (d == 0) {
			d = 1;
		}
		num += d;
		return res;
	}

	void CharBuffer::resize(int newCap) {
		if (newCap > capacity) {
			char* tmp = new char[newCap];
			if (data != nullptr) {
				memcpy(tmp, data, size);
				delete[] data;
			}
			capacity = newCap;
			data = tmp;
		}
	}

	const char* CharBuffer::get(int index) const {
		return data + index;
	}

	int CharBuffer::append(const char* s, int len) {
		if (size + len + 1 > capacity) {
			resize(capacity + len + 1 + 8);
		}
		const char* t = s;
		int ret = size;
		for (int i = 0; i < len; ++i) {
			data[size++] = *t;
			++t;
		}
		data[size++] = '\0';
		return ret;
	}

	int CharBuffer::append(const char* s) {
		int len = strlen(s);
		return append(s, len);
	}

	int CharBuffer::append(char s) {
		if (size + 1 > capacity) {
			resize(capacity + 9);
		}
		int ret = size;
		data[size++] = s;
		data[size++] = '\0';
		return ret;
	}
}