text:
#include "battery.h"
#include "battery_smart.h"
#include "chipset.h"
#include "common.h"
#include "ec_tasks.h"
#include "emul/emul_common_i2c.h"
#include "emul/emul_smart_battery.h"
#include "extpower.h"
#include "hooks.h"
#include "host_command.h"
#include "power.h"
#include "task.h"
#include "test/drivers/stubs.h"
#include "test/drivers/test_state.h"
#include "test/drivers/utils.h"

#include <string.h>

#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/gpio/gpio_emul.h>
#include <zephyr/shell/shell.h>
#include <zephyr/shell/shell_dummy.h>
#include <zephyr/shell/shell_uart.h>
#include <zephyr/ztest.h>

#define BATTERY_NODE DT_NODELABEL(battery)

/* Description of all power states with chipset state masks */
static struct {
	/* Power state */
	enum power_state p_state;
	/*
	 * CHIPSET_STATE_* to which this state transition (the same as
	 * transition_from for static states)
	 */
	int transition_to;
	/* CHIPSET_STATE_* from which this state transition */
	int transition_from;
} test_power_state_desc[] = {
	{
		.p_state = POWER_G3,
		.transition_to = CHIPSET_STATE_HARD_OFF,
		.transition_from = CHIPSET_STATE_HARD_OFF,
	},
	{
		.p_state = POWER_G3S5,
		.transition_to = CHIPSET_STATE_SOFT_OFF,
		.transition_from = CHIPSET_STATE_HARD_OFF,
	},
	{
		.p_state = POWER_S5G3,
		.transition_to = CHIPSET_STATE_HARD_OFF,
		.transition_from = CHIPSET_STATE_SOFT_OFF,
	},
	{
		.p_state = POWER_S5,
		.transition_to = CHIPSET_STATE_SOFT_OFF,
		.transition_from = CHIPSET_STATE_SOFT_OFF,
	},
	{
		.p_state = POWER_S5S3,
		.transition_to = CHIPSET_STATE_SUSPEND,
		.transition_from = CHIPSET_STATE_SOFT_OFF,
	},
	{
		.p_state = POWER_S3S5,
		.transition_to = CHIPSET_STATE_SOFT_OFF,
		.transition_from = CHIPSET_STATE_SUSPEND,
	},
	{
		.p_state = POWER_S3,
		.transition_to = CHIPSET_STATE_SUSPEND,
		.transition_from = CHIPSET_STATE_SUSPEND,
	},
	{
		.p_state = POWER_S3S0,
		.transition_to = CHIPSET_STATE_ON,
		.transition_from = CHIPSET_STATE_SUSPEND,
	},
	{
		.p_state = POWER_S0S3,
		.transition_to = CHIPSET_STATE_SUSPEND,
		.transition_from = CHIPSET_STATE_ON,
	},
	{
		.p_state = POWER_S0,
		.transition_to = CHIPSET_STATE_ON,
		.transition_from = CHIPSET_STATE_ON,
	},
};

/*
 * Chipset state masks used by chipset_in_state and
 * chipset_in_or_transitioning_to_state tests
 */
static int in_state_test_masks[] = {
	CHIPSET_STATE_HARD_OFF,
	CHIPSET_STATE_SOFT_OFF,
	CHIPSET_STATE_SUSPEND,
	CHIPSET_STATE_ON,
	CHIPSET_STATE_STANDBY,
	CHIPSET_STATE_ANY_OFF,
	CHIPSET_STATE_ANY_SUSPEND,
	CHIPSET_STATE_ANY_SUSPEND | CHIPSET_STATE_SOFT_OFF,
};

/** Test chipset_in_state() for each state */
ZTEST(power_common_no_tasks, test_power_chipset_in_state)
{
	bool expected_in_state;
	bool transition_from;
	bool transition_to;
	bool in_state;
	int mask;

	for (int i = 0; i < ARRAY_SIZE(test_power_state_desc); i++) {
		/* Set given power state */
		power_set_state(test_power_state_desc[i].p_state);
		/* Test with selected state masks */
		for (int j = 0; j < ARRAY_SIZE(in_state_test_masks); j++) {
			mask = in_state_test_masks[j];
			/*
			 * Currently tested mask match with state if it match
			 * with transition_to and from chipset states
			 */
			transition_to = mask &
					test_power_state_desc[i].transition_to;
			transition_from =
				mask & test_power_state_desc[i].transition_from;
			expected_in_state = transition_to && transition_from;
			in_state = chipset_in_state(mask);
			zassert_equal(expected_in_state, in_state,
				      "Wrong chipset_in_state() == %d, "
				      "should be %d; mask 0x%x; power state %d "
				      "in test case %d",
				      in_state, expected_in_state, mask,
				      test_power_state_desc[i].p_state, i);
		}
	}
}

/** Test chipset_in_or_transitioning_to_state() for each state */
ZTEST(power_common_no_tasks, test_power_chipset_in_or_transitioning_to_state)
{
	bool expected_in_state;
	bool in_state;
	int mask;

	for (int i = 0; i < ARRAY_SIZE(test_power_state_desc); i++) {
		/* Set given power state */
		power_set_state(test_power_state_desc[i].p_state);
		/* Test with selected state masks */
		for (int j = 0; j < ARRAY_SIZE(in_state_test_masks); j++) {
			mask = in_state_test_masks[j];
			/*
			 * Currently tested mask match with state if it match
			 * with transition_to chipset state
			 */
			expected_in_state =
				mask & test_power_state_desc[i].transition_to;
			in_state = chipset_in_or_transitioning_to_state(mask);
			zassert_equal(expected_in_state, in_state,
				      "Wrong "
				      "chipset_in_or_transitioning_to_state() "
				      "== %d, should be %d; mask 0x%x; "
				      "power state %d in test case %d",
				      in_state, expected_in_state, mask,
				      test_power_state_desc[i].p_state, i);
		}
	}
}

/* Test using chipset_exit_hard_off() in different power states. The only
 * way to test the value of want_g3_exit is to set the power state to G3
 * and then to see if test_power_common_state() transitions to G3S5 or not.
 */
ZTEST(power_common_no_tasks, test_power_exit_hard_off)
{
	/*
	 * Every test runs in a new thread, we need to add this thread to the
	 * dynamic shimmed tasks or this test will fail.
	 */
	set_test_runner_tid();

	/* Force initial state */
	power_set_state(POWER_G3);
	test_power_common_state();
	zassert_equal(POWER_G3, power_get_state());

	/* Test after exit hard off, we reach G3S5 */
	chipset_exit_hard_off();
	test_power_common_state();
	zassert_equal(POWER_G3S5, power_get_state());

	/* Go back to G3 and check we stay there */
	power_set_state(POWER_G3);
	test_power_common_state();
	zassert_equal(POWER_G3, power_get_state());

	/* Exit G3 again */
	chipset_exit_hard_off();
	test_power_common_state();
	zassert_equal(POWER_G3S5, power_get_state());

	/* Go to S5G3 */
	power_set_state(POWER_S5G3);
	test_power_common_state();
	zassert_equal(POWER_S5G3, power_get_state());

	/* Test exit hard off in S5G3 -- should set want_g3_exit */
	chipset_exit_hard_off();
	/* Go back to G3 and check we exit it to G3S5 */
	power_set_state(POWER_G3);
	test_power_common_state();
	zassert_equal(POWER_G3S5, power_get_state());

	/* Test exit hard off is cleared on entering S5 */
	chipset_exit_hard_off();
	power_set_state(POWER_S5);
	test_power_common_state();
	zassert_equal(POWER_S5, power_get_state());

	/* Go back to G3 and check we stay in G3 */
	power_set_state(POWER_G3);
	test_power_common_state();
	zassert_equal(POWER_G3, power_get_state());

	/* Test exit hard off doesn't work on other states */
	power_set_state(POWER_S5S3);
	test_power_common_state();
	zassert_equal(POWER_S5S3, power_get_state());
	chipset_exit_hard_off();
	test_power_common_state();

	/* Go back to G3 and check we stay in G3 */
	power_set_state(POWER_G3);
	test_power_common_state();
	zassert_equal(POWER_G3, power_get_state());
}

/* Test reboot ap on g3 host command is triggering reboot */
ZTEST(power_common_no_tasks, test_power_reboot_ap_at_g3)
{
	struct ec_params_reboot_ap_on_g3_v1 params;
	struct host_cmd_handler_args args = {
		.command = EC_CMD_REBOOT_AP_ON_G3,
		.version = 0,
		.send_response = stub_send_response_callback,
		.params = &params,
		.params_size = sizeof(params),
	};
	int delay_ms;
	int64_t before_time;

	/*
	 * Every test runs in a new thread, we need to add this thread to the
	 * dynamic shimmed tasks or this test will fail.
	 */
	set_test_runner_tid();

	/* Force initial state S0 */
	power_set_state(POWER_S0);
	test_power_common_state();
	zassert_equal(POWER_S0, power_get_state());

	/* Test version 0 (no delay argument) */
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	/* Go to G3 and check if reboot is triggered */
	power_set_state(POWER_G3);
	test_power_common_state();
	zassert_equal(POWER_G3S5, power_get_state());

	/* Test version 1 (with delay argument) */
	args.version = 1;
	delay_ms = 3000;
	params.reboot_ap_at_g3_delay = delay_ms / 1000; /* in seconds */
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	/* Go to G3 and check if reboot is triggered after delay */
	power_set_state(POWER_G3);
	before_time = k_uptime_get();
	test_power_common_state();
	zassert_true(k_uptime_delta(&before_time) >= 3000);
	zassert_equal(POWER_G3S5, power_get_state());
}

