text:
package org.apache.ignite.ml.nn;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.ignite.ml.dataset.Dataset;
import org.apache.ignite.ml.dataset.DatasetBuilder;
import org.apache.ignite.ml.dataset.primitive.builder.context.EmptyContextBuilder;
import org.apache.ignite.ml.dataset.primitive.builder.data.SimpleLabeledDatasetDataBuilder;
import org.apache.ignite.ml.dataset.primitive.context.EmptyContext;
import org.apache.ignite.ml.dataset.primitive.data.SimpleLabeledDatasetData;
import org.apache.ignite.ml.math.functions.IgniteBiFunction;
import org.apache.ignite.ml.math.functions.IgniteDifferentiableVectorToDoubleFunction;
import org.apache.ignite.ml.math.functions.IgniteFunction;
import org.apache.ignite.ml.math.primitives.matrix.Matrix;
import org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.nn.architecture.MLPArchitecture;
import org.apache.ignite.ml.nn.initializers.RandomInitializer;
import org.apache.ignite.ml.optimization.updatecalculators.ParameterUpdateCalculator;
import org.apache.ignite.ml.trainers.MultiLabelDatasetTrainer;
import org.apache.ignite.ml.util.Utils;

/**
 * Multilayer perceptron trainer based on partition based {@link Dataset}.
 *
 * @param <P> Type of model update used in this trainer.
 */
public class MLPTrainer<P extends Serializable> extends MultiLabelDatasetTrainer<MultilayerPerceptron> {
    /** Multilayer perceptron architecture supplier that defines layers and activators. */
    private IgniteFunction<Dataset<EmptyContext, SimpleLabeledDatasetData>, MLPArchitecture> archSupplier;

    /** Loss function to be minimized during the training. */
    private IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss;

    /** Update strategy that defines how to update model parameters during the training. */
    private UpdatesStrategy<? super MultilayerPerceptron, P> updatesStgy;

    /** Maximal number of iterations before the training will be stopped. */
    private int maxIterations = 100;

    /** Batch size (per every partition). */
    private int batchSize = 100;

    /** Maximal number of local iterations before synchronization. */
    private int locIterations = 100;

    /** Multilayer perceptron model initializer. */
    private long seed = 1234L;

    /**
     * Constructs a new instance of multilayer perceptron trainer.
     *
     * @param arch Multilayer perceptron architecture that defines layers and activators.
     * @param loss Loss function to be minimized during the training.
     * @param updatesStgy Update strategy that defines how to update model parameters during the training.
     * @param maxIterations Maximal number of iterations before the training will be stopped.
     * @param batchSize Batch size (per every partition).
     * @param locIterations Maximal number of local iterations before synchronization.
     * @param seed Random initializer seed.
     */
    public MLPTrainer(MLPArchitecture arch, IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss,
        UpdatesStrategy<? super MultilayerPerceptron, P> updatesStgy, int maxIterations, int batchSize,
        int locIterations, long seed) {
        this(dataset -> arch, loss, updatesStgy, maxIterations, batchSize, locIterations, seed);
    }

    /**
     * Constructs a new instance of multilayer perceptron trainer.
     *
     * @param archSupplier Multilayer perceptron architecture supplier that defines layers and activators.
     * @param loss Loss function to be minimized during the training.
     * @param updatesStgy Update strategy that defines how to update model parameters during the training.
     * @param maxIterations Maximal number of iterations before the training will be stopped.
     * @param batchSize Batch size (per every partition).
     * @param locIterations Maximal number of local iterations before synchronization.
     * @param seed Random initializer seed.
     */
    public MLPTrainer(IgniteFunction<Dataset<EmptyContext, SimpleLabeledDatasetData>, MLPArchitecture> archSupplier,
        IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss,
        UpdatesStrategy<? super MultilayerPerceptron, P> updatesStgy, int maxIterations, int batchSize,
        int locIterations, long seed) {
        this.archSupplier = archSupplier;
        this.loss = loss;
        this.updatesStgy = updatesStgy;
        this.maxIterations = maxIterations;
        this.batchSize = batchSize;
        this.locIterations = locIterations;
        this.seed = seed;
    }

    /** {@inheritDoc} */
    public <K, V> MultilayerPerceptron fit(DatasetBuilder<K, V> datasetBuilder,
        IgniteBiFunction<K, V, Vector> featureExtractor, IgniteBiFunction<K, V, double[]> lbExtractor) {

        return updateModel(null, datasetBuilder, featureExtractor, lbExtractor);
    }

