text:
/**
 * @file mali_kbase_config.h
 * Configuration API and Attributes for KBase
 */

#ifndef _KBASE_CONFIG_H_
#define _KBASE_CONFIG_H_

#include <malisw/mali_stdtypes.h>

/**
 * @addtogroup base_api
 * @{
 */

/**
 * @addtogroup base_kbase_api
 * @{
 */

/**
 * @addtogroup kbase_config Configuration API and Attributes
 * @{
 */

#if MALI_CUSTOMER_RELEASE == 0
/* This flag is set for internal builds so we can run tests without credentials. */
#define KBASE_HWCNT_DUMP_BYPASS_ROOT 1
#else
#define KBASE_HWCNT_DUMP_BYPASS_ROOT 0
#endif

#include <linux/rbtree.h>

/**
 * Device wide configuration
 */
enum {
	/**
	 * Invalid attribute ID (reserve 0).
	 *
	 * Attached value: Ignored
	 * Default value: NA
	 * */
	KBASE_CONFIG_ATTR_INVALID,

	/**
	 * Maximum frequency GPU will be clocked at. Given in kHz.
	 * This must be specified as there is no default value.
	 *
	 * Attached value: number in kHz
	 * Default value: NA
	 */
	KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MAX,

	/**
	 * Minimum frequency GPU will be clocked at. Given in kHz.
	 * This must be specified as there is no default value.
	 *
	 * Attached value: number in kHz
	 * Default value: NA
	 */
	KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MIN,

	/**
	 * Irq throttle. It is the minimum desired time in between two
	 * consecutive gpu interrupts (given in 'us'). The irq throttle
	 * gpu register will be configured after this, taking into
	 * account the configured max frequency.
	 *
	 * Attached value: number in micro seconds
	 * Default value: see DEFAULT_IRQ_THROTTLE_TIME_US
	 */
	KBASE_CONFIG_ATTR_GPU_IRQ_THROTTLE_TIME_US,

	/*** Begin Job Scheduling Configs ***/
	/**
	 * Job Scheduler scheduling tick granuality. This is in nanoseconds to
	 * allow HR timer support.
	 *
	 * On each scheduling tick, the scheduler may decide to:
	 * -# soft stop a job (the job will be re-run later, and other jobs will
	 * be able to run on the GPU now). This effectively controls the
	 * 'timeslice' given to a job.
	 * -# hard stop a job (to kill a job if it has spent too long on the GPU
	 * and didn't soft-stop).
	 *
	 * The numbers of ticks for these events are controlled by:
	 * - @ref KBASE_CONFIG_ATTR_JS_SOFT_STOP_TICKS
	 * - @ref KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_SS
	 * - @ref KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_NSS
	 *
	 * A soft-stopped job will later be resumed, allowing it to use more GPU
	 * time in total than that defined by any of the above. However,
	 * the scheduling policy attempts to limit the amount of \em uninterrupted
	 * time spent on the GPU using the above values (that is, the 'timeslice'
	 * of a job)
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::scheduling_tick_ns.
	 * The value might be rounded down to lower precision. Must be non-zero
	 * after rounding.

	 * Default value: @ref DEFAULT_JS_SCHEDULING_TICK_NS
	 *
	 * @note this value is allowed to be greater than
	 * @ref KBASE_CONFIG_ATTR_JS_CTX_TIMESLICE_NS. This allows jobs to run on (much)
	 * longer than the job-timeslice, but once this happens, the context gets
	 * scheduled in (much) less frequently than others that stay within the
	 * ctx-timeslice.
	 */
	KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS,

	/**
	 * Job Scheduler minimum number of scheduling ticks before non-CL jobs
	 * are soft-stopped.
	 *
	 * This defines the amount of time a job is allowed to stay on the GPU,
	 * before it is soft-stopped to allow other jobs to run.
	 *
	 * That is, this defines the 'timeslice' of the job. It is separate from the
	 * timeslice of the context that contains the job (see
	 * @ref KBASE_CONFIG_ATTR_JS_CTX_TIMESLICE_NS).
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::soft_stop_ticks

	 * Default value: @ref DEFAULT_JS_SOFT_STOP_TICKS
	 *
	 * @note a value of zero means "the quickest time to soft-stop a job",
	 * which is somewhere between instant and one tick later.
	 *
	 * @note this value is allowed to be greater than
	 * @ref KBASE_CONFIG_ATTR_JS_RESET_TICKS_SS or
	 * @ref KBASE_CONFIG_ATTR_JS_RESET_TICKS_NSS. This effectively disables
	 * soft-stop, and just uses hard-stop instead. In this case, this value
	 * should be much greater than any of the hard stop values (to avoid
	 * soft-stop-after-hard-stop)
	 *
	 * @see KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS
	 */
	KBASE_CONFIG_ATTR_JS_SOFT_STOP_TICKS,

	/**
	 * Job Scheduler minimum number of scheduling ticks before CL jobs
	 * are soft-stopped.
	 *
	 * This defines the amount of time a job is allowed to stay on the GPU,
	 * before it is soft-stopped to allow other jobs to run.
	 *
	 * That is, this defines the 'timeslice' of the job. It is separate
	 * from the timeslice of the context that contains the job (see
	 * @ref KBASE_CONFIG_ATTR_JS_CTX_TIMESLICE_NS).
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit
	 *                         kbasep_js_device_data::soft_stop_ticks_cl

	 * Default value: @ref DEFAULT_JS_SOFT_STOP_TICKS_CL
	 *
	 * @note a value of zero means "the quickest time to soft-stop a job",
	 * which is somewhere between instant and one tick later.
	 *
	 * @note this value is allowed to be greater than
	 * @ref KBASE_CONFIG_ATTR_JS_RESET_TICKS_CL. This effectively
	 * disables soft-stop, and just uses hard-stop instead. In this case,
	 * this value should be much greater than any of the hard stop values
	 * (to avoid soft-stop-after-hard-stop)
	 *
	 * @see KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS
	 */
	KBASE_CONFIG_ATTR_JS_SOFT_STOP_TICKS_CL,

	/**
	 * Job Scheduler minimum number of scheduling ticks before non-CL jobs
	 * are hard-stopped.
	 *
	 * This defines the amount of time a job is allowed to spend on the GPU before it
	 * is killed. Such jobs won't be resumed if killed.
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::hard_stop_ticks_ss

	 * Default value: @ref DEFAULT_JS_HARD_STOP_TICKS_SS
	 *
	 * @note a value of zero means "the quickest time to hard-stop a job",
	 * which is somewhere between instant and one tick later.
	 *
	 * @see KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS
	 */
	KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_SS,

	/**
	 * Job Scheduler minimum number of scheduling ticks before CL jobs are hard-stopped.
	 *
	 * This defines the amount of time a job is allowed to spend on the GPU before it
	 * is killed. Such jobs won't be resumed if killed.
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::hard_stop_ticks_cl

	 * Default value: @ref DEFAULT_JS_HARD_STOP_TICKS_CL
	 *
	 * @note a value of zero means "the quickest time to hard-stop a job",
	 * which is somewhere between instant and one tick later.
	 *
	 * @see KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS
	 */
	KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_CL,

	/**
	 * Job Scheduler minimum number of scheduling ticks before jobs are hard-stopped
	 * when dumping.
	 *
	 * This defines the amount of time a job is allowed to spend on the GPU before it
	 * is killed. Such jobs won't be resumed if killed.
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::hard_stop_ticks_nss

	 * Default value: @ref DEFAULT_JS_HARD_STOP_TICKS_NSS
	 *
	 * @note a value of zero means "the quickest time to hard-stop a job",
	 * which is somewhere between instant and one tick later.
	 *
	 * @see KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS
	 */
	KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_NSS,

	/**
	 * Job Scheduler timeslice that a context is scheduled in for, in nanoseconds.
	 *
	 * When a context has used up this amount of time across its jobs, it is
	 * scheduled out to let another run.
	 *
	 * @note the resolution is nanoseconds (ns) here, because that's the format
	 * often used by the OS.
	 *
	 * This value controls affects the actual time defined by the following
	 * config values:
	 * - @ref KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_INIT_SLICES
	 * - @ref KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_MIN_SLICES
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::ctx_timeslice_ns.
	 * The value might be rounded down to lower precision.

	 * Default value: @ref DEFAULT_JS_CTX_TIMESLICE_NS
	 *
	 * @note a value of zero models a "Round Robin" scheduling policy, and
	 * disables @ref KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_INIT_SLICES
	 * (initially causing LIFO scheduling) and
	 * @ref KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_MIN_SLICES (allowing
	 * not-run-often contexts to get scheduled in quickly, but to only use
	 * a single timeslice when they get scheduled in).
	 */
	KBASE_CONFIG_ATTR_JS_CTX_TIMESLICE_NS,

	/**
	 * Job Scheduler initial runtime of a context for the CFS Policy, in time-slices.
	 *
	 * This value is relative to that of the least-run context, and defines
	 * where in the CFS queue a new context is added. A value of 1 means 'after
	 * the least-run context has used its timeslice'. Therefore, when all
	 * contexts consistently use the same amount of time, a value of 1 models a
	 * FIFO. A value of 0 would model a LIFO.
	 *
	 * The value is represented in "numbers of time slices". Multiply this
	 * value by that defined in @ref KBASE_CONFIG_ATTR_JS_CTX_TIMESLICE_NS to get
	 * the time value for this in nanoseconds.
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::cfs_ctx_runtime_init_slices

	 * Default value: @ref DEFAULT_JS_CFS_CTX_RUNTIME_INIT_SLICES
	 */
	KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_INIT_SLICES,

	/**
	 * Job Scheduler minimum runtime value of a context for CFS, in time_slices
	 * relative to that of the least-run context.
	 *
	 * This is a measure of how much preferrential treatment is given to a
	 * context that is not run very often.
	 *
	 * Specficially, this value defines how many timeslices such a context is
	 * (initially) allowed to use at once. Such contexts (e.g. 'interactive'
	 * processes) will appear near the front of the CFS queue, and can initially
	 * use more time than contexts that run continuously (e.g. 'batch'
	 * processes).
	 *
	 * This limit \b prevents a "stored-up timeslices" DoS attack, where a ctx
	 * not run for a long time attacks the system by using a very large initial
	 * number of timeslices when it finally does run.
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::cfs_ctx_runtime_min_slices

	 * Default value: @ref DEFAULT_JS_CFS_CTX_RUNTIME_MIN_SLICES
	 *
	 * @note A value of zero allows not-run-often contexts to get scheduled in
	 * quickly, but to only use a single timeslice when they get scheduled in.
	 */
	KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_MIN_SLICES,