/** Test setting cutoff and stay-up battery levels through host command */
ZTEST(power_common, test_power_hc_smart_discharge)
{
	struct ec_response_smart_discharge response;
	struct ec_params_smart_discharge params;
	struct host_cmd_handler_args args =
		BUILD_HOST_COMMAND(EC_CMD_SMART_DISCHARGE, 0, response, params);
	const struct emul *emul = EMUL_DT_GET(BATTERY_NODE);
	struct i2c_common_emul_data *common_data =
		emul_smart_battery_get_i2c_common_data(emul);
	int hours_to_zero;
	int hibern_drate;
	int cutoff_drate;
	int stayup_cap;
	int cutoff_cap;

	/* Set up host command parameters */
	params.flags = EC_SMART_DISCHARGE_FLAGS_SET;

	/* Test fail when battery capacity is not available */
	i2c_common_emul_set_read_fail_reg(common_data, SB_FULL_CHARGE_CAPACITY);
	zassert_equal(EC_RES_UNAVAILABLE, host_command_process(&args));
	i2c_common_emul_set_read_fail_reg(common_data,
					  I2C_COMMON_EMUL_NO_FAIL_REG);

	/* Setup discharge rates */
	params.drate.hibern = 10;
	params.drate.cutoff = 100;
	/* Test fail on higher discahrge in hibernation than cutoff */
	zassert_equal(EC_RES_INVALID_PARAM, host_command_process(&args));

	/* Setup discharge rates */
	params.drate.hibern = 10;
	params.drate.cutoff = 0;
	/* Test fail on only one discharge rate set to 0 */
	zassert_equal(EC_RES_INVALID_PARAM, host_command_process(&args));

	/* Setup correct parameters */
	hours_to_zero = 1000;
	hibern_drate = 100; /* uA */
	cutoff_drate = 10; /* uA */
	/* Need at least 100 mA capacity to stay 1000h using 0.1mAh */
	stayup_cap = hibern_drate * hours_to_zero / 1000;
	/* Need at least 10 mA capacity to stay 1000h using 0.01mAh */
	cutoff_cap = cutoff_drate * hours_to_zero / 1000;

	params.drate.hibern = hibern_drate;
	params.drate.cutoff = cutoff_drate;
	params.hours_to_zero = hours_to_zero;

	/* Test if correct values are set */
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));
	zassert_equal(hibern_drate, response.drate.hibern);
	zassert_equal(cutoff_drate, response.drate.cutoff);
	zassert_equal(hours_to_zero, response.hours_to_zero);
	zassert_equal(stayup_cap, response.dzone.stayup);
	zassert_equal(cutoff_cap, response.dzone.cutoff);

	/* Setup discharge rate to 0 */
	params.drate.hibern = 0;
	params.drate.cutoff = 0;
	/* Update hours to zero */
	hours_to_zero = 2000;
	params.hours_to_zero = hours_to_zero;
	/* Need at least 200 mA capacity to stay 2000h using 0.1mAh */
	stayup_cap = hibern_drate * hours_to_zero / 1000;
	/* Need at least 20 mA capacity to stay 2000h using 0.01mAh */
	cutoff_cap = cutoff_drate * hours_to_zero / 1000;

	/* Test that command doesn't change drate but apply new hours to zero */
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));
	zassert_equal(hibern_drate, response.drate.hibern);
	zassert_equal(cutoff_drate, response.drate.cutoff);
	zassert_equal(hours_to_zero, response.hours_to_zero);
	zassert_equal(stayup_cap, response.dzone.stayup);
	zassert_equal(cutoff_cap, response.dzone.cutoff);

	/* Setup any parameters != 0 */
	params.drate.hibern = 1000;
	params.drate.cutoff = 1000;
	/* Clear set flag */
	params.flags = 0;

	/* Test that command doesn't change drate and dzone */
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));
	zassert_equal(hibern_drate, response.drate.hibern);
	zassert_equal(cutoff_drate, response.drate.cutoff);
	zassert_equal(hours_to_zero, response.hours_to_zero);
	zassert_equal(stayup_cap, response.dzone.stayup);
	zassert_equal(cutoff_cap, response.dzone.cutoff);
}

/**
 * Test if default board_system_is_idle() recognize cutoff and stay-up
 * levels correctly.
 */
ZTEST(power_common, test_power_board_system_is_idle)
{
	struct ec_response_smart_discharge response;
	struct ec_params_smart_discharge params;
	struct host_cmd_handler_args args =
		BUILD_HOST_COMMAND(EC_CMD_SMART_DISCHARGE, 0, response, params);
	struct sbat_emul_bat_data *bat;
	const struct emul *emul = EMUL_DT_GET(BATTERY_NODE);
	struct i2c_common_emul_data *common_data =
		emul_smart_battery_get_i2c_common_data(emul);
	uint64_t last_shutdown_time = 0;
	uint64_t target;
	uint64_t now;

	bat = sbat_emul_get_bat_data(emul);

	/* Set up host command parameters */
	params.drate.hibern = 100; /* uA */
	params.drate.cutoff = 10; /* uA */
	params.hours_to_zero = 1000; /* h */
	params.flags = EC_SMART_DISCHARGE_FLAGS_SET;
	/* Set stay-up and cutoff zones */
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	/* Test shutdown ignore is send when target time is in future */
	target = 1125;
	now = 1000;
	zassert_equal(CRITICAL_SHUTDOWN_IGNORE,
		      board_system_is_idle(last_shutdown_time, &target, now),
		      NULL);

	/* Set "now" time after target time */
	now = target + 30;

	/*
	 * Test hibernation is requested when battery remaining capacity
	 * is not available
	 */
	i2c_common_emul_set_read_fail_reg(common_data, SB_REMAINING_CAPACITY);
	zassert_equal(CRITICAL_SHUTDOWN_HIBERNATE,
		      board_system_is_idle(last_shutdown_time, &target, now),
		      NULL);
	i2c_common_emul_set_read_fail_reg(common_data,
					  I2C_COMMON_EMUL_NO_FAIL_REG);

	/* Setup remaining capacity to trigger cutoff */
	bat->cap = response.dzone.cutoff - 5;
	zassert_equal(CRITICAL_SHUTDOWN_CUTOFF,
		      board_system_is_idle(last_shutdown_time, &target, now),
		      NULL);

	/* Setup remaining capacity to trigger stay-up and ignore shutdown */
	bat->cap = response.dzone.stayup - 5;
	zassert_equal(CRITICAL_SHUTDOWN_IGNORE,
		      board_system_is_idle(last_shutdown_time, &target, now),
		      NULL);

	/* Setup remaining capacity to be in safe zone to hibernate */
	bat->cap = response.dzone.stayup + 5;
	zassert_equal(CRITICAL_SHUTDOWN_HIBERNATE,
		      board_system_is_idle(last_shutdown_time, &target, now),
		      NULL);
}

/**
 * Test power console command
 */
ZTEST(power_common, power_console_cmd)
{
	const char *buffer;
	size_t buffer_size;

	test_set_chipset_to_g3();
	shell_backend_dummy_clear_output(get_ec_shell());
	zassert_equal(EC_SUCCESS, shell_execute_cmd(get_ec_shell(), "power"),
		      NULL);
	buffer = shell_backend_dummy_get_output(get_ec_shell(), &buffer_size);
	zassert_true(strcmp(buffer, "\r\noff\r\n") == 0 ||
			     strcmp(buffer, "\r\nOFF\r\n") == 0,
		     "Invalid console output %s", buffer);

	test_set_chipset_to_s0();
	shell_backend_dummy_clear_output(get_ec_shell());
	zassert_equal(EC_SUCCESS, shell_execute_cmd(get_ec_shell(), "power"),
		      NULL);
	buffer = shell_backend_dummy_get_output(get_ec_shell(), &buffer_size);
	zassert_true(strcmp(buffer, "\r\non\r\n") == 0 ||
			     strcmp(buffer, "\r\nON\r\n") == 0,
		     "Invalid console output %s", buffer);

	zassert_equal(EC_ERROR_PARAM1,
		      shell_execute_cmd(get_ec_shell(), "power x"), NULL);

	zassert_equal(EC_SUCCESS, shell_execute_cmd(get_ec_shell(), "power on"),
		      NULL);

	zassert_equal(EC_SUCCESS,
		      shell_execute_cmd(get_ec_shell(), "power off"), NULL);
}

/**
 * Test powerinfo console command
 */
ZTEST_USER(power_common, powerinfo_console_cmd)
{
	char expected_buffer[32];

	snprintf(expected_buffer, sizeof(expected_buffer), "power state %d",
		 power_get_state());

	CHECK_CONSOLE_CMD("powerinfo", expected_buffer, EC_SUCCESS);
}

/**
 * Common setup for hibernation delay tests. Smart discharge zone is setup,
 * battery is set in safe zone (which trigger hibernation), power state is
 * set to G3 and AC is disabled. system_hibernate mock is reset.
 */
static void setup_hibernation_delay(void *state)
{
	struct ec_response_smart_discharge response;
	struct ec_params_smart_discharge params;
	struct host_cmd_handler_args args =
		BUILD_HOST_COMMAND(EC_CMD_SMART_DISCHARGE, 0, response, params);
	struct sbat_emul_bat_data *bat;
	const struct emul *emul = EMUL_DT_GET(BATTERY_NODE);
	ARG_UNUSED(state);

	bat = sbat_emul_get_bat_data(emul);

	/* Setup smart discharge zone and set capacity to safe zone */
	params.drate.hibern = 100; /* uA */
	params.drate.cutoff = 10; /* uA */
	params.hours_to_zero = 10000; /* h */
	params.flags = EC_SMART_DISCHARGE_FLAGS_SET;
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));
	/*
	 * Make sure that battery is in safe zone in good condition to
	 * not trigger hibernate in charge_state_v2.c
	 */
	bat->cap = response.dzone.stayup + 5;
	bat->volt = battery_get_info()->voltage_normal;

	/* Force initial state */
	test_set_chipset_to_g3();

	/* Disable AC */
	set_ac_enabled(false);

	RESET_FAKE(system_hibernate);
}

