text:
#include <canbus/isotp.h>
#include <drivers/can.h>
#include <ztest.h>
#include <strings.h>
#include "random_data.h"

#define PCI_TYPE_POS      4
#define DATA_SIZE_SF      7
#define DATA_SIZE_CF      7
#define DATA_SIZE_SF_EXT  6
#define DATA_SIZE_FF      6
#define CAN_DL            8
#define DATA_SEND_LENGTH  272
#define SF_PCI_TYPE       0
#define SF_PCI_BYTE_1     ((SF_PCI_TYPE << PCI_TYPE_POS) | DATA_SIZE_SF)
#define SF_PCI_BYTE_2_EXT ((SF_PCI_TYPE << PCI_TYPE_POS) | DATA_SIZE_SF_EXT)
#define SF_PCI_BYTE_LEN_8 ((SF_PCI_TYPE << PCI_TYPE_POS) | (DATA_SIZE_SF + 1))
#define EXT_ADDR           5
#define FF_PCI_TYPE        1
#define FF_PCI_BYTE_1(dl)      ((FF_PCI_TYPE << PCI_TYPE_POS) | ((dl) >> 8))
#define FF_PCI_BYTE_2(dl)      ((dl) & 0xFF)
#define FC_PCI_TYPE        3
#define FC_PCI_CTS         0
#define FC_PCI_WAIT        1
#define FC_PCI_OVFLW       2
#define FC_PCI_BYTE_1(FS)  ((FC_PCI_TYPE << PCI_TYPE_POS) | (FS))
#define FC_PCI_BYTE_2(BS)  (BS)
#define FC_PCI_BYTE_3(ST_MIN) (ST_MIN)
#define CF_PCI_TYPE        2
#define CF_PCI_BYTE_1      (CF_PCI_TYPE << PCI_TYPE_POS)
#define STMIN_VAL_1        5
#define STMIN_VAL_2        50
#define STMIN_UPPER_TOLERANCE 5

#if defined(CONFIG_ISOTP_ENABLE_TX_PADDING) || \
				defined(CONFIG_ISOTP_ENABLE_TX_PADDING)
#define DATA_SIZE_FC       CAN_DL
#else
#define DATA_SIZE_FC       3
#endif

#define CEIL(A, B) (((A) + (B) - 1) / (B))

#define BS_TIMEOUT_UPPER_MS   1100
#define BS_TIMEOUT_LOWER_MS   1000

#if defined(CONFIG_CAN_LOOPBACK_DEV_NAME)
#define CAN_DEVICE_NAME CONFIG_CAN_LOOPBACK_DEV_NAME
#else
#define CAN_DEVICE_NAME DT_CHOSEN_ZEPHYR_CAN_PRIMARY_LABEL
#endif

/*
 * @addtogroup t_can
 * @{
 * @defgroup t_can_isotp test_can_isotp
 * @brief TestPurpose: verify correctness of the iso tp implementation
 * @details
 * - Test Steps
 *   -#
 * - Expected Results
 *   -#
 * @}
 */

struct frame_desired {
	uint8_t data[8];
	uint8_t length;
};

struct frame_desired des_frames[CEIL((DATA_SEND_LENGTH - DATA_SIZE_FF),
				      DATA_SIZE_CF)];

const struct isotp_fc_opts fc_opts = {
	.bs = 8,
	.stmin = 0
};
const struct isotp_fc_opts fc_opts_single = {
	.bs = 0,
	.stmin = 0
};
const struct isotp_msg_id rx_addr = {
	.std_id = 0x10,
	.id_type = CAN_STANDARD_IDENTIFIER,
	.use_ext_addr = 0
};
const struct isotp_msg_id tx_addr = {
	.std_id = 0x11,
	.id_type = CAN_STANDARD_IDENTIFIER,
	.use_ext_addr = 0
};

const struct isotp_msg_id rx_addr_ext = {
	.std_id = 0x10,
	.id_type = CAN_STANDARD_IDENTIFIER,
	.use_ext_addr = 1,
	.ext_addr = EXT_ADDR
};

const struct isotp_msg_id tx_addr_ext = {
	.std_id = 0x11,
	.id_type = CAN_STANDARD_IDENTIFIER,
	.use_ext_addr = 1,
	.ext_addr = EXT_ADDR
};

const struct isotp_msg_id rx_addr_fixed = {
	.ext_id = 0x18DA0201,
	.id_type = CAN_EXTENDED_IDENTIFIER,
	.use_ext_addr = 0,
	.use_fixed_addr = 1
};

const struct isotp_msg_id tx_addr_fixed = {
	.ext_id = 0x18DA0102,
	.id_type = CAN_EXTENDED_IDENTIFIER,
	.use_ext_addr = 0,
	.use_fixed_addr = 1
};

const struct device *can_dev;
struct isotp_recv_ctx recv_ctx;
struct isotp_send_ctx send_ctx;
uint8_t data_buf[128];
CAN_DEFINE_MSGQ(frame_msgq, 10);
struct k_sem send_compl_sem;

void send_complette_cb(int error_nr, void *arg)
{
	int expected_err_nr = (int) arg;

	zassert_equal(error_nr, expected_err_nr,
		      "Unexpected error nr. expect: %d, got %d",
		      expected_err_nr, error_nr);
	k_sem_give(&send_compl_sem);
}

static void print_hex(const uint8_t *ptr, size_t len)
{
	while (len--) {
		printk("%02x ", *ptr++);
	}
}

static int check_data(const uint8_t *frame, const uint8_t *desired, size_t length)
{
	int ret;

	ret = memcmp(frame, desired, length);
	if (ret) {
		printk("desired bytes:\n");
		print_hex(desired, length);
		printk("\nreceived (%d bytes):\n", length);
		print_hex(frame, length);
		printk("\n");
	}

	return ret;
}

static void send_sf(void)
{
	int ret;

	ret = isotp_send(&send_ctx, can_dev, random_data, DATA_SIZE_SF,
			 &rx_addr, &tx_addr, send_complette_cb, ISOTP_N_OK);
	zassert_equal(ret, 0, "Send returned %d", ret);
}

static void get_sf(struct isotp_recv_ctx *recv_ctx, size_t data_size)
{
	int ret;

	memset(data_buf, 0, sizeof(data_buf));
	ret = isotp_recv(recv_ctx, data_buf, sizeof(data_buf), K_MSEC(1000));
	zassert_equal(ret, data_size, "recv returned %d", ret);

	ret = check_data(data_buf, random_data, data_size);
	zassert_equal(ret, 0, "Data differ");
}

static void get_sf_ignore(struct isotp_recv_ctx *recv_ctx)
{
	int ret;

	ret = isotp_recv(recv_ctx, data_buf, sizeof(data_buf), K_MSEC(200));
	zassert_equal(ret, ISOTP_RECV_TIMEOUT, "recv returned %d", ret);
}

static void send_test_data(const uint8_t *data, size_t len)
{
	int ret;

	ret = isotp_send(&send_ctx, can_dev, data, len, &rx_addr, &tx_addr,
			 send_complette_cb, ISOTP_N_OK);
	zassert_equal(ret, 0, "Send returned %d", ret);
}

static void receive_test_data(struct isotp_recv_ctx *recv_ctx,
			      const uint8_t *data, size_t len, int32_t delay)
{
	size_t remaining_len = len;
	int ret, recv_len;
	const uint8_t *data_ptr = data;

	do {
		memset(data_buf, 0, sizeof(data_buf));
		recv_len = isotp_recv(recv_ctx, data_buf, sizeof(data_buf),
				      K_MSEC(1000));
		zassert_true(recv_len >= 0, "recv error: %d", recv_len);

		zassert_true(remaining_len >= recv_len,
			     "More data then expected");
		ret = check_data(data_buf, data_ptr, recv_len);
		zassert_equal(ret, 0, "Data differ");
		data_ptr += recv_len;
		remaining_len -= recv_len;

		if (delay) {
			k_msleep(delay);
		}
	} while (remaining_len);

	ret = isotp_recv(recv_ctx, data_buf, sizeof(data_buf), K_MSEC(50));
	zassert_equal(ret, ISOTP_RECV_TIMEOUT,
		      "Expected timeout but got %d", ret);
}