	/**
	 * Job Scheduler minimum number of scheduling ticks before non-CL jobs
	 * cause the GPU to be reset.
	 *
	 * This defines the amount of time a job is allowed to spend on the GPU before it
	 * is assumed that the GPU has hung and needs to be reset. The assumes that the job
	 * has been hard-stopped already and so the presence of a job that has remained on
	 * the GPU for so long indicates that the GPU has in some way hung.
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::gpu_reset_ticks_nss

	 * Default value: @ref DEFAULT_JS_RESET_TICKS_SS
	 *
	 * @see KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS
	 */
	KBASE_CONFIG_ATTR_JS_RESET_TICKS_SS,

	/**
	 * Job Scheduler minimum number of scheduling ticks before CL jobs
	 * cause the GPU to be reset.
	 *
	 * This defines the amount of time a job is allowed to spend on the GPU before it
	 * is assumed that the GPU has hung and needs to be reset. The assumes that the job
	 * has been hard-stopped already and so the presence of a job that has remained on
	 * the GPU for so long indicates that the GPU has in some way hung.
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::gpu_reset_ticks_cl

	 * Default value: @ref DEFAULT_JS_RESET_TICKS_CL
	 *
	 * @see KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS
	 */
	KBASE_CONFIG_ATTR_JS_RESET_TICKS_CL,

	/**
	 * Job Scheduler minimum number of scheduling ticks before jobs cause the GPU to be
	 * reset when dumping.
	 *
	 * This defines the amount of time a job is allowed to spend on the GPU before it
	 * is assumed that the GPU has hung and needs to be reset. The assumes that the job
	 * has been hard-stopped already and so the presence of a job that has remained on
	 * the GPU for so long indicates that the GPU has in some way hung.
	 *
	 * This value is supported by the following scheduling policies:
	 * - The Completely Fair Share (CFS) policy
	 *
	 * Attached value: unsigned 32-bit kbasep_js_device_data::gpu_reset_ticks_nss

	 * Default value: @ref DEFAULT_JS_RESET_TICKS_NSS
	 *
	 * @see KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS
	 */
	KBASE_CONFIG_ATTR_JS_RESET_TICKS_NSS,

	/**
	 * Number of milliseconds given for other jobs on the GPU to be
	 * soft-stopped when the GPU needs to be reset.
	 *
	 * Attached value: number in milliseconds
	 * Default value: @ref DEFAULT_JS_RESET_TIMEOUT_MS
	 */
	KBASE_CONFIG_ATTR_JS_RESET_TIMEOUT_MS,
	/*** End Job Scheduling Configs ***/

	/** Power management configuration
	 *
	 * Attached value: pointer to @ref kbase_pm_callback_conf
	 * Default value: See @ref kbase_pm_callback_conf
	 */
	KBASE_CONFIG_ATTR_POWER_MANAGEMENT_CALLBACKS,

	/**
	 * Boolean indicating whether the driver is configured to be secure at
	 * a potential loss of performance.
	 *
	 * This currently affects only r0p0-15dev0 HW and earlier.
	 *
	 * On r0p0-15dev0 HW and earlier, there are tradeoffs between security and
	 * performance:
	 *
	 * - When this is set to MALI_TRUE, the driver remains fully secure,
	 * but potentially loses performance compared with setting this to
	 * MALI_FALSE.
	 * - When set to MALI_FALSE, the driver is open to certain security
	 * attacks.
	 *
	 * From r0p0-00rel0 and onwards, there is no security loss by setting
	 * this to MALI_FALSE, and no performance loss by setting it to
	 * MALI_TRUE.
	 *
	 * Attached value: mali_bool value
	 * Default value: @ref DEFAULT_SECURE_BUT_LOSS_OF_PERFORMANCE
	 */
	KBASE_CONFIG_ATTR_SECURE_BUT_LOSS_OF_PERFORMANCE,

	/**
	 * A pointer to a function that calculates the CPU clock
	 * speed of the platform in MHz - see
	 * @ref kbase_cpuprops_clock_speed_function for the function
	 * prototype.
	 *
	 * Attached value: A @ref kbase_cpuprops_clock_speed_function.
	 * Default Value:  Pointer to @ref DEFAULT_CPU_SPEED_FUNC -
	 *                 returns a clock speed of 100 MHz.
	 */
	KBASE_CONFIG_ATTR_CPU_SPEED_FUNC,

	/**
	 * A pointer to a function that calculates the GPU clock
	 * speed of the platform in MHz - see
	 * @ref kbase_gpuprops_clock_speed_function for the function
	 * prototype.
	 *
	 * Attached value: A @ref kbase_gpuprops_clock_speed_function.
	 * Default Value:  NULL (in which case the driver assumes a current
	 *                 GPU frequency specified by KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MAX)
	 */
	KBASE_CONFIG_ATTR_GPU_SPEED_FUNC,

	/**
	 * Platform specific configuration functions
	 *
	 * Attached value: pointer to @ref kbase_platform_funcs_conf
	 * Default value: See @ref kbase_platform_funcs_conf
	 */
	KBASE_CONFIG_ATTR_PLATFORM_FUNCS,

	/**
	 * Limit ARID width on the AXI bus.
	 *
	 * Attached value: u32 register value
	 *    KBASE_AID_32 - use the full 32 IDs (5 ID bits)
	 *    KBASE_AID_16 - use 16 IDs (4 ID bits)
	 *    KBASE_AID_8  - use 8 IDs (3 ID bits)
	 *    KBASE_AID_4  - use 4 IDs (2 ID bits)
	 * Default value: KBASE_AID_32 (no limit). Note hardware implementation
	 * may limit to a lower value.
	 */
	KBASE_CONFIG_ATTR_ARID_LIMIT,

	/**
	 * Limit AWID width on the AXI bus.
	 *
	 * Attached value: u32 register value
	 *    KBASE_AID_32 - use the full 32 IDs (5 ID bits)
	 *    KBASE_AID_16 - use 16 IDs (4 ID bits)
	 *    KBASE_AID_8  - use 8 IDs (3 ID bits)
	 *    KBASE_AID_4  - use 4 IDs (2 ID bits)
	 * Default value: KBASE_AID_32 (no limit). Note hardware implementation
	 * may limit to a lower value.
	 */
	KBASE_CONFIG_ATTR_AWID_LIMIT,

	/**
	 * Enable alternative hardware counter capture for the Mali shader cores.
	 *
	 * Attached value: mali_bool value
	 * Default value: @ref MALI_FALSE
	 */
	KBASE_CONFIG_ATTR_ALTERNATIVE_HWC,

	/**
	 * Rate at which dvfs data should be collected.
	 *
	 * Attached value: u32 value
	 * Default value: 500 Milliseconds
	 */

	KBASE_CONFIG_ATTR_POWER_MANAGEMENT_DVFS_FREQ,

	/**
	 * Number of microseconds between the PM core requesting that a shader
	 * is powered off, and the shader actually being powered off.
	 *
	 * If a shader poweroff is scheduled to occur and at some time prior to
	 * the poweroff the GPU goes idle, then the shader poweroff is cancelled.
	 * This usually lengthens the shader poweroff delay to that of the gpu
	 * poweroff delay when the GPU goes idle.

	 * Attached value: number in microseconds
	 * Default value: @ref DEFAULT_PM_SHADER_POWEROFF_TIME
	 */
	KBASE_CONFIG_ATTR_PM_SHADER_POWEROFF_TIME,

	/**
	 * Number of microseconds between the PM core requesting that the GPU
	 * is powered off, and the GPU actually being powered off.
	 *
	 * Attached value: number in microseconds
	 * Default value: @ref DEFAULT_PM_GPU_POWEROFF_TIME
	 */
	KBASE_CONFIG_ATTR_PM_GPU_POWEROFF_TIME,

	/**
	 * End of attribute list indicator.
	 * The configuration loader will stop processing any more elements
	 * when it encounters this attribute.
	 *
	 * Default value: NA
	 */
	KBASE_CONFIG_ATTR_END = 0x1FFFUL
};

enum {
	/**
	 * Use unrestricted Address ID width on the AXI bus.
	 */
	KBASE_AID_32 = 0x0,

	/**
	 * Restrict GPU to a half of maximum Address ID count.
	 * This will reduce performance, but reduce bus load due to GPU.
	 */
	KBASE_AID_16 = 0x3,

	/**
	 * Restrict GPU to a quarter of maximum Address ID count.
	 * This will reduce performance, but reduce bus load due to GPU.
	 */
	KBASE_AID_8  = 0x2,

	/**
	 * Restrict GPU to an eighth of maximum Address ID count.
	 * This will reduce performance, but reduce bus load due to GPU.
	 */
	KBASE_AID_4  = 0x1
};

/*
 * @brief specifies a single attribute
 *
 * Attribute is identified by attr field. Data is either integer or a pointer to attribute-specific structure.
 */
typedef struct kbase_attribute {
	int id;
	uintptr_t data;
} kbase_attribute;

/* Forward declaration of kbase_device */
struct kbase_device;

/*
 * @brief Specifies the functions for platform specific initialization and termination
 *
 * By default no functions are required. No additional platform specific control is necessary.
 */
typedef struct kbase_platform_funcs_conf {
	/**
	 * Function pointer for platform specific initialization or NULL if no initialization function is required.
	 * This function will be called \em before any other callbacks listed in the kbase_attribute struct (such as
	 * Power Management callbacks).
	 * The platform specific private pointer kbase_device::platform_context can be accessed (and possibly initialized) in here.
	 */
	mali_bool(*platform_init_func) (struct kbase_device *kbdev);
	/**
	 * Function pointer for platform specific termination or NULL if no termination function is required.
	 * This function will be called \em after any other callbacks listed in the kbase_attribute struct (such as
	 * Power Management callbacks).
	 * The platform specific private pointer kbase_device::platform_context can be accessed (and possibly terminated) in here.
	 */
	void (*platform_term_func) (struct kbase_device *kbdev);

} kbase_platform_funcs_conf;

/*
 * @brief Specifies the callbacks for power management
 *
 * By default no callbacks will be made and the GPU must not be powered off.
 */