/** Test setting hibernation delay through host command */
ZTEST(power_common_hibernation, test_power_hc_hibernation_delay)
{
	struct ec_response_hibernation_delay response;
	struct ec_params_hibernation_delay params;
	struct host_cmd_handler_args args = BUILD_HOST_COMMAND(
		EC_CMD_HIBERNATION_DELAY, 0, response, params);
	uint32_t h_delay;
	int sleep_time;

	/* Ensure the lid is closed so AC connect does not boot system */
	zassert_ok(shell_execute_cmd(get_ec_shell(), "lidclose"));

	zassert_equal(power_get_state(), POWER_G3,
		      "Power state is %d, expected G3", power_get_state());
	/* This is a no-op, but it will reset the last_shutdown_time. */
	power_set_state(POWER_G3);

	/* Set hibernate delay */
	h_delay = 9;
	params.seconds = h_delay;
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	zassert_equal(0, response.time_g3, "Time from last G3 enter %d != 0",
		      response.time_g3);
	zassert_equal(h_delay, response.time_remaining,
		      "Time to hibernation %d != %d", response.time_remaining,
		      h_delay);
	zassert_equal(h_delay, response.hibernate_delay,
		      "Hibernation delay %d != %d", h_delay,
		      response.hibernate_delay);

	/* Kick chipset task to process new hibernation delay */
	task_wake(TASK_ID_CHIPSET);
	/* Wait some arbitrary time less than hibernate delay */
	sleep_time = 6;
	k_msleep(sleep_time * 1000);

	/* Get hibernate delay */
	params.seconds = 0;
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	zassert_equal(sleep_time, response.time_g3,
		      "Time from last G3 enter %d != %d", response.time_g3,
		      sleep_time);
	zassert_equal(h_delay - sleep_time, response.time_remaining,
		      "Time to hibernation %d != %d", response.time_remaining,
		      h_delay - sleep_time);
	zassert_equal(h_delay, response.hibernate_delay,
		      "Hibernation delay %d != %d", h_delay,
		      response.hibernate_delay);
	zassert_equal(0, system_hibernate_fake.call_count,
		      "system_hibernate() shouldn't be called before delay");

	/* Wait to end of the hibenate delay */
	k_msleep((h_delay - sleep_time) * 1000);

	/* Get hibernate delay */
	params.seconds = 0;
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	zassert_equal(h_delay, response.time_g3,
		      "Time from last G3 enter %d != %d", response.time_g3,
		      h_delay);
	zassert_equal(0, response.time_remaining, "Time to hibernation %d != 0",
		      response.time_remaining);
	zassert_equal(h_delay, response.hibernate_delay,
		      "Hibernation delay %d != %d", h_delay,
		      response.hibernate_delay);
	zassert_equal(1, system_hibernate_fake.call_count,
		      "system_hibernate() should be called after delay %d",
		      system_hibernate_fake.call_count);

	/* Wait some more time */
	k_msleep(2000);

	/* Get hibernate delay */
	params.seconds = 0;
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	/* After hibernation, remaining time shouldn't be negative */
	zassert_equal(0, response.time_remaining, "Time to hibernation %d != 0",
		      response.time_remaining);

	/* Enable AC */
	set_ac_enabled(true);

	/* Reset system_hibernate fake to check that it is not called on AC */
	RESET_FAKE(system_hibernate);
	/* Allow chipset task to spin with enabled AC */
	task_wake(TASK_ID_CHIPSET);
	k_msleep(1);

	/* Get hibernate delay */
	params.seconds = 0;
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	zassert_equal(0, response.time_g3,
		      "Time from last G3 enter %d should be 0 on AC",
		      response.time_g3);
	zassert_equal(0, system_hibernate_fake.call_count,
		      "system_hibernate() shouldn't be called on AC");

	/* Disable AC */
	set_ac_enabled(false);

	/* Go to different state */
	power_set_state(POWER_G3S5);
	zassert_equal(POWER_G3S5, power_get_state());

	/* Get hibernate delay */
	params.seconds = 0;
	zassert_equal(EC_RES_SUCCESS, host_command_process(&args));

	zassert_equal(0, response.time_g3,
		      "Time from last G3 enter %d should be 0 on state != G3",
		      response.time_g3);
}

/** Test setting hibernation delay through UART command */
ZTEST(power_common_hibernation, test_power_cmd_hibernation_delay)
{
	uint32_t h_delay;
	int sleep_time;

	zassert_equal(power_get_state(), POWER_G3,
		      "Power state is %d, expected G3", power_get_state());
	/* This is a no-op, but it will reset the last_shutdown_time. */
	power_set_state(POWER_G3);

	/* Test success on call without argument */
	zassert_equal(EC_SUCCESS, shell_execute_cmd(get_ec_shell(), "hibdelay"),
		      NULL);

	/* Test error on hibernation delay argument that is not a number */
	zassert_equal(EC_ERROR_PARAM1,
		      shell_execute_cmd(get_ec_shell(), "hibdelay test1"),
		      NULL);

	/* Set hibernate delay */
	h_delay = 3;
	zassert_equal(EC_SUCCESS,
		      shell_execute_cmd(get_ec_shell(), "hibdelay 3"), NULL);

	/* Kick chipset task to process new hibernation delay */
	task_wake(TASK_ID_CHIPSET);
	/* Wait some arbitrary time less than hibernate delay */
	sleep_time = 2;
	k_msleep(sleep_time * 1000);

	zassert_equal(0, system_hibernate_fake.call_count,
		      "system_hibernate() shouldn't be called before delay");

	/* Wait to end of the hibenate delay */
	k_msleep((h_delay - sleep_time) * 1000);

	zassert_equal(1, system_hibernate_fake.call_count,
		      "system_hibernate() should be called after delay %d",
		      system_hibernate_fake.call_count);
}

ZTEST_SUITE(power_common_no_tasks, drivers_predicate_pre_main, NULL, NULL, NULL,
	    NULL);

ZTEST_SUITE(power_common, drivers_predicate_post_main, NULL, NULL, NULL, NULL);

ZTEST_SUITE(power_common_hibernation, drivers_predicate_post_main, NULL,
	    setup_hibernation_delay, NULL, NULL);


text:
require 'monitor_logger'

class Dyno
  MAX_ALLOWED_ERROR_COUNT = 3

  def initialize(heroku_connection, app_name, dyno_name)
    @heroku_connection = heroku_connection
    @app_name = app_name
    @name = dyno_name
    @error_count = 0
  end

  def handle_h12
    add_to_error_count
    MonitorLogger.warn "#{@name} reports H12 (##{@error_count})"

    if exceeded_error_count?
      restart_dyno
      reset_error_count
    end
  end

  def reset_error_count
    @error_count = 0
  end

  private

  def add_to_error_count
    @error_count += 1
  end

  def exceeded_error_count?
    @error_count >= MAX_ALLOWED_ERROR_COUNT
  end

  def restart_dyno
    MonitorLogger.warn "restarting dyno #{@name}"
    @heroku_connection.post_ps_restart @app_name, ps: @name
  end
end

redpajama_set_name: RedPajamaGithub


text:
Rails.application.routes.draw do
  root to: 'sessions#index'

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  get '/logout' => 'sessions#destroy'

  get '/signup' => 'users#new'
  post '/signup' => 'users#create'

  post '/activity' => 'activities#create'

  resources :users

  get '/users/:id/data' => 'users#data'

  resources :friendships
  resources :timeboxes
  resources :activities

  get '/timeboxes/:id/info' => 'timeboxes#time_info'

end


text:
'use strict'

const rule = require('../rules/no-delegate')
const RuleTester = require('eslint').RuleTester

const error = 'Prefer addEventListener to $.delegate'

const ruleTester = new RuleTester()
ruleTester.run('no-delegate', rule, {
  valid: ['delegate()', '[].delegate()', 'div.delegate()', 'div.delegate'],
  invalid: [
    {
      code: '$("div").delegate()',
      errors: [{message: error, type: 'CallExpression'}]
    },
    {
      code: '$div.delegate()',
      errors: [{message: error, type: 'CallExpression'}]
    },
    {
      code: '$("div").first().delegate()',
      errors: [{message: error, type: 'CallExpression'}]
    },
    {
      code: '$("div").append($("input").delegate())',
      errors: [{message: error, type: 'CallExpression'}]
    }
  ]
})


text:
WalrusROG allows only 254 characters (256 minus `\0` and `\xFF`) per font. While it may not fit for big alphabets or ideogram-based languages, it allows enough data for latin-based languages.

If the charsets are esoteric, a tool should be done to allow encoding and previewing with fonts.

##Preferred charset
On a common point, Windows's version of extended Ascii (ANSI IIRC) provides enough characters (like accents) to cover most latin-based language.


text:
<wicket:panel>

		<form wicket:id="form">

					<wicket:message
									key="Settings.synchronizer.cron">Cron expression</wicket:message>

					<input wicket:id="synchronizer.cronExpression"
						class="form-control input-xs" type="text" size="16"
						name="synchronizer.cronExpression"
						style="margin-top: 5px !important; width: 180px!important" />

					<wicket:message
									key="Settings.synchronizer.startup">Run on startup</wicket:message>

					 <input
							wicket:id="synchronizer.runOnStartup" type="checkbox" class="nrs"
							name="synchronizer.runOnStartup" />

					<wicket:message
									key="Settings.synchronizer.createUsers">Create users</wicket:message>

					 <input
							wicket:id="synchronizer.createUsers" type="checkbox" class="nrs"
							name="synchronizer.createUsers" />

					<wicket:message
									key="Settings.synchronizer.deleteUsers">Delete users</wicket:message>

					 <input
							wicket:id="synchronizer.deleteUsers" type="checkbox" class="nrs"
							name="synchronizer.deleteUsers" />

<input wicket:id="change" type="submit" name="change"
					wicket:message="value:change" class="btn btn-primary btn-xs" />

		</form>

