text:
package org.efaps.db.stmt.selection;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import org.apache.commons.collections4.multimap.AbstractListValuedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.efaps.db.Instance;
import org.efaps.db.stmt.selection.elements.AbstractElement;
import org.efaps.db.stmt.selection.elements.ISquash;
import org.efaps.util.EFapsException;

/**
 * The Class Selection.
 *
 * @author The eFaps Team
 */
public final class Select
{

    /** The objects. */
    private final List<Object> objects = new ArrayList<>();

    /** The elements. */
    private final List<AbstractElement<?>> elements = new ArrayList<>();

    /** The alias. */
    private final String alias;

    /** The iterator. */
    private Iterator<Object> iterator;

    /** The current. */
    private Object current;

    /** The squash able. */
    private boolean noSquashRequired = true;

    /** The squash. */
    private Squashing squash;

    /**
     * Instantiates a new select.
     *
     * @param _alias the alias
     */
    private Select(final String _alias)
    {
        alias = _alias;
    }

    /**
     * Adds the element.
     *
     * @param _element the element
     * @return the select
     */
    protected Select addElement(final AbstractElement<?> _element)
    {
        noSquashRequired = noSquashRequired && !(_element instanceof ISquash);
        if (!elements.isEmpty()) {
            final AbstractElement<?> prev = elements.get(elements.size() - 1);
            _element.setPrevious(prev);
        }
        elements.add(_element);
        return this;
    }

    /**
     * Checks if is squash able.
     *
     * @return the squash able
     */
    protected boolean isSquash()
    {
        return !noSquashRequired;
    }

    protected Squashing getSquash()
    {
        return squash;
    }

    protected void setSquash(final Squashing _squash)
    {
        squash = _squash;
    }

    protected List<Object> getObjects() {
        return objects;
    }

    /**
     * Adds the object.
     *
     * @param _row the row
     * @throws EFapsException the e faps exception
     */
    public void addObject(final Object[] _row)
        throws EFapsException
    {
        objects.add(elements.get(0).getObject(_row));
    }

    /**
     * Gets the objects.
     *
     * @param _evaluator the evaluator
     * @return the objects
     * @throws EFapsException the e faps exception
     */
    protected List<Object> getObjects(final Evaluator _evaluator)
        throws EFapsException
    {
        final List<Object> result;
        if (_evaluator == null) {
            result = objects;
        } else {
            result = new ArrayList<>();
            final AbstractElement<?> element = getElements().get(getElements().size() - 1);
            final String path = element.getPath();
            final Select instSelection = _evaluator.getSelection().getInstSelects().get(StringUtils.isEmpty(path)
                            ? Selection.BASEPATH
                            : path);
            final List<Object> instObjs = instSelection.getObjects(null);
            final Iterator<Object> objIter = objects.iterator();
            for (final Object instObj : instObjs) {
                if (_evaluator.getAccess().hasAccess((Instance) instObj)) {
                    result.add(objIter.next());
                } else {
                    objIter.next();
                }
            }
        }
        return Collections.unmodifiableList(result);
    }

    /**
     * Gets the elements.
     *
     * @return the elements
     */
    public List<AbstractElement<?>> getElements()
    {
        return elements;
    }

    /**
     * Gets the alias.
     *
     * @return the alias
     */
    public String getAlias()
    {
        return alias;
    }

    /**
     * Gets the current.
     *
     * @return the current
     */
    public Object getCurrent()
    {
        return current instanceof ProxiedObject ? ((ProxiedObject) current).getObject() : current;
    }

    /**
     * Next.
     *
     * @return true, if successful
     */
    public boolean next()
    {
        boolean ret = false;
        if (iterator == null) {
            iterator = objects.iterator();
        }
        if (iterator.hasNext()) {
            current = iterator.next();
            ret = true;
        }
        return ret;
    }

    /**
     * Reset.
     */
    protected void reset()
    {
        iterator = null;
        current = null;
    }

    /**
     * Gets the.
     *
     * @return the select
     */
    public static Select get()
    {
        return new Select(null);
    }

    /**
     * Gets the.
     *
     * @param _alias the alias
     * @return the select
     */
    public static Select get(final String _alias)
    {
        return new Select(_alias);
    }

    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this);
    }

    /**
     * The Class SortedListValuedMap.
     *
     * @param <K> the key type
     * @param <V> the value type
     */
    public static class SortedListValuedMap<K, V>
        extends AbstractListValuedMap<K, V>
        implements Serializable
    {

        /** The Constant serialVersionUID. */
        private static final long serialVersionUID = 1L;

        /**
         * Instantiates a new sorted list valued map.
         */
        public SortedListValuedMap()
        {
            super(new TreeMap<>());
        }

        @Override
        protected List<V> createCollection()
        {
            return new ArrayList<>();
        }
    }
}


text:
class GuiManager(object):
	def __init__(self, gui, total_uploaded):
		self.gui = gui
		self.gui.set_uploaded(total_uploaded)
		self.gui.set_remaining(0)
		self.gui.set_skipped(0)
		if total_uploaded == 0:
			self.gui.enable_listen(False)
		else:
			self.gui.enable_listen(True)

		self.uploaded = total_uploaded
		self.skipped = 0
		self.remaining = 0

	def start_search(self):
		self.gui.set_msg('Searching for music...')
		self.gui.enable_login(False)
		self.gui.enable_options(True)

	def start_auth(self, upload_src):
		self.gui.enable_login(True)
		msg = 'Music has been found that has not been uploaded\n'
		if upload_src == 'itunes':
			msg += 'Click Login to start uploading your iTunes library'
		else:
			msg += 'Click Login to start uploading your music'
		self.gui.set_msg(msg)

	def end_auth(self):
		self.gui.enable_login(False)
		self.gui.set_msg('Login complete, uploading will begin shortly')
		self.gui.activate()

	def start_reauth(self):
		self.gui.enable_login(True)
		self.gui.set_msg('You need to re-login to continue\nClick "Save my login" on login page to stay logged in')

	def end_reauth(self):
		self.gui.enable_login(False)
		self.gui.set_msg('Login complete, uploading will resume shortly')
		self.gui.activate()

	def conn_error(self):
		self.gui.set_msg('Error connecting to server,\nWill retry in a moment')
		self.gui.set_progress(True)

	def no_music_found(self):
		self.gui.set_msg('No music found!\nClick Options to add some')

	def no_new_music(self):
		self.gui.set_msg('No new music to upload...')
		self.gui.set_progress(False, 0.0)

	def start_analysis(self, total_tracks):
		self.gui.set_msg('Analyzing library...')
		self.gui.set_progress(False, 0.0)
		self.gui.enable_options(False)
		self.total_tracks = float(total_tracks)
		self.tracks_analyzed = 0

	def file_analyzed(self, count=1):
		self.gui.set_msg('Analyzing library...')
		self.tracks_analyzed += count
		self.gui.set_progress(False, (self.tracks_analyzed/self.total_tracks))

	def file_skipped(self):
		self.skipped += 1
		self.gui.set_skipped(self.skipped)

	def file_auto_uploaded(self, amount=1):
		self.uploaded += amount
		self.gui.set_uploaded(self.uploaded)

	def file_queued(self):
		self.remaining += 1
		self.gui.set_remaining(self.remaining)

	def start_upload(self, filename, file_len):
		self.gui.set_msg(u'Uploading file:\n%s' % filename)
		self.gui.set_progress(False, 0.0)
		self.file_len = float(file_len)
		self.amount_uploaded = 0

	def file_uploaded(self):
		self.uploaded += 1
		self.remaining -= 1
		self.gui.set_uploaded(self.uploaded)
		self.gui.set_remaining(self.remaining)

	def upload_progress(self, amount_uploaded):
		self.amount_uploaded += amount_uploaded
		self.gui.set_progress(False, self.amount_uploaded/self.file_len)

	def activate(self):
		self.gui.activate()

	def upload_complete(self):
		self.gui.set_msg('Upload complete!')
		self.gui.enable_options(True)

	def fatal_error(self):
		self.gui.enable_options(False)
		self.gui.fatal_error('A fatal error has occured in the Harmonizer.\n\nPlease exit the program and start it again.')

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2019-2022, University of Colorado Boulder

/**
 * Timer so that other modules can run timing related code through the simulation's requestAnimationFrame. Use its
 * Emitter interface for adding/removing listeners.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

import axon from './axon.js';
import TinyEmitter from './TinyEmitter.js';

export type TimerListener = ( dt: number ) => void;

export default class Timer extends TinyEmitter<[number]> {

  /**
   * Adds a listener to be called back once after the specified time in milliseconds
   * @param listener - called with no arguments
   * @param timeout in milliseconds
   * @returns an internally-wrapped listener which can be removed with clearTimeout
   */
  public setTimeout( listener: () => void, timeout: number ): TimerListener { // eslint-disable-line bad-sim-text
    let elapsed = 0;
    const callback = ( dt: number ) => {
      elapsed += dt;

      // Convert seconds to ms and see if item has timed out
      if ( elapsed * 1000 >= timeout ) {

        // make sure that this callback hasn't already been removed by another listener while emit() is in progress
        if ( this.hasListener( callback ) ) {
          listener();
          this.removeListener( callback );
        }
      }
    };
    this.addListener( callback );

    // Return the callback so it can be removed with removeStepListener
    return callback;
  }

  /**
   * Clear a scheduled timeout. If there was no timeout, nothing is done.
   */
  public clearTimeout( listener: TimerListener ): void {
    if ( this.hasListener( listener ) ) {
      this.removeListener( listener );
    }
  }

  /**
   * Adds a listener to be called at specified intervals (in milliseconds)
   * @param listener - called with no arguments
   * @param interval - in milliseconds
   * @returns an internally-wrapped listener which can be removed with clearInterval
   */
  public setInterval( listener: () => void, interval: number ): TimerListener { // eslint-disable-line bad-sim-text
    let elapsed = 0;
    const callback = ( dt: number ) => {
      elapsed += dt;

      // Convert seconds to ms and see if item has timed out
      while ( elapsed * 1000 >= interval && this.hasListener( callback ) ) {
        listener();
        elapsed = elapsed - interval / 1000.0; // Save the leftover time so it won't accumulate
      }
    };
    this.addListener( callback );

    // Return the callback so it can be removed with removeListener
    return callback;
  }

  /**
   * Clear a scheduled interval. If there was no interval, nothing is done.
   */
  public clearInterval( listener: TimerListener ): void {
    if ( this.hasListener( listener ) ) {
      this.removeListener( listener );
    }
  }

  /**
   * Run a callback on the next frame. This method is largely for clarity.
   */
  public runOnNextTick( listener: () => void ): void {
    this.setTimeout( listener, 0 );
  }
}

axon.register( 'Timer', Timer );


text:
package org.bouncycastle.jcajce.provider.asymmetric.dstu;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.interfaces.ECPrivateKey;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.EllipticCurve;
import java.util.Enumeration;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.ua.DSTU4145NamedCurves;
import org.bouncycastle.asn1.ua.UAObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X962Parameters;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util;
import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil;
import org.bouncycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl;
import org.bouncycastle.jce.interfaces.ECPointEncoder;
import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.math.ec.ECCurve;