typedef struct kbase_pm_callback_conf {
	/** Callback for when the GPU is idle and the power to it can be switched off.
	 *
	 * The system integrator can decide whether to either do nothing, just switch off
	 * the clocks to the GPU, or to completely power down the GPU.
	 * The platform specific private pointer kbase_device::platform_context can be accessed and modified in here. It is the
	 * platform \em callbacks responsiblity to initialize and terminate this pointer if used (see @ref kbase_platform_funcs_conf).
	 */
	void (*power_off_callback) (struct kbase_device *kbdev);

	/** Callback for when the GPU is about to become active and power must be supplied.
	 *
	 * This function must not return until the GPU is powered and clocked sufficiently for register access to
	 * succeed.  The return value specifies whether the GPU was powered down since the call to power_off_callback.
	 * If the GPU state has been lost then this function must return 1, otherwise it should return 0.
	 * The platform specific private pointer kbase_device::platform_context can be accessed and modified in here. It is the
	 * platform \em callbacks responsiblity to initialize and terminate this pointer if used (see @ref kbase_platform_funcs_conf).
	 *
	 * The return value of the first call to this function is ignored.
	 *
	 * @return 1 if the GPU state may have been lost, 0 otherwise.
	 */
	int (*power_on_callback) (struct kbase_device *kbdev);

	/** Callback for when the system is requesting a suspend and GPU power
	 * must be switched off.
	 *
	 * Note that if this callback is present, then this may be called
	 * without a preceding call to power_off_callback. Therefore this
	 * callback must be able to take any action that might otherwise happen
	 * in power_off_callback.
	 *
	 * The platform specific private pointer kbase_device::platform_context
	 * can be accessed and modified in here. It is the platform \em
	 * callbacks responsibility to initialize and terminate this pointer if
	 * used (see @ref kbase_platform_funcs_conf).
	 */
	void (*power_suspend_callback) (struct kbase_device *kbdev);

	/** Callback for when the system is resuming from a suspend and GPU
	 * power must be switched on.
	 *
	 * Note that if this callback is present, then this may be called
	 * without a following call to power_on_callback. Therefore this
	 * callback must be able to take any action that might otherwise happen
	 * in power_on_callback.
	 *
	 * The platform specific private pointer kbase_device::platform_context
	 * can be accessed and modified in here. It is the platform \em
	 * callbacks responsibility to initialize and terminate this pointer if
	 * used (see @ref kbase_platform_funcs_conf).
	 */
	void (*power_resume_callback) (struct kbase_device *kbdev);

	/** Callback for handling runtime power management initialization.
	 *
	 * The runtime power management callbacks @ref power_runtime_off_callback and @ref power_runtime_on_callback
	 * will become active from calls made to the OS from within this function.
	 * The runtime calls can be triggered by calls from @ref power_off_callback and @ref power_on_callback.
	 * Note: for linux the kernel must have CONFIG_PM_RUNTIME enabled to use this feature.
	 *
	 * @return MALI_ERROR_NONE on success, else mali_error erro code.
	 */
	 mali_error(*power_runtime_init_callback) (struct kbase_device *kbdev);

	/** Callback for handling runtime power management termination.
	 *
	 * The runtime power management callbacks @ref power_runtime_off_callback and @ref power_runtime_on_callback
	 * should no longer be called by the OS on completion of this function.
	 * Note: for linux the kernel must have CONFIG_PM_RUNTIME enabled to use this feature.
	 */
	void (*power_runtime_term_callback) (struct kbase_device *kbdev);

	/** Callback for runtime power-off power management callback
	 *
	 * For linux this callback will be called by the kernel runtime_suspend callback.
	 * Note: for linux the kernel must have CONFIG_PM_RUNTIME enabled to use this feature.
	 *
	 * @return 0 on success, else OS error code.
	 */
	void (*power_runtime_off_callback) (struct kbase_device *kbdev);

	/** Callback for runtime power-on power management callback
	 *
	 * For linux this callback will be called by the kernel runtime_resume callback.
	 * Note: for linux the kernel must have CONFIG_PM_RUNTIME enabled to use this feature.
	 */
	int (*power_runtime_on_callback) (struct kbase_device *kbdev);

	/** Callback for when the GPU is about to become active and power must be supplied.
	 *
	 * This function must not return until the GPU is powered and clocked sufficiently for register access to
	 * succeed.  The return value specifies whether the GPU was powered down since the call to power_off_callback.
	 * If the GPU state has been lost then this function must return 1, otherwise it should return 0.
	 * The platform specific private pointer kbase_device::platform_context can be accessed and modified in here. It is the
	 * platform \em callbacks responsiblity to initialize and terminate this pointer if used (see @ref kbase_platform_funcs_conf).
	 *
	 * The return value of the first call to this function is ignored.
	 *
	 * @return 1 if the GPU state may have been lost, 0 otherwise.
	 */
	int (*power_on_post_callback) (struct kbase_device *kbdev);
} kbase_pm_callback_conf;

/**
 * Type of the function pointer for KBASE_CONFIG_ATTR_CPU_SPEED_FUNC.
 *
 * @param clock_speed [out] Once called this will contain the current CPU clock speed in MHz.
 *                          This is mainly used to implement OpenCL's clGetDeviceInfo().
 *
 * @return 0 on success, 1 on error.
 */
typedef int (*kbase_cpuprops_clock_speed_function) (u32 *clock_speed);

/**
 * Type of the function pointer for KBASE_CONFIG_ATTR_GPU_SPEED_FUNC.
 *
 * @param clock_speed [out] Once called this will contain the current GPU clock speed in MHz.
 *                          If the system timer is not available then this function is required
 *                          for the OpenCL queue profiling to return correct timing information.
 *
 * @return 0 on success, 1 on error. When an error is returned the caller assumes a current
 * GPU speed as specified by KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MAX.
 */
typedef int (*kbase_gpuprops_clock_speed_function) (u32 *clock_speed);

#ifdef CONFIG_OF
typedef struct kbase_platform_config {
	const kbase_attribute *attributes;
	u32 midgard_type;
} kbase_platform_config;
#else

/*
 * @brief Specifies start and end of I/O memory region.
 */
typedef struct kbase_io_memory_region {
	u64 start;
	u64 end;
} kbase_io_memory_region;

/*
 * @brief Specifies I/O related resources like IRQs and memory region for I/O operations.
 */
typedef struct kbase_io_resources {
	u32 job_irq_number;
	u32 mmu_irq_number;
	u32 gpu_irq_number;
	kbase_io_memory_region io_memory_region;
} kbase_io_resources;

typedef struct kbase_platform_config {
	const kbase_attribute *attributes;
	const kbase_io_resources *io_resources;
	u32 midgard_type;
} kbase_platform_config;

#endif /* CONFIG_OF */

/**
 * @brief Return character string associated with the given midgard type.
 *
 * @param[in]  midgard_type - ID of midgard type
  *
 * @return  Pointer to NULL-terminated character array associated with the given midgard type
 */
const char *kbasep_midgard_type_to_string(u32 midgard_type);

/**
 * @brief Gets the next config attribute with the specified ID from the array of attributes.
 *
 * Function gets the next attribute with specified attribute id within specified array. If no such attribute is found,
 * NULL is returned.
 *
 * @param[in]  attributes     Array of attributes in which lookup is performed
 * @param[in]  attribute_id   ID of attribute
 *
 * @return  Pointer to the first attribute matching id or NULL if none is found.
 */
const kbase_attribute *kbasep_get_next_attribute(const kbase_attribute *attributes, int attribute_id);

/**
 * @brief Gets the value of a single config attribute.
 *
 * Function gets the value of attribute specified as parameter. If no such attribute is found in the array of
 * attributes, default value is used.
 *
 * @param[in]  kbdev          Kbase device pointer
 * @param[in]  attributes     Array of attributes in which lookup is performed
 * @param[in]  attribute_id   ID of attribute
 *
 * @return Value of attribute with the given id
 */
uintptr_t kbasep_get_config_value(struct kbase_device *kbdev, const kbase_attribute *attributes, int attribute_id);

/**
 * @brief Validates configuration attributes
 *
 * Function checks validity of given configuration attributes. It will fail on any attribute with unknown id, attribute
 * with invalid value or attribute list that is not correctly terminated. It will also fail if
 * KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MIN or KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MAX are not specified.
 *
 * @param[in]  kbdev       Kbase device pointer
 * @param[in]  attributes  Array of attributes to validate
 *
 * @return   MALI_TRUE if no errors have been found in the config. MALI_FALSE otherwise.
 */
mali_bool kbasep_validate_configuration_attributes(struct kbase_device *kbdev, const kbase_attribute *attributes);

/**
 * @brief Gets the pointer to platform config.
 *
 * @return Pointer to the platform config
 */
kbase_platform_config *kbase_get_platform_config(void);

/**
 * @brief Gets the count of attributes in array
 *
 * Function gets the count of attributes in array. Note that end of list indicator is also included.
 *
 * @param[in]  attributes     Array of attributes
 *
 * @return  Number of attributes in the array including end of list indicator.
 */
int kbasep_get_config_attribute_count(const kbase_attribute *attributes);

/**
 * @brief Platform specific call to initialize hardware
 *
 * Function calls a platform defined routine if specified in the configuration attributes.
 * The routine can initialize any hardware and context state that is required for the GPU block to function.
 *
 * @param[in]  kbdev       Kbase device pointer
 *
 * @return   MALI_TRUE if no errors have been found in the config. MALI_FALSE otherwise.
 */
mali_bool kbasep_platform_device_init(struct kbase_device *kbdev);

/**
 * @brief Platform specific call to terminate hardware
 *
 * Function calls a platform defined routine if specified in the configuration attributes.
 * The routine can destroy any platform specific context state and shut down any hardware functionality that are
 * outside of the Power Management callbacks.
 *
 * @param[in]  kbdev       Kbase device pointer
 *
 */
void kbasep_platform_device_term(struct kbase_device *kbdev);

	  /** @} *//* end group kbase_config */
	  /** @} *//* end group base_kbase_api */
	  /** @} *//* end group base_api */

#endif				/* _KBASE_CONFIG_H_ */


text:
package com.saoyor.serializable;

import java.io.Serializable;

public class UserVo implements Serializable {
}

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.cagrid</groupId>
		<artifactId>cagrid-mms</artifactId>
		<version>2.1.0-SNAPSHOT</version>
	</parent>
	<artifactId>cagrid-mms-soap-client</artifactId>
	<packaging>bundle</packaging>
	<name>caGrid MMS Soap Client</name>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
						<Export-Package>
							org.cagrid.mms.soapclient
						</Export-Package>
                        <Private-Package>
                        </Private-Package>
						<Import-Package>
                            *
						</Import-Package>
					</instructions>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>cagrid-mms-api</artifactId>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>cagrid-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-frontend-jaxws</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http</artifactId>
		</dependency>
	</dependencies>
