text:
package com.jgoodies.forms.layout;

import com.jgoodies.forms.util.DefaultUnitConverter;
import com.jgoodies.forms.util.UnitConverter;

import java.awt.*;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

/**
 * Consists only of static methods that create and convert sizes
 * as required by the {@link FormLayout}. The conversion of sizes
 * that are not based on pixel is delegated to an implementation
 * of {@link UnitConverter}. The conversion methods require the
 * layout container as parameter to read its current font and resolution.
 *
 * @author  Karsten Lentzsch
 * @version $Revision: 1.10 $
 *
 * @see     Size
 * @see     UnitConverter
 * @see     DefaultUnitConverter
 */
public final class Sizes {

    // Common Constant Sizes ************************************************

    public static final ConstantSize ZERO   = pixel(0);

    public static final ConstantSize DLUX1  = dluX( 1);
    public static final ConstantSize DLUX2  = dluX( 2);
    public static final ConstantSize DLUX3  = dluX( 3);
    public static final ConstantSize DLUX4  = dluX( 4);
    public static final ConstantSize DLUX5  = dluX( 5);
    public static final ConstantSize DLUX6  = dluX( 6);
    public static final ConstantSize DLUX7  = dluX( 7);
    public static final ConstantSize DLUX8  = dluX( 8);
    public static final ConstantSize DLUX9  = dluX( 9);
    public static final ConstantSize DLUX11 = dluX(11);
    public static final ConstantSize DLUX14 = dluX(14);

    public static final ConstantSize DLUY1  = dluY( 1);
    public static final ConstantSize DLUY2  = dluY( 2);
    public static final ConstantSize DLUY3  = dluY( 3);
    public static final ConstantSize DLUY4  = dluY( 4);
    public static final ConstantSize DLUY5  = dluY( 5);
    public static final ConstantSize DLUY6  = dluY( 6);
    public static final ConstantSize DLUY7  = dluY( 7);
    public static final ConstantSize DLUY8  = dluY( 8);
    public static final ConstantSize DLUY9  = dluY( 9);
    public static final ConstantSize DLUY11 = dluY(11);
    public static final ConstantSize DLUY14 = dluY(14);

    // Static Component Sizes ***********************************************

    /**
     * Use the maximum of all component minimum sizes as column or row size.
     */
    public static final ComponentSize MINIMUM  = new ComponentSize("minimum");

    /**
     * Use the maximum of all component preferred sizes as column or row size.
     */
    public static final ComponentSize PREFERRED = new ComponentSize("preferred");

    /**
     * Use the maximum of all component sizes as column or row size;
     * measures preferred sizes when asked for the preferred size
     * and minimum sizes when asked for the minimum size.
     */
    public static final ComponentSize DEFAULT = new ComponentSize("default");

    /**
     * An array of all enumeration values used to canonicalize
     * deserialized component sizes.
     */
    private static final ComponentSize[] VALUES =
        { MINIMUM, PREFERRED, DEFAULT};

    // Singleton State *******************************************************

    /**
     * Holds the current converter that maps non-pixel sizes to pixels.
     */
    private static UnitConverter unitConverter;

    // Instance Creation ******************************************************

    private Sizes() {
        // Suppresses default constructor, ensuring non-instantiability.
    }

    // Creation of Size Instances *********************************************

    /**
     * Creates and returns an instance of ConstantSize from the
     * given encoded size and unit description.
     *
     * @param encodedValueAndUnit  value and unit in string representation
     * @param horizontal			true for horizontal, false for vertical
     * @return a ConstantSize for the given value and unit
     */
    public static ConstantSize constant(String encodedValueAndUnit,
                                         boolean horizontal) {
        return ConstantSize.valueOf(encodedValueAndUnit, horizontal);
    }

    /**
     * Returns an instance of Size for the specified value
     * in horizontal dialog units.
     *
     * @param value	size value in horizontal dialog units
     * @return the associated ConstantSize
     */
    public static ConstantSize dluX(int value) {
        return ConstantSize.dluX(value);
    }

    /**
     * Returns an instance of Size for the specified value
     * in vertical dialog units.
     *
     * @param value 	size value in vertical dialog units
     * @return the associated ConstantSize
     */
    public static ConstantSize dluY(int value) {
        return ConstantSize.dluY(value);
    }

    /**
     * Creates and returns an instance of Size
     * for the specified pixel value.
     *
     * @param value  value in pixel
     * @return the associated ConstantSize
     */
    public static ConstantSize pixel(int value) {
        return new ConstantSize(value, ConstantSize.PIXEL);
    }

    /**
     * Creates and returns a BoundedSize for the given basis
     * using the specified lower and upper bounds.
     *
     * @param basis  		the base size
     * @param lowerBound  	the lower bound size
     * @param upperBound  	the upper bound size
     * @return a BoundedSize for the given basis and bounds
     * @throws NullPointerException if basis is null
     */
    public static Size bounded(Size basis, Size lowerBound, Size upperBound) {
        return new BoundedSize(basis, lowerBound, upperBound);
    }

    // Unit Conversion ******************************************************

    /**
     * Converts Inches and returns pixels using the specified resolution.
     *
     * @param in           the Inches
     * @param component    the component that provides the graphics object
     * @return the given Inches as pixels
     */
    public static int inchAsPixel(double in, Component component) {
        return in == 0d
            ? 0
            : getUnitConverter().inchAsPixel(in, component);
    }

    /**
     * Converts Millimeters and returns pixels using the resolution of the
     * given component's graphics object.
     *
     * @param mm	        Millimeters
     * @param component    the component that provides the graphics object
     * @return the given Millimeters as pixels
     */
    public static int millimeterAsPixel(double mm, Component component) {
        return mm == 0d
            ? 0
            : getUnitConverter().millimeterAsPixel(mm, component);
    }

    /**
     * Converts Centimeters and returns pixels using the resolution of the
     * given component's graphics object.
     *
     * @param cm	        Centimeters
     * @param component    the component that provides the graphics object
     * @return the given Centimeters as pixels
     */
    public static int centimeterAsPixel(double cm, Component component) {
        return cm == 0d
            ? 0
            : getUnitConverter().centimeterAsPixel(cm, component);
    }

    /**
     * Converts DTP Points and returns pixels using the resolution of the
     * given component's graphics object.
     *
     * @param pt	        DTP Points
     * @param component    the component that provides the graphics object
     * @return the given Points as pixels
     */
    public static int pointAsPixel(int pt, Component component) {
        return pt == 0
            ? 0
            :getUnitConverter().pointAsPixel(pt, component);
    }

    /**
     * Converts horizontal dialog units and returns pixels.
     * Honors the resolution, dialog font size, platform, and l&f.
     *
     * @param dluX         the horizontal dialog units
     * @param component    the component that provides the graphics object
     * @return the given horizontal dialog units as pixels
     */
    public static int dialogUnitXAsPixel(int dluX, Component component) {
        return dluX == 0
            ? 0
            : getUnitConverter().dialogUnitXAsPixel(dluX, component);
    }

    /**
     * Converts vertical dialog units and returns pixels.
     * Honors the resolution, dialog font size, platform, and l&f.
     *
     * @param dluY         the vertical dialog units
     * @param component    the component that provides the graphics object
     * @return the given vertical dialog units as pixels
     */
    public static int dialogUnitYAsPixel(int dluY, Component component) {
        return dluY == 0
            ? 0
            : getUnitConverter().dialogUnitYAsPixel(dluY, component);
    }

    // Accessing the Unit Converter *******************************************

    /**
     * Returns the current {@link UnitConverter}. If it has not been initialized
     * before it will get an instance of {@link DefaultUnitConverter}.
     *
     * @return the current UnitConverter
     */
    public static UnitConverter getUnitConverter() {
        if (unitConverter == null) {
            unitConverter = DefaultUnitConverter.getInstance();
        }
        return unitConverter;
    }

    /**
     * Sets a new {@link UnitConverter} that will be used to convert
     * font-dependent sizes to pixel sizes.
     *
     * @param newUnitConverter  the unit converter to be set
     */
    public static void setUnitConverter(UnitConverter newUnitConverter) {
        unitConverter = newUnitConverter;
    }

    // Helper Class *********************************************************

    /**
     * An ordinal-based serializable typesafe enumeration that implements
     * the  {@link Size} interface for the component sizes:
     * min, pref, default.
     */
    static final class ComponentSize implements Size, Serializable {

        private final transient String name;

        private ComponentSize(String name) {
            this.name = name;
        }

        /**
         * Returns an instance of ComponentSize that corresponds
         * to the specified string.
         * @param str   		the encoded component size
         * @return the corresponding ComponentSize or null if none matches
         */
        static ComponentSize valueOf(String str) {
            if (str.equals("m") || str.equals("min"))
                return MINIMUM;
            if (str.equals("p") || str.equals("pref"))
                return PREFERRED;
            if (str.equals("d") || str.equals("default"))
                return DEFAULT;
            else
                return null;
        }