    /** {@inheritDoc} */
    @Override protected <K, V> MultilayerPerceptron updateModel(MultilayerPerceptron lastLearnedModel,
        DatasetBuilder<K, V> datasetBuilder,
        IgniteBiFunction<K, V, Vector> featureExtractor, IgniteBiFunction<K, V, double[]> lbExtractor) {

        assert archSupplier != null;
        assert loss!= null;
        assert updatesStgy!= null;

        try (Dataset<EmptyContext, SimpleLabeledDatasetData> dataset = datasetBuilder.build(
            new EmptyContextBuilder<>(),
            new SimpleLabeledDatasetDataBuilder<>(featureExtractor, lbExtractor)
        )) {
            MultilayerPerceptron mdl;
            if (lastLearnedModel != null)
                mdl = lastLearnedModel;
            else {
                MLPArchitecture arch = archSupplier.apply(dataset);
                mdl = new MultilayerPerceptron(arch, new RandomInitializer(seed));
            }
            ParameterUpdateCalculator<? super MultilayerPerceptron, P> updater = updatesStgy.getUpdatesCalculator();

            for (int i = 0; i < maxIterations; i += locIterations) {

                MultilayerPerceptron finalMdl = mdl;
                int finalI = i;

                List<P> totUp = dataset.compute(
                    data -> {
                        P update = updater.init(finalMdl, loss);

                        MultilayerPerceptron mlp = Utils.copy(finalMdl);

                        if (data.getFeatures() != null) {
                            List<P> updates = new ArrayList<>();

                            for (int locStep = 0; locStep < locIterations; locStep++) {
                                int[] rows = Utils.selectKDistinct(
                                    data.getRows(),
                                    Math.min(batchSize, data.getRows()),
                                    new Random(seed ^ (finalI * locStep))
                                );

                                double[] inputsBatch = batch(data.getFeatures(), rows, data.getRows());
                                double[] groundTruthBatch = batch(data.getLabels(), rows, data.getRows());

                                Matrix inputs = new DenseMatrix(inputsBatch, rows.length, 0);
                                Matrix groundTruth = new DenseMatrix(groundTruthBatch, rows.length, 0);

                                update = updater.calculateNewUpdate(
                                    mlp,
                                    update,
                                    locStep,
                                    inputs.transpose(),
                                    groundTruth.transpose()
                                );

                                mlp = updater.update(mlp, update);
                                updates.add(update);
                            }

                            List<P> res = new ArrayList<>();
                            res.add(updatesStgy.locStepUpdatesReducer().apply(updates));

                            return res;
                        }

                        return null;
                    },
                    (a, b) -> {
                        if (a == null)
                            return b;
                        else if (b == null)
                            return a;
                        else {
                            a.addAll(b);
                            return a;
                        }
                    }
                );

                if (totUp == null)
                    return getLastTrainedModelOrThrowEmptyDatasetException(lastLearnedModel);

                P update = updatesStgy.allUpdatesReducer().apply(totUp);
                mdl = updater.update(mdl, update);
            }

            return mdl;
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Get the multilayer perceptron architecture supplier that defines layers and activators.
     *
     * @return The property value.
     */
    public IgniteFunction<Dataset<EmptyContext, SimpleLabeledDatasetData>, MLPArchitecture> getArchSupplier() {
        return archSupplier;
    }

    /**
     * Set up the multilayer perceptron architecture supplier that defines layers and activators.
     *
     * @param archSupplier The parameter value.
     * @return Model with the multilayer perceptron architecture supplier that defines layers and activators.
     */
    public MLPTrainer<P> withArchSupplier(
        IgniteFunction<Dataset<EmptyContext, SimpleLabeledDatasetData>, MLPArchitecture> archSupplier) {
        this.archSupplier = archSupplier;
        return this;
    }

    /**
     * Get the loss function to be minimized during the training.
     *
     * @return The property value.
     */
    public IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> getLoss() {
        return loss;
    }

    /**
     * Set up the loss function to be minimized during the training.
     *
     * @param loss The parameter value.
     * @return Model with the loss function to be minimized during the training.
     */
    public MLPTrainer<P> withLoss(
        IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss) {
        this.loss = loss;
        return this;
    }

    /**
     * Get the update strategy that defines how to update model parameters during the training.
     *
     * @return The property value.
     */
    public UpdatesStrategy<? super MultilayerPerceptron, P> getUpdatesStgy() {
        return updatesStgy;
    }

    /**
     * Set up the update strategy that defines how to update model parameters during the training.
     *
     * @param updatesStgy The parameter value.
     * @return Model with the update strategy that defines how to update model parameters during the training.
     */
    public MLPTrainer<P> withUpdatesStgy(
        UpdatesStrategy<? super MultilayerPerceptron, P> updatesStgy) {
        this.updatesStgy = updatesStgy;
        return this;
    }

    /**
     * Get the maximal number of iterations before the training will be stopped.
     *
     * @return The property value.
     */
    public int getMaxIterations() {
        return maxIterations;
    }

    /**
     * Set up the maximal number of iterations before the training will be stopped.
     *
     * @param maxIterations The parameter value.
     * @return Model with the maximal number of iterations before the training will be stopped.
     */
    public MLPTrainer<P> withMaxIterations(int maxIterations) {
        this.maxIterations = maxIterations;
        return this;
    }

    /**
     * Get the batch size (per every partition).
     *
     * @return The property value.
     */
    public int getBatchSize() {
        return batchSize;
    }

    /**
     * Set up the batch size (per every partition).
     *
     * @param batchSize The parameter value.
     * @return Model with the batch size (per every partition).
     */
    public MLPTrainer<P> withBatchSize(int batchSize) {
        this.batchSize = batchSize;
        return this;
    }

    /**
     * Get the maximal number of local iterations before synchronization.
     *
     * @return The property value.
     */
    public int getLocIterations() {
        return locIterations;
    }

    /**
     * Set up the maximal number of local iterations before synchronization.
     *
     * @param locIterations The parameter value.
     * @return Model with the maximal number of local iterations before synchronization.
     */
    public MLPTrainer<P>  withLocIterations(int locIterations) {
        this.locIterations = locIterations;
        return this;
    }

    /**
     * Get the multilayer perceptron model initializer.
     *
     * @return The property value.
     */
    public long getSeed() {
        return seed;
    }

    /**
     * Set up the multilayer perceptron model initializer.
     *
     * @param seed The parameter value.
     * @return Model with the multilayer perceptron model initializer.
     */
    public MLPTrainer<P>  withSeed(long seed) {
        this.seed = seed;
        return this;
    }

    /** {@inheritDoc} */
    @Override protected boolean checkState(MultilayerPerceptron mdl) {
        return true;
    }

    /**
     * Builds a batch of the data by fetching specified rows.
     *
     * @param data All data.
     * @param rows Rows to be fetched from the data.
     * @param totalRows Total number of rows in all data.
     * @return Batch data.
     */
    static double[] batch(double[] data, int[] rows, int totalRows) {
        int cols = data.length / totalRows;

        double[] res = new double[cols * rows.length];

        for (int i = 0; i < rows.length; i++)
            for (int j = 0; j < cols; j++)
                res[j * rows.length + i] = data[j * totalRows + rows[i]];

        return res;
    }
}


text:
class Renderable : public Component
{
public:

	Renderable(std::shared_ptr<Mesh> mesh, std::shared_ptr<Material> material)
		: Component{}
		, material{ material }
		, mesh{ mesh }
	{
	}

	const std::shared_ptr<Material> GetMaterial() const { return material; }
	const std::shared_ptr<Mesh> GetMesh() const { return mesh; }

private:

	virtual void Init() {};

private:

	std::shared_ptr<Material> material;
	std::shared_ptr<Mesh> mesh;

};

redpajama_set_name: RedPajamaGithub


text:
import fs from 'fs';

function get(type) {
    return new Promise((resolve, reject) => {
        fs.readFile(`./${type}.json`, (err, data) => {
            if (err)
                return reject(err);
            try {
                let str = data.toString();
                let json = JSON.parse(str);
                return resolve(json);
            }
            catch(e) {
                return reject(e);
            }
        });
    });
}

let api = {};
api.get = get;

export default api;


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

namespace Blog.Models
{
    public interface ICategoriesRepositories
    {
        int GetCategoryCountByUID(int uid);
        List<Categories> GetCategories(int uid, int PageIndex, int ListItemNum);
        IQueryable<Categories> GetCategoriesByUID(int uid);
        int AddCategories(Categories categories);
        bool CategoryExist(string cname,int uid);
        void DeleteCategory(int uid, int cid);
        void UpdateCategory(Categories category);
        IQueryable<ArticleCategoriesViewModel> GetArticleCategories(int uid);
    }
}


text:
package com.example.kamil.fotosforwebsite;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Comparator;

public class Photos extends AppCompatActivity
{
	private static final String TAG="Photos";
	private File photoDirectory;
	private File[] photos;
	private int current;
	private final static int REQUEST_IMAGES_DIRECTORY=1;
	private final static int REQUEST_IMAGES_FILE=2;
	private final static String LAST_DIRECTORY_PREFERENCE="LAST_OPENED";
	private static Bitmap getRotatedBitmap(final File imgFile)
	{
		Bitmap myBitmap=BitmapFactory.decodeFile(imgFile.getAbsolutePath());
		try
		{
			final ExifInterface exif=new ExifInterface(imgFile.getAbsolutePath());
			final int orientation=exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,1);
			final Matrix matrix=new Matrix();
			switch(orientation)
			{
				case 3:
					matrix.postRotate(180);
					myBitmap=Bitmap.createBitmap(myBitmap,0,0,myBitmap.getWidth(),myBitmap.getHeight(),matrix,true);
					break;
				case 6:
					matrix.postRotate(90);
					myBitmap=Bitmap.createBitmap(myBitmap,0,0,myBitmap.getWidth(),myBitmap.getHeight(),matrix,true);
					break;
				case 8:
					matrix.postRotate(90);
					myBitmap=Bitmap.createBitmap(myBitmap,0,0,myBitmap.getWidth(),myBitmap.getHeight(),matrix,true);
					break;
			}
		}catch(final IOException e)
		{
			e.printStackTrace();
		}
		return myBitmap;
	}

	@Override
	protected void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fotos);
	}

	@SuppressLint("NewApi")
	private File getRealPathFromURI(final Uri contentUri)
	{
		final String[] project={"_data"};
		try(Cursor cursor=getApplicationContext().getContentResolver()
				.query(contentUri,project,     // Which columns to return
				null,     // WHERE clause; which rows to return (all rows)
				null,     // WHERE clause selection arguments (none)
						null))
		{
			if(cursor==null)
				throw new AssertionError("cursor is null");
			final int column_index=cursor.getColumnIndexOrThrow("_data");
			if(cursor.moveToFirst())
			{
				String extracted=cursor.getString(column_index);
				final int index=extracted.lastIndexOf('/');
				return new File(extracted.substring(0,index));
			}
			throw new AssertionError("Cannot move cursor");
		}
	}

	@SuppressLint("NewApi")
	@Override
	protected void onActivityResult(final int requestCode,final int resultCode,final Intent data)
	{
		switch(requestCode)
		{
			case REQUEST_IMAGES_DIRECTORY:
			case REQUEST_IMAGES_FILE:
				if(resultCode!=RESULT_OK)
					return;
				current=0;
				final Uri uri=data.getData();
				if(requestCode==REQUEST_IMAGES_DIRECTORY)
					photoDirectory=new File(FileUtil.getFullPathFromTreeUri(uri,this));
				else
					photoDirectory=getRealPathFromURI(uri);
				//	final String PATH=;
			//	if(PATH==null)
			//		throw new AssertionError("PATH is null");
			//	Log.e(TAG,"ABC"+PATH+"DEF");
			//	final int index=PATH.lastIndexOf('/');
			//	photoDirectory=new File(PATH.substring(0,index));
				//getPreferences(MODE_PRIVATE).edit().putString(LAST_DIRECTORY_PREFERENCE,photoDirectory).commit();
			//	Log.e(TAG,"files:"+photoDirectory);
			//	Log.e(TAG,"files:"+photoDirectory.listFiles());
				photos=photoDirectory.listFiles(new FilenameFilter()
				{
					@Override
					public boolean accept(final File dir,final String name)
					{
						return name.toLowerCase().endsWith(".jpg");
					}
				});
				Arrays.sort(photos,new Comparator<File>()
				{
					@Override
					public int compare(final File lhs,final File rhs)
					{
						return lhs.getName().compareTo(rhs.getName());
					}
				});
				final File imgFile=photos[current];
				if(imgFile.exists())
				{
					final Bitmap myBitmap=getRotatedBitmap(imgFile);
					final ImageView myImage=(ImageView)findViewById(R.id.imageView);
					final int nh=(int)(myBitmap.getHeight()*(512.0/myBitmap.getWidth()));
					final Bitmap scaled=Bitmap.createScaledBitmap(myBitmap,512,nh,true);
					myImage.setImageBitmap(scaled);
				}
				final String PATH2=photos[current].toString();
				final int index2=PATH2.lastIndexOf('.');
				final File descriptionFile=new File(PATH2.substring(0,index2)+".txt");
				if(descriptionFile.exists())
				{
					try(FileInputStream fis=new FileInputStream(descriptionFile))
					{
						final byte[] description=new byte[(int)descriptionFile.length()];
						fis.read(description);
						((TextView)findViewById(R.id.editText)).setText(
								new String(description,"UTF-8"));
					}catch(final IOException e)
					{
						e.printStackTrace();
					}
				}
				return;
			default:
				super.onActivityResult(requestCode,resultCode,data);
		}

	}

	@SuppressLint("NewApi")
	public void nextPhoto(final View view)
	{
		if(photoDirectory==null)
			return;
		final String PATH=photos[current].toString();
		final int index=PATH.lastIndexOf('.');
		try(PrintWriter writer=new PrintWriter(PATH.substring(0,index)+".txt","UTF-8"))
		{
			final TextView textField=(TextView)findViewById(R.id.editText);
			writer.println(textField.getText());
			textField.setText("");
		}catch(FileNotFoundException|UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		if(view.equals(findViewById(R.id.button2)))
		{
			current++;
			current%=photos.length;
		}
		else if(view.equals(findViewById(R.id.button3)))
		{
			current--;
			current+=photos.length;
			current%=photos.length;
		}
		final File imgFile=new File(String.valueOf(photos[current]));
		if(imgFile.exists())
		{
			final Bitmap myBitmap=getRotatedBitmap(imgFile);
			final int nh=(int)(myBitmap.getHeight()*(512.0/myBitmap.getWidth()));
			final Bitmap scaled=Bitmap.createScaledBitmap(myBitmap,512,nh,true);
			((ImageView)findViewById(R.id.imageView)).setImageBitmap(scaled);

		}
		final String PATH2=photos[current].toString();
		final int index2=PATH2.lastIndexOf('.');
		final File descriptionFile=new File(PATH2.substring(0,index2)+".txt");
		if(descriptionFile.exists())
		{
			try(FileInputStream fis=new FileInputStream(descriptionFile))
			{
				final byte[] data=new byte[(int)descriptionFile.length()];
				fis.read(data);
				((TextView)findViewById(R.id.editText)).setText(new String(data,"UTF-8"));
			}catch(final IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	public void selectDirectory(@SuppressWarnings("UnusedParameters") final View ignored)
	{
		/*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
		{
			final Intent intent=new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
			startActivityForResult(Intent.createChooser(intent,"Select Picture"),
					REQUEST_IMAGES_DIRECTORY);
		}
		else
		{*/
			final Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
			startActivityForResult(Intent.createChooser(intent,"Select Picture"),
					REQUEST_IMAGES_FILE);
		//}
			//String lastAccessed=getPreferences(MODE_PRIVATE).getString(LAST_DIRECTORY_PREFERENCE,null);
		//
		//if(lastAccessed!=null)
		//	intent.setDataAndType(Uri.parse(lastAccessed),"image/*");

	}
}


text:
#ifndef POLARSSL_X509_H
#define POLARSSL_X509_H

#include "polarssl/rsa.h"

/*
 * ASN1 Error codes
 *
 * These error codes will be OR'ed to X509 error codes for
 * higher error granularity.
 */
#define POLARSSL_ERR_ASN1_OUT_OF_DATA                      0x0014
#define POLARSSL_ERR_ASN1_UNEXPECTED_TAG                   0x0016
#define POLARSSL_ERR_ASN1_INVALID_LENGTH                   0x0018
#define POLARSSL_ERR_ASN1_LENGTH_MISMATCH                  0x001A
#define POLARSSL_ERR_ASN1_INVALID_DATA                     0x001C

/*
 * X509 Error codes
 */
#define POLARSSL_ERR_X509_FEATURE_UNAVAILABLE              -0x0020
#define POLARSSL_ERR_X509_CERT_INVALID_PEM                 -0x0040
#define POLARSSL_ERR_X509_CERT_INVALID_FORMAT              -0x0060
#define POLARSSL_ERR_X509_CERT_INVALID_VERSION             -0x0080
#define POLARSSL_ERR_X509_CERT_INVALID_SERIAL              -0x00A0
#define POLARSSL_ERR_X509_CERT_INVALID_ALG                 -0x00C0
#define POLARSSL_ERR_X509_CERT_INVALID_NAME                -0x00E0
#define POLARSSL_ERR_X509_CERT_INVALID_DATE                -0x0100
#define POLARSSL_ERR_X509_CERT_INVALID_PUBKEY              -0x0120
#define POLARSSL_ERR_X509_CERT_INVALID_SIGNATURE           -0x0140
#define POLARSSL_ERR_X509_CERT_INVALID_EXTENSIONS          -0x0160
#define POLARSSL_ERR_X509_CERT_UNKNOWN_VERSION             -0x0180
#define POLARSSL_ERR_X509_CERT_UNKNOWN_SIG_ALG             -0x01A0
#define POLARSSL_ERR_X509_CERT_UNKNOWN_PK_ALG              -0x01C0
#define POLARSSL_ERR_X509_CERT_SIG_MISMATCH                -0x01E0
#define POLARSSL_ERR_X509_CERT_VERIFY_FAILED               -0x0200
#define POLARSSL_ERR_X509_KEY_INVALID_PEM                  -0x0220
#define POLARSSL_ERR_X509_KEY_INVALID_VERSION              -0x0240
#define POLARSSL_ERR_X509_KEY_INVALID_FORMAT               -0x0260
#define POLARSSL_ERR_X509_KEY_INVALID_ENC_IV               -0x0280
#define POLARSSL_ERR_X509_KEY_UNKNOWN_ENC_ALG              -0x02A0
#define POLARSSL_ERR_X509_KEY_PASSWORD_REQUIRED            -0x02C0
#define POLARSSL_ERR_X509_KEY_PASSWORD_MISMATCH            -0x02E0
#define POLARSSL_ERR_X509_POINT_ERROR                      -0x0300
#define POLARSSL_ERR_X509_VALUE_TO_LENGTH                  -0x0320

/*
 * X509 Verify codes
 */
#define BADCERT_EXPIRED                 1
#define BADCERT_REVOKED                 2
#define BADCERT_CN_MISMATCH             4
#define BADCERT_NOT_TRUSTED             8
#define BADCRL_NOT_TRUSTED             16
#define BADCRL_EXPIRED                 32

/*
 * DER constants
 */
#define ASN1_BOOLEAN                 0x01
#define ASN1_INTEGER                 0x02
#define ASN1_BIT_STRING              0x03
#define ASN1_OCTET_STRING            0x04
#define ASN1_NULL                    0x05
#define ASN1_OID                     0x06
#define ASN1_UTF8_STRING             0x0C
#define ASN1_SEQUENCE                0x10
#define ASN1_SET                     0x11
#define ASN1_PRINTABLE_STRING        0x13
#define ASN1_T61_STRING              0x14
#define ASN1_IA5_STRING              0x16
#define ASN1_UTC_TIME                0x17
#define ASN1_GENERALIZED_TIME        0x18
#define ASN1_UNIVERSAL_STRING        0x1C
#define ASN1_BMP_STRING              0x1E
#define ASN1_PRIMITIVE               0x00
#define ASN1_CONSTRUCTED             0x20
#define ASN1_CONTEXT_SPECIFIC        0x80

/*
 * various object identifiers
 */
#define X520_COMMON_NAME                3
#define X520_COUNTRY                    6
#define X520_LOCALITY                   7
#define X520_STATE                      8
#define X520_ORGANIZATION              10
#define X520_ORG_UNIT                  11
#define PKCS9_EMAIL                     1

#define X509_OUTPUT_DER              0x01
#define X509_OUTPUT_PEM              0x02
#define PEM_LINE_LENGTH                72
#define X509_ISSUER                  0x01
#define X509_SUBJECT                 0x02

#define OID_X520                "\x55\x04"
#define OID_CN                  "\x55\x04\x03"
#define OID_PKCS1               "\x2A\x86\x48\x86\xF7\x0D\x01\x01"
#define OID_PKCS1_RSA           "\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01"
#define OID_RSA_SHA_OBS         "\x2B\x0E\x03\x02\x1D"
#define OID_PKCS9               "\x2A\x86\x48\x86\xF7\x0D\x01\x09"
#define OID_PKCS9_EMAIL         "\x2A\x86\x48\x86\xF7\x0D\x01\x09\x01"

/*
 * Structures for parsing X.509 certificates
 */
typedef struct _x509_buf
{
    int tag;
    int len;
    unsigned char *p;
}
x509_buf;

typedef struct _x509_name
{
    x509_buf oid;
    x509_buf val;
    struct _x509_name *next;
}
x509_name;

typedef struct _x509_time
{
    int year, mon, day;
    int hour, min, sec;
}
x509_time;

typedef struct _x509_cert
{
    x509_buf raw;
    x509_buf tbs;

    int version;
    x509_buf serial;
    x509_buf sig_oid1;

    x509_buf issuer_raw;
    x509_buf subject_raw;

    x509_name issuer;
    x509_name subject;

    x509_time valid_from;
    x509_time valid_to;

    x509_buf pk_oid;
    rsa_context rsa;

    x509_buf issuer_id;
    x509_buf subject_id;
    x509_buf v3_ext;

    int ca_istrue;
    int max_pathlen;

    x509_buf sig_oid2;
    x509_buf sig;
    int sig_alg;

    struct _x509_cert *next;
}
x509_cert;

typedef struct _x509_crl_entry
{
    x509_buf raw;

    x509_buf serial;

    x509_time revocation_date;

    x509_buf entry_ext;

    struct _x509_crl_entry *next;
}
x509_crl_entry;

typedef struct _x509_crl
{
    x509_buf raw;
    x509_buf tbs;

    int version;
    x509_buf sig_oid1;

    x509_buf issuer_raw;

    x509_name issuer;

    x509_time this_update;
    x509_time next_update;

    x509_crl_entry entry;

    x509_buf crl_ext;

    x509_buf sig_oid2;
    x509_buf sig;
    int sig_alg;

    struct _x509_crl *next;
}
x509_crl;

/*
 * Structures for writing X.509 certificates
 */
typedef struct _x509_node
{
    unsigned char *data;
    unsigned char *p;
    unsigned char *end;

    size_t len;
}
x509_node;

typedef struct _x509_raw
{
    x509_node raw;
    x509_node tbs;

    x509_node version;
    x509_node serial;
    x509_node tbs_signalg;
    x509_node issuer;
    x509_node validity;
    x509_node subject;
    x509_node subpubkey;

    x509_node signalg;
    x509_node sign;
}
x509_raw;

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \brief          Parse one or more certificates and add them
 *                 to the chained list
 *
 * \param chain    points to the start of the chain
 * \param buf      buffer holding the certificate data
 * \param buflen   size of the buffer
 *
 * \return         0 if successful, or a specific X509 error code
 */
int x509parse_crt( x509_cert *chain, const unsigned char *buf, int buflen );

/**
 * \brief          Load one or more certificates and add them
 *                 to the chained list
 *
 * \param chain    points to the start of the chain
 * \param path     filename to read the certificates from
 *
 * \return         0 if successful, or a specific X509 error code
 */
int x509parse_crtfile( x509_cert *chain, const char *path );

/**
 * \brief          Parse one or more CRLs and add them
 *                 to the chained list
 *
 * \param chain    points to the start of the chain
 * \param buf      buffer holding the CRL data
 * \param buflen   size of the buffer
 *
 * \return         0 if successful, or a specific X509 error code
 */
int x509parse_crl( x509_crl *chain, const unsigned char *buf, int buflen );

/**
 * \brief          Load one or more CRLs and add them
 *                 to the chained list
 *
 * \param chain    points to the start of the chain
 * \param path     filename to read the CRLs from
 *
 * \return         0 if successful, or a specific X509 error code
 */
int x509parse_crlfile( x509_crl *chain, const char *path );

/**
 * \brief          Parse a private RSA key
 *
 * \param rsa      RSA context to be initialized
 * \param key      input buffer
 * \param keylen   size of the buffer
 * \param pwd      password for decryption (optional)
 * \param pwdlen   size of the password
 *
 * \return         0 if successful, or a specific X509 error code
 */
int x509parse_key( rsa_context *rsa,
                   const unsigned char *key, int keylen,
                   const unsigned char *pwd, int pwdlen );

/**
 * \brief          Load and parse a private RSA key
 *
 * \param rsa      RSA context to be initialized
 * \param path     filename to read the private key from
 * \param pwd      password to decrypt the file (can be NULL)
 *
 * \return         0 if successful, or a specific X509 error code
 */
int x509parse_keyfile( rsa_context *rsa, const char *path,
                       const char *password );

/**
 * \brief          Store the certificate DN in printable form into buf;
 *                 no more than size characters will be written.
 *
 * \param buf      Buffer to write to
 * \param size     Maximum size of buffer
 * \param dn       The X509 name to represent
 *
 * \return         The amount of data written to the buffer, or -1 in
 *                 case of an error.
 */
int x509parse_dn_gets( char *buf, size_t size, const x509_name *dn );

/**
 * \brief          Returns an informational string about the
 *                 certificate.
 *
 * \param buf      Buffer to write to
 * \param size     Maximum size of buffer
 * \param prefix   A line prefix
 * \param crt      The X509 certificate to represent
 *
 * \return         The amount of data written to the buffer, or -1 in
 *                 case of an error.
 */
int x509parse_cert_info( char *buf, size_t size, const char *prefix,
                         const x509_cert *crt );

/**
 * \brief          Returns an informational string about the
 *                 CRL.
 *
 * \param buf      Buffer to write to
 * \param size     Maximum size of buffer
 * \param prefix   A line prefix
 * \param crt      The X509 CRL to represent
 *
 * \return         The amount of data written to the buffer, or -1 in
 *                 case of an error.
 */
int x509parse_crl_info( char *buf, size_t size, const char *prefix,
                        const x509_crl *crl );

/**
 * \brief          Check a given x509_time against the system time and check
 *                 if it is valid.
 *
 * \param time     x509_time to check
 *
 * \return         Return 0 if the x509_time is still valid,
 *                 or 1 otherwise.
 */
int x509parse_time_expired( const x509_time *time );

/**
 * \brief          Verify the certificate signature
 *
 * \param crt      a certificate to be verified
 * \param trust_ca the trusted CA chain
 * \param ca_crl   the CRL chain for trusted CA's
 * \param cn       expected Common Name (can be set to
 *                 NULL if the CN must not be verified)
 * \param flags    result of the verification
 *
 * \return         0 if successful or POLARSSL_ERR_X509_SIG_VERIFY_FAILED,
 *                 in which case *flags will have one or more of
 *                 the following values set:
 *                      BADCERT_EXPIRED --
 *                      BADCERT_REVOKED --
 *                      BADCERT_CN_MISMATCH --
 *                      BADCERT_NOT_TRUSTED
 *
 * \note           TODO: add two arguments, depth and crl
 */
int x509parse_verify( x509_cert *crt,
                      x509_cert *trust_ca,
                      x509_crl *ca_crl,
                      const char *cn, int *flags );

/**
 * \brief          Unallocate all certificate data
 *
 * \param crt      Certificate chain to free
 */
void x509_free( x509_cert *crt );

/**
 * \brief          Unallocate all CRL data
 *
 * \param crt      CRL chain to free
 */
void x509_crl_free( x509_crl *crl );

/**
 * \brief          Checkup routine
 *
 * \return         0 if successful, or 1 if the test failed
 */
int x509_self_test( int verbose );

#ifdef __cplusplus
}
#endif

#endif /* x509.h */


text:
export declare function makeDecorator(annotationCls: any): (...args: any[]) => (cls: any) => any;
export declare function makeParamDecorator(annotationCls: any): any;


text:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class AwesomeFormWithEvents extends JFrame implements ActionListener {

	JButton btnWinOrLose = new JButton("Win Or Lose?");
	JButton btnYesOrNo = new JButton("Yes or NO?");
	JLabel lblResult = new JLabel("n/a");

	public AwesomeFormWithEvents() {
		setSize(500, 500);
		setTitle("This is an awesome Form!");
		setResizable(false);
		center();
		// layout Manager is set to null so we can absolutely position everything.
		setLayout(null);

		// add our components
		addButton();
		addLabel();
		addButton2();

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void buttonClicked() {
		double res = Math.random();
		System.out.println("Math result: " + res);

		if(res > 0.5) {
			lblResult.setText("Winner!");
		} else {
			lblResult.setText("Sorry you lost!");
		}
	}

	public void addLabel() {
		this.add(lblResult);
		lblResult.setBounds(100, 350, 300, 30);
	}

	public void addButton() {
		this.add(btnWinOrLose);
		// the button will flow to expand into the entire window unless you kill the layoutManager
		btnWinOrLose.setBounds(100, 100, 200, 30);

		btnWinOrLose.addActionListener(this);
	}

	public void addButton2() {
		this.add(btnYesOrNo);
		btnYesOrNo.setBounds(100, 200, 150, 30);

		btnYesOrNo.addActionListener(this);
	}

	public void center() {
		CUtilities.CenterScreen(this);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		System.out.println("Action event: " +
				arg0.getActionCommand() +
				" " + arg0.getSource());
	}

}


text:
<?php

namespace Reurbano\CoreBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;

use Symfony\Component\Filesystem\Filesystem;

class SitemapCommand extends ContainerAwareCommand {

    protected function configure() {
        $this
                ->setName('reurbano:sitemap')
                ->setDescription('Gera sitemap do sistema Reurbano');
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        $container = $this->getContainer();
        $dm = $container->get('mastop.dm');
        $filesystem = new Filesystem();
        $sitemapFile = $container->get('kernel')->getRootDir().'/../web/sitemap.xml';
        $output->writeln("Gerando sitemap em <question>".$sitemapFile."</question>");
        $filesystem->touch($sitemapFile);
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $sitemap = $dom->createElement('urlset');
        $sitemap->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
        $sitemap->setAttribute('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');

        // Páginas de ofertas
        $dealRepo = $dm->getRepository('ReurbanoDealBundle:Deal');
        $deals = $dealRepo->findBy(array('active' => true), array('createdAt'=>'desc')); // Todas as ofertas ativas ordenadas por data

        if($deals->count()){
            foreach($deals as $deal){
                $dealLink = $container->get('router')->generate('deal_deal_show', array('city'=>$deal->getSource()->getCity()->getSlug(), 'category' => $deal->getSource()->getCategory()->getSlug(), 'slug' => $deal->getSlug()), true);
                $url = $dom->createElement('url');
                $url->appendChild($dom->createElement('loc', $dealLink));
                if($deal->getUpdatedAt()){
                    $url->appendChild($dom->createElement('lastmod', $deal->getUpdatedAt()->format('Y-m-d')));
                }
                $url->appendChild($dom->createElement('priority', '0.9'));
                $url->appendChild($dom->createElement('changefreq', 'weekly'));
                $sitemap->appendChild($url);
            }
        }

        // Cidades e Categorias

        $cityRepo = $dm->getRepository('ReurbanoCoreBundle:City');
        $catRepo = $dm->getRepository('ReurbanoDealBundle:Category');
        $cities = $cityRepo->findAll();
        $categories = $catRepo->findAllByOrder();
        if($cities->count()){
            foreach($cities as $city){
                $cityLink = $container->get('router')->generate('core_city_index', array('slug' => $city->getSlug()), true);
                $url = $dom->createElement('url');
                $url->appendChild($dom->createElement('loc', $cityLink));
                $url->appendChild($dom->createElement('priority', '0.7'));
                $url->appendChild($dom->createElement('changefreq', 'daily'));
                $sitemap->appendChild($url);
                // Categorias dentro das cidades
                foreach ($categories as $category) {
                    $categoryLink = $container->get('router')->generate('deal_category_index', array('city' => $city->getSlug(), 'slug' => $category->getSlug()), true);
                    $url = $dom->createElement('url');
                    $url->appendChild($dom->createElement('loc', $categoryLink));
                    $url->appendChild($dom->createElement('priority', '0.8'));
                    $url->appendChild($dom->createElement('changefreq', 'daily'));
                    $sitemap->appendChild($url);
                }
            }
        }

        // Páginas estáticas
        $conentRepo = $dm->getRepository('ReurbanoCoreBundle:Content');
        $contents = $conentRepo->findAllByCreated();

        if($contents->count()){
            foreach($contents as $content){
                $contentLink = $container->get('router')->generate('core_content_index', array('slug' => $content->getSlug()), true);
                $url = $dom->createElement('url');
                $url->appendChild($dom->createElement('loc', $contentLink));
                if($content->getUpdated()){
                    $url->appendChild($dom->createElement('lastmod', $content->getUpdated()->format('Y-m-d')));
                }
                $url->appendChild($dom->createElement('priority', '0.6'));
                $url->appendChild($dom->createElement('changefreq', 'monthly'));
                $sitemap->appendChild($url);
            }
        }

        // Contato
        $url = $dom->createElement('url');
        $url->appendChild($dom->createElement('loc', $container->get('router')->generate('core_html_contact', array(), true)));
        $url->appendChild($dom->createElement('priority', '0.8'));
        $url->appendChild($dom->createElement('changefreq', 'never'));

        $sitemap->appendChild($url);

        // Página de Novo Usuário
        $url = $dom->createElement('url');
        $url->appendChild($dom->createElement('loc', $container->get('router')->generate('user_user_new', array(), true)));
        $url->appendChild($dom->createElement('priority', '0.8'));
        $url->appendChild($dom->createElement('changefreq', 'never'));

        $sitemap->appendChild($url);

        // Joga o XML criado no $dom

        $dom->appendChild($sitemap);

        return file_put_contents($sitemapFile, $dom->saveXml()); // Coloca o conteúdo do XML no arquivo e retorna
    }

}


text:
import React from "react";
import {Button, Modal} from "antd";

let CustomModal = React.createClass({

	render(){
		const {title, visible, onCancel, children, ...otherProps} = this.props;
		return (

			<Modal title={title} maskClosable={false} visible={visible} onCancel={onCancel} footer={this.renderFooter()} {...otherProps}>
				{children}
			</Modal>
		)
	},

	renderFooter(){

		return [
			<Button key="back" type="ghost" size="large" onClick={this.props.onCancel}>取消</Button>,
			<Button key="submit" type="primary" size="large" onClick={this.props.onSave}>提 交</Button>,
		]

	}
});

CustomModal.propTypes = {
	title: React.PropTypes.string.isRequired,
	onSave: React.PropTypes.func.isRequired,
	onCancel: React.PropTypes.func.isRequired,
	visible: React.PropTypes.bool.isRequired
};

export default CustomModal;


text:
import { getKeys, each, findItem, merge } from '@vessel/core';

/**
 *
 * Limitations:
 *
 * - You can't use a injected property by
 * @get decorator within constructor or a method
 * called immediately within the constructor. But you
 * can always use this.get() or this.container.get()
 * within constructor. That is, because @get decorator
 * adds the dependencies but it doesn't inject them,
 * the dependencies are resolved when the module is
 * started from the container with a .get() or when
 * the module is a dependency of a module which is being
 * started with the container method .get(). That said,
 * using the container method .get() returns the dependency
 * immediately.
 */
export class Container {

    private modules = {};

    private cache = new WeakMap();

    public register(opts) {
        merge(this.modules, opts);
        return this;
    }

    public registerSingleModule(name, module) {

        if (!module) {
            throw TypeError("Cannot registerSingleModule(), 'module' was " + module);
        }

        let modules = this.modules;

        if (!modules.hasOwnProperty("@")) {
            modules["@"] = {}
        }

        if (modules["@"].hasOwnProperty(name)) {
            throw TypeError("Cannot registerSingleModule(), '" + name + "' is already registered");
        }

        modules["@"][name] = module;

        return this.loadModule(module);
    }

    /**
     * Gets a given module name.
     */
    public get(name) {
        return this.resolveDependencies(name);
    }

    public remove(constructor) {
        return this.cache.delete(constructor);
    }

    /**
     * Loads a module by its constructor,
     * if it's already instantiated it will
     * return the instance, otherwise it will
     * instantiate and then return it.
     *
     * It can be used to get an instance directly
     * without its name but it will not resolve
     * its @get() dependencies.
     */
    public loadModule(constructor) {
        let cache = this.cache;

        if (!cache.has(constructor))
            cache.set(constructor, new constructor());

        return cache.get(constructor);
    }

    /**
     * Gets the dependencies of a given className.
     *
     * At this time, metadataManager cannot be loaded by
     * container.get(). That is, because the container.get()
     * of the injector needs the MetadataManager to get the
     * dependencies, so we manually load the dependency
     * @metadata_manager (which is already registered
     * within ContainerLoader) avoiding an unkind infinite loop :)
     */
    private getDependencies(className) {
        let metadataConstructor = this.modules['@']['@metadata_manager'],
            metadataManager = this.loadModule(metadataConstructor);
        return metadataManager.getDependencies(className);
    }

    /**
     * Resolves dependencies for a given module, recursively
     * injecting its dependencies.
     */
    private resolveDependencies(name) {
        let constructor = this.findModuleByName(name);

        if (!constructor) {
            throw new TypeError("Attempt to get " +
                "non-existent module: '" +
                name +"'. Did you register it?");
        }

        let dependencies = this.getDependencies(constructor.name),
            topParent = {
                name: name,
                constructor: constructor
            };

        each(dependencies, function(item){
            this.inject(item.depName, item.attrName, topParent);
        }, this);

        return this.loadModule(constructor);
    }

    /**
     * The purpose of this function is to
     * get a @get('registrated_module_name') injected.
     *
     * All children dependencies are recursively resolved.
     *
     * The top parent of each container.inject() is
     * the very first dependency.
     *
     * e.g. For a @get('module.name') the very first
     * dependency is 'module.name', which will be injected
     * to an instantiated constructor passed in as the
     * 'constructor' parameter.
     *
     * @param depName is the current dependency name.
     * @param attrName is the current attribute name to be injected on.
     * @param topParent is an object with the name and constructor of
     * the topParent dependency (not the module where we are injecting).
     * @param parents is an array with the dependencies for a single @get().
     * @param constructor is where the first dep will be injected.
     *
     */
    private inject(depName, attrName, topParent, parents=[], constructor=null) {
        let depConstructor = this.findModuleByName(depName);

        if (!depConstructor) {
            throw new TypeError("Injection error on '"+topParent.name+
                "': Attempt to inject non-existent dependency: '"
                + depName + "'. Did you register it?");
        }

        if (this.isCircular(depName, parents, topParent.name)) {
            throw new RangeError("Circular dependency detected: "+
                "module injection was impossible. Attempting to "+
                "inject '" + depName + "' which have tried to "+
                "resolve a parent dependency.");
        }

        let depDependencies = this.getDependencies(depConstructor.name);

        parents.push(depName);

        each(depDependencies, function(dep) {
            this.inject(dep.depName, dep.attrName, topParent, parents, depConstructor);
        }, this);

        // Only the top-parent dependency enters here.

        if (parents.length === 1) {
            // Inject the very first parent dependency
            // to the module prototype.
            let topParentInstance = this.loadModule(topParent.constructor),
                topDependencyInstance = this.loadModule(depConstructor);
            return topParentInstance[attrName] = topDependencyInstance;
        }

        // Children dependencies enter here.

        parents.pop();
        // Inject the dependency to the parent prototype.
            let topDepInstance = this.loadModule(constructor),
                depInstance = this.loadModule(depConstructor);
        return topDepInstance[attrName] = depInstance;
    }

    /**
     * Find a module by its name, when a
     * match is found, the loop stops.
     *
     * Returns the constructor if a module
     * is found.
     */
    private findModuleByName(queryName) {
        let modules = this.modules,
            keys = getKeys(modules),
            len = keys.length;
        for (let i = 0; i < len; i++) {
            let moduleType = keys[i],
                module = modules[moduleType];
            if (module && module.hasOwnProperty(queryName))
                return modules[moduleType][queryName];
        }
        return null;
    }

    private isCircular(depName, parents, topParentName) {
        return depName === topParentName || findItem(parents, depName);
    }
}


text:
package fi.nls.oskari.eu.elf.administrativeunits;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement(namespace = "http://www.locationframework.eu/schemas/AdministrativeUnits/MasterLoD1/1.0")
public class AdministrativeUnit extends AdministrativeUnitType {

}


text:
<?php

namespace Google\AdsApi\AdManager\v202202;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class makeTestNetworkResponse
{

    /**
     * @var \Google\AdsApi\AdManager\v202202\Network $rval
     */
    protected $rval = null;

    /**
     * @param \Google\AdsApi\AdManager\v202202\Network $rval
     */
    public function __construct($rval = null)
    {
      $this->rval = $rval;
    }

    /**
     * @return \Google\AdsApi\AdManager\v202202\Network
     */
    public function getRval()
    {
      return $this->rval;
    }

    /**
     * @param \Google\AdsApi\AdManager\v202202\Network $rval
     * @return \Google\AdsApi\AdManager\v202202\makeTestNetworkResponse
     */
    public function setRval($rval)
    {
      $this->rval = $rval;
      return $this;
    }

}


text:
<?php

namespace ONGR\ElasticsearchBundle\Annotation;

/**
 * Annotation used to enable ROUTING and associate document property with _routing meta-field.
 *
 * @Annotation
 * @Target("PROPERTY")
 */
final class Routing implements MetaField
{
    /**
     * @var bool
     */
    public $required = false;

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return '_routing';
    }

    /**
     * {@inheritdoc}
     */
    public function getSettings()
    {
        return [
            'required' => $this->required
        ];
    }
}


text:
using System;
using NBitcoin;
using QBitNinja.Client;
using QBitNinja.Client.Models;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using HBitcoin.KeyManagement;

namespace HBitcoin.Tests
{
	public static class QBitNinjaJutsus
	{
		public static void GetBalances(IEnumerable<AddressHistoryRecord> addressHistoryRecords, out Money confirmedBalance, out Money unconfirmedBalance)
		{
			confirmedBalance = Money.Zero;
			unconfirmedBalance = Money.Zero;
			foreach (var record in addressHistoryRecords)
			{
				if (record.Confirmed)
					confirmedBalance += record.Amount;
				else
				{
					unconfirmedBalance += record.Amount;
				}
			}
		}

		public static bool SelectCoins(ref HashSet<Coin> coinsToSpend, Money totalOutAmount, IEnumerable<Coin> unspentCoins)
		{
			var haveEnough = false;
			foreach (Coin coin in unspentCoins.OrderByDescending(x => x.Amount))
			{
				coinsToSpend.Add(coin);
				// if doesn't reach amount, continue adding next coin
				if (coinsToSpend.Sum(x => x.Amount) < totalOutAmount) continue;

				haveEnough = true;
				break;
			}

			return haveEnough;
		}

		public static Dictionary<uint256, List<BalanceOperation>> GetOperationsPerTransactions(Dictionary<BitcoinAddress, List<BalanceOperation>> operationsPerAddresses)
		{
			// 1. Get all the unique operations
			var opSet = new HashSet<BalanceOperation>();
			foreach (var elem in operationsPerAddresses)
				foreach (var op in elem.Value)
					opSet.Add(op);

			if (!opSet.Any()) throw new NotSupportedException();

			// 2. Get all operations, grouped by transactions
			var operationsPerTransactions = new Dictionary<uint256, List<BalanceOperation>>();
			foreach (var op in opSet)
			{
				var txId = op.TransactionId;
                if (operationsPerTransactions.TryGetValue(txId, out List<BalanceOperation> ol))
                {
                    ol.Add(op);
                    operationsPerTransactions[txId] = ol;
                }
                else operationsPerTransactions.Add(txId, new List<BalanceOperation> { op });
            }

			return operationsPerTransactions;
		}

		public static async Task<Dictionary<BitcoinAddress, List<BalanceOperation>>> QueryOperationsPerSafeAddressesAsync(QBitNinjaClient client, Safe safe, int minUnusedKeys = 7, HdPathType? hdPathType = null)
		{
			if (hdPathType == null)
			{
				var t1 = QueryOperationsPerSafeAddressesAsync(client, safe, minUnusedKeys, HdPathType.Receive);
				var t2 = QueryOperationsPerSafeAddressesAsync(client, safe, minUnusedKeys, HdPathType.Change);
				var t3 = QueryOperationsPerSafeAddressesAsync(client, safe, minUnusedKeys, HdPathType.NonHardened);

				await Task.WhenAll(t1, t2, t3).ConfigureAwait(false);

				Dictionary<BitcoinAddress, List<BalanceOperation>> operationsPerReceiveAddresses = await t1.ConfigureAwait(false);
				Dictionary<BitcoinAddress, List<BalanceOperation>> operationsPerChangeAddresses = await t2.ConfigureAwait(false);
				Dictionary<BitcoinAddress, List<BalanceOperation>> operationsPerNonHardenedAddresses = await t3.ConfigureAwait(false);

				var operationsPerAllAddresses = new Dictionary<BitcoinAddress, List<BalanceOperation>>();
				foreach (var elem in operationsPerReceiveAddresses)
					operationsPerAllAddresses.Add(elem.Key, elem.Value);
				foreach (var elem in operationsPerChangeAddresses)
					operationsPerAllAddresses.Add(elem.Key, elem.Value);
				foreach (var elem in operationsPerNonHardenedAddresses)
					operationsPerAllAddresses.Add(elem.Key, elem.Value);

				return operationsPerAllAddresses;
			}

			var addresses = safe.GetFirstNAddresses(minUnusedKeys, hdPathType.GetValueOrDefault());
			//var addresses = FakeData.FakeSafe.GetFirstNAddresses(minUnusedKeys);

			var operationsPerAddresses = new Dictionary<BitcoinAddress, List<BalanceOperation>>();
			var unusedKeyCount = 0;
			foreach (var elem in await QueryOperationsPerAddressesAsync(client, addresses).ConfigureAwait(false))
			{
				operationsPerAddresses.Add(elem.Key, elem.Value);
				if (elem.Value.Count == 0) unusedKeyCount++;
			}

			Debug.WriteLine($"{operationsPerAddresses.Count} {hdPathType} keys are processed.");

			var startIndex = minUnusedKeys;
			while (unusedKeyCount < minUnusedKeys)
			{
				addresses = new List<BitcoinAddress>();
				for (int i = startIndex; i < startIndex + minUnusedKeys; i++)
				{
					addresses.Add(safe.GetAddress(i, hdPathType.GetValueOrDefault()));
					//addresses.Add(FakeData.FakeSafe.GetAddress(i));
				}
				foreach (var elem in await QueryOperationsPerAddressesAsync(client, addresses).ConfigureAwait(false))
				{
					operationsPerAddresses.Add(elem.Key, elem.Value);
					if (elem.Value.Count == 0) unusedKeyCount++;
				}

				Debug.WriteLine($"{operationsPerAddresses.Count} {hdPathType} keys are processed.");
				startIndex += minUnusedKeys;
			}

			return operationsPerAddresses;
		}

		public static async Task<Dictionary<BitcoinAddress, List<BalanceOperation>>> QueryOperationsPerAddressesAsync(QBitNinjaClient client, IEnumerable<BitcoinAddress> addresses)
		{
			var operationsPerAddresses = new Dictionary<BitcoinAddress, List<BalanceOperation>>();

			var addressList = addresses.ToList();
			var balanceModelList = new List<BalanceModel>();

			foreach (var balance in await GetBalancesAsync(client, addressList, unspentOnly: false).ConfigureAwait(false))
			{
				balanceModelList.Add(balance);
			}

			for (var i = 0; i < balanceModelList.Count; i++)
			{
				operationsPerAddresses.Add(addressList[i], balanceModelList[i].Operations);
			}

			return operationsPerAddresses;
		}

		private static async Task<IEnumerable<BalanceModel>> GetBalancesAsync(QBitNinjaClient client, IEnumerable<BitcoinAddress> addresses, bool unspentOnly)
		{
			var tasks = new HashSet<Task<BalanceModel>>();
			foreach (var dest in addresses)
			{
				var task = client.GetBalance(dest, unspentOnly);

				tasks.Add(task);
			}

			await Task.WhenAll(tasks).ConfigureAwait(false);

			var results = new HashSet<BalanceModel>();
			foreach (var task in tasks)
				results.Add(await task.ConfigureAwait(false));

			return results;
		}
	}
}


text:
package org.kaazing.gateway.transport.http.acceptor.specification.rfc7230;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertTrue;

import java.util.concurrent.CountDownLatch;

import org.apache.mina.core.service.IoHandler;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.kaazing.gateway.resource.address.ResourceAddress;
import org.kaazing.gateway.resource.address.ResourceAddressFactory;
import org.kaazing.gateway.transport.IoHandlerAdapter;
import org.kaazing.gateway.transport.http.HttpAcceptSession;
import org.kaazing.gateway.transport.http.HttpAcceptorRule;
import org.kaazing.gateway.transport.http.HttpHeaders;
import org.kaazing.gateway.transport.http.HttpStatus;
import org.kaazing.k3po.junit.annotation.Specification;
import org.kaazing.k3po.junit.rules.K3poRule;
import org.kaazing.test.util.ITUtil;
import org.kaazing.test.util.MethodExecutionTrace;

/**
 * Test to validate behavior as specified in RFC 7231 section 4:
 * Request Methods.
 */
public class MessageFormatIT {
    private static final ResourceAddress HTTP_ADDRESS = httpAddress();

    private final HttpAcceptorRule acceptor = new HttpAcceptorRule();

    private JUnitRuleMockery context = new JUnitRuleMockery() {
        {
            setThreadingPolicy(new Synchroniser());
        }
    };

    private TestRule contextRule = ITUtil.toTestRule(context);
    private final TestRule trace = new MethodExecutionTrace();
    private final K3poRule k3po = new K3poRule().setScriptRoot("org/kaazing/specification/http/rfc7230/message.format");
    private final TestRule timeoutRule = new DisableOnDebug(new Timeout(5, SECONDS));

    @Rule
    public TestRule chain = RuleChain.outerRule(trace).around(acceptor).around(contextRule).around(k3po).around(timeoutRule);

    @Test
    @Specification({"inbound.should.accept.headers/request"})
    public void inboundShouldAcceptHeaders() throws Exception {
        standardHttpTestCase(HTTP_ADDRESS);
    }

    @Test
    @Specification({"outbound.should.accept.no.headers/request"})
    public void outboundShouldAcceptNoHeaders() throws Exception {
        standardHttpTestCase(HTTP_ADDRESS);
    }

    @Test
    @Specification({"outbound.should.accept.headers/request"})
    public void outboundShouldAcceptHeaders() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.addWriteHeader("some", "header");
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Test
    @Specification({"inbound.should.reject.request.with.whitespace.between.start.line.and.first.header/request"})
    public void inboundShouldRejectRequestWithWhitespaceBetweenStartLineAndFirstHeader() throws Exception {

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>();
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
    }

    @Test
    @Specification({"request.must.start.with.request.line/request"})
    public void requestMustStartWithRequestLine() throws Exception {
        standardHttpTestCase(HTTP_ADDRESS);
    }

    @Ignore("BUG: No response to lacking URI")
    @Test
    @Specification({"inbound.should.reject.invalid.request.line/request"})
    public void inboundShouldRejectInvalidRequestLine() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.SUCCESS_OK);
                session.close(false);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Test
    @Specification({"server.should.send.501.to.unimplemented.methods/request"})
    public void serverShouldSend501ToUnImplementedMethods() throws Exception {
        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>();
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
    }

    @Ignore("BUG: No response to error in URI")
    @Test
    @Specification({"server.should.send.414.to.request.with.too.long.a.request/request"})
    public void serverShouldSend414ToRequestWithTooLongARequest() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.SUCCESS_OK);
                session.close(false);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Test
    @Specification({"server.should.send.status.line.in.start.line/request"})
    public void serverShouldSendStatusLineInStartLine() throws Exception {
        standardHttpTestCase(HTTP_ADDRESS);
    }

    /*
     * No whitespace is allowed between the header field-name and colon.  In
     * the past, differences in the handling of such whitespace have led to
     * security vulnerabilities in request routing and response handling.  A
     * server MUST reject any received request message that contains
     * whitespace between a header field-name and colon with a response code
     * of 400 (Bad Request).  A proxy MUST remove any such whitespace from a
     * response message before forwarding the message downstream.
     */
    @Ignore("Not Spec Complient")
    @Test
    @Specification({"server.must.reject.header.with.space.between.header.name.and.colon/request"})
    public void serverMustRejectHeaderWithSpaceBetweenHeaderNameAndColon() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.SUCCESS_OK);
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Ignore("BUG: No response to error in bad header.")
    @Test
    @Specification({"server.should.reject.obs.in.header.value/request"})
    public void serverShouldRejectOBSInHeaderValue() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.SUCCESS_OK);
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Ignore("BUG: No response to error in bad header.")
    @Test
    @Specification({"proxy.or.gateway.must.reject.obs.in.header.value/request"})
    public void proxyOrGatewayMustRejectOBSInHeaderValue() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.SUCCESS_OK);
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Test
    @Specification({"inbound.on.receiving.field.with.length.larger.than.wanting.to.process.must.reply.with.4xx/request"})
    public void inboundOnReceivingFieldWithLengthLargerThanWantingToProcessMustReplyWith4xx() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.CLIENT_BAD_REQUEST);
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Ignore("Transfer Encoding Bug")
    @Test
    @Specification({"server.should.send.501.to.unknown.transfer.encoding/request"})
    public void serverShouldSend501ToUnknownTransferEncoding() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.SUCCESS_OK);
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Test
    @Specification({"outbound.should.process.response.with.content.length/request"})
    public void outboundShouldProcessResponseWithContentLength() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.SUCCESS_OK);
                session.close(false);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Test
    @Specification({"inbound.should.process.request.with.content.length/request"})
    public void inboundShouldProcessRequestWithContentLength() throws Exception {
        standardHttpTestCase(HTTP_ADDRESS);
    }

    @Test
    @Specification({"client.should.send.content.length.header.in.post.even.if.no.content/request"})
    public void clientShouldSendContentLengthHeaderInPostEvenIfNoContent() throws Exception {
        standardHttpTestCase(HTTP_ADDRESS);
    }

    @Test
    @Specification({"head.response.must.not.have.content/request"})
    public void headResponseMustNotHaveContent() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.INFO_CONTINUE);
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Test
    @Specification({"head.response.must.not.have.content.though.may.have.content.length/request"})
    public void headResponseMustNotHaveContentThoughMayHaveContentLength() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.addWriteHeader(HttpHeaders.HEADER_CONTENT_LENGTH, String.valueOf(100));
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Test
    @Specification({"server.must.reject.request.with.multiple.different.content.length/request"})
    public void serverMustRejectRequestWithMultipleDifferentContentLength() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.CLIENT_BAD_REQUEST);
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    @Ignore("BUG: Extra CRLF makes response 400.")
    @Test
    @Specification({"robust.server.should.allow.extra.CRLF.after.request.line/request"})
    public void robustServerShouldAllowExtraCRLFAfterRequestLine() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.setStatus(HttpStatus.SUCCESS_OK);
                session.close(true);
            }
        };
        acceptor.bind(HTTP_ADDRESS, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    /*
     * Bytes won't make it to the Http layer
     *
     * @Test
     * @Specification({"non.http.request.to.http.server.should.be.responded.to.with.400/request"})
     * public void nonHttpRequestToHttpServerShouldBeRespondedToWith400() throws Exception {
     *     final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
     *         @Override
     *         protected void doSessionOpened(HttpAcceptSession session) throws Exception {
     *             session.setStatus(HttpStatus.CLIENT_BAD_REQUEST);
     *             session.close(false);
     *         }
     *     };
     *     acceptor.bind(HTTP_ADDRESS, acceptHandler);
     *     k3po.finish();
     * }
     */

    private void standardHttpTestCase(ResourceAddress address) throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);

        final IoHandler acceptHandler = new IoHandlerAdapter<HttpAcceptSession>() {
            @Override
            protected void doSessionOpened(HttpAcceptSession session) throws Exception {
                latch.countDown();
                session.close(true);
            }
        };
        acceptor.bind(address, acceptHandler);

        k3po.finish();
        assertTrue(latch.await(4, SECONDS));
    }

    private static ResourceAddress httpAddress() {
        ResourceAddressFactory addressFactory = ResourceAddressFactory.newResourceAddressFactory();
        String address = "http://localhost:8080/";
        return addressFactory.newResourceAddress(address);
    }
}