static void send_frame_series(struct frame_desired *frames, size_t length,
			      uint32_t id)
{
	int i, ret;
	struct zcan_frame frame = {
		.id_type = (id > 0x7FF) ? CAN_EXTENDED_IDENTIFIER :
			CAN_STANDARD_IDENTIFIER,
		.rtr = CAN_DATAFRAME,
		.id = id
	};
	struct frame_desired *desired = frames;

	for (i = 0; i < length; i++) {
		frame.dlc = desired->length;
		memcpy(frame.data, desired->data, desired->length);
		ret = can_send(can_dev, &frame, K_MSEC(500), NULL, NULL);
		zassert_equal(ret, CAN_TX_OK, "Sending msg %d failed.", i);
		desired++;
	}
}

static void check_frame_series(struct frame_desired *frames, size_t length,
			       struct k_msgq *msgq)
{
	int i, ret;
	struct zcan_frame frame;
	struct frame_desired *desired = frames;

	for (i = 0; i < length; i++) {
		ret = k_msgq_get(msgq, &frame, K_MSEC(500));
		zassert_equal(ret, 0, "Timeout waiting for msg nr %d. ret: %d",
			      i, ret);

#if !defined(CONFIG_ISOTP_REQUIRE_RX_PADDING) && \
					!defined(CONFIG_ISOTP_ENABLE_TX_PADDING)
		zassert_equal(frame.dlc, desired->length,
			      "DLC of frame nr %d differ. Desired: %d, Got: %d",
			      i, desired->length, frame.dlc);
#endif

#if !defined(CONFIG_ISOTP_ENABLE_TX_PADDING)
		ret = check_data(frame.data, desired->data, desired->length);
		zassert_equal(ret, 0, "Data differ");
#endif

		desired++;
	}
	ret = k_msgq_get(msgq, &frame, K_MSEC(200));
	zassert_equal(ret, -EAGAIN, "Expected timeout, but received %d", ret);
}

static int attach_msgq(uint32_t id, uint32_t mask)
{
	int filter_id;
	struct zcan_filter filter = {
		.id_type = (id > 0x7FF) ? CAN_EXTENDED_IDENTIFIER :
			CAN_STANDARD_IDENTIFIER,
		.rtr = CAN_DATAFRAME,
		.id = id,
		.rtr_mask = 1,
		.id_mask = mask
	};

	filter_id = can_attach_msgq(can_dev, &frame_msgq, &filter);
	zassert_not_equal(filter_id, CAN_NO_FREE_FILTER, "Filter full");
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	return filter_id;
}

static void prepare_cf_frames(struct frame_desired *frames, size_t frames_cnt,
			      const uint8_t *data, size_t data_len)
{
	int i;
	const uint8_t *data_ptr = data;
	size_t remaining_length = data_len;

	for (i = 0; i < frames_cnt && remaining_length; i++) {
		frames[i].data[0] = CF_PCI_BYTE_1 | ((i+1) & 0x0F);
		frames[i].length = CAN_DL;
		memcpy(&des_frames[i].data[1], data_ptr, DATA_SIZE_CF);

		if (remaining_length < DATA_SIZE_CF) {
#ifndef CONFIG_ISOTP_ENABLE_TX_PADDING
			frames[i].length = remaining_length + 1;
#endif
			remaining_length = 0;
		}

		remaining_length -= DATA_SIZE_CF;
		data_ptr += DATA_SIZE_CF;
	}
}

static void test_send_sf(void)
{
	int filter_id;
	struct frame_desired des_frame;

	des_frame.data[0] = SF_PCI_BYTE_1;
	memcpy(&des_frame.data[1], random_data, DATA_SIZE_SF);
	des_frame.length = DATA_SIZE_SF + 1;

	filter_id = attach_msgq(rx_addr.std_id, CAN_STD_ID_MASK);
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	send_sf();

	check_frame_series(&des_frame, 1, &frame_msgq);

	can_detach(can_dev, filter_id);
}

static void test_receive_sf(void)
{
	int ret;
	struct frame_desired single_frame;

	single_frame.data[0] = SF_PCI_BYTE_1;
	memcpy(&single_frame.data[1], random_data, DATA_SIZE_SF);
	single_frame.length  = DATA_SIZE_SF + 1;

	ret = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr,
			 &fc_opts_single, K_NO_WAIT);
	zassert_equal(ret, ISOTP_N_OK, "Binding failed [%d]", ret);

	send_frame_series(&single_frame, 1, rx_addr.std_id);

	get_sf(&recv_ctx, DATA_SIZE_SF);

	single_frame.data[0] = SF_PCI_BYTE_LEN_8;
	send_frame_series(&single_frame, 1, rx_addr.std_id);

#ifdef CONFIG_ISOTP_REQUIRE_RX_PADDING
	single_frame.data[0] = SF_PCI_BYTE_1;
	single_frame.length = 7;
	send_frame_series(&single_frame, 1, rx_addr.std_id);

	get_sf_ignore(&recv_ctx);
#endif

	isotp_unbind(&recv_ctx);
}

static void test_send_sf_ext(void)
{
	int filter_id, ret;
	struct frame_desired des_frame;

	des_frame.data[0] = rx_addr_ext.ext_addr;
	des_frame.data[1] = SF_PCI_BYTE_2_EXT;
	memcpy(&des_frame.data[2], random_data, DATA_SIZE_SF_EXT);
	des_frame.length = DATA_SIZE_SF_EXT + 2;

	filter_id = attach_msgq(rx_addr_ext.std_id, CAN_STD_ID_MASK);
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	ret = isotp_send(&send_ctx, can_dev, random_data, DATA_SIZE_SF_EXT,
			 &rx_addr_ext, &tx_addr_ext, send_complette_cb,
			  ISOTP_N_OK);
	zassert_equal(ret, 0, "Send returned %d", ret);

	check_frame_series(&des_frame, 1, &frame_msgq);

	can_detach(can_dev, filter_id);
}

static void test_receive_sf_ext(void)
{
	int ret;
	struct frame_desired single_frame;

	single_frame.data[0] = EXT_ADDR;
	single_frame.data[1] = SF_PCI_BYTE_2_EXT;
	memcpy(&single_frame.data[2], random_data, DATA_SIZE_SF_EXT);
	single_frame.length  = DATA_SIZE_SF_EXT + 2;

	ret = isotp_bind(&recv_ctx, can_dev, &rx_addr_ext, &tx_addr,
			 &fc_opts_single, K_NO_WAIT);
	zassert_equal(ret, ISOTP_N_OK, "Binding failed [%d]", ret);

	send_frame_series(&single_frame, 1, rx_addr.std_id);

	get_sf(&recv_ctx, DATA_SIZE_SF_EXT);

	single_frame.data[1] = SF_PCI_BYTE_1;
	send_frame_series(&single_frame, 1, rx_addr.std_id);

#ifdef CONFIG_ISOTP_REQUIRE_RX_PADDING
	single_frame.data[1] = SF_PCI_BYTE_2_EXT;
	single_frame.length = 7;
	send_frame_series(&single_frame, 1, rx_addr.std_id);

	get_sf_ignore(&recv_ctx);
#endif

	isotp_unbind(&recv_ctx);
}