        /**
         * Computes the maximum size for the given list of components, using
         * this form spec and the specified measure.
         *

         * Invoked by FormLayout to determine the size of one of my elements
         *
         * @param container       the layout container
         * @param components      the list of components to measure
         * @param minMeasure      the measure used to determine the minimum size
         * @param prefMeasure     the measure used to determine the preferred size
         * @param defaultMeasure  the measure used to determine the default size
         * @return the maximum size in pixels for the given list of components
         */
        public int maximumSize(
            Container container,
            List components,
            FormLayout.Measure minMeasure,
            FormLayout.Measure prefMeasure,
            FormLayout.Measure defaultMeasure) {

            FormLayout.Measure measure = this == MINIMUM
                    ? minMeasure
                    : (this == PREFERRED ? prefMeasure : defaultMeasure);
            int maximum = 0;
            for (Iterator i = components.iterator(); i.hasNext();) {
                Component c = (Component) i.next();
                maximum = Math.max(maximum, measure.sizeOf(c));
            }
            return maximum;
        }

        public String toString()  { return name.substring(0, 1); }

        // Serialization *****************************************************

        private static int nextOrdinal = 0;

        private final int ordinal = nextOrdinal++;

        private Object readResolve() {
            return VALUES[ordinal];  // Canonicalize
        }

    }

}


text:
function controlHead(direction)
  system(sprintf('rosrun simple_head point_head %f %f %f', direction(1), direction(2), direction(3)));

redpajama_set_name: RedPajamaGithub


text:
/**
 * SNAP Decimal_Mult Example
 *
 * Demonstration how to get data into the FPGA, process it using a SNAP
 * action and move the data out of the FPGA back to host-DRAM.
 */

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <getopt.h>
#include <malloc.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <assert.h>

#include <snap_tools.h>
#include <libsnap.h>
#include <common_decimal.h>
#include <snap_hls_if.h>

int verbose_flag = 0;

static const char *version = GIT_VERSION;

static const char *mem_tab[] = { "HOST_DRAM", "CARD_DRAM", "TYPE_NVME" };

/**
 * @brief	prints valid command line options
 *
 * @param prog	current program's name
 */
static void usage(const char *prog)
{
	printf("Usage: %s [-h] [-v, --verbose] [-V, --version]\n"
	       "  -C, --card <cardno> can be (0...3)\n"
	       "  -n, --number              number of inputs to process < %d (configurable).\n"
	       "  -t, --timeout             timeout in sec to wait for done.\n"
	       "  -N, --no-irq              disable Interrupts\n"
	       "\n"
	       "Example:\n"
	       "  snap_decimal_mult. ...\n"
	       "\n",
	       prog, MAX_NB_OF_DECIMAL_READ);
}

static void snap_prepare_decimal_mult(struct snap_job *cjob,
				 struct decimal_mult_job *mjob,
				 void *addr_in,
				 uint32_t size_in,
				 uint8_t type_in,
				 void *addr_out,
				 uint32_t size_out,
				 uint8_t type_out)
{
	fprintf(stderr, "  prepare decimal_mult job of %ld bytes size\n", sizeof(*mjob));

	assert(sizeof(*mjob) <= SNAP_JOBSIZE);
	memset(mjob, 0, sizeof(*mjob));

	snap_addr_set(&mjob->in, addr_in, size_in, type_in,
		      SNAP_ADDRFLAG_ADDR | SNAP_ADDRFLAG_SRC);
	snap_addr_set(&mjob->out, addr_out, size_out, type_out,
		      SNAP_ADDRFLAG_ADDR | SNAP_ADDRFLAG_DST |
		      SNAP_ADDRFLAG_END);

	snap_job_set(cjob, mjob, sizeof(*mjob), NULL, 0);
}

int main(int argc, char *argv[])
{
	int ch, rc = 0;
	int card_no = 0;
	struct snap_card *card = NULL;
	struct snap_action *action = NULL;
	char device[128];
	struct snap_job cjob;
	struct decimal_mult_job mjob;
	unsigned long timeout = 600;
	int write_results = 0;
	struct timeval etime, stime;
	ssize_t max_number_of_inputs = MAX_NB_OF_DECIMAL_READ; // Value defined in sync with the hardware
	ssize_t inputs_to_process = 12;    // Allow user to process only part of the inputs
	uint8_t type_in = SNAP_ADDRTYPE_HOST_DRAM;
	uint64_t addr_in = 0x0ull;
	uint8_t type_out = SNAP_ADDRTYPE_HOST_DRAM;
	uint64_t addr_out = 0x0ull;
	int exit_code = EXIT_SUCCESS;
	FILE *fp_ref, *fp_action;

	// default is completion of the action by IRQ
	snap_action_flag_t action_irq = (SNAP_ACTION_DONE_IRQ | SNAP_ATTACH_IRQ);

	//mat_elmt_t is declared in common header file in include directory
	// and can be a float or a double as user needs
	mat_elmt_t ref_result[max_number_of_inputs/3];
	mat_elmt_t *data_in = NULL, *data_out = NULL;

	while (1) {
		int option_index = 0;
		static struct option long_options[] = {
			{ "card",	 required_argument, NULL, 'C' },
			{ "number",	 required_argument, NULL, 'n' },
			{ "timeout",	 required_argument, NULL, 't' },
			{ "no-irq",	 no_argument,	    NULL, 'N' },
			{ "version",	 no_argument,	    NULL, 'V' },
			{ "verbose",	 no_argument,	    NULL, 'v' },
			{ "write-results", no_argument,	    NULL, 'w' },
			{ "help",	 no_argument,	    NULL, 'h' },
			{ 0,		 no_argument,	    NULL, 0   },
		};

		ch = getopt_long(argc, argv,
				 "C:n:t:VNvwh",
				 long_options, &option_index);
		if (ch == -1)
			break;

		switch (ch) {
		case 'C':
			card_no = strtol(optarg, (char **)NULL, 0);
			break;
		case 'n':
			inputs_to_process = strtol(optarg, (char **)NULL, 0);
			// check max: bounded to MAX_NB_OF_DECIMAL_READ in this example
			if (inputs_to_process > max_number_of_inputs)
				inputs_to_process = max_number_of_inputs;
			// check min: less than 3 entries cannot give a result
			if (inputs_to_process < 3)
				inputs_to_process = 3;
			break;
		case 't':
			timeout = strtol(optarg, (char **)NULL, 0);
			break;
		case 'V':
			printf("%s\n", version);
			exit(EXIT_SUCCESS);
		case 'v':
			verbose_flag = 1;
			break;
		case 'h':
			usage(argv[0]);
			exit(EXIT_SUCCESS);
			break;
		case 'N':
			action_irq = 0;
			break;
		case 'w':
			write_results = 1;
			break;
		default:
			usage(argv[0]);
			exit(EXIT_FAILURE);
		}
	}

	if (optind != argc) {
		usage(argv[0]);
		exit(EXIT_FAILURE);
	}

	//Prepare memory area which will contain the date to be processed by the action
	// reserve a memory area for max_number_of_inputs doubles of 8 bytes OR floats of 4 bytes
	data_in = snap_malloc(max_number_of_inputs * sizeof(mat_elmt_t));
	if (data_in == NULL)
		goto out_error;
	// write 0 into this buffer
	memset(data_in, 0, max_number_of_inputs * sizeof(mat_elmt_t));

	//Fill a table with only inputs_to_process values: 1.0, 1.5, 2.0, 2.5,... 8.5
	for(int i = 0; i < inputs_to_process ; i++){
		*(data_in+i) = 1 + 0.5*i;
	}

	//specify where data are located => in Host DRAM at address addr_in
	type_in = SNAP_ADDRTYPE_HOST_DRAM;
	addr_in = (unsigned long)data_in;

	//Prepare memory area which will contain the results of the operation done by the action
	// reserve a data_out with one third of the inputs of doubles of 8 bytes OR floats of 4 bytes
	data_out = snap_malloc((inputs_to_process/3) * sizeof(mat_elmt_t));
	if (data_out == NULL)
		goto out_error;
	// write 0 into this buffer
	memset(data_out, 0, (inputs_to_process/3) * sizeof(mat_elmt_t));

	//specify where result will be located => in Host DRAM at address addr_out
	type_out = SNAP_ADDRTYPE_HOST_DRAM;
	addr_out = (unsigned long)data_out;

	// Display the parameters that will be filled in the sructure exchanged with the action
	printf("PARAMETERS:\n"
	       "  input:       %s\n"
	       "  output:      %s\n"
	       "  type_in:     %x %s\n"
	       "  addr_in:     %016llx\n"
	       "  type_out:    %x %s\n"
	       "  addr_out:    %016llx\n"
	       "  size_in/out: %08lx\n",
	       "none", "none",
	       type_in,  mem_tab[type_in],  (long long)addr_in,
	       type_out, mem_tab[type_out], (long long)addr_out,
	       inputs_to_process);

	// Allocate the FPGA card that will be used for the processing
	snprintf(device, sizeof(device)-1, "/dev/cxl/afu%d.0s", card_no);
	card = snap_card_alloc_dev(device, SNAP_VENDOR_ID_IBM,
				   SNAP_DEVICE_ID_SNAP);
	if (card == NULL) {
		fprintf(stderr, "err: failed to open card %u: %s\n",
			card_no, strerror(errno));
                fprintf(stderr, "Default mode is FPGA mode.\n");
                fprintf(stderr, "Did you want to run CPU mode ? => add SNAP_CONFIG=CPU before your command.\n");
                fprintf(stderr, "Otherwise make sure you ran snap_find_card and snap_maint for your selected card.\n");

		goto out_error;
	}

	// Allocate the action that will be used for the processing
	action = snap_attach_action(card, DECIMALMULT_ACTION_TYPE, action_irq, 60);
	if (action == NULL) {
		fprintf(stderr, "err: failed to attach action %u: %s\n",
			card_no, strerror(errno));
		goto out_error1;
	}

	// Fil thes structure that will be exchnaged between this application and the action
	snap_prepare_decimal_mult(&cjob, &mjob,
			     (void *)addr_in,  inputs_to_process, type_in,
			     (void *)addr_out, inputs_to_process/3, type_out);

	//__hexdump(stderr, &mjob, sizeof(mjob));

	gettimeofday(&stime, NULL);
	// Send the structure to the action, start the action, wait for the completion
	rc = snap_action_sync_execute_job(action, &cjob, timeout);
	gettimeofday(&etime, NULL);

	fprintf(stdout, "Action processing decimal_mult took %lld usec\n",
		(long long)timediff_usec(&etime, &stime));

	// Test the return code of the action
	if (rc != 0) {
		fprintf(stderr, "err: job execution %d: %s!\n", rc,
			strerror(errno));
		goto out_error2;
	}

	(cjob.retc == SNAP_RETC_SUCCESS) ? fprintf(stdout, "SUCCESS\n") : fprintf(stdout, "FAILED\n");
	if (cjob.retc != SNAP_RETC_SUCCESS) {
		fprintf(stderr, "err: Unexpected RETC=%x!\n", cjob.retc);
		goto out_error2;
	}

        // Process data multiplying doubles/floats 3 by 3
        for ( int i = 0; i < inputs_to_process/3; i++ ) {
        	ref_result[i] = data_in[3*i] * data_in[(3*i)+1] * data_in[(3*i)+2];
        }

	fprintf(stdout, "In this example %d decimal numbers (%d bytes large) are used as inputs " \
		"(float=4B - double=8B)\n", (int)inputs_to_process, (int)sizeof(mat_elmt_t));
	fprintf(stdout, "Max value of inputs is set as %d (set in header file of include directory)\n",
		MAX_NB_OF_DECIMAL_READ);
	fprintf(stdout, "Operation is the multiplication of 3 decimals \n");
	fprintf(stdout, "\n All products results processed by (software or hardware) action are below \n");
        for ( int i = 0; i < inputs_to_process/3; i++ )
		fprintf(stdout, "inputs: %lf * %lf * %lf =>\t  expected: %lf \t action processed: %lf \n",
			data_in[3*i], data_in[(3*i)+1], data_in[(3*i)+2], *(data_out + i), *(ref_result + i));

	// This can help understanding how data are stored in host server
	if (verbose_flag) {
		fprintf(stdout, "DUMP of input data:\n");
		__hexdump(stderr, data_in,  (max_number_of_inputs * sizeof(mat_elmt_t)));
		fprintf(stdout, "DUMP of output data:\n");
		__hexdump(stderr, data_out, (max_number_of_inputs/3 * sizeof(mat_elmt_t)));
	}
	// if option has been selected write results to files for log and comparisons
	if (write_results) {
		fp_ref = fopen("dec_mult_ref.bin", "w");
		fp_action = fopen("dec_mult_action.bin", "w");
        	for ( int i = 0; i < inputs_to_process/3; i++ ) {
			fprintf(fp_ref, "%lf \n", *(ref_result + i));
			fprintf(fp_action, "%lf \n", *(data_out + i));
		}
		fclose(fp_ref);
		fclose(fp_action);
	}

	snap_detach_action(action);
	snap_card_free(card);

	__free(data_out);
	__free(data_in);
	exit(exit_code);

 out_error2:
	snap_detach_action(action);
 out_error1:
	snap_card_free(card);
 out_error:
	__free(data_out);
	__free(data_in);
	exit(EXIT_FAILURE);
}