text:
#import <UIKit/UIKit.h>
#import "WFListController.h"
#import "WFResultsModel.h"
#import "constants.h"

@class WFPropellerView;
@class WFNoResultsView;
@class WFDetailsViewController;

@interface WFResultListController : WFListController <WFResultModelDelegate>
{
    WFPropellerView *propellerView;
    WFDetailsViewController *detailsCtrl;
    WFNoResultsView *noResultsView;
}

// Show search text field or normal nav bar
- (void)setResultModel:(WFResultsModel *)model;
- (void)setNavigationBarType:(navBarType)barType;
- (void)showResultsForCategory:(NSDictionary *)categoryDict;
- (void)showResultsForString:(NSString *)queryString;

@end


text:
/**
 * TODO: I need something better than this. Manually changing template is
 * very inconvenient :(. Should it be defined with metadata?
 */
import defaultTempalte from './default.jsx';

export default {
  default: defaultTempalte
}


text:
/*
 * 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.
 */
package com.facebook.presto.spiller;

import org.weakref.jmx.Managed;

import java.util.concurrent.atomic.AtomicLong;

public class SpillerStats
{
    protected final AtomicLong totalSpilledBytes = new AtomicLong();
    protected final AtomicLong totalSpilledBytesRead = new AtomicLong();