</wicket:panel>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using TokyoSubwayView.Models.Metro;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace TokyoSubwayView.Views.Controls
{
	public sealed partial class ConnectorMember : RailwayMember
	{
		public ConnectorMember()
		{
			this.InitializeComponent();
		}

		#region Geometry

		public double X1
		{
			get { return (double)GetValue(X1Property); }
			set { SetValue(X1Property, value); }
		}
		public static readonly DependencyProperty X1Property =
			DependencyProperty.Register(
				"X1",
				typeof(double),
				typeof(ConnectorMember),
				new PropertyMetadata(0D, OnCoordinateChanged));

		public double X2
		{
			get { return (double)GetValue(X2Property); }
			set { SetValue(X2Property, value); }
		}
		public static readonly DependencyProperty X2Property =
			DependencyProperty.Register(
				"X2",
				typeof(double),
				typeof(ConnectorMember),
				new PropertyMetadata(0D, OnCoordinateChanged));

		public double Y1
		{
			get { return (double)GetValue(Y1Property); }
			set { SetValue(Y1Property, value); }
		}
		public static readonly DependencyProperty Y1Property =
			DependencyProperty.Register(
				"Y1",
				typeof(double),
				typeof(ConnectorMember),
				new PropertyMetadata(0D, OnCoordinateChanged));

		public double Y2
		{
			get { return (double)GetValue(Y2Property); }
			set { SetValue(Y2Property, value); }
		}
		public static readonly DependencyProperty Y2Property =
			DependencyProperty.Register(
				"Y2",
				typeof(double),
				typeof(ConnectorMember),
				new PropertyMetadata(0D, OnCoordinateChanged));

		public double LineLength
		{
			get { return (double)GetValue(LineLengthProperty); }
			set { SetValue(LineLengthProperty, value); }
		}
		public static readonly DependencyProperty LineLengthProperty =
			DependencyProperty.Register(
				"LineLength",
				typeof(double),
				typeof(ConnectorMember),
				new PropertyMetadata(400D));

		public double LineWidth
		{
			get { return (double)GetValue(LineWidthProperty); }
			set { SetValue(LineWidthProperty, value); }
		}
		public static readonly DependencyProperty LineWidthProperty =
			DependencyProperty.Register(
				"LineWidth",
				typeof(double),
				typeof(ConnectorMember),
				new PropertyMetadata(40D));

		public double LineAngle
		{
			get { return (double)GetValue(LineAngleProperty); }
			set { SetValue(LineAngleProperty, value); }
		}
		public static readonly DependencyProperty LineAngleProperty =
			DependencyProperty.Register(
				"LineAngle",
				typeof(double),
				typeof(ConnectorMember),
				new PropertyMetadata(30D));

		private static void OnCoordinateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var lines = (ConnectorMember)d;

			if ((0 < lines.X1) && (0 < lines.X2) && (0 < lines.Y1) && (0 < lines.Y2)) // TODO: Conider later
			{
				var lengthX = lines.X2 - lines.X1;
				var lengthY = lines.Y2 - lines.Y1;

				lines.LineLength = CalcLength(lengthX, lengthY);
				lines.LineAngle = CalcAngle(lengthX, lengthY);
			}
		}

		private static double CalcLength(double lengthX, double lengthY)
		{
			return Math.Sqrt(Math.Pow(lengthX, 2D) + Math.Pow(lengthY, 2D));
		}

		private static double CalcAngle(double lengthX, double lengthY)
		{
			var angle = Math.Atan(lengthY / lengthX) * 180D / Math.PI;

			if (lengthX < 0)
				return 180D + angle;

			if (lengthY < 0)
				return 360D + angle;

			return angle;
		}

		#endregion

		#region State

		public TrainState UpperState
		{
			get { return (TrainState)GetValue(UpperStateProperty); }
			set { SetValue(UpperStateProperty, value); }
		}
		public static readonly DependencyProperty UpperStateProperty =
			DependencyProperty.Register(
				"UpperState",
				typeof(TrainState),
				typeof(ConnectorMember),
				new PropertyMetadata(TrainState.Vacant));

		public TrainState LowerState
		{
			get { return (TrainState)GetValue(LowerStateProperty); }
			set { SetValue(LowerStateProperty, value); }
		}
		public static readonly DependencyProperty LowerStateProperty =
			DependencyProperty.Register(
				"LowerState",
				typeof(TrainState),
				typeof(ConnectorMember),
				new PropertyMetadata(TrainState.Vacant));

		#endregion
	}
}


text:
package com.zimbra.soap.admin.message;

import com.google.common.base.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import com.zimbra.common.soap.AdminConstants;
import com.zimbra.common.soap.CertMgrConstants;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name=CertMgrConstants.E_GEN_CSR_RESPONSE)
public class GenCSRResponse {

    /**
     * @zm-api-field-tag server-name
     * @zm-api-field-description Server name
     */
    @XmlAttribute(name=AdminConstants.A_SERVER /* server */, required=true)
    private final String server;

    /**
     * no-argument constructor wanted by JAXB
     */
    @SuppressWarnings("unused")
    private GenCSRResponse() {
        this((String) null);
    }

    public GenCSRResponse(String server) {
        this.server = server;
    }

    public String getServer() { return server; }

    public Objects.ToStringHelper addToStringInfo(
                Objects.ToStringHelper helper) {
        return helper
            .add("server", server);
    }

    @Override
    public String toString() {
        return addToStringInfo(Objects.toStringHelper(this))
                .toString();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

 -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="car_lockscreen_disclaimer_title" msgid="7997539137376896441">"Ry veilig"</string>
    <string name="car_lockscreen_disclaimer_text" msgid="3061224684092952864">"Bly heeltemal bewus van bestuurtoestande en gehoorsaam toepaslike wette altyd. Rigtingaanwysings sal dalk onakkuraat, onvolledig, gevaarlik, ontoepaslik of verbode wees of behels dat administratiewe gebiede oorgesteek word. Besigheidsinligting sal dalk ook onakkuraat of onvolledig wees. Data is nie intyds nie en liggingakkuraatheid kan nie gewaarborg word nie. Moenie jou mobiele toestel hanteer of programme wat nie vir Android Auto bedoel is, gebruik terwyl jy bestuur nie."</string>
</resources>


text:
<?php

// Call Zend_Validate_File_NotExistsTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "Zend_Validate_File_NotExistsTest::main");
}

/**
 * @see Zend_Validate_File_Size
 */
require_once 'Zend/Validate/File/NotExists.php';

/**
 * NotExists testbed
 *
 * @category   Zend
 * @package    Zend_Validate_File
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Validate
 */
class Zend_Validate_File_NotExistsTest extends PHPUnit_Framework_TestCase
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite("Zend_Validate_File_NotExistsTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    /**
     * Ensures that the validator follows expected behavior
     *
     * @return void
     */
    public function testBasic()
    {
        $baseDir = dirname(__FILE__);
        $valuesExpected = array(
            array($baseDir, 'testsize.mo', true),
            array($baseDir . '/_files', 'testsize.mo', false)
        );

        $files = array(
            'name'        => 'testsize.mo',
            'type'        => 'text',
            'size'        => 200,
            'tmp_name'    => dirname(__FILE__) . '/_files/testsize.mo',
            'error'       => 0
        );

        foreach ($valuesExpected as $element) {
            $validator = new Zend_Validate_File_NotExists($element[0]);
            $this->assertEquals(
                $element[2],
                $validator->isValid($element[1]),
                "Tested with " . var_export($element, 1)
            );
            $this->assertEquals(
                $element[2],
                $validator->isValid($element[1], $files),
                "Tested with " . var_export($element, 1)
                );
        }

        $valuesExpected = array(
            array($baseDir, 'testsize.mo', true, false),
            array($baseDir . '/_files', 'testsize.mo', false, false)
        );

        $files = array(
            'name'        => 'testsize.mo',
            'type'        => 'text',
            'size'        => 200,
            'tmp_name'    => dirname(__FILE__) . '/_files/testsize.mo',
            'error'       => 0,
            'destination' => dirname(__FILE__) . '/_files'
        );

        foreach ($valuesExpected as $element) {
            $validator = new Zend_Validate_File_NotExists($element[0]);
            $this->assertEquals(
                $element[2],
                $validator->isValid($element[1]),
                "Tested with " . var_export($element, 1)
            );
            $this->assertEquals(
                $element[3],
                $validator->isValid($element[1], $files),
                "Tested with " . var_export($element, 1)
            );
        }

        $valuesExpected = array(
            array($baseDir, 'testsize.mo', false, false),
            array($baseDir . '/_files', 'testsize.mo', false, false)
        );

        foreach ($valuesExpected as $element) {
            $validator = new Zend_Validate_File_NotExists();
            $this->assertEquals(
                $element[2],
                $validator->isValid($element[1]),
                "Tested with " . var_export($element, 1)
            );
            $this->assertEquals(
                $element[3],
                $validator->isValid($element[1], $files),
                "Tested with " . var_export($element, 1)
            );
        }
    }

    /**
     * Ensures that getDirectory() returns expected value
     *
     * @return void
     */
    public function testGetDirectory()
    {
        $validator = new Zend_Validate_File_NotExists('C:/temp');
        $this->assertEquals('C:/temp', $validator->getDirectory());

        $validator = new Zend_Validate_File_NotExists(array('temp', 'dir', 'jpg'));
        $this->assertEquals('temp,dir,jpg', $validator->getDirectory());

        $validator = new Zend_Validate_File_NotExists(array('temp', 'dir', 'jpg'));
        $this->assertEquals(array('temp', 'dir', 'jpg'), $validator->getDirectory(true));
    }

    /**
     * Ensures that setDirectory() returns expected value
     *
     * @return void
     */
    public function testSetDirectory()
    {
        $validator = new Zend_Validate_File_NotExists('temp');
        $validator->setDirectory('gif');
        $this->assertEquals('gif', $validator->getDirectory());
        $this->assertEquals(array('gif'), $validator->getDirectory(true));

        $validator->setDirectory('jpg, temp');
        $this->assertEquals('jpg,temp', $validator->getDirectory());
        $this->assertEquals(array('jpg', 'temp'), $validator->getDirectory(true));

        $validator->setDirectory(array('zip', 'ti'));
        $this->assertEquals('zip,ti', $validator->getDirectory());
        $this->assertEquals(array('zip', 'ti'), $validator->getDirectory(true));
    }

    /**
     * Ensures that addDirectory() returns expected value
     *
     * @return void
     */
    public function testAddDirectory()
    {
        $validator = new Zend_Validate_File_NotExists('temp');
        $validator->addDirectory('gif');
        $this->assertEquals('temp,gif', $validator->getDirectory());
        $this->assertEquals(array('temp', 'gif'), $validator->getDirectory(true));

        $validator->addDirectory('jpg, to');
        $this->assertEquals('temp,gif,jpg,to', $validator->getDirectory());
        $this->assertEquals(array('temp', 'gif', 'jpg', 'to'), $validator->getDirectory(true));

        $validator->addDirectory(array('zip', 'ti'));
        $this->assertEquals('temp,gif,jpg,to,zip,ti', $validator->getDirectory());
        $this->assertEquals(array('temp', 'gif', 'jpg', 'to', 'zip', 'ti'), $validator->getDirectory(true));

        $validator->addDirectory('');
        $this->assertEquals('temp,gif,jpg,to,zip,ti', $validator->getDirectory());
        $this->assertEquals(array('temp', 'gif', 'jpg', 'to', 'zip', 'ti'), $validator->getDirectory(true));
    }
}

// Call Zend_Validate_File_NotExistsTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Validate_File_NotExistsTest::main") {
    Zend_Validate_File_NotExistsTest::main();
}


text:
require 'securerandom'
require 'fileutils'
require 'rake'

Rake::Task.clear # necessary to avoid tasks being loaded several times in dev mode
Integra::Application.load_tasks # providing your application name is 'sample'