text:
        adjust
        {{$node->name}}

            {{$node->description}}

            {{$node->info->employ_description}}


text:
   #ifndef ALLEGRO_STATICLINK
      #ifdef ALLEGRO_COLOR_SRC
         #define _ALLEGRO_COLOR_DLL __declspec(dllexport)
      #else
         #define _ALLEGRO_COLOR_DLL __declspec(dllimport)
      #endif
   #else
      #define _ALLEGRO_COLOR_DLL
   #endif
#endif

#if defined ALLEGRO_MSVC
   #define ALLEGRO_COLOR_FUNC(type, name, args)      _ALLEGRO_COLOR_DLL type __cdecl name args
#elif defined ALLEGRO_MINGW32
   #define ALLEGRO_COLOR_FUNC(type, name, args)      extern type name args
#elif defined ALLEGRO_BCC32
   #define ALLEGRO_COLOR_FUNC(type, name, args)      extern _ALLEGRO_COLOR_DLL type name args
#else
   #define ALLEGRO_COLOR_FUNC      AL_FUNC
#endif

#ifdef __cplusplus
   extern "C" {
#endif

ALLEGRO_COLOR_FUNC(uint32_t, al_get_allegro_color_version, (void));

ALLEGRO_COLOR_FUNC(void, al_color_hsv_to_rgb, (float hue, float saturation,
   float value, float *red, float *green, float *blue));
ALLEGRO_COLOR_FUNC(void, al_color_rgb_to_hsl, (float red, float green, float blue,
   float *hue, float *saturation, float *lightness));
ALLEGRO_COLOR_FUNC(void, al_color_rgb_to_hsv, (float red, float green, float blue,
   float *hue, float *saturation, float *value));
ALLEGRO_COLOR_FUNC(void, al_color_hsl_to_rgb, (float hue, float saturation, float lightness,
   float *red, float *green, float *blue));
ALLEGRO_COLOR_FUNC(bool, al_color_name_to_rgb, (char const *name, float *r, float *g,
   float *b));
ALLEGRO_COLOR_FUNC(const char*, al_color_rgb_to_name, (float r, float g, float b));
ALLEGRO_COLOR_FUNC(void, al_color_cmyk_to_rgb, (float cyan, float magenta, float yellow,
    float key, float *red, float *green, float *blue));
ALLEGRO_COLOR_FUNC(void, al_color_rgb_to_cmyk, (float red, float green, float blue,
   float *cyan, float *magenta, float *yellow, float *key));
ALLEGRO_COLOR_FUNC(void, al_color_yuv_to_rgb, (float y, float u, float v,
    float *red, float *green, float *blue));
ALLEGRO_COLOR_FUNC(void, al_color_rgb_to_yuv, (float red, float green, float blue,
   float *y, float *u, float *v));
ALLEGRO_COLOR_FUNC(void, al_color_rgb_to_html, (float red, float green, float blue,
    char *string));
ALLEGRO_COLOR_FUNC(void, al_color_html_to_rgb, (char const *string,
   float *red, float *green, float *blue));
ALLEGRO_COLOR_FUNC(ALLEGRO_COLOR, al_color_yuv, (float y, float u, float v));
ALLEGRO_COLOR_FUNC(ALLEGRO_COLOR, al_color_cmyk, (float c, float m, float y, float k));
ALLEGRO_COLOR_FUNC(ALLEGRO_COLOR, al_color_hsl, (float h, float s, float l));
ALLEGRO_COLOR_FUNC(ALLEGRO_COLOR, al_color_hsv, (float h, float s, float v));
ALLEGRO_COLOR_FUNC(ALLEGRO_COLOR, al_color_name, (char const *name));
ALLEGRO_COLOR_FUNC(ALLEGRO_COLOR, al_color_html, (char const *string));

#ifdef __cplusplus
   }
#endif

#endif


text:
  <ngm-conversation-header [conversationDetailItem]="conversationDetailItem"></ngm-conversation-header>

    <ngm-messages-list #messagesList [author]="author" [loadPerformer]="loadPerformer"></ngm-messages-list>

      <ngm-message-textfield (onPostText)="onPostText($event)"></ngm-message-textfield>


text:
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Schokotaler.Api.Common;
using Schokotaler.Api.Models;
using Schokotaler.Api.Models.Controllers.Transactions;
using Schokotaler.Api.Producers;
using Schokotaler.Api.Repository;

namespace Schokotaler.Api.Tasks {
    public class RecurringTask {
        private readonly ILogger _logger;
        private IIntervalRepository _intRepo;
        private IRecurrenceRepository _recRepo;
        private TransactionProducer _transProd;
        private IAccountRepository _accRepo;
        private ITransactionRepository _transRepo;
        private readonly IServiceProvider _sProv;

        public RecurringTask(ILogger<RecurringTask> logger, IServiceProvider serviceProvider) {
            _logger = logger;
            _sProv = serviceProvider;
        }

        public void Init() {
            using (IServiceScope scope =  _sProv.CreateScope()) {
                _intRepo = scope.ServiceProvider.GetRequiredService<IIntervalRepository>();
                _recRepo =  scope.ServiceProvider.GetRequiredService<IRecurrenceRepository>();
                _transProd = scope.ServiceProvider.GetRequiredService<TransactionProducer>();
                _accRepo = scope.ServiceProvider.GetRequiredService<IAccountRepository>();
                _transRepo = scope.ServiceProvider.GetRequiredService<ITransactionRepository>();
                _recRepo.Init(_intRepo);
            }
            _logger.LogDebug(LoggingEvents.TaskInit, "RecurringTask Initialized.");
        }