    @Managed
    public long getTotalSpilledBytes()
    {
        return totalSpilledBytes.get();
    }

    @Managed
    public long getTotalSpilledBytesRead()
    {
        return totalSpilledBytesRead.get();
    }

    public void addToTotalSpilledBytes(long delta)
    {
        totalSpilledBytes.addAndGet(delta);
    }

    public void addToTotalSpilledBytesRead(long delta)
    {
        totalSpilledBytesRead.addAndGet(delta);
    }
}


text:
var makeIterable = require('../../src/iterable').makeIterable
var Iteration = require('./Iteration')

module.exports = ArrayIterable

function ArrayIterable (a) {
  this.array = a
}

ArrayIterable.prototype = makeIterable(function () {
  return new ArrayIterator(this.array)
}, ArrayIterable.prototype)

function ArrayIterator (a) {
  this.array = a
  this.index = 0
  this.length = a.length >>> 0
}

ArrayIterator.prototype.next = function () {
  var l = this.length
  if (this.index < l) {
    var x = this.array[this.index]
    this.index += 1
    return new Iteration(false, x)
  }

  return Iteration.DONE
}


text:
/**
 *
Accumulates common high-level uses of the {@code java.lang.reflect} APIs.

 *
These classes are immutable, and therefore thread-safe.

 *
 * @since 3.0
 * @version $Id$
 */