</project>


text:
<?php

/*
 *
 *  ____            _        _   __  __ _                  __  __ ____
 * |  _ \ ___   ___| | _____| |_|  \/  (_)_ __   ___      |  \/  |  _ \
 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
 * |  __/ (_) | (__|   <  __/ |_| |  | | | | | |  __/_____| |  | |  __/
 * |_|   \___/ \___|_|\_\___|\__|_|  |_|_|_| |_|\___|     |_|  |_|_|
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * @author PocketMine Team
 * @link http://www.pocketmine.net/
 *
 *
*/

namespace pocketmine\scheduler;

use pocketmine\event\Timings;
use pocketmine\Server;

class AsyncPool{

	/** @var Server */
	private $server;

	protected $size;

	/** @var AsyncTask[] */
	private $tasks = [];
	/** @var int[] */
	private $taskWorkers = [];

	/** @var AsyncWorker[] */
	private $workers = [];
	/** @var int[] */
	private $workerUsage = [];

	public function __construct(Server $server, $size){
		$this->server = $server;
		$this->size = (int) $size;

		for($i = 0; $i < $this->size; ++$i){
			$this->workerUsage[$i] = 0;
			$this->workers[$i] = new AsyncWorker($this->server->getLogger(), $i + 1);
			$this->workers[$i]->setClassLoader($this->server->getLoader());
			$this->workers[$i]->start();
		}
	}

	public function getSize(){
		return $this->size;
	}

	public function increaseSize($newSize){
		$newSize = (int) $newSize;
		if($newSize > $this->size){
			for($i = $this->size; $i < $newSize; ++$i){
				$this->workerUsage[$i] = 0;
				$this->workers[$i] = new AsyncWorker($this->server->getLogger(), $i + 1);
				$this->workers[$i]->setClassLoader($this->server->getLoader());
				$this->workers[$i]->start();
			}
			$this->size = $newSize;
		}
	}

	public function submitTaskToWorker(AsyncTask $task, $worker){
		if(isset($this->tasks[$task->getTaskId()]) or $task->isGarbage()){
			return;
		}

		$worker = (int) $worker;
		if($worker < 0 or $worker >= $this->size){
			throw new \InvalidArgumentException("Invalid worker $worker");
		}

		$this->tasks[$task->getTaskId()] = $task;

		$this->workers[$worker]->stack($task);
		$this->workerUsage[$worker]++;
		$this->taskWorkers[$task->getTaskId()] = $worker;
	}

	public function submitTask(AsyncTask $task){
		if(isset($this->tasks[$task->getTaskId()]) or $task->isGarbage()){
			return;
		}

		$selectedWorker = mt_rand(0, $this->size - 1);
		$selectedTasks = $this->workerUsage[$selectedWorker];
		for($i = 0; $i < $this->size; ++$i){
			if($this->workerUsage[$i] < $selectedTasks){
				$selectedWorker = $i;
				$selectedTasks = $this->workerUsage[$i];
			}
		}

		$this->submitTaskToWorker($task, $selectedWorker);
	}

	private function removeTask(AsyncTask $task, $force = false){
		if(isset($this->taskWorkers[$task->getTaskId()])){
			if(!$force and ($task->isRunning() or !$task->isGarbage())){
				return;
			}
			$this->workerUsage[$this->taskWorkers[$task->getTaskId()]]--;
		}

		unset($this->tasks[$task->getTaskId()]);
		unset($this->taskWorkers[$task->getTaskId()]);

		$task->cleanObject();
	}

	public function removeTasks(){
		do{
			foreach($this->tasks as $task){
				$task->cancelRun();
				$this->removeTask($task);
			}

			if(count($this->tasks) > 0){
				Server::microSleep(25000);
			}
		}while(count($this->tasks) > 0);

		for($i = 0; $i < $this->size; ++$i){
			$this->workerUsage[$i] = 0;
		}

		$this->taskWorkers = [];
		$this->tasks = [];

		$this->collectWorkers();
	}

	private function collectWorkers(){
		foreach($this->workers as $worker){
			$worker->collect();
		}
	}