static void test_send_sf_fixed(void)
{
	int filter_id, ret;
	struct frame_desired des_frame;

	des_frame.data[0] = SF_PCI_BYTE_1;
	memcpy(&des_frame.data[1], random_data, DATA_SIZE_SF);
	des_frame.length = DATA_SIZE_SF + 1;

	/* mask to allow any priority and source address (SA) */
	filter_id = attach_msgq(rx_addr_fixed.ext_id, 0x03FFFF00);
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	ret = isotp_send(&send_ctx, can_dev, random_data, DATA_SIZE_SF,
			 &rx_addr_fixed, &tx_addr_fixed, send_complette_cb,
			 ISOTP_N_OK);
	zassert_equal(ret, 0, "Send returned %d", ret);

	check_frame_series(&des_frame, 1, &frame_msgq);

	can_detach(can_dev, filter_id);
}

static void test_receive_sf_fixed(void)
{
	int ret;
	struct frame_desired single_frame;

	single_frame.data[0] = SF_PCI_BYTE_1;
	memcpy(&single_frame.data[1], random_data, DATA_SIZE_SF);
	single_frame.length  = DATA_SIZE_SF + 1;

	ret = isotp_bind(&recv_ctx, can_dev, &rx_addr_fixed, &tx_addr_fixed,
			 &fc_opts_single, K_NO_WAIT);
	zassert_equal(ret, ISOTP_N_OK, "Binding failed [%d]", ret);

	/* default source address */
	send_frame_series(&single_frame, 1, rx_addr_fixed.ext_id);
	get_sf(&recv_ctx, DATA_SIZE_SF);

	/* different source address */
	send_frame_series(&single_frame, 1, rx_addr_fixed.ext_id | 0xFF);
	get_sf(&recv_ctx, DATA_SIZE_SF);

	/* different priority */
	send_frame_series(&single_frame, 1, rx_addr_fixed.ext_id | (7U << 26));
	get_sf(&recv_ctx, DATA_SIZE_SF);

	/* different target address (should fail) */
	send_frame_series(&single_frame, 1, rx_addr_fixed.ext_id | 0xFF00);
	get_sf_ignore(&recv_ctx);

	isotp_unbind(&recv_ctx);
}

static void test_send_data(void)
{
	struct frame_desired fc_frame, ff_frame;
	const uint8_t *data_ptr = random_data;
	size_t remaining_length = DATA_SEND_LENGTH;
	int filter_id;

	ff_frame.data[0] = FF_PCI_BYTE_1(DATA_SEND_LENGTH);
	ff_frame.data[1] = FF_PCI_BYTE_2(DATA_SEND_LENGTH);
	memcpy(&ff_frame.data[2], data_ptr, DATA_SIZE_FF);
	ff_frame.length = CAN_DL;
	data_ptr += DATA_SIZE_FF;
	remaining_length -= DATA_SIZE_FF;

	fc_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_CTS);
	fc_frame.data[1] = FC_PCI_BYTE_2(0);
	fc_frame.data[2] = FC_PCI_BYTE_3(0);
	fc_frame.length = DATA_SIZE_FC;

	prepare_cf_frames(des_frames, ARRAY_SIZE(des_frames), data_ptr,
			  remaining_length);

	filter_id = attach_msgq(rx_addr.std_id, CAN_STD_ID_MASK);
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	send_test_data(random_data, DATA_SEND_LENGTH);

	check_frame_series(&ff_frame, 1, &frame_msgq);

	send_frame_series(&fc_frame, 1, tx_addr.std_id);

	check_frame_series(des_frames, ARRAY_SIZE(des_frames), &frame_msgq);

	can_detach(can_dev, filter_id);
}

static void test_send_data_blocks(void)
{
	const uint8_t *data_ptr = random_data;
	size_t remaining_length = DATA_SEND_LENGTH;
	struct frame_desired *data_frame_ptr = des_frames;
	int filter_id, ret;
	struct zcan_frame dummy_frame;
	struct frame_desired fc_frame, ff_frame;

	ff_frame.data[0] = FF_PCI_BYTE_1(DATA_SEND_LENGTH);
	ff_frame.data[1] = FF_PCI_BYTE_2(DATA_SEND_LENGTH);
	memcpy(&ff_frame.data[2], data_ptr, DATA_SIZE_FF);
	ff_frame.length = DATA_SIZE_FF + 2;
	data_ptr += DATA_SIZE_FF;
	remaining_length -= DATA_SIZE_FF;

	fc_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_CTS);
	fc_frame.data[1] = FC_PCI_BYTE_2(fc_opts.bs);
	fc_frame.data[2] = FC_PCI_BYTE_3(0);
	fc_frame.length = DATA_SIZE_FC;

	prepare_cf_frames(des_frames, ARRAY_SIZE(des_frames), data_ptr,
			  remaining_length);

	remaining_length = DATA_SEND_LENGTH;

	filter_id = attach_msgq(rx_addr.std_id, CAN_STD_ID_MASK);
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	send_test_data(random_data, DATA_SEND_LENGTH);

	check_frame_series(&ff_frame, 1, &frame_msgq);
	remaining_length -= DATA_SIZE_FF;

	send_frame_series(&fc_frame, 1, tx_addr.std_id);

	check_frame_series(data_frame_ptr, fc_opts.bs, &frame_msgq);
	data_frame_ptr += fc_opts.bs;
	remaining_length -= fc_opts.bs * DATA_SIZE_CF;
	ret = k_msgq_get(&frame_msgq, &dummy_frame, K_MSEC(50));
	zassert_equal(ret, -EAGAIN, "Expected timeout but got %d", ret);

	fc_frame.data[1] = FC_PCI_BYTE_2(2);
	send_frame_series(&fc_frame, 1, tx_addr.std_id);

	/* dynamic bs */
	check_frame_series(data_frame_ptr, 2, &frame_msgq);
	data_frame_ptr += 2;
	remaining_length -= 2  * DATA_SIZE_CF;
	ret = k_msgq_get(&frame_msgq, &dummy_frame, K_MSEC(50));
	zassert_equal(ret, -EAGAIN, "Expected timeout but got %d", ret);

	/* get the rest */
	fc_frame.data[1] = FC_PCI_BYTE_2(0);
	send_frame_series(&fc_frame, 1, tx_addr.std_id);

	check_frame_series(data_frame_ptr, CEIL(remaining_length, DATA_SIZE_CF),
			   &frame_msgq);
	ret = k_msgq_get(&frame_msgq, &dummy_frame, K_MSEC(50));
	zassert_equal(ret, -EAGAIN, "Expected timeout but got %d", ret);

	can_detach(can_dev, filter_id);
}

static void test_receive_data(void)
{
	const uint8_t *data_ptr = random_data;
	size_t remaining_length = DATA_SEND_LENGTH;
	int filter_id, ret;
	struct frame_desired fc_frame, ff_frame;

	ff_frame.data[0] = FF_PCI_BYTE_1(DATA_SEND_LENGTH);
	ff_frame.data[1] = FF_PCI_BYTE_2(DATA_SEND_LENGTH);
	memcpy(&ff_frame.data[2], data_ptr, DATA_SIZE_FF);
	ff_frame.length = CAN_DL;
	data_ptr += DATA_SIZE_FF;
	remaining_length -= DATA_SIZE_FF;

	fc_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_CTS);
	fc_frame.data[1] = FC_PCI_BYTE_2(fc_opts_single.bs);
	fc_frame.data[2] = FC_PCI_BYTE_3(fc_opts_single.stmin);
	fc_frame.length = DATA_SIZE_FC;

	prepare_cf_frames(des_frames, ARRAY_SIZE(des_frames), data_ptr,
			  remaining_length);

	filter_id = attach_msgq(tx_addr.std_id, CAN_STD_ID_MASK);

	ret = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr,
			 &fc_opts_single, K_NO_WAIT);
	zassert_equal(ret, ISOTP_N_OK, "Binding failed [%d]", ret);

	send_frame_series(&ff_frame, 1, rx_addr.std_id);

	check_frame_series(&fc_frame, 1, &frame_msgq);

	send_frame_series(des_frames, ARRAY_SIZE(des_frames), rx_addr.std_id);

	receive_test_data(&recv_ctx, random_data, DATA_SEND_LENGTH, 0);

	can_detach(can_dev, filter_id);
	isotp_unbind(&recv_ctx);
}