        public void ApplyTransactions(DateTime today, int daysInMonth) {
            int dayOfMonth = today.Day;
            int dayOfWeek = (int)today.DayOfWeek;
            _logger.LogInformation(LoggingEvents.TaskRun, "Task running for {dow} the {dom}.", today.DayOfWeek.ToString(), dayOfMonth.ToString());

            using (IServiceScope scope = _sProv.CreateScope()) {
                _intRepo = scope.ServiceProvider.GetRequiredService<IIntervalRepository>();
                _recRepo =  scope.ServiceProvider.GetRequiredService<IRecurrenceRepository>();
                _transProd = scope.ServiceProvider.GetRequiredService<TransactionProducer>();
                _accRepo = scope.ServiceProvider.GetRequiredService<IAccountRepository>();
                _transRepo = scope.ServiceProvider.GetRequiredService<ITransactionRepository>();
                var recurrences = _recRepo.GetRecurrencesForToday(dayOfWeek, dayOfMonth, daysInMonth == dayOfMonth);

                foreach (Recurrence item in recurrences) {
                    CreateTransaction(item);
                }
            }
        }

        private void CreateTransaction(Recurrence template) {
            TransactionPatch patch = new TransactionPatch {
                Amount = template.Transaction.Amount,
                CategoryId = template.Transaction.CategoryId,
                Description = template.Transaction.Description,
                FromAccountId = template.Transaction.FromAccountId,
                Title = template.Transaction.Title,
                ToAccountId = template.Transaction.ToAccountId
            };
            long uid = template.Transaction.UserId;
            long? tid = _transProd.Create(uid, patch, _transRepo, _accRepo, template.Transaction.Id);
            if (tid.HasValue) {
                _logger.LogInformation(LoggingEvents.TaskRun, "Recurrence create Transaction with Id {tid}", tid.ToString());
            } else {
                _logger.LogError(LoggingEvents.TaskError, "Error creating transation for template {temp}", template.Id);
            }
        }
    }
}


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

    <RelativeLayout
        android:id="@+id/header_bar_photo_browse"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/album_header_bar_height"
        android:background="@color/common_title_bg" >

        <ImageView
            android:id="@+id/header_bar_photo_back"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:paddingLeft="@dimen/title_view_left_back_padding_left"
            android:paddingRight="5.0dip"
            android:scaleType="fitCenter"
            android:src="@drawable/icon_back2" />

        <TextView
            android:id="@+id/header_bar_photo_count"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:paddingLeft="20dip"
            android:paddingRight="@dimen/dimen_10"
            android:layout_toRightOf="@id/header_bar_photo_back"
            android:gravity="center"
            android:singleLine="true"
            android:textColor="@color/primary_title_text_color"
            android:textSize="22.0sp" />

        <ImageView
            android:id="@+id/header_bar_photo_delete"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentRight="true"
            android:paddingRight="@dimen/dimen_15"
            android:paddingLeft="5.0dip"
            android:scaleType="fitCenter"
            android:src="@drawable/post_pager_delete"
            android:visibility="gone" />

        <TextView
            android:id="@+id/header_save"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:minWidth="50dip"
            android:gravity="center"
            android:background="@drawable/album_finish"
            android:textColor="#ffffff"
            android:layout_marginRight="@dimen/dimen_10"
            android:text="保存"
            android:visibility="gone"
            android:layout_height="30dip" />
    </RelativeLayout>

</LinearLayout>


text:
package org.keycloak.testsuite;

/**
 * @author Stian Thorgersen
 */
public class Retry {

    public static void execute(Runnable runnable, int retry, long interval) throws InterruptedException {
        while (true) {
            try {
                runnable.run();
                return;
            } catch (RuntimeException e) {
                retry--;
                if (retry > 0) {
                   Thread.sleep(interval);
                } else {
                    throw e;
                }
            }
        }
    }

}


text:
DevToolsEyeDropper::DevToolsEyeDropper(content::WebContents* web_contents,
                                       EyeDropperCallback callback)
    : content::WebContentsObserver(web_contents),
      callback_(callback),
      last_cursor_x_(-1),
      last_cursor_y_(-1),
      host_(nullptr) {
  mouse_event_callback_ =
      base::Bind(&DevToolsEyeDropper::HandleMouseEvent, base::Unretained(this));
  content::RenderViewHost* rvh = web_contents->GetRenderViewHost();
  if (rvh)
    AttachToHost(rvh->GetWidget());
}

DevToolsEyeDropper::~DevToolsEyeDropper() {
  DetachFromHost();
}

void DevToolsEyeDropper::AttachToHost(content::RenderWidgetHost* host) {
  host_ = host;
  host_->AddMouseEventCallback(mouse_event_callback_);

  // The view can be null if the renderer process has crashed.
  // (https://crbug.com/847363)
  if (!host_->GetView())
    return;

  // Capturing a full-page screenshot can be costly so we shouldn't do it too
  // often. We can capture at a lower frame rate without hurting the user
  // experience.
  constexpr static int kMaxFrameRate = 15;

  // Create and configure the video capturer.
  video_capturer_ = host_->GetView()->CreateVideoCapturer();
  video_capturer_->SetResolutionConstraints(
      host_->GetView()->GetViewBounds().size(),
      host_->GetView()->GetViewBounds().size(), true);
  video_capturer_->SetAutoThrottlingEnabled(false);
  video_capturer_->SetMinSizeChangePeriod(base::TimeDelta());
  video_capturer_->SetFormat(media::PIXEL_FORMAT_ARGB,
                             gfx::ColorSpace::CreateREC709());
  video_capturer_->SetMinCapturePeriod(base::TimeDelta::FromSeconds(1) /
                                       kMaxFrameRate);
  video_capturer_->Start(this);
}

void DevToolsEyeDropper::DetachFromHost() {
  if (!host_)
    return;
  host_->RemoveMouseEventCallback(mouse_event_callback_);
  ui::Cursor cursor(ui::mojom::CursorType::kPointer);
  host_->SetCursor(cursor);
  video_capturer_.reset();
  host_ = nullptr;
}

void DevToolsEyeDropper::RenderViewCreated(content::RenderViewHost* host) {
  if (!host_)
    AttachToHost(host->GetWidget());
}

void DevToolsEyeDropper::RenderViewDeleted(content::RenderViewHost* host) {
  if (host->GetWidget() == host_) {
    DetachFromHost();
    ResetFrame();
  }
}

void DevToolsEyeDropper::RenderViewHostChanged(
    content::RenderViewHost* old_host,
    content::RenderViewHost* new_host) {
  if ((old_host && old_host->GetWidget() == host_) || (!old_host && !host_)) {
    DetachFromHost();
    AttachToHost(new_host->GetWidget());
  }
}

void DevToolsEyeDropper::ResetFrame() {
  frame_.reset();
  last_cursor_x_ = -1;
  last_cursor_y_ = -1;
}

bool DevToolsEyeDropper::HandleMouseEvent(const blink::WebMouseEvent& event) {
  last_cursor_x_ = event.PositionInWidget().x();
  last_cursor_y_ = event.PositionInWidget().y();
  if (frame_.drawsNothing())
    return true;

  if (event.button == blink::WebMouseEvent::Button::kLeft &&
      (event.GetType() == blink::WebInputEvent::Type::kMouseDown ||
       event.GetType() == blink::WebInputEvent::Type::kMouseMove)) {
    if (last_cursor_x_ < 0 || last_cursor_x_ >= frame_.width() ||
        last_cursor_y_ < 0 || last_cursor_y_ >= frame_.height()) {
      return true;
    }

    SkColor sk_color = frame_.getColor(last_cursor_x_, last_cursor_y_);

    // The picked colors are expected to be sRGB. Convert from |frame_|'s color
    // space to sRGB.
    SkPixmap pm(
        SkImageInfo::Make(1, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType,
                          frame_.refColorSpace()),
        &sk_color, sizeof(sk_color));
    uint8_t rgba_color[4];
    bool ok = pm.readPixels(
        SkImageInfo::Make(1, 1, kRGBA_8888_SkColorType, kUnpremul_SkAlphaType,
                          SkColorSpace::MakeSRGB()),
        rgba_color, sizeof(rgba_color));
    DCHECK(ok);

    callback_.Run(rgba_color[0], rgba_color[1], rgba_color[2], rgba_color[3]);
  }
  UpdateCursor();
  return true;
}

