text:
using System;

namespace FluentFTP {
	/// <summary>
	/// Different types of hashing algorithms for computing checksums.
	/// </summary>
	[Flags]
	public enum FtpHashAlgorithm : int {

		/// <summary>
		/// Automatic algorithm, or hashing not supported.
		/// </summary>
		NONE = 0,

		/// <summary>
		/// SHA-1 algorithm
		/// </summary>
		SHA1 = 1,

		/// <summary>
		/// SHA-256 algorithm
		/// </summary>
		SHA256 = 2,

		/// <summary>
		/// SHA-512 algorithm
		/// </summary>
		SHA512 = 4,

		/// <summary>
		/// MD5 algorithm
		/// </summary>
		MD5 = 8,

		/// <summary>
		/// CRC algorithm
		/// </summary>
		CRC = 16
	}
}


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Provides a number of unsafe byte operations to be used by advanced applications with high
 * performance requirements. These methods are referred to as "unsafe" due to the fact that they
 * potentially expose the backing buffer of a {@link ByteString} to the application.
 *
 *
DISCLAIMER: The methods in this class should only be called if it is
 * guaranteed that the buffer backing the {@link ByteString} will never change! Mutation of a {@link
 * ByteString} can lead to unexpected and undesirable consequences in your application, and will
 * likely be difficult to debug. Proceed with caution!
 *
 *
This can have a number of significant side affects that have spooky-action-at-a-distance-like
 * behavior. In particular, if the bytes value changes out from under a Protocol Buffer:
 *
 *

 *
serialization may throw
 *
serialization may succeed but the wrong bytes may be written out
 *
messages are no longer threadsafe
 *
hashCode may be incorrect
 *

 *
can result in a permanent memory leak when used as a key in a long-lived HashMap
 *
the semantics of many programs may be violated if this is the case
 *

 *

 *
 * Each of these issues will occur in parts of the code base that are entirely distinct from the
 * parts of the code base modifying the buffer. In fact, both parts of the code base may be correct
 * - it is the bridging with the unsafe operations that was in error!
 */
@ExperimentalApi
public final class UnsafeByteOperations {
  private UnsafeByteOperations() {}

  /**
   * An unsafe operation that returns a {@link ByteString} that is backed by the provided buffer.
   *
   * @param buffer the buffer to be wrapped
   * @return a {@link ByteString} backed by the provided buffer
   */
  public static ByteString unsafeWrap(byte[] buffer) {
    return ByteString.wrap(buffer);
  }

  /**
   * An unsafe operation that returns a {@link ByteString} that is backed by a subregion of the
   * provided buffer.
   *
   * @param buffer the buffer to be wrapped
   * @param offset the offset of the wrapped region
   * @param length the number of bytes of the wrapped region
   * @return a {@link ByteString} backed by the provided buffer
   */
  public static ByteString unsafeWrap(byte[] buffer, int offset, int length) {
    return ByteString.wrap(buffer, offset, length);
  }

  /**
   * An unsafe operation that returns a {@link ByteString} that is backed by the provided buffer.
   *
   * @param buffer the Java NIO buffer to be wrapped
   * @return a {@link ByteString} backed by the provided buffer
   */
  public static ByteString unsafeWrap(ByteBuffer buffer) {
    return ByteString.wrap(buffer);
  }

  /**
   * Writes the given {@link ByteString} to the provided {@link ByteOutput}. Calling this method may
   * result in multiple operations on the target {@link ByteOutput} (i.e. for roped {@link
   * ByteString}s).
   *
   *
This method exposes the internal backing buffer(s) of the {@link ByteString} to the {@link
   * ByteOutput} in order to avoid additional copying overhead. It would be possible for a malicious
   * {@link ByteOutput} to corrupt the {@link ByteString}. Use with caution!
   *
   *
NOTE: The {@link ByteOutput} MUST NOT modify the provided buffers. Doing so
   * may result in corrupted data, which would be difficult to debug.
   *
   * @param bytes the {@link ByteString} to be written
   * @param output the output to receive the bytes
   * @throws IOException if an I/O error occurs
   */
  public static void unsafeWriteTo(ByteString bytes, ByteOutput output) throws IOException {
    bytes.writeTo(output);
  }

}

redpajama_set_name: RedPajamaGithub


text:
package io.reflectoring.coderadar.dependencymap.port.driver;

import io.reflectoring.coderadar.dependencymap.domain.Node;

public interface GetDependencyTreeUseCase {
  Node getDependencyTree(Long projectId, String commitName);
}


text:
//Copyright (c) 2010, Carnegie Mellon University
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted provided
//that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice, this list of conditions and
//      the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
//      and the following disclaimer in the documentation and/or other materials provided with the
//      distribution.
//    * Neither the names of Carnegie Mellon University nor the names of its contributors may be used to
//      endorse or promote products derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
//WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
//PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
//ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
//TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
package org.fieldstream.service.sensors.phone;

import org.fieldstream.Constants;
import org.fieldstream.service.InferrenceService;
import org.fieldstream.service.sensors.api.AbstractSensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
/**
 * Wrapper class that manages the communication with the phone accelerometer. has the actual sensors (instances of {@link AbstractSensor}) as inner classes.
 * @author Patrick Blitz
 *
 */
public class Accelerometer  implements SensorEventListener{
	private SensorManager mSensorManager;
	/**
	 * The multiplier we use to get integer values instead of floats!
	 */
	private static final int MULTIPLIER = 100;
	//	private static final String TAG = "AccelPhone";
	static Accelerometer INSTANCE;
	//	private
	/**
	 * magnitude Sensors (see {@link AccelerometerSensor} ). If this is non-null, magnitude values will be passed to the  Magnitude Sensor.
	 */
	protected AccelerometerSensor magnitude ;
	/**
	 * X values Sensors (see {@link AccelerometerSensor} ). If this is non-null, the read X values will be passed to the Sensor.
	 */
	protected AccelerometerSensor accelX ;
	protected AccelerometerSensor accelY ;
	protected AccelerometerSensor accelZ ;
	protected int active=0;
	static Accelerometer getInstance() {
		if (INSTANCE==null) {
			INSTANCE = new Accelerometer();
		}
		return INSTANCE;
	}
	protected Accelerometer() {

	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		//Nothing
	}
	/**
	 * Overrides {@link SensorEventListener} to retrieve sensor Readings.
	 * @param event
	 */
	public void onSensorChanged(SensorEvent event) {
		// TODO what about the multiplier

		// I don't think we can use event.timestamp.
		// It seems event.timestamp is the # of nanoseconds since the device was booted,
		// rather than # of nanoseconds since the epoch.
		// long timestamp = event.timestamp / 1000000;   // convert to milliseconds

		long timestamp = System.currentTimeMillis();  // assume this is close to the real timestamp

		if (accelX!= null) {
			accelX.addValue((int)(event.values[SensorManager.DATA_X]*MULTIPLIER), timestamp);
		}
		if (accelY!= null) {
			accelY.addValue((int)(event.values[SensorManager.DATA_Y]*MULTIPLIER), timestamp);
		}
		if (accelZ!= null) {
			accelZ.addValue((int)(event.values[SensorManager.DATA_Z]*MULTIPLIER), timestamp);
		}
		if (magnitude!= null) {
			magnitude.addValue((int)Math.floor(
					Math.sqrt(event.values[SensorManager.DATA_X]*event.values[SensorManager.DATA_X]+
							event.values[SensorManager.DATA_Y]*event.values[SensorManager.DATA_Y]+
							event.values[SensorManager.DATA_Z]*event.values[SensorManager.DATA_Z])
							*MULTIPLIER), timestamp);
		}
	}

	public void activateSensor() {
		mSensorManager = (SensorManager) InferrenceService.INSTANCE.getSystemService(Context.SENSOR_SERVICE);
		mSensorManager.registerListener(this,
				mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(Constants.ACCELEROMETER_LOCATION), //accel is 0 here, may change
				SensorManager.SENSOR_DELAY_FASTEST);

	}

	public void deactivateSensor() {
		if (mSensorManager != null) {
			mSensorManager.unregisterListener(this);
		}

	}

}


text:
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later
 * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
 */
package org.hibernate.query.sqm.tree.expression.domain;

import org.hibernate.persister.common.spi.Navigable;
import org.hibernate.query.sqm.NotYetImplementedException;
import org.hibernate.query.sqm.consume.spi.SemanticQueryWalker;
import org.hibernate.query.sqm.domain.SqmExpressableTypeEntity;
import org.hibernate.query.sqm.domain.type.SqmDomainTypeEntity;
import org.hibernate.query.sqm.tree.from.SqmFrom;

import org.jboss.logging.Logger;

/**
 * @author Steve Ebersole
 */
public class SqmCollectionElementReferenceEntity extends AbstractSqmCollectionElementReference implements
		SqmCollectionElementReference,
		SqmEntityTypedReference {
	private static final Logger log = Logger.getLogger( SqmCollectionElementReferenceEntity.class );

	private SqmFrom exportedFromElement;

	public SqmCollectionElementReferenceEntity(SqmPluralAttributeReference pluralAttributeBinding) {
		super( pluralAttributeBinding );
	}

	@Override
	public SqmExpressableTypeEntity getExpressionType() {
		return (SqmExpressableTypeEntity) getPluralAttributeBinding().getReferencedNavigable().getElementDescriptor();
	}

	@Override
	public SqmExpressableTypeEntity getInferableType() {
		return getExpressionType();
	}

	@Override
	public Navigable getReferencedNavigable() {
		return (SqmExpressableTypeEntity) super.getReferencedNavigable();
	}

	@Override
	public SqmDomainTypeEntity getExportedDomainType() {
		return (SqmDomainTypeEntity) super.getExportedDomainType();
	}

	@Override
	public SqmFrom getExportedFromElement() {
		return exportedFromElement;
	}

	@Override
	public void injectExportedFromElement(SqmFrom sqmFrom) {
		log.debugf(
				"Injecting SqmFrom [%s] into CollectionElementBindingEntity [%s], was [%s]",
				sqmFrom,
				this,
				this.exportedFromElement
		);
		exportedFromElement = sqmFrom;
	}

	@Override
	public <T> T accept(SemanticQueryWalker<T> walker) {
		throw new NotYetImplementedException(  );
	}
}


text:
#ifndef GEO_EARTH_ENTERPRISE_SRC_FUSION_RASTERFUSE_TILELOADER_H_
#define GEO_EARTH_ENTERPRISE_SRC_FUSION_RASTERFUSE_TILELOADER_H_

#include "common/khTileAddr.h"
#include "fusion/khraster/khOpacityMask.h"
#include "fusion/khraster/khRasterTile.h"

namespace fusion {
namespace rasterfuse {

// Status of Tile loading by RasterBlender/RasterMerger.
enum TileBlendStatus {
  NonBlended = 0,    // There was no blending/merging.
  Blended = 1,       // There was blending/merging, but all the tiles are
                     // covered with one of the insets of the project.
  NoDataBlended = 2  // There was merging and at least one, but not all of the
                     // source tiles is not covered by any source inset of the
                     // project.
};

template <class TileType>
class TileLoader {
 public:
  virtual ~TileLoader(void) { }

  // Fetches product and alpha tile.
  // @note will succeed or throw.
  // @param[in] addr tile address.
  // @param[out] data_tile fetched product tile.
  // @param[out] alpha_tile fetched alpha tile.
  // @param[out] blend_status status of tile loading.
  // @return tile opacity value.
  virtual khOpacityMask::OpacityType Load(
      const khTileAddr &addr,
      TileType *data_tile,
      AlphaProductTile *alpha_tile,
      TileBlendStatus *const blend_status) = 0;
};

}  // namespace rasterfuse
}  // namespace fusion