module IntegraNews
  module Generators
    class InstallGenerator < Rails::Generators::Base
      include Rails::Generators::Migration
      source_root File.expand_path("../../templates", __FILE__)

      # Descricao sumaria do que o generator faz
      desc "Instalador do módulo integra IntegraNews"
      class_option :orm

      # Cadastra a Engine na base de dados. Necessário para controle de perfis e permissoes.
      def add_integra_engine
        if generating?
          IntegraEngine.create(:module_name => 'IntegraNews', :display_name => 'Integra News')
        elsif destroying?
          IntegraEngine.where(:module_name => 'IntegraNews').where(:display_name => 'Integra News').first.destroy
        end
      end

      def self.next_migration_number(path)
        unless @prev_migration_nr
          @prev_migration_nr = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
        else
          @prev_migration_nr += 1
        end
          @prev_migration_nr.to_s
      end

      def install_migration
         if generating?
            ### Instala gems de dependencia ###
            system "bundle"

            ### Recupera as migrations da engine ###
            Dir.glob("engines/integra_news/db/migrate/*").sort_by{ |f| File.basename(f) }.each_with_index do |inm, index|
              engine_migrate_file = inm.split('/').last
              engine_migrate = engine_migrate_file[15..engine_migrate_file.size].split('.')[0]

              original_version = engine_migrate_file.split('_').first.to_s
              migrated_version = (migration_template "../../../db/migrate/#{engine_migrate_file}", "db/migrate/#{engine_migrate}.rb").split('/').last.split('_').first

              IntegraEngineMigrated.create(:integra_engine_id => (IntegraEngine.where(:module_name => 'IntegraNews').where(:display_name => 'Integra News').first).id, :original_version => original_version, :migrated_version => migrated_version) if !IntegraEngineMigrated.find_by_original_version(original_version)
            end

            ### Nao migra o que ja foi migrado ###
            Dir.glob("engines/integra_news/db/migrate/*").sort_by{ |f| File.basename(f) }.each do |inm|
              migrated_version = IntegraEngineMigrated.where(:integra_engine_id => (IntegraEngine.where(:module_name => 'IntegraNews').where(:display_name => 'Integra News').first).id, :original_version => (inm.split('/').last).split('_').first.to_s).first.migrated_version
              if SchemaMigration.all.map {|sm| sm.version}.include?(migrated_version)
                FileUtils.rm(Dir.glob("db/migrate/*").select {|m| m.include?(inm.split('/').last[15..inm.size].split('.').first)})
              end
            end

            begin
               Rake::Task['db:migrate'].reenable
               Rake::Task['db:migrate'].invoke

               Dir.glob("engines/integra_news/db/migrate/*").sort_by{ |f| File.basename(f) }.each do |inm|
                 Dir.glob("db/migrate/*").sort_by{ |f| File.mtime(f) }.each do |im|
                   if im.include?(inm.split('/')[4][15..inm.size].split('.')[0].to_s)
                     FileUtils.rm(im)
                   end
                 end
               end

               puts "\n\n"
               readme "README"
            rescue Exception => msg
               puts "\n\nHouve um erro: \n\n#{msg}"
               Dir.glob("engines/integra_news/db/migrate/*").sort_by{ |f| File.basename(f) }.each do |inm|
                 Dir.glob("db/migrate/*").sort_by{ |f| File.mtime(f) }.each do |im|
                   if im.include?(inm.split('/')[4][15..inm.size].split('.')[0].to_s)
                     FileUtils.rm(im)
                   end
                 end
               end
            end

         elsif destroying?
           puts "\n\n"
           readme "README_DESTROYING"
         end
      end

      protected

      def generating?
         :invoke == behavior
      end

      def destroying?
         :revoke == behavior
      end
    end
  end
end


text:
  layout:     post
  title:      YODO (Inverse Reinforcement Learning)
  date:       2018-12-15 18:12:15
  summary:    This project aims to teach an agent to stack blocks together in a simulated 2D world using Inverse Reinforcement Learning
  categories: reinforcement-learning inverse-reinforcement-learning block-world python3 q-learning demonstrations learning-from-demonstration georgia-tech interactive-robot-learning
  cover-image: /images/yodo-teaser.png
  redirect_to:
    - /YODO-Inverse-Reinforcement-Learning/
---


text:
<!DOCTYPE HTML>

	<title>sap.uxap.ObjectPage</title>


text:
FROM iaf-as-tomcat AS iaf-test-tomcat

# copy additional environment configuration for iaf-test
COPY --chown=tomcat src/scripts/catalinaAdditionalTest.properties /tmp
RUN cat /tmp/catalinaAdditionalTest.properties >> /usr/local/tomcat/conf/catalina.properties  && rm -f /tmp/catalinaAdditionalTest.properties

# copy war
COPY --chown=tomcat target/dependencies/ibis-adapterframework-test.war /usr/local/tomcat/webapps/iaf-test.war