void DevToolsEyeDropper::UpdateCursor() {
  if (!host_ || frame_.drawsNothing())
    return;

  if (last_cursor_x_ < 0 || last_cursor_x_ >= frame_.width() ||
      last_cursor_y_ < 0 || last_cursor_y_ >= frame_.height()) {
    return;
  }

// Due to platform limitations, we are using two different cursors
// depending on the platform. Mac and Win have large cursors with two circles
// for original spot and its magnified projection; Linux gets smaller (64 px)
// magnified projection only with centered hotspot.
// Mac Retina requires cursor to be > 120px in order to render smoothly.

#if defined(OS_LINUX)
  const float kCursorSize = 63;
  const float kDiameter = 63;
  const float kHotspotOffset = 32;
  const float kHotspotRadius = 0;
  const float kPixelSize = 9;
#else
  const float kCursorSize = 150;
  const float kDiameter = 110;
  const float kHotspotOffset = 25;
  const float kHotspotRadius = 5;
  const float kPixelSize = 10;
#endif

  content::ScreenInfo screen_info;
  host_->GetScreenInfo(&screen_info);
  double device_scale_factor = screen_info.device_scale_factor;

  SkBitmap result;
  result.allocN32Pixels(kCursorSize * device_scale_factor,
                        kCursorSize * device_scale_factor);
  result.eraseARGB(0, 0, 0, 0);

  SkCanvas canvas(result);
  canvas.scale(device_scale_factor, device_scale_factor);
  canvas.translate(0.5f, 0.5f);

  SkPaint paint;

  // Paint original spot with cross.
  if (kHotspotRadius > 0) {
    paint.setStrokeWidth(1);
    paint.setAntiAlias(false);
    paint.setColor(SK_ColorDKGRAY);
    paint.setStyle(SkPaint::kStroke_Style);

    canvas.drawLine(kHotspotOffset, kHotspotOffset - 2 * kHotspotRadius,
                    kHotspotOffset, kHotspotOffset - kHotspotRadius, paint);
    canvas.drawLine(kHotspotOffset, kHotspotOffset + kHotspotRadius,
                    kHotspotOffset, kHotspotOffset + 2 * kHotspotRadius, paint);
    canvas.drawLine(kHotspotOffset - 2 * kHotspotRadius, kHotspotOffset,
                    kHotspotOffset - kHotspotRadius, kHotspotOffset, paint);
    canvas.drawLine(kHotspotOffset + kHotspotRadius, kHotspotOffset,
                    kHotspotOffset + 2 * kHotspotRadius, kHotspotOffset, paint);

    paint.setStrokeWidth(2);
    paint.setAntiAlias(true);
    canvas.drawCircle(kHotspotOffset, kHotspotOffset, kHotspotRadius, paint);
  }

  // Clip circle for magnified projection.
  float padding = (kCursorSize - kDiameter) / 2;
  SkPath clip_path;
  clip_path.addOval(SkRect::MakeXYWH(padding, padding, kDiameter, kDiameter));
  clip_path.close();
  canvas.clipPath(clip_path, SkClipOp::kIntersect, true);

  // Project pixels.
  int pixel_count = kDiameter / kPixelSize;
  SkRect src_rect = SkRect::MakeXYWH(last_cursor_x_ - pixel_count / 2,
                                     last_cursor_y_ - pixel_count / 2,
                                     pixel_count, pixel_count);
  SkRect dst_rect = SkRect::MakeXYWH(padding, padding, kDiameter, kDiameter);
  canvas.drawBitmapRect(frame_, src_rect, dst_rect, NULL);

  // Paint grid.
  paint.setStrokeWidth(1);
  paint.setAntiAlias(false);
  paint.setColor(SK_ColorGRAY);
  for (int i = 0; i < pixel_count; ++i) {
    canvas.drawLine(padding + i * kPixelSize, padding, padding + i * kPixelSize,
                    kCursorSize - padding, paint);
    canvas.drawLine(padding, padding + i * kPixelSize, kCursorSize - padding,
                    padding + i * kPixelSize, paint);
  }

  // Paint central pixel in red.
  SkRect pixel =
      SkRect::MakeXYWH((kCursorSize - kPixelSize) / 2,
                       (kCursorSize - kPixelSize) / 2, kPixelSize, kPixelSize);
  paint.setColor(SK_ColorRED);
  paint.setStyle(SkPaint::kStroke_Style);
  canvas.drawRect(pixel, paint);

  // Paint outline.
  paint.setStrokeWidth(2);
  paint.setColor(SK_ColorDKGRAY);
  paint.setAntiAlias(true);
  canvas.drawCircle(kCursorSize / 2, kCursorSize / 2, kDiameter / 2, paint);

  ui::Cursor cursor(ui::mojom::CursorType::kCustom);
  cursor.set_image_scale_factor(device_scale_factor);
  cursor.set_custom_bitmap(result);
  cursor.set_custom_hotspot(gfx::Point(kHotspotOffset * device_scale_factor,
                                       kHotspotOffset * device_scale_factor));
  host_->SetCursor(cursor);
}

void DevToolsEyeDropper::OnFrameCaptured(
    base::ReadOnlySharedMemoryRegion data,
    ::media::mojom::VideoFrameInfoPtr info,
    const gfx::Rect& content_rect,
    mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks>
        callbacks) {
  gfx::Size view_size = host_->GetView()->GetViewBounds().size();
  if (view_size != content_rect.size()) {
    video_capturer_->SetResolutionConstraints(view_size, view_size, true);
    video_capturer_->RequestRefreshFrame();
    return;
  }

  mojo::Remote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks>
      callbacks_remote(std::move(callbacks));

  if (!data.IsValid()) {
    callbacks_remote->Done();
    return;
  }
  base::ReadOnlySharedMemoryMapping mapping = data.Map();
  if (!mapping.IsValid()) {
    DLOG(ERROR) << "Shared memory mapping failed.";
    return;
  }
  if (mapping.size() <
      media::VideoFrame::AllocationSize(info->pixel_format, info->coded_size)) {
    DLOG(ERROR) << "Shared memory size was less than expected.";
    return;
  }
  if (!info->color_space) {
    DLOG(ERROR) << "Missing mandatory color space info.";
    return;
  }

  // The SkBitmap's pixels will be marked as immutable, but the installPixels()
  // API requires a non-const pointer. So, cast away the const.
  void* const pixels = const_cast<void*>(mapping.memory());

  // Call installPixels() with a |releaseProc| that: 1) notifies the capturer
  // that this consumer has finished with the frame, and 2) releases the shared
  // memory mapping.
  struct FramePinner {
    // Keeps the shared memory that backs |frame_| mapped.
    base::ReadOnlySharedMemoryMapping mapping;
    // Prevents FrameSinkVideoCapturer from recycling the shared memory that
    // backs |frame_|.
    mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks>
        releaser;
  };
  frame_.installPixels(
      SkImageInfo::MakeN32(content_rect.width(), content_rect.height(),
                           kPremul_SkAlphaType,
                           info->color_space->ToSkColorSpace()),
      pixels,
      media::VideoFrame::RowBytes(media::VideoFrame::kARGBPlane,
                                  info->pixel_format, info->coded_size.width()),
      [](void* addr, void* context) {
        delete static_cast<FramePinner*>(context);
      },
      new FramePinner{std::move(mapping), callbacks_remote.Unbind()});
  frame_.setImmutable();

  UpdateCursor();
}

void DevToolsEyeDropper::OnStopped() {}


text:
#include <aws/cloudformation/model/TypeConfigurationDetails.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace CloudFormation
{
namespace Model
{

TypeConfigurationDetails::TypeConfigurationDetails() :
    m_arnHasBeenSet(false),
    m_aliasHasBeenSet(false),
    m_configurationHasBeenSet(false),
    m_lastUpdatedHasBeenSet(false),
    m_typeArnHasBeenSet(false),
    m_typeNameHasBeenSet(false),
    m_isDefaultConfiguration(false),
    m_isDefaultConfigurationHasBeenSet(false)
{
}

TypeConfigurationDetails::TypeConfigurationDetails(const XmlNode& xmlNode) :
    m_arnHasBeenSet(false),
    m_aliasHasBeenSet(false),
    m_configurationHasBeenSet(false),
    m_lastUpdatedHasBeenSet(false),
    m_typeArnHasBeenSet(false),
    m_typeNameHasBeenSet(false),
    m_isDefaultConfiguration(false),
    m_isDefaultConfigurationHasBeenSet(false)
{
  *this = xmlNode;
}

TypeConfigurationDetails& TypeConfigurationDetails::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode arnNode = resultNode.FirstChild("Arn");
    if(!arnNode.IsNull())
    {
      m_arn = Aws::Utils::Xml::DecodeEscapedXmlText(arnNode.GetText());
      m_arnHasBeenSet = true;
    }
    XmlNode aliasNode = resultNode.FirstChild("Alias");
    if(!aliasNode.IsNull())
    {
      m_alias = Aws::Utils::Xml::DecodeEscapedXmlText(aliasNode.GetText());
      m_aliasHasBeenSet = true;
    }
    XmlNode configurationNode = resultNode.FirstChild("Configuration");
    if(!configurationNode.IsNull())
    {
      m_configuration = Aws::Utils::Xml::DecodeEscapedXmlText(configurationNode.GetText());
      m_configurationHasBeenSet = true;
    }
    XmlNode lastUpdatedNode = resultNode.FirstChild("LastUpdated");
    if(!lastUpdatedNode.IsNull())
    {
      m_lastUpdated = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(lastUpdatedNode.GetText()).c_str()).c_str(), Aws::Utils::DateFormat::ISO_8601);
      m_lastUpdatedHasBeenSet = true;
    }
    XmlNode typeArnNode = resultNode.FirstChild("TypeArn");
    if(!typeArnNode.IsNull())
    {
      m_typeArn = Aws::Utils::Xml::DecodeEscapedXmlText(typeArnNode.GetText());
      m_typeArnHasBeenSet = true;
    }
    XmlNode typeNameNode = resultNode.FirstChild("TypeName");
    if(!typeNameNode.IsNull())
    {
      m_typeName = Aws::Utils::Xml::DecodeEscapedXmlText(typeNameNode.GetText());
      m_typeNameHasBeenSet = true;
    }
    XmlNode isDefaultConfigurationNode = resultNode.FirstChild("IsDefaultConfiguration");
    if(!isDefaultConfigurationNode.IsNull())
    {
      m_isDefaultConfiguration = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(isDefaultConfigurationNode.GetText()).c_str()).c_str());
      m_isDefaultConfigurationHasBeenSet = true;
    }
  }

  return *this;
}