#endif  // GEO_EARTH_ENTERPRISE_SRC_FUSION_RASTERFUSE_TILELOADER_H_


text:
package org.springframework.boot.maven;

import java.io.File;

import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.contentOf;

/**
 * Integration tests for the Maven plugin's war support.
 *
 * @author Andy Wilkinson
 */
@ExtendWith(MavenBuildExtension.class)
class StartStopIntegrationTests {

	@TestTemplate
	void startStopWithForkDisabledWaitsForApplicationToBeReadyAndThenRequestsShutdown(MavenBuild mavenBuild) {
		mavenBuild.project("start-stop-fork-disabled").goals("verify").execute(
				(project) -> assertThat(buildLog(project)).contains("isReady: true").contains("Shutdown requested"));
	}

	@TestTemplate
	void startStopWaitsForApplicationToBeReadyAndThenRequestsShutdown(MavenBuild mavenBuild) {
		mavenBuild.project("start-stop").goals("verify").execute(
				(project) -> assertThat(buildLog(project)).contains("isReady: true").contains("Shutdown requested"));
	}

	@TestTemplate
	void whenSkipIsTrueStartAndStopAreSkipped(MavenBuild mavenBuild) {
		mavenBuild.project("start-stop-skip").goals("verify").execute((project) -> assertThat(buildLog(project))
				.doesNotContain("Ooops, I haz been run").doesNotContain("Stopping application"));
	}

	private String buildLog(File project) {
		return contentOf(new File(project, "target/build.log"));
	}

}


text:
package data

import(
    "fmt"

    "github.com/wardlem/graphlite/util"
)

// Error strings
const (
    labelCreationFailure = "could not create label"
    labelWrongDataSize = "wrong data size when creating label"
    nilLabel = "attempt to operate on a nil label"
)

const labelDataSize = 21    // this is the number of bytes a label takes up in the file

// A label is any text value that is expected to be reused throughout the graph.
// This can be an edge label, an attribute name, a class name, a map key, etc.
type Label struct {
    Id uint16    // the id of the label
    value uint64 // the id of the text object for the label
    refs uint64  // the number of objects that use this label
                 // when refs < 1, it is deleted upon writing
    l uint16  // the left node for binary (avl) searches
    r uint16 // the right node for binary (avl) searches
    h uint8 // keeps track of the height of the node for avl tree operations
}

// Creates an existing label from byte data.
// Panics if the length of the bytes does not match labelDataSize.
// Returns an error of type *DataError if there is a conversion error.
func constructLabel (id uint16, bytes []byte) (*Label, *DataError) {
    Assert(labelWrongDataSize, len(bytes) == labelDataSize)

    var e error

    l := new(Label)
    l.Id = id

    val := bytes[0:8]
    refs := bytes[8:16]
    left := bytes[16:18]
    right := bytes[18:20]
    height := bytes[20]

    l.value, e = util.BytesToUint64(val)
    if e != nil {
        return nil, dataError(labelCreationFailure, e, nil)
    }
    l.refs, e = util.BytesToUint64(refs)
    if e != nil {
        return nil, dataError(labelCreationFailure, e, nil)
    }
    if l.l, e = util.BytesToUint16(left); e != nil {
        return nil, dataError(labelCreationFailure, e, nil)
    }
    if l.r, e = util.BytesToUint16(right); e != nil {
        return nil, dataError(labelCreationFailure, e, nil)
    }
    l.h = height

    return l, nil
}

// Responsible for creating a new label.
// This method should only be called by the label store.
// The addLabel(value string) method of the label store should be called to create a label.
// This method panics if the graph is nil or the graph's text store is nil.
func newLabel(value string, g *Graph) *Label {
    Assert(nilGraph, g != nil)
    Assert(nilTextStore, g.textStore != nil)

    l := new(Label)
    t := newText(value)
    l.value = g.textStore.addText(t)

    return l
}

// Returns the string value of the label.
func (l *Label) Value(g *Graph) string {
    Assert(nilLabel, l != nil)
    Assert(nilGraph, g != nil)
    Assert(nilTextStore, g.textStore != nil)

    t, _ := g.textStore.find(l.value) // TODO don't ignore error
    return t.Value()
}

// Returns the byte representation of the label for storage.
func (l *Label) data() []byte {
    Assert(nilLabel, l != nil)

    bytes, _ := util.Uint64ToBytes(l.value)
    refs, _ := util.Uint64ToBytes(l.refs)
    left, _ := util.Uint16ToBytes(l.l)
    right, _ := util.Uint16ToBytes(l.r)

    bytes = append(bytes, append(refs, append(left, append(right, l.h)...)...)...) // TODO ??
    return bytes

}

// Returns the height of a label for binary search operations.
func (l *Label) height() int8 {
    if (l == nil) {
        return int8(-1)
    }
    return int8(l.h)
}

// Calculates and sets the height of a label.
// Returns true if the height is changed, or false if it has not.
func (l *Label) setHeight(g *Graph) bool {
    // keep track of whether or not the height has changed
    changed := false

    Assert (nilLabel, l != nil)
    Assert(nilGraph, g != nil)
    Assert(nilLabelStore, g.labelStore != nil)

    var newHeight uint8

    // get the heights of the right and left nodes
    left, _ := l.left(g) // TODO do not ignore this error
    right, _ := l.right(g) // TODO do not ignore this error

    lh := left.height()
    rh := right.height()

    // determine the new height
    if (lh < rh) {
        newHeight = uint8(1 + rh)
    } else {
        newHeight = uint8(1 + lh)
    }

    if int8(newHeight) != l.height() {
        changed = true
    }

    l.h = newHeight

    return changed
}

// Returns the right node for the label in the binary search tree.
func (l *Label) right(g *Graph) (*Label, *DataError) {
    Assert (nilLabel, l != nil)
    Assert(nilGraph, g != nil)
    Assert(nilLabelStore, g.labelStore != nil)

    return g.labelStore.findAllowZero(l.r)
}

// Returns the left node for the label in the binary search tree.
func (l *Label) left(g *Graph) (*Label, *DataError) {
    Assert(nilLabel, l != nil)
    Assert(nilGraph, g != nil)
    Assert(nilLabelStore, g.labelStore != nil)

    return g.labelStore.findAllowZero(l.l)
}

// Recursive function that adds a node to the binary search tree
func (currentLabel *Label) addNode(newLabel *Label, g *Graph) uint16 {
    Assert(nilGraph, g != nil)
    Assert(nilLabelStore, g.labelStore != nil)
    Assert(nilLabel, newLabel != nil)

    if currentLabel == nil {
        return newLabel.Id
    }

    currentVal := currentLabel.Value(g)
    newVal := newLabel.Value(g)

    if newVal < currentVal {
        ln, _ := currentLabel.left(g) // TODO do not ignore error
        l := ln.addNode(newLabel, g)
        if l != currentLabel.l {
            g.labelStore.writes[currentLabel.Id] = currentLabel
        }
        currentLabel.l = l
    } else {
        rn, _ := currentLabel.right(g) // TODO do not ignore error
        r := rn.addNode(newLabel, g)
        if r != currentLabel.r {
            g.labelStore.writes[currentLabel.Id] = currentLabel
        }
        currentLabel.r = r
    }

    currentLabel.setHeight(g)
    return currentLabel.balance(g)
}

// Updates the the structure of the label avl tree when removing a label.
func (currentLabel *Label) removeNode(removeLabel *Label, g *Graph) uint16 {
    Assert(nilGraph, g != nil)
    Assert(nilLabelStore, g.labelStore != nil)
    Assert(nilLabel, removeLabel != nil)

    // make sure we haven't reached the end of the road
    if (currentLabel == nil) {  // TODO should this cause an error?
        return uint16(0)
    }

    // this is the one we want
    if removeLabel.Id == currentLabel.Id {
        // remove this label
        cl, _ := currentLabel.left(g) // TODO do not ignore error
        cr, _ := currentLabel.right(g) // TODO do not ignore error

        if cl == nil && cr == nil { // no descendents
            return uint16(0)
        } else if cl == nil { // one descendent
            return cr.Id
        } else if cr == nil { // one descendent
            return cl.Id
        } else if cl.height() > cr.height() {
            // get the right most node of the left branch
            rLabel := cl.rightmostNode(g)
            rLabel.l = cl.removeNode(rLabel, g)
            rLabel.r = currentLabel.r
            g.labelStore.writes[rLabel.Id] = rLabel
            return rLabel.balance(g)
        } else {
            // get the left most node of the right branch
            lLabel := cr.leftmostNode(g)
            lLabel.r = cl.removeNode(lLabel, g)
            lLabel.l = currentLabel.l
            g.labelStore.writes[lLabel.Id] = lLabel
            return lLabel.balance(g)
        }

    // keep looking
    } else if removeLabel.Value(g) < currentLabel.Value(g) {
        left, _ := currentLabel.left(g) // TODO do not ignore error
        l := left.removeNode(removeLabel, g)
        if (l != currentLabel.l) {
            g.labelStore.writes[currentLabel.Id] = currentLabel
        }
        currentLabel.l = l
    } else {
        right, _ := currentLabel.right(g) // TODO do not ignore error
        r := right.removeNode(removeLabel, g)
        if (r != currentLabel.r) {
            g.labelStore.writes[currentLabel.Id] = currentLabel
        }
        currentLabel.r = r
    }

    return currentLabel.balance(g)

}

// Balances the avl tree.
func (l *Label) balance(g *Graph) uint16 {
    Assert(nilLabel, l != nil)
    Assert(nilGraph, g != nil)
    Assert(nilLabelStore, g.labelStore != nil)
    Assert(nilLabelWriteMap, g.labelStore.writes != nil)

    // set the height
    changed := l.setHeight(g)
    if changed {
        g.labelStore.writes[l.Id] = l
    }

    // get the current balance
    b := l.currentBalance(g)
    if b < -1 {
        // make sure we remember to write the changes
        g.labelStore.writes[l.Id] = l
        left, _ := l.left(g)    // TODO do not ignore error
        if left.currentBalance(g) > 0 {  // double rotation
            l.l = left.rotateLeft(g)
        }
        return l.rotateRight(g)
    } else if b > 1 {
        // make sure we remember to write the changes
        g.labelStore.writes[l.Id] = l
        right, _ := l.right(g) // TODO do not ignore error
        if right.currentBalance(g) < 0 { // double rotation
            l.r = right.rotateRight(g)
        }
        return l.rotateLeft(g)
    }

    return l.Id
}

// Returns the current balance of the label for avl operations.
func (l *Label) currentBalance(g *Graph) int {
    Assert(nilLabel, l != nil)
    Assert(nilGraph, g != nil)

    right, _ := l.right(g) // TODO do not ignore the error
    left, _ := l.left(g) // TODO do not ignore the error
    rh := right.height()
    lh := left.height()
    return int(rh) - int(lh)
}

// Rotates the label right to balance the label avl tree.
func (l *Label) rotateRight(g *Graph) uint16 {
    Assert(nilLabel, l != nil)
    Assert(nilGraph, g != nil)
    Assert(nilLabelStore, g.labelStore != nil)
    Assert(nilLabelWriteMap, g.labelStore.writes != nil)

    // perform the rotation
    left, _ := l.left(g) // TODO do not ignore error
    l.l = left.r
    left.r = l.Id

    l.setHeight(g)
    left.setHeight(g)

    // make sure the changes are written
    g.labelStore.writes[l.Id] = l
    g.labelStore.writes[left.Id] = left

    return left.Id
}