package org.apache.commons.lang3.reflect;


text:
package com.suscipio_solutions.consecro_mud.core.database;
import java.sql.ResultSet;

import com.suscipio_solutions.consecro_mud.Common.interfaces.Clan;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMProps;
import com.suscipio_solutions.consecro_mud.core.CMath;
import com.suscipio_solutions.consecro_mud.core.Log;

public class ClanLoader
{
	protected DBConnector DB=null;
	public ClanLoader(DBConnector newDB)
	{
		DB=newDB;
	}
	protected int currentRecordPos=1;
	protected int recordCount=0;

	public void updateBootStatus(String loading)
	{
		CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Loading "+loading+" ("+currentRecordPos+" of "+recordCount+")");
	}

	public void DBRead()
	{
		DBConnection D=null;
		Clan C=null;
		try
		{
			D=DB.DBFetch();
			final ResultSet R=D.query("SELECT * FROM CMCLAN");
			recordCount=DB.getRecordCount(D,R);
			while(R.next())
			{
				currentRecordPos=R.getRow();
				final String name=DBConnections.getRes(R,"CMCLID");
				C=(Clan)CMClass.getCommon("DefaultClan");
				C.setName(name);
				C.setPremise(DBConnections.getRes(R,"CMDESC"));
				C.setAcceptanceSettings(DBConnections.getRes(R,"CMACPT"));
				C.setPolitics(DBConnections.getRes(R,"CMPOLI"));
				C.setRecall(DBConnections.getRes(R,"CMRCLL"));
				C.setDonation(DBConnections.getRes(R,"CMDNAT"));
				C.setStatus(CMath.s_int(DBConnections.getRes(R, "CMSTAT")));
				C.setMorgue(DBConnections.getRes(R,"CMMORG"));
				C.setTrophies(CMath.s_int(DBConnections.getRes(R, "CMTROP")));
				CMLib.clans().addClan(C);
				updateBootStatus("Clans");
			}
		}
		catch(final Exception sqle)
		{
			Log.errOut("Clan",sqle);
		}
		finally
		{
			DB.DBDone(D);
		}
		// log comment
	}