static void test_receive_data_blocks(void)
{
	const uint8_t *data_ptr = random_data;
	size_t remaining_length = DATA_SEND_LENGTH;
	struct frame_desired *data_frame_ptr = des_frames;
	int filter_id, ret;
	size_t remaining_frames;
	struct frame_desired fc_frame, ff_frame;

	struct zcan_frame dummy_frame;

	ff_frame.data[0] = FF_PCI_BYTE_1(DATA_SEND_LENGTH);
	ff_frame.data[1] = FF_PCI_BYTE_2(DATA_SEND_LENGTH);
	memcpy(&ff_frame.data[2], data_ptr, DATA_SIZE_FF);
	ff_frame.length = DATA_SIZE_FF + 2;
	data_ptr += DATA_SIZE_FF;
	remaining_length -= DATA_SIZE_FF;

	fc_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_CTS);
	fc_frame.data[1] = FC_PCI_BYTE_2(fc_opts.bs);
	fc_frame.data[2] = FC_PCI_BYTE_3(fc_opts.stmin);
	fc_frame.length = DATA_SIZE_FC;

	prepare_cf_frames(des_frames, ARRAY_SIZE(des_frames), data_ptr,
			  remaining_length);

	remaining_frames = CEIL(remaining_length, DATA_SIZE_CF);

	filter_id = attach_msgq(tx_addr.std_id, CAN_STD_ID_MASK);
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	ret = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr,
			 &fc_opts, K_NO_WAIT);
	zassert_equal(ret, ISOTP_N_OK, "Binding failed [%d]", ret);

	send_frame_series(&ff_frame, 1, rx_addr.std_id);

	while (remaining_frames) {
		check_frame_series(&fc_frame, 1, &frame_msgq);

		if (remaining_frames >= fc_opts.bs) {
			send_frame_series(data_frame_ptr, fc_opts.bs,
					  rx_addr.std_id);
			data_frame_ptr += fc_opts.bs;
			remaining_frames -= fc_opts.bs;
		} else {
			send_frame_series(data_frame_ptr, remaining_frames,
					  rx_addr.std_id);
			data_frame_ptr += remaining_frames;
			remaining_frames = 0;
		}
	}

	ret = k_msgq_get(&frame_msgq, &dummy_frame, K_MSEC(50));
	zassert_equal(ret, -EAGAIN, "Expected timeout but got %d", ret);

	receive_test_data(&recv_ctx, random_data, DATA_SEND_LENGTH, 0);

	can_detach(can_dev, filter_id);
	isotp_unbind(&recv_ctx);
}

static void test_send_timeouts(void)
{
	int ret;
	uint32_t start_time, time_diff;
	struct frame_desired fc_cts_frame;

	fc_cts_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_CTS);
	fc_cts_frame.data[1] = FC_PCI_BYTE_2(fc_opts.bs);
	fc_cts_frame.data[2] = FC_PCI_BYTE_3(0);
	fc_cts_frame.length = DATA_SIZE_FC;

	/* Test timeout for first FC*/
	start_time = k_uptime_get_32();
	ret = isotp_send(&send_ctx, can_dev, random_data, sizeof(random_data),
			 &tx_addr, &rx_addr, NULL, NULL);
	time_diff = k_uptime_get_32() - start_time;
	zassert_equal(ret, ISOTP_N_TIMEOUT_BS, "Expected timeout but got %d",
		      ret);
	zassert_true(time_diff <= BS_TIMEOUT_UPPER_MS,
		     "Timeout too late (%dms)",  time_diff);
	zassert_true(time_diff >= BS_TIMEOUT_LOWER_MS,
		     "Timeout too early (%dms)", time_diff);

	/* Test timeout for consecutive FC frames */
	k_sem_reset(&send_compl_sem);
	ret = isotp_send(&send_ctx, can_dev, random_data, sizeof(random_data),
			 &tx_addr, &rx_addr, send_complette_cb,
			 (void *)ISOTP_N_TIMEOUT_BS);
	zassert_equal(ret, ISOTP_N_OK, "Send returned %d", ret);

	send_frame_series(&fc_cts_frame, 1, rx_addr.std_id);

	start_time = k_uptime_get_32();
	ret = k_sem_take(&send_compl_sem, K_MSEC(BS_TIMEOUT_UPPER_MS));
	zassert_equal(ret, 0, "Timeout too late");

	time_diff = k_uptime_get_32() - start_time;
	zassert_true(time_diff >= BS_TIMEOUT_LOWER_MS,
		     "Timeout too early (%dms)", time_diff);

	/* Test timeout reset with WAIT frame */
	k_sem_reset(&send_compl_sem);
	ret = isotp_send(&send_ctx, can_dev, random_data, sizeof(random_data),
			 &tx_addr, &rx_addr, send_complette_cb,
			 (void *)ISOTP_N_TIMEOUT_BS);
	zassert_equal(ret, ISOTP_N_OK, "Send returned %d", ret);

	ret = k_sem_take(&send_compl_sem, K_MSEC(800));
	zassert_equal(ret, -EAGAIN, "Timeout too early");

	fc_cts_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_CTS);
	send_frame_series(&fc_cts_frame, 1, rx_addr.std_id);

	start_time = k_uptime_get_32();
	ret = k_sem_take(&send_compl_sem, K_MSEC(BS_TIMEOUT_UPPER_MS));
	zassert_equal(ret, 0, "Timeout too late");
	time_diff = k_uptime_get_32() - start_time;
	zassert_true(time_diff >= BS_TIMEOUT_LOWER_MS,
		     "Timeout too early (%dms)", time_diff);
}

static void test_receive_timeouts(void)
{
	int ret;
	uint32_t start_time, time_diff;
	struct frame_desired ff_frame;

	ff_frame.data[0] = FF_PCI_BYTE_1(DATA_SEND_LENGTH);
	ff_frame.data[1] = FF_PCI_BYTE_2(DATA_SEND_LENGTH);
	memcpy(&ff_frame.data[2], random_data, DATA_SIZE_FF);
	ff_frame.length = DATA_SIZE_FF + 2;

	ret = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr,
			 &fc_opts, K_NO_WAIT);
	zassert_equal(ret, ISOTP_N_OK, "Binding failed [%d]", ret);

	send_frame_series(&ff_frame, 1, rx_addr.std_id);
	start_time = k_uptime_get_32();

	ret = isotp_recv(&recv_ctx, data_buf, sizeof(data_buf), K_FOREVER);
	zassert_equal(ret, DATA_SIZE_FF,
		      "Expected FF data length but got %d", ret);
	ret = isotp_recv(&recv_ctx, data_buf, sizeof(data_buf), K_FOREVER);
	zassert_equal(ret, ISOTP_N_TIMEOUT_CR,
		      "Expected timeout but got %d", ret);

	time_diff = k_uptime_get_32() - start_time;
	zassert_true(time_diff >= BS_TIMEOUT_LOWER_MS,
		     "Timeout too early (%dms)", time_diff);
	zassert_true(time_diff <= BS_TIMEOUT_UPPER_MS,
		     "Timeout too slow (%dms)", time_diff);

	isotp_unbind(&recv_ctx);
}