void TypeConfigurationDetails::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_arnHasBeenSet)
  {
      oStream << location << index << locationValue << ".Arn=" << StringUtils::URLEncode(m_arn.c_str()) << "&";
  }

  if(m_aliasHasBeenSet)
  {
      oStream << location << index << locationValue << ".Alias=" << StringUtils::URLEncode(m_alias.c_str()) << "&";
  }

  if(m_configurationHasBeenSet)
  {
      oStream << location << index << locationValue << ".Configuration=" << StringUtils::URLEncode(m_configuration.c_str()) << "&";
  }

  if(m_lastUpdatedHasBeenSet)
  {
      oStream << location << index << locationValue << ".LastUpdated=" << StringUtils::URLEncode(m_lastUpdated.ToGmtString(Aws::Utils::DateFormat::ISO_8601).c_str()) << "&";
  }

  if(m_typeArnHasBeenSet)
  {
      oStream << location << index << locationValue << ".TypeArn=" << StringUtils::URLEncode(m_typeArn.c_str()) << "&";
  }

  if(m_typeNameHasBeenSet)
  {
      oStream << location << index << locationValue << ".TypeName=" << StringUtils::URLEncode(m_typeName.c_str()) << "&";
  }

  if(m_isDefaultConfigurationHasBeenSet)
  {
      oStream << location << index << locationValue << ".IsDefaultConfiguration=" << std::boolalpha << m_isDefaultConfiguration << "&";
  }

}

void TypeConfigurationDetails::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_arnHasBeenSet)
  {
      oStream << location << ".Arn=" << StringUtils::URLEncode(m_arn.c_str()) << "&";
  }
  if(m_aliasHasBeenSet)
  {
      oStream << location << ".Alias=" << StringUtils::URLEncode(m_alias.c_str()) << "&";
  }
  if(m_configurationHasBeenSet)
  {
      oStream << location << ".Configuration=" << StringUtils::URLEncode(m_configuration.c_str()) << "&";
  }
  if(m_lastUpdatedHasBeenSet)
  {
      oStream << location << ".LastUpdated=" << StringUtils::URLEncode(m_lastUpdated.ToGmtString(Aws::Utils::DateFormat::ISO_8601).c_str()) << "&";
  }
  if(m_typeArnHasBeenSet)
  {
      oStream << location << ".TypeArn=" << StringUtils::URLEncode(m_typeArn.c_str()) << "&";
  }
  if(m_typeNameHasBeenSet)
  {
      oStream << location << ".TypeName=" << StringUtils::URLEncode(m_typeName.c_str()) << "&";
  }
  if(m_isDefaultConfigurationHasBeenSet)
  {
      oStream << location << ".IsDefaultConfiguration=" << std::boolalpha << m_isDefaultConfiguration << "&";
  }
}

} // namespace Model
} // namespace CloudFormation
} // namespace Aws


text:
package org.springframework.boot.actuate.audit;

import java.time.Instant;
import java.util.Collections;

import net.minidev.json.JSONArray;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.web.reactive.server.WebTestClient;

/**
 * Integration tests for {@link AuditEventsEndpoint} exposed by Jersey, Spring MVC, and
 * WebFlux.
 *
 * @author Vedran Pavic
 * @author Andy Wilkinson
 */
@RunWith(WebEndpointRunners.class)
public class AuditEventsEndpointWebIntegrationTests {

	private static WebTestClient client;

	@Test
	public void allEvents() {
		client.get().uri((builder) -> builder.path("/actuator/auditevents").build())
				.exchange().expectStatus().isOk().expectBody()
				.jsonPath("events.[*].principal")
				.isEqualTo(new JSONArray().appendElement("admin").appendElement("admin")
						.appendElement("user"));
	}

	@Test
	public void eventsAfter() {
		client.get()
				.uri((builder) -> builder.path("/actuator/auditevents")
						.queryParam("after", "2016-11-01T13:00:00%2B00:00").build())
				.exchange().expectStatus().isOk().expectBody().jsonPath("events")
				.isEmpty();
	}

	@Test
	public void eventsWithPrincipal() {
		client.get()
				.uri((builder) -> builder.path("/actuator/auditevents")
						.queryParam("principal", "user").build())
				.exchange().expectStatus().isOk().expectBody()
				.jsonPath("events.[*].principal")
				.isEqualTo(new JSONArray().appendElement("user"));
	}

	@Test
	public void eventsWithType() {
		client.get()
				.uri((builder) -> builder.path("/actuator/auditevents")
						.queryParam("type", "logout").build())
				.exchange().expectStatus().isOk().expectBody()
				.jsonPath("events.[*].principal")
				.isEqualTo(new JSONArray().appendElement("admin"))
				.jsonPath("events.[*].type")
				.isEqualTo(new JSONArray().appendElement("logout"));
	}

	@Configuration(proxyBeanMethods = false)
	protected static class TestConfiguration {

		@Bean
		public AuditEventRepository auditEventsRepository() {
			AuditEventRepository repository = new InMemoryAuditEventRepository(3);
			repository.add(createEvent("2016-11-01T11:00:00Z", "admin", "login"));
			repository.add(createEvent("2016-11-01T12:00:00Z", "admin", "logout"));
			repository.add(createEvent("2016-11-01T12:00:00Z", "user", "login"));
			return repository;
		}

		@Bean
		public AuditEventsEndpoint auditEventsEndpoint(
				AuditEventRepository auditEventRepository) {
			return new AuditEventsEndpoint(auditEventRepository);
		}

		private AuditEvent createEvent(String instant, String principal, String type) {
			return new AuditEvent(Instant.parse(instant), principal, type,
					Collections.emptyMap());
		}

	}

}


text:
package sys

import (
	"syscall"
	"unsafe"
)

// PR_SET_CHILD_SUBREAPER allows setting the child subreaper.
// If arg2 is nonzero, set the "child subreaper" attribute of the
// calling process; if arg2 is zero, unset the attribute.  When a
// process is marked as a child subreaper, all of the children
// that it creates, and their descendants, will be marked as
// having a subreaper.  In effect, a subreaper fulfills the role
// of init(1) for its descendant processes.  Upon termination of
// a process that is orphaned (i.e., its immediate parent has
// already terminated) and marked as having a subreaper, the
// nearest still living ancestor subreaper will receive a SIGCHLD
// signal and be able to wait(2) on the process to discover its
// termination status.
const prSetChildSubreaper = 36

// PR_GET_CHILD_SUBREAPER allows retrieving the current child
// subreaper.
// Returns the "child subreaper" setting of the caller, in the
// location pointed to by (int *) arg2.
const prGetChildSubreaper = 37

// GetSubreaper returns the subreaper setting for the calling process
func GetSubreaper() (int, error) {
	var i uintptr
	if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, prGetChildSubreaper, uintptr(unsafe.Pointer(&i)), 0); err != 0 {
		return -1, err
	}
	return int(i), nil
}

// SetSubreaper sets the value i as the subreaper setting for the calling process
func SetSubreaper(i int) error {
	if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, prSetChildSubreaper, uintptr(i), 0); err != 0 {
		return err
	}
	return nil
}


text:
require 'resolv'