	public function collectTasks(){
		Timings::$schedulerAsyncTimer->startTiming();

		foreach($this->tasks as $task){
			if(!$task->isGarbage()){
				$task->checkProgressUpdates($this->server);
			}
			if($task->isGarbage() and !$task->isRunning() and !$task->isCrashed()){
				if(!$task->hasCancelledRun()){
					$task->onCompletion($this->server);
					$this->server->getScheduler()->removeLocalComplex($task);
				}

				$this->removeTask($task);
			}elseif($task->isTerminated() or $task->isCrashed()){
				$this->server->getLogger()->critical("Could not execute asynchronous task " . (new \ReflectionClass($task))->getShortName() . ": Task crashed");
				$this->removeTask($task, true);
			}
		}

		$this->collectWorkers();

		Timings::$schedulerAsyncTimer->stopTiming();
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Conduit.Tests
{
    [TestClass]
    public abstract class SpecificationContext
    {
        [TestInitialize]
        public void Init()
        {
            this.Given();
            this.When();
        }

        public virtual void Given() { }
        public virtual void When() { }
        public virtual void Cleanup() { }
    }
}


text:
:- use_package(assertions).
:- comment(nodoc,assertions).

:- comment(title,"Definite clause grammars").

:- comment(author, "The CLIP Group").

%% see @cite{Les Grammaires de Metamorphos} by A.Colmerauer,
%% Technical Report, Groupe d'Intelligence Artificielle,
%% Marseille-Luminy, November, 1975, and @cite{Definite clause grammars for
%% language analysis---a survey of the formalism and a comparison with
%% augmented transition networks} by F.C.N. Pereira and D.H.D. Warren, in
%% @cite{Artificial Intelligence} 13:231-278, 1980.

:- comment(module,"This library package allows the use of DCGs
   (Definite Clause Grammars) @cite{Colmerauer78,PereiraWarren80}
   in a Ciao module/program.

Definite clause grammars are an extension of the well-known context-free
grammars. Prolog's grammar rules provide a convenient notation for expressing
definite clause grammars. A DCG rule in Prolog takes the general form

@begin{verbatim}
@var{head} --> @var{body}.
@end{verbatim}

@noindent
meaning ``a possible form for @var{head} is @var{body}''.  Both
@var{body} and @var{head} are sequences of one or more items linked by the
standard Prolog conjunction operator ""@tt{,}"".

Definite clause grammars extend context-free grammars in the following ways:

@begin{enumerate}

@item
A non-terminal symbol may be any Prolog term (other than a variable or
number).

@item
A terminal symbol may be any Prolog term.  To distinguish terminals from
non-terminals, a sequence of one or more terminal symbols is written within
a grammar rule as a Prolog list.  An empty sequence is written as the empty
list @tt{[]}.  If the terminal symbols are ASCII character codes, such
lists can be written (as elsewhere) as strings.  An empty sequence is
written as the empty list, @tt{[]} or @tt{""""}.

@item
Extra conditions, in the form of Prolog procedure calls, may be included in
the right-hand side of a grammar rule.  Such procedure calls are written
enclosed in @tt{@{@}} brackets.

@item
The left-hand side of a grammar rule consists of a non-terminal, optionally
followed by a sequence of terminals (again written as a Prolog list).

@item
Alternatives may be stated explicitly in the right-hand side of a
grammar rule, using the disjunction operator @tt{;}, or, also, as
traditionally in Prolog, using @tt{|} (which is treated specially when this
package is loaded).

@item
The cut symbol may be included in the right-hand side of a grammar rule, as
in a Prolog clause.  The cut symbol does not need to be enclosed in
@tt{@{@}} brackets.
@end{enumerate}

As an example, here is a simple grammar which parses an arithmetic
expression (made up of digits and operators) and computes its value.

@begin{verbatim}
expr(Z) --> term(X), ""+"", expr(Y), @{Z is X + Y@}.
expr(Z) --> term(X), ""-"", expr(Y), @{Z is X - Y@}.
expr(X) --> term(X).

term(Z) --> number(X), ""*"", term(Y), @{Z is X * Y@}.
term(Z) --> number(X), ""/"", term(Y), @{Z is X / Y@}.
term(Z) --> number(Z).

number(C) --> ""+"", number(C).
number(C) --> ""-"", number(X), @{C is -X@}.
number(X) --> [C], @{0'0=<C, C=<0'9, X is C - 0'0@}.
@end{verbatim}

In the last rule, @var{C} is the ASCII code of some digit.

The query

@begin{verbatim}
?- expr(Z, ""-2+3*5+1"", []).
@end{verbatim}

@noindent
will compute @var{Z}=14.  The two extra arguments are explained below.

Now, in fact, grammar rules are merely a convenient ``syntactic sugar'' for
ordinary Prolog clauses.  Each grammar rule takes an input string, analyses
some initial portion, and produces the remaining portion (possibly
enlarged) as output for further analysis.  The arguments required for the
input and output strings are not written explicitly in a grammar rule, but
the syntax implicitly defines them.  We now show how to translate grammar
rules into ordinary clauses by making explicit the extra arguments.

A rule such as

@begin{verbatim}
p(X) --> q(X).
@end{verbatim}

@noindent
translates into

@begin{verbatim}
p(X, S0, S) :- q(X, S0, S).
@end{verbatim}

If there is more than one non-terminal on the right-hand side, as in

@begin{verbatim}
p(X, Y) -->
        q(X),
        r(X, Y),
        s(Y).
@end{verbatim}

@noindent
then corresponding input and output arguments are identified, as in

@begin{verbatim}
p(X, Y, S0, S) :-
        q(X, S0, S1),
        r(X, Y, S1, S2),
        r(Y, S2, S).
@end{verbatim}

Terminals are translated using the built-in predicate
@tt{'C'/3} (this predicate is not normally useful in itself;
it has been given the name @tt{'C'} simply to avoid using up a more
useful name).
Then, for instance

@begin{verbatim}
p(X) --> [go,to], q(X), [stop].
@end{verbatim}

@noindent
is translated by

@begin{verbatim}
p(X, S0, S) :-
        'C'(S0, go, S1),
        'C'(S1, to, S2),
        q(X, S2, S3),
        'C'(S3, stop, S).
@end{verbatim}

Extra conditions expressed as explicit procedure calls naturally translate
as themselves, e.g.

@begin{verbatim}
p(X) --> [X], @{integer(X), X>0@}, q(X).
@end{verbatim}

@noindent
translates to

@begin{verbatim}
p(X, S0, S) :-
        'C'(S0, X, S1),
        integer(X),
        X>0,
        q(X, S1, S).
@end{verbatim}

Similarly, a cut is translated literally.

Terminals on the left-hand side of a rule translate into an explicit list
in the output argument of the main non-terminal, e.g.

@begin{verbatim}
is(N), [not] --> [aint].
@end{verbatim}

@noindent
becomes

@begin{verbatim}
is(N, S0, [not|S]) :- 'C'(S0, aint, S).
@end{verbatim}

Disjunction has a fairly obvious translation, e.g.

@begin{verbatim}
args(X, Y) -->
        (   dir(X), [to], indir(Y)
        ;   indir(Y), dir(X)
        ).
@end{verbatim}

@noindent
translates to

@begin{verbatim}
args(X, Y, S0, S) :-
        (   dir(X, S0, S1),
            'C'(S1, to, S2),
            indir(Y, S2, S)
        ;   indir(Y, S0, S1),
            dir(X, S1, S)
        ).
@end{verbatim}

").


text:
/*global Officials, Backbone*/

Officials.Collections = Officials.Collections || {}

Officials.Collections.Province = Backbone.Collection.extend({
  url: '/api/province',
  model: Officials.Models.Province

})


text:
namespace MakerJs.models {

    /**
     * @private
     */
    var hasLib = false;

    /**
     * @private
     */
    function ensureBezierLib() {

        if (hasLib) return;

        try {
            var lib = Bezier.prototype;
            hasLib = true;
        }
        catch (e) {
            throw "Bezier library not found. If you are using Node, try running 'npm install' or if you are in the browser, download http://pomax.github.io/bezierjs/bezier.js to your website and add a script tag.";
        }
    }

    /**
     * @private
     */
    var scratch: BezierJs.Bezier;

    /**
     * @private
     */
    function getScratch(seed: IPathBezierSeed) {

        var points: IPoint[] = [seed.origin];
        points.push.apply(points, seed.controls);
        points.push(seed.end);

        var bezierJsPoints = points.map(function (p: IPoint) {
            var bp: BezierJs.Point = {
                x: p[0], y: p[1]
            };
            return bp;
        });

        if (!scratch) {

            ensureBezierLib();
            scratch = new Bezier(bezierJsPoints);
        } else {
            //invoke the constructor on the same object
            Bezier.apply(scratch, bezierJsPoints);
        }

        return scratch;
    }

    /**
     * @private
     */
    function BezierToSeed(b: BezierJs.Bezier, range?: IBezierRange): IPathBezierSeed {
        var points = b.points.map(getIPoint);
        var seed = new BezierSeed(points) as IPathBezierSeed;
        if (range) {
            seed.parentRange = range;
        }
        return seed;
    }

    /**
     * @private
     */
    function seedToBezier(seed: IPathBezierSeed): BezierJs.Bezier {
        var coords: number[] = [];

        coords.push.apply(coords, seed.origin);
        coords.push.apply(coords, seed.controls[0]);
        if (seed.controls.length > 1) {
            coords.push.apply(coords, seed.controls[1]);
        }
        coords.push.apply(coords, seed.end);

        ensureBezierLib();
        return new Bezier(coords);
    }

    /**
     * @private
     */
    function getExtrema(b: BezierJs.Bezier) {

        var extrema = b.extrema().values

            //round the numbers so we can compare them to each other
            .map(m => round(m))

            //remove duplicates
            .filter((value, index, self) => self.indexOf(value) === index)

            //and put them in order
            .sort();

        if (extrema.length === 0) return [0, 1];

        //ensure leading zero
        if (extrema[0] !== 0) {
            extrema.unshift(0);
        }

        //ensure ending 1
        if (extrema[extrema.length - 1] !== 1) {
            extrema.push(1);
        }

        return extrema;
    }

    /**
     * @private
     */
    function getIPoint(p: BezierJs.Point): IPoint {
        return [p.x, p.y];
    }

    /**
     * @private
     */
    class TPoint {
        public point: IPoint;

        constructor(b: BezierJs.Bezier, public t: number, offset?: IPoint) {
            this.point = point.add(getIPoint(b.get(t)), offset);
        }
    }

    /**
     * @private
     */
    function getError(b: BezierJs.Bezier, startT: number, endT: number, arc: IPathArc, arcReversed: boolean): number {
        var tSpan = endT - startT;

        function m(ratio: number) {
            var t = startT + tSpan * ratio;
            var bp = getIPoint(b.get(t));
            var ap = point.middle(arc, arcReversed ? 1 - ratio : ratio);
            return measure.pointDistance(ap, bp);
        }

        return m(0.25) + m(0.75);
    }

    /**
     * @private
     */
    function getLargestArc(b: BezierJs.Bezier, startT: number, endT: number, accuracy: number): IPathArcInBezierCurve {

        var arc: IPathArc, lastGoodArc: IPathArc;
        var start = new TPoint(b, startT);
        var end = new TPoint(b, endT);
        var upper = end;
        var lower = start;
        var count = 0;
        var test = upper;
        var reversed: boolean;

        while (count < 100) {
            const middle = getIPoint(b.get((start.t + test.t) / 2));

            //if the 3 points are linear, this may throw
            try {
                arc = new paths.Arc(start.point, middle, test.point);
            }
            catch (e) {
                if (lastGoodArc) {
                    return lastGoodArc as IPath as IPathArcInBezierCurve;
                } else {
                    break;
                }
            }

            //only need to test once to see if this arc is polar / clockwise
            if (reversed === undefined) {
                reversed = measure.isPointEqual(start.point, point.fromAngleOnCircle(arc.endAngle, arc));
            }

            //now we have a valid arc, measure the error.
            var error = getError(b, startT, test.t, arc, reversed);

            //if error is within accuracy, this becomes the lower
            if (error <= accuracy) {
                (arc as IPath as IPathArcInBezierCurve).bezierData = {
                    startT: startT,
                    endT: test.t
                };
                lower = test;
                lastGoodArc = arc;
            } else {
                upper = test;
            }

            //exit if lower is the end
            if (lower.t === upper.t || (lastGoodArc && (lastGoodArc !== arc) && (angle.ofArcSpan(arc) - angle.ofArcSpan(lastGoodArc)) < .5)) {
                return lastGoodArc as IPath as IPathArcInBezierCurve;
            }

            count++;
            test = new TPoint(b, (lower.t + upper.t) / 2);
        }

        //arc failed, so return a line
        var line = new paths.Line(start.point, test.point) as IPath as IPathArcInBezierCurve;
        line.bezierData = {
            startT: startT,
            endT: test.t
        };
        return line;
    }

    /**
     * @private
     */
    function getArcs(bc: BezierCurve, b: BezierJs.Bezier, accuracy: number, startT: number, endT: number, base: number): number {
        var added = 0;
        var arc: IPathArcInBezierCurve;

        while (startT < endT) {

            arc = getLargestArc(b, startT, endT, accuracy);
            //add an arc

            startT = arc.bezierData.endT

            var len = measure.pathLength(arc);
            if (len < .0001) {
                continue;
            }

            bc.paths[arc.type + '_' + (base + added)] = arc;

            added++;
        }

        return added;
    }

    /**
     * @private
     */
    function getActualBezierRange(curve: BezierCurve, arc: IPathArcInBezierCurve, endpoints: IPoint[], offset: IPoint): IBezierRange {
        var b = getScratch(curve.seed);
        var tPoints = [arc.bezierData.startT, arc.bezierData.endT].map(t => new TPoint(b, t, offset));
        var ends = endpoints.slice();

        //clipped arcs will still have endpoints closer to the original endpoints
        var endpointDistancetoStart = ends.map(e => measure.pointDistance(e, tPoints[0].point));
        if (endpointDistancetoStart[0] > endpointDistancetoStart[1]) ends.reverse();

        for (var i = 2; i--;) {
            if (!measure.isPointEqual(ends[i], tPoints[i].point)) {
                return null;
            }
        }

        return arc.bezierData;
    }

    /**
     * @private
     */
    interface IAddToLayer {
        (pathToAdd: IPath, layer: string, clone?: boolean): void;
    }

    /**
     * @private
     */
    function getChainBezierRange(curve: BezierCurve, c: IChain, layer: string, addToLayer: IAddToLayer): IBezierRange {

        var endLinks = [c.links[0], c.links[c.links.length - 1]];
        if ((endLinks[0].walkedPath.pathContext as IPathArcInBezierCurve).bezierData.startT > (endLinks[1].walkedPath.pathContext as IPathArcInBezierCurve).bezierData.startT) {
            chain.reverse(c);
            endLinks.reverse();
        }

        var actualBezierRanges = endLinks.map(endLink => getActualBezierRange(curve, endLink.walkedPath.pathContext as IPathArcInBezierCurve, endLink.endPoints, endLink.walkedPath.offset));

        var result: IBezierRange = {
            startT: actualBezierRanges[0] ? actualBezierRanges[0].startT : null,
            endT: actualBezierRanges[1] ? actualBezierRanges[1].endT : null
        };

        if (result.startT !== null && result.endT !== null) {
            return result;

        } else if (c.links.length > 2) {

            if (result.startT === null) {
                //exclude the first from the chain
                addToLayer(c.links[0].walkedPath.pathContext, layer, true);
                result.startT = (c.links[1].walkedPath.pathContext as IPathArcInBezierCurve).bezierData.startT;
            }

            if (result.endT === null) {
                //exclude the last from the chain
                addToLayer(c.links[c.links.length - 1].walkedPath.pathContext, layer, true);
                result.endT = (c.links[c.links.length - 2].walkedPath.pathContext as IPathArcInBezierCurve).bezierData.endT;
            }

            return result;
        }
        return null;
    }

    /**
     * @private
     * Class for bezier seed.
     */
    class BezierSeed implements IPathBezierSeed {
        public type: string;
        public origin: IPoint;
        public end: IPoint
        public controls: IPoint[];

        /**
         * Class for bezier seed, created from point array.
         *
         * @param points Array of points, with the first being the origin, and the last being the end, and points between used as control points.
         */
        constructor(points: IPoint[]);

        /**
         * Class for quadratic bezier seed.
         *
         * @param origin The origin point of the curve.
         * @param control The control point of the curve.
         * @param end The end point of the curve.
         */
        constructor(origin: IPoint, control: IPoint, end: IPoint);

        /**
         * Class for cubic bezier seed.
         *
         * @param origin The origin point of the curve.
         * @param controls The control points of the curve.
         * @param end The end point of the curve.
         */
        constructor(origin: IPoint, controls: IPoint[], end: IPoint);

        /**
         * Class for cubic bezier seed.
         *
         * @param origin The origin point of the curve.
         * @param control1 The control point of the curve origin.
         * @param control1 The control point of the curve end.
         * @param end The end point of the curve.
         */
        constructor(origin: IPoint, control1: IPoint, control2: IPoint, end: IPoint);

        constructor(...args: any[]) {
            this.type = pathType.BezierSeed;

            switch (args.length) {

                case 1: //point array
                    var points = args[0] as IPoint[];

                    this.origin = points[0];

                    if (points.length === 3) {
                        this.controls = [points[1]];
                        this.end = points[2];

                    } else if (points.length === 4) {
                        this.controls = [points[1], points[2]];
                        this.end = points[3];

                    } else {
                        this.end = points[1];
                    }

                    break;

                case 3: //quadratic or cubic
                    if (Array.isArray(args[1])) {
                        this.controls = args[1] as IPoint[];
                    } else {
                        this.controls = [args[1] as IPoint];
                    }

                    this.end = args[2] as IPoint;
                    break;

                case 4: //cubic params
                    this.controls = [args[1] as IPoint, args[2] as IPoint];
                    this.end = args[3] as IPoint;
                    break;
            }

        }
    }

    export class BezierCurve implements IModel {

        public models: IModelMap;
        public paths: IPathMap;
        public origin: IPoint;
        public type = BezierCurve.typeName;
        public seed: IPathBezierSeed;
        public accuracy: number;

        constructor(points: IPoint[], accuracy?: number);
        constructor(seed: IPathBezierSeed, accuracy?: number);
        constructor(origin: IPoint, control: IPoint, end: IPoint, accuracy?: number);
        constructor(origin: IPoint, controls: IPoint[], end: IPoint, accuracy?: number);
        constructor(origin: IPoint, control1: IPoint, control2: IPoint, end: IPoint, accuracy?: number);

        constructor(...args: any[]) {

            var isArrayArg0 = Array.isArray(args[0]);

            switch (args.length) {

                case 2:
                    if (isArrayArg0) {
                        this.accuracy = args[1] as number;
                    } else {
                        //seed
                        this.seed = args[0] as IPathBezierSeed;
                        this.accuracy = args[1] as number;
                        break;
                    }
                //fall through to point array

                case 1: //point array or seed
                    if (isArrayArg0) {

                        var points = args[0] as IPoint[];

                        this.seed = new BezierSeed(points);
                    } else {
                        this.seed = args[0] as IPathBezierSeed;
                    }
                    break;

                default:
                    switch (args.length) {
                        case 4:
                            if (isPoint(args[3])) {
                                this.seed = new BezierSeed(args as IPoint[]);
                                break;
                            } else {
                                this.accuracy = args[3] as number;
                                //fall through
                            }
                        case 3:
                            if (isArrayArg0) {
                                this.seed = new BezierSeed(args.slice(0, 3) as IPoint[]);
                            }
                            break;

                        case 5:
                            this.accuracy = args[4] as number;
                            this.seed = new BezierSeed(args.slice(0, 4) as IPoint[]);
                            break;
                    }
                    break;
            }

            this.paths = {};

            if (measure.isBezierSeedLinear(this.seed)) {
                //use a line and exit

                var line = new paths.Line(point.clone(this.seed.origin), point.clone(this.seed.end));
                (line as IPath as IPathArcInBezierCurve).bezierData = {
                    startT: 0,
                    endT: 1
                };

                this.paths = {
                    "0": line
                };
                return;
            }

            var b = seedToBezier(this.seed);
            var extrema = getExtrema(b);

            this.paths = {};

            //use arcs

            if (!this.accuracy) {
                //get a default accuracy relative to the size of the bezier
                var len = b.length();

                //set the default to be a combination of fast rendering and good smoothing.
                this.accuracy = len / 100;
            }

            var count = 0;
            for (var i = 1; i < extrema.length; i++) {
                var extremaSpan = extrema[i] - extrema[i - 1];
                count += getArcs(this, b, this.accuracy * extremaSpan, extrema[i - 1], extrema[i], count);
            }
        }

        public static typeName = 'BezierCurve';

        public static getBezierSeeds(curve: BezierCurve, options: IFindChainsOptions = {}): IPath[] | { [layer: string]: IPath[] } {

            options.shallow = true;
            options.unifyBeziers = false;

            const seedsByLayer: { [layer: string]: IPath[] } = {};

            const addToLayer: IAddToLayer = (pathToAdd: IPath, layer: string, clone = false) => {
                if (!seedsByLayer[layer]) {
                    seedsByLayer[layer] = [];
                }
                seedsByLayer[layer].push(clone ? path.clone(pathToAdd) : pathToAdd);
            }

            model.findChains(curve, function (chains: IChain[], loose: IWalkPath[], layer: string) {

                chains.forEach(c => {
                    var range = getChainBezierRange(curve, c, layer, addToLayer);
                    if (range) {
                        var b = getScratch(curve.seed);
                        var piece = b.split(range.startT, range.endT);
                        addToLayer(BezierToSeed(piece), layer);
                    } else {
                        c.links.forEach(link => addToLayer(link.walkedPath.pathContext, layer, true));
                    }
                });

                loose.forEach(wp => {
                    if (wp.pathContext.type === pathType.Line) {
                        //bezier is linear
                        return addToLayer(wp.pathContext, layer, true);
                    }
                    var range = getActualBezierRange(curve, wp.pathContext as IPathArcInBezierCurve, point.fromPathEnds(wp.pathContext), wp.offset);
                    if (range) {
                        var b = getScratch(curve.seed);
                        var piece = b.split(range.startT, range.endT);
                        addToLayer(BezierToSeed(piece), layer);
                    } else {
                        addToLayer(wp.pathContext, layer, true);
                    }
                });

            }, options);

            if (options.byLayers) {
                return seedsByLayer;
            } else {
                return seedsByLayer[''];
            }
        }

        public static computeLength(seed: IPathBezierSeed): number {
            var b = seedToBezier(seed);
            return b.length();
        }

        public static computePoint(seed: IPathBezierSeed, t: number): IPoint {
            var s = getScratch(seed);

            var computedPoint = s.compute(t);

            return getIPoint(computedPoint);
        }

    }

    (<IKit>BezierCurve).metaParameters = [
        {
            title: "points", type: "select", value: [
                [[100, 0], [-80, -60], [100, 220], [100, 60]],
                [[0, 0], [100, 0], [100, 100]],
                [[0, 0], [20, 0], [80, 100], [100, 100]]
            ]
        }
    ];
}

declare var Bezier: typeof BezierJs.Bezier;


text:
var fs = require('fs');
var cofs = require('co-fs');
var path = require('path');
var parse = require('co-busboy');
var Router = require('koa-router');
var Router = require('koa-router');
var Award = require('../../libs/award');

var router = module.exports = new Router();

router.get('/awards', function *() {

	var page = parseInt(this.request.query.page) || 1;
	var perPage = parseInt(this.request.query.perpage) || 100;

	var data = yield Award.list({
		skip: (page - 1) * perPage,
		limit: perPage
	});

	this.body = {
		page: page,
		perPage: perPage,
		pageCount: Math.ceil(data.count / perPage),
		awards: data.awards
	}
});

router.post('/awards', function *() {

	var name = this.request.body.name;
	var desc = this.request.body.desc;
	var points = this.request.body.points;
	var icon = this.request.body.icon;

	var awardData = {
		name: name,
		desc: desc,
		points: points,
		icon: icon
	};

	this.body = yield Award.create(awardData);
});

router.put('/award/:id', function *() {

	var awardId = this.params.id;

	var name = this.request.body.name;
	var desc = this.request.body.desc;
	var points = this.request.body.points;

	var awardData = {
		name: name,
		desc: desc,
		points: points
	};

	this.body = yield Award.save(awardId, awardData);
});

router.post('/uploads/award', function *() {

	if (!this.request.is('multipart/*'))
		return yield next;

	var parts = parse(this);
	var part;

	// Getting target path to put icons
	var awardIconsDir = Award.getIconsDir();
	var Id = Award.getAvailableId();

	// Save one file only
	var part = yield parts;
	var filename = path.join(awardIconsDir, Id + path.extname(part.filename));
	var stream = fs.createWriteStream(filename);
	part.pipe(stream);
	console.log('uploading %s -> %s', part.filename, stream.path);

	this.body = {
		id: Id
	};
});

router.get('/award/:id/icon', function *() {

	// Getting target path to put icons
	var awardIconsDir = Award.getIconsDir();
	var awardId = this.params.id;
	var filename = path.join(awardIconsDir, awardId);

	if (!awardId)
		return;
	console.log(filename);

	if (yield cofs.exists(filename + '.jpg')) {
		this.type = '.jpg';
		this.body = fs.createReadStream(filename + '.jpg');
	} else if (yield cofs.exists(filename + '.png')) {
		this.type = '.png';
		this.body = fs.createReadStream(filename + '.png');
	} else if (yield cofs.exists(filename + '.gif')) {
		this.type = '.gif';
		this.body = fs.createReadStream(filename + '.gif');
	} else {
		this.status = 404;
		this.body = 'Not Found';
	}
});


text:
package models;

public class LineageEdgeLite {

    public int id;
    public int source;
    public int target;
    public String label;
    public String chain;
    public String type;
    public String color;
    public String style;
}


text:
<?php

class form
{
	private static $enctype = 'application/x-www-form-urlencoded';
	private $elements;

	function __construct()
	{
	}

	static function text($settings = array())
	{
        $settings['type'] = 'text';
        return self::_input($settings);
	}

	static function password($settings = array())
	{
        $settings['type'] = 'password';
        return self::_input($settings);
	}

	static function hidden($settings = array())
	{
        $settings['type'] = 'hidden';
        return self::_input($settings);
	}

	static function textarea($settings = array())
	{
		if(!is_array($settings) || !isset($settings['name'])) return FALSE;
		extract($settings);
		$html  = "<textarea name=\"$name\" id=\"$id\" ";
		if(isset($rows)) $html .= " rows=\"$rows\" ";
		if(isset($cols)) $html .= " cols=\"$cols\" ";
		if(isset($wrap)) $html .= " wrap=\"$wrap\" ";
        $html .= self::_attribute($settings);
		$html .= " >";
		if(isset($value)) $html .= htmlspecialchars($value);
		$html .= "</textarea>";
        return $html;
	}

	static function select($settings = array())
	{
		if(!is_array($settings) || !isset($settings['name'])) return FALSE;
		extract($settings);
		if (!isset($id)) $id = $name;
		$html  = "<select name=\"$name\" id=\"$id\" ";
		if(isset($size)) $html .= " size=\"$size\" ";
		if(isset($multiple)) $html .= " multiple=\"multiple\" ";
        $html .= self::_attribute($settings);
		$html .= " >\n";
		foreach ($options as $k=>$v)
		{
			$selected = $k == $value ? 'selected="selected"' : '';
			$html .= "<option $selected value=\"$k\">$v</option>\n";
		}
		$html .= "</select>";
        return $html;
	}

	static function radio($settings = array())
	{
        $settings['type'] = 'radio';
        return self::_check($settings);
	}

	static function checkbox($settings = array())
	{
        $settings['type'] = 'checkbox';
        return self::_check($settings);
	}

	static function file($settings = array())
	{
		if(!is_array($settings) || !isset($settings['name'])) return FALSE;
		extract($settings);
		if (!isset($id)) $id = $name;
		$html = '';
		if(isset($max_file_size)) $html .= "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$max_file_size\" />";
		$attr = self::_attribute($settings);
		$size = isset($size) ? " size=\"$size\" " : '';
		$html .= "<input type=\"file\" name=\"$name\" id=\"$id\" $size $attr />";
		self::$enctype = 'multipart/form-data';
		return $html;
	}

	static function button($settings = array())
	{
        $settings['type'] = 'button';
        return self::_button($settings);
	}

	static function submit($settings = array())
	{
        $settings['type'] = 'submit';
        return self::_button($settings);
	}

	static function reset($settings = array())
	{
        $settings['type'] = 'reset';
        return self::_button($settings);
	}

	static function image($settings = array())
	{
		if(!is_array($settings) || !isset($settings['name']) || !isset($settings['src'])) return FALSE;
		extract($settings);
		if (!isset($id)) $id = $name;
		$attr = self::_attribute($settings);
		$html = "<input type=\"image\" name=\"$name\" id=\"$id\" src=\"$src\"";
		if(isset($align)) $html .= " align=\"$align\" ";
		if(isset($attr)) $html .= $attr;
		$html .= '/>';
		return $html;
	}

	private static function _input($settings = array())
	{
		if(!is_array($settings) || !isset($settings['name']) || !isset($settings['type'])) return FALSE;
		extract($settings);
		if (!isset($id)) $id = $name;
		$html  = "<input type=\"$type\" name=\"$name\" id=\"$id\"  style=\"$style\" ";
		if(isset($value)) $html .= " value=\"".htmlspecialchars($value)."\" ";
		if(isset($size)) $html .= " size=\"$size\" ";
		if(isset($maxlength)) $html .= " maxlength=\"$maxlength\" ";
        $html .= self::_attribute($settings);
		$html .= ' />';
		return $html;
	}

	private static function _check($settings = array())
	{
		if(!is_array($settings) || !isset($settings['name']) || !isset($settings['type'])) return FALSE;
		extract($settings);
		$attr = self::_attribute($settings);
		$html = '';
		$i = 1;
		foreach ($options as $v=>$label)
		{
			$checked = $v == $value ? ' checked="checked"' : '';
			$checked = $defaultchecked ? ' checked="checked"' : '';
		    $html .= "<label><input type=\"$type\" name=\"$name\" id=\"{$name}_{$i}\" value=\"$v\" $checked $attr /> $label </label>\n";
		    if (isset($br)) $html .= '<br />';
		    $i++;
		}
        return $html;
	}

	private static function _button($settings = array())
	{
		if(!is_array($settings) || !isset($settings['name']) || !isset($settings['value'])) return FALSE;
		extract($settings);
		if (!isset($id)) $id = $name;
		$attr = self::_attribute($settings);
		$html = "<input type=\"$type\" name=\"$name\" id=\"$id\" value=\"$value\" $attr />";
		return $html;
	}

	private static function _attribute($settings = array())
	{
		extract($settings);
		$html = '';
		if(isset($readonly)) $html .= " readonly";
		if(isset($disabled)) $html .= " disabled";
		if(isset($alt)) $html .= " alt=\"$alt\" ";
		if(isset($tabindex)) $html .= " tabindex=\"$tabindex\" ";
		if(isset($accesskey)) $html .= " accesskey=\"$accesskey\" ";
		if(isset($class)) $html .= " class=\"$class\" ";
		if(isset($attribute)) $html .= " $attribute ";
		return $html;
	}
}


text:
package com.amazonaws.services.cloudformation.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.cloudformation.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * CreateStackRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateStackRequestMarshaller implements Marshaller<Request<CreateStackRequest>, CreateStackRequest> {

    public Request<CreateStackRequest> marshall(CreateStackRequest createStackRequest) {

        if (createStackRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<CreateStackRequest> request = new DefaultRequest<CreateStackRequest>(createStackRequest, "AmazonCloudFormation");
        request.addParameter("Action", "CreateStack");
        request.addParameter("Version", "2010-05-15");
        request.setHttpMethod(HttpMethodName.POST);

        if (createStackRequest.getStackName() != null) {
            request.addParameter("StackName", StringUtils.fromString(createStackRequest.getStackName()));
        }

        if (createStackRequest.getTemplateBody() != null) {
            request.addParameter("TemplateBody", StringUtils.fromString(createStackRequest.getTemplateBody()));
        }

        if (createStackRequest.getTemplateURL() != null) {
            request.addParameter("TemplateURL", StringUtils.fromString(createStackRequest.getTemplateURL()));
        }

        com.amazonaws.internal.SdkInternalList<Parameter> parametersList = (com.amazonaws.internal.SdkInternalList<Parameter>) createStackRequest
                .getParameters();
        if (parametersList.isEmpty() && !parametersList.isAutoConstruct()) {
            request.addParameter("Parameters", "");
        }
        if (!parametersList.isEmpty() || !parametersList.isAutoConstruct()) {
            int parametersListIndex = 1;

            for (Parameter parametersListValue : parametersList) {

                if (parametersListValue.getParameterKey() != null) {
                    request.addParameter("Parameters.member." + parametersListIndex + ".ParameterKey",
                            StringUtils.fromString(parametersListValue.getParameterKey()));
                }

                if (parametersListValue.getParameterValue() != null) {
                    request.addParameter("Parameters.member." + parametersListIndex + ".ParameterValue",
                            StringUtils.fromString(parametersListValue.getParameterValue()));
                }

                if (parametersListValue.getUsePreviousValue() != null) {
                    request.addParameter("Parameters.member." + parametersListIndex + ".UsePreviousValue",
                            StringUtils.fromBoolean(parametersListValue.getUsePreviousValue()));
                }
                parametersListIndex++;
            }
        }

        if (createStackRequest.getDisableRollback() != null) {
            request.addParameter("DisableRollback", StringUtils.fromBoolean(createStackRequest.getDisableRollback()));
        }

        if (createStackRequest.getTimeoutInMinutes() != null) {
            request.addParameter("TimeoutInMinutes", StringUtils.fromInteger(createStackRequest.getTimeoutInMinutes()));
        }

        com.amazonaws.internal.SdkInternalList<String> notificationARNsList = (com.amazonaws.internal.SdkInternalList<String>) createStackRequest
                .getNotificationARNs();
        if (notificationARNsList.isEmpty() && !notificationARNsList.isAutoConstruct()) {
            request.addParameter("NotificationARNs", "");
        }
        if (!notificationARNsList.isEmpty() || !notificationARNsList.isAutoConstruct()) {
            int notificationARNsListIndex = 1;

            for (String notificationARNsListValue : notificationARNsList) {
                if (notificationARNsListValue != null) {
                    request.addParameter("NotificationARNs.member." + notificationARNsListIndex, StringUtils.fromString(notificationARNsListValue));
                }
                notificationARNsListIndex++;
            }
        }

        com.amazonaws.internal.SdkInternalList<String> capabilitiesList = (com.amazonaws.internal.SdkInternalList<String>) createStackRequest.getCapabilities();
        if (capabilitiesList.isEmpty() && !capabilitiesList.isAutoConstruct()) {
            request.addParameter("Capabilities", "");
        }
        if (!capabilitiesList.isEmpty() || !capabilitiesList.isAutoConstruct()) {
            int capabilitiesListIndex = 1;

            for (String capabilitiesListValue : capabilitiesList) {
                if (capabilitiesListValue != null) {
                    request.addParameter("Capabilities.member." + capabilitiesListIndex, StringUtils.fromString(capabilitiesListValue));
                }
                capabilitiesListIndex++;
            }
        }

        com.amazonaws.internal.SdkInternalList<String> resourceTypesList = (com.amazonaws.internal.SdkInternalList<String>) createStackRequest
                .getResourceTypes();
        if (resourceTypesList.isEmpty() && !resourceTypesList.isAutoConstruct()) {
            request.addParameter("ResourceTypes", "");
        }
        if (!resourceTypesList.isEmpty() || !resourceTypesList.isAutoConstruct()) {
            int resourceTypesListIndex = 1;

            for (String resourceTypesListValue : resourceTypesList) {
                if (resourceTypesListValue != null) {
                    request.addParameter("ResourceTypes.member." + resourceTypesListIndex, StringUtils.fromString(resourceTypesListValue));
                }
                resourceTypesListIndex++;
            }
        }

        if (createStackRequest.getRoleARN() != null) {
            request.addParameter("RoleARN", StringUtils.fromString(createStackRequest.getRoleARN()));
        }

        if (createStackRequest.getOnFailure() != null) {
            request.addParameter("OnFailure", StringUtils.fromString(createStackRequest.getOnFailure()));
        }

        if (createStackRequest.getStackPolicyBody() != null) {
            request.addParameter("StackPolicyBody", StringUtils.fromString(createStackRequest.getStackPolicyBody()));
        }

        if (createStackRequest.getStackPolicyURL() != null) {
            request.addParameter("StackPolicyURL", StringUtils.fromString(createStackRequest.getStackPolicyURL()));
        }

        com.amazonaws.internal.SdkInternalList<Tag> tagsList = (com.amazonaws.internal.SdkInternalList<Tag>) createStackRequest.getTags();
        if (tagsList.isEmpty() && !tagsList.isAutoConstruct()) {
            request.addParameter("Tags", "");
        }
        if (!tagsList.isEmpty() || !tagsList.isAutoConstruct()) {
            int tagsListIndex = 1;

            for (Tag tagsListValue : tagsList) {

                if (tagsListValue.getKey() != null) {
                    request.addParameter("Tags.member." + tagsListIndex + ".Key", StringUtils.fromString(tagsListValue.getKey()));
                }

                if (tagsListValue.getValue() != null) {
                    request.addParameter("Tags.member." + tagsListIndex + ".Value", StringUtils.fromString(tagsListValue.getValue()));
                }
                tagsListIndex++;
            }
        }

        if (createStackRequest.getClientRequestToken() != null) {
            request.addParameter("ClientRequestToken", StringUtils.fromString(createStackRequest.getClientRequestToken()));
        }

        return request;
    }

}


text:
jsftp
=====

jsftp is a client FTP library for NodeJS that focuses on correctness, clarity
and conciseness. It doesn't get in the way and plays nice with streaming APIs.

**BIG Warning: The latest version (1.0.0) of jsftp breaks API compatibility with previous
versions, it is NOT a drop-in replacement. Please be careful when upgrading. The
API changes are not drastic at all and it is all documented below. If you do not
want to upgrade yet you should stay with version 0.6.0, the last one before the
upgrade. The API docs below are updated for 1.0.**

Starting it up
--------------

```javascript
var Ftp = require("jsftp");

// The constructor accepts the parameters `host`, `port`, `user` and `pass`.
// `port` defaults to `21`.
var myFtp = new Ftp({
  host: "myserver.com",
  user: "user", // defaults to "anonymous"
  pass: "1234" // defaults to "@anonymous"
};
```

jsftp gives you access to all the raw commands of the FTP protocol in form of
methods in the `Ftp` object. It also provides several convenience methods for
actions that require complex chains of commands (e.g. uploading and retrieving
files, passive operations).

When raw commands succeed they always pass the response of the server to the
callback, in the form of an object that contains two properties: `code`, which
is the response code of the FTP operation, and `text`, which is the complete
text of the response.

Raw (or native) commands are accessible in the form `Ftp.raw["desired_command"](params, callback)`

Thus, a command like `QUIT` will be called like this:

```javascript
Ftp.raw.quit(function(err, data) {
    if (err) return console.error(err);

    console.log("Bye!");
});
```

and a command like `MKD` (make directory), which accepts parameters, looks like this:

```javascript
Ftp.raw.mkd("/new_dir", function(err, data) {
    if (err) return console.error(err);

    console.log(data.text); // Presenting the FTP response text to the user
    console.log(data.code); // Presenting the FTP response code to the user
});
```

API and examples
----------------

### Properties

#### Ftp.host

Host name for the current FTP server.

#### Ftp.port

Port number for the current FTP server (defaults to 21).

#### Ftp.socket

NodeJS socket for the current FTP server.

#### Ftp.features

Array of feature names for the current FTP server. It is
generated when the user authenticates with the `auth` method.

#### Ftp.system

Contains the system identification string for the remote FTP server.

### Methods

#### Ftp.raw.FTP_COMMAND([params], callback)
All the standard FTP commands are available under the `raw` namespace. These
commands might accept parameters or not, but they always accept a callback
with the signature `err, data`, in which `err` is the error response coming
from the server (usually a 4xx or 5xx error code) and the data is an object
that contains two properties: `code` and `text`. `code` is an integer indicating
the response code of the response and `text` is the response string itself.

#### Ftp.auth(username, password, callback)
Authenticates the user with the given username and password. If null or empty
values are passed for those, `auth` will use anonymous credentials. `callback`
will be called with the response text in case of successful login or with an
error as a first parameter, in normal Node fashion.

#### Ftp.ls(filePath, callback)
Lists information about files or directories and yields an array of file objects
with parsed file properties to the `callback`. You should use this function
instead of `stat` or `list` in case you need to do something with the individual
file properties.

```javascript
ftp.ls(".", function(err, res) {
  res.forEach(function(file) {
    console.log(file.name);
  });
});
```

#### Ftp.list(filePath, callback)
Lists `filePath` contents using a passive connection. Calls callback with an
array of strings with complete file information.

```javascript
ftp.list(remoteCWD, function(err, res) {
  res.forEach(function(file) {
    console.log(file.name);
  });
  // Prints something like
  // -rw-r--r--   1 sergi    staff           4 Jun 03 09:32 testfile1.txt
  // -rw-r--r--   1 sergi    staff           4 Jun 03 09:31 testfile2.txt
  // -rw-r--r--   1 sergi    staff           0 May 29 13:05 testfile3.txt
  // ...
});
```

#### Ftp.get(remotePath, callback)
Gives back a paused socket with the file contents ready to be streamed,
or calls the callback with an error if not successful.

```javascript
  var str = ""; // We will store the contents of the file in this string
  ftp.get('remote/path/file.txt', function(err, socket) {
    if (err) return;

    socket.on("data", function(d) { str += d.toString(); })
    socket.on("close", function(hadErr) {
      if (hadErr)
        console.error('There was an error retrieving the file.');
    });
    socket.resume();
  });
```

#### Ftp.get(remotePath, localPath, callback)
Stores the remote file directly in the given local path.

```javascript
  ftp.get('remote/file.txt, 'local/file.txt, function(hadErr) {
    if (hadErr)
      console.error('There was an error retrieving the file.');
    else
      console.log('File copied successfully!');
  });
```

#### Ftp.put(source, remotePath, callback)
Uploads a file to `filePath`. It accepts a string with the local path for the
file or a `Buffer` as a `source` parameter.

```javascript
ftp.put(buffer, 'path/to/remote/file.txt', function(hadError) {
  if (!hadError)
    console.log("File transferred successfully!");
});
```

#### Ftp.rename(from, to, callback)
Renames a file in the server. `from` and `to` are both filepaths.

```javascript
ftp.rename(from, to, function(err, res) {
  if (!err)
    console.log("Renaming successful!");
});
```

#### Ftp.keepAlive()
Refreshes the interval thats keep the server connection active.

You can find more usage examples in the [unit tests](https://github.com/sergi/jsftp/blob/master/test/jsftp_test.js). This documentation
will grow as jsftp evolves.

Installation
------------

    npm install jsftp

Test coverage
-------------

In order to run coverage reports:

    npm install --dev
    make coverage

Current overall coverage rate:
  lines......: 92.1% (316 of 343 lines)
  functions..: 91.0% (71 of 78 functions)

Tests
-----

To run the tests:

    npm install --dev
    make test

License
-------

See LICENSE.


text:
@interface PopularTopicsViewController ()
@property (nonatomic, retain) UIActivityIndicatorView *indicator;
@end

@implementation PopularTopicsViewController {
    int numLimit;
}

@synthesize popularTopics;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.title = @"当天最热";
        self.tabBarItem.image = [UIImage imageNamed:@"popular"];
        numLimit = 20;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (void) showMore
{
    if (numLimit < self.popularTopics.count) {
        numLimit += 20;
        [self.tableView reloadData];
    }
}

- (void)reload:(__unused id)sender {
    [BDWMPopularReader getPopularTopicsOfType:0 WithBlock:^(NSMutableArray *topics, NSError *error) {
        if (!error) {
            self.popularTopics = topics;
            if (self.popularTopics.count == 0) {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"未取到数据!可能是网络或其他原因导致。" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
            } else {
                [self.tableView reloadData];
            }
        } else {
            [BDWMAlertMessage alertAndAutoDismissMessage:[error localizedDescription]];
            [self.navigationController popViewControllerAnimated:YES];
        }
        [self.refreshControl endRefreshing];
    }];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(reload:) forControlEvents:UIControlEventValueChanged];

    [self.refreshControl layoutIfNeeded];
    [self.refreshControl beginRefreshing];
    [self reload:nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if ([BDWMUserModel getEnterAppAndAutoLogin] == YES && [BDWMUserModel isLogined] == NO && [BDWMUserModel getStoredUserInfo] != nil) {
        [BDWMUserModel autoLogin:^() {
        //    [BDWMAlertMessage alertMessage:@"登录成功!"];
        } WithFailurBlock:^(){
            [BDWMAlertMessage alertMessage:@"登录失败!"];
        }];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger num = MIN([popularTopics count], numLimit);
    return num;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"PopularCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    NSDictionary *topic = [popularTopics objectAtIndex:[indexPath row]];
    cell.textLabel.text = [topic valueForKey:@"title"];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:16];

    NSString *detail = [NSString stringWithFormat:@"%@  -  %@  -  %@",[topic valueForKey:@"date"], [topic valueForKey:@"author"], [topic valueForKey:@"boardDescription"]];
    cell.detailTextLabel.text = detail;
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *topic = [popularTopics objectAtIndex:[indexPath row]];
    TopicViewController *topicViewController = [[TopicViewController alloc] initWithStyle:UITableViewStylePlain];
    topicViewController.title = [topic valueForKey:@"title"];
    topicViewController.topicURI = [NSString stringWithFormat:@"%@/%@", [topic valueForKey:@"boardName"], [topic valueForKey:@"threadid"]];
    [self.navigationController pushViewController:topicViewController animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // check if indexPath.row is last row
    // Perform operation to load new Cell's.
    if (indexPath.row == numLimit - 1) {
        [self showMore];
    }
}

@end


text:
namespace ouzel
{
    namespace scene
    {
        SceneManager::SceneManager()
        {
        }

        SceneManager::~SceneManager()
        {
            for (Scene* scene : scenes)
            {
                if (scene->entered) scene->leave();
                scene->sceneManger = nullptr;
            }
        }

        void SceneManager::addChildScene(Scene* scene)
        {
            if (scene)
            {
                if (scene->sceneManger) scene->sceneManger->removeScene(scene);

                scene->sceneManger = this;

                scenes.push_back(scene);
            }
        }

        bool SceneManager::removeChildScene(Scene* scene)
        {
            bool result = false;

            std::vector<Scene*>::iterator sceneIterator = std::find(scenes.begin(), scenes.end(), scene);

            if (sceneIterator != scenes.end())
            {
                if (scene->entered) scene->leave();
                scene->sceneManger = nullptr;
                scenes.erase(sceneIterator);

                result = true;
            }

            std::vector<std::unique_ptr<Scene>>::iterator ownedIterator = std::find_if(ownedScenes.begin(), ownedScenes.end(), [scene](const std::unique_ptr<Scene>& other) {
                return other.get() == scene;
            });

            if (ownedIterator != ownedScenes.end())
            {
                ownedScenes.erase(ownedIterator);
            }

            return result;
        }

        void SceneManager::draw()
        {
            while (scenes.size() > 1)
            {
                removeScene(scenes.front());
            }

            if (!scenes.empty())
            {
                Scene* scene = scenes.back();
                if (!scene->entered) scene->enter();
                scene->draw();
            }
        }
    } // namespace scene
} // namespace ouzel