	public void DBUpdate(Clan C)
	{
		final String sql="UPDATE CMCLAN SET "
				+"CMDESC='"+C.getPremise()+"',"
				+"CMACPT='"+C.getAcceptanceSettings()+"',"
				+"CMPOLI=?,"
				+"CMRCLL='"+C.getRecall()+"',"
				+"CMDNAT='"+C.getDonation()+"',"
				+"CMSTAT="+C.getStatus()+","
				+"CMMORG='"+C.getMorgue()+"',"
				+"CMTROP="+C.getTrophies()+""
				+" WHERE CMCLID='"+C.clanID()+"'";
		DB.updateWithClobs(sql, C.getPolitics());
	}

	public void DBCreate(Clan C)
	{
		if(C.clanID().length()==0) return;
		final String sql="INSERT INTO CMCLAN ("
			+"CMCLID,"
			+"CMTYPE,"
			+"CMDESC,"
			+"CMACPT,"
			+"CMPOLI,"
			+"CMRCLL,"
			+"CMDNAT,"
			+"CMSTAT,"
			+"CMMORG,"
			+"CMTROP"
			+") values ("
			+"'"+C.clanID()+"',"
			+"0,"
			+"'"+C.getPremise()+"',"
			+"'"+C.getAcceptanceSettings()+"',"
			+"?,"
			+"'"+C.getRecall()+"',"
			+"'"+C.getDonation()+"',"
			+""+C.getStatus()+","
			+"'"+C.getMorgue()+"',"
			+""+C.getTrophies()
			+")";
			DB.updateWithClobs(sql, C.getPolitics());
	}