# copy any additional drivers
COPY --chown=tomcat target/dependencies/*.jar /usr/local/tomcat/lib/

# Credentials need to be mounted in /opt/frank/secrets at runtime


text:
maintainer       "Guilhem Lettron"
maintainer_email "guilhem.lettron@youscribe.com"
license          "Apache v2.0"
description      "Manage modules on linux"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "0.1.2"
supports         "ubuntu"
supports         "debian"


text:
module Azure::CDN::Mgmt::V2016_04_02
  module Models
    #
    # Endpoint properties required for new endpoint creation.
    #
    class EndpointCreateParameters

      include MsRestAzure

      # @return [String] Endpoint location
      attr_accessor :location

      # @return [Hash{String => String}] Endpoint tags
      attr_accessor :tags

      # @return [String] The host header CDN provider will send along with
      # content requests to origins. The default value is the host name of the
      # origin.
      attr_accessor :origin_host_header

      # @return [String] The path used for origin requests.
      attr_accessor :origin_path

      # @return [Array<String>] List of content types on which compression will
      # be applied. The value for the elements should be a valid MIME type.
      attr_accessor :content_types_to_compress

      # @return [Boolean] Indicates whether content compression is enabled.
      # Default value is false. If compression is enabled, the content
      # transferred from the CDN endpoint to the end user will be compressed.
      # The requested content must be larger than 1 byte and smaller than 1 MB.
      attr_accessor :is_compression_enabled

      # @return [Boolean] Indicates whether HTTP traffic is allowed on the
      # endpoint. Default value is true. At least one protocol (HTTP or HTTPS)
      # must be allowed.
      attr_accessor :is_http_allowed

      # @return [Boolean] Indicates whether https traffic is allowed on the
      # endpoint. Default value is true. At least one protocol (HTTP or HTTPS)
      # must be allowed.
      attr_accessor :is_https_allowed

      # @return [QueryStringCachingBehavior] Defines the query string caching
      # behavior. Possible values include: 'IgnoreQueryString',
      # 'BypassCaching', 'UseQueryString', 'NotSet'
      attr_accessor :query_string_caching_behavior

      # @return [Array<DeepCreatedOrigin>] The set of origins for the CDN
      # endpoint. When multiple origins exist, the first origin will be used as
      # primary and rest will be used as failover options.
      attr_accessor :origins

      #
      # Mapper for EndpointCreateParameters class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'EndpointCreateParameters',
          type: {
            name: 'Composite',
            class_name: 'EndpointCreateParameters',
            model_properties: {
              location: {
                client_side_validation: true,
                required: true,
                serialized_name: 'location',
                type: {
                  name: 'String'
                }
              },
              tags: {
                client_side_validation: true,
                required: false,
                serialized_name: 'tags',
                type: {
                  name: 'Dictionary',
                  value: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              origin_host_header: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.originHostHeader',
                type: {
                  name: 'String'
                }
              },
              origin_path: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.originPath',
                type: {
                  name: 'String'
                }
              },
              content_types_to_compress: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.contentTypesToCompress',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              is_compression_enabled: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.isCompressionEnabled',
                type: {
                  name: 'Boolean'
                }
              },
              is_http_allowed: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.isHttpAllowed',
                type: {
                  name: 'Boolean'
                }
              },
              is_https_allowed: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.isHttpsAllowed',
                type: {
                  name: 'Boolean'
                }
              },
              query_string_caching_behavior: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.queryStringCachingBehavior',
                type: {
                  name: 'Enum',
                  module: 'QueryStringCachingBehavior'
                }
              },
              origins: {
                client_side_validation: true,
                required: true,
                serialized_name: 'properties.origins',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'DeepCreatedOriginElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'DeepCreatedOrigin'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class ServiceAssociationLink : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Id))
            {
                writer.WritePropertyName("id");
                writer.WriteStringValue(Id);
            }
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(LinkedResourceType))
            {
                writer.WritePropertyName("linkedResourceType");
                writer.WriteStringValue(LinkedResourceType.Value);
            }
            if (Optional.IsDefined(Link))
            {
                writer.WritePropertyName("link");
                writer.WriteStringValue(Link);
            }
            if (Optional.IsDefined(AllowDelete))
            {
                writer.WritePropertyName("allowDelete");
                writer.WriteBooleanValue(AllowDelete.Value);
            }
            if (Optional.IsCollectionDefined(Locations))
            {
                writer.WritePropertyName("locations");
                writer.WriteStartArray();
                foreach (var item in Locations)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static ServiceAssociationLink DeserializeServiceAssociationLink(JsonElement element)
        {
            Optional<ETag> etag = default;
            Optional<ResourceIdentifier> id = default;
            Optional<string> name = default;
            Optional<ResourceType> type = default;
            Optional<ResourceType> linkedResourceType = default;
            Optional<ResourceIdentifier> link = default;
            Optional<NetworkProvisioningState> provisioningState = default;
            Optional<bool> allowDelete = default;
            Optional<IList<AzureLocation>> locations = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("etag"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    etag = new ETag(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("linkedResourceType"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            linkedResourceType = new ResourceType(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("link"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            link = new ResourceIdentifier(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new NetworkProvisioningState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("allowDelete"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            allowDelete = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("locations"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<AzureLocation> array = new List<AzureLocation>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(new AzureLocation(item.GetString()));
                            }
                            locations = array;
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new ServiceAssociationLink(id.Value, name.Value, Optional.ToNullable(type), Optional.ToNullable(etag), Optional.ToNullable(linkedResourceType), link.Value, Optional.ToNullable(provisioningState), Optional.ToNullable(allowDelete), Optional.ToList(locations));
        }
    }
}


text:
module.exports = function(agent , database , ipTracker) {
    const ObjectId = require('mongodb').ObjectId;
  	const Spooky = require('spooky');
    const EventEmitter = require('events').EventEmitter;
    const domain = require('domain');
    const Buckets = database.model('Buckets');

    let child_processes = 0;
    let ipQueue = [];
    let bucket;

    // @method getBucket
    const getBucket = () => bucket;

    // @method setBucket
    const setBucket =  (bucketObj) => {
        bucket = bucketObj;
        if(bucket.urls.length > 0) {
            for(let i=0; i < bucket.urls.length; i++){
                bucket.urls[i].visited = 0;
                bucket.urls[i].statusText = 'No status yet';
            };
         }
    	 console.log('bucket set in visitor');
    };

    // @method updateBucket
    const updateBucket = (bucketObj, meta) => {
    	if(bucket) {
            if(bucketObj._id+'' == bucket._id) {
	           if(meta.action == 0) {
	           	   console.log('Deleting url in this bucket');
                   bucket.urls.splice(meta.index , 1);
	           }
	           else if(meta.action == 1) {
                   console.log('Updating url in this bucket');
                   bucket = bucketObj;
	           }
	    	}
    	}
    }

    // @method notifyDelete
    const notifyDelete = (_id) => {
        if(bucket){
            if(bucket._id == _id){
                setTimeout(() => {
                    process.exit(0);
                } , 10000);
             }
         }
    }

    // @method visitWith
    const visitWith = (ip) => {
        console.log('Adding %s to queue' , ip);
        if(ipQueue.indexOf(ip) < 0){
            ipQueue.push(ip);
            if(ipQueue.length === 1){
                startUpdateDaemon();
                startVisitingDaemon();
            }
        }
    }

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    const V_WORKER = () => {
        console.log('we got here V_WORKER');
        let workerEvents = new EventEmitter;

        let visit = (ip, urlObj, index, userAgent) => {
            console.log(`visit starting with ${ip} and ${urlObj.urlName}`);

            let spooky = Spooky.create({
                child: {
                    transport: 'http',
                    proxy: ip
                },

                casper: {
                    logLevel: 'debug',
                    verbose: true,
                    options: {
                        clientScripts: [],
                        pageSettings: {
                            webSecurityEnabled: false,
                            userAgent:userAgent
                        }
                    }
                }
            }, (err) => {
               if (err) {
                    e = new Error('Failed to initialize SpookyJS');
                    e.details = err;
                    throw e;
                }

                ((url, selector, index) => {
                    console.log(userAgent);
                    spooky.start();
                    spooky.then(function() {
                        this.page.customHeaders = {
                            "Referer": 'https://www.yahoo.com'
                        };
                    });
                    spooky.thenOpen(url);
                    spooky.then([{url:url, selector:selector, index:index}, function() {
                        this.done = function(err , status) {
                            if(err){
                                this.emit('done', {status: this.getCurrentUrl(), index:index});
                                return phantom.clearCookies();
                            } else {
                                this.emit('done', {status: this.getCurrentUrl(), index:index});
                                return phantom.clearCookies();
                            }
                        }

                       if(selector === 'none'){
                            this.then(function() {
                                this.wait(10000, function() {
                                    return this.done(null, true);
                                });
                            });
                        } else{
                            this.then(function() {
                                this.waitForSelector(selector, function() {
                                    this.thenClick(selector, function() {
                                        this.wait(10000, function() {
                                            return this.done(null, true);
                                        });
                                    });

                                }, function() {
                                    return this.done(true, null);
                                }, 10000);
                            });
                        }
                    }]);

                })(urlObj.urlName , urlObj.selector , index);

                spooky.run();
            });

            spooky.on('console', (line) => {
                console.log(line);
            });

            //
            spooky.on('error', (e, stack) => {
                console.error(stack||e);
                workerEvents.emit('done' , {status:stack?stack:e , index:0});
            });

            //
            spooky.on('done', (status) => {
                workerEvents.emit('done' , status);
            });

            //self destruct this instance in 8 minutes
            setTimeout(() => {
                spooky.destroy();
                child_processes--;
                return;
            } , 8*60000);
        };

        return {
            visit:visit,
            status:workerEvents
        }
    }
    //++++++++++++++++++++++++++++++++END++++++++++++++++++++++++++++++++++++++++++

    function startVisitingDaemon() {
       console.log('visiting daemon started');
       let v_worker = V_WORKER();

       (function fillVisiting(currentIp) {
            if(currentIp < ipQueue.length && child_processes < 20) {
               child_processes+=bucket.urls.length;

               //spin all new workers for each urls
               (function validateUnique(urlIndex) {
                    if(urlIndex >= bucket.urls.length) {
                        console.log('ip round complete... starting next round in 10 secs');
                        setTimeout(() => {
                             return fillVisiting(++currentIp);
                        } , 10000);
                    } else {
                       ipTracker.isUsable(ipQueue[currentIp], bucket.urls[urlIndex], (ip) => {
                           if(ip) {
                               console.log(urlIndex);
                               console.log('there is an ip', bucket.urls[urlIndex]);
                               v_worker.visit(ip, bucket.urls[urlIndex], urlIndex, agent.next());
                           }
                           return validateUnique(++urlIndex);
                       });
                    }
                })(0);
            }
            else {
                console.log('Good ip shortage trying again in 10 secs');
                setTimeout(() => {
                     return fillVisiting(currentIp);
                } , 10000);
            }
       })(0);

       v_worker.status.on('done', (status) => {
            console.log(status);
            bucket.urls[status.index].statusText = status.status;
            bucket.urls[status.index].visited++;
       });
    }

    //updateBucket after every 120 secs of activity
    function startUpdateDaemon() {
        let timer = 0;
        console.log('Starting cron daemon');
        setInterval(() => {
            bucket.lastActive = Date.now()+'';
            Buckets.update({_id : ObjectId(bucket._id)}, bucket, (err , result) => {
                if(err){
                   console.log(err);
                }
                else {
                    timer += 2;
                    if(timer >= 120){
                        console.log('Maximum uptime of 2 hours exceeded exiting....');
                        process.exit(0);
                    }
                    console.log('bucket updated in cron job');
                }
            }
          );
        } , 120000);
    }

    return {
        visitWith,
        getBucket,
        setBucket,
        updateBucket,
        notifyDelete
    }
};


text:
[![Wercker](https://img.shields.io/wercker/ci/wercker/docs.svg?maxAge=2592000)]() [![PyPI](https://img.shields.io/pypi/status/Django.svg?style=flat-square)]()

A multiple todo list manager.

## Technology Stack

* MongoDB with Mongoose
* Node with Express
* Angular

## Setup (Please follow in order)

* Git clone the repo
* Checkout the dev branch
* Make sure you are in the root folder of the dockit directory, which is 'dockit'.
* Install npm if you haven't. Follow instrucions [here](https://docs.npmjs.com/getting-started/installing-node)
* Install MongoDB, Follow instructions [here](https://www.npmjs.com/package/mongodb)
* npm install
* bower install
* Navigate to the /dockit/server folder and run `jasmine init` (this is for setting up server side specs)
* Navigate to the /dockit folder and run `gulp serve`

At this point, you should have the app setup complete.

#### Running the App

* Open a new terminal window and run the command 'mongod'.
* You should now see that Mongo server is running

![Alt text](img/Mongod.png "Mongod Server Running")

* Open another terminal window and run the command 'gulp serve' to have the server running.
* With default settings, the app should automatically pop up in a new web browser window.
* (Skip this if previous step was successful) If not, open a new web browser window and in the URL bar, type in 'localhost:3000'. This should redirect you to the landing page of the app.
* You should see the landing page as shown below:

![Eggercise Landing Page](img/LandingPage.png "Eggercise Landing Page")


text:
<?php
require_once 'ComboInstituicao.php';
?>

     <form class="col s12" method='post' action='cadLicenca.php'>

                        <input name="dt_compra" placeholder="Escolha a data da compra" id="compra" type="date" >
                        Data de Compra

                        <input name="dt_vencimento" placeholder="Escolha a data de vencimento" id="vemc" type="date" >
                        Data de Vencimento

                        <input name="valor" placeholder="R$ 0,00" id="valor" type="text" class="validate" pattern="^\d+(\.|\,)\d{2}$">
                        Valor

                        <input name="quantidade_licenca" placeholder="Digite a quantidade de lincença" id="licenca" type="text" class="validate" maxlength="80">
                        Licença

                        Licença ativa?

                             <input name="ativo" type="radio" id="fem"id="fem" value='sim' />
                            Sim
                            <input class="radioPesq" name="ativo" type='radio'id="masc" value='nao'  />
                            Não

                        Instituições

                        <select name="id_inst" class="browser-default">
                            <option value="" disabled selected>Escolha uma instituiçao</option>
                       <?php echo comboInst();?>
                        </select>

        <button class="btn waves-effect waves-light" type="submit" name="action">ENVIAR

        </button>

  </form>


text:
import numpy as np

"""
Interface for accessing contexts, because different datasets have different looking formats.
This handles both label-dependent features and non-label dependent features.
"""
class Context(object):
    def __init__(self, name, features, K, L, clusters=None):
        self.name = name
        self.K = K
        self.L = L
        if clusters != None:
            self.clusters = clusters
        if features.shape[0] > 1:
            assert features.shape[0] == K, "Multi-row feature vec but not K rows"
            self.ld_features = features
            self.ld_dim = features.shape[1]
            self.features = np.reshape(features, self.K*self.ld_dim)
            self.dim = len(self.features)
        else:
            self.ld_dim = None
            self.ld_features = None
            self.features = features
            self.dim = self.features.shape[1]

    def get_ld_features(self):
        assert self.ld_features is not None, "Dataset does not support label dependent features"
        return self.ld_features

    def get_features(self):
        assert self.L == 1, "Cannot implement reduction to classification for semibandits"
        return self.features

    def get_L(self):
        return self.L

    def get_K(self):
        return self.K

    def get_name(self):
        return self.name

    def get_ld_dim(self):
        return self.ld_dim

    def get_dim(self):
        return self.dim


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.videoanalyzer.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.videoanalyzer.models.ParameterDefinition;
import com.azure.resourcemanager.videoanalyzer.models.PipelineJobError;
import com.azure.resourcemanager.videoanalyzer.models.PipelineJobState;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.List;

/** Pipeline job properties. */
@Fluent
public final class PipelineJobProperties {
    /*
     * Reference to an existing pipeline topology. When activated, this
     * pipeline job will process content according to the pipeline topology
     * definition.
     */
    @JsonProperty(value = "topologyName", required = true)
    private String topologyName;