static void test_stmin(void)
{
	int filter_id, ret;
	struct frame_desired fc_frame, ff_frame;
	struct zcan_frame raw_frame;
	uint32_t start_time, time_diff;

	ff_frame.data[0] = FF_PCI_BYTE_1(DATA_SIZE_FF + DATA_SIZE_CF * 4);
	ff_frame.data[1] = FF_PCI_BYTE_2(DATA_SIZE_FF + DATA_SIZE_CF * 4);
	memcpy(&ff_frame.data[2], random_data, DATA_SIZE_FF);
	ff_frame.length = DATA_SIZE_FF + 2;

	fc_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_CTS);
	fc_frame.data[1] = FC_PCI_BYTE_2(2);
	fc_frame.data[2] = FC_PCI_BYTE_3(STMIN_VAL_1);
	fc_frame.length = DATA_SIZE_FC;

	filter_id = attach_msgq(rx_addr.std_id, CAN_STD_ID_MASK);
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	send_test_data(random_data, DATA_SIZE_FF + DATA_SIZE_CF * 4);

	check_frame_series(&ff_frame, 1, &frame_msgq);

	send_frame_series(&fc_frame, 1, tx_addr.std_id);

	ret = k_msgq_get(&frame_msgq, &raw_frame, K_MSEC(100));
	zassert_equal(ret, 0, "Expected to get a message. [%d]", ret);

	start_time = k_uptime_get_32();
	ret = k_msgq_get(&frame_msgq, &raw_frame,
			 K_MSEC(STMIN_VAL_1 + STMIN_UPPER_TOLERANCE));
	time_diff = k_uptime_get_32() - start_time;
	zassert_equal(ret, 0, "Expected to get a message within %dms. [%d]",
		      STMIN_VAL_1 + STMIN_UPPER_TOLERANCE, ret);
	zassert_true(time_diff >= STMIN_VAL_1, "STmin too short (%dms)",
		     time_diff);

	fc_frame.data[2] = FC_PCI_BYTE_3(STMIN_VAL_2);
	send_frame_series(&fc_frame, 1, tx_addr.std_id);

	ret = k_msgq_get(&frame_msgq, &raw_frame, K_MSEC(100));
	zassert_equal(ret, 0, "Expected to get a message. [%d]", ret);

	start_time = k_uptime_get_32();
	ret = k_msgq_get(&frame_msgq, &raw_frame,
			 K_MSEC(STMIN_VAL_2 + STMIN_UPPER_TOLERANCE));
	time_diff = k_uptime_get_32() - start_time;
	zassert_equal(ret, 0, "Expected to get a message within %dms. [%d]",
		      STMIN_VAL_2 + STMIN_UPPER_TOLERANCE, ret);
	zassert_true(time_diff >= STMIN_VAL_2, "STmin too short (%dms)",
		     time_diff);

	can_detach(can_dev, filter_id);
}

void test_receiver_fc_errors(void)
{
	int ret, filter_id;
	struct frame_desired ff_frame, fc_frame;

	ff_frame.data[0] = FF_PCI_BYTE_1(DATA_SEND_LENGTH);
	ff_frame.data[1] = FF_PCI_BYTE_2(DATA_SEND_LENGTH);
	memcpy(&ff_frame.data[2], random_data, DATA_SIZE_FF);
	ff_frame.length = DATA_SIZE_FF + 2;

	fc_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_CTS);
	fc_frame.data[1] = FC_PCI_BYTE_2(fc_opts.bs);
	fc_frame.data[2] = FC_PCI_BYTE_3(fc_opts.stmin);
	fc_frame.length = DATA_SIZE_FC;

	filter_id = attach_msgq(tx_addr.std_id, CAN_STD_ID_MASK);
	zassert_true((filter_id >= 0), "Negative filter number [%d]",
		     filter_id);

	ret = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr,
			 &fc_opts, K_NO_WAIT);
	zassert_equal(ret, ISOTP_N_OK, "Binding failed [%d]", ret);

	/* wrong sequence number */
	send_frame_series(&ff_frame, 1, rx_addr.std_id);
	check_frame_series(&fc_frame, 1, &frame_msgq);
	prepare_cf_frames(des_frames, ARRAY_SIZE(des_frames),
			  random_data + DATA_SIZE_FF,
			  sizeof(random_data) - DATA_SIZE_FF);
	/* SN should be 2 but is set to 3 for this test */
	des_frames[1].data[0] = CF_PCI_BYTE_1 | (3 & 0x0F);
	send_frame_series(des_frames, fc_opts.bs, rx_addr.std_id);

	ret = isotp_recv(&recv_ctx, data_buf, sizeof(data_buf), K_MSEC(200));
	zassert_equal(ret, DATA_SIZE_FF,
		      "Expected FF data length but got %d", ret);
	ret = isotp_recv(&recv_ctx, data_buf, sizeof(data_buf), K_MSEC(200));
	zassert_equal(ret, ISOTP_N_WRONG_SN,
		      "Expected wrong SN but got %d", ret);

	can_detach(can_dev, filter_id);
	k_msgq_cleanup(&frame_msgq);
	isotp_unbind(&recv_ctx);
}

void test_sender_fc_errors(void)
{
	int ret, filter_id, i;
	struct frame_desired ff_frame, fc_frame;

	ff_frame.data[0] = FF_PCI_BYTE_1(DATA_SEND_LENGTH);
	ff_frame.data[1] = FF_PCI_BYTE_2(DATA_SEND_LENGTH);
	memcpy(&ff_frame.data[2], random_data, DATA_SIZE_FF);
	ff_frame.length = DATA_SIZE_FF + 2;

	filter_id = attach_msgq(tx_addr.std_id, CAN_STD_ID_MASK);

	/* invalid flow status */
	fc_frame.data[0] = FC_PCI_BYTE_1(3);
	fc_frame.data[1] = FC_PCI_BYTE_2(fc_opts.bs);
	fc_frame.data[2] = FC_PCI_BYTE_3(fc_opts.stmin);
	fc_frame.length = DATA_SIZE_FC;

	k_sem_reset(&send_compl_sem);
	ret = isotp_send(&send_ctx, can_dev, random_data, DATA_SEND_LENGTH,
			 &tx_addr, &rx_addr, send_complette_cb,
			 (void *)ISOTP_N_INVALID_FS);
	zassert_equal(ret, ISOTP_N_OK, "Send returned %d", ret);

	check_frame_series(&ff_frame, 1, &frame_msgq);
	send_frame_series(&fc_frame, 1, rx_addr.std_id);
	ret = k_sem_take(&send_compl_sem, K_MSEC(200));
	zassert_equal(ret, 0, "Send complete callback not called");

	/* buffer overflow */
	can_detach(can_dev, filter_id);
	ret = isotp_bind(&recv_ctx, can_dev, &tx_addr, &rx_addr,
			 &fc_opts_single, K_NO_WAIT);
	zassert_equal(ret, ISOTP_N_OK, "Binding failed [%d]", ret);

	ret = isotp_send(&send_ctx, can_dev, random_data, 5*1024,
			 &tx_addr, &rx_addr, NULL, NULL);
	zassert_equal(ret, ISOTP_N_BUFFER_OVERFLW,
		      "Expected overflow but got %d", ret);
	isotp_unbind(&recv_ctx);
	filter_id = attach_msgq(tx_addr.std_id, CAN_STD_ID_MASK);

	k_sem_reset(&send_compl_sem);
	ret = isotp_send(&send_ctx, can_dev, random_data, DATA_SEND_LENGTH,
			 &tx_addr, &rx_addr, send_complette_cb,
			 (void *)ISOTP_N_BUFFER_OVERFLW);

	check_frame_series(&ff_frame, 1, &frame_msgq);
	fc_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_OVFLW);
	send_frame_series(&fc_frame, 1, rx_addr.std_id);
	ret = k_sem_take(&send_compl_sem, K_MSEC(200));
	zassert_equal(ret, 0, "Send complete callback not called");

	/* wft overrun */
	k_sem_reset(&send_compl_sem);
	ret = isotp_send(&send_ctx, can_dev, random_data, DATA_SEND_LENGTH,
			 &tx_addr, &rx_addr, send_complette_cb,
			 (void *)ISOTP_N_WFT_OVRN);

	check_frame_series(&ff_frame, 1, &frame_msgq);
	fc_frame.data[0] = FC_PCI_BYTE_1(FC_PCI_WAIT);
	for (i = 0; i < CONFIG_ISOTP_WFTMAX + 1; i++) {
		send_frame_series(&fc_frame, 1, rx_addr.std_id);
	}

	ret = k_sem_take(&send_compl_sem, K_MSEC(200));
	zassert_equal(ret, 0, "Send complete callback not called");
	k_msgq_cleanup(&frame_msgq);
	can_detach(can_dev, filter_id);
}