	public void DBDelete(Clan C)
	{
		DB.update("DELETE FROM CMCLAN WHERE CMCLID='"+C.clanID()+"'");
	}

}


text:
#include <stdlib.h>
#include <stdio.h>
#include <evpaxos.h>
#include <signal.h>

#define MAX_VALUE_SIZE 8192

struct client_value
{
  struct timeval t;
  size_t size;
  char value[MAX_VALUE_SIZE];
};

static void
handle_sigint(int sig, short ev, void* arg)
{
	struct event_base* base = arg;
	printf("Caught signal %d\n", sig);
	event_base_loopexit(base, NULL);
}

static void
deliver(unsigned iid, char* value, size_t size, void* arg)
{
	struct client_value* v = (struct client_value*)value;
	printf("Delivered value: %s\n", v->value);
}

static void
start_learner(const char* config)
{
	struct event* sig;
	struct evlearner* lea;
	struct event_base* base;

	base = event_base_new();
	lea = evlearner_init(config, deliver, NULL, base);
	if (lea == NULL) {
		printf("Could not start the learner!\n");
		exit(1);
	}

	sig = evsignal_new(base, SIGINT, handle_sigint, base);
	evsignal_add(sig, NULL);

	event_base_dispatch(base);

	event_free(sig);
	evlearner_free(lea);
	event_base_free(base);
}

int
main(int argc, char const *argv[])
{
	const char* config = "../paxos.conf";

	if (argc != 1 && argc != 2) {
		printf("Usage: %s [path/to/paxos.conf]\n", argv[0]);
		exit(1);
	}

	if (argc == 2)
		config = argv[1];

	start_learner(config);

	return 0;
}


text:
@interface PacketData ()

@end

@implementation PacketData

+ (NSData *)CommandWithCMDs:(Byte)cmd SUB:(Byte)sub DATA:(NSData *)data
{
    MessageHEAD[0] = 0xEE;
    MessageHEAD[1] = 0xaa;

    MessageCMD = cmd;
    MessageSUB = sub;

    MessageData = data;

    [PacketData CommandData];

    NSMutableData *commandData = [[NSMutableData alloc] init];

    [commandData appendBytes:&MessageHEAD length:2];
    [commandData appendData:CrcData];
    [commandData appendData:MessageCRCData];

    return commandData;
}

+ (void)covertIntToHex:(NSInteger)size
{

    if (size > 255*255*255) {

        MessageLEN[0] = 0xff;
        MessageLEN[1] = 0xff;
        MessageLEN[2] = 0xff;
        MessageLEN[3] = size-255*255*255;

    } else if (size > 255*255) {

        MessageLEN[0] = 0xff;
        MessageLEN[1] = 0xff;
        MessageLEN[2] = size - 255*255;
        MessageLEN[3] = 0x00;

    } else if (size > 255) {

        MessageLEN[0] = 0xff;
        MessageLEN[1] = size - 255;
        MessageLEN[2] = 0x00;
        MessageLEN[3] = 0x00;

    } else {

        MessageLEN[0] = size;
        MessageLEN[1] = 0x00;
        MessageLEN[2] = 0x00;
        MessageLEN[3] = 0x00;

    }

}

+ (void)CommandData
{
    NSMutableData *crcData = [[NSMutableData alloc] init];
    NSMutableData *lenData = [[NSMutableData alloc] init];
    [lenData appendBytes:&MessageCMD length:1];
    [lenData appendBytes:&MessageSUB length:1];
    [lenData appendData:MessageData];

    [PacketData covertIntToHex:lenData.length];

    [crcData appendBytes:&MessageLEN length:4];
    [crcData appendData:lenData];

    CrcData = crcData;

    // 操作Crc32
    uint32_t crcdata = [PacketData CRC32Data:CrcData];

    MessageCRCData = [NSData dataWithBytes:&crcdata length:4];

}

+ (uint32_t)CRC32Data:(NSData *)CrcData
{

    uint8_t *bytes = (uint8_t *)[CrcData bytes];

    uint32_t crc32data = [CRC32Data getCRC32Data:bytes Len:(UInt32)CrcData.length oldCrc32:0];

    NSLog(@"crc32data ==== %d", crc32data);

    return crc32data;

}

+ (uint32_t)getMessageCRC:(struct message_info)info dataLen:(uint32_t)datalen
{

    NSMutableData *crcData = [[NSMutableData alloc] init];
    [crcData appendBytes:&info.len length:4];
    [crcData appendBytes:&info.cmd length:1];
    [crcData appendBytes:&info.sub length:1];
    [crcData appendBytes:info.data length:datalen];

    return [self CRC32Data:crcData];

}

+ (uint32_t)getMessageLEN:(struct message_info)info dataLen:(uint32_t)datalen
{

    uint32_t len = 0;

    len += sizeof(info.cmd);
    len += sizeof(info.sub);
    len += datalen;

    return len;

}

+ (NSData *)CommandWithCMD:(Byte)cmd SUB:(Byte)sub DATA:(NSData *)data
{

    uint32_t datalen = 0;

    struct message_info info;

    if (data) {

//        [data getBytes:info.data length:data.length];
        info.data = (uint8_t *)data.bytes;
        datalen = (uint32_t)data.length;

    }

    info.head[0] = 0xee;
    info.head[1] = 0xaa;

    info.cmd = cmd;
    info.sub = sub;

    info.len = [self getMessageLEN:info dataLen:datalen];
    info.crc = [self getMessageCRC:info dataLen:datalen];

    NSMutableData *commandData = [[NSMutableData alloc] init];
    [commandData appendBytes:&info.head length:2];
    [commandData appendBytes:&info.len length:4];
    [commandData appendBytes:&info.cmd length:1];
    [commandData appendBytes:&info.sub length:1];
    [commandData appendBytes:info.data length:datalen];
    [commandData appendBytes:&info.crc length:4];
//    [commandData appendBytes:&info length:8];

    return commandData;

}

+ (BaseModel *)unPacket:(NSData *)data
{
    struct message_info info;
    [data getBytes:&info.head range:NSMakeRange(0, 2)];
    [data getBytes:&info.len range:NSMakeRange(2, 4)];
    [data getBytes:&info.cmd range:NSMakeRange(6, 1)];
    [data getBytes:&info.sub range:NSMakeRange(7, 1)];
    info.data = (uint8_t *)[[data subdataWithRange:NSMakeRange(8, data.length-12)] bytes];
    [data getBytes:&info.crc range:NSMakeRange(data.length-4, 4)];

    if (info.head[0]==0xee&&info.head[1]==0xaa) {

        uint32_t crc = [self getMessageCRC:info dataLen:info.len-2];

        if (crc==info.crc) {

            return [PacketCMD packetdata:info];

        } else{

            NSLog(@"crc 校验错误");

        }

    }

    return nil;
}

+ (BOOL)dataComplition:(NSData *)data
{
    struct message_info info;
    [data getBytes:&info.head range:NSMakeRange(0, 2)];
    [data getBytes:&info.len range:NSMakeRange(2, 4)];
    [data getBytes:&info.cmd range:NSMakeRange(6, 1)];
    [data getBytes:&info.sub range:NSMakeRange(7, 1)];
    if (data.length!=info.len+10) {
        return NO;
    }

    return YES;
}

@end


text:
require 'em-synchrony'
require 'librevox/response'
require 'librevox/commands'