    /*
     * An optional description for the pipeline.
     */
    @JsonProperty(value = "description")
    private String description;

    /*
     * Current state of the pipeline (read-only).
     */
    @JsonProperty(value = "state", access = JsonProperty.Access.WRITE_ONLY)
    private PipelineJobState state;

    /*
     * The date-time by when this pipeline job will be automatically deleted
     * from your account.
     */
    @JsonProperty(value = "expiration", access = JsonProperty.Access.WRITE_ONLY)
    private OffsetDateTime expiration;

    /*
     * Details about the error, in case the pipeline job fails.
     */
    @JsonProperty(value = "error", access = JsonProperty.Access.WRITE_ONLY)
    private PipelineJobError error;

    /*
     * List of the instance level parameter values for the user-defined
     * topology parameters. A pipeline can only define or override parameters
     * values for parameters which have been declared in the referenced
     * topology. Topology parameters without a default value must be defined.
     * Topology parameters with a default value can be optionally be
     * overridden.
     */
    @JsonProperty(value = "parameters")
    private List<ParameterDefinition> parameters;

    /**
     * Get the topologyName property: Reference to an existing pipeline topology. When activated, this pipeline job will
     * process content according to the pipeline topology definition.
     *
     * @return the topologyName value.
     */
    public String topologyName() {
        return this.topologyName;
    }

    /**
     * Set the topologyName property: Reference to an existing pipeline topology. When activated, this pipeline job will
     * process content according to the pipeline topology definition.
     *
     * @param topologyName the topologyName value to set.
     * @return the PipelineJobProperties object itself.
     */
    public PipelineJobProperties withTopologyName(String topologyName) {
        this.topologyName = topologyName;
        return this;
    }

    /**
     * Get the description property: An optional description for the pipeline.
     *
     * @return the description value.
     */
    public String description() {
        return this.description;
    }

    /**
     * Set the description property: An optional description for the pipeline.
     *
     * @param description the description value to set.
     * @return the PipelineJobProperties object itself.
     */
    public PipelineJobProperties withDescription(String description) {
        this.description = description;
        return this;
    }

    /**
     * Get the state property: Current state of the pipeline (read-only).
     *
     * @return the state value.
     */
    public PipelineJobState state() {
        return this.state;
    }

    /**
     * Get the expiration property: The date-time by when this pipeline job will be automatically deleted from your
     * account.
     *
     * @return the expiration value.
     */
    public OffsetDateTime expiration() {
        return this.expiration;
    }

    /**
     * Get the error property: Details about the error, in case the pipeline job fails.
     *
     * @return the error value.
     */
    public PipelineJobError error() {
        return this.error;
    }

    /**
     * Get the parameters property: List of the instance level parameter values for the user-defined topology
     * parameters. A pipeline can only define or override parameters values for parameters which have been declared in
     * the referenced topology. Topology parameters without a default value must be defined. Topology parameters with a
     * default value can be optionally be overridden.
     *
     * @return the parameters value.
     */
    public List<ParameterDefinition> parameters() {
        return this.parameters;
    }

    /**
     * Set the parameters property: List of the instance level parameter values for the user-defined topology
     * parameters. A pipeline can only define or override parameters values for parameters which have been declared in
     * the referenced topology. Topology parameters without a default value must be defined. Topology parameters with a
     * default value can be optionally be overridden.
     *
     * @param parameters the parameters value to set.
     * @return the PipelineJobProperties object itself.
     */
    public PipelineJobProperties withParameters(List<ParameterDefinition> parameters) {
        this.parameters = parameters;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (topologyName() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property topologyName in model PipelineJobProperties"));
        }
        if (error() != null) {
            error().validate();
        }
        if (parameters() != null) {
            parameters().forEach(e -> e.validate());
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(PipelineJobProperties.class);
}


text:
package de.espend.idea.oxid;

import com.intellij.openapi.util.IconLoader;

import javax.swing.*;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class OxidPluginIcons {
    public static final Icon OXID = IconLoader.getIcon("icons/oxid.png");
    public static final Icon OXID_LINEMARKER = IconLoader.getIcon("icons/line_marker_oxid.png");
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Scriban.Helpers;
using Scriban.Parsing;
using Scriban.Runtime;

namespace Scriban.Syntax
{
    /// <summary>
    /// Base class for the abstract syntax tree of a scriban program.
    /// </summary>
#if SCRIBAN_PUBLIC
    public
#else
    internal
#endif
    abstract class ScriptNode
    {
        /// <summary>
        /// The source span of this node.
        /// </summary>
        public SourceSpan Span;

        /// <summary>
        /// Gets the parent of this node.
        /// </summary>
        public ScriptNode Parent { get; internal set; }

        /// <summary>
        /// Evaluates this instance with the specified context.
        /// </summary>
        /// <param name="context">The template context.</param>
        public abstract object Evaluate(TemplateContext context);

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        public virtual int ChildrenCount => 0;

        /// <summary>
        /// Clones this node including its trivias.
        /// </summary>
        /// <returns>Return a clone of this node.</returns>
        public ScriptNode Clone()
        {
            return Clone(true);
        }

        /// <summary>
        /// Clones this node.
        /// </summary>
        /// <param name="withTrivias"><c>true</c> to copy the trivias.</param>
        /// <returns>Return a clone of this node.</returns>
        public ScriptNode Clone(bool withTrivias)
        {
            var cloner = withTrivias ? ScriptCloner.WithTrivias : ScriptCloner.Instance;
            return cloner.Visit(this);
        }

        /// <summary>
        /// Gets a children at the specified index.
        /// </summary>
        /// <param name="index">Index of the children</param>
        /// <returns>A children at the specified index</returns>
        public ScriptNode GetChildren(int index)
        {
            if (index < 0) throw ThrowHelper.GetIndexNegativeArgumentOutOfRangeException();
            if (index > ChildrenCount) throw ThrowHelper.GetIndexArgumentOutOfRangeException(ChildrenCount);
            return GetChildrenImpl(index);
        }

        /// <summary>
        /// Gets a children at the specified index.
        /// </summary>
        /// <param name="index">Index of the children</param>
        /// <returns>A children at the specified index</returns>
        /// <remarks>The index is safe to use</remarks>
        protected virtual ScriptNode GetChildrenImpl(int index) => null;

#if !SCRIBAN_NO_ASYNC
        public virtual ValueTask<object> EvaluateAsync(TemplateContext context)
        {
            return new ValueTask<object>(Evaluate(context));
        }
#endif

        public virtual bool CanHaveLeadingTrivia()
        {
            return true;
        }

        public abstract void PrintTo(ScriptPrinter printer);

        public virtual void Accept(ScriptVisitor visitor) => throw new NotImplementedException($"This method must be implemented by the type {this.GetType()}");

        public virtual TResult Accept<TResult>(ScriptVisitor<TResult> visitor) => throw new NotImplementedException($"This method must be implemented by the type {this.GetType()}");

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        public IEnumerable<ScriptNode> Children
        {
            get
            {
                var count = ChildrenCount;
                for (int i = 0; i < count; i++)
                {
                    yield return GetChildrenImpl(i);
                }
            }
        }

        /// <summary>
        /// Helper method to deparent/parent a node to this instance.
        /// </summary>
        /// <typeparam name="TSyntaxNode">Type of the node</typeparam>
        /// <param name="set">The previous child node parented to this instance</param>
        /// <param name="node">The new child node to parent to this instance</param>
        protected void ParentToThis<TSyntaxNode>(ref TSyntaxNode set, TSyntaxNode node) where TSyntaxNode : ScriptNode
        {
            if (node == set) return;
            if (node?.Parent != null) throw ThrowHelper.GetExpectingNoParentException();
            if (set != null)
            {
                set.Parent = null;
            }
            if (node != null)
            {
                node.Parent = this;
            }
            set = node;
        }

        public sealed override string ToString()
        {
            var strOutput = new StringBuilderOutput();
            var printer = new ScriptPrinter(strOutput , new ScriptPrinterOptions() { Mode = ScriptMode.ScriptOnly });
            printer.Write(this);
            var result = strOutput.ToString();
            strOutput.Builder.Length = 0;
            return result;
        }
    }
}


text:
<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<div class="_filters _hidden_inputs">
    <?php
    foreach($invoices_sale_agents as $agent){
        echo form_hidden('sale_agent_'.$agent['sale_agent']);
    }
    foreach($invoices_statuses as $_status){
        $val = '';
        if($_status == $this->input->get('status')){
            $val = $_status;
        }
        echo form_hidden('invoices_'.$_status,$val);
    }
    foreach($invoices_years as $year){
        echo form_hidden('year_'.$year['year'],$year['year']);
    }
    foreach($payment_modes as $mode){
        echo form_hidden('invoice_payments_by_'.$mode['id']);
    }
    echo form_hidden('not_sent',$this->input->get('filter'));
    echo form_hidden('not_have_payment');
    echo form_hidden('recurring');
    echo form_hidden('project_id');
    ?>
</div>


text:
package com.facebook.infer.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Similar to the {@literal @ThreadSafe} annotation from javax.concurrent.annotation, but can be
 * applied to methods. In addition, you can ask Infer to assume thread-safety rather than checking
 * it by using {@literal @ThreadSafe(enableChecks = false)}.
 */
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
public @interface ThreadSafe {
  boolean enableChecks() default true;
}


text:
  Morville-sur-Andelle est
       un village
       situé dans le département de Seine-Maritime en Haute-Normandie. On dénombrait 255 habitants en 2008.

À proximité de Morville-sur-Andelle sont situées les villes de
Saint-Denis-le-Thiboult à 5 km, 504 habitants,
Nolléval localisée à 4 km, 390 habitants,
La Hallotière localisée à 5 km, 131 habitants,
Ry à 5 km, 688 habitants,
Le Héron localisée à 1 km, 242 habitants,
Rebets localisée à 4 km, 133 habitants,
 entre autres. De plus, Morville-sur-Andelle est située à seulement 24 km de Rouen.

Le parc d'habitations, à Morville-sur-Andelle, se décomposait en 2011 en quatre appartements et 117 maisons soit
 un marché relativement équilibré.

Si vous pensez venir habiter à Morville-sur-Andelle, vous pourrez aisément trouver une maison à vendre.


text:
/**
 * Created by sebastian on 5/13/15.
 */

var ownsheetApp = angular.module("ownsheetApp");

ownsheetApp.service('previewContentService', ["$q", function ($q) {
    var preview = this;

    preview.add = function(content){
        preview.content = content;
    };

    preview.get = function(){
        var deferred = $q.defer();
        setTimeout(function () {
            deferred.resolve(preview.content);
        }, 0);
        return deferred.promise;
    };

    preview.buffer = function(bufferedContent){
        preview.bufferedContent = bufferedContent;
    };

    preview.getBuffer = function(){
        return preview.bufferedContent;
    };

}]);


text:
/* vms-c.c  */
extern void vms_c_register_pragma (void);

/* vms.c  */
void vms_patch_builtins (void);

#ifdef TREE_CODE
extern section *vms_function_section (tree decl ATTRIBUTE_UNUSED,
                                      enum node_frequency freq ATTRIBUTE_UNUSED,
                                      bool startup ATTRIBUTE_UNUSED,
                                      bool exit ATTRIBUTE_UNUSED);
#endif /* TREE_CODE */


text:
let chai = require("chai");
let sinon = require("sinon");
let sinonChai = require("sinon-chai");
chai.use(sinonChai);
let expect = chai.expect;

import Logger from "../../src/logger";

describe("warn", () => {
  it("logs to console.warn", () => {
    let logger = new Logger();
    sinon.spy(console, "warn");

    logger.warn({ help: "example", nodes: []});
    logger.warn({ help: "example", nodes: []});

    expect(console.warn).to.be.have.been.calledWith("example", []);
    expect(console.warn).to.be.have.been.calledOnce;
  });
});


text:
from flask import Flask, redirect, render_template, request
import jinja2
from tempfile import NamedTemporaryFile

from .. import Directory, directory_by_hash, directory_delete, directory_list, str_size

# Init app

jinja2.filters.FILTERS['str_size'] = str_size

app = Flask(__name__)

# Pages

@app.route('/')
def dirlist():
    directories = [Directory(d, checkvalid=False) for d in directory_list()]
    return render_template('dirlist.html',
                           directories=directories)

@app.route('/dir/add', methods=['post'])
def diradd():
    dirname = request.form.get('directory', '')
    if dirname:
        Directory(dirname)
    return redirect('/')

@app.route('/dir/<dirhash>')
def dirinfo(dirhash):
    return render_template('dirinfo.html',
                           directory=directory_by_hash(dirhash, checkvalid=False))

@app.route('/dir/<dirhash>/option', methods=['post'])
def diroption(dirhash):
    directory = directory_by_hash(dirhash)
    directory.set_option_follow_link('followlink' in request.form)
    directory.save_meta()
    directory.exclude = request.form.get('exclude', '').splitlines()
    directory.save_exclude()
    return redirect('/dir/%s' % dirhash)

@app.route('/dir/<dirhash>/update')
def dirupdate(dirhash):
    directory = directory_by_hash(dirhash)
    outtree = directory.update_tree()
    outhash = list(directory.hash_for_update())
    [directory.update_hash(i) for i in outhash]
    return render_template('dirupdate.html',
                           directory=directory,
                           outtree=outtree,
                           outhash=outhash)

@app.route('/dir/<dirhash>/delete')
def dirdelete(dirhash):
    directory_delete(dirhash)
    return redirect('/')

@app.route('/dir/<dirhash>/deletefile', methods=['post'])
def dirdeletefile(dirhash):
    directory = directory_by_hash(dirhash)
    for filename in request.form.getlist('file'):
        directory.delete_file(filename)
    return redirect('/dir/%s' % dirhash)

@app.route('/dir/<dirhash>/indir', methods=['post'])
def indir(dirhash):
    directory = directory_by_hash(dirhash)
    with NamedTemporaryFile(prefix='deduplicated-') as tmpfile:
        request.files.get('file').save(tmpfile.name)
        files = directory.is_file_in(tmpfile.name)
    return render_template('indir.html',
                           directory=directory,
                           name=request.files.get('file').filename,
                           files=files)

# Run

def main():
    app.run(port=5050)


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Book',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),
                ('title', models.CharField(max_length=255)),
                ('slug', models.SlugField(max_length=500)),
                ('author', models.CharField(max_length=255)),
                ('pages', models.IntegerField()),
                ('publish_date', models.DateTimeField()),
                ('description', models.TextField(default='', blank=True)),
            ],
            options={
                'db_table': 'book',
            },
        ),
        migrations.CreateModel(
            name='UserProfileBook',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),
                ('status', models.IntegerField(default=1, choices=[(1, 'Reading'), (2, 'Read')])),
                ('book', models.ForeignKey(to='books.Book')),
            ],
            options={
                'db_table': 'user_book',
            },
        ),
    ]