// Rotates the label left to balance the label avl tree
func (l *Label) rotateLeft(g *Graph) uint16 {
    Assert(nilLabel, l != nil)
    Assert(nilGraph, g != nil)
    Assert(nilLabelStore, g.labelStore != nil)
    Assert(nilLabelWriteMap, g.labelStore.writes != nil)

    // perform the rotation
    right, _ := l.right(g) // TODO do not ignore error
    l.r = right.l
    right.l = l.Id

    l.setHeight(g)
    right.setHeight(g)

    // make sure the changes are written
    g.labelStore.writes[l.Id] = l
    g.labelStore.writes[right.Id] = right

    return right.Id
}

// Recursive function that returns the leftmost node of a label
func (l *Label) leftmostNode(g *Graph) *Label {
    left, _ := l.left(g) // TODO do not ignore error
    if left == nil {
        return l
    }
    return left.leftmostNode(g)
}

// Recursive function that returns the rightmost node of a label
func (l *Label) rightmostNode(g *Graph) *Label {
    right, _ := l.right(g) // TODO do not ignore error
    if right == nil {
        return l
    }
    return right.rightmostNode(g)
}

func (l *Label) printTree(spaces string, side string, g *Graph) {
    if (l == nil) {
        fmt.Printf("%s(%s)<nil>\n", spaces, side)
    } else {
        fmt.Printf("%s(%s)%s: %d\n", spaces, side, l.Value(g), l.height())
        spaces += "  "
        left, _ := l.left(g)
        right, _ := l.right(g)
        left.printTree(spaces, "l", g)
        right.printTree(spaces, "r", g)
    }
}


text:
<?php

namespace Drupal\Core\EventSubscriber;

use Drupal\Core\Cache\CacheableRedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Redirects paths starting with multiple slashes to a single slash.
 */
class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {

  /**
   * Redirects paths starting with multiple slashes to a single slash.
   *
   * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event
   *   The RequestEvent to process.
   */
  public function redirect(RequestEvent $event) {
    $request = $event->getRequest();
    // Get the requested path minus the base path.
    $path = $request->getPathInfo();

    // It is impossible to create a link or a route to a path starting with
    // multiple leading slashes. However if a form is added to the 404 page that
    // submits back to the same URI this presents an open redirect
    // vulnerability. Also, Drupal 7 renders the same page for
    // http://www.example.org/foo and http://www.example.org////foo.
    if (strpos($path, '//') === 0) {
      $path = '/' . ltrim($path, '/');
      $qs = $request->getQueryString();
      if ($qs) {
        $qs = '?' . $qs;
      }
      $event->setResponse(new CacheableRedirectResponse($request->getUriForPath($path) . $qs));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect', 1000];
    return $events;
  }

}


text:
package test.net.hasor.rsf.client.async;
import net.hasor.core.setting.StandardContextSettings;
import net.hasor.rsf.RsfContext;
import net.hasor.rsf.plugins.monitor.QpsMonitor;
import test.net.hasor.rsf.customer._01_echo.RsfCustomer;
/**
 *
 * @version : 2014年9月12日
 * @author 赵永春(zyc@hasor.net)
 */
public class AsyncMain {
    public static void main(String[] args) throws Throwable {
        //
        //因为没有注册中心,由配置文件来代替。
        QpsMonitor qps = new QpsMonitor();
        StandardContextSettings setting = new StandardContextSettings("rsf-config.xml");
        setting.refresh();
        //获取准备启动的客户端数量
        final int clientCount = setting.getInteger("testConfig.clientCount");
        for (int chientID = 0; chientID < clientCount; chientID++) {
            final int id = chientID;
            final RsfContext rsfContext = RsfCustomer.build(qps, setting);
            new Thread() {
                public void run() {
                    new AsyncClient(id, rsfContext).syncRun();
                };
            }.start();
        }
        //
        while (true) {
            Thread.sleep(1000);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using Prometheus;
using tester;

namespace Benchmark.NetCore
{
    // NB! This benchmark requires the Tester project to be running and the MetricPusherTester module to be active (to receive the data).
    // If there is no tester listening, the results will be overly good because the runtime is under less I/O load.
    [MemoryDiagnoser]
    [SimpleJob(RunStrategy.Monitoring, warmupCount:0)]
    public class MetricPusherBenchmarks
    {
        private static string MetricPusherUrl = $"http://localhost:{TesterConstants.TesterPort}";

        [GlobalSetup]
        public async Task GlobalSetup()
        {
            // Verify that there is a MetricPusher listening on Tester.

            using (var client = new HttpClient())
            {
                try
                {
                    var result = await client.GetAsync(MetricPusherUrl);
                    result.EnsureSuccessStatusCode();
                }
                catch
                {
                    throw new Exception("You must start the Tester.NetCore project and configure it to use MetricPusherTester in its Program.cs before running this benchmark.");
                }
            }
        }

        [Benchmark]
        public async Task PushTest()
        {
            var registry = Metrics.NewCustomRegistry();
            var factory = Metrics.WithCustomRegistry(registry);

            var pusher = new MetricPusher(new MetricPusherOptions
            {
                Endpoint = MetricPusherUrl,
                Registry = registry,
                IntervalMilliseconds = 30,
                Job = "job"
            });
            pusher.Start();

            var counters = new List<Counter>();
            for (int i = 0; i < 1000; i++)
            {
                var counter = factory.CreateCounter($"Counter{i}", String.Empty);
                counters.Add(counter);
            }

            var ct = new CancellationTokenSource();
            var incTask = Task.Run(async () =>
            {
                while (!ct.IsCancellationRequested)
                {
                    foreach (var counter in counters)
                    {
                        counter.Inc();
                    }

                    await Task.Delay(30);
                }
            });

            await Task.Delay(5000);
            ct.Cancel();
            await incTask;

            pusher.Stop();
        }
    }
}


text:
require 'dp'

--[[command line arguments]]--
cmd = torch.CmdLine()
cmd:text()
cmd:text('Image Classification using MLP Training/Optimization')
cmd:text('Example:')
cmd:text('$> th neuralnetwork.lua --batchSize 128 --momentum 0.5')
cmd:text('Options:')
cmd:option('--learningRate', 0.1, 'learning rate at t=0')
cmd:option('--maxOutNorm', 1, 'max norm each layers output neuron weights')
cmd:option('--momentum', 0, 'momentum')
cmd:option('--nHidden', 200, 'number of hidden units')
cmd:option('--batchSize', 32, 'number of examples per batch')
cmd:option('--cuda', false, 'use CUDA')
cmd:option('--useDevice', 1, 'sets the device (GPU) to use')
cmd:option('--maxEpoch', 100, 'maximum number of epochs to run')
cmd:option('--maxTries', 30, 'maximum number of epochs to try to find a better local minima for early-stopping')
cmd:option('--dropout', false, 'apply dropout on hidden neurons, requires "nnx" luarock')
cmd:option('--dataset', 'Mnist', 'which dataset to use : Mnist | NotMnist | Cifar10 | Cifar100')
cmd:option('--standardize', false, 'apply Standardize preprocessing')
cmd:option('--zca', false, 'apply Zero-Component Analysis whitening')
cmd:option('--progress', false, 'display progress bar')
cmd:option('--silent', false, 'dont print anything to stdout')
cmd:text()
opt = cmd:parse(arg or {})
if not opt.silent then
   table.print(opt)
end

--[[preprocessing]]--
local input_preprocess = {}
if opt.standardize then
   table.insert(input_preprocess, dp.Standardize())
end
if opt.zca then
   table.insert(input_preprocess, dp.ZCA())
end

--[[data]]--
local datasource
if opt.dataset == 'Mnist' then
   datasource = dp.Mnist{input_preprocess = input_preprocess}
elseif opt.dataset == 'NotMnist' then
   datasource = dp.NotMnist{input_preprocess = input_preprocess}
elseif opt.dataset == 'Cifar10' then
   datasource = dp.Cifar10{input_preprocess = input_preprocess}
elseif opt.dataset == 'Cifar100' then
   datasource = dp.Cifar100{input_preprocess = input_preprocess}
else
    error("Unknown Dataset")
end

--[[Model]]--
local dropout
if opt.dropout then
   dropout = nn.Dropout()
end

mlp = dp.Sequential{
   models = {
      dp.Neural{
         input_size = datasource:featureSize(),
         output_size = opt.nHidden,
         transfer = nn.Tanh()
      },
      dp.Neural{
         input_size = opt.nHidden,
         output_size = #(datasource:classes()),
         transfer = nn.LogSoftMax(),
         dropout = dropout
      }
   }
}

--[[Propagators]]--
train = dp.Optimizer{
   loss = dp.NLL(),
   visitor = { -- the ordering here is important:
      dp.Momentum{momentum_factor = opt.momentum},
      dp.Learn{
         learning_rate = opt.learningRate,
         observer = dp.LearningRateSchedule{
            schedule = {[200]=0.01, [400]=0.001}
         }
      },
      dp.MaxNorm{max_out_norm = opt.maxOutNorm}
   },
   feedback = dp.Confusion(),
   sampler = dp.ShuffleSampler{batch_size = opt.batchSize},
   progress = opt.progress
}
valid = dp.Evaluator{
   loss = dp.NLL(),
   feedback = dp.Confusion(),
   sampler = dp.Sampler()
}
test = dp.Evaluator{
   loss = dp.NLL(),
   feedback = dp.Confusion(),
   sampler = dp.Sampler()
}

--[[Experiment]]--
xp = dp.Experiment{
   model = mlp,
   optimizer = train,
   validator = valid,
   tester = test,
   observer = {
      dp.FileLogger(),
      dp.EarlyStopper{
         error_report = {'validator','feedback','confusion','accuracy'},
         maximize = true,
         max_epochs = opt.maxTries
      }
   },
   random_seed = os.time(),
   max_epoch = opt.maxEpoch
}

--[[GPU or CPU]]--
if opt.cuda then
   require 'cutorch'
   require 'cunn'
   cutorch.setDevice(opt.useDevice)
   xp:cuda()
end

xp:verbose(not opt.silent)
if not opt.silent then
   print"dp.Models :"
   print(mlp)
   print"nn.Modules :"
   print(mlp:toModule(datasource:trainSet():sub(1,32)))
end

xp:run(datasource)


text:
Umfang
======
Diese Vorlage ist prinzipiell für alle Arbeiten auf der Fakultät Physik der Technische Universität Wien geeignet. Angelehnt ist die Titelseite an die Vorlage für Diplomarbeiten die vom Dekanat herausgegeben wurde. Speziell vorgesehen sind Seminararbeiten, Bachelorarbeiten, Projektarbeiten, Diplom- und Masterarbeiten sowie Dissertationen. Laut Auskunft des Dekants müssen auch Masterarbeiten den Titel "Diplomarbeit" tragen, deshalb liefern diese beiden Optionen das selbe Endergebnis.
Wenn diese Auswahl nicht reicht, kann man den Titel auch sehr leicht selbst definieren.

Verwendung
==========
Ich möchte allen wärmstens ans Herz legen [GIT] [1] zu verwenden, und das frei verfügbare [Buch] [2] dazu zu lesen. Für diejenigen denen dies zu aufwendig ist gibt auf der [Projekthomepage] [3] einen direkten Downloadlink.
Ein vollständiges Beispiel ist in abschlussarbeit.tex gegeben. Meine Empfehlung wäre dieses direkt als Skelett für die eigene Arbeit zu verwenden.
Beim erstellen der PDF nicht vergessen zuerst BibTex zu kompilieren und dann mindestens zwei mal PDFLatex. Eine etwas ausführlichere Beschreibung findet sich in der abschlussarbeit.pdf Datei.

Entwicklung
===========
Natürlich sind alle Änderungswünsche und Erweiterungen gerne gesehen und werden, sofern sinnvoll und gut, in das Projekt eingepflegt.
GIT Pull requests bzw. Einträge im [Bugtracker] [4] werden bevorzugt. Alternativ kann man mir auch eine Mail mit den Vorschlägen schicken, an joerg.herzinger@oiml.at

Sprache
=======
Laut Studienplan §9 muss jede Abschlussarbeit "Diplomarbeit" genannt werden, deshalb gibt es hier keine Unterscheidung bei den Sprachen. Man dürfte als "zweite Seite" eine englische Titelseite anlegen in der es dann "Diploma Thesis" heißen muss. (Auskunft des Dekanats)

ToDo
====
* ~~Vorlagen für Bacc- und Projektarbeiten, eventuell auch für Dissertationen.~~

Danksagung
==========
Besten Dank an Robert Hollenstein und im weiteren Manfred Menhart und Joachim Jeitler für die Vorlagen zu diesem Projekt.

[1]: http://git-scm.com/
[2]: http://git-scm.com/book
[3]: https://github.com/joerg/abschlussarbeit-tuwien-physik
[4]: https://github.com/joerg/abschlussarbeit-tuwien-physik/issues


text:
<?php

namespace ZfrOAuth2Test\Server\Entity;

use DateInterval;
use DateTime;
use ZfrOAuth2\Server\Entity\AccessToken;
use ZfrOAuth2\Server\Entity\Client;
use ZfrOAuth2\Server\Entity\Scope;

/**
 * @author  Michaël Gallego <mic.gallego@gmail.com>
 * @licence MIT
 * @covers \ZfrOAuth2\Server\Entity\AbstractToken
 * @covers \ZfrOAuth2\Server\Entity\AccessToken
 */
class AccessTokenTest extends \PHPUnit_Framework_TestCase
{
    public function testGettersAndSetters()
    {
        $owner     = $this->getMock('ZfrOAuth2\Server\Entity\TokenOwnerInterface');
        $client    = new Client();
        $expiresAt = new DateTime();

        $accessToken = new AccessToken();
        $accessToken->setToken('token');
        $accessToken->setScopes(['scope1', 'scope2']);
        $accessToken->setClient($client);
        $accessToken->setExpiresAt($expiresAt);
        $accessToken->setOwner($owner);

        $this->assertEquals('token', $accessToken->getToken());
        $this->assertCount(2, $accessToken->getScopes());
        $this->assertTrue($accessToken->matchScopes('scope1'));
        $this->assertFalse($accessToken->matchScopes('scope3'));
        $this->assertSame($client, $accessToken->getClient());
        $this->assertEquals($expiresAt, $accessToken->getExpiresAt());
        $this->assertSame($owner, $accessToken->getOwner());
    }

    public function testCanSetScopesFromString()
    {
        $scopes = 'foo bar';

        $accessToken = new AccessToken();
        $accessToken->setScopes($scopes);

        $this->assertCount(2, $accessToken->getScopes());
    }

    public function testCanSetScopesFromInstances()
    {
        $scope = new Scope();
        $scope->setName('bar');

        $accessToken = new AccessToken();
        $accessToken->setScopes([$scope]);

        $this->assertCount(1, $accessToken->getScopes());
    }

    public function testCalculateExpiresIn()
    {
        $expiresAt = new DateTime();
        $expiresAt->add(new DateInterval('PT60S'));

        $accessToken = new AccessToken();
        $accessToken->setExpiresAt($expiresAt);

        $this->assertFalse($accessToken->isExpired());
        $this->assertEquals(60, $accessToken->getExpiresIn());
    }

    public function testCanCheckIfATokenIsExpired()
    {
        $expiresAt = new DateTime();
        $expiresAt->sub(new DateInterval('PT60S'));

        $accessToken = new AccessToken();
        $accessToken->setExpiresAt($expiresAt);

        $this->assertTrue($accessToken->isExpired());
    }

    public function testSupportLongLiveToken()
    {
        $accessToken = new AccessToken();
        $this->assertFalse($accessToken->isExpired());
    }
}


text:
Work in progress on a d3js presentation.

## Building the presentation

1. Install [Pandoc](http://johnmacfarlane.net/pandoc/)
2. Clone [reveal.js](https://github.com/hakimel/reveal.js/) at the same level as this repo (i.e. ../reveal.js should be a legal path)
3. make

## Want to know more?

Contact [Richard](mailto:richard.clark@kaazing.com)


text:
import { Rainy } from "../../";

export = Rainy;


text:
layout: blog_full_layout
title: Week 7 XP1 (July 30-August 3):
category: xp
image: https://dl.dropboxusercontent.com/s/k6e5tfehthnzi6i/pastel2_Optim.jpg?dl=0
---

### Pastels
**Plein Air Pastel Drawing** Enjoy capturing the creative activity and varied scenery at CAMP 510. This active and nature-rich  setting provides an inspiring environment in which to develop individual creativity and drawing skills. The course will cover exercises in the use of pastels, color blending and composition and welcomes beginner and experienced pastel-users alike.
**_Artist: Judith Schoenbaum_**

**$470**

*12 spaces for CAMPers entering grades 5-8*


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="72dp"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_margin="4dp"
    android:paddingLeft="4dp"
    android:paddingBottom="4dp"
    >

    <TextView
        android:id="@+id/tv_setting_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="6dp"
        android:background="@drawable/text_view"
        android:text="头条"
        android:textColor="@color/colorAccent"
        android:textSize="20sp"/>
    <ImageView
        android:id="@+id/image_setting_item"
        android:layout_width="18dp"
        android:layout_height="18dp"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_cancel"/>

</RelativeLayout>


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Discussion — Boost.HigherOrderFunctions 0.6 documentation</title>

    <link rel="stylesheet" href="../../_static/boostbook.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Partial function evaluation" href="partialfunctions.html" />
    <link rel="prev" title="Configurations" href="configurations.html" />

Discussion¶

Partial function evaluation

FAQ

Q: Why is const required for the call operator on function objects?

Q: Is the reinterpret cast in BOOST_HOF_STATIC_LAMBDA undefined behaviour?

            © Copyright 2016, Paul Fultz II.

          Created using Sphinx 1.5.6.

Distributed under the Boost Software License, Version 1.0.
          (See accompanying file LICENSE_1_0.txt or copy at
          http://www.boost.org/LICENSE_1_0.txt)


text:
package uk.ac.kent.dover.fastGraph.editOperation;

import java.util.*;
import uk.ac.kent.dover.fastGraph.*;
import uk.ac.kent.dover.fastGraph.comparators.EditOperationComparator;
import uk.ac.kent.dover.fastGraph.graphSimilarity.ApproximateGEDBipartite;
import uk.ac.kent.dover.fastGraph.graphSimilarity.ApproximateGEDSimple;
import uk.ac.kent.dover.fastGraph.graphSimilarity.ExactGEDAStarIso;

/**
 *
 * @author Peter Rodgers
 *
 */
public class EditList {

	LinkedList<EditOperation> editList;
	double cost = 0.0;

	EditOperationComparator eoc = new EditOperationComparator();

	static final byte MARK = (byte)111;

	public static void main(String [] args) {
		Debugger.enabled = false;

		HashMap<Integer,Double> editCosts = new HashMap<>();
		editCosts.put(EditOperation.DELETE_NODE,1.0);
		editCosts.put(EditOperation.ADD_NODE,3.0);
		editCosts.put(EditOperation.DELETE_EDGE,5.0);
		editCosts.put(EditOperation.ADD_EDGE,7.0);
		editCosts.put(EditOperation.RELABEL_NODE,11.0);

		ArrayList<String> labels = new ArrayList<>();
		labels.add("blue");
		labels.add("black");
		labels.add("green");

		FastGraph g;
		try {

//int i=3;
			for(int i = 1; i < 200; i++) {

				long seed1 = System.currentTimeMillis()*i;
				long seed2 = System.currentTimeMillis()*i*999;
				long seed3 = System.currentTimeMillis()*i*3333;
				long seed4 = System.currentTimeMillis()*i*7777;
				long seed5 = System.currentTimeMillis()*i*111;

				System.out.println("i "+i+ " seed1: "+seed1+" seed2: "+seed2+" seed3: "+seed4+" seed3: "+seed4+" seed5: "+seed5);

//				seed1= 225674035693704L;
//				seed2= 225448361658010296L;

				boolean simple = false;

				g = FastGraph.randomGraphFactory(10, 15, seed1,simple, false);

				Random r = new Random(seed3);
				for(int n = 0; n < g.getNumberOfNodes(); n++) {
					String label = labels.get(r.nextInt(labels.size()));
					g = g.generateGraphByRelabellingNode(n, label);
				}

				EditList el = generateEditList(g,5,labels,editCosts, seed2);
//				System.out.println(el);

				FastGraph g2 = el.applyOperations(g);
				g2 = ExactIsomorphism.generateRandomIsomorphicGraph(g2, seed5, false);

//				ExactGEDAStarIso exactGED = new ExactGEDAStarIso(false,true,editCosts);
//				double exactSimilarity = exactGED.similarity(g, g2);
//				EditList el2 = exactGED.getEditList();

				ApproximateGEDSimple simpleGED = new ApproximateGEDSimple(false,true,editCosts,100, 0, seed4);
				double simpleSimilarity = simpleGED.similarity(g, g2);
				EditList el3 = simpleGED.getEditList();

				ApproximateGEDBipartite bipartiteGED = new ApproximateGEDBipartite(false,true,editCosts);
				double bipartiteSimilarity = bipartiteGED.similarity(g, g2);
				EditList el4 = bipartiteGED.getEditList();

//System.out.println(el.getCost()+" "+exactSimilarity+" "+simpleSimilarity);
//System.out.println("calc  : "+el.getEditList().get(0)+"\nexact : "+el2.getEditList().get(0)+"\nsimple: "+el3.getEditList().get(0));
//System.out.println("calc  : "+el.getEditList().get(1)+"\nexact : "+el2.getEditList().get(1)+"\nsimple: "+el3.getEditList().get(1));

System.out.println("original: "+el.getCost()+" simple: "+simpleSimilarity+" bipartite: "+bipartiteSimilarity);
//System.out.println("calc  : "+el.getEditList().get(0)+"\nsimple: "+el3.getEditList().get(0));
//System.out.println("calc  : "+el.getEditList().get(1)+"\nsimple: "+el3.getEditList().get(1));
//System.out.println("calc  : "+el.getEditList().get(2)+"\nsimple: "+el3.getEditList().get(2));
//System.out.println("calc  : "+el.getEditList().get(3)+"\nsimple: "+el3.getEditList().get(3));
//System.out.println("calc  : "+el.getEditList().get(4)+"\nsimple: "+el3.getEditList().get(4));

//				System.out.println(g2);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public EditList() {
		editList = new LinkedList<EditOperation>();
	}

	/**
	 * Makes a new list. The edit list is not shared, but the edit operations are.
	 * The expectation is that the list will have one element added at some point,
	 * hence the size of the list is slightly bigger than the length of the passed one.
	 *
	 * @param an existing list to copy.
	 */
	public EditList(EditList el) {
		editList = new LinkedList<EditOperation>(el.getEditList());
		cost = el.getCost();
	}

	/**
	 *
	 * @return the editList
	 */
	public List<EditOperation> getEditList() {
		return editList;
	}

 	/**
 	 * Find the total cost of the edit operations.
 	 * @return
 	 */
	public double getCost() {
		return cost;
	}

/**
 * Add a graph edit operation to the list
 *
 * @param eo edit operation to add to the end of the list.
 */
 	public void addOperation(EditOperation eo) {

		editList.add(eo);
		cost += eo.getCost();
	}

 	/**
 	 * Apply the list in sequence.
 	 *
 	 * @param g the graph to edit.
 	 * @return the new FastGraph, or null if any of the operation fail.
 	 */
 	public FastGraph applyOperations(FastGraph g) {

 		FastGraph ret = g;
 		for(EditOperation eo : editList) {
 			ret = eo.edit(ret);
 			if(ret == null) {
 				return null;
 			}
 		}

 		return ret;
 	}

 	/**
 	 *
 	 * @return returns only the delete node operations
 	 */
 	public List<EditOperation> findDeleteNodeOperations() {
 		LinkedList<EditOperation> ret = new LinkedList<>();

 		for(EditOperation eo : editList) {
 			if(eo.getOperationCode() == EditOperation.DELETE_NODE) {
 				ret.add(eo);
 			}
 		}

 		return ret;
 	}

 	/**
 	 *
 	 * @return returns only the add node operations
 	 */
 	public List<EditOperation> findAddNodeOperations() {
 		LinkedList<EditOperation> ret = new LinkedList<>();

 		for(EditOperation eo : editList) {
 			if(eo.getOperationCode() == EditOperation.ADD_NODE) {
 				ret.add(eo);
 			}
 		}

 		return ret;
 	}

 	/**
 	 *
 	 * @return returns only the delete edge operations
 	 */
 	public List<EditOperation> findDeleteEdgeOperations() {
 		LinkedList<EditOperation> ret = new LinkedList<>();

 		for(EditOperation eo : editList) {
 			if(eo.getOperationCode() == EditOperation.DELETE_EDGE) {
 				ret.add(eo);
 			}
 		}

 		return ret;
 	}

 	/**
 	 *
 	 * @return returns only the add edge operations
 	 */
 	public List<EditOperation> findAddEdgeOperations() {
 		LinkedList<EditOperation> ret = new LinkedList<>();

 		for(EditOperation eo : editList) {
 			if(eo.getOperationCode() == EditOperation.ADD_EDGE) {
 				ret.add(eo);
 			}
 		}

 		return ret;
 	}

 	/**
 	 *
 	 * @return returns only the relabel node operations
 	 */
 	public List<EditOperation> findRelabelNodeOperations() {
 		LinkedList<EditOperation> ret = new LinkedList<>();

 		for(EditOperation eo : editList) {
 			if(eo.getOperationCode() == EditOperation.RELABEL_NODE) {
 				ret.add(eo);
 			}
 		}

 		return ret;
 	}

 	/**
 	 * Sort the edit list by preferred operation order.
 	 */
	public void sort() {
		Collections.sort(editList,eoc);
	}

	/**
	 * @return the hashCode of the list
	 */
	@Override
	public int hashCode() {
    	return editList.hashCode();
	}

    /**
 	 * @param obj the object to compare.
     * @return equality of the lists
     */
   @Override
	public boolean equals(Object obj) {
    	if (!(obj instanceof EditList)) {
    		return false;
    	}
    	EditList el = (EditList) obj;
    	return editList.equals(el.editList);
	}

	/**
	 * @return a String output for debugging
	 */
	public String toString() {
		String ret = "";
		for(EditOperation eo : editList) {
			ret += eo.toString()+"\n";
		}
		return ret;
	}

	/**
	 *
	 * Generate a list of edit operations. Does not delete an added edge,
	 * does not delete a relabelled node, does not add a edge between two nodes that have an edge deleted.
	 * Either adds or deletes nodes, not both. The idea is to produce an edit list that is close as possible to the minimum needed
	 * to get to the new graph
	 *
	 * @param g the graph to apply edit operations on
	 * @param numberOfEdits length of edit list
	 * @param nodeLables is the list of possible, RELABEL_NODE labels, if null, RELABEL_NODE operation are not included
	 * @param editCost the cost of edit operations
	 * @param seed the random number generator seed, pass System.currentTimeMillis() if in doubt
	 * @return the edit list with the edit operations on g
	 */
	public static EditList generateEditList(FastGraph g, int numberOfEdits, ArrayList<String> nodeLabels, HashMap<Integer,Double> editCosts, long seed) {

		Double deleteNodeCost = editCosts.get(EditOperation.DELETE_NODE);
		Double addNodeCost = editCosts.get(EditOperation.ADD_NODE);
		Double deleteEdgeCost = editCosts.get(EditOperation.DELETE_EDGE);
		Double addEdgeCost = editCosts.get(EditOperation.ADD_EDGE);
		Double relabelNodeCost = editCosts.get(EditOperation.RELABEL_NODE);

		boolean addedNode = false;
		boolean deletedNode = false;

		EditList ret = new EditList();

		Random r = new Random(seed);

		EditOperation eo = null;

		FastGraph currentGraph = g;

		int markNodeId = -1;
		int markEdgeId = -1;

		while(ret.getEditList().size() < numberOfEdits) {
			int editCode = -1;
			if(nodeLabels != null) {
				editCode = r.nextInt(5); // include node relabelling
			} else {
				editCode = r.nextInt(4); // do not include node relabelling
			}

			if((editCode == 0 && !deletedNode) || currentGraph.getNumberOfNodes() == 0) { // try adding a node
				addedNode = true; // this fixes it so only node additions, no node deletions occur from now on
				String label = "new node";
				if(nodeLabels != null) {
					int index = r.nextInt(nodeLabels.size());
					label = nodeLabels.get(index);
				}
				eo = new EditOperation(EditOperation.ADD_NODE,addNodeCost,-1,label,-1,-1);
				markNodeId = currentGraph.getNumberOfNodes();

			}
			if(editCode == 1 && !addedNode) { // try deleting a node

				deletedNode = true; // even if we don't delete a node, this will fix it so no node additions occur, only node deletions
				int deleteIndex = r.nextInt(currentGraph.getNumberOfNodes());
				if(currentGraph.getNodeDegree(deleteIndex) > 0) {
					continue;
				}
				if(currentGraph.getNodeType(deleteIndex) == MARK) {
					continue;
				}
				eo = new EditOperation(EditOperation.DELETE_NODE,deleteNodeCost,deleteIndex,null,-1,-1);

			}
			if(editCode == 2) { // try adding an edge
				int n1 = r.nextInt(currentGraph.getNumberOfNodes());
				int n2 = r.nextInt(currentGraph.getNumberOfNodes());

				eo = new EditOperation(EditOperation.ADD_EDGE,addEdgeCost,-1,"added Edge",n1,n2);
				markEdgeId = currentGraph.getNumberOfEdges();

			}
			if(editCode == 3) { // try deleting an edge
				if(currentGraph.getNumberOfEdges() == 0) {
					continue;
				}
				int deleteIndex = r.nextInt(currentGraph.getNumberOfEdges());
				if(currentGraph.getEdgeType(deleteIndex) == MARK) {
					continue;
				}
				eo = new EditOperation(EditOperation.DELETE_EDGE,deleteEdgeCost,deleteIndex,null,-1,-1);
			}
			if(editCode == 4) { // try relabelling
				// find an label
				int index = r.nextInt(nodeLabels.size());
				String label = nodeLabels.get(index);

				// check for previous edit operations on the node
				int relabelIndex = r.nextInt(currentGraph.getNumberOfNodes());
				String currentLabel = currentGraph.getNodeLabel(relabelIndex);
				if(label.equals(currentLabel)) {
					continue;
				}
				if(currentGraph.getNodeType(relabelIndex) == MARK) {
					continue;
				}
				eo = new EditOperation(EditOperation.RELABEL_NODE,relabelNodeCost,relabelIndex,label,-1,-1);
				markNodeId = relabelIndex;
			}

			if(eo != null) {
				ret.addOperation(eo);
				currentGraph = eo.edit(currentGraph);
				if(markNodeId > 0 ) {
					currentGraph.setNodeType(markNodeId, MARK);
				}
				if(markEdgeId > 0 ) {
					currentGraph.setEdgeType(markEdgeId, MARK);
				}
				eo = null;
			}

			markNodeId = -1;
			markEdgeId = -1;

		}

		return ret;
	}

}


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Hygiea, (N. S. ) 2 (1), 357.

#### Original name
null

### Remarks
null


text:
import {isObject} from './../../helpers/object';
import {isDefined} from './../../helpers/mixed';

export const DIRECTIONS = {
  horizontal: 'horizontal',
  vertical: 'vertical'
};

/**
 * Get deltas array.
 *
 * @param {WalkontableCellCoords} start
 * @param {WalkontableCellCoords} end
 * @param {Array} data
 * @param {String} direction
 * @returns {Array}
 */
export function getDeltas(start, end, data, direction) {
  const rowsLength = data.length;
  const columnsLength = data ? data[0].length : 0;
  const deltas = [];
  const diffRow = end.row - start.row;
  const diffCol = end.col - start.col;

  if (['down', 'up'].indexOf(direction) !== -1) {
    const arr = [];

    for (let col = 0; col <= diffCol; col++) {
      let startValue = parseInt(data[0][col], 10);
      let endValue = parseInt(data[rowsLength - 1][col], 10);
      let delta = (direction === 'down' ? (endValue - startValue) : (startValue - endValue)) / (rowsLength - 1) || 0;

      arr.push(delta);
    }

    deltas.push(arr);
  }

  if (['right', 'left'].indexOf(direction) !== -1) {
    for (let row = 0; row <= diffRow; row++) {
      let startValue = parseInt(data[row][0], 10);
      let endValue = parseInt(data[row][columnsLength - 1], 10);
      let delta = (direction === 'right' ? (endValue - startValue) : (startValue - endValue)) / (columnsLength - 1) || 0;

      deltas.push([delta]);
    }
  }

  return deltas;
}

/**
 * Get direction between positions and cords of selections difference (drag area)
 *
 * @param {Array} startSelection
 * @param {Array} endSelection
 * @returns {{direction: String, start: WalkontableCellCoords, end: WalkontableCellCoords}}
 */
export function getDragDirectionAndRange(startSelection, endSelection) {
  let startOfDragCoords, endOfDragCoords, directionOfDrag;

  if (endSelection[0] === startSelection[0] && endSelection[1] < startSelection[1]) {
    directionOfDrag = 'left';

    startOfDragCoords = new WalkontableCellCoords(endSelection[0], endSelection[1]);
    endOfDragCoords = new WalkontableCellCoords(endSelection[2], startSelection[1] - 1);

  } else if (endSelection[0] === startSelection[0] && endSelection[3] > startSelection[3]) {
    directionOfDrag = 'right';

    startOfDragCoords = new WalkontableCellCoords(endSelection[0], startSelection[3] + 1);
    endOfDragCoords = new WalkontableCellCoords(endSelection[2], endSelection[3]);

  } else if (endSelection[0] < startSelection[0] && endSelection[1] === startSelection[1]) {
    directionOfDrag = 'up';

    startOfDragCoords = new WalkontableCellCoords(endSelection[0], endSelection[1]);
    endOfDragCoords = new WalkontableCellCoords(startSelection[0] - 1, endSelection[3]);

  } else if (endSelection[2] > startSelection[2] &&
    endSelection[1] === startSelection[1]) {
    directionOfDrag = 'down';

    startOfDragCoords = new WalkontableCellCoords(startSelection[2] + 1, endSelection[1]);
    endOfDragCoords = new WalkontableCellCoords(endSelection[2], endSelection[3]);
  }

  return {
    directionOfDrag,
    startOfDragCoords,
    endOfDragCoords
  };
}

/**
 * Get mapped FillHandle setting containing information about
 * allowed FillHandle directions and if allowed is automatic insertion of rows on drag
 *
 * @param {Boolean|Object} fillHandle property of Handsontable settings
 * @returns {{directions: Array, autoInsertRow: Boolean}} object allowing access to information
 * about FillHandle in more useful way
 */
export function getMappedFillHandleSetting(fillHandle) {
  const mappedSettings = {};

  if (fillHandle === true) {
    mappedSettings.directions = Object.keys(DIRECTIONS);
    mappedSettings.autoInsertRow = true;

  } else if (isObject(fillHandle)) {
    if (isDefined(fillHandle.autoInsertRow)) {

      // autoInsertRow for horizontal direction will be always false

      if (fillHandle.direction === DIRECTIONS.horizontal) {
        mappedSettings.autoInsertRow = false;

      } else {
        mappedSettings.autoInsertRow = fillHandle.autoInsertRow;
      }

    } else {
      mappedSettings.autoInsertRow = false;
    }

    if (isDefined(fillHandle.direction)) {
      mappedSettings.directions = [fillHandle.direction];

    } else {
      mappedSettings.directions = Object.keys(DIRECTIONS);
    }

  } else if (typeof fillHandle === 'string') {
    mappedSettings.directions = [fillHandle];
    mappedSettings.autoInsertRow = true;

  } else {
    mappedSettings.directions = [];
    mappedSettings.autoInsertRow = false;
  }

  return mappedSettings;
}


text:
<?php
namespace Cohesion\Environment;

use \Cohesion\Util\Input;
use \Cohesion\Structure\Factory\ServiceFactory;
use \Cohesion\Structure\Factory\RoutingFactory;
use \Cohesion\Structure\Factory\ViewFactory;

class HTTPEnvironment extends Environment {

    protected $supportedMimeTypes;

    const DEFAULT_FORMAT = 'html';

    public function __construct() {
        parent::__construct();

        if (!isset($_SESSION)) {
            session_start();
        }

        $this->input = new Input($_REQUEST ?: array());

        $global = $this->config->get('global');
        $this->supportedMimeTypes = $this->config->get('view.mime_types');

        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) {
            $global['protocol'] = 'https';
            $this->isSecure = true;
        } else {
            $global['protocol'] = 'http';
            $this->isSecure = false;
        }
        $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'] ? $_SERVER['SERVER_NAME'] : null);
        if ($domain) {
            $global['domain'] = $domain;
            $global['abs_base_url'] = "http://$domain";
            $global['ssl_base_url'] = "https://$domain";
            $global['base_url'] = $global['protocol'] . '://' . $domain;
        }

        $global['web_root'] = $_SERVER['DOCUMENT_ROOT'];
        $global['base_dir'] = dirname($global['web_root']);

        $global['uri'] = explode('?', $_SERVER['REQUEST_URI'])[0];

        $this->config->merge('global', $global);

        RoutingFactory::$config = $this->getConfig('routing');
        ViewFactory::$config = $this->getConfig('view');
    }

    public function getFormat() {
        $format = $this->input->get('format');
        if ($format && $this->config->get("view.formats.$format")) {
            return $format;
        }
        $accepts = $_SERVER['HTTP_ACCEPT'];
        if ($accepts) {
            $type = $this->getHighestSupportedValue($accepts, array_keys($this->supportedMimeTypes));
            if ($type) {
                return $this->supportedMimeTypes[$type]['format'];
            }
        }
        return static::DEFAULT_FORMAT;
    }

    /**
     * Not implemented yet.
     * TODO: Use the Accept-Language to get the language to use
     */
    public function getLanguage() {
        return parent::getLanguage();
    }

    /**
     * Returns the highest value found in the string that is within the supported array
     * For use with headers such as:
     * Accept: text/html,application/xhtml+xml,application/xml;q=0.9
     * Accept-Encoding: gzip,deflate,sdch
     * Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
     *
     * @param $str The header string to use
     * @param $supported an array of supported values
     * @return The supported value with the highest weighting or NULL if there are no matches
     */
    private function getHighestSupportedValue($str, $supported) {
        $accepts = explode(',', $str);
        $types = array();
        foreach ($accepts as $accept) {
            $tmp = explode(';', trim($accept));
            $q = 1;
            if (count($tmp) > 1) {
                if (preg_match('/q=(\d+(?:\.\d+)?)/', $tmp[1], $matches)) {
                    $q = $matches[1];
                }
            }
            if ($q > 0) {
                $types[strtolower(trim($tmp[0]))] = $q;
            }
        }
        arsort($types);
        foreach ($types as $type => $q) {
            if (in_array($type, $supported)) {
                return $type;
            }
        }
        return null;
    }
}


text:
package com.github.javaparser.symbolsolver.resolution;

import com.github.javaparser.ParseException;
import com.github.javaparser.symbolsolver.AbstractTest;
import com.github.javaparser.symbolsolver.SourceFileInfoExtractor;
import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade;
import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
import org.junit.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

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

public class AnalyseJavaParserTest extends AbstractTest {

    private static final File src = adaptPath(new File("src/test/resources/javaparser_src/proper_source"));

    private SourceFileInfoExtractor getSourceFileInfoExtractor() {
        CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver();
        combinedTypeSolver.add(new ReflectionTypeSolver());
        combinedTypeSolver.add(new JavaParserTypeSolver(src));
        combinedTypeSolver.add(new JavaParserTypeSolver(adaptPath(new File("src/test/resources/javaparser_src/generated"))));
        SourceFileInfoExtractor sourceFileInfoExtractor = new SourceFileInfoExtractor();
        sourceFileInfoExtractor.setTypeSolver(combinedTypeSolver);
        sourceFileInfoExtractor.setPrintFileName(false);
        return sourceFileInfoExtractor;
    }

    static String readFile(File file)
            throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
        return new String(encoded, StandardCharsets.UTF_8);
    }

    private static final boolean DEBUG = true;

    private void parse(String fileName) throws IOException, ParseException {
        File sourceFile = new File(src.getAbsolutePath() + "/" + fileName + ".java");
        SourceFileInfoExtractor sourceFileInfoExtractor = getSourceFileInfoExtractor();
        OutputStream outErrStream = new ByteArrayOutputStream();
        PrintStream outErr = new PrintStream(outErrStream);

        sourceFileInfoExtractor.setOut(outErr);
        sourceFileInfoExtractor.setErr(outErr);
        sourceFileInfoExtractor.solve(sourceFile);
        String output = outErrStream.toString();

        String path = "src/test/resources/javaparser_expected_output/" + fileName.replaceAll("/", "_") + ".txt";
        File dstFile = adaptPath(new File(path));

        if (DEBUG && (sourceFileInfoExtractor.getKo() != 0 || sourceFileInfoExtractor.getUnsupported() != 0)) {
            System.err.println(output);
        }

        assertTrue("No failures expected when analyzing " + path, 0 == sourceFileInfoExtractor.getKo());
        assertTrue("No UnsupportedOperationException expected when analyzing " + path, 0 == sourceFileInfoExtractor.getUnsupported());

        String expected = readFile(dstFile);

        String[] outputLines = output.split("\n");
        String[] expectedLines = expected.split("\n");

        for (int i = 0; i < Math.min(outputLines.length, expectedLines.length); i++) {
            assertEquals("Line " + (i + 1) + " of " + path + " is different from what is expected", expectedLines[i].trim(), outputLines[i].trim());
        }

        assertEquals(expectedLines.length, outputLines.length);

        JavaParserFacade.clearInstances();

        // If we need to update the file uncomment these lines
        //PrintWriter writer = new PrintWriter(dstFile.getAbsoluteFile(), "UTF-8");
        //writer.print(output);
        //writer.close();
    }

    @Test
    public void parsePositionUtils() throws IOException, ParseException {
        parse("com/github/javaparser/PositionUtils");
    }

    @Test
    public void parseJavaParser() throws IOException, ParseException {
        parse("com/github/javaparser/JavaParser");
    }

    @Test
    public void parseStatement() throws IOException, ParseException {
        parse("com/github/javaparser/ast/stmt/Statement");
    }

    @Test
    public void parseCatchClause() throws IOException, ParseException {
        parse("com/github/javaparser/ast/stmt/CatchClause");
    }

    @Test
    public void parseStatements() throws IOException, ParseException {
        parse("com/github/javaparser/ast/stmt/LabeledStmt");
        parse("com/github/javaparser/ast/stmt/BreakStmt");
        parse("com/github/javaparser/ast/stmt/ReturnStmt");
        parse("com/github/javaparser/ast/stmt/DoStmt");
        parse("com/github/javaparser/ast/stmt/AssertStmt");
        parse("com/github/javaparser/ast/stmt/ContinueStmt");
        parse("com/github/javaparser/ast/stmt/BlockStmt");
        parse("com/github/javaparser/ast/stmt/ExplicitConstructorInvocationStmt");
        parse("com/github/javaparser/ast/stmt/ExpressionStmt");
        parse("com/github/javaparser/ast/stmt/EmptyStmt");
        parse("com/github/javaparser/ast/stmt/SwitchStmt");
        parse("com/github/javaparser/ast/stmt/IfStmt");
        parse("com/github/javaparser/ast/stmt/SwitchEntryStmt");
        parse("com/github/javaparser/ast/stmt/SynchronizedStmt");
        parse("com/github/javaparser/ast/stmt/ForeachStmt");
        parse("com/github/javaparser/ast/stmt/ForStmt");
        parse("com/github/javaparser/ast/stmt/WhileStmt");
        parse("com/github/javaparser/ast/stmt/ThrowStmt");
        parse("com/github/javaparser/ast/stmt/TryStmt");
        parse("com/github/javaparser/ast/stmt/TypeDeclarationStmt");
    }

    @Test
    public void parseExpressions() throws IOException, ParseException {
        parse("com/github/javaparser/ast/expr/NameExpr");
        parse("com/github/javaparser/ast/expr/FieldAccessExpr");
        parse("com/github/javaparser/ast/expr/CharLiteralExpr");
        parse("com/github/javaparser/ast/expr/IntegerLiteralMinValueExpr");
        parse("com/github/javaparser/ast/expr/IntegerLiteralExpr");
        parse("com/github/javaparser/ast/expr/ArrayCreationExpr");
        parse("com/github/javaparser/ast/expr/VariableDeclarationExpr");
        parse("com/github/javaparser/ast/expr/SuperExpr");
        parse("com/github/javaparser/ast/expr/ArrayInitializerExpr");
        parse("com/github/javaparser/ast/expr/EnclosedExpr");
        parse("com/github/javaparser/ast/expr/Expression");
        parse("com/github/javaparser/ast/expr/SingleMemberAnnotationExpr");
        parse("com/github/javaparser/ast/expr/MethodReferenceExpr");
        parse("com/github/javaparser/ast/expr/ThisExpr");
        parse("com/github/javaparser/ast/expr/LiteralExpr");
        parse("com/github/javaparser/ast/expr/AnnotationExpr");
        parse("com/github/javaparser/ast/expr/InstanceOfExpr");
        parse("com/github/javaparser/ast/expr/LongLiteralExpr");
        parse("com/github/javaparser/ast/expr/StringLiteralExpr");
        parse("com/github/javaparser/ast/expr/NullLiteralExpr");
        parse("com/github/javaparser/ast/expr/ObjectCreationExpr");
        parse("com/github/javaparser/ast/expr/TypeExpr");
        parse("com/github/javaparser/ast/expr/DoubleLiteralExpr");
        parse("com/github/javaparser/ast/expr/LongLiteralMinValueExpr");
        parse("com/github/javaparser/ast/expr/MarkerAnnotationExpr");
        parse("com/github/javaparser/ast/expr/LambdaExpr");
        parse("com/github/javaparser/ast/expr/AssignExpr");
        parse("com/github/javaparser/ast/expr/NormalAnnotationExpr");
        parse("com/github/javaparser/ast/expr/QualifiedNameExpr");
        parse("com/github/javaparser/ast/expr/MemberValuePair");
        parse("com/github/javaparser/ast/expr/ArrayAccessExpr");
        parse("com/github/javaparser/ast/expr/ClassExpr");
        parse("com/github/javaparser/ast/expr/MethodCallExpr");
        parse("com/github/javaparser/ast/expr/ConditionalExpr");
        parse("com/github/javaparser/ast/expr/CastExpr");
        parse("com/github/javaparser/ast/expr/BooleanLiteralExpr");
        parse("com/github/javaparser/ast/expr/BinaryExpr");
        parse("com/github/javaparser/ast/expr/UnaryExpr");
    }

    @Test
    public void parseTypes() throws IOException, ParseException {
        parse("com/github/javaparser/ast/type/ClassOrInterfaceType");
        parse("com/github/javaparser/ast/type/PrimitiveType");
        parse("com/github/javaparser/ast/type/WildcardType");
        parse("com/github/javaparser/ast/type/UnknownType");
        parse("com/github/javaparser/ast/type/ReferenceType");
        parse("com/github/javaparser/ast/type/VoidType");
        parse("com/github/javaparser/ast/type/Type");
    }

    @Test
    public void parseVisitors() throws IOException, ParseException {
        parse("com/github/javaparser/ast/visitor/EqualsVisitor");
        parse("com/github/javaparser/ast/visitor/ModifierVisitorAdapter");
        parse("com/github/javaparser/ast/visitor/DumpVisitor");
        parse("com/github/javaparser/ast/visitor/VoidVisitor");
        parse("com/github/javaparser/ast/visitor/GenericVisitor");
        parse("com/github/javaparser/ast/visitor/VoidVisitorAdapter");
        parse("com/github/javaparser/ast/visitor/GenericVisitorAdapter");
    }

    @Test
    public void parseCloneVisitor() throws IOException, ParseException {
        parse("com/github/javaparser/ast/visitor/CloneVisitor");
    }

    @Test
    public void parseSourcesHelper() throws IOException, ParseException {
        parse("com/github/javaparser/SourcesHelper");
    }

    @Test
    public void parseComments() throws IOException, ParseException {
        parse("com/github/javaparser/ast/comments/LineComment");
        parse("com/github/javaparser/ast/comments/Comment");
        parse("com/github/javaparser/ast/comments/CommentsParser");
        parse("com/github/javaparser/ast/comments/JavadocComment");
        parse("com/github/javaparser/ast/comments/BlockComment");
        parse("com/github/javaparser/ast/comments/CommentsCollection");
    }

    @Test
    public void parseTheRest() throws IOException, ParseException {
        parse("com/github/javaparser/ast/internal/Utils");
        parse("com/github/javaparser/ast/body/AnnotationMemberDeclaration");
        parse("com/github/javaparser/ast/body/EnumDeclaration");
        parse("com/github/javaparser/ast/body/Parameter");
        parse("com/github/javaparser/ast/body/EnumConstantDeclaration");
        parse("com/github/javaparser/ast/body/VariableDeclarator");
        parse("com/github/javaparser/ast/body/TypeDeclaration");
        parse("com/github/javaparser/ast/body/EmptyMemberDeclaration");
        parse("com/github/javaparser/ast/body/ModifierSet");
        parse("com/github/javaparser/ast/body/VariableDeclaratorId");
        parse("com/github/javaparser/ast/body/BaseParameter");
        parse("com/github/javaparser/ast/body/AnnotableNode");
        parse("com/github/javaparser/ast/body/AnnotationDeclaration");
        parse("com/github/javaparser/ast/body/MethodDeclaration");
        parse("com/github/javaparser/ast/body/EmptyTypeDeclaration");
        parse("com/github/javaparser/ast/body/InitializerDeclaration");
        parse("com/github/javaparser/ast/body/BodyDeclaration");
        parse("com/github/javaparser/ast/body/FieldDeclaration");
        parse("com/github/javaparser/ast/body/ConstructorDeclaration");
        parse("com/github/javaparser/ast/body/WithDeclaration");
        parse("com/github/javaparser/ast/body/MultiTypeParameter");
        parse("com/github/javaparser/ast/body/ClassOrInterfaceDeclaration");
        parse("com/github/javaparser/ast/TreeVisitor");
        parse("com/github/javaparser/ast/PackageDeclaration");
        parse("com/github/javaparser/ast/DocumentableNode");
        parse("com/github/javaparser/ast/NamedNode");
        parse("com/github/javaparser/ast/Node");
        parse("com/github/javaparser/ast/AccessSpecifier");
        parse("com/github/javaparser/ast/CompilationUnit");
        parse("com/github/javaparser/ast/TypeParameter");
        parse("com/github/javaparser/ast/ImportDeclaration");
        parse("com/github/javaparser/Position");
        parse("com/github/javaparser/ASTHelper");
    }

}


text:
var Playback = require('../../base/playback')
var JST = require('../../base/jst')
var Styler = require('../../base/styler')
var Events = require('../../base/events')
var requestAnimationFrame = require('../../base/utils').requestAnimationFrame
var cancelAnimationFrame = require('../../base/utils').cancelAnimationFrame

class NoOp extends Playback {
  get name() { return 'no_op' }
  get template() { return JST.no_op }
  get attributes() {
    return {'data-no-op': ''}
  }

  constructor(options) {
    super(options);
  }

  render() {
    var style = Styler.getStyleFor(this.name);
    this.$el.html(this.template())
    this.$el.append(style);
    this.animate()
    this.trigger(Events.PLAYBACK_READY, this.name)
    return this
  }

  noise() {
    var idata = this.context.createImageData(this.context.canvas.width, this.context.canvas.height)
    var buffer32 = new Uint32Array(idata.data.buffer)
    var len = buffer32.length
    var run = 0
    var color = 0
    var m = Math.random() * 6 + 4

    for (var i = 0; i < len;) {
      if (run < 0) {
        run = m * Math.random();
        var p = Math.pow(Math.random(), 0.4);
        color = (255 * p) << 24;
      }
      run -= 1;
      buffer32[i++] = color;
    }
    this.context.putImageData(idata, 0, 0);
  }

  loop() {
    this.noise()
    requestAnimationFrame(() => this.loop())
  }

  animate() {
    this.canvas = this.$el.find('canvas[data-no-op-canvas]')[0]
    this.context = this.canvas.getContext('2d')
    this.loop()
  }
}

NoOp.canPlay = (source) => {
  return true
}

module.exports = NoOp


text:
import { Aggregations } from "app/Components/ArtworkFilter/ArtworkFilterHelpers"
import {
  SavedSearchEntityArtist,
  SearchCriteria,
  SearchCriteriaAttributes,
} from "app/Components/ArtworkFilter/SavedSearch/types"
import {
  extractArtistPills,
  extractPillFromAggregation,
  extractPillsFromCriteria,
  extractSizeLabel,
} from "./pillExtractors"

describe("extractPillFromAggregation", () => {
  it("returns pills", () => {
    const result = extractPillFromAggregation(
      SearchCriteria.materialsTerms,
      ["acrylic", "canvas"],
      aggregations
    )

    const pills = [
      { label: "Acrylic", value: "acrylic", paramName: SearchCriteria.materialsTerms },
      { label: "Canvas", value: "canvas", paramName: SearchCriteria.materialsTerms },
    ]

    expect(result).toEqual(pills)
  })

  it("returns undefined for unknown param values", () => {
    const result = extractPillFromAggregation(
      SearchCriteria.materialsTerms,
      ["acrylic", "canvas", "unknown-value"],
      aggregations
    )

    const pills = [
      { label: "Acrylic", value: "acrylic", paramName: SearchCriteria.materialsTerms },
      { label: "Canvas", value: "canvas", paramName: SearchCriteria.materialsTerms },
      undefined,
    ]

    expect(result).toEqual(pills)
  })

  it("returns empty array when couldn't get aggregation by param name", () => {
    const result = extractPillFromAggregation(
      SearchCriteria.materialsTerms,
      ["acrylic", "canvas", "unknown-value"],
      []
    )

    expect(result).toEqual([])
  })
})

describe("extractSizeLabel", () => {
  it("returns correcly label when full range is specified", () => {
    expect(extractSizeLabel({ prefix: "w", value: "5-10", unit: "in" })).toBe("w: 5-10 in")
    expect(extractSizeLabel({ prefix: "w", value: "5-10", unit: "cm" })).toBe("w: 12.7-25.4 cm")
  })

  it("returns correcly label when only min value is specified", () => {
    expect(extractSizeLabel({ prefix: "w", value: "5-*", unit: "in" })).toBe("w: from 5 in")
    expect(extractSizeLabel({ prefix: "w", value: "5-*", unit: "cm" })).toBe("w: from 12.7 cm")
  })

  it("returns correcly label when only max value is specified", () => {
    expect(extractSizeLabel({ prefix: "w", value: "*-10", unit: "in" })).toBe("w: to 10 in")
    expect(extractSizeLabel({ prefix: "w", value: "*-10", unit: "cm" })).toBe("w: to 25.4 cm")
  })

  it("returns specified prefix", () => {
    expect(extractSizeLabel({ prefix: "h", value: "5-10", unit: "in" })).toBe("h: 5-10 in")
    expect(extractSizeLabel({ prefix: "h", value: "5-10", unit: "cm" })).toBe("h: 12.7-25.4 cm")
  })
})

describe("extractPillsFromCriteria", () => {
  it("should correctly extract pills", () => {
    const attributes: SearchCriteriaAttributes = {
      materialsTerms: ["acrylic", "canvas"],
      priceRange: "5000-10000",
      attributionClass: ["limited edition", "open edition"],
      offerable: true,
      width: "5-10",
      height: "15-*",
      colors: ["unknown-color"],
    }

    const result = extractPillsFromCriteria({ attributes, aggregations, unit: "in" })

    const pills = [
      {
        label: "Acrylic",
        paramName: SearchCriteria.materialsTerms,
        value: "acrylic",
      },
      {
        label: "Canvas",
        paramName: SearchCriteria.materialsTerms,
        value: "canvas",
      },
      {
        label: "$5,000–10,000",
        value: "5000-10000",
        paramName: SearchCriteria.priceRange,
      },
      {
        paramName: SearchCriteria.attributionClass,
        label: "Limited Edition",
        value: "limited edition",
      },
      {
        paramName: SearchCriteria.attributionClass,
        label: "Open Edition",
        value: "open edition",
      },
      {
        label: "Make Offer",
        value: true,
        paramName: SearchCriteria.offerable,
      },
      {
        label: "w: 5-10 in",
        value: "5-10",
        paramName: SearchCriteria.width,
      },
      {
        label: "h: from 15 in",
        value: "15-*",
        paramName: SearchCriteria.height,
      },
    ]

    expect(result).toEqual(pills)
  })

  it("should correctly extract ways to buy pills", () => {
    const attributes: SearchCriteriaAttributes = {
      offerable: true,
      atAuction: true,
    }
    const result = extractPillsFromCriteria({ attributes, aggregations, unit: "in" })

    const pills = [
      {
        label: "Make Offer",
        value: true,
        paramName: SearchCriteria.offerable,
      },
      {
        label: "Bid",
        value: true,
        paramName: SearchCriteria.atAuction,
      },
    ]

    expect(result).toEqual(pills)
  })

  it("should correctly extract size pills", () => {
    const attributes: SearchCriteriaAttributes = {
      sizes: ["SMALL", "LARGE"],
    }

    // with unit inches
    const inResult = extractPillsFromCriteria({ attributes, aggregations, unit: "in" })

    expect(inResult).toEqual([
      {
        label: "Small (under 16in)",
        paramName: SearchCriteria.sizes,
        value: "SMALL",
      },
      {
        label: "Large (over 40in)",
        paramName: SearchCriteria.sizes,
        value: "LARGE",
      },
    ])

    // with unit centimeters
    const cmResult = extractPillsFromCriteria({ attributes, aggregations, unit: "cm" })

    expect(cmResult).toEqual([
      {
        label: "Small (under 40cm)",
        paramName: SearchCriteria.sizes,
        value: "SMALL",
      },
      {
        label: "Large (over 100cm)",
        paramName: SearchCriteria.sizes,
        value: "LARGE",
      },
    ])
  })

  it("should correctly extract time period pills", () => {
    const attributes: SearchCriteriaAttributes = {
      majorPeriods: ["2020", "2010"],
    }
    const result = extractPillsFromCriteria({ attributes, aggregations, unit: "in" })

    expect(result).toEqual([
      {
        label: "2020–Today",
        paramName: SearchCriteria.majorPeriods,
        value: "2020",
      },
      {
        label: "2010–2019",
        paramName: SearchCriteria.majorPeriods,
        value: "2010",
      },
    ])
  })

  it("should correctly extract color pills", () => {
    const attributes: SearchCriteriaAttributes = {
      colors: ["pink", "orange"],
    }
    const result = extractPillsFromCriteria({ attributes, aggregations, unit: "in" })

    expect(result).toEqual([
      {
        label: "Pink",
        paramName: SearchCriteria.colors,
        value: "pink",
      },
      {
        label: "Orange",
        paramName: SearchCriteria.colors,
        value: "orange",
      },
    ])
  })

  it("should correctly extract attribution pills", () => {
    const attributes: SearchCriteriaAttributes = {
      attributionClass: ["unique", "unknown edition"],
    }
    const result = extractPillsFromCriteria({ attributes, aggregations, unit: "in" })

    expect(result).toEqual([
      {
        label: "Unique",
        paramName: SearchCriteria.attributionClass,
        value: "unique",
      },
      {
        label: "Unknown Edition",
        paramName: SearchCriteria.attributionClass,
        value: "unknown edition",
      },
    ])
  })

  it("should correctly extract custom price range pill", () => {
    const attributes: SearchCriteriaAttributes = {
      priceRange: "1000-1500",
    }
    const result = extractPillsFromCriteria({ attributes, aggregations, unit: "in" })

    expect(result).toEqual([
      {
        label: "$1,000–1,500",
        paramName: SearchCriteria.priceRange,
        value: "1000-1500",
      },
    ])
  })
})

describe("artistPills", () => {
  it("should return empty array", () => {
    const result = extractArtistPills([])

    expect(result).toEqual([])
  })

  it("should correctly extract single artist", () => {
    const result = extractArtistPills([firstArtist])

    expect(result).toEqual([
      {
        label: "firstArtistName",
        value: "firstArtistId",
        paramName: SearchCriteria.artistID,
      },
    ])
  })

  it("should correctly extract single artist", () => {
    const result = extractArtistPills([firstArtist, secondArtist])

    expect(result).toEqual([
      {
        label: "firstArtistName",
        value: "firstArtistId",
        paramName: SearchCriteria.artistID,
      },
      {
        label: "secondArtistName",
        value: "secondArtistId",
        paramName: SearchCriteria.artistID,
      },
    ])
  })
})

const firstArtist: SavedSearchEntityArtist = {
  id: "firstArtistId",
  name: "firstArtistName",
}

const secondArtist: SavedSearchEntityArtist = {
  id: "secondArtistId",
  name: "secondArtistName",
}

const aggregations: Aggregations = [
  {
    slice: "MATERIALS_TERMS",
    counts: [
      {
        count: 44,
        name: "Acrylic",
        value: "acrylic",
      },
      {
        count: 30,
        name: "Canvas",
        value: "canvas",
      },
      {
        count: 26,
        name: "Metal",
        value: "metal",
      },
    ],
  },
]


text:
<?php

namespace Lemon\RestBundle\Serializer;

use JMS\Serializer\DeserializationContext as BaseDeserializationContext;

class DeserializationContext extends BaseDeserializationContext
{
    protected $useDoctrineConstructor = false;

    public function useDoctrineConstructor()
    {
        $this->useDoctrineConstructor = true;
    }

    public function shouldUseDoctrineConstructor()
    {
        return $this->useDoctrineConstructor;
    }
}


text:
<?php

namespace Distill\Exception;

class FormatGuesserRequiredException extends \Exception implements ExceptionInterface
{
    /**
     * Constructor
     * @param int        $code     Exception code
     * @param \Exception $previous Previous exception
     */
    public function __construct($code = 0, \Exception $previous = null)
    {
        parent::__construct('Format guesser required', $code, $previous);
    }
}


text:
package com.gizmoideas.mobile.memap.activity;

import com.gizmoideas.mobile.memap.R;
import com.gizmoideas.mobile.memap.service.PositionReceiver;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class LoginActivity extends Activity {

	PositionReceiver position;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		//super.registerReceiver(receiver, new IntentFilter("com.gizmoideas.mobile.memap"));
		//Intent intent = new Intent(this, BackgroundPosition.class);
		//super.startService(intent);
		//position.setPosition(this);
		position  = new PositionReceiver(this);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/*private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundel=intent.getExtras();
			textView.setText(bundel.getString(BackgroundPosition.latitude));
			textView.setText(bundel.getString(BackgroundPosition.longitude));

		}

	  };*/

	public void openMap(View view){

		Intent intent = new Intent(this,MyMapActivity.class);
		startActivity(intent);
	}

	public void openNotesList(View view){

		Intent intent = new Intent(this,NoteListActivity.class);
		startActivity(intent);
	}

}


text:
def key_exists?(path_reg)
  begin
    Win32::Registry::HKEY_LOCAL_MACHINE.open(path_reg, ::Win32::Registry::KEY_READ | 0x100 )
    return true
  rescue
    return false
  end
end

def readkey(path_reg,value)
  begin
    mykey = Win32::Registry.open(Win32::Registry::HKEY_LOCAL_MACHINE,path_reg,Win32::Registry::Constants::KEY_READ | 0x100)
    return mykey[value]
  rescue
    return false
  end
end

Facter.add(:cic_configured) do
  confine :osfamily => "Windows"
  setcode do
    require 'win32/registry'

    if key_exists?('SOFTWARE\Wow6432Node\Interactive Intelligence\Setup Assistant')
      complete = readkey('SOFTWARE\Wow6432Node\Interactive Intelligence\Setup Assistant', 'Complete')
    end

    cic_configured = complete == 0x00000001
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

	<title>dojo.window.getBox() test</title>

dojo.window.getBox() test

padding div

		<button onclick="addText(); compute();">add text and compute size</button>
		<button onclick="compute();">recompute size</button>

check results div below to see that before adding text, document is smaller than viewport

after adding text, document should be bigger than viewport,and check that viewport size hasn't changed,
				except maybe being a little bit smaller (about 15px) because of the size of the scrollbars

resize browser window and click the "recompute size" button; reported viewport size should change

scroll the window and click "recompute size" to see that the scroll position is taken into effect


text:
package com.siso.app.adapter;

import java.util.List;

import com.siso.app.entity.FindListJsonEntity;
import com.siso.app.entity.GoodsEntity;
import com.siso.app.ui.R;
import com.squareup.picasso.Picasso;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * description :
 *
 * @version 1.0
 * @author Owater
 * @param <T>
 * @createtime : 2015-5-9 下午12:49:09
 *
 * 修改历史:
 * 修改人                                          修改时间                                                     修改内容
 * --------------- ------------------- -----------------------------------
 * Owater        2015-5-9 下午12:49:09
 *
 */
public class UserGoodsAdapter extends RecyclerView.Adapter<UserGoodsAdapter.ViewHolder> implements OnClickListener,OnLongClickListener {

	private final LayoutInflater inflater;
	private List<GoodsEntity> list;
	private Context context;
	private OnItemClickListener listener;
	private boolean isMe;

	public UserGoodsAdapter(Context context,List<GoodsEntity> list,boolean isMe){
		this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.list = list;
        this.isMe = isMe;
	}

	public static class ViewHolder extends RecyclerView.ViewHolder {
		public ImageView imageView;
		public TextView price;
		public TextView title;
		public TextView desp;
		public ViewHolder(View itemView) {
			super(itemView);
			this.price = (TextView)itemView.findViewById(R.id.item_user_pub_price);
			this.title = (TextView)itemView.findViewById(R.id.item_user_pub_title);
			this.desp = (TextView)itemView.findViewById(R.id.item_user_pub_desp);
			this.imageView = (ImageView)itemView.findViewById(R.id.item_user_pub_img);
		}
	}

	public static interface OnItemClickListener {
        public void onItemClick(View view,GoodsEntity goodsEntity);
        public void onItemLongClick(View view,GoodsEntity goodsEntity);
    }

	@Override
	public int getItemCount() {
		return list.size();
	}

	@Override
	public void onBindViewHolder(ViewHolder holder, int position) {
		GoodsEntity goodsEntity = list.get(position);

		holder.price.setText("¥"+goodsEntity.getGoodPrice());
		holder.title.setText(goodsEntity.getGoodName());
		holder.desp.setText(goodsEntity.getGoodDescribe());

		if(goodsEntity.getGoodImages()!=null){
			String imgUrls[] = goodsEntity.getGoodImages().split(";");
			Log.i("tag", "imgUrls[0]===="+imgUrls[0]);
			Picasso picasso = Picasso.with(holder.imageView.getContext());
	        picasso.load(imgUrls[0]).placeholder(R.drawable.ic_img_loading).into(holder.imageView);
		}
		holder.itemView.setTag(goodsEntity);
	}

	@Override
	public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		View view = inflater.inflate(R.layout.item_user_pub_goods,parent,false);
        ViewHolder viewHolder = new ViewHolder(view);
        view.setOnClickListener(this);
        if(isMe)
        	view.setOnLongClickListener(this);
        return viewHolder;
	}

	public void setOnItemClickListener(OnItemClickListener onItemClickListener){
		if(onItemClickListener!=null){
			this.listener = onItemClickListener;
		}
	}

	@Override
	public void onClick(View view) {
		if (listener!=null) {
			listener.onItemClick(view, (GoodsEntity)view.getTag());
		}
	}

	@Override
	public boolean onLongClick(View view) {
		if (listener!=null) {
			listener.onItemLongClick(view, (GoodsEntity)view.getTag());
		}
		return true;
	}

}