void test_main(void)
{
	int ret;

	zassert_true(sizeof(random_data) >= sizeof(data_buf) * 2 + 10,
		     "Test data size to small");

	can_dev = device_get_binding(CAN_DEVICE_NAME);
	zassert_not_null(can_dev, "CAN device not not found");

	ret = can_set_mode(can_dev, CAN_LOOPBACK_MODE);
	zassert_equal(ret, 0, "Failed to set loopback mode [%d]", ret);

	k_sem_init(&send_compl_sem, 0, 1);

	ztest_test_suite(isotp_conformance,
			 ztest_unit_test(test_send_sf),
			 ztest_unit_test(test_receive_sf),
			 ztest_unit_test(test_send_sf_ext),
			 ztest_unit_test(test_receive_sf_ext),
			 ztest_unit_test(test_send_sf_fixed),
			 ztest_unit_test(test_receive_sf_fixed),
			 ztest_unit_test(test_send_data),
			 ztest_unit_test(test_send_data_blocks),
			 ztest_unit_test(test_receive_data),
			 ztest_unit_test(test_receive_data_blocks),
			 ztest_unit_test(test_send_timeouts),
			 ztest_unit_test(test_receive_timeouts),
			 ztest_unit_test(test_stmin),
			 ztest_unit_test(test_receiver_fc_errors),
			 ztest_unit_test(test_sender_fc_errors)
			 );
	ztest_run_test_suite(isotp_conformance);
}


text:
import unittest

import numpy

import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr

@testing.parameterize(*testing.product({
    'shape': [(3, 2), ()],
    'dtype': [numpy.float16, numpy.float32, numpy.float64],
    'x_min_max': [
        (-0.75, 1.53),
        (numpy.float32(-0.75), numpy.float32(1.53)),
        (-1, 2),
    ]
}))
class TestClip(unittest.TestCase):

    def setUp(self):
        self.x = numpy.random.uniform(-3, 3, self.shape).astype(self.dtype)
        # Avoid values around x_min and x_max for stability of numerical
        # gradient
        x_min, x_max = self.x_min_max
        x_min = float(x_min)
        x_max = float(x_max)
        eps = 0.01
        for ind in numpy.ndindex(self.x.shape):
            if x_min - eps < self.x[ind] < x_min + eps:
                self.x[ind] = -0.5
            elif x_max - eps < self.x[ind] < x_max + eps:
                self.x[ind] = 0.5
        self.gy = numpy.random.uniform(-1, 1, self.shape).astype(self.dtype)
        self.ggx = numpy.random.uniform(-1, 1, self.shape).astype(self.dtype)

    def check_forward(self, x_data):
        x_min, x_max = self.x_min_max
        x = chainer.Variable(x_data)
        y = functions.clip(x, x_min, x_max)
        self.assertEqual(y.data.dtype, self.dtype)

        y_expect = self.x.copy()
        for i in numpy.ndindex(self.x.shape):
            if self.x[i] < x_min:
                y_expect[i] = x_min
            elif self.x[i] > x_max:
                y_expect[i] = x_max

        testing.assert_allclose(y_expect, y.data)

    def test_forward_cpu(self):
        self.check_forward(self.x)

    @attr.gpu
    def test_forward_gpu(self):
        self.check_forward(cuda.to_gpu(self.x))

    def check_backward(self, x_data, y_grad):
        def f(x):
            x_min, x_max = self.x_min_max
            return functions.clip(x, x_min, x_max)

        gradient_check.check_backward(
            f, x_data, y_grad, dtype=numpy.float64)

    def test_backward_cpu(self):
        self.check_backward(self.x, self.gy)

    @attr.gpu
    def test_backward_gpu(self):
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))

    def check_double_backward(self, x_data, y_grad, gx_grad):
        def f(x):
            x_min, x_max = self.x_min_max
            return functions.clip(x, x_min, x_max)

        gradient_check.check_double_backward(
            f, x_data, y_grad, gx_grad, dtype=numpy.float64, atol=1e-3)

    def test_double_backward_cpu(self):
        self.check_double_backward(self.x, self.gy, self.ggx)

    @attr.gpu
    def test_double_backward_gpu(self):
        self.check_double_backward(
            cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx))

class TestClipInvalidInterval(unittest.TestCase):

    def setUp(self):
        self.x = numpy.random.uniform(-1, 1, (3, 2)).astype(numpy.float32)

    def test_invalid_interval(self):
        with self.assertRaises(ValueError):
            functions.clip(self.x, 1.0, -1.0)