text:
/**
 * Created by weigg on 2017/7/11.
 */
angular.module('ZrsmWorker')
    .controller('taskStorageListCtrl', function($scope,ionicPopup,$state,$ionicHistory,taskStorageListService,$stateParams,API_CONFIG_UTIL) {
        $scope.goback = function(){
            $ionicHistory.goBack();
        };
        $scope.allDays = '1';
        $scope.finished = 0;
        $scope.unfinished = 0;
        $scope.works = null;

        var fetchData = function() {
            taskStorageListService.mystoragetasks({
                allDays:!!($scope.allDays-0),
                stockroomId:$stateParams.item.stockroomId
            }).then(function(data){
                $scope.works = data.works;
                $scope.finished = data.finish;
                $scope.unfinished = data.unfinish;
            })
        }

        $scope.select_ = function(){
            fetchData();
        }

        $scope.stockcheck = function(){
            taskStorageListService.stockcheck({
                stockroomId:$stateParams.item.stockroomId
            }).then(()=>{
                API_CONFIG_UTIL.showAlert('签到成功!');
            },()=>{
                API_CONFIG_UTIL.showAlert('签到失败!');
            })
        }

        fetchData();

    });


text:
package org.apache.hadoop.hive.ql.exec.vector;

import java.util.Arrays;

import org.junit.Test;
import static org.junit.Assert.*;

public class TestBytesColumnVector {
  @Test
  public void testSmallBufferReuse() {
    BytesColumnVector col = new BytesColumnVector();
    int smallWriteSize = 1024;
    int largeWriteSize = 1024 * 1024 * 2;

    int rowIdx = 0;
    int bytesWrittenToBytes1 = 0;
    col.reset();

    // Initial write (small value)
    byte[] bytes1 = writeToBytesColumnVector(rowIdx, col, smallWriteSize, (byte) 1);
    bytesWrittenToBytes1 += smallWriteSize;

    // Write a large value. This should use a different byte buffer
    rowIdx++;
    byte[] bytes2 = writeToBytesColumnVector(rowIdx, col, largeWriteSize, (byte) 2);
    assertFalse(bytes1 == bytes2);

    // Another small write. smallBuffer should be re-used for this write
    rowIdx++;
    byte[] bytes3 = writeToBytesColumnVector(rowIdx, col, smallWriteSize, (byte) 1);
    bytesWrittenToBytes1 += smallWriteSize;
    assertTrue(bytes1 == bytes3);

    // Write another large value. This should use a different byte buffer
    rowIdx++;
    byte[] bytes4 = writeToBytesColumnVector(rowIdx, col, largeWriteSize, (byte) 3);
    assertFalse(bytes1 == bytes4);
    assertFalse(bytes2 == bytes4);

    // Eventually enough small writes should result in another buffer getting created
    boolean gotNewBuffer = false;
    // Test is dependent on getting a new buffer within 1MB.
    // This may need to change as the implementation changes.
    for (int i = 0; i < 1024; ++i) {
      rowIdx++;
      byte[] currBytes = writeToBytesColumnVector(rowIdx, col, smallWriteSize, (byte) 1);
      if (currBytes == bytes1) {
        bytesWrittenToBytes1 += smallWriteSize;
      } else {
        gotNewBuffer = true;
        break;
      }
    }

    assertTrue(gotNewBuffer);

    // All small writes to the first buffer should be in contiguous memory
    for (int i = 0; i < bytesWrittenToBytes1; ++i) {
      assertEquals((byte) 1, bytes1[i]);
    }
  }

  // Write a value to the column vector, and return back the byte buffer used.
  private static byte[] writeToBytesColumnVector(int rowIdx, BytesColumnVector col, int writeSize, byte val) {
    col.ensureValPreallocated(writeSize);
    byte[] bytes = col.getValPreallocatedBytes();
    int startIdx = col.getValPreallocatedStart();
    Arrays.fill(bytes, startIdx, startIdx + writeSize, val);
    col.setValPreallocated(rowIdx, writeSize);
    return bytes;
  }
}


text:
package $packageName;

import io.vertx.core.AbstractVerticle;

/**
 * Main application class.
 */
public class MainVerticle extends AbstractVerticle {

    /**
     * Called when verticle is deployed.
     */
    public void start() {
    }

    /**
     * Optional - called when verticle is undeployed.
     */
    public void stop() {
    }
}


text:
class Shader_Pair;
class CrossDeviceShaderPair
{
public:
	CrossDeviceShaderPair(const std::vector<std::string>& Names, const std::vector<EShaderType::Type>& StageList, const std::vector<ShaderProgramBase::Shader_Define>& Defines = std::vector<ShaderProgramBase::Shader_Define>());

	void InitOnDevice(int DeviceIndex);

	Shader_Pair* Get(DeviceContext* context = nullptr);
	Shader_Pair * Get(RHICommandList * list);
private:
	Shader_Pair* Pairs[MAX_GPU_DEVICE_COUNT];
	std::vector<std::string> Names;
	std::vector<EShaderType::Type> StageList;
	std::vector<ShaderProgramBase::Shader_Define> Defines;
};


text:
package credentials

func (oldCred *StsRoleNameOnEcsCredential) ToEcsRamRoleCredential() *EcsRamRoleCredential {
	return &EcsRamRoleCredential{
		RoleName: oldCred.RoleName,
	}
}

type EcsRamRoleCredential struct {
	RoleName string
}

func NewEcsRamRoleCredential(roleName string) *EcsRamRoleCredential {
	return &EcsRamRoleCredential{
		RoleName: roleName,
	}
}

// Deprecated: Use EcsRamRoleCredential in this package instead.
type StsRoleNameOnEcsCredential struct {
	RoleName string
}

// Deprecated: Use NewEcsRamRoleCredential in this package instead.
func NewStsRoleNameOnEcsCredential(roleName string) *StsRoleNameOnEcsCredential {
	return &StsRoleNameOnEcsCredential{
		RoleName: roleName,
	}
}