module Librevox
  module Listener
    class Base < EventMachine::Protocols::HeaderAndContentProtocol
      class << self
        def hooks
          @hooks ||= Hash.new { |hash, key| hash[key] = [] }
        end

        def event(event, &block)
          hooks[event] << block
        end
      end

      # In some cases there are both applications and commands with the same
      # name, e.g. fifo. But we can't have two `fifo`-methods, so we include
      # commands in CommandDelegate, and expose all commands through the `api`
      # method, which wraps a CommandDelegate instance.
      class CommandDelegate
        include Librevox::Commands

        def initialize(listener)
          @listener = listener
        end

        def command(*args, &block)
          @listener.command(super(*args), &block)
        end
      end

      # Exposes an instance of {CommandDelegate}, which includes {Librevox::Commands}.
      # @example
      #   api.status
      #   api.fsctl :pause
      #   api.uuid_park "592567a2-1be4-11df-a036-19bfdab2092f"
      # @see Librevox::Commands
      def api
        @command_delegate ||= CommandDelegate.new(self)
      end

      def command(msg, &block)
        send_data("#{msg}\n\n")

        @command_queue.push(block)
      end

      attr_accessor :response
      alias :event :response

      def post_init
        @command_queue = []
      end

      def receive_request(header, content)
        @response = Librevox::Response.new(header, content)
        handle_response
      end

      def handle_response
        if response.api_response? && @command_queue.any?
          @command_queue.shift.call(response)
        end

        if response.event?
          on_event(response.dup)
          invoke_event_hooks
        end
      end

      # override
      def on_event(event)
      end

      alias :done :close_connection_after_writing

      private
      def invoke_event_hooks
        event = response.event.downcase.to_sym
        self.class.hooks[event].each do |block|
          instance_exec(response.dup, &block)
        end
      end
    end
  end
end


text:
require 'spec_helper'

describe Midishark::Parser::Base do
  let(:config) { double(:config) }

  subject { described_class.new(config) }

  describe '#parse' do
    it "should raise NotImplementedError" do
      expect { subject.parse('line') }.to raise_error(NotImplementedError)
    end
  end
end


text:
/// <reference path="references.ts" />
/// <reference path="Server.ts" />
/// <reference path="Client.ts" />

module.exports.Server = Server

module.exports.Client = Client


text:
scrollable = true

$(document).ready(function() {
  heart();
  unheart();
  comment();
  deleteComment();
  lightBox();
  hideLightBox();
  loginPrompt();
  showForm();
  $(document).on("scrollend", function() {
    infiniteScroll.requestPuppies(scrollable);
  });

  // Setup for Facebook integration
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '1639495569664010',
      xfbml      : true,
      version    : 'v2.4'
    });
  };

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

});

function showForm() {
  $('body').on('click', '.call-form', function(event){
    event.preventDefault()
    var url = $(this).attr('href')

    $.ajax({
      method: 'get',
      url: url,
    })
    .done(function(response){
      if($('.user-form').length == 0){
        $('.main').prepend(response)
      }
      else{
        $('.user-form').remove()
        $('.main').prepend(response)
      }
    })

  })
}

function heart() {
  $('body').on("submit", ".heart-buttons #heart", function(event){
    event.preventDefault();

    var heartInfo = $(this).serialize()
    var photoID = $(this).closest('.photo').attr('id')

    $('#'+photoID+' #unheart').removeClass('hidden');
    $('#'+photoID+' #heart').addClass('hidden');

    $.ajax({
      method:"post",
      url: "/hearts",
      data: heartInfo,
      datatype: "json"
    })

    .done(function(response) {
      response = JSON.parse(response);
      $('.photo'+response.photo).text(response.heart_count)
    })

    .fail(function(response){
      $('#'+photoID+' #heart').removeClass('hidden');
      $('#'+photoID+' #unheart').addClass('hidden');
    });

  })
};

function unheart() {
  $('body').on("submit", ".heart-buttons #unheart", function(event){
    event.preventDefault();

    var heartInfo = $(this).serialize()
    var photoID = $(this).closest('.photo').attr('id')

    $('#'+photoID+' #heart').removeClass('hidden');
    $('#'+photoID+' #unheart').addClass('hidden');

    $.ajax({
      method: "post",
      url: "/hearts",
      data: heartInfo
    })

    .done(function(response){
      response = JSON.parse(response);
      $('.photo'+response.photo).text(response.heart_count)
    })

    .fail(function(response){
      $('#'+photoID+' #unheart').removeClass('hidden');
      $('#'+photoID+' #heart').addClass('hidden');
    })
  });
}

function comment() {
  $('body').on("submit", "#comment", function(event){
    event.preventDefault();

    var comment = $(this).serialize()
    var photoID = $(this).closest('.photo').attr('id')
    photoID = photoID.substr(5)

    console.log(comment)
    console.log(photoID)
    $('input[type=text]').val('');
    $.ajax({
      method:"post",
      url: "/comments/"+photoID,
      data: comment,
      datatype: "json"
    })

    .done(function(response) {
      response = JSON.parse(response);
      $('.comments').prepend(response.html);
    })

    .fail(function(response){
      console.log(this)
    });
  })
};

function deleteComment() {
  $('body').on("submit", "#delete_comment", function(event){
    event.preventDefault();

    var comment = $(this).closest('li')
    var commentID = $(this).closest('li').attr('id');

    comment.remove();
    $.ajax({
      method:"delete",
      url: "/comments/"+commentID,
      datatype: "json"
    })

    .done(function(response) {

    })

    .fail(function(response){
      $('.comments').prepend(comment)
    });
  })
};

// Lightbox
function lockScroll(){
  var scrollPosition = [
    self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
    self.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
  ];
  var html = jQuery('html'); // it would make more sense to apply this to body, but IE7 won't have that
  html.data('scroll-position', scrollPosition);
  html.data('previous-overflow', html.css('overflow'));
  html.css('overflow', 'hidden');
  $('#lightbox-background').css('top', scrollPosition[1])
  window.scrollTo(scrollPosition[0], scrollPosition[1]);
}

function unlockScroll(){
  var html = jQuery('html');
  var scrollPosition = html.data('scroll-position');
  html.css('overflow', html.data('previous-overflow'));
  window.scrollTo(scrollPosition[0], scrollPosition[1])
}

function lightBox() {
  $('body').on("click", ".panel-body a", function(event){
    event.preventDefault()

    lockScroll();

    $('#lightbox-background').fadeIn("slow")

    var url = $(this).attr('href')

    $.ajax({
      method: 'get',
      url: url,
      dataType: 'html',
    })

    .done(function(response){
      var lightbox = "
"+response+"
"
      $('#lightbox-background').append(lightbox).fadeIn(400)
    })
    })
}

function hideLightBox() {
  $('#lightbox-background').on("click", ".photo.single", function(event){
    event.stopPropagation()
  })
  $('#lightbox-background').click(function(event){

      $('#lightbox-background').fadeOut(300);
      $('.lightbox-panel').remove();
      $('html, body').css({
          'overflow': 'auto',
          'height': 'auto'
      });

    })

}

var infiniteScroll = {
  start: 0,
  stop: 19,
  requestPuppies: function(scrollable){

    if (scrollable){
    $.ajax({
      method: 'get',
      url: location.pathname,
      data: {start: String(this.start+20), stop: String(this.stop+20)},
    })
    .done(function(response){

      length = response.length
      test = response.slice(1, length-5)
      sliced = test+"]"
      parsed = JSON.parse(sliced)

      var grid = document.querySelector('#columns');
      jQuery(parsed).each( function(index, element) {
          var item = document.createElement('article');
          salvattore['append_elements'](grid, [item]);
          jQuery(item).html(element);
      })

    })
    .fail(function(response){
      if($('#end_scroll').length === 0){
        $('#columns').append('

that\'s all we have.  go find more to add to our collection!

')
    }
    })
      this.start += 20
      this.stop += 20
    }
  }
}

function loginPrompt() {
  $('body').on('mouseup', '.login', function(){

    // console.log($(this).closest('div.panel-footer'))

      $(this).closest('.panel-footer').children().children('.login-prompt').fadeIn().delay(2000).fadeOut('slow')

      // $(this).parent().children('.login-prompt').fadeIn().delay(2000).fadeOut('slow')
      // $(this).closest('.panel-footer').prepend("
please log in or sign up to heart.
").remove().delay(10000000000000)
      // $('.login-prompt').remove().delay(10000000000000)
    // }
  });

  $('body').on('')
  // $('lightbox-background').on('click', '.login', function(){
  //   console.log($(this))
  // });

  // $('body').on('click', '.login-lightbox', function(){
  //   console.log($(this))
  // })

}

// JSON ATTEMPTS
      // length = response.length
      // test = response.substr(1, length-6)
      // testlength = test.length

      // sliced = test.slice(1, testlength-3)
      // again = sliced+"]"


text:
import sys
import argparse
from socks1 import *    #import all the socks from the file
from twisted.internet import reactor
#from twisted.protocols import socks
from twisted.python import log

sys.path.append('.')

import marionette_tg.conf

def startthestuff(port, address):
    ip = address
    s5 = Socks5(address, port)
    s5.start()
    return 'started socks5 on ' + str(address) + ' with port ' + str(port) #outputs? atm no..

parser = argparse.ArgumentParser(
    description='SOCKS5 proxy server.')
parser.add_argument('--local_port', '-lport', dest='local_port', required=True,
    help='local port to listen on for HTTP requests')
args = parser.parse_args()

SOCKS_PORT = int(args.local_port)
port = SOCKS_PORT
address = '0.0.0.0'

if '__main__' == __name__:
    if marionette_tg.conf.get("general.debug"):
        log.startLogging(sys.stdout)

    #reactor.listenTCP(SOCKS_PORT, socks.SOCKSv4Factory(None))
    startthestuff(port, address)
    reactor.run()

#<---


text:
Plugin.define "cPanel" do
author "Andrew Horton"
version "0.5"
description "Site configuration and management software application. Supporting many operating systems while allowing endusers to control every aspect of their webhosting experience."
website "http://www.cpanel.net/"

# Google results as at 2012-04-11 #
# 899 for inurl:":2082/frontend" -demo
# 487 for inurl:":2095/webmail/x3"

# Dorks #
dorks [
'inurl:":2082/frontend" -demo',
'inurl:":2095/webmail/x3"'
]

# Matches #
matches [

# Welcome Page # Default title
{ :text=>"<title>cPanel®</title>" },

# Welcome Page # Default logo HTML
{ :text=>'
' },

# Welcome Page # Default text
{ :text=>"Apache is working on your cPanel® and WHM™ Server" },

# Default meta refresh redirection webpage
{ :text=>'<META HTTP-EQUIV="refresh" CONTENT="0;URL=/cgi-sys/defaultwebpage.cgi">'},

# Login Page # Default CSS
{ :regexp=>/<link rel="stylesheet" href="[^>^"]*\/unprotected\/cpanel\/style_optimized\.css" type="text\/css" \/>/ },

# Version Detection # Login page # Default title
{ :version=>/<title>cPanel®[\s]{0,2}([\d\.]+)<\/title>/ },

# Aggressive # /cgi-sys/defaultwebpage.cgi
{ :url=>"/cgi-sys/defaultwebpage.cgi", :text=>'
It may be possible to restore access to this site by following these instructions for clearing your dns cache.
' },

# Aggressive # /img-sys/header.jpg
{ :url=>"/img-sys/header.jpg", :md5=>"b0f3863b68ff707c3fb586bd87b4f9c6" },

# Version Detection # HTTP Server header
{ :search=>"headers[server]", :version=>/^cpsrvd\/([\d\.]+)$/ },

]

end