public class BCDSTU4145PrivateKey
    implements ECPrivateKey, org.bouncycastle.jce.interfaces.ECPrivateKey, PKCS12BagAttributeCarrier, ECPointEncoder
{
    static final long serialVersionUID = 7245981689601667138L;

    private String algorithm = "DSTU4145";
    private boolean withCompression;

    private transient BigInteger d;
    private transient ECParameterSpec ecSpec;
    private transient DERBitString publicKey;
    private transient PKCS12BagAttributeCarrierImpl attrCarrier = new PKCS12BagAttributeCarrierImpl();

    protected BCDSTU4145PrivateKey()
    {
    }

    public BCDSTU4145PrivateKey(
        ECPrivateKey key)
    {
        this.d = key.getS();
        this.algorithm = key.getAlgorithm();
        this.ecSpec = key.getParams();
    }

    public BCDSTU4145PrivateKey(
        org.bouncycastle.jce.spec.ECPrivateKeySpec spec)
    {
        this.d = spec.getD();

        if (spec.getParams() != null) // can be null if implicitlyCA
        {
            ECCurve curve = spec.getParams().getCurve();
            EllipticCurve ellipticCurve;

            ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

            this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
        }
        else
        {
            this.ecSpec = null;
        }
    }

    public BCDSTU4145PrivateKey(
        ECPrivateKeySpec spec)
    {
        this.d = spec.getS();
        this.ecSpec = spec.getParams();
    }

    public BCDSTU4145PrivateKey(
        BCDSTU4145PrivateKey key)
    {
        this.d = key.d;
        this.ecSpec = key.ecSpec;
        this.withCompression = key.withCompression;
        this.attrCarrier = key.attrCarrier;
        this.publicKey = key.publicKey;
    }

    public BCDSTU4145PrivateKey(
        String algorithm,
        ECPrivateKeyParameters params,
        BCDSTU4145PublicKey pubKey,
        ECParameterSpec spec)
    {
        ECDomainParameters dp = params.getParameters();

        this.algorithm = algorithm;
        this.d = params.getD();

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

            this.ecSpec = new ECParameterSpec(
                ellipticCurve,
                new ECPoint(
                    dp.getG().getAffineXCoord().toBigInteger(),
                    dp.getG().getAffineYCoord().toBigInteger()),
                dp.getN(),
                dp.getH().intValue());
        }
        else
        {
            this.ecSpec = spec;
        }

        publicKey = getPublicKeyDetails(pubKey);
    }

    public BCDSTU4145PrivateKey(
        String algorithm,
        ECPrivateKeyParameters params,
        BCDSTU4145PublicKey pubKey,
        org.bouncycastle.jce.spec.ECParameterSpec spec)
    {
        ECDomainParameters dp = params.getParameters();

        this.algorithm = algorithm;
        this.d = params.getD();

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

            this.ecSpec = new ECParameterSpec(
                ellipticCurve,
                new ECPoint(
                    dp.getG().getAffineXCoord().toBigInteger(),
                    dp.getG().getAffineYCoord().toBigInteger()),
                dp.getN(),
                dp.getH().intValue());
        }
        else
        {
            EllipticCurve ellipticCurve = EC5Util.convertCurve(spec.getCurve(), spec.getSeed());

            this.ecSpec = new ECParameterSpec(
                ellipticCurve,
                new ECPoint(
                    spec.getG().getAffineXCoord().toBigInteger(),
                    spec.getG().getAffineYCoord().toBigInteger()),
                spec.getN(),
                spec.getH().intValue());
        }

        publicKey = getPublicKeyDetails(pubKey);
    }

    public BCDSTU4145PrivateKey(
        String algorithm,
        ECPrivateKeyParameters params)
    {
        this.algorithm = algorithm;
        this.d = params.getD();
        this.ecSpec = null;
    }

    BCDSTU4145PrivateKey(
        PrivateKeyInfo info)
        throws IOException
    {
        populateFromPrivKeyInfo(info);
    }

    private void populateFromPrivKeyInfo(PrivateKeyInfo info)
        throws IOException
    {
        X962Parameters params = new X962Parameters((ASN1Primitive)info.getPrivateKeyAlgorithm().getParameters());

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

            if (ecP == null) // DSTU Curve
            {
                ECDomainParameters gParam = DSTU4145NamedCurves.getByOID(oid);
                EllipticCurve ellipticCurve = EC5Util.convertCurve(gParam.getCurve(), gParam.getSeed());

                ecSpec = new ECNamedCurveSpec(
                    oid.getId(),
                    ellipticCurve,
                    new ECPoint(
                        gParam.getG().getAffineXCoord().toBigInteger(),
                        gParam.getG().getAffineYCoord().toBigInteger()),
                    gParam.getN(),
                    gParam.getH());
            }
            else
            {
                EllipticCurve ellipticCurve = EC5Util.convertCurve(ecP.getCurve(), ecP.getSeed());

                ecSpec = new ECNamedCurveSpec(
                    ECUtil.getCurveName(oid),
                    ellipticCurve,
                    new ECPoint(
                        ecP.getG().getAffineXCoord().toBigInteger(),
                        ecP.getG().getAffineYCoord().toBigInteger()),
                    ecP.getN(),
                    ecP.getH());
            }
        }
        else if (params.isImplicitlyCA())
        {
            ecSpec = null;
        }
        else
        {
            X9ECParameters ecP = X9ECParameters.getInstance(params.getParameters());
            EllipticCurve ellipticCurve = EC5Util.convertCurve(ecP.getCurve(), ecP.getSeed());

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

        ASN1Encodable privKey = info.parsePrivateKey();
        if (privKey instanceof ASN1Integer)
        {
            ASN1Integer derD = ASN1Integer.getInstance(privKey);

            this.d = derD.getValue();
        }
        else
        {
            org.bouncycastle.asn1.sec.ECPrivateKey ec = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(privKey);

            this.d = ec.getKey();
            this.publicKey = ec.getPublicKey();
        }
    }

    public String getAlgorithm()
    {
        return algorithm;
    }

    /**
     * return the encoding format we produce in getEncoded().
     *
     * @return the string "PKCS#8"
     */
    public String getFormat()
    {
        return "PKCS#8";
    }

    /**
     * Return a PKCS8 representation of the key. The sequence returned
     * represents a full PrivateKeyInfo object.
     *
     * @return a PKCS8 representation of the key.
     */
    public byte[] getEncoded()
    {
        X962Parameters params;

        if (ecSpec instanceof ECNamedCurveSpec)
        {
            ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveSpec)ecSpec).getName());
            if (curveOid == null)  // guess it's the OID
            {
                curveOid = new ASN1ObjectIdentifier(((ECNamedCurveSpec)ecSpec).getName());
            }
            params = new X962Parameters(curveOid);
        }
        else if (ecSpec == null)
        {
            params = new X962Parameters(DERNull.INSTANCE);
        }
        else
        {
            ECCurve curve = EC5Util.convertCurve(ecSpec.getCurve());

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

            params = new X962Parameters(ecP);
        }

        PrivateKeyInfo info;
        org.bouncycastle.asn1.sec.ECPrivateKey keyStructure;

        if (publicKey != null)
        {
            keyStructure = new org.bouncycastle.asn1.sec.ECPrivateKey(this.getS(), publicKey, params);
        }
        else
        {
            keyStructure = new org.bouncycastle.asn1.sec.ECPrivateKey(this.getS(), params);
        }

        try
        {
            if (algorithm.equals("DSTU4145"))
            {
                info = new PrivateKeyInfo(new AlgorithmIdentifier(UAObjectIdentifiers.dstu4145be, params.toASN1Primitive()), keyStructure.toASN1Primitive());
            }
            else
            {

                info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params.toASN1Primitive()), keyStructure.toASN1Primitive());
            }

            return info.getEncoded(ASN1Encoding.DER);
        }
        catch (IOException e)
        {
            return null;
        }
    }

    public ECParameterSpec getParams()
    {
        return ecSpec;
    }

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

        return EC5Util.convertSpec(ecSpec, withCompression);
    }

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

        return BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();
    }

    public BigInteger getS()
    {
        return d;
    }

    public BigInteger getD()
    {
        return d;
    }

    public void setBagAttribute(
        ASN1ObjectIdentifier oid,
        ASN1Encodable attribute)
    {
        attrCarrier.setBagAttribute(oid, attribute);
    }

    public ASN1Encodable getBagAttribute(
        ASN1ObjectIdentifier oid)
    {
        return attrCarrier.getBagAttribute(oid);
    }

    public Enumeration getBagAttributeKeys()
    {
        return attrCarrier.getBagAttributeKeys();
    }

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

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

        BCDSTU4145PrivateKey other = (BCDSTU4145PrivateKey)o;

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

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

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

        buf.append("EC Private Key").append(nl);
        buf.append("             S: ").append(this.d.toString(16)).append(nl);

        return buf.toString();

    }

    private DERBitString getPublicKeyDetails(BCDSTU4145PublicKey pub)
    {
        try
        {
            SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(pub.getEncoded()));

            return info.getPublicKeyData();
        }
        catch (IOException e)
        {   // should never happen
            return null;
        }
    }

    private void readObject(
        ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        in.defaultReadObject();

        byte[] enc = (byte[])in.readObject();

        populateFromPrivKeyInfo(PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(enc)));

        this.attrCarrier = new PKCS12BagAttributeCarrierImpl();
    }

    private void writeObject(
        ObjectOutputStream out)
        throws IOException
    {
        out.defaultWriteObject();

        out.writeObject(this.getEncoded());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simplic.AdaptiveTesting.Configuration
{
    /// <summary>
    /// Contains the settings for the current test
    /// </summary>
    public class TestSettingsConfiguration
    {
        /// <summary>
        /// Name of the project
        /// </summary>
        public string Project
        {
            get;
            set;
        }

        /// <summary>
        /// Report-Output path
        /// </summary>
        public string ReportOutput
        {
            get;
            set;
        }

        /// <summary>
        /// Output options, for example output directory, ...
        /// </summary>
        public IList<TestOutputConfiguration> Output
        {
            get;
            set;
        }
    }
}


text:
package com.orientechnologies.orient.spatial.strategy;

import com.orientechnologies.lucene.engine.OLuceneSpatialIndexContainer;
import com.orientechnologies.lucene.query.SpatialQueryContext;
import com.orientechnologies.orient.spatial.shape.OShapeBuilder;
import com.spatial4j.core.shape.Shape;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.spatial.SpatialStrategy;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialOperation;

import java.util.Map;

/**
 * Created by Enrico Risa on 11/08/15.
 */
public class SpatialQueryBuilderDWithin extends SpatialQueryBuilderAbstract {

  public static final String NAME = "dwithin";

  public SpatialQueryBuilderDWithin(OLuceneSpatialIndexContainer manager, OShapeBuilder factory) {
    super(manager, factory);
  }

  @Override
  public SpatialQueryContext build(Map<String, Object> query) throws Exception {
    Shape shape = parseShape(query);

    SpatialStrategy strategy = manager.strategy();
    if (isOnlyBB(strategy)) {
      shape = shape.getBoundingBox();
    }
    SpatialArgs args = new SpatialArgs(SpatialOperation.IsWithin, shape);
    Filter filter = strategy.makeFilter(args);
    return new SpatialQueryContext(null, manager.searcher(), new MatchAllDocsQuery(), filter);
  }

  @Override
  public String getName() {
    return NAME;
  }
}


text:
package org.eclipse.bpmn2.tests;

import junit.textui.TestRunner;

import org.eclipse.bpmn2.Bpmn2Factory;
import org.eclipse.bpmn2.CandidateGroup;

/**
 *
 * A test case for the model object 'Candidate Group'.
 *
 * @generated
 */
public class CandidateGroupTest extends BaseElementTest {

	/**
	 *
	 *
	 * @generated
	 */
	public static void main(String[] args) {
		TestRunner.run(CandidateGroupTest.class);
	}

	/**
	 * Constructs a new Candidate Group test case with the given name.
	 *
	 *
	 * @generated
	 */
	public CandidateGroupTest(String name) {
		super(name);
	}

	/**
	 * Returns the fixture for this Candidate Group test case.
	 *
	 *
	 * @generated
	 */
	@Override
	protected CandidateGroup getFixture() {
		return (CandidateGroup) fixture;
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#setUp()
	 * @generated
	 */
	@Override
	protected void setUp() throws Exception {
		setFixture(Bpmn2Factory.eINSTANCE.createCandidateGroup());
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#tearDown()
	 * @generated
	 */
	@Override
	protected void tearDown() throws Exception {
		setFixture(null);
	}

} //CandidateGroupTest


text:
//
//  Copyright © 2015 Claus Christmann <hcc |ä| gatech.edu>.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#ifndef NODEID_128_H
#define NODEID_128_H

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/graph/buffer_concepts.hpp>
#include <assert.h>

#include <QtCore/QDebug>
#include <QtCore/QByteArray>

#include "IDL/data.h"
#include "DDS/ddssupport.h"

/** \brief A class holding Node specific 128 UUID data.
 *
 * \todo missing bool opertor==(IDL::Data::NodeId, NodeId_128);
 */
class NodeId_128 : public boost::uuids::uuid
{
public:

  /** \brief Default (empty) constructor. */
  NodeId_128()
    :boost::uuids::uuid({{0}}){ };

  /** \brief Constructor. */
  NodeId_128(boost::uuids::uuid const & u)
    :boost::uuids::uuid(u) {};

  /** \brief Constructor. */
  NodeId_128(IDL::Data::NodeId const & idlId)
  {
    Q_ASSERT( size()==static_cast<size_t>( idlId.length() ) );
    memcpy(data,idlId.get_contiguous_buffer(),size());
  };

  /** \brief Constructor. */
  explicit NodeId_128(DDS_GUID_t const & guid)
  {
    Q_ASSERT( size()==sizeof(guid.value) );
    memcpy(data,guid.value, sizeof(guid.value));
  };

  /** \brief Constructor. */
  explicit NodeId_128(DDS_InstanceHandle_t const & handle)
    :NodeId_128(DDS::convertToGuid(handle))
  {};

  /** \brief Constructor. */
  explicit NodeId_128(DDS_BuiltinTopicKey_t const & key)
    :NodeId_128(DDS::convertToGuid(key))
  {};

  explicit NodeId_128(QByteArray const & byteArray)
    :boost::uuids::uuid({{0}})
  {
    Q_ASSERT(byteArray.size() == static_cast<int>(size()));
    for( std::size_t i=0; i<size(); ++i)
    { data[i] = byteArray.at(i); }
  };

  DDS_GUID_t toDdsGuid() const
  {
    DDS_GUID_t guid;
    Q_ASSERT( size()==sizeof(guid.value) );
    memcpy(guid.value,data,size());
    return guid;
  };

  DDS_InstanceHandle_t toDdsInstanceHandle() const
  {
    DDS_InstanceHandle_t handle;
    memcpy(&(handle),&data,size());
    handle.isValid = DDS_BOOLEAN_TRUE;
    return handle;
  };

  IDL::Data::NodeId toIdlNodeId() const
  {
    DDS_Long length = static_cast<DDS_Long>(this->size());
    IDL::Data::NodeId idlId(length);

    //NOTE: If this assert fails, a common mistake is that the DDS sequence
    // for the IDL::Data:NodeId hasn't been properly initialized. Maybe a `new`
    // instead of a `TopicSupport::create_data()` was used?
    Q_ASSERT( idlId.maximum() == static_cast<DDS_Long>( this->size() ));

    idlId.from_array( this->data,this->size() );
    return idlId;
  };

  QByteArray toByteArray() const
  {
    QByteArray qba;
    for(auto& byte : data)
    { qba.append(byte); }
    return qba;
  };

  std::string toString() const
  {
    return boost::uuids::to_string(*this);
  };

  QString toQString() const
  {
    return QString(toString().c_str());
  };

  NodeId_128& operator=(NodeId_128 const & rhs) = default;

  /** \brief Conversion operator to boost::uuid.
   * \internal The conversion operators are taken from
   * http://www.boost.org/doc/libs/1_53_0/libs/uuid/uuid.html .
   * \todo I honestly have no idea why they return a cast to a \e reference,
   * but I assume that has something to do with boost::uuid being a base class.
   */
  operator boost::uuids::uuid()
  { return static_cast<boost::uuids::uuid&>(*this); }

  /** \brief Conversion operator to boost::uuid. */
  operator boost::uuids::uuid() const
  { return static_cast<boost::uuids::uuid const&>(*this); };

//   /** \brief Conversion operator to std::string. */
//   operator std::string() const
//   { return boost::uuids::to_string(*this); };

//   /** \brief Conversion operator to QString. */
//   operator QString() const
//   { return QString(std::string(*this).c_str()); };

//   /** \brief Conversion operator to DDS_GUID_t. */
//   operator DDS_GUID_t() const
//   { return toDdsGuid(); };

//   /** \brief Conversion operator to DDS_InstanceHandle_t. */
//   operator DDS_InstanceHandle_t() const
//   { return toDdsInstanceHandle(); };

  /** \brief Conversion operator to IDL::Data::ID. */
  operator IDL::Data::NodeId() const
  { return toIdlNodeId(); };

  /** \brief Conversion operator to QByteArray. */
  operator QByteArray() const
  { return toByteArray(); }

protected:
  template<typename T1, typename T2, typename T3, typename T4>
  NodeId_128(T1 const & d1, T2 const & d2, T3 const & d3, T4 const & d4)
  {
    auto& raw_data = data;

    const size_t s1 = sizeof(d1);
    const size_t s2 = sizeof(d2);
    const size_t s3 = sizeof(d3);
    const size_t s4 = sizeof(d4);
    Q_ASSERT(s1+s2+s3+s4 == sizeof(raw_data));

    // fill raw_uuid_data
    memcpy( &raw_data[0], &d1, s1);
    memcpy( &raw_data[(s1)/sizeof(raw_data[0])], &d2, s2);
    memcpy( &raw_data[(s1+s2)/sizeof(raw_data[0])], &d3, s3);
    memcpy( &raw_data[(s1+s2+s3)/sizeof(raw_data[0])], &d4, s4);
  };

};

const NodeId_128 NULL_NODE_128_ID = NodeId_128();

namespace std {

  template<>
  struct hash<NodeId_128>
  {
    size_t operator()(const NodeId_128& u) const
    { return boost::uuids::hash_value(u); }
  };

  template<>
  inline void swap(NodeId_128& lhs, NodeId_128& rhs)
  { boost::uuids::swap(lhs,rhs); };

} // end namespace std

// inline unsigned int qHash(NodeId_128 const & u)
// { return boost::uuids::hash_value(u); };

//############################################################################//
//                                                                            //
//  I/O Support                                                               //
//                                                                            //
//############################################################################//

inline std::ostream& operator<<(std::ostream& out, const NodeId_128& uuid)
{ return out << boost::uuids::to_string(uuid); };

inline QDebug operator<<(QDebug dbg, const NodeId_128& uuid)
{
  dbg.nospace() << boost::uuids::to_string(uuid).c_str();
  return dbg.space();
};

inline QDataStream & operator<<(QDataStream &out, const NodeId_128 & id)
{
  out << id.toByteArray();
  out.setVersion(QDataStream::Qt_5_0);

  return out;
};

inline QDataStream & operator>>(QDataStream &in, NodeId_128 & id)
{
  if( in.version() == QDataStream::Qt_5_0 )
  {
    QByteArray qba;
    in >> qba;
    id = NodeId_128(qba);
  }
  else
  {
   qCritical("Wrong QDataStream version. QDataStream::Qt_5_0 is required.");
  }

  return in;
};

#endif // NODEID_128_H


text:
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <display-name>Validation-test-AS7</display-name>

    <context-param>
        <param-name>resteasy.validation.suppress.path</param-name>
        <param-value>true</param-value>
    </context-param>

</web-app>


text:
#ifndef __LIBSSH2_CHANNEL_H
#define __LIBSSH2_CHANNEL_H

/*
 * _libssh2_channel_receive_window_adjust
 *
 * Adjust the receive window for a channel by adjustment bytes. If the amount
 * to be adjusted is less than LIBSSH2_CHANNEL_MINADJUST and force is 0 the
 * adjustment amount will be queued for a later packet.
 *
 * Always non-blocking.
 */
int _libssh2_channel_receive_window_adjust(LIBSSH2_CHANNEL * channel,
                                           unsigned long adjustment,
                                           unsigned char force,
                                           unsigned int *store);

/*
 * _libssh2_channel_flush
 *
 * Flush data from one (or all) stream
 * Returns number of bytes flushed, or negative on failure
 */
int _libssh2_channel_flush(LIBSSH2_CHANNEL *channel, int streamid);

/*
 * _libssh2_channel_free
 *
 * Make sure a channel is closed, then remove the channel from the session
 * and free its resource(s)
 *
 * Returns 0 on success, negative on failure
 */
int _libssh2_channel_free(LIBSSH2_CHANNEL *channel);

int
_libssh2_channel_extended_data(LIBSSH2_CHANNEL *channel, int ignore_mode);

/*
 * _libssh2_channel_write
 *
 * Send data to a channel
 */
ssize_t
_libssh2_channel_write(LIBSSH2_CHANNEL *channel, int stream_id,
                       const char *buf, size_t buflen);

/*
 * _libssh2_channel_open
 *
 * Establish a generic session channel
 */
LIBSSH2_CHANNEL *
_libssh2_channel_open(LIBSSH2_SESSION * session, const char *channel_type,
                      unsigned int channel_type_len,
                      unsigned int window_size, unsigned int packet_size,
                      const char *message, unsigned int message_len);

/*
 * _libssh2_channel_process_startup
 *
 * Primitive for libssh2_channel_(shell|exec|subsystem)
 */
int
_libssh2_channel_process_startup(LIBSSH2_CHANNEL *channel,
                                 const char *request, unsigned int request_len,
                                 const char *message, unsigned int message_len);

/*
 * _libssh2_channel_read
 *
 * Read data from a channel
 *
 * It is important to not return 0 until the currently read channel is
 * complete. If we read stuff from the wire but it was no payload data to fill
 * in the buffer with, we MUST make sure to return PACKET_EAGAIN.
 */
ssize_t _libssh2_channel_read(LIBSSH2_CHANNEL *channel, int stream_id,
                              char *buf, size_t buflen);

uint32_t _libssh2_channel_nextid(LIBSSH2_SESSION * session);

LIBSSH2_CHANNEL *_libssh2_channel_locate(LIBSSH2_SESSION * session,
                                         uint32_t channel_id);

size_t _libssh2_channel_packet_data_len(LIBSSH2_CHANNEL * channel,
                                        int stream_id);

int _libssh2_channel_close(LIBSSH2_CHANNEL * channel);

/*
 * _libssh2_channel_forward_cancel
 *
 * Stop listening on a remote port and free the listener
 * Toss out any pending (un-accept()ed) connections
 *
 * Return 0 on success, LIBSSH2_ERROR_EAGAIN if would block, -1 on error
 */
int _libssh2_channel_forward_cancel(LIBSSH2_LISTENER *listener);

#endif /* __LIBSSH2_CHANNEL_H */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Collections.Specialized;
using System.Windows.Media.Animation;
using System.ComponentModel;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Threading;
using System.Reflection;

namespace ChromeTabs
{
    /// <summary>
    /// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file.
    ///
    /// Step 1a) Using this custom control in a XAML file that exists in the current project.
    /// Add this XmlNamespace attribute to the root element of the markup file where it is
    /// to be used:
    ///
    ///     xmlns:MyNamespace="clr-namespace:ChromeTabs"
    ///
    ///
    /// Step 1b) Using this custom control in a XAML file that exists in a different project.
    /// Add this XmlNamespace attribute to the root element of the markup file where it is
    /// to be used:
    ///
    ///     xmlns:MyNamespace="clr-namespace:ChromeTabs;assembly=ChromeTabs"
    ///
    /// You will also need to add a project reference from the project where the XAML file lives
    /// to this project and Rebuild to avoid compilation errors:
    ///
    ///     Right click on the target project in the Solution Explorer and
    ///     "Add Reference"->"Projects"->[Browse to and select this project]
    ///
    ///
    /// Step 2)
    /// Go ahead and use your control in the XAML file.
    ///
    ///     <MyNamespace:ChromeTabs/>
    ///
    /// </summary>
    public class ChromeTabControl : Selector
    {
        private object _lastSelectedItem;

        internal static readonly DependencyPropertyKey CanAddTabPropertyKey = DependencyProperty.RegisterReadOnly("CanAddTab", typeof(bool), typeof(ChromeTabControl), new PropertyMetadata(true));
        public static readonly DependencyProperty CanAddTabProperty = CanAddTabPropertyKey.DependencyProperty;
        public static readonly DependencyProperty SelectedContentProperty = DependencyProperty.Register("SelectedContent", typeof(object), typeof(ChromeTabControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));

        public static readonly DependencyProperty CloseTabCommandProperty =
    DependencyProperty.Register(
        "CloseTabCommand",
        typeof(ICommand),
        typeof(ChromeTabControl));

        public ICommand CloseTabCommand
        {
            get { return (ICommand)GetValue(CloseTabCommandProperty); }
            set { SetValue(CloseTabCommandProperty, value); }
        }

        public static readonly DependencyProperty AddTabCommandProperty =
    DependencyProperty.Register(
        "AddTabCommand",
        typeof(ICommand),
        typeof(ChromeTabControl));

        public ICommand AddTabCommand
        {
            get { return (ICommand)GetValue(AddTabCommandProperty); }
            set { SetValue(AddTabCommandProperty, value); }
        }

        public static readonly DependencyProperty ReorderTabsCommandProperty =
            DependencyProperty.Register(
            "ReorderTabsCommand",
            typeof(ICommand),
            typeof(ChromeTabControl));

        public ICommand ReorderTabsCommand
        {
            get { return (ICommand)GetValue(ReorderTabsCommandProperty); }
            set { SetValue(ReorderTabsCommandProperty, value); }
        }

        // Provide CLR accessors for the event
        public event TabDragEventHandler TabDraggedOutsideBonds
        {
            add { AddHandler(TabDraggedOutsideBondsEvent, value); }
            remove { RemoveHandler(TabDraggedOutsideBondsEvent, value); }
        }

        // Using a RoutedEvent
        public static readonly RoutedEvent TabDraggedOutsideBondsEvent = EventManager.RegisterRoutedEvent(
            "TabDraggedOutsideBonds", RoutingStrategy.Bubble, typeof(TabDragEventHandler), typeof(ChromeTabControl));

        public bool CloseTabWhenDraggedOutsideBonds
        {
            get { return (bool)GetValue(CloseTabWhenDraggedOutsideBondsProperty); }
            set { SetValue(CloseTabWhenDraggedOutsideBondsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CloseTabWhenDraggedOutsideBonds.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CloseTabWhenDraggedOutsideBondsProperty =
            DependencyProperty.Register("CloseTabWhenDraggedOutsideBonds", typeof(bool), typeof(ChromeTabControl), new PropertyMetadata(false));

        public bool IsAddButtonVisible
        {
            get { return (bool)GetValue(IsAddButtonVisibleProperty); }
            set { SetValue(IsAddButtonVisibleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsAddButtonEnabled.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsAddButtonVisibleProperty =
            DependencyProperty.Register("IsAddButtonVisible", typeof(bool), typeof(ChromeTabControl), new PropertyMetadata(true, new PropertyChangedCallback(IsAddButtonVisiblePropertyCallback)));

        private static void IsAddButtonVisiblePropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ChromeTabControl ctc = d as ChromeTabControl;

            ChromeTabPanel panel = (ChromeTabPanel)ctc.ItemsHost;
            if (panel != null)
                panel.InvalidateVisual();
        }

        public bool CanMoveTabs
        {
            get { return (bool)GetValue(CanMoveTabsProperty); }
            set { SetValue(CanMoveTabsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CanMoveTabs.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CanMoveTabsProperty =
            DependencyProperty.Register("CanMoveTabs", typeof(bool), typeof(ChromeTabControl), new PropertyMetadata(true));

        public bool DragWindowWithOneTab
        {
            get { return (bool)GetValue(DragWindowWithOneTabProperty); }
            set { SetValue(DragWindowWithOneTabProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DragWindowWithOneTab.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DragWindowWithOneTabProperty =
            DependencyProperty.Register("DragWindowWithOneTab", typeof(bool), typeof(ChromeTabControl), new PropertyMetadata(true));

        public Brush SelectedTabBrush
        {
            get { return (Brush)GetValue(SelectedTabBrushProperty); }
            set { SetValue(SelectedTabBrushProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedTabBrush.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedTabBrushProperty =
            DependencyProperty.Register("SelectedTabBrush", typeof(Brush), typeof(ChromeTabControl), new PropertyMetadata(null, new PropertyChangedCallback(SelectedTabBrushPropertyCallback)));

        /// <summary>
        /// The extra pixel distance you need to drag up or down the tab before the tab tears out.
        /// </summary>
        public double TabTearTriggerDistance
        {
            get { return (double)GetValue(TabTearTriggerDistanceProperty); }
            set { SetValue(TabTearTriggerDistanceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TabTearTriggerDistance.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TabTearTriggerDistanceProperty =
            DependencyProperty.Register("TabTearTriggerDistance", typeof(double), typeof(ChromeTabControl), new PropertyMetadata(0.0));

        static ChromeTabControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ChromeTabControl), new FrameworkPropertyMetadata(typeof(ChromeTabControl)));
        }

        private static void SelectedTabBrushPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ChromeTabControl ctc = (ChromeTabControl)d;
            if (e.NewValue != null && ctc.SelectedItem != null)
                ctc.AsTabItem(ctc.SelectedItem).SelectedTabBrush = (Brush)e.NewValue;
        }
        /// <summary>
        /// Grabs hold of the tab based on the input viewmodel and positions it at the mouse cursor.
        /// </summary>
        /// <param name="viewModel"></param>
        public void GrabTab(object viewModel)
        {
            ChromeTabPanel p = (ChromeTabPanel)ItemsHost;
            ChromeTabItem item = AsTabItem(viewModel);
            p.StartTabDrag(item, true);
        }
        protected Panel ItemsHost
        {
            get
            {
                return (Panel)typeof(MultiSelector).InvokeMember("ItemsHost",
                    BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance,
                    null, this, null);
            }
        }

        public void AddTab()
        {
            if (!CanAddTab)
            {
                return;
            }
            if (this.AddTabCommand != null)
                this.AddTabCommand.Execute(null);
        }

        public bool CanAddTab
        {
            get { return (bool)GetValue(CanAddTabProperty); }
        }

        public void RemoveTab(object tab)
        {
            ChromeTabItem removeItem = this.AsTabItem(tab);
            if (CloseTabCommand != null)
                CloseTabCommand.Execute(removeItem.DataContext);
        }

        public void RemoveAllTabs(object exceptThis = null)
        {
            var objects = this.ItemsSource.Cast<object>().Where(x => x != exceptThis).ToList();
            foreach (object obj in objects)
            {
                CloseTabCommand.Execute(obj);
            }
        }

        public object SelectedContent
        {
            get { return (object)GetValue(SelectedContentProperty); }
            set { SetValue(SelectedContentProperty, value); }
        }

        internal int GetTabIndex(ChromeTabItem item)
        {
            for (int i = 0; i < this.Items.Count; i += 1)
            {
                ChromeTabItem tabItem = this.AsTabItem(this.Items[i]);
                if (tabItem == item)
                {
                    return i;
                }
            }
            return -1;
        }

        internal void ChangeSelectedItem(ChromeTabItem item)
        {
            int index = this.GetTabIndex(item);
            if (index != this.SelectedIndex)
            {
                if (index > -1)
                {
                    if (this.SelectedItem != null)
                    {
                        Canvas.SetZIndex(this.AsTabItem(this.SelectedItem), 0);
                    }
                    this.SelectedIndex = index;
                    Canvas.SetZIndex(item, 1001);
                }
            }
        }

        internal void MoveTab(int fromIndex, int toIndex)
        {
            if (this.Items.Count == 0 || fromIndex == toIndex || fromIndex >= this.Items.Count)
            {
                return;
            }
            object fromTab = this.Items[fromIndex];
            if (this.ReorderTabsCommand != null)
            {
                this.ReorderTabsCommand.Execute(new TabReorder(fromIndex, toIndex));
            }

            for (int i = 0; i < this.Items.Count; i += 1)
            {
                var v = this.AsTabItem(this.Items[i]);
                v.Margin = new Thickness(0);
            }
            this.SelectedItem = fromTab;
        }

        internal void SetCanAddTab(bool value)
        {
            SetValue(CanAddTabPropertyKey, value);
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            var tab = new ChromeTabItem();
            if (this.SelectedTabBrush != null)
                tab.SelectedTabBrush = this.SelectedTabBrush;
            return tab;

        }

        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return (item is ChromeTabItem);
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            bool somethingSelected = false;
            foreach (UIElement element in this.Items)
            {
                somethingSelected |= ChromeTabItem.GetIsSelected(element);
            }
            if (!somethingSelected)
            {
                this.SelectedIndex = 0;
            }
            KeyboardNavigation.SetIsTabStop(this, false);
        }

        protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);

            this.SetChildrenZ();
        }

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            base.OnSelectionChanged(e);
            this.SetChildrenZ();

            if (e.AddedItems.Count == 0)
            {
                if (this.SelectedItem == null)
                {
                    if (this.Items.Count > 0)
                    {
                        if (_lastSelectedItem != null)
                            this.SelectedItem = _lastSelectedItem;
                        else
                            this.SelectedItem = this.Items[0];
                    }
                    else
                    {
                        this.SelectedItem = null;
                        this.SelectedContent = null;
                    }
                }
                return;
            }

            if (this.SelectedIndex > 0)
            {
                this._lastSelectedItem = this.Items[this.SelectedIndex - 1];
            }
            else if (this.SelectedIndex == 0 && this.Items.Count > 1)
            {
                this._lastSelectedItem = this.Items[this.SelectedIndex + 1];
            }
            else
            {
                this._lastSelectedItem = null;
            }
            ChromeTabItem item = this.AsTabItem(this.SelectedItem);
            this.SelectedContent = item != null ? item.Content : null;
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            if (element != item)
            {
                this.ObjectToContainer[item] = element;
                this.SetChildrenZ();
            }
        }

        internal ChromeTabItem AsTabItem(object item)
        {
            ChromeTabItem tabItem = item as ChromeTabItem;
            if (tabItem == null && item != null && this.ObjectToContainer.ContainsKey(item))
            {
                tabItem = this.ObjectToContainer[item] as ChromeTabItem;
            }
            return tabItem;
        }

        private Dictionary<object, DependencyObject> ObjectToContainer
        {
            get
            {
                if (objectToContainerMap == null)
                {
                    objectToContainerMap = new Dictionary<object, DependencyObject>();
                }
                return objectToContainerMap;
            }
        }

        private void SetChildrenZ()
        {
            int zindex = this.Items.Count - 1;
            foreach (object element in this.Items)
            {
                ChromeTabItem tabItem = this.AsTabItem(element);
                if (tabItem == null) { continue; }
                if (ChromeTabItem.GetIsSelected(tabItem))
                {
                    Panel.SetZIndex(tabItem, this.Items.Count);
                }
                else
                {
                    Panel.SetZIndex(tabItem, zindex);
                }
                zindex -= 1;
            }
        }

        private Dictionary<object, DependencyObject> objectToContainerMap;
    }
}


text:
"""Test the "pipeline.py" restricted parallel programming library.
"""
from _common import unittest
from beets.util import pipeline

# Some simple pipeline stages for testing.
def _produce(num=5):
    for i in range(num):
        yield i
def _work():
    i = None
    while True:
        i = yield i
        i *= 2
def _consume(l):
    while True:
        i = yield
        l.append(i)

# A worker that raises an exception.
class TestException(Exception): pass
def _exc_work(num=3):
    i = None
    while True:
        i = yield i
        if i == num:
            raise TestException()
        i *= 2

# A worker that yields a bubble.
def _bub_work(num=3):
    i = None
    while True:
        i = yield i
        if i == num:
            i = pipeline.BUBBLE
        else:
            i *= 2

# Yet another worker that yields multiple messages.
def _multi_work():
    i = None
    while True:
        i = yield i
        i = pipeline.multiple([i, -i])

class SimplePipelineTest(unittest.TestCase):
    def setUp(self):
        self.l = []
        self.pl = pipeline.Pipeline((_produce(), _work(), _consume(self.l)))

    def test_run_sequential(self):
        self.pl.run_sequential()
        self.assertEqual(self.l, [0,2,4,6,8])

    def test_run_parallel(self):
        self.pl.run_parallel()
        self.assertEqual(self.l, [0,2,4,6,8])

class ParallelStageTest(unittest.TestCase):
    def setUp(self):
        self.l = []
        self.pl = pipeline.Pipeline((
            _produce(), (_work(), _work()), _consume(self.l)
        ))

    def test_run_sequential(self):
        self.pl.run_sequential()
        self.assertEqual(self.l, [0,2,4,6,8])

    def test_run_parallel(self):
        self.pl.run_parallel()
        # Order possibly not preserved; use set equality.
        self.assertEqual(set(self.l), set([0,2,4,6,8]))

class ExceptionTest(unittest.TestCase):
    def setUp(self):
        self.l = []
        self.pl = pipeline.Pipeline((_produce(), _exc_work(), _consume(self.l)))

    def test_run_sequential(self):
        self.assertRaises(TestException, self.pl.run_sequential)

    def test_run_parallel(self):
        self.assertRaises(TestException, self.pl.run_parallel)

class ParallelExceptionTest(unittest.TestCase):
    def setUp(self):
        self.l = []
        self.pl = pipeline.Pipeline((
            _produce(), (_exc_work(), _exc_work()), _consume(self.l)
        ))

    def test_run_parallel(self):
        self.assertRaises(TestException, self.pl.run_parallel)

class ConstrainedThreadedPipelineTest(unittest.TestCase):
    def test_constrained(self):
        l = []
        # Do a "significant" amount of work...
        pl = pipeline.Pipeline((_produce(1000), _work(), _consume(l)))
        # ... with only a single queue slot.
        pl.run_parallel(1)
        self.assertEqual(l, [i*2 for i in range(1000)])

    def test_constrained_exception(self):
        # Raise an exception in a constrained pipeline.
        l = []
        pl = pipeline.Pipeline((_produce(1000), _exc_work(), _consume(l)))
        self.assertRaises(TestException, pl.run_parallel, 1)

    def test_constrained_parallel(self):
        l = []
        pl = pipeline.Pipeline((
            _produce(1000), (_work(), _work()), _consume(l)
        ))
        pl.run_parallel(1)
        self.assertEqual(set(l), set(i*2 for i in range(1000)))

class BubbleTest(unittest.TestCase):
    def setUp(self):
        self.l = []
        self.pl = pipeline.Pipeline((_produce(), _bub_work(), _consume(self.l)))

    def test_run_sequential(self):
        self.pl.run_sequential()
        self.assertEqual(self.l, [0,2,4,8])

    def test_run_parallel(self):
        self.pl.run_parallel()
        self.assertEqual(self.l, [0,2,4,8])

class MultiMessageTest(unittest.TestCase):
    def setUp(self):
        self.l = []
        self.pl = pipeline.Pipeline((
            _produce(), _multi_work(), _consume(self.l)
        ))

    def test_run_sequential(self):
        self.pl.run_sequential()
        self.assertEqual(self.l, [0,0,1,-1,2,-2,3,-3,4,-4])

    def test_run_parallel(self):
        self.pl.run_parallel()
        self.assertEqual(self.l, [0,0,1,-1,2,-2,3,-3,4,-4])

def suite():
    return unittest.TestLoader().loadTestsFromName(__name__)

if __name__ == '__main__':
    unittest.main(defaultTest='suite')


text:
<?php
// Include required library files.
require_once('../includes/config.php');
require_once('../autoload.php');

// Create PayPal object.
$PayPalConfig = array(
					'Sandbox' => $sandbox,
					'APIUsername' => $api_username,
					'APIPassword' => $api_password,
					'APISignature' => $api_signature,
					'PrintHeaders' => $print_headers,
					'LogResults' => $log_results,
					'LogPath' => $log_path,
					);

$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);

// Prepare request arrays
$DCFields = array(
					'authorizationid' => '', 				// Required. The authorization identification number of the payment you want to capture. This is the transaction ID returned from DoExpressCheckoutPayment or DoDirectPayment.
					'amt' => '', 							// Required. Must have two decimal places.  Decimal separator must be a period (.) and optional thousands separator must be a comma (,)
					'completetype' => '', 					// Required.  The value Complete indicates that this is the last capture you intend to make.  The value NotComplete indicates that you intend to make additional captures.
					'currencycode' => '', 					// Three-character currency code
					'invnum' => '', 						// Your invoice number
					'note' => '', 							// Informational note about this setlement that is displayed to the buyer in an email and in his transaction history.  255 character max.
					'softdescriptor' => '', 				// Per transaction description of the payment that is passed to the customer's credit card statement.
					'msgsubid' => '', 						// A message ID used for idempotence to uniquely identify a message.  This ID can later be used to request the latest results for a previous request without generating a new request.  Examples of this include requests due to timeouts or errors during the original request.  38 Char Max
					'storeid' => '', 						// ID of the merchant store.  This field is required for point-of-sale transactions.  Max: 50 char
					'terminalid' => ''						// ID of the terminal.  50 char max.
				);

$PayPalRequestData = array('DCFields' => $DCFields);

// Pass data into class for processing with PayPal and load the response array into $PayPalResult
$PayPalResult = $PayPal->DoCapture($PayPalRequestData);

// Write the contents of the response array to the screen for demo purposes.
echo '<pre />';
print_r($PayPalResult);
?>


text:
<!DOCTYPE html>

    <title>three-mesh-bvh - Geometry Voxelization</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

		Demonstration of voxelizing a mesh with the ability to detect the inside and outside of a model.


text:
var util = require("../util");
var AbstractEmission = require("./AbstractEmission.js");
var EmissionTypes = require("./EmissionTypes.js");

function RandomEmission() {
	AbstractEmission.call(this);

	this._maxParticles = 0;
	this._emissionRate = 0;
}

util.inherit(RandomEmission, AbstractEmission);

RandomEmission.prototype.howMany = function(deltaTime, particlesCount) {
	if (particlesCount < this.maxParticles) {
		var count = Math.round(util.Random.uniform(0, Math.ceil(this.emissionRate * deltaTime)));
		var total = particlesCount + count;
		return total > this._maxParticles ? this.maxParticles - particlesCount : count;
	}

	return 0;
};

Object.defineProperty(RandomEmission.prototype, "emissionRate", {
	get: function() {
		return this._emissionRate;
	},
	set: function(value) {
		this._emissionRate = Math.max(0, value);
	}
});

Object.defineProperty(RandomEmission.prototype, "maxParticles", {
	get: function() {
		return this._maxParticles;
	},
	set: function(value) {
		this._maxParticles = Math.max(0, value);
	}
});

RandomEmission.prototype.getName = function() {
	return EmissionTypes.RANDOM;
};

module.exports = RandomEmission;


text:
require "Apollo"
require "Window"
require "GameLib"
require "GroupLib"
require "MatchingGameLib"
require "MatchMakingLib"

-----------------------------------------------------------------------------------------------
-- ReQueue Module Definition
-----------------------------------------------------------------------------------------------
local ReQueue = {
  uiMapperLib = "uiMapper:0.9.3",
  uiMapperPath = "libs/_uiMapper/",
  EnumQueueType = {
    SoloQueue = 0,
    GroupQueue = 1
  },
  defaults = {},
  config = {},
  version = "0.5.2",
  author = "Zod Bain@Jabbit"
}

local InInstanceGroup = GroupLib.InInstance
local InGroup = GroupLib.InGroup
local AmILeader = GroupLib.AmILeader
local Queue = MatchMakingLib.Queue
local QueueAsGroup = MatchMakingLib.QueueAsGroup
local IsCharacterLoaded = GameLib.IsCharacterLoaded
local IsRoleCheckActive = MatchingGameLib.IsRoleCheckActive
local ConfirmRole = MatchingGameLib.ConfirmRole
local DeclineRoleCheck = MatchingGameLib.DeclineRoleCheck
local IsInGameInstance = MatchingGameLib.IsInGameInstance
local IsFinished = MatchingGameLib.IsFinished
local IsQueuedForMatching = MatchMakingLib.IsQueuedForMatching
local IsQueuedAsGroupForMatching = MatchMakingLib.IsQueuedAsGroupForMatching
local GetMatchMakingEntries = MatchMakingLib.GetMatchMakingEntries
local Roles = MatchMakingLib.Roles
local GetEligibleRoles = MatchMakingLib.GetEligibleRoles
local next = next
-----------------------------------------------------------------------------------------------
-- Initialization
-----------------------------------------------------------------------------------------------
function ReQueue:new(o)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  self.lastQueueData = {}
  self.inInstanceGroup = InInstanceGroup()
  self.MatchMaker = nil
  self.newQueueData = false
  self.queuesToLeave = 0
  self.leftMatch = false
  return o
end

function ReQueue:Init()
  Apollo.RegisterAddon(self, true, "ReQueue", {self.uiMapperLib, "MatchMaker"})
end

function ReQueue:GetDefaults()
  return {
    autoQueue = false,
    queueType = self.EnumQueueType.SoloQueue,
    ignoreWarning = false,
    autoRoleSelect = true
  }
end

-----------------------------------------------------------------------------------------------
-- ReQueue OnLoad
-----------------------------------------------------------------------------------------------
function ReQueue:OnLoad()
  self.defaults = self:GetDefaults()
  self.config = self:GetDefaults()
  Apollo.GetPackage("Gemini:Hook-1.0").tPackage:Embed(self)

  Apollo.RegisterSlashCommand("requeue", "OnSlashCommand", self)
  Apollo.RegisterSlashCommand("rq", "OnSlashCommand", self)

  Apollo.RegisterEventHandler("Group_Left", "OnGroupLeave", self)
  Apollo.RegisterEventHandler("Group_Join", "OnGroupJoin", self)
  Apollo.RegisterEventHandler("Group_MemberPromoted", "UpdateGroupQueueButtonStatus", self)
  Apollo.RegisterEventHandler("MatchingEligibilityChanged", "UpdateGroupQueueButtonStatus", self)
  Apollo.RegisterEventHandler("CharacterCreated", "OnCharacterCreated", self)
  Apollo.RegisterEventHandler("MatchLeft", "OnLeaveMatch", self)
  Apollo.RegisterEventHandler("MatchingLeaveQueue", "OnLeaveQueue", self)

  self.MatchMaker = Apollo.GetAddon("MatchMaker")

  self:InitHooks()

  self.xmlDoc = XmlDoc.CreateFromFile("ReQueue.xml")

  local uiMapper = Apollo.GetPackage(self.uiMapperLib).tPackage
  self.ui = uiMapper:new({
      container = self.config,
      defaults = self.defaults,
      name = "ReQueue Configuration",
      author = self.author,
      version = self.version,
      path = self.uiMapperPath,
    }
  ):build(self.BuildConfig, self)
end

function ReQueue:InitHooks()
  self:Hook(MatchMakingLib, "Queue")
  self:Hook(MatchMakingLib, "QueueAsGroup")
  self:Hook(MatchMakingLib, "LeaveAllQueues")
  self:PostHook(self.MatchMaker, "OnRoleCheck")
  self:RawHook(self.MatchMaker, "OnSoloQueue")
  self:RawHook(self.MatchMaker, "OnGroupQueue")
end

-----------------------------------------------------------------------------------------------
-- ReQueue Hooks
-----------------------------------------------------------------------------------------------
function ReQueue:OnRoleCheck()
  if self.config.autoRoleSelect and #self:GetSelectedRoles() > 0 then
    self.MatchMaker:OnAcceptRole()
  end
end

function ReQueue:LeaveAllQueues()
  self.queuesToLeave = 0
  local size = #self.lastQueueData
  for i = 1, size do
    local queueData = self.lastQueueData[i]
    if queueData:IsQueued() or queueData:IsQueuedAsGroup() then
      self.queuesToLeave = self.queuesToLeave + 1
    end
  end
end

function ReQueue:Queue(queueData, queueOptions)
  self.config.queueType = self.EnumQueueType.SoloQueue
  self:OnQueue(queueData, queueOptions)
end

function ReQueue:QueueAsGroup(queueData, queueOptions)
  self.config.queueType = self.EnumQueueType.GroupQueue
  self:OnQueue(queueData, queueOptions)
end

function ReQueue:OnQueue(queueData, queueOptions)
  if self:IsQueued() then
    for _, v in next, queueData do
      table.insert(self.lastQueueData, v)
    end
    self.newQueueData = true
  else
    self.newQueueData = false
    self.lastQueueData = queueData
  end
  self.queueOptions = queueOptions
end

--Contentfinder queue events, here we start the queue after getting the data
function ReQueue:OnSoloQueue()
  self:Queue(self.MatchMaker.arMatchesToQueue, self:GetQueueOptions())
  self:OnSlashCommand()
end

function ReQueue:OnGroupQueue()
  self:QueueAsGroup(self.MatchMaker.arMatchesToQueue, self:GetQueueOptions())
  self:OnSlashCommand()
end
-----------------------------------------------------------------------------------------------
-- ReQueue Events
-----------------------------------------------------------------------------------------------
function ReQueue:OnSlashCommand(_, args)
  if args == "config" then
    self:OnConfigure()
    return
  elseif args == "roles" or args == "role" then
    self:DisplayRoleConfirm()
    return
  end

  if not self.newQueueData and self:IsQueued() then
    self:ToggleQueueStatusWindow()
    return
  end

  if IsInGameInstance() and not IsFinished() then
    return
  end

  if self:IsQueueDataEmpty() then
    --TODO: Display a message
    return
  end

  if self:IsQueueingSoloInGroup() and not self.config.ignoreWarning then
    self:DisplaySoloQueueWarning()
  else
    self:StartQueue()
  end
end

function ReQueue:OnGroupLeave()
  if self.inInstanceGroup then
    self.inInstanceGroup = false
    --TODO: Auto ReQueue here?

    --Group_Left does not get fired when leaving a normal party while
    --being in an instance party so we have to check again to be sure
    if not InGroup() then
      self:OnGroupLeave()
    end
  else --Left all groups
    self.config.queueType = self.EnumQueueType.SoloQueue
    self:SetConfig("ignoreWarning", false)
  end
end

function ReQueue:OnCharacterCreated()
  self:LoadSaveData()
end

function ReQueue:OnGroupJoin()
  self.inInstanceGroup = InInstanceGroup()
end

function ReQueue:OnSave(eType)
  if eType ~= GameLib.CodeEnumAddonSaveLevel.Character then
    return nil
  end

  local saveData = {
    config = self.config,
    autoQueue = self.autoQueue,
    lastQueueData = {},
    queueOptions = self.queueOptions
  }

  local size = #self.lastQueueData
  for i = 1, size do
    local queueData = self.lastQueueData[i]
    table.insert(saveData.lastQueueData, self:SerializeMatchingGame(queueData))
  end
  return saveData
end

function ReQueue:OnRestore(eType, saveData)
  if eType ~= GameLib.CodeEnumAddonSaveLevel.Character then
    return
  end
  self.saveData = saveData

  --When logging in wait for character to be loaded
  if IsCharacterLoaded() then
    self:LoadSaveData()
  end
end

function ReQueue:LoadSaveData()
  if not self.saveData then
    return
  end

  for k, _ in next, self.config do
    if self.saveData.config[k] ~= nil then
      self.config[k] = self.saveData.config[k]
    end
  end

  if not InGroup() then
    self.config.queueType = self.defaults.queueType
    self:SetConfig("ignoreWarning", self.defaults.ignoreWarning)
  end

  self.lastQueueData = {}
  for _, qd in pairs(self.saveData.lastQueueData or {}) do
    table.insert(self.lastQueueData, self:UnWrapSerializedMatchingGame(qd))
  end
  self.queueOptions = self.saveData.queueOptions
  self.saveData = nil
end

function ReQueue:OnLeaveMatch()
  self.leftMatch = true
end

function ReQueue:OnLeaveQueue()
  if self.leftMatch then
    self.leftMatch = false
    if AmILeader() then
      self.newQueueData = true
    end
    return
  end

  if self.queuesToLeave > 0 then
    self.queuesToLeave = self.queuesToLeave - 1
    return
  end

  if not self:IsQueued() then
    return
  end

  self:RemoveNotQueuedEntries()
end
-----------------------------------------------------------------------------------------------
-- ReQueue Functions
-----------------------------------------------------------------------------------------------
function ReQueue:OnConfigure()
  if self.ui then
    self.ui.wndMain:Show(true,true)
  end
end

function ReQueue:IsQueueingSoloInGroup()
  return self.config.queueType == self.EnumQueueType.SoloQueue and InGroup()
end

function ReQueue:IsQueueDataEmpty()
  return #self.lastQueueData == 0
end

function ReQueue:GetGroupQueueButtonStatus()
  local buttonEnabled = AmILeader()
  if not buttonEnabled then
    return buttonEnabled
  end

  local size = #self.lastQueueData
  for i = 1, size do
    local queueData = self.lastQueueData[i]
    buttonEnabled = queueData:DoesGroupMeetRequirements()
    if not buttonEnabled then
      break
    end
  end
  return buttonEnabled
end

function ReQueue:UpdateGroupQueueButtonStatus()
  if self.wndSoloQW then
    self.wndSoloQW:FindChild("GroupQueueButton"):Enable(self:GetGroupQueueButtonStatus())
  end
end

function ReQueue:DisplayRoleConfirm()
  if not self.xmlDoc or self.wndRoleConfirm ~= nil then
    return
  elseif not self.xmlDoc:IsLoaded() then
    self.xmlDoc:RegisterCallback("DisplayRoleConfirm", self)
    return
  end

  self.wndRoleConfirm = Apollo.LoadForm(self.xmlDoc, "RoleConfirm", nil, self)

  self.wndRoleConfirm:Show(true)
  self.wndRoleConfirm:ToFront()
end

function ReQueue:DisplaySoloQueueWarning()
  if not self.xmlDoc or self.wndSoloQW ~= nil then
    return
  elseif not self.xmlDoc:IsLoaded() then
    self.xmlDoc:RegisterCallback("DisplaySoloQueueWarning", self)
    return
  end

  self.wndSoloQW = Apollo.LoadForm(self.xmlDoc, "SoloQueueWarning", nil, self)

  self:UpdateGroupQueueButtonStatus()
  self.wndSoloQW:FindChild("RememberCheckBox"):SetCheck(false)
  self.wndSoloQW:Show(true)
  self.wndSoloQW:ToFront()
end

function ReQueue:StartQueue()
  self.newQueueData = false
  if self.config.queueType == self.EnumQueueType.SoloQueue then
    Queue(self.lastQueueData, self.queueOptions)
  else
    QueueAsGroup(self.lastQueueData, self.queueOptions)
  end
end

function ReQueue:SerializeMatchingGame(matchingGame)
  local t = {
    bIsRandom = matchingGame:IsRandom(),
    bIsVeteran = matchingGame:IsVeteran()
  }
  for k, v in pairs(matchingGame:GetInfo()) do
    t[k] = v
  end
  return t
end

function ReQueue:UnWrapSerializedMatchingGame(serialized)
  local matchingGame = nil
  local matchingGames = GetMatchMakingEntries(
    serialized.eMatchType,
    serialized.bIsVeteran,
    true
  )
  for _, mg in next, matchingGames do
    local found = true
    local cnt = 0
    for k, v in next, mg:GetInfo() do
      if serialized[k] ~= v then
        found = false
        break
      end
      cnt = cnt + 1
    end
    self.debug = self.debug or ""
    self.debug = self.debug .. " " .. tostring(cnt)
    if serialized.bIsRandom ~= mg:IsRandom() then
      found = false
    end
    if found then
      matchingGame = mg
      break
    end
  end
  return matchingGame
end

function ReQueue:ToggleQueueStatusWindow()
  local wnd = self.MatchMaker.tWndRefs.wndQueueStatus
  if wnd and wnd:IsVisible() then
    self.MatchMaker:OnCloseQueueStatus()
  else
    self.MatchMaker:OnShowQueueStatus()
  end
end

function ReQueue:GetQueueOptions()
  return self.MatchMaker.tQueueOptions[self.MatchMaker.eSelectedMasterType]
end

function ReQueue:RemoveNotQueuedEntries()
  --iterate backwards and remove not queued entries
  for i = #self.lastQueueData, 1, -1 do
    local entry = self.lastQueueData[i]
    if not entry:IsQueued() and not entry:IsQueuedAsGroup() then
      table.remove(self.lastQueueData, i)
    end
  end
end

function ReQueue:IsQueued()
  return IsQueuedForMatching() or IsQueuedAsGroupForMatching()
end
---------------------------------------------------------------------------------------------------
-- SoloQueueWarningForm Functions
---------------------------------------------------------------------------------------------------
function ReQueue:SetConfig(map, value)
  self.config[map] = value
  if self.ui and self.ui.wndMain then
    self.ui.wndMain:FindChild(self.ui.conventions.controlPrefix .. map):SetCheck(value)
  end
end

function ReQueue:OnButtonGroupQueue()
  self:OnButtonUse(self.EnumQueueType.GroupQueue)
end

function ReQueue:OnButtonSoloQueue()
  self:OnButtonUse(self.EnumQueueType.SoloQueue)
end

function ReQueue:OnButtonUse(queueType)
  self.config.queueType = queueType
  self:SetConfig("ignoreWarning", self.wndSoloQW:FindChild("RememberCheckBox"):IsChecked())

  self:OnButtonDecline()
  self:StartQueue()
end

function ReQueue:OnButtonDecline()
  self.wndSoloQW:Close()
end

function ReQueue:OnSoloQWClosed()
  --free memory
  self.wndSoloQW = nil
end

---------------------------------------------------------------------------------------------------
-- ConfirmRole Form Functions
---------------------------------------------------------------------------------------------------
function ReQueue:OnAcceptRole()
  if IsRoleCheckActive() then
    ConfirmRole(self:GetSelectedRoles())
  end
  self.wndRoleConfirm:Close()
end

function ReQueue:OnCancelRole()
  if IsRoleCheckActive() then
    DeclineRoleCheck()
  end
  self.wndRoleConfirm:Close()
end

function ReQueue:OnToggleRoleCheck(wndHandler, wndControl)
  if wndHandler ~= wndControl then
    return
  end

  self.MatchMaker:HelperToggleRole(wndHandler:GetData(), self.MatchMaker.eSelectedMasterType, wndHandler:IsChecked())

  local selectedRoles = self:GetSelectedRoles()
  self.wndRoleConfirm:FindChild("AcceptButton"):Enable(selectedRoles and #selectedRoles > 0)
end

function ReQueue:GetSelectedRoles()
  return self.MatchMaker.tQueueOptions[self.MatchMaker.eSelectedMasterType].arRoles
end

function ReQueue:OnRoleConfirmClosed()
  --free memory
  self.wndRoleConfirm = nil
end

function ReQueue:OnRoleConfirmShow()
  local roleConfirmButtons = {
    [Roles.Tank] = self.wndRoleConfirm:FindChild("TankBtn"),
    [Roles.Healer] = self.wndRoleConfirm:FindChild("HealerBtn"),
    [Roles.DPS] = self.wndRoleConfirm:FindChild("DPSBtn"),
  }

  for role, wndButton in pairs(roleConfirmButtons) do
    wndButton:Enable(false)
    wndButton:SetData(role)
  end

  for _, role in next, GetEligibleRoles() do
    roleConfirmButtons[role]:Enable(true)
  end

  local selectedRoles = self:GetSelectedRoles()
  for _, role in next, selectedRoles do
    roleConfirmButtons[role]:SetCheck(true)
  end

  self.wndRoleConfirm:FindChild("AcceptButton"):Enable(#selectedRoles > 0)
end
-----------------------------------------------------------------------------------------------
-- ReQueue Instance
-----------------------------------------------------------------------------------------------
local ReQueueInst = ReQueue:new()
ReQueueInst:Init()


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	oldNeo "koding/databases/neo4j"
	"koding/db/mongodb"
	"koding/tools/amqputil"
	"koding/tools/config"
	"koding/tools/logger"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/siesta/neo4j"
	"github.com/streadway/amqp"
	"gopkg.in/mgo.v2"
)

var log = logger.New("sync")

type strToInf map[string]interface{}

var (
	GRAPH_URL           = config.Current.Neo4j.Write + ":" + strconv.Itoa(config.Current.Neo4j.Port)
	EXCHANGENAME        = "graphFeederExchange"
	MAX_ITERATION_COUNT = 50
	GUEST_GROUP_ID      = "51f41f195f07655e560001c1"
	SLEEPING_TIME       = 100 * time.Millisecond
)

func main() {
	log.Info("Sync worker started")

	amqpChannel := connectToRabbitMQ()
	log.Info("Connected to Rabbit")

	err := mongodb.Run("relationships", createQuery(amqpChannel))
	if err != nil {
		log.Fatalf("Connecting to Mongo: %v", err)
	}
}

func createQuery(amqpChannel *amqp.Channel) func(coll *mgo.Collection) error {

	return func(coll *mgo.Collection) error {
		filter := strToInf{
			"targetName": strToInf{"$nin": oldNeo.NotAllowedNames},
			"sourceName": strToInf{"$nin": oldNeo.NotAllowedNames},
		}
		query := coll.Find(filter)

		totalCount, err := query.Count()
		if err != nil {
			log.Error("While getting count, exiting: %v", err)
			return err
		}

		skip := config.Skip
		// this is a starting point
		index := skip
		// this is the item count to be processed
		limit := config.Count
		// this will be the ending point
		count := index + limit

		var result oldNeo.Relationship

		iteration := 0
		for {
			// if we reach to the end of the all collection, exit
			if index >= totalCount {
				log.Info("All items are processed, exiting")
				break
			}

			// this is the max re-iterating count
			if iteration == MAX_ITERATION_COUNT {
				break
			}

			// if we processed all items then exit
			if index == count {
				break
			}

			iter := query.Skip(index).Limit(count - index).Iter()
			for iter.Next(&result) {
				time.Sleep(SLEEPING_TIME)

				if relationshipNeedsToBeSynced(result) {
					createRelationship(result, amqpChannel)
				}

				index++
				log.Info("Index: %v", index)
			}

			if err := iter.Close(); err != nil {
				log.Error("Iteration failed: %v", err)
			}

			if iter.Timeout() {
				continue
			}

			log.Info("iter existed, starting over from %v  -- %v  item(s) are processsed on this iter", index+1, index-skip)
			iteration++
		}

		if iteration == MAX_ITERATION_COUNT {
			log.Info("Max iteration count %v reached, exiting", iteration)
		}
		log.Info("Synced %v entries on this process", index-skip)

		return nil
	}
}

func connectToRabbitMQ() *amqp.Channel {
	conn := amqputil.CreateConnection("syncWorker")
	amqpChannel, err := conn.Channel()
	if err != nil {
		panic(err)
	}
	return amqpChannel
}

func createRelationship(rel oldNeo.Relationship, amqpChannel *amqp.Channel) {
	data := make([]strToInf, 1)
	data[0] = strToInf{
		"_id":        rel.Id,
		"sourceId":   rel.SourceId,
		"sourceName": rel.SourceName,
		"targetId":   rel.TargetId,
		"targetName": rel.TargetName,
		"as":         rel.As,
	}

	eventData := strToInf{"event": "RelationshipSaved", "payload": data}

	neoMessage, err := json.Marshal(eventData)
	if err != nil {
		log.Error("unmarshall error: %v", err)
		return
	}

	amqpChannel.Publish(
		EXCHANGENAME, // exchange name
		"",           // key
		false,        // mandatory
		false,        // immediate
		amqp.Publishing{
			Body: neoMessage,
		},
	)
}

func relationshipNeedsToBeSynced(result oldNeo.Relationship) bool {
	if result.SourceId.Hex() == GUEST_GROUP_ID || result.TargetId.Hex() == GUEST_GROUP_ID {
		return false
	}

	exists, sourceId := checkNodeExists(result.SourceId.Hex())
	if exists != true {
		logError(result, "No source node")
		return true
	}

	exists, targetId := checkNodeExists(result.TargetId.Hex())
	if exists != true {
		logError(result, "No target node")
		return true
	}

	// flip JGroup relationships since they take a long time to check
	var flipped = false
	if result.SourceName == "JGroup" {
		flipped = true

		tempId := sourceId
		sourceId = targetId
		targetId = tempId
	}

	exists = checkRelationshipExists(sourceId, targetId, result.As, flipped)
	if exists != true {
		logError(result, "No relationship")
		return true
	}

	// everything is fine
	return false
}

func getAndParse(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

func checkRelationshipExists(sourceId, targetId, relType string, flipped bool) bool {
	url := fmt.Sprintf("%v/db/data/node/%v/relationships/all/%v", GRAPH_URL, sourceId, relType)

	body, err := getAndParse(url)
	if err != nil {
		return false
	}

	relResponse := make([]neo4j.RelationshipResponse, 1)
	err = json.Unmarshal(body, &relResponse)
	if err != nil {
		return false
	}

	var numberofRelsFound = 0
	var relIds []string

	for _, rl := range relResponse {
		var checkPos string
		if flipped {
			checkPos = rl.Start
		} else {
			checkPos = rl.End
		}

		id := strings.SplitAfter(checkPos, GRAPH_URL+"/db/data/node/")[1]
		if targetId == id {
			numberofRelsFound++
			relIds = append(relIds, getRelIdFromUrl(rl.Self))
		}
	}

	switch numberofRelsFound {
	case 0:
		return false
	case 1:
		return true
	default:
		log.Info("multiple '%v' rel %v", relType, relIds)

		if relType == "member" || relType == "creator" || relType == "author" {
			deleteDuplicateRel(relIds[1:])
			log.Info("deleted multiple '%v' rel", relType)
		}
	}

	return true
}

func deleteDuplicateRel(relIds []string) {
	neo4jConnection := neo4j.Connect(GRAPH_URL)
	batch := neo4jConnection.NewBatch()

	for _, id := range relIds {
		rel := neo4j.Relationship{Id: id}
		batch.Delete(&rel)
	}

	_, err := batch.Execute()
	if err != nil {
		log.Error("err deleting rel: %v", err)
	}
}

func checkNodeExists(id string) (bool, string) {
	url := fmt.Sprintf("%v/db/data/index/node/koding/id/%v", GRAPH_URL, id)
	body, err := getAndParse(url)
	if err != nil {
		return false, ""
	}

	nodeResponse := make([]neo4j.NodeResponse, 1)
	err = json.Unmarshal(body, &nodeResponse)
	if err != nil {
		return false, ""
	}

	if len(nodeResponse) < 1 {
		return false, ""
	}

	node := nodeResponse[0]
	idd := getNodeIdFromUrl(node.Self)

	nodeId := string(idd)
	if nodeId == "" {
		return false, ""
	}

	return true, nodeId
}

func getNodeIdFromUrl(nodeSelf string) string {
	return strings.SplitAfter(nodeSelf, GRAPH_URL+"/db/data/node/")[1]
}

func getRelIdFromUrl(nodeSelf string) string {
	return strings.SplitAfter(nodeSelf, GRAPH_URL+"/db/data/relationship/")[1]
}

func logError(result oldNeo.Relationship, errMsg string) {
	log.Error("id: %v, type: %v, source: {%v %v} target: {%v %v}; err: %v", result.SourceId.Hex(), result.As, result.SourceId.Hex(), result.SourceName, result.TargetId.Hex(), result.TargetName, errMsg)
}


text:
<component name="libraryTable">
  <library name="TornadoFX">
    <CLASSES>
      <root url="file://$PROJECT_DIR$/lib/tornadoFX" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="file://$PROJECT_DIR$/lib/tornadoFX" />
    </SOURCES>
    <jarDirectory url="file://$PROJECT_DIR$/lib/tornadoFX" recursive="false" />
    <jarDirectory url="file://$PROJECT_DIR$/lib/tornadoFX" recursive="false" type="SOURCES" />
  </library>
</component>


text:
<project default="jars" name="Create Runnable Jar for Project AndroidSSLBypass with libraries in sub-folder">
    <property file="local.properties"/>
    <property file="build.properties"/>
    <property file="env.properties"/>
    <!-- Java 1.6 and earlier on Mac OS X has the tools.jar classes in class.jar... -->
    <available property="jdi.tools.location" file="${java.home}/../Classes/classes.jar" value="${java.home}/../Classes/classes.jar" />
    <!-- Everything else should use the proper location...
    	however ../ is required because the default ant config sets to jre dir (?)
    -->
    <available property="jdi.tools.location" file="${java.home}/lib/tools.jar" value="${java.home}/lib/tools.jar" />
    <available property="jdi.tools.location" file="${java.home}/../lib/tools.jar" value="${java.home}/../lib/tools.jar" />
    <echo message="Location of java.home: ${java.home}, location of JDI tools/classes jar: ${jdi.tools.location}"/>

    <target name="copy_libs">
        <copy file="${jdi.tools.location}" todir="libs"/>
        <copy file="${ddmlib.location}" todir="libs"/>
    </target>

    <target name="compile" depends="copy_libs">
        <mkdir dir="bin"/>
        <javac srcdir="src" destdir="bin" includeantruntime="false">
            <classpath>
                <path>
                    <fileset dir="libs" includes="**/*.jar" />
                </path>
            </classpath>
        </javac>
    </target>

    <target name="jar_asb" depends="compile">
        <jar destfile="asb.jar" indexMetaInf="true">
            <manifest>
                <attribute name="Main-Class" value="com.isecpartners.android.jdwp.CommandLine"/>
                <attribute name="Class-Path" value=". libs/ddmlib.jar libs/log4j-1.2.17.jar libs/tools.jar libs/jython-standalone-2.5.3.jar libs/asg.cliche-020310.jar libs/args4j-2.0.21.jar"/>
	</manifest>
	<fileset dir="bin"/>
	<service type="com.isecpartners.android.jdwp.pluginservice.JDIPlugin">
		<provider classname="com.isecpartners.android.jdwp.plugin.SSLBypassJDIPlugin"/>
		<provider classname="com.isecpartners.android.jdwp.plugin.JythonConsoleJDIPlugin"/>
		<provider classname="com.isecpartners.android.jdwp.plugin.TraceMethodsJDIPlugin"/>
		<provider classname="com.isecpartners.android.jdwp.plugin.TestJDIPlugin"/>
	</service>
       </jar>
    </target>

    <target name="jar_plugins">
        <jar destfile="plugins/plugins.jar">
            <fileset dir="bin/com/isecpartners/android/jdwp/plugin/"/>
        </jar>
    </target>

    <target name="jars" depends="jar_asb,jar_plugins" />

    <target name="clean">
        <delete file="asb.jar"/>
        <delete file="plugins/plugins.jar"/>
        <delete dir="bin"/>
        <delete file="libs/ddmlib.jar" />
        <delete file="libs/classes.jar" />
        <delete file="libs/tools.jar" />
    </target>

</project>


text:
import ServiceManager from '../services/SvcManager'
import { serverConfig as config } from 'c0nfig'
import express from 'express'
import fs from 'fs'

module.exports = function() {

  var router = express.Router()

  /////////////////////////////////////////////////////////////////////////////
  // GET /buckets
  //
  //
  /////////////////////////////////////////////////////////////////////////////
  router.get('/buckets', async (req, res) =>{

    try {

      // obtain forge service
      var forgeSvc = ServiceManager.getService(
        'ForgeSvc')

      // request 2legged token
      var token = await forgeSvc.get2LeggedToken()

      // obtain oss service
      var ossSvc = ServiceManager.getService('OssSvc')

      // get list of bucket by passing valid token
      var response = await ossSvc.getBuckets(
        token.access_token)

      // send json-formatted response
      res.json(response)

    } catch (ex) {

      res.status(ex.statusCode || 500)
      res.json(ex)
    }
  })

  /////////////////////////////////////////////////////////////////////////////
  // GET /buckets/:bucketKey/details
  //
  //
  /////////////////////////////////////////////////////////////////////////////
  router.get('/buckets/:bucketKey/details', async (req, res) =>{

    try {

      var bucketKey = req.params.bucketKey

      var forgeSvc = ServiceManager.getService(
        'ForgeSvc')

      var token = await forgeSvc.get2LeggedToken()

      var ossSvc = ServiceManager.getService('OssSvc')

      var response = await ossSvc.getBucketDetails(
        token.access_token, bucketKey)

      res.json(response)

    } catch (ex) {

      res.status(ex.statusCode || 500)
      res.json(ex)
    }
  })

  /////////////////////////////////////////////////////////////////////////////
  // GET /buckets/:bucketKey/objects
  //
  //
  /////////////////////////////////////////////////////////////////////////////
  router.get('/buckets/:bucketKey/objects', async (req, res) =>{

    try {

      var bucketKey = req.params.bucketKey

      var forgeSvc = ServiceManager.getService(
        'ForgeSvc')

      var token = await forgeSvc.get2LeggedToken()

      var ossSvc = ServiceManager.getService('OssSvc')

      var response = await ossSvc.getObjects(
        token.access_token, bucketKey)

      res.send(response)

    } catch (ex) {

      console.log(ex)

      res.status(ex.statusCode || 500)
      res.json(ex)
    }
  })

  /////////////////////////////////////////////////////////////////////////////
  // GET /buckets/:bucketKey/objects/:objectKey/details
  //
  //
  /////////////////////////////////////////////////////////////////////////////
  router.get('/buckets/:bucketKey/objects/:objectKey/details', async (req, res) =>{

    try {

      var bucketKey = req.params.bucketKey

      var objectKey = req.params.objectKey

      var forgeSvc = ServiceManager.getService(
        'ForgeSvc')

      var token = await forgeSvc.get2LeggedToken()

      var ossSvc = ServiceManager.getService('OssSvc')

      var response = await ossSvc.getObjectDetails(
        token.access_token,
        bucketKey,
        objectKey)

      res.json(response)

    } catch (ex) {

      res.status(ex.statusCode || 500)
      res.json(ex)
    }
  })

  /////////////////////////////////////////////////////////////////////////////
  // GET /buckets/:bucketKey/objects/:objectKey
  //
  //
  /////////////////////////////////////////////////////////////////////////////
  router.get('/buckets/:bucketKey/objects/:objectKey', async (req, res) =>{

    try {

      var bucketKey = req.params.bucketKey

      var objectKey = req.params.objectKey

      var forgeSvc = ServiceManager.getService(
        'ForgeSvc')

      var ossSvc = ServiceManager.getService(
        'OssSvc')

      var token = await forgeSvc.get2LeggedToken()

      var object = await ossSvc.getObject(
        token.access_token,
        bucketKey,
        objectKey)

      res.end(object)

    } catch(ex) {

      console.log(ex)
    }
  })

  /////////////////////////////////////////////////////////////////////////////
  // POST /buckets
  //
  //
  /////////////////////////////////////////////////////////////////////////////
  router.post('/buckets', async (req, res) => {

    try {

      var bucketCreationData = req.body.bucketCreationData

      var forgeSvc = ServiceManager.getService(
        'ForgeSvc')

      var token = await forgeSvc.get2LeggedToken()

      var ossSvc = ServiceManager.getService('OssSvc')

      var response = await ossSvc.createBucket(
        token.access_token,
        bucketCreationData)

      res.json(response)

    } catch (ex) {

      console.log(ex)

      res.status(ex.statusCode || 500)
      res.json(ex)
    }
  })

  /////////////////////////////////////////////////////////////////////////////
  // DELETE /buckets/:bucketKey/objects/:objectKey
  //
  //
  /////////////////////////////////////////////////////////////////////////////
  router.delete('/buckets/:bucketKey/objects/:objectKey', async (req, res) =>{

    try {

      var bucketKey = req.params.bucketKey

      var objectKey = req.params.objectKey

      var forgeSvc = ServiceManager.getService(
        'ForgeSvc')

      var ossSvc = ServiceManager.getService(
        'OssSvc')

      var token = await forgeSvc.get2LeggedToken()

      var response = await ossSvc.deleteObject(
        token.access_token,
        bucketKey,
        objectKey)

      res.end(response)

    } catch(ex) {

      res.status(ex.statusCode || 500)
      res.json(ex)
    }
  })

  return router
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Gherkin.Util
{
    /// <summary>
    /// Pure DI. It resoves all dependencies after registering interface implementation.
    /// Concrete classes are automatically registered if not yet registered.
    /// </summary>
    public class DIContainer
    {
        /// <summary>
        /// Mapping contract type to implementation type
        /// </summary>
        private readonly Dictionary<Type, Type> m_TypeMapping = new Dictionary<Type, Type>();
        /// <summary>
        /// Singleton implementation of contract type
        /// </summary>
        private readonly Dictionary<Type, object> m_TypeImpl = new Dictionary<Type, object>();

        public void Register<TContract, TImplementation>()
        {
            m_TypeMapping[typeof(TContract)] = typeof(TImplementation);
        }

        public T Resolve<T>()
        {
            return (T)Resolve(typeof(T));
        }

        private object Resolve(Type contract)
        {
            if (m_TypeImpl.ContainsKey(contract))
            {
                return m_TypeImpl[contract];
            }

            if (!m_TypeMapping.ContainsKey(contract))
            {
                if (contract.IsInterface)
                    throw new ApplicationException(contract.Name + " must be registered before resoving it.");
                else
                    m_TypeMapping[contract] = contract;
            }

            return CreateObjectOf(contract);
        }

        private object CreateObjectOf(Type contract)
        {
            Type implType = m_TypeMapping[contract];
            ConstructorInfo[] constructors = implType.GetConstructors();
            if (constructors.Length == 0)
                throw new ApplicationException(implType.Name + " has no public constructors.");

            ConstructorInfo constructor = implType.GetConstructors()[0];    // create object by using 1st constructor

            ParameterInfo[] constructorParameters = constructor.GetParameters();
            List<object> parameters = new List<object>(constructorParameters.Length);
            foreach (ParameterInfo parameterInfo in constructorParameters)
            {
                if (Util.IsSimpleType(parameterInfo.ParameterType))
                {
                    // set default value for simple types, for string type null will be set
                    parameters.Add(null);
                }
                else
                {
                    // Recursively resolve parameters
                    parameters.Add(Resolve(parameterInfo.ParameterType));
                }
            }

            object impl = constructor.Invoke(parameters.ToArray());
            m_TypeImpl[contract] = impl;
            return impl;
        }
    }
}