class Trial < ActiveRecord::Base

  EMAIL_PATTERN = /(\S+)@(\S+)/

  validates_format_of :customeremail, :with => EMAIL_PATTERN
  validates_uniqueness_of :customeremail

  def validate
    unless errors[:customeremail].count >= 1
    #unless errors.on(:customeremail)
      unless valid_domain?(customeremail)
        errors.add(:customeremail, 'domain name appears to be incorrect')
      end
    end
  end

  SERVER_TIMEOUT = 3 # seconds

  def valid_domain?(email)
    domain = email.match(EMAIL_PATTERN)[2]

    dns = Resolv::DNS.new

    Timeout::timeout(SERVER_TIMEOUT) do
      # Check the MX records
      mx_records =
        dns.getresources(domain, Resolv::DNS::Resource::IN::MX)

      mx_records.sort_by {|mx| mx.preference}.each do |mx|
        a_records = dns.getresources(mx.exchange.to_s,
                                     Resolv::DNS::Resource::IN::A)
        return true if a_records.any?
      end

      # Try a straight A record
      a_records = dns.getresources(domain, Resolv::DNS::Resource::IN::A)
      a_records.any?
    end
  rescue Timeout::Error, Errno::ECONNREFUSED
    false
  end

  # Check if the trials has expired
  def expired?
    created_at < 14.days.ago && updated_at < 14.days.ago
  end

  # Check if the trial has reached the point of deletion threshold
  def threshold?
    created_at < 200.days.ago && updated_at < 200.days.ago
  end

  # Extend the livetrial by 14 days
  def extendbyfourteendays
    updated_at = Time.now
  end

  # Extend the livetrial by 30 days
  def extendbythirthydays
    update_at = update_at + 14.days.from_now
  end

  # This function gets the trialpw from the instance
  def sftptrialpwget( host, username, password )
    require 'net/ssh'
    require 'net/http'
    require 'net/sftp'

    @trialpw = nil
    uri = URI.parse("http://#{host}")

    begin
      # Check if the server is up first for four minutes
      # Using HTTP
      Timeout::timeout(240) do
        begin
          while ( Net::HTTP.get_response(uri).code != "200" ) do
            sleep 2
          end
        rescue Errno::ECONNREFUSED
          # Connection refused means the server is coming up
          # But the SnapLogic server is not up yet
          retry
        end
      end

      Net::SFTP.start(host, username, :password => password) do |sftp|
        begin
          @data = sftp.download!("/opt/snaplogic/config/textpasswords").split('\n')
        rescue RuntimeError
          # File not found maybe a earlier version of snaplogic
          @data = nil
          @trialpw = 'thinkcloud'
        end

        @data.each do |entry|
          entry = entry.split(' ')
          if (entry.first == "admin:")
             @trialpw = entry.second
             break
          end
        end
      end

    rescue Timeout::Error
      # This means that the server didn't come up, timeout
      raise
    rescue Net::SSH::AuthenticationFailed
      # Do nothing "Authentication failed"
    rescue SocketError
      # Do nothing the hostname is bogus
    end # end of rescue
    @trialpw
  end

  def check_provision_status( host, username, password)
    require 'net/ssh'
    require 'net/http'
    require 'net/sftp'

    uri = URI.parse("http://#{host}/__snap__/__static__/protected/ground.cert")

    begin
      # Using HTTP
      Timeout::timeout(240) do
        begin
          if ( Net::HTTP.get_response(uri).code == "404" ) then
            status = "Provisioned"
          elsif ( Net::HTTP.get_response(uri).code == "200" ) then
            status = "Not provisioned"
          else
            status = "Unknown"
          end
        rescue Errno::ECONNREFUSED
          puts "Exception"
          # Connection refused means the server is coming up
          # But the SnapLogic server is not up yet
        end
      end

    rescue Timeout::Error
      # This means that the server is not up, timeout
       status = "Down"
    end # End of rescue
    status
  end

  def check_provision_return_code( host, username, password)
    require 'net/ssh'
    require 'net/http'
    require 'net/sftp'

    @uri = URI.parse("http://#{host}/__snap__/__static__/protected/ground.cert")

    @request = Net::HTTP::Get.new(@uri.request_uri)
    @request.basic_auth username, password

    begin
      @response = Net::HTTP.start(@uri.host, @uri.port) {|http|
        http.request(@request)
      }
      @response.code
    rescue SocketError => e
      puts "Exception: " + e
    rescue
      puts "General exception"
    end

  end

end


text:
package com.indix.gocd.s3fetch;

import com.indix.gocd.utils.Context;
import com.indix.gocd.utils.GoEnvironment;
import com.indix.gocd.utils.TaskExecutionResult;
import com.indix.gocd.utils.store.S3ArtifactStore;
import com.thoughtworks.go.plugin.api.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import static com.indix.gocd.utils.Constants.*;

public abstract class FetchExecutor {
    private static Logger logger = Logger.getLoggerFor(FetchExecutor.class);

    public TaskExecutionResult execute(Config config, final Context context) {

        try {
            final GoEnvironment env = new GoEnvironment(context.getEnvironmentVariables());
            String artifactPathOnS3 = getArtifactsLocationTemplate(config, env);
            final String bucket = getBucket(config, env);
            final S3ArtifactStore store = getS3ArtifactStore(env, bucket);

            String destination = String.format("%s/%s", context.getWorkingDir(), config.getDestination());
            context.printMessage(String.format("Getting artifacts from %s to %s", store.pathString(artifactPathOnS3), destination));
            if(StringUtils.isNotBlank(config.getDestination())) {
                setupDestinationDirectory(destination);
            }
            store.getPrefix(artifactPathOnS3, destination);
            return new TaskExecutionResult(true, "Fetched all artifacts");
        } catch (Exception e) {
            String message = String.format("Failure while downloading artifacts - %s", e.getMessage());
            logger.error(message, e);
            return new TaskExecutionResult(false, message, e);
        }
    }

    protected S3ArtifactStore getS3ArtifactStore(GoEnvironment env, String bucket) {
        return new S3ArtifactStore(env, bucket);
    }

    private void setupDestinationDirectory(String destination) {
        File destinationDirectory = new File(destination);
        try {
            if(!destinationDirectory.exists()) {
                FileUtils.forceMkdir(destinationDirectory);
            }
        } catch (IOException ioe) {
            logger.error(String.format("Error while setting up destination - %s", ioe.getMessage()), ioe);
        }
    }

    protected String getBucket(Config config, GoEnvironment env) {
        if(env.isAbsent(GO_ARTIFACTS_S3_BUCKET)) {
            throw new RuntimeException("S3 bucket to fetch from should be from material plugin or GO_ARTIFACTS_S3_BUCKET env var.");
        }

        return env.get(GO_ARTIFACTS_S3_BUCKET);
    }

    protected abstract String getArtifactsLocationTemplate(Config config, GoEnvironment env);

    public abstract Map<String,String> validate(Config config);
}


text:
#pragma once

#include <memory>
#include <optional>
#include <string>

#include "rocksdb/db.h"
#include "logging/Logger.h"
#include "RocksDbUtils.h"
#include "OpenRocksDb.h"

namespace org::apache::nifi::minifi::internal {

class RocksDbInstance;

/**
 * Purpose: represents a column in a RocksDbInstance.
 * There can be multiple RocksDatabase handles to the same instance.
 */
class RocksDatabase {
 public:
  static std::unique_ptr<RocksDatabase> create(const DBOptionsPatch& db_options_patch,
                                               const ColumnFamilyOptionsPatch& cf_options_patch,
                                               const std::string& uri,
                                               RocksDbMode mode = RocksDbMode::ReadWrite);

  RocksDatabase(std::shared_ptr<RocksDbInstance> db, std::string column, const DBOptionsPatch& db_options_patch, const ColumnFamilyOptionsPatch& cf_options_patch);

  RocksDatabase(const RocksDatabase&) = delete;
  RocksDatabase(RocksDatabase&&) = delete;
  RocksDatabase& operator=(const RocksDatabase&) = delete;
  RocksDatabase& operator=(RocksDatabase&&) = delete;

  std::optional<OpenRocksDb> open();

  ~RocksDatabase();

 private:
  const std::string column_;
  std::shared_ptr<RocksDbInstance> db_;

  static std::shared_ptr<core::logging::Logger> logger_;
};

}  // namespace org::apache::nifi::minifi::internal


text:
<?php
require_once('params.php');

if($key) {
	if(auth($email, $key)) {
		resp(nextToken($email, $key));
	} else {
		resp('fail', 'authentication failed');
	}
} else {
	resp('fail', 'not enough params');
}

?>