@testing.parameterize(*testing.product({
    'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
class TestClipBorderGrad(unittest.TestCase):

    def setUp(self):
        self.x = numpy.arange(6, dtype=self.dtype)
        self.x_min = 1.0
        self.x_max = 4.0
        self.expected = numpy.asarray([0, 1, 1, 1, 1, 0], dtype=self.dtype)

    def check_border_grad(self, x, expected):
        x = chainer.Variable(x)
        y = functions.clip(x, self.x_min, self.x_max)
        l = functions.sum(y)
        l.backward()
        testing.assert_allclose(x.grad, expected, atol=0, rtol=0)

    def test_border_grad_cpu(self):
        self.check_border_grad(self.x, self.expected)

    @attr.gpu
    def test_border_grad_gpu(self):
        self.check_border_grad(cuda.to_gpu(self.x), cuda.to_gpu(self.expected))

testing.run_module(__name__, __file__)

redpajama_set_name: RedPajamaGithub


text:
package org.kuali.kpme.tklm.time.batch;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.kuali.kpme.core.api.assignment.Assignment;
import org.kuali.kpme.core.api.assignment.AssignmentDescriptionKey;
import org.kuali.kpme.core.api.calendar.Calendar;
import org.kuali.kpme.core.api.calendar.entry.CalendarEntry;
import org.kuali.kpme.core.api.principal.PrincipalHRAttributes;
import org.kuali.kpme.core.batch.BatchJob;
import org.kuali.kpme.core.service.HrServiceLocator;
import org.kuali.kpme.core.util.TKUtils;
import org.kuali.kpme.tklm.api.common.TkConstants;
import org.kuali.kpme.tklm.api.time.clocklog.ClockLog;
import org.kuali.kpme.tklm.common.BatchJobService;
import org.kuali.kpme.tklm.time.service.TkServiceLocator;
import org.kuali.kpme.tklm.time.workflow.TimesheetDocumentHeader;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.List;

public class EndPayPeriodJob extends BatchJob {

	private static final Logger LOG = Logger.getLogger(EndPayPeriodJob.class);

	public void execute(JobExecutionContext context) throws JobExecutionException {

		String batchUserPrincipalId = getBatchUserPrincipalId();
		if (batchUserPrincipalId != null) {
			JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

			String hrCalendarEntryId = jobDataMap.getString("hrCalendarEntryId");
			TkServiceLocator.getBatchJobService().updateStatus(context.getJobDetail(), BatchJobService.RUNNING_JOB_STATUS_CODE);

		    DateTime currentDateTime =  new DateTime();
			LOG.info("EndOfPayPeiodJob is running at " + currentDateTime.toString() + " for hrCalendarEntryId " + hrCalendarEntryId);

	        CalendarEntry calendarEntry = HrServiceLocator.getCalendarEntryService().getCalendarEntry(hrCalendarEntryId);
	        Calendar calendar = HrServiceLocator.getCalendarService().getCalendar(calendarEntry.getHrCalendarId());
	        //calendarEntry.setCalendarObj(calendar);

	    	String calendarName = calendarEntry.getCalendarName();
	    	DateTime scheduleDate = calendarEntry.getBatchEndPayPeriodFullDateTime();

	    	List<PrincipalHRAttributes> principalHRAttributes = HrServiceLocator.getPrincipalHRAttributeService().getActiveEmployeesForPayCalendar(calendarName, scheduleDate.toLocalDate());
            for (PrincipalHRAttributes principalHRAttribute : principalHRAttributes) {
	    		String pId = principalHRAttribute.getPrincipalId();

	    		List<Assignment> assignments = HrServiceLocator.getAssignmentService().getAllAssignmentsByCalEntryForTimeCalendar(pId, calendarEntry);
	    		for (Assignment assignment : assignments) {
	    			String groupKeyCode = assignment.getGroupKeyCode();
	    			String jobNumber = String.valueOf(assignment.getJobNumber());
	    			String workArea = String.valueOf(assignment.getWorkArea());
	    			String task = String.valueOf(assignment.getTask());

	    			ClockLog lastClockLog = TkServiceLocator.getClockLogService().getLastClockLog(groupKeyCode, pId, jobNumber, workArea, task, calendarEntry);
	    	    	if (lastClockLog != null && TkConstants.ON_THE_CLOCK_CODES.contains(lastClockLog.getClockAction())) {
	    	    		runEndPayPeriodJobForUser(calendarEntry, pId, lastClockLog, batchUserPrincipalId);
	    	    	}
	    		}
	    	}
        } else {
        	String principalName = getBatchUserPrincipalName();
        	TkServiceLocator.getBatchJobService().updateStatus(context.getJobDetail(), BatchJobService.CANCELLED_JOB_STATUS_CODE);
        	LOG.error("Could not run batch jobs due to missing batch user " + principalName);
        }
		TkServiceLocator.getBatchJobService().updateStatus(context.getJobDetail(), BatchJobService.SUCCEEDED_JOB_STATUS_CODE);
	}

	protected void runEndPayPeriodJobForUser(CalendarEntry calendarEntry, String principalId, ClockLog openClockLog, String batchUserPrincipalId) {
        LOG.debug("EndOfPayPeiodJob started for user " + principalId + " and clockLog " + openClockLog.getTkClockLogId());
		DateTime endPeriodDateTime = calendarEntry.getEndPeriodFullDateTime();

        // need to use the user's time zone and the system time zone to figure out the system time of endPeriodDatTime in the user's timezone
        DateTimeZone userTimezone = DateTimeZone.forID(HrServiceLocator.getTimezoneService().getUserTimezone(principalId));
		DateTimeZone systemTimeZone = TKUtils.getSystemDateTimeZone();
		// time to use to create the CO clock log
        DateTime coLogDateTime = TKUtils.convertTimeForDifferentTimeZone(endPeriodDateTime,systemTimeZone,userTimezone);

        CalendarEntry nextCalendarEntry = HrServiceLocator.getCalendarEntryService().getNextCalendarEntryByCalendarId(calendarEntry.getHrCalendarId(), calendarEntry);
        DateTime beginNextPeriodDateTime = nextCalendarEntry.getBeginPeriodFullDateTime();
        // time to use to create the CI clock log
        DateTime ciLogDateTime = TKUtils.convertTimeForDifferentTimeZone(beginNextPeriodDateTime,systemTimeZone,userTimezone);

        String ipAddress = openClockLog.getIpAddress();
	    TimesheetDocumentHeader timesheetDocumentHeader = TkServiceLocator.getTimesheetDocumentHeaderService().getDocumentHeader(principalId, calendarEntry.getBeginPeriodFullDateTime(), endPeriodDateTime);
	    if (timesheetDocumentHeader != null) {
	        AssignmentDescriptionKey assignmentKey = new AssignmentDescriptionKey(openClockLog.getGroupKeyCode(), openClockLog.getJobNumber(), openClockLog.getWorkArea(), openClockLog.getTask());
            Assignment assignment = HrServiceLocator.getAssignmentService().getAssignment(principalId, assignmentKey, coLogDateTime.toLocalDate());
	        ClockLog clockOutLog = TkServiceLocator.getClockLogService().processClockLog(principalId, timesheetDocumentHeader.getDocumentId(), coLogDateTime, assignment, calendarEntry, ipAddress,
	            		endPeriodDateTime.toLocalDate(), TkConstants.CLOCK_OUT, false, batchUserPrincipalId);

            TimesheetDocumentHeader nextTdh = TkServiceLocator.getTimesheetDocumentHeaderService()
            		.getDocumentHeader(principalId, nextCalendarEntry.getBeginPeriodFullDateTime(), nextCalendarEntry.getEndPeriodFullDateTime());
            //TimesheetDocument nextTimeDoc = null;
            //if(nextTdh != null) {
            //	nextTimeDoc = TkServiceLocator.getTimesheetService().getTimesheetDocument(nextTdh.getDocumentId());
            //}
            ClockLog clockInLog = TkServiceLocator.getClockLogService().processClockLog(principalId, nextTdh == null ? null : nextTdh.getDocumentId(), ciLogDateTime, assignment, nextCalendarEntry, ipAddress,
            		beginNextPeriodDateTime.toLocalDate(), TkConstants.CLOCK_IN, false, batchUserPrincipalId);

            // add 5 seconds to clock in log's timestamp so it will be found as the latest clock action
            ClockLog.Builder ciBuilder = ClockLog.Builder.create(clockInLog);
            ciBuilder.setCreateTime(clockInLog.getCreateTime().plusSeconds(5));
            clockInLog = TkServiceLocator.getClockLogService().saveClockLog(ciBuilder.build());
            LOG.debug("Clock Out log created is  " + clockOutLog.getTkClockLogId() + ",  Clock In Log created is " + clockInLog.getTkClockLogId());
	    }
        LOG.debug("EndOfPayPeiodJob is finished for user " + principalId + " and clockLog " + openClockLog.getTkClockLogId());
	}

}


text:
'use strict';

angular.
  module('settings').
  component('account', {
    templateUrl: 'settings/account/account.template.html',
    controller: ['Backend','$scope','$uibModal',function AccountController(Backend,$scope,$uibModal) {
      var self = this;
      Backend.getApi().then(function(api) {
      	api.accounts.getAccounts().then(function(response) {
      		self.accounts = response.data;
      	});
      });

      self.removeAccount = function(index) {
        Backend.getApi().then(function(api) {
          api.accounts.delete(self.accounts[index]).then(function() {
            self.accounts.splice(index,1);
          });
        });
        self.closeConfirmModal();
      }

      self.updateAccount = function(data,account) {
        Backend.getApi().then(function(api) {
          if(typeof account.id === 'undefined') {
            api.accounts.createAccount(data).then(function(response) {
              account.id = response.data.id;
            });
          } else {
            angular.extend(data,{id:account.id});
            return api.accounts.replace(data);
          }
        });
      }

      self.openConfirmModal = function(index) {
        $scope.index = index;
        self.modalInstance = $uibModal.open({
          animation: 'true',
          templateUrl: 'settings/account/confirmation-modal.template.html',
          scope: $scope,
          size: 'sm'
        });
      }

      self.closeConfirmModal = function() {
        if(self.modalInstance) {
          self.modalInstance.close();
        }
      }

      self.addAccount = function() {
        self.inserted = {
          number: '',
          name: ''
        }
        self.accounts.push(self.inserted);
      }

      self.cancelUpdate = function(index) {
        if(self.inserted == self.accounts[index]) {
          self.accounts.splice(index,1);
        }
      }

      self.checkEmpty = function(data) {
        if(!data) {
          return "can't be empty !";
        }
      }

      self.searchQueryClear = function() {
        self.searchQuery="";
      }
    }]
  });


text:
/**
 * Determines whether a given node is suitable for text matching.
 *
 * @internal
 */
export declare const isSuitableNodeForTextMatching: (node: Node) => boolean;
/**
 * @internal
 */
export declare type TextContent = {
    full: string;
    immediate: string[];
};
/**
 * Builds the text content of a node using some custom logic.
 *
 * @remarks
 * The primary reason this function exists is due to {@link ShadowRoot}s not having
 * text content.
 *
 * @internal
 */
export declare const createTextContent: (root: Node) => TextContent;
//# sourceMappingURL=TextContent.d.ts.map


text:
    @if(userCan('settings-manage'))
        @icon('settings'){{ trans('settings.settings') }}
        @icon('spanner'){{ trans('settings.maint') }}
    @endif
    @if(userCan('settings-manage') && userCan('users-manage'))
        @icon('open-book'){{ trans('settings.audit') }}
    @endif
    @if(userCan('users-manage'))
        @icon('users'){{ trans('settings.users') }}
    @endif
    @if(userCan('user-roles-manage'))
        @icon('lock-open'){{ trans('settings.roles') }}
    @endif
    @if(userCan('settings-manage'))
        @icon('webhooks'){{ trans('settings.webhooks') }}
    @endif


text:
Imports System.IO
Imports System.Runtime.InteropServices

Module Example
    <STAThread()> _
    Sub Main()

        Dim objApplication As SolidEdgeFramework.Application = Nothing
        Dim objPartDocument As SolidEdgePart.PartDocument = Nothing
        Dim objSketchs As SolidEdgePart.Sketchs = Nothing
        Dim objSketch As SolidEdgePart.Sketch = Nothing
        Dim objProfile As SolidEdgePart.Profile = Nothing
        Dim objModels As SolidEdgePart.Models = Nothing
        Dim objModel As SolidEdgePart.Model = Nothing
        Dim objSlots As SolidEdgePart.Slots = Nothing
        Dim objSlot As SolidEdgePart.Slot = Nothing

        Try
            OleMessageFilter.Register()

            objApplication = Marshal.GetActiveObject("SolidEdge.Application")
            objPartDocument = objApplication.ActiveDocument

            'set the modeling mode
            objPartDocument.ModelingMode = SolidEdgePart.ModelingModeConstants.seModelingModeOrdered

            objSketchs = objPartDocument.Sketches

            'get a sketch & profile
            objSketch = objSketchs.Item(1)
            objProfile = objSketch.Profile

            objModels = objPartDocument.Models
            objModel = objModels.Item(1)

            'get Slots collection
            objSlots = objModel.Slots

            'create a Slot
            objSlot = objSlots.Add(objProfile,
                                   SolidEdgePart.FeaturePropertyConstants.igRegularSlot,
                                   SolidEdgePart.FeaturePropertyConstants.igFormedEnd,
                                   0.005,
                                   0.0,
                                   0.0,
                                   SolidEdgePart.FeaturePropertyConstants.igFinite,
                                   SolidEdgePart.FeaturePropertyConstants.igLeft,
                                   0.5,
                                   SolidEdgePart.KeyPointExtentConstants.igTangentNormal,
                                   Nothing,
                                   SolidEdgePart.FeaturePropertyConstants.igNone,
                                   SolidEdgePart.FeaturePropertyConstants.igNone,
                                   0.0,
                                   SolidEdgePart.KeyPointExtentConstants.igTangentNormal,
                                   Nothing,
                                   Nothing,
                                   SolidEdgePart.OffsetSideConstants.seOffsetNone,
                                   0.0,
                                   Nothing,
                                   SolidEdgePart.OffsetSideConstants.seOffsetNone,
                                   0.0)

            'set some properties (edit) on the slot
            objSlot.SlotEndCondition = SolidEdgePart.FeaturePropertyConstants.igLancedEnd

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        Finally
            OleMessageFilter.Revoke()
        End Try
    End Sub
End Module


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<TITLE>About this document ...</TITLE>
<META NAME="description" CONTENT="About this document ...">
<META NAME="keywords" CONTENT="Events">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="Generator" CONTENT="LaTeX2HTML v99.2beta6">
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">

<LINK REL="STYLESHEET" HREF="Events.css">

<LINK REL="previous" HREF="Events.html">
<LINK REL="up" HREF="Events.html">

 Up: Events
 Previous: Events

About this document ...

This document was generated using the
LaTeX2<tt>HTML</tt> translator Version 99.2beta6 (1.42)

Copyright © 1993, 1994, 1995, 1996,
Nikos Drakos,
Computer Based Learning Unit, University of Leeds.

Copyright © 1997, 1998, 1999,
Ross Moore,
Mathematics Department, Macquarie University, Sydney.

The command line arguments were:

 latex2html <TT>bioinformatics.bib Component.bib e-commerce.bib Events.bib Services.bib trans.bib Unbundling.bib WF.bib XML.bib</TT>

The translation was initiated by Khalid Belhajjam on 2001-01-04

<ADDRESS>
Khalid Belhajjam
2001-01-04
</ADDRESS>


text:
"""The forked_daapd component."""
from homeassistant.const import Platform

from .const import DOMAIN, HASS_DATA_REMOVE_LISTENERS_KEY, HASS_DATA_UPDATER_KEY

PLATFORMS = [Platform.MEDIA_PLAYER]

async def async_setup_entry(hass, entry):
    """Set up forked-daapd from a config entry by forwarding to platform."""
    hass.config_entries.async_setup_platforms(entry, PLATFORMS)
    return True

async def async_unload_entry(hass, entry):
    """Remove forked-daapd component."""
    status = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if status and hass.data.get(DOMAIN) and hass.data[DOMAIN].get(entry.entry_id):
        hass.data[DOMAIN][entry.entry_id][
            HASS_DATA_UPDATER_KEY
        ].websocket_handler.cancel()
        for remove_listener in hass.data[DOMAIN][entry.entry_id][
            HASS_DATA_REMOVE_LISTENERS_KEY
        ]:
            remove_listener()
        del hass.data[DOMAIN][entry.entry_id]
        if not hass.data[DOMAIN]:
            del hass.data[DOMAIN]
    return status


text:
require 'rails_helper'

RSpec.describe TextsController, :type => :controller do

end


text:
package jef.tools.unrar;

/**
 * the multipart volumn change event calback
 * @author Joker
 */
public interface VolumeChangeCallBack {
	public static final int RAR_VOL_ASK=0;
	public static final int RAR_VOL_NOTIFY=1;

	/**
	 * you should check the RarVolCallBackType,if it is {@link RarVolCallBackType#RAR_VOL_NOTIFY }
	 * you should return NULL for not change the next volumn name.otherwise if it is
	 * {@link RarVolCallBackType#RAR_VOL_ASK } ,you should return the next volumn name or hold on
	 * the thread untill the next default volumn is present
	 * @param type callback type
	 * @param volename default Required volume
	 * @return next volumn name
	 */
	VolumnChangeCallbackResult invoke(int type,String volename);
}


text:
module Roadcrew
  module ControllerHelpers
    extend ActiveSupport::Concern

    SESSION_AUTH_KEY = 'roadcrew:auth'

    included do
      rescue_from Roadcrew::NotAuthenticatedError do
        not_authenticated
      end

      helper_method :roadcrew_admin?
    end

    private
      def roadcrew_auth
        session[SESSION_AUTH_KEY]
      end

      def roadcrew_admin?
        !!roadcrew_auth
      end

      def authenticate_admin_by_roadcrew!
        Roadcrew::Authenticator.authenticate!(roadcrew_auth)
      end

      def login(credentials)
        Roadcrew::Authenticator.login!(credentials) do |auth|
          session[SESSION_AUTH_KEY] = auth if auth
        end
      end

      def logout
        Roadcrew::Authenticator.logout(roadcrew_auth)
        not_authenticated
      end

      def not_authenticated
        session.delete(SESSION_AUTH_KEY)
        redirect_to roadcrew.login_path
      end
  end
end