text:
/**
 * \file consistent_hash_map_test.cpp
 *
 * \brief Unit test for Consistent Hashing class
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <string.h>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "vobla/consistent_hash_map.h"
#include "vobla/hash.h"
#include "vobla/range.h"
#include "vobla/status.h"

using std::numeric_limits;
using std::string;
using std::vector;
using std::to_string;
using ::testing::ContainerEq;

namespace vobla {

typedef ConsistentHashMap<size_t, string, 4> TestMap;

TEST(ConsistentHashMapTest, TestInsert) {
  TestMap test_map;
  vector<size_t> partitions;

  const string node1("node1");
  SHA1Digest hash1(node1);
  size_t hash_value1;
  memcpy(&hash_value1, hash1.digest(), sizeof(size_t));
  test_map.insert(hash_value1, node1);
  EXPECT_EQ(4u, test_map.num_partitions());
  partitions = test_map.get_partitions();
  EXPECT_EQ(4u, partitions.size());

  const string node2("node2");
  SHA1Digest hash2(node2);
  size_t hash_value2;
  memcpy(&hash_value2, hash2.digest(), sizeof(size_t));
  test_map.insert(hash_value2, node2);
  EXPECT_EQ(8u, test_map.num_partitions());
  partitions = test_map.get_partitions();
  EXPECT_EQ(8u, partitions.size());
}

TEST(ConsistentHashMapTest, TestRemove) {
  TestMap test_map;

  const string node1("node1");
  SHA1Digest hash1(node1);
  size_t hash_value1;
  memcpy(&hash_value1, hash1.digest(), sizeof(size_t));
  test_map.insert(hash_value1, node1);

  const string node2("node2");
  SHA1Digest hash2(node2);
  size_t hash_value2;
  memcpy(&hash_value2, hash2.digest(), sizeof(size_t));
  test_map.insert(hash_value2, node2);

  test_map.remove(hash_value2);
  EXPECT_EQ(4u, test_map.num_partitions());
  test_map.remove(hash_value1);
  EXPECT_EQ(0u, test_map.num_partitions());
}

TEST(ConsistentHashMapTest, TestGetPartitionOneNode) {
  TestMap test_map;
  const string node1("node1");
  test_map.insert(0, node1);
  vector<size_t> expected_parts;
  size_t range = numeric_limits<size_t>::max() / test_map.num_partitions();
  for (unsigned int i = 0; i < test_map.num_partitions(); i++) {
    expected_parts.push_back(range*i);
  }
  vector<size_t> actual_parts = test_map.get_partitions();
  EXPECT_THAT(actual_parts, ContainerEq(expected_parts));
}

TEST(ConsistentHashMapTest, TestGetRange) {
  TestMap test_map;
  typedef std::pair<string, Range<size_t>> node_range_type;
  const string node1("node1");
  test_map.insert(0, node1);
  size_t range = numeric_limits<size_t>::max() / test_map.num_partitions();
  vector<size_t> expected_parts;
  for (unsigned int i = 0; i < test_map.num_partitions(); i++) {
    expected_parts.push_back(range*i);
  }
  vector<size_t> actual_parts = test_map.get_partitions();
  EXPECT_THAT(actual_parts, ContainerEq(expected_parts));

  Range<size_t> range1(0, range - 1);
  Range<size_t> range2(range, range*2 - 1);
  Range<size_t> range3(range*2, range*3 - 1);
  Range<size_t> range4(range*3, numeric_limits<size_t>::max());
  node_range_type range1_node1 = std::make_pair(node1, range1);
  node_range_type range2_node1 = std::make_pair(node1, range2);
  node_range_type range3_node1 = std::make_pair(node1, range3);
  node_range_type range4_node1 = std::make_pair(node1, range4);
  node_range_type tmp;
  EXPECT_TRUE(test_map.get_range(range/2, &tmp).ok());
  EXPECT_EQ(range1_node1, tmp);
  EXPECT_TRUE(test_map.get_range(range + range/2, &tmp).ok());
  EXPECT_EQ(range2_node1, tmp);
  EXPECT_TRUE(test_map.get_range(range*2 + range/2, &tmp).ok());
  EXPECT_EQ(range3_node1, tmp);
  EXPECT_TRUE(test_map.get_range(range*3 + range/2, &tmp).ok());
  EXPECT_EQ(range4_node1, tmp);
}

TEST(ConsistentHashMapTest, TestGetMaxRange) {
  ConsistentHashMap<size_t, string, 1> test_map;
  const string node1("node1");
  const string node2("node2");
  const string node3("node3");
  const string node4("node4");
  Range<size_t> range;

  EXPECT_FALSE(test_map.get_max_range(&range).ok());

  test_map.insert(10, node1);
  EXPECT_TRUE(test_map.get_max_range(&range).ok());
  EXPECT_EQ(range.lower(), 10u);
  EXPECT_EQ(range.upper(), 10u);

  test_map.insert(100, node2);
  test_map.insert(500, node3);
  EXPECT_TRUE(test_map.get_max_range(&range).ok());
  EXPECT_EQ(range.lower(), 500u);
  EXPECT_EQ(range.upper(), 10u);

  test_map.insert(numeric_limits<size_t>::max() - 1, node4);
  EXPECT_TRUE(test_map.get_max_range(&range).ok());
  EXPECT_EQ(range.lower(), 500u);
  EXPECT_EQ(range.upper(), numeric_limits<size_t>::max() - 1);
}

TEST(ConsistentHashMapTest, TestGet) {
  TestMap test_map;
  const string node1("node1");
  test_map.insert(0, node1);
  const string node2("node2");
  // insert another node in the middle of the first nodes's range
  size_t hash_node2 = numeric_limits<size_t>::max() /
                      test_map.num_partitions() / 2;
  test_map.insert(hash_node2, node2);
  size_t range_node = numeric_limits<size_t>::max() / test_map.num_partitions();
  EXPECT_EQ(hash_node2, range_node);

  string tmp;
  for (int i = 0; i < 6; i++) {
    if (i % 2 == 0) {
      EXPECT_TRUE(test_map.get(range_node*i + range_node/2, &tmp).ok());
      EXPECT_EQ(node1, tmp);
    } else {
      EXPECT_TRUE(test_map.get(range_node*i + range_node/2, &tmp).ok());
      EXPECT_EQ(node2, tmp);
    }
  }
}

TEST(ConsistentHashMapTest, TestGetValues) {
  TestMap test_map;
  vector<string> expected_nodes;
  for (int i = 0; i < 10; ++i) {
    string node_name = string("node") + to_string(i);
    test_map.insert(i * 1000, node_name);
    expected_nodes.push_back(node_name);
  }
  vector<string> actual_nodes = test_map.get_values();
  EXPECT_THAT(actual_nodes, ContainerEq(expected_nodes));
}

TEST(ConsistentHashMapTest, TestSuccByValue) {
  TestMap test_map;
  const string node1("node1");
  test_map.insert(0, node1);
  const string node2("node2");
  test_map.insert(1000, node2);
  const string node3("node3");
  test_map.insert(2000, node3);

  string tmp;
  EXPECT_TRUE(test_map.succ_by_value(node1, &tmp).ok());
  EXPECT_EQ(node2, tmp);
}

TEST(ConsistentHashMapTest, TestSucc) {
  TestMap test_map;
  const string node1("node1");
  test_map.insert(0, node1);
  const string node2("node2");
  test_map.insert(1000, node2);
  const string node3("node3");
  test_map.insert(2000, node3);

  string tmp;
  EXPECT_EQ(-ENOENT, test_map.succ(500, &tmp).error());
  EXPECT_TRUE(test_map.succ(1000, &tmp).ok());
  EXPECT_EQ(node3, tmp);
  EXPECT_TRUE(test_map.succ(2000, &tmp).ok());
  EXPECT_EQ(node1, tmp);
}

TEST(ConsistentHashMapTest, TestPrevByValue) {
  TestMap test_map;
  const string node1("node1");
  test_map.insert(0, node1);
  const string node2("node2");
  test_map.insert(1000, node2);
  const string node3("node3");
  test_map.insert(2000, node3);

  string tmp;
  EXPECT_TRUE(test_map.prev_by_value(node3, &tmp).ok());
  EXPECT_EQ(node2, tmp);
  EXPECT_TRUE(test_map.prev_by_value(node1, &tmp).ok());
  EXPECT_EQ(node3, tmp);
}

TEST(ConsistentHashMapTest, TestPrev) {
  TestMap test_map;
  const string node1("node1");
  test_map.insert(0, node1);
  const string node2("node2");
  test_map.insert(1000, node2);
  const string node3("node3");
  test_map.insert(2000, node3);

  string tmp;
  EXPECT_EQ(-ENOENT, test_map.prev(500, &tmp).error());
  EXPECT_TRUE(test_map.prev(0, &tmp).ok());
  EXPECT_EQ(node3, tmp);
}

TEST(ConsistentHashMapTest, TestCopyConstructor) {
  TestMap test_map;
  for (int i = 0; i < 10; i++) {
    test_map.insert(0*100, string("node") + to_string(i));
  }
  vector<TestMap::key_type> partitions = test_map.get_partitions();

  TestMap copy_map = test_map;
  vector<TestMap::key_type> copy_partitions = copy_map.get_partitions();
  EXPECT_EQ(partitions, copy_partitions);
}

TEST(ConsistentHashMapTest, TestIterator) {
  TestMap test_map;
  for (int i = 0; i < 10; i++) {
    test_map.insert(i*100, string("node") + to_string(i));
  }

  TestMap::iterator it = test_map.begin();
  for (size_t i = 0; i < test_map.num_nodes(); ++i, ++it) {
    EXPECT_EQ(i*100, it->first);
    EXPECT_EQ(string("node") + to_string(i), it->second);
  }

  TestMap::const_iterator cit = test_map.begin();
  for (size_t i = 0; i < test_map.num_nodes(); ++i, ++cit) {
    EXPECT_EQ(i*100, cit->first);
    EXPECT_EQ(string("node") + to_string(i), cit->second);
  }
}

TEST(ConsistentHashMapTest, TestSinglePartition) {
  ConsistentHashMap<uint64_t, string, 1> test_map;
  test_map.insert(0, "p0");
  uint64_t sep = std::numeric_limits<uint64_t>::max() / 2;
  test_map.insert(sep, "p1");
}

TEST(ConsistentHashMapTest, TestNumNodes) {
  TestMap test_map;
  for (int i = 0; i < 10; i++) {
    test_map.insert(i*100, string("node") + to_string(i));
  }
  EXPECT_EQ(10u, test_map.num_nodes());
}

TEST(ConsistentHashMapTest, TestNumPartitions) {
  TestMap test_map;
  for (int i = 0; i < 10; i++) {
    test_map.insert(i*100, string("node") + to_string(i));
  }
  EXPECT_EQ(40u, test_map.num_partitions());
}

TEST(ConsistentHashMapTest, TestNumPartitionsPerNode) {
  TestMap test_map;
  EXPECT_EQ(4u, test_map.num_partitions_per_node());
}

TEST(ConsistentHashMapTest, TestInt64MapInsert) {
  typedef ConsistentHashMap<int64_t, int64_t> Int64Map;
  Int64Map test_map;
  int64_t part = std::numeric_limits<int64_t>::max() / 64;

  for (int64_t i = 0; i < 128; i++) {
    int64_t k = i * part;
    int64_t v = i * 2;
    EXPECT_TRUE(test_map.insert(k, v).ok());
  }
}

TEST(ConsistentHashMapTest, TestSwapTwoMaps) {
  TestMap map0 = { {1, "node1"}, {10, "node2"} };
  TestMap map1;
  map0.swap(map1);

  EXPECT_TRUE(map0.empty());

  size_t sep;
  string node;
  EXPECT_TRUE(map1.get(5, &sep, &node).ok());
  EXPECT_EQ(1u, sep);
  EXPECT_EQ("node1", node);
}

}  // namespace vobla


text:
/**
 * @memberOf Jymfony.Component.Validator.Fixtures.Constraints
 */
export default class Limit {
    __construct(value) {
        this._value = value;
    }

    get value() {
        return this._value;
    }
}