text:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <fs.h>
#include <nffs/queue.h>
#include <nffs/nffs.h>
#include <nffs/os.h>
#include <flash.h>
#include <ztest_assert.h>
#include "nffs_test_utils.h"

/*
 * This should fit the largest area used in test (128K).
 */
#define AREA_BUF_MAX_SIZE (128 * 1024)
static u8_t area_buf[AREA_BUF_MAX_SIZE];

#define NFFS_TEST_BUF_SIZE (24 * 1024)
u8_t nffs_test_buf[NFFS_TEST_BUF_SIZE];

void nffs_test_util_overwrite_data(u8_t *data, u32_t data_len,
				   u32_t addr)
{
	struct device *dev;
	struct flash_pages_info info;
	off_t off;

	dev = device_get_binding(CONFIG_FS_NFFS_FLASH_DEV_NAME);
	flash_get_page_info_by_offs(dev, addr, &info);

	nffs_os_flash_read(0, info.start_offset, area_buf, info.size);

	/*
	 * To make this simpler, assume we always overwrite within sector
	 *  boundary (which is the case here).
	 */
	off = addr - info.start_offset;
	memcpy(&area_buf[off], data, data_len);

	nffs_os_flash_erase(0, info.start_offset, info.size);
	nffs_os_flash_write(0, info.start_offset, area_buf, info.size);
}

void nffs_test_util_assert_ent_name(struct fs_dirent *fs_dirent,
				    const char *expected_name)
{
	zassert_equal(strcmp(fs_dirent->name, expected_name), 0, NULL);
}

void nffs_test_util_assert_file_len(struct nffs_file *file, u32_t expected)
{
	u32_t len;
	int rc;

	rc = nffs_inode_data_len(file->nf_inode_entry, &len);
	zassert_equal(rc, 0, NULL);
	zassert_equal(len, expected, NULL);
}

void nffs_test_util_assert_cache_is_sane(const char *filename)
{
	struct nffs_cache_inode *cache_inode;
	struct nffs_cache_block *cache_block;
	struct nffs_file *file;
	struct fs_file_t fs_file;
	u32_t cache_start;
	u32_t cache_end;
	u32_t block_end;
	int rc;

	rc = fs_open(&fs_file, filename);
	zassert_equal(rc, 0, NULL);

	file = fs_file.filep;
	rc = nffs_cache_inode_ensure(&cache_inode, file->nf_inode_entry);
	zassert_equal(rc, 0, NULL);

	nffs_cache_inode_range(cache_inode, &cache_start, &cache_end);

	if (TAILQ_EMPTY(&cache_inode->nci_block_list)) {
		zassert_equal(cache_start, 0, NULL);
		zassert_equal(cache_end, 0, NULL);
	} else {
		block_end = 0;  /* Pacify gcc. */
		TAILQ_FOREACH(cache_block, &cache_inode->nci_block_list,
			      ncb_link) {
			if (cache_block ==
				TAILQ_FIRST(&cache_inode->nci_block_list)) {
				zassert_equal(cache_block->ncb_file_offset,
						cache_start, NULL);
			} else {
				/* Ensure no gap between this block and its
				 * predecessor.
				 */
				zassert_equal(cache_block->ncb_file_offset,
						block_end, NULL);
			}

			block_end = cache_block->ncb_file_offset +
					cache_block->ncb_block.nb_data_len;
			if (cache_block ==
				TAILQ_LAST(&cache_inode->nci_block_list,
					nffs_cache_block_list)) {
				zassert_equal(block_end, cache_end, NULL);
			}
		}
	}

	rc = fs_close(&fs_file);
	zassert_equal(rc, 0, NULL);
}

void
nffs_test_util_assert_contents(const char *filename, const char *contents,
			       int contents_len)
{
	struct fs_file_t file;
	u32_t bytes_read;
	void *buf;
	int rc;

	rc = fs_open(&file, filename);
	zassert_equal(rc, 0, NULL);

	zassert_true(contents_len <= AREA_BUF_MAX_SIZE, "contents too large");
	buf = area_buf;

	bytes_read = fs_read(&file, buf, contents_len);
	zassert_equal(bytes_read, contents_len, NULL);
	zassert_equal(memcmp(buf, contents, contents_len), 0, NULL);

	rc = fs_close(&file);
	zassert_equal(rc, 0, NULL);

	nffs_test_util_assert_cache_is_sane(filename);
}

int nffs_test_util_block_count(const char *filename)
{
	struct nffs_hash_entry *entry;
	struct nffs_block block;
	struct nffs_file *file;
	struct fs_file_t fs_file;
	int count;
	int rc;

	rc = fs_open(&fs_file, filename);
	zassert_equal(rc, 0, NULL);

	file = fs_file.filep;
	count = 0;
	entry = file->nf_inode_entry->nie_last_block_entry;
	while (entry != NULL) {
		count++;
		rc = nffs_block_from_hash_entry(&block, entry);
		zassert_equal(rc, 0, NULL);
		zassert_not_equal(block.nb_prev, entry, NULL);
		entry = block.nb_prev;
	}

	rc = fs_close(&fs_file);
	zassert_equal(rc, 0, NULL);

	return count;
}

void nffs_test_util_assert_block_count(const char *filename, int expected_count)
{
	int actual_count;

	actual_count = nffs_test_util_block_count(filename);
	zassert_equal(actual_count, expected_count, NULL);
}

void nffs_test_util_assert_cache_range(const char *filename,
				       u32_t expected_cache_start,
				       u32_t expected_cache_end)
{
	struct nffs_cache_inode *cache_inode;
	struct nffs_file *file;
	struct fs_file_t fs_file;
	u32_t cache_start;
	u32_t cache_end;
	int rc;

	rc = fs_open(&fs_file, filename);
	zassert_equal(rc, 0, NULL);

	file = fs_file.filep;
	rc = nffs_cache_inode_ensure(&cache_inode, file->nf_inode_entry);
	zassert_equal(rc, 0, NULL);

	nffs_cache_inode_range(cache_inode, &cache_start, &cache_end);
	zassert_equal(cache_start, expected_cache_start, NULL);
	zassert_equal(cache_end, expected_cache_end, NULL);

	rc = fs_close(&fs_file);
	zassert_equal(rc, 0, NULL);

	nffs_test_util_assert_cache_is_sane(filename);
}

void nffs_test_util_create_file_blocks(const char *filename,
				       const struct nffs_test_block_desc *blks,
				       int num_blocks)
{
	struct fs_file_t file;
	u32_t total_len;
	u32_t offset;
	char *buf;
	int num_writes;
	int rc;
	int i;

	/* We do not have 'truncate' flag in fs_open, so unlink here instead */
	fs_unlink(filename);

	rc = fs_open(&file, filename);
	zassert_equal(rc, 0, NULL);

	total_len = 0;
	if (num_blocks <= 0) {
		num_writes = 1;
	} else {
		num_writes = num_blocks;
	}
	for (i = 0; i < num_writes; i++) {
		rc = fs_write(&file, blks[i].data, blks[i].data_len);
		zassert_equal(rc, blks[i].data_len, NULL);

		total_len += blks[i].data_len;
	}

	rc = fs_close(&file);
	zassert_equal(rc, 0, NULL);

	zassert_true(total_len <= AREA_BUF_MAX_SIZE, "contents too large");
	buf = area_buf;

	offset = 0;
	for (i = 0; i < num_writes; i++) {
		memcpy(buf + offset, blks[i].data, blks[i].data_len);
		offset += blks[i].data_len;
	}
	zassert_equal(offset, total_len, NULL);

	nffs_test_util_assert_contents(filename, buf, total_len);
	if (num_blocks > 0) {
		nffs_test_util_assert_block_count(filename, num_blocks);
	}
}

void nffs_test_util_create_file(const char *filename, const char *contents,
				int contents_len)
{
	struct nffs_test_block_desc block;

	block.data = contents;
	block.data_len = contents_len;

	nffs_test_util_create_file_blocks(filename, &block, 0);
}

void nffs_test_util_append_file(const char *filename, const char *contents,
				int contents_len)
{
	struct fs_file_t file;
	int rc;

	rc = fs_open(&file, filename);
	zassert_equal(rc, 0, NULL);

	rc = fs_seek(&file, 0, FS_SEEK_END);
	zassert_equal(rc, 0, NULL);

	rc = fs_write(&file, contents, contents_len);
	zassert_equal(rc, contents_len, NULL);

	rc = fs_close(&file);
	zassert_equal(rc, 0, NULL);
}

void nffs_test_copy_area(const struct nffs_area_desc *from,
			 const struct nffs_area_desc *to)
{
	int rc;
	void *buf;

	zassert_equal(from->nad_length, to->nad_length, NULL);

	zassert_true(from->nad_length <= AREA_BUF_MAX_SIZE, "area too large");
	buf = area_buf;

	rc = nffs_os_flash_read(from->nad_flash_id, from->nad_offset, buf,
			from->nad_length);
	zassert_equal(rc, 0, NULL);

	rc = nffs_os_flash_erase(from->nad_flash_id, to->nad_offset,
			to->nad_length);
	zassert_equal(rc, 0, NULL);

	rc = nffs_os_flash_write(to->nad_flash_id, to->nad_offset, buf,
			to->nad_length);
	zassert_equal(rc, 0, NULL);
}

void nffs_test_util_create_subtree(const char *parent_path,
				   const struct nffs_test_file_desc *elem)
{
	char *path;
	int rc;
	int i;

	if (parent_path == NULL) {
		path = k_malloc(1);
		zassert_not_null(path, NULL);
		path[0] = '\0';
	} else {
		path = k_malloc(strlen(parent_path) +
				strlen(elem->filename) + 2);
		zassert_not_null(path, NULL);

		sprintf(path, "%s/%s", parent_path, elem->filename);
	}

	if (elem->is_dir) {
		if ((parent_path != NULL) &&
				(strlen(parent_path) > strlen(NFFS_MNTP))) {
			rc = fs_mkdir(path);
			zassert_equal(rc, 0, NULL);
		}

		if (elem->children != NULL) {
			for (i = 0; elem->children[i].filename != NULL; i++) {
				nffs_test_util_create_subtree(path,
						elem->children + i);
			}
		}
	} else {
		nffs_test_util_create_file(path, elem->contents,
				elem->contents_len);
	}

	k_free(path);
}

void nffs_test_util_create_tree(const struct nffs_test_file_desc *root_dir)
{
	nffs_test_util_create_subtree(NFFS_MNTP, root_dir);
}

#define NFFS_TEST_TOUCHED_ARR_SZ     (16 * 64)
/*#define NFFS_TEST_TOUCHED_ARR_SZ     (16 * 1024)*/
struct nffs_hash_entry
*nffs_test_touched_entries[NFFS_TEST_TOUCHED_ARR_SZ];
int nffs_test_num_touched_entries;

/* Recursively descend directory structure */
void nffs_test_assert_file(const struct nffs_test_file_desc *file,
			   struct nffs_inode_entry *inode_entry,
			   const char *path)
{
	const struct nffs_test_file_desc *child_file;
	struct nffs_inode inode;
	struct nffs_inode_entry *child_inode_entry;
	char *child_path, *abs_path;
	int child_filename_len;
	int path_len;
	int rc;

	/*
	 * track of hash entries that have been examined
	 */
	zassert_true(nffs_test_num_touched_entries < NFFS_TEST_TOUCHED_ARR_SZ,
		     NULL);
	nffs_test_touched_entries[nffs_test_num_touched_entries] =
			&inode_entry->nie_hash_entry;
	nffs_test_num_touched_entries++;

	path_len = strlen(path);

	rc = nffs_inode_from_entry(&inode, inode_entry);
	zassert_equal(rc, 0, NULL);

	/* recursively examine each child of directory */
	if (nffs_hash_id_is_dir(inode_entry->nie_hash_entry.nhe_id)) {
		for (child_file = file->children;
			child_file != NULL && child_file->filename != NULL;
			child_file++) {

			/*
			 * Construct full pathname for file
			 * Not null terminated
			 */
			child_filename_len = strlen(child_file->filename);
			child_path = k_malloc(path_len +
					child_filename_len + 2);
			zassert_not_null(child_path, NULL);
			memcpy(child_path, path, path_len);
			child_path[path_len] = '/';
			memcpy(child_path + path_len + 1, child_file->filename,
			       child_filename_len);
			child_path[path_len + 1 + child_filename_len] = '\0';

			/*
			 * Verify child inode can be found using full pathname
			 */
			rc = nffs_path_find_inode_entry(child_path,
					&child_inode_entry);
			zassert_equal(rc, 0, NULL);

			nffs_test_assert_file(child_file, child_inode_entry,
					      child_path);

			k_free(child_path);
		}
	} else {
		abs_path = k_malloc(strlen(NFFS_MNTP) + path_len + 2);
		sprintf(abs_path, "%s%s", NFFS_MNTP, path);
		nffs_test_util_assert_contents(abs_path, file->contents,
				file->contents_len);
		k_free(abs_path);
	}
}

void nffs_test_assert_branch_touched(struct nffs_inode_entry *inode_entry)
{
	struct nffs_inode_entry *child;
	int i;

	if (inode_entry == nffs_lost_found_dir) {
		return;
	}

	for (i = 0; i < nffs_test_num_touched_entries; i++) {
		if (nffs_test_touched_entries[i] ==
				&inode_entry->nie_hash_entry) {
			break;
		}
	}
	zassert_true(i < nffs_test_num_touched_entries, NULL);
	nffs_test_touched_entries[i] = NULL;

	if (nffs_hash_id_is_dir(inode_entry->nie_hash_entry.nhe_id)) {
		SLIST_FOREACH(child, &inode_entry->nie_child_list,
				nie_sibling_next) {
			nffs_test_assert_branch_touched(child);
		}
	}
}

void nffs_test_assert_child_inode_present(struct nffs_inode_entry *child)
{
	const struct nffs_inode_entry *inode_entry;
	const struct nffs_inode_entry *parent;
	struct nffs_inode inode;
	int rc;

	/*
	 * Successfully read inode data from flash
	 */
	rc = nffs_inode_from_entry(&inode, child);
	zassert_equal(rc, 0, NULL);

	/*
	 * Validate parent
	 */
	parent = inode.ni_parent;
	zassert_not_null(parent, NULL);
	zassert_true(nffs_hash_id_is_dir(parent->nie_hash_entry.nhe_id), NULL);

	/*
	 * Make sure inode is in parents child list
	 */
	SLIST_FOREACH(inode_entry, &parent->nie_child_list, nie_sibling_next) {
		if (inode_entry == child) {
			return;
		}
	}

	zassert_true(0, NULL);
}

void nffs_test_assert_block_present(struct nffs_hash_entry *block_entry)
{
	const struct nffs_inode_entry *inode_entry;
	struct nffs_hash_entry *cur;
	struct nffs_block block;
	int rc;

	/*
	 * Successfully read block data from flash
	 */
	rc = nffs_block_from_hash_entry(&block, block_entry);
	zassert_equal(rc, 0, NULL);

	/*
	 * Validate owning inode
	 */
	inode_entry = block.nb_inode_entry;
	zassert_not_null(inode_entry, NULL);
	zassert_true(nffs_hash_id_is_file(inode_entry->nie_hash_entry.nhe_id),
		     NULL);

	/*
	 * Validate that block is in owning inode's block chain
	 */
	cur = inode_entry->nie_last_block_entry;
	while (cur != NULL) {
		if (cur == block_entry) {
			return;
		}

		rc = nffs_block_from_hash_entry(&block, cur);
		zassert_equal(rc, 0, NULL);
		cur = block.nb_prev;
	}

	zassert_true(0, NULL);
}

/*
 * Recursively verify that the children of each directory are sorted
 * on the directory children linked list by filename length
 */
void nffs_test_assert_children_sorted(struct nffs_inode_entry *inode_entry)
{
	struct nffs_inode_entry *child_entry;
	struct nffs_inode_entry *prev_entry;
	struct nffs_inode child_inode;
	struct nffs_inode prev_inode;
	int cmp;
	int rc;

	prev_entry = NULL;
	SLIST_FOREACH(child_entry, &inode_entry->nie_child_list,
		      nie_sibling_next) {
		rc = nffs_inode_from_entry(&child_inode, child_entry);
		zassert_equal(rc, 0, NULL);

		if (prev_entry != NULL) {
			rc = nffs_inode_from_entry(&prev_inode, prev_entry);
			zassert_equal(rc, 0, NULL);

			rc = nffs_inode_filename_cmp_flash(&prev_inode,
					&child_inode, &cmp);
			zassert_equal(rc, 0, NULL);
			zassert_true(cmp < 0, NULL);
		}

		if (nffs_hash_id_is_dir(child_entry->nie_hash_entry.nhe_id)) {
			nffs_test_assert_children_sorted(child_entry);
		}

		prev_entry = child_entry;
	}
}

void nffs_test_assert_system_once(const struct nffs_test_file_desc *root_dir)
{
	struct nffs_inode_entry *inode_entry;
	struct nffs_hash_entry *entry;
	struct nffs_hash_entry *next;
	int i;

	nffs_test_num_touched_entries = 0;
	nffs_test_assert_file(root_dir, nffs_root_dir, "");
	nffs_test_assert_branch_touched(nffs_root_dir);

	/* Ensure no orphaned inodes or blocks. */
	NFFS_HASH_FOREACH(entry, i, next) {
		zassert_true(entry->nhe_flash_loc != NFFS_FLASH_LOC_NONE, NULL);
		if (nffs_hash_id_is_inode(entry->nhe_id)) {
			inode_entry = (void *)entry;
			zassert_equal(inode_entry->nie_refcnt, 1, NULL);
			if (entry->nhe_id == NFFS_ID_ROOT_DIR) {
				zassert_true(inode_entry == nffs_root_dir,
						NULL);
			} else {
				nffs_test_assert_child_inode_present(
								inode_entry);
			}
		} else {
			nffs_test_assert_block_present(entry);
		}
	}

	/* Ensure proper sorting. */
	nffs_test_assert_children_sorted(nffs_root_dir);
}

void nffs_test_assert_system(const struct nffs_test_file_desc *root_dir,
			     const struct nffs_area_desc *area_descs)
{
	int rc;

	/* Ensure files are as specified, and that there are no other files or
	 * orphaned inodes / blocks.
	 */
	nffs_test_assert_system_once(root_dir);

	/* Force a garbage collection cycle. */
	rc = nffs_gc(NULL);
	zassert_equal(rc, 0, NULL);

	/* Ensure file system is still as expected. */
	nffs_test_assert_system_once(root_dir);

	/* Clear cached data and restore from flash (i.e, simulate a reboot). */
	rc = nffs_misc_reset();
	zassert_equal(rc, 0, NULL);
	rc = nffs_restore_full(area_descs);
	zassert_equal(rc, 0, NULL);

	/* Ensure file system is still as expected. */
	nffs_test_assert_system_once(root_dir);
}

void nffs_test_assert_area_seqs(int seq1, int count1, int seq2, int count2)
{
	struct nffs_disk_area disk_area;
	int cur1;
	int cur2;
	int rc;
	int i;

	cur1 = 0;
	cur2 = 0;

	for (i = 0; i < nffs_num_areas; i++) {
		rc = nffs_flash_read(i, 0, &disk_area, sizeof(disk_area));
		zassert_equal(rc, 0, NULL);
		zassert_true(nffs_area_magic_is_set(&disk_area), NULL);
		zassert_equal(disk_area.nda_gc_seq, nffs_areas[i].na_gc_seq,
			      NULL);
		if (i == nffs_scratch_area_idx) {
			zassert_equal(disk_area.nda_id, NFFS_AREA_ID_NONE,
					NULL);
		}

		if (nffs_areas[i].na_gc_seq == seq1) {
			cur1++;
		} else if (nffs_areas[i].na_gc_seq == seq2) {
			cur2++;
		} else {
			zassert_true(0, NULL);
		}
	}

	zassert_equal(cur1, count1, NULL);
	zassert_equal(cur2, count2, NULL);
}


text:
package org.finra.jtaf.core.parallel;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.finra.jtaf.core.AutomationEngine;
import org.finra.jtaf.core.model.test.TestComponent;
import org.finra.jtaf.core.model.test.TestScript;
import org.finra.jtaf.core.model.test.TestSuite;
import org.finra.jtaf.core.model.test.digraph.DiNode;
import org.finra.jtaf.core.utilities.logging.MessageCollector;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ParallelScriptRunnerTest
{

    private TestScript testScript = null;
    private ParallelScriptRunner runner = null;

    @Test
    public void testCreateJunitName() throws Exception
    {
        Node testRoot = buildTestRoot("testscripts/ManipulateContextHelper.xml", "Manipulate");
        TestSuite testSuite = buildTestSuite(testRoot);

        List<TestComponent> componentList = testSuite.getComponentList();
        testScript = (TestScript) componentList.get(0);

        List<String> crs = new ArrayList<String>();
        crs.add("Test");
        testScript.setCRs(crs);
        runner = new ParallelScriptRunner(testScript);
        Assert.assertEquals(runner.getName(),
                "/dummy test suite/Manipulate CR=\"Test\" [ISSUE EXISTS]");

        testScript.setCRs(new ArrayList<String>());
        runner = new ParallelScriptRunner(testScript);
        Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate");

        testScript.setStatus("Pass");
        testScript.setCRs(null);
        runner = new ParallelScriptRunner(testScript);
        Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate STATUS=\"Pass\"");

        testScript.setStatus(null);
        testScript.setIssue("");
        runner = new ParallelScriptRunner(testScript);
        Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate");

        testScript.setStatus(null);
        testScript.setIssue(null);
        runner = new ParallelScriptRunner(testScript);
        Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate");

        testScript.setStatus(null);
        testScript.setIssue("Issue");
        runner = new ParallelScriptRunner(testScript);
        Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate [ISSUE EXISTS]");

    }

    @Test
    public void testRunJtafTestScript() throws Throwable
    {
        Node testRoot = buildTestRoot("testscripts/ParallelScriptRunner.xml", "Runner");
        TestSuite testSuite = buildTestSuite(testRoot);

        List<TestComponent> componentList = testSuite.getComponentList();
        testScript = (TestScript) componentList.get(0);
        if (AutomationEngine.getInstance().getTestDigraph().getVertex(testScript.getName()) != null)
        {
            AutomationEngine.getInstance().getTestDigraph().updateTestStatus(testScript.getName(),
                    "FAILED");

        }
        else
        {
            MyNode node = new MyNode(testScript);
            node.setTestStatus("FAILED");

            AutomationEngine.getInstance().getTestDigraph().addVertex(node);
        }

        runner = new ParallelScriptRunner(testScript);

        Throwable error = null;
        try
        {
            runner.runJtafTestScript();
        }
        catch (Throwable e)
        {
            error = e;
        }
        Assert.assertTrue(error.getClass().getSimpleName().equals("AssertionError"));
        Assert.assertTrue(error.getMessage().equals("One or more Dependent tests failed"));

        AutomationEngine.getInstance().getTestDigraph().updateTestStatus(testScript.getName(),
                "SUCCESS");
        try
        {
            runner.runJtafTestScript();
        }
        catch (Throwable e)
        {
            error = e;
        }
        Assert.assertTrue(error.getClass().getSimpleName().equals("AssertionFailedError"));

    }

    protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception
    {
        Node testRoot = null;
        InputStream inputStream = new FileInputStream(scriptFileName);
        Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
                inputStream).getDocumentElement();
        NodeList suiteNodeChildNodes = suiteNode.getChildNodes();
        for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++)
        {
            Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex);
            if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test")
                    && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent()
                            .equals(testOfInterestName))
            {
                testRoot = suiteNodeChildNode;
                break;
            }
        }
        return testRoot;
    }

    protected TestSuite buildTestSuite(Node testRoot) throws Exception
    {
        TestSuite testSuite = new TestSuite("dummy test suite");
        TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript(
                (Element) testRoot, new MessageCollector());
        testSuite.add(testScript);
        return testSuite;
    }

    private class MyNode extends DiNode
    {

        private String testName = ""; // This shouldnt change after being set
                                      // initially
        private String testStatus = "";
        private TestScript testScript = null; // This shouldnt change after
                                              // being set initially

        public MyNode(TestScript ts)
        {
            super(ts);
            this.testName = ts.getName();
            this.testScript = ts;
        }

        @Override
        public String getTestStatus()
        {
            return testStatus;
        }

        @Override
        protected void setTestStatus(String newTestStatus)
        {
            testStatus = newTestStatus;
        }

        @Override
        public String getTestName()
        {
            return testName;
        }

        @Override
        public TestScript getTestScript()
        {
            return testScript;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
layout: doc
title: Tagging - L'editor iD
permalink: /it/hot-tips/tagging/
lang: it
category: hot-tips
---

Tagging - iD editor
============

> Revisionato il 2019-06-28

- TOC
{:toc}

![tagging][]

Perchè sono necessari i tag?
-------------------

Senza un tag un oggetto non ha significato e le mappe non lo visualizzeranno. Il tag spiega al computer che tipo di oggetto rappresenta. Se trovi un oggetto senza tag, aggiungilo. Se un oggetto è taggato, esso avrà un colore, come il colore rosso per l'edificio taggato nell'immagine qui sopra.  **Se è bianco investiga e aggiungigli il tag appropriato, se è mancante**.

![tagged-building][]

L'autore del progetto nel Tasking Manager non conosce quale editor userà il mappatore, così le istruzioni posso spesso avere un commento simile a questo:

- *Gli edifici sono generalmente capanne rotonde e dovrebbero essere taggate come **Caratteristiche degli edifici / Edificio** in iD and **building=yes** in JOSM.*

Se tu vuoi verificare quale (o quali) tag è applicato ad un oggetto, cliccaci sopra, poi scorri sino al fondo del pannello laterale deile caratteristiche (tag) e guarda sotto a **Tutti i tag**

### Tag - una breve spiegazione ###

Se tu selezioni un oggetto e clicchi su **Tutti i tag** vedrai un'etichetta come questa

**building yes**

Questo è il tag più comune per gli edifici, ed è quello raccomandato quando si tracciano edifici in un task nel Tasking Manager.

Se conosci esattamente la funzione dell'edificio, allora puoi usare un tag più specifico, come:
  **building house**
  **building school**
o uno dei molti altri tag. Per informazioni più dettagliate sui tag per gli edifici guarda <https://wiki.openstreetmap.org/wiki/IT:Buildings>

Per ulteriori informazioni su come taggare le strade vedi la [sezione strade di questa parte di consigli utili su HOT](/en/hot-tips/highways/).

### Relazioni - come un edificio con all'interno una corte o un'isola in un fiume ###

Alcuni oggetti hanno i loro tag in una **Relazione**, non sull'oggetto stesso. Se vedi sullo schermo un riferimento ad una relazione e sei un novizio, il miglior consiglio è  'lasciala così com'è'.

Per maggiori informazioni sulle relazioni (**non è un argomento per i novizi di OSM**) guarda;

[LearnOSM - JOSM - Relazioni](/en/josm/josm-relations/) che spiega le relazioni ma usa un editor OSM differente, o
<https://wiki.openstreetmap.org/wiki/IT:Relation>

Vedi anche
---------

Per una lista quasi completa dei tag disponibili vedi <https://wiki.openstreetmap.org/wiki/IT:Map_Features>

[![video tutorial da un minuto]{: height="150px"}](https://www.youtube.com/playlist?list=PLb9506_-6FMHZ3nwn9heri3xjQKrSq1hN "Humanitarian OpenStreetMap Team - One minute Tutorial Videos")
*Sottotitoli in diverse lingue*

[tagging]:/images/hot-tips/tagging.gif
[keymon]:/images/hot-tips/keymon.png
[tagged-building]:/images/hot-tips/tagged-building.png
[video guide da un minuto]: /images/hot-tips/one-mnute-tutorial-videos.png "Humanitarian OpenStreetMap Team One-Minute Tutorial Videos"


text:
'use strict';

var Property = require('./Property'),
    AnimatedProperty = require('./AnimatedProperty');

function Polystar(data) {
    this.name = data.name;
    this.closed = true; // TODO ??

    this.starType = data.starType;
    this.points = data.points.length > 1 ? new AnimatedProperty(data.points) : new Property(data.points);
    this.innerRadius = data.innerRadius.length > 1 ? new AnimatedProperty(data.innerRadius) : new Property(data.innerRadius);
    this.outerRadius = data.outerRadius.length > 1 ? new AnimatedProperty(data.outerRadius) : new Property(data.outerRadius);

    //optinals
    if (data.position) this.position = data.position.length > 1 ? new AnimatedProperty(data.position) : new Property(data.position);
    if (data.rotation) this.rotation = data.rotation.length > 1 ? new AnimatedProperty(data.rotation) : new Property(data.rotation);
    if (data.innerRoundness) this.innerRoundness = data.innerRoundness.length > 1 ? new AnimatedProperty(data.innerRoundness) : new Property(data.innerRoundness);
    if (data.outerRoundness) this.outerRoundness = data.outerRoundness.length > 1 ? new AnimatedProperty(data.outerRoundness) : new Property(data.outerRoundness);
}

Polystar.prototype.draw = function (ctx, time) {

    var points = this.points.getValue(time),
        innerRadius = this.innerRadius.getValue(time),
        outerRadius = this.outerRadius.getValue(time),
        position = this.position ? this.position.getValue(time) : [0, 0],
        rotation = this.rotation ? this.rotation.getValue(time) : 0,
        innerRoundness = this.innerRoundness ? this.innerRoundness.getValue(time) : 0,
        outerRoundness = this.outerRoundness ? this.outerRoundness.getValue(time) : 0;

    rotation = this.deg2rad(rotation);
    var start = this.rotatePoint(0, 0, 0, 0 - outerRadius, rotation);

    ctx.save();
    ctx.beginPath();
    ctx.translate(position[0], position[1]);
    ctx.moveTo(start[0], start[1]);

    for (var i = 0; i < points; i++) {

        var pInner,
            pOuter,
            pOuter1Tangent,
            pOuter2Tangent,
            pInner1Tangent,
            pInner2Tangent,
            outerOffset,
            innerOffset,
            rot;

        rot = Math.PI / points * 2;

        pInner = this.rotatePoint(0, 0, 0, 0 - innerRadius, (rot * (i + 1) - rot / 2) + rotation);
        pOuter = this.rotatePoint(0, 0, 0, 0 - outerRadius, (rot * (i + 1)) + rotation);

        //FIxME
        if (!outerOffset) outerOffset = (start[0] + pInner[0]) * outerRoundness / 100 * .5522848;
        if (!innerOffset) innerOffset = (start[0] + pInner[0]) * innerRoundness / 100 * .5522848;

        pOuter1Tangent = this.rotatePoint(0, 0, outerOffset, 0 - outerRadius, (rot * i) + rotation);
        pInner1Tangent = this.rotatePoint(0, 0, innerOffset * -1, 0 - innerRadius, (rot * (i + 1) - rot / 2) + rotation);
        pInner2Tangent = this.rotatePoint(0, 0, innerOffset, 0 - innerRadius, (rot * (i + 1) - rot / 2) + rotation);
        pOuter2Tangent = this.rotatePoint(0, 0, outerOffset * -1, 0 - outerRadius, (rot * (i + 1)) + rotation);

        if (this.starType === 1) {
            //star
            ctx.bezierCurveTo(pOuter1Tangent[0], pOuter1Tangent[1], pInner1Tangent[0], pInner1Tangent[1], pInner[0], pInner[1]);
            ctx.bezierCurveTo(pInner2Tangent[0], pInner2Tangent[1], pOuter2Tangent[0], pOuter2Tangent[1], pOuter[0], pOuter[1]);
        } else {
            //polygon
            ctx.bezierCurveTo(pOuter1Tangent[0], pOuter1Tangent[1], pOuter2Tangent[0], pOuter2Tangent[1], pOuter[0], pOuter[1]);
        }

        //debug
        //ctx.fillStyle = "black";
        //ctx.fillRect(pInner[0], pInner[1], 5, 5);
        //ctx.fillRect(pOuter[0], pOuter[1], 5, 5);
        //ctx.fillStyle = "blue";
        //ctx.fillRect(pOuter1Tangent[0], pOuter1Tangent[1], 5, 5);
        //ctx.fillStyle = "red";
        //ctx.fillRect(pInner1Tangent[0], pInner1Tangent[1], 5, 5);
        //ctx.fillStyle = "green";
        //ctx.fillRect(pInner2Tangent[0], pInner2Tangent[1], 5, 5);
        //ctx.fillStyle = "brown";
        //ctx.fillRect(pOuter2Tangent[0], pOuter2Tangent[1], 5, 5);

    }

    ctx.restore();
};

Polystar.prototype.rotatePoint = function (cx, cy, x, y, radians) {
    var cos = Math.cos(radians),
        sin = Math.sin(radians),
        nx = (cos * (x - cx)) - (sin * (y - cy)) + cx,
        ny = (sin * (x - cx)) + (cos * (y - cy)) + cy;
    return [nx, ny];
};

Polystar.prototype.deg2rad = function (deg) {
    return deg * (Math.PI / 180);
};

Polystar.prototype.setKeyframes = function (time) {
    this.points.setKeyframes(time);
    this.innerRadius.setKeyframes(time);
    this.outerRadius.setKeyframes(time);
    if (this.position) this.position.setKeyframes(time);
    if (this.rotation) this.rotation.setKeyframes(time);
    if (this.innerRoundness) this.innerRoundness.setKeyframes(time);
    if (this.outerRoundness) this.outerRoundness.setKeyframes(time);
};

Polystar.prototype.reset = function (reversed) {
    this.points.reset(reversed);
    this.innerRadius.reset(reversed);
    this.outerRadius.reset(reversed);
    if (this.position) this.position.reset(reversed);
    if (this.rotation) this.rotation.reset(reversed);
    if (this.innerRoundness) this.innerRoundness.reset(reversed);
    if (this.outerRoundness) this.outerRoundness.reset(reversed);
};

module.exports = Polystar;


text:
In this analysis, the level of beta cells linearly and monotonically varies,
but beta cells regenerate; accounting for this would make the model more
biologically accurate. Models of type 2 diabetes often consider this and
could serve as a starting point for research [Dr.\ Jiaxu Li, University of
  Louisville, personal communication, December 6, 2013]. Additionally,
conducting further experiments in mice to obtain more data on the
oscillations would help fine-tune the model; note both the large error bars
in the original data (see introduction) and the parameter sensitivity of
this model \cite{Mahaffy2007}. Finally, the WKB method could be applied to
approximate when exactly the oscillations begin [Dr.\ Stephen Baer, Arizona
  State University, personal communication, January 3, 2014].


text:
using System;
using System.Reflection;

namespace Python.Runtime
{
    /// <summary>
    /// Implements a Python descriptor type that provides access to CLR fields.
    /// </summary>
    internal class FieldObject : ExtensionType
    {
        private FieldInfo info;

        public FieldObject(FieldInfo info)
        {
            this.info = info;
        }

        /// <summary>
        /// Descriptor __get__ implementation. This method returns the
        /// value of the field on the given object. The returned value
        /// is converted to an appropriately typed Python object.
        /// </summary>
        public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp)
        {
            var self = (FieldObject)GetManagedObject(ds);
            object result;

            if (self == null)
            {
                return IntPtr.Zero;
            }

            FieldInfo info = self.info;

            if (ob == IntPtr.Zero || ob == Runtime.PyNone)
            {
                if (!info.IsStatic)
                {
                    Exceptions.SetError(Exceptions.TypeError,
                        "instance attribute must be accessed through a class instance");
                    return IntPtr.Zero;
                }
                try
                {
                    result = info.GetValue(null);
                    return Converter.ToPython(result, info.FieldType);
                }
                catch (Exception e)
                {
                    Exceptions.SetError(Exceptions.TypeError, e.Message);
                    return IntPtr.Zero;
                }
            }

            try
            {
                var co = (CLRObject)GetManagedObject(ob);
                result = info.GetValue(co.inst);
                return Converter.ToPython(result, info.FieldType);
            }
            catch (Exception e)
            {
                Exceptions.SetError(Exceptions.TypeError, e.Message);
                return IntPtr.Zero;
            }
        }

        /// <summary>
        /// Descriptor __set__ implementation. This method sets the value of
        /// a field based on the given Python value. The Python value must be
        /// convertible to the type of the field.
        /// </summary>
        public new static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val)
        {
            var self = (FieldObject)GetManagedObject(ds);
            object newval;

            if (self == null)
            {
                return -1;
            }

            if (val == IntPtr.Zero)
            {
                Exceptions.SetError(Exceptions.TypeError, "cannot delete field");
                return -1;
            }

            FieldInfo info = self.info;

            if (info.IsLiteral || info.IsInitOnly)
            {
                Exceptions.SetError(Exceptions.TypeError, "field is read-only");
                return -1;
            }

            bool is_static = info.IsStatic;

            if (ob == IntPtr.Zero || ob == Runtime.PyNone)
            {
                if (!is_static)
                {
                    Exceptions.SetError(Exceptions.TypeError, "instance attribute must be set through a class instance");
                    return -1;
                }
            }

            if (!Converter.ToManaged(val, info.FieldType, out newval, true))
            {
                return -1;
            }

            try
            {
                if (!is_static)
                {
                    var co = (CLRObject)GetManagedObject(ob);
                    info.SetValue(co.inst, newval);
                }
                else
                {
                    info.SetValue(null, newval);
                }
                return 0;
            }
            catch (Exception e)
            {
                Exceptions.SetError(Exceptions.TypeError, e.Message);
                return -1;
            }
        }

        /// <summary>
        /// Descriptor __repr__ implementation.
        /// </summary>
        public static IntPtr tp_repr(IntPtr ob)
        {
            var self = (FieldObject)GetManagedObject(ob);
            return Runtime.PyString_FromString($"<field '{self.info.Name}'>");
        }
    }
}


text:
import requests

DEFAULT_RDAP_IP_URL = 'http://rdap.arin.net/registry/ip/{0}'
DEFAULT_RDAP_ENTITY_URL = 'http://rdap.arin.net/registry/entity/{0}'

def lookup(ip):
    r = requests.get(DEFAULT_RDAP_IP_URL.format(ip))
    return r.json()


text:
package trademark

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// ListNotaryInfos invokes the trademark.ListNotaryInfos API synchronously
// api document: https://help.aliyun.com/api/trademark/listnotaryinfos.html
func (client *Client) ListNotaryInfos(request *ListNotaryInfosRequest) (response *ListNotaryInfosResponse, err error) {
	response = CreateListNotaryInfosResponse()
	err = client.DoAction(request, response)
	return
}

// ListNotaryInfosWithChan invokes the trademark.ListNotaryInfos API asynchronously
// api document: https://help.aliyun.com/api/trademark/listnotaryinfos.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListNotaryInfosWithChan(request *ListNotaryInfosRequest) (<-chan *ListNotaryInfosResponse, <-chan error) {
	responseChan := make(chan *ListNotaryInfosResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.ListNotaryInfos(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// ListNotaryInfosWithCallback invokes the trademark.ListNotaryInfos API asynchronously
// api document: https://help.aliyun.com/api/trademark/listnotaryinfos.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListNotaryInfosWithCallback(request *ListNotaryInfosRequest, callback func(response *ListNotaryInfosResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *ListNotaryInfosResponse
		var err error
		defer close(result)
		response, err = client.ListNotaryInfos(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// ListNotaryInfosRequest is the request struct for api ListNotaryInfos
type ListNotaryInfosRequest struct {
	*requests.RpcRequest
	BizOrderNo string           `position:"Query" name:"BizOrderNo"`
	NotaryType requests.Integer `position:"Query" name:"NotaryType"`
	PageSize   requests.Integer `position:"Query" name:"PageSize"`
	PageNum    requests.Integer `position:"Query" name:"PageNum"`
	Token      string           `position:"Query" name:"Token"`
}

// ListNotaryInfosResponse is the response struct for api ListNotaryInfos
type ListNotaryInfosResponse struct {
	*responses.BaseResponse
	RequestId      string                `json:"RequestId" xml:"RequestId"`
	TotalItemNum   int                   `json:"TotalItemNum" xml:"TotalItemNum"`
	CurrentPageNum int                   `json:"CurrentPageNum" xml:"CurrentPageNum"`
	PageSize       int                   `json:"PageSize" xml:"PageSize"`
	TotalPageNum   int                   `json:"TotalPageNum" xml:"TotalPageNum"`
	PrePage        bool                  `json:"PrePage" xml:"PrePage"`
	NextPage       bool                  `json:"NextPage" xml:"NextPage"`
	Success        bool                  `json:"Success" xml:"Success"`
	ErrorMsg       string                `json:"ErrorMsg" xml:"ErrorMsg"`
	ErrorCode      string                `json:"ErrorCode" xml:"ErrorCode"`
	Data           DataInListNotaryInfos `json:"Data" xml:"Data"`
}

// CreateListNotaryInfosRequest creates a request to invoke ListNotaryInfos API
func CreateListNotaryInfosRequest() (request *ListNotaryInfosRequest) {
	request = &ListNotaryInfosRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Trademark", "2018-07-24", "ListNotaryInfos", "trademark", "openAPI")
	return
}

// CreateListNotaryInfosResponse creates a response to parse from ListNotaryInfos response
func CreateListNotaryInfosResponse() (response *ListNotaryInfosResponse) {
	response = &ListNotaryInfosResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
#ifndef QPLAINTEXTEDIT_P_H
#define QPLAINTEXTEDIT_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "private/qabstractscrollarea_p.h"
#include "QtGui/qtextdocumentfragment.h"
#include "QtWidgets/qscrollbar.h"
#include "QtGui/qtextcursor.h"
#include "QtGui/qtextformat.h"
#include "QtWidgets/qmenu.h"
#include "QtGui/qabstracttextdocumentlayout.h"
#include "QtCore/qbasictimer.h"
#include "private/qwidgettextcontrol_p.h"
#include "qplaintextedit.h"

#ifndef QT_NO_TEXTEDIT

QT_BEGIN_NAMESPACE

class QMimeData;

class QPlainTextEdit;
class ExtraArea;

class QPlainTextEditControl : public QWidgetTextControl
{
    Q_OBJECT
public:
    QPlainTextEditControl(QPlainTextEdit *parent);

    QMimeData *createMimeDataFromSelection() const Q_DECL_OVERRIDE;
    bool canInsertFromMimeData(const QMimeData *source) const Q_DECL_OVERRIDE;
    void insertFromMimeData(const QMimeData *source) Q_DECL_OVERRIDE;
    int hitTest(const QPointF &point, Qt::HitTestAccuracy = Qt::FuzzyHit) const Q_DECL_OVERRIDE;
    QRectF blockBoundingRect(const QTextBlock &block) const Q_DECL_OVERRIDE;
    QString anchorAt(const QPointF &pos) const Q_DECL_OVERRIDE;
    inline QRectF cursorRect(const QTextCursor &cursor) const {
        QRectF r = QWidgetTextControl::cursorRect(cursor);
        r.setLeft(qMax(r.left(), (qreal) 0.));
        return r;
    }
    inline QRectF cursorRect() { return cursorRect(textCursor()); }
    void ensureCursorVisible() Q_DECL_OVERRIDE {
        textEdit->ensureCursorVisible();
        emit microFocusChanged();
    }

    QPlainTextEdit *textEdit;
    int topBlock;
    QTextBlock firstVisibleBlock() const;

    QVariant loadResource(int type, const QUrl &name) Q_DECL_OVERRIDE {
        return textEdit->loadResource(type, name);
    }

};

class QPlainTextEditPrivate : public QAbstractScrollAreaPrivate
{
    Q_DECLARE_PUBLIC(QPlainTextEdit)
public:
    QPlainTextEditPrivate();

    void init(const QString &txt = QString());
    void _q_repaintContents(const QRectF &contentsRect);

    inline QPoint mapToContents(const QPoint &point) const
        { return QPoint(point.x() + horizontalOffset(), point.y() + verticalOffset()); }

    void _q_adjustScrollbars();
    void _q_verticalScrollbarActionTriggered(int action);
    void ensureViewportLayouted();
    void relayoutDocument();

    void pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode, bool moveCursor = true);

    inline int horizontalOffset() const
        { return (q_func()->isRightToLeft() ? (hbar->maximum() - hbar->value()) : hbar->value()); }
    qreal verticalOffset(int topBlock, int topLine) const;
    qreal verticalOffset() const;

    inline void sendControlEvent(QEvent *e)
        { control->processEvent(e, QPointF(horizontalOffset(), verticalOffset()), viewport); }

    void updateDefaultTextOption();

    QPlainTextEditControl *control;

    bool tabChangesFocus;

    QBasicTimer autoScrollTimer;
    QPoint autoScrollDragPos;

    QPlainTextEdit::LineWrapMode lineWrap;
    QTextOption::WrapMode wordWrap;

    uint showCursorOnInitialShow : 1;
    uint backgroundVisible : 1;
    uint centerOnScroll : 1;
    uint inDrag : 1;
    uint clickCausedFocus : 1;

    int topLine;
    qreal topLineFracture; // for non-int sized fonts

    void setTopLine(int visualTopLine, int dx = 0);
    void setTopBlock(int newTopBlock, int newTopLine, int dx = 0);

    void ensureVisible(int position, bool center, bool forceCenter = false);
    void ensureCursorVisible(bool center = false);
    void updateViewport();

    QPointer<QPlainTextDocumentLayout> documentLayoutPtr;

    void append(const QString &text, Qt::TextFormat format = Qt::AutoText);

    qreal pageUpDownLastCursorY;
    bool pageUpDownLastCursorYIsValid;

#ifdef QT_KEYPAD_NAVIGATION
    QBasicTimer deleteAllTimer;
#endif

    void _q_cursorPositionChanged();
    void _q_modificationChanged(bool);

    int originalOffsetY;
    QString placeholderText;
};

QT_END_NAMESPACE

#endif // QT_NO_TEXTEDIT

#endif // QPLAINTEXTEDIT_P_H


text:
[![Build Status](https://travis-ci.org/jadu/pulsar.svg?branch=develop)](https://travis-ci.org/jadu/pulsar) [![codecov](https://codecov.io/gh/jadu/pulsar/branch/develop/graph/badge.svg)](https://codecov.io/gh/jadu/pulsar) [![license](https://img.shields.io/github/license/jadu/pulsar.svg)]()

Pulsar is the User Experience and Interface framework for [Jadu](http://jadu.net) software.

## Introduction

Watch a Jadu Academy session presented by Paul Stanton, Pulsar Product Owner which gives an overview of Pulsar and how it influences our product development.

[![Jadu Pulsar - The UI framework for the Continuum platform](https://raw.githubusercontent.com/jadu/pulsar/develop/images/youtube.jpg)](https://www.youtube.com/watch?v=rmGUTvuBvdw)

## Documentation

Documentation is available online at [https://jadu.github.io/pulsar](https://jadu.github.io/pulsar), we welcome any feedback on areas which may need improvement.

## Contributing

New issues can be submitted through the [GitHub Issue Tracker](https://github.com/jadu/pulsar/issues), and [Pull Requests](https://github.com/jadu/pulsar/pulls) are very welcome, please take a minute to read our [notes for contributors](https://jadu.gitbooks.io/pulsar/content/contributing.html).

## Mission Statement

* Improve code quality and consistency
* Enable developers to prototype in hours, not days
* Allow the continual release of UI improvements
* Provide a common UI language to help new developers learn our lingo
* Provide a starting point to redesign older parts of the software
* Improve performance
* Make our interfaces more testable
* Make the users of our software happier
* Make the people designing Jadu interfaces happier
* Learn how our customers use our software
* Learn what our customers need (not necessarily what they ask for) so that we can build the right thing
* Reduce the complexity of the tasks our customers need to perform
* Define clear, understandable guidelines for developers to build awesome things

## License

MIT © [Jadu](http://jadu.net)


text:
package test.junit4;

/** @author lukas */
public class InheritedTest extends JUnit4Sample1 {}


text:
<?php

namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;

/**
 * NativeSqliteSessionStorage.
 *
 * Driver for the sqlite session save hadlers provided by the SQLite PHP extension.
 *
 * @author Drak <drak@zikula.org>
 */
class NativeSqliteSessionHandler extends NativeSessionHandler
{
    /**
     * Constructor.
     *
     * @param string $savePath Path to SQLite database file itself.
     * @param array  $options  Session configuration options.
     *
     * @see AbstractSessionStorage::__construct()
     */
    public function __construct($savePath, array $options = array())
    {
        if (!extension_loaded('sqlite')) {
            throw new \RuntimeException('PHP does not have "sqlite" session module registered');
        }

        if (null === $savePath) {
            $savePath = ini_get('session.save_path');
        }

        ini_set('session.save_handler', 'sqlite');
        ini_set('session.save_path', $savePath);

        $this->setOptions($options);
    }

    /**
     * {@inheritdoc}
     *
     * Sets any values sqlite ini values.
     *
     * @see http://php.net/sqlite.configuration
     */
    protected function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            if (in_array($key, array('sqlite.assoc_case'))) {
                ini_set($key, $value);
            }
        }
    }
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.engine.test.bpmn.event.end;

import java.util.List;

import org.flowable.engine.common.impl.util.CollectionUtil;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.runtime.Job;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Task;
import org.flowable.engine.test.Deployment;

/**
 * @author Joram Barrez
 */
public class TerminateMultiInstanceEndEventTest extends PluggableFlowableTestCase {

    @Deployment
    public void testMultiInstanceEmbeddedSubprocess() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("terminateMi");

        Task aTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.complete(aTask.getId());

        List<Task> bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        assertEquals(8, bTasks.size());

        // Complete 2 tasks by going to task C. The 3th tasks goes to the MI terminate end and shuts down the MI.
        for (int i = 0; i < 2; i++) {
            Task bTask = bTasks.get(i);
            taskService.complete(bTask.getId(), CollectionUtil.singletonMap("myVar", "toC"));
        }

        bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("B").list();
        assertEquals(6, bTasks.size());

        taskService.complete(bTasks.get(0).getId(), CollectionUtil.singletonMap("myVar", "toEnd"));

        Task afterMiTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertEquals("AfterMi", afterMiTask.getName());
        taskService.complete(afterMiTask.getId());

        assertEquals(0, runtimeService.createExecutionQuery().count());
    }

    @Deployment
    public void testMultiInstanceEmbeddedSubprocessSequential() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("terminateMi");

        Task aTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.complete(aTask.getId());

        List<Task> bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        assertEquals(1, bTasks.size());
        taskService.complete(bTasks.get(0).getId(), CollectionUtil.singletonMap("myVar", "toC"));

        List<Task> cTasks = taskService.createTaskQuery().taskName("C").list();
        assertEquals(1, cTasks.size());
        taskService.complete(cTasks.get(0).getId());

        bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("B").list();
        assertEquals(1, bTasks.size());
        taskService.complete(bTasks.get(0).getId(), CollectionUtil.singletonMap("myVar", "toEnd"));

        Task afterMiTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertEquals("AfterMi", afterMiTask.getName());
        taskService.complete(afterMiTask.getId());

        assertEquals(0, runtimeService.createExecutionQuery().count());
    }

    @Deployment
    public void testMultiInstanceEmbeddedSubprocess2() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("terminateMi");

        Task aTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.complete(aTask.getId());

        List<Task> bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        assertEquals(5, bTasks.size());

        // Complete one b task to get one C and D
        taskService.complete(bTasks.get(0).getId());

        // C and D should now be active
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).orderByTaskName().asc().list();
        assertEquals(6, tasks.size());
        // 0-3 are B tasks
        assertEquals("C", tasks.get(4).getName());
        assertEquals("D", tasks.get(5).getName());

        // Completing C should terminate the multi instance
        taskService.complete(tasks.get(4).getId());

        Task afterMiTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertEquals("AfterMi", afterMiTask.getName());
        taskService.complete(afterMiTask.getId());

        assertEquals(0, runtimeService.createExecutionQuery().count());
    }

    @Deployment
    public void testMultiInstanceEmbeddedSubprocess2Sequential() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("terminateMi");

        Task aTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.complete(aTask.getId());

        List<Task> bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        assertEquals(1, bTasks.size());

        // Complete one b task to get one C and D
        taskService.complete(bTasks.get(0).getId());

        // C and D should now be active
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).orderByTaskName().asc().list();
        assertEquals(2, tasks.size());
        assertEquals("C", tasks.get(0).getName());
        assertEquals("D", tasks.get(1).getName());

        // Completing C should terminate the multi instance
        taskService.complete(tasks.get(0).getId());

        Task afterMiTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertEquals("AfterMi", afterMiTask.getName());
        taskService.complete(afterMiTask.getId());

        assertEquals(0, runtimeService.createExecutionQuery().count());
    }

    @Deployment(resources = {
            "org/flowable/engine/test/bpmn/event/end/TerminateMultiInstanceEndEventTest.testTerminateMiCallactivity-parentProcess.bpmn20.xml",
            "org/flowable/engine/test/bpmn/event/end/TerminateMultiInstanceEndEventTest.testTerminateMiCallactivity-calledProcess.bpmn20.xml"
    })
    public void testTerminateMiCallactivity() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("terminateMiCallActivity");

        Task taskA = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertEquals("A", taskA.getName());
        taskService.complete(taskA.getId());

        // After completing A, four B's should be active (due to the call activity)
        List<Task> bTasks = taskService.createTaskQuery().taskName("B").list();
        assertEquals(4, bTasks.size());

        // Completing 3 B tasks, giving 3 C's and D's
        for (int i = 0; i < 3; i++) {
            taskService.complete(bTasks.get(i).getId());
        }

        List<Task> cTasks = taskService.createTaskQuery().taskName("C").list();
        assertEquals(3, cTasks.size());
        List<Task> dTasks = taskService.createTaskQuery().taskName("D").list();
        assertEquals(3, dTasks.size());

        // Completing one of the C tasks should terminate the whole multi instance
        taskService.complete(cTasks.get(0).getId());

        List<Task> afterMiTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).orderByTaskName().asc().list();
        assertEquals(2, afterMiTasks.size());
        assertEquals("AfterMi", afterMiTasks.get(0).getName());
        assertEquals("Parallel task", afterMiTasks.get(1).getName());
    }

    @Deployment(resources = {
            "org/flowable/engine/test/bpmn/event/end/TerminateMultiInstanceEndEventTest.testTerminateMiCallactivity-parentProcessSequential.bpmn20.xml",
            "org/flowable/engine/test/bpmn/event/end/TerminateMultiInstanceEndEventTest.testTerminateMiCallactivity-calledProcess.bpmn20.xml"
    })
    public void testTerminateMiCallactivitySequential() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("terminateMiCallActivity");

        Task taskA = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertEquals("A", taskA.getName());
        taskService.complete(taskA.getId());

        List<Task> bTasks = taskService.createTaskQuery().taskName("B").list();
        assertEquals(1, bTasks.size());
        taskService.complete(bTasks.get(0).getId());

        List<Task> cTasks = taskService.createTaskQuery().taskName("C").list();
        assertEquals(1, cTasks.size());
        List<Task> dTasks = taskService.createTaskQuery().taskName("D").list();
        assertEquals(1, dTasks.size());

        // Completing one of the C tasks should terminate the whole multi instance
        taskService.complete(cTasks.get(0).getId());

        List<Task> afterMiTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).orderByTaskName().asc().list();
        assertEquals(2, afterMiTasks.size());
        assertEquals("AfterMi", afterMiTasks.get(0).getName());
        assertEquals("Parallel task", afterMiTasks.get(1).getName());
    }

    @Deployment
    public void testTerminateNestedMiEmbeddedSubprocess() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                "terminateNestedMiEmbeddedSubprocess", CollectionUtil.singletonMap("var", "notEnd"));

        List<Task> aTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("A").list();
        assertEquals(12, aTasks.size());
        List<Task> bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("B").list();
        assertEquals(72, bTasks.size());

        // Completing a few B's will create a subprocess with some C's
        int nrOfBTasksCompleted = 3;
        for (int i = 0; i < nrOfBTasksCompleted; i++) {
            taskService.complete(bTasks.get(i).getId());
        }

        bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("B").list();
        assertEquals(72 - nrOfBTasksCompleted, bTasks.size());

        // Firing the timer --> inner MI gets destroyed
        List<Job> timers = managementService.createTimerJobQuery().list();
        assertEquals(nrOfBTasksCompleted, timers.size());
        managementService.moveTimerToExecutableJob(timers.get(0).getId());
        managementService.executeJob(timers.get(0).getId());

        // We only completed 3 B's. 3 other ones should be destroyed too (as one inner multi instance are 6 instances of B)
        bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("B").list();
        assertEquals(66, bTasks.size());

        // One of the inner multi instances should have been killed
        List<Task> afterInnerMiTasks = taskService.createTaskQuery().taskName("AfterInnerMi").list();
        assertEquals(1, afterInnerMiTasks.size());

        for (Task aTask : aTasks) {
            taskService.complete(aTask.getId());
        }

        // Finish
        List<Task> nextTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        while (nextTasks != null && nextTasks.size() > 0) {
            taskService.complete(nextTasks.get(0).getId());
            nextTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        }

        assertEquals(0, runtimeService.createExecutionQuery().count());
    }

    @Deployment(resources = "org/flowable/engine/test/bpmn/event/end/TerminateMultiInstanceEndEventTest.testTerminateNestedMiEmbeddedSubprocess.bpmn20.xml")
    public void testTerminateNestedMiEmbeddedSubprocess2() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                "terminateNestedMiEmbeddedSubprocess", CollectionUtil.singletonMap("var", "toEnd"));

        List<Task> aTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("A").list();
        assertEquals(12, aTasks.size());
        List<Task> afterInnerMiTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("AfterInnerMi").list();
        assertEquals(12, afterInnerMiTasks.size());

    }

    @Deployment
    public void testTerminateNestedMiEmbeddedSubprocessWithOneLoopCardinality() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                "terminateNestedMiEmbeddedSubprocess", CollectionUtil.singletonMap("var", "notEnd"));

        List<Task> aTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("A").list();
        assertEquals(1, aTasks.size());
        List<Task> bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("B").list();
        assertEquals(1, bTasks.size());

        taskService.complete(bTasks.get(0).getId());
        bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("B").list();
        assertEquals(0, bTasks.size());

        // Firing the timer --> inner MI gets destroyed
        List<Job> timers = managementService.createTimerJobQuery().list();
        assertEquals(1, timers.size());
        managementService.moveTimerToExecutableJob(timers.get(0).getId());
        managementService.executeJob(timers.get(0).getId());

        bTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskName("B").list();
        assertEquals(0, bTasks.size());

        // One of the inner multi instances should have been killed
        List<Task> afterInnerMiTasks = taskService.createTaskQuery().taskName("AfterInnerMi").list();
        assertEquals(1, afterInnerMiTasks.size());

        for (Task aTask : aTasks) {
            taskService.complete(aTask.getId());
        }

        // Finish
        List<Task> nextTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        while (nextTasks != null && nextTasks.size() > 0) {
            taskService.complete(nextTasks.get(0).getId());
            nextTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        }

        assertEquals(0, runtimeService.createExecutionQuery().count());
    }

}


text:
using namespace SideCar::GUI::Spectrum;

Logger::Log&
ScaleWidget::Log()
{
    static Logger::Log& log_ = Logger::Log::Find("spectrum.ScaleWidget");
    return log_;
}

ScaleWidget::ScaleWidget(QWidget* parent, Qt::Orientation orientation) :
    QWidget(parent), label_(""), inset_(0), majorTickHeight_(10), minorTickHeight_(3), majorTickDivisionsMax_(8),
    minorTickDivisionsMax_(4), start_(0.0), range_(4.0), orientation_(orientation),
    majorGridPen_(QColor(64, 64, 64), 0.0), minorGridPen_(QColor(32, 32, 32), 0.0),
    cursorIndicatorPen_(QColor(255, 0, 0, 128), 0), cursorPosition_(-1), autoDivide_(false)
{
    QFont labelFont(font());
    labelFont.setPointSize(10);
    setFont(labelFont);
    setBackgroundRole(QPalette::Base);
    setOrientation(orientation);
}

void
ScaleWidget::setLabel(const QString& label)
{
    label_ = label;
    makeTicks();
    update();
}

void
ScaleWidget::setSpan(int span)
{
    static Logger::ProcLog log("setSpan", Log());
    LOGINFO << "span: " << span << std::endl;

    if (orientation_ == Qt::Horizontal) {
        resize(span, height());
    } else {
        resize(width(), span);
    }

    updateGeometry();
    recalculateTickIntervals();
}

void
ScaleWidget::resizeEvent(QResizeEvent* event)
{
    static Logger::ProcLog log("resizeEvent", Log());
    LOGINFO << "width: " << width() << " height: " << height() << std::endl;

    Super::resizeEvent(event);

    if (orientation_ == Qt::Vertical) {
        transform_.reset();
        transform_.translate(width(), 1);
        transform_.rotate(90.0);
    }

    recalculateTickIntervals();
}

QSize
ScaleWidget::sizeHint() const
{
    if (orientation_ == Qt::Horizontal)
        return QSize(width(), majorTickHeight_ + fontMetrics().height() * 2);
    else
        return QSize(majorTickHeight_ + fontMetrics().height() * 2, height());
}

QSize
ScaleWidget::minimumSizeHint() const
{
    return sizeHint();
}

void
ScaleWidget::setAutoDivide(bool autoDivide)
{
    autoDivide_ = autoDivide;
    recalculateTickIntervals();
}

double
ScaleWidget::getTickSpan() const
{
    return getSpan() - 2 * inset_ - 1;
}

double
ScaleWidget::getTagOffset() const
{
    return (orientation_ == Qt::Horizontal ? height() : width()) - fontMetrics().height() - 1;
}

void
ScaleWidget::recalculateTickIntervals()
{
    static Logger::ProcLog log("recalculateTickIntervals", Log());
    LOGINFO << std::endl;

    double span = getTickSpan();

    if (autoDivide_) {
        majorIncrement_ = std::max(80.0, span / majorTickDivisionsMax_);
        majorTickDivisions_ = std::max(1, int(::floor(span / majorIncrement_)));
        majorIncrement_ = span / majorTickDivisions_;
        minorIncrement_ = std::max(40.0, majorIncrement_ / minorTickDivisionsMax_);
        minorTickDivisions_ = std::max(1, int(::floor(majorIncrement_ / minorIncrement_)));
        minorIncrement_ = majorIncrement_ / minorTickDivisions_;
    } else {
        majorIncrement_ = span / majorTickDivisionsMax_;
        majorTickDivisions_ = majorTickDivisionsMax_;
        minorIncrement_ = majorIncrement_ / minorTickDivisionsMax_;
        minorTickDivisions_ = minorTickDivisionsMax_;
    }

    makeTicks();
}

void
ScaleWidget::makeTicks()
{
    static Logger::ProcLog log("makeTicks", Log());
    LOGINFO << std::endl;

    majorTicks_.clear();
    minorTicks_.clear();
    labelStarts_.clear();
    labelTexts_.clear();

    QFontMetrics fm(fontMetrics());

    double span = getTickSpan();
    double tagOffset = getTagOffset();

    double tag = start_;
    int tickCounter = 0;
    double tagIncrement = range_ / majorTickDivisions_;

    LOGDEBUG << "tagIncrement: " << tagIncrement << std::endl;

    while (1) {
        double x = inset_ + tickCounter * minorIncrement_;
        LOGDEBUG << "x: " << x << " tickCounter: " << tickCounter << std::endl;

        if (x > span) break;

        if ((tickCounter % minorTickDivisions_) == 0) {
            QLineF line(x, 0.0, x, majorTickHeight_);
            majorTicks_.push_back(line);

            if (::fabs(tag) < 1E-6) tag = 0.0;

            QString label = formatTickTag(tag);
            labelTexts_.push_back(label);

            double offset = fm.boundingRect(label).width() / 2.0;
            if (x - offset < 0.0) {
                offset = 0.0;
            } else if (x + offset > span) {
                offset += offset;
            }

            line.translate(-offset, tagOffset - fm.descent() - 1);
            labelStarts_.push_back(line.p1());

            tag += tagIncrement;
        } else {
            minorTicks_.push_back(QLineF(x, 0.0, x, minorTickHeight_));
        }

        ++tickCounter;
    }

    if (!label_.isEmpty()) {
        double offset = fm.boundingRect(label_).width() / 2.0;
        QPointF pt(getSpan() / 2.0, 0.0);
        pt += QPointF(-offset, tagOffset + fm.height() - fm.descent() - 1);
        labelPosition_ = pt.toPoint();
    }

    update();
}

void
ScaleWidget::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);

    // For tick marks, disable antialiasing.
    //
    painter.setRenderHint(QPainter::Antialiasing, false);
    painter.setRenderHint(QPainter::TextAntialiasing, true);

    auto palette = QGuiApplication::palette();
    painter.setFont(font());
    painter.setBrush(palette.windowText());

    if (orientation_ == Qt::Vertical) painter.setWorldTransform(transform_);

    painter.drawLines(majorTicks_);
    painter.drawLines(minorTicks_);

    for (int index = 0; index < labelStarts_.size(); ++index) {
        painter.drawText(labelStarts_[index], labelTexts_[index]);
    }

    if (!label_.isEmpty()) painter.drawText(labelPosition_, label_);

    if (cursorPosition_ != -1) {
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setPen(cursorIndicatorPen_);
        painter.setBrush(cursorIndicatorPen_.color());
        QPolygonF indicator;
        indicator << QPointF(cursorPosition_, 0) << QPointF(cursorPosition_ - 4, majorTickHeight_)
                  << QPointF(cursorPosition_ + 4, majorTickHeight_) << QPointF(cursorPosition_, 0);
        painter.drawConvexPolygon(indicator);
    }
}

void
ScaleWidget::drawGridLines(QPainter& painter)
{
    QPaintDevice* device = painter.device();
    painter.setRenderHint(QPainter::Antialiasing, false);
    if (orientation_ == Qt::Horizontal) {
        drawGridLines(painter, device->height());
    } else {
        painter.save();
        painter.translate(device->width(), 1);
        painter.rotate(90.0);
        drawGridLines(painter, device->width());
        painter.restore();
    }
}

void
ScaleWidget::drawGridLines(QPainter& painter, int height) const
{
    QVector<QLineF> lines;
    painter.setPen(majorGridPen_);
    for (int index = 0; index < majorTicks_.size(); ++index) {
        qreal x = majorTicks_[index].x1();
        lines.push_back(QLineF(x, 0.0, x, height));
    }

    painter.drawLines(lines);
    lines.clear();

    painter.setPen(minorGridPen_);
    for (int index = 0; index < minorTicks_.size(); ++index) {
        qreal x = minorTicks_[index].x1();
        lines.push_back(QLineF(x, 0.0, x, height));
    }

    painter.drawLines(lines);
}

void
ScaleWidget::setMajorTickHeight(int height)
{
    majorTickHeight_ = height;
    makeTicks();
}

void
ScaleWidget::setMinorTickHeight(int height)
{
    minorTickHeight_ = height;
    makeTicks();
}

void
ScaleWidget::setMajorTickDivisions(int divisions)
{
    majorTickDivisionsMax_ = divisions;
    recalculateTickIntervals();
}

void
ScaleWidget::setMinorTickDivisions(int divisions)
{
    minorTickDivisionsMax_ = divisions;
    recalculateTickIntervals();
}

void
ScaleWidget::setStart(double start)
{
    start_ = start;
    makeTicks();
    update();
}

void
ScaleWidget::setEnd(double end)
{
    range_ = end - start_;
    makeTicks();
    update();
}

void
ScaleWidget::setMidPoint(double zero)
{
    start_ = zero - range_ / 2.0;
    makeTicks();
    update();
}

void
ScaleWidget::setRange(double range)
{
    range_ = range;
    makeTicks();
    update();
}

void
ScaleWidget::setOrientation(Qt::Orientation orientation)
{
    orientation_ = orientation;
    if (orientation_ == Qt::Horizontal) {
        setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
    } else {
        setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding));
    }

    recalculateTickIntervals();
}

void
ScaleWidget::setCursorPosition(int position)
{
    cursorPosition_ = position;
    update();
}

void
ScaleWidget::setCursorValue(double value)
{
    cursorPosition_ = int(::rint((value - start_) * double(getSpan()) / range_));
    update();
}


text:
require 'logstash-logger'

describe LogStashLogger::Device::Socket do
  include_context 'device'

  it "defaults host to 0.0.0.0" do
    expect(device_with_port.host).to eq("0.0.0.0")
  end

  context "when port is not specified" do
    it "raises an exception" do
      expect { described_class.new }.to raise_error(ArgumentError)
    end
  end
end


text:
using System;
using System.Net.Http;
using Firestorm.Testing.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace Firestorm.Stems.FunctionalTests.Web
{
    public class ExampleIntegrationSuite : IHttpIntegrationSuite
    {
        private readonly Type _testClassType;

        private static int _startPort = 2240;
        private readonly string _url = "http://localhost:" + _startPort++;

        private IWebHost _host;

        public ExampleIntegrationSuite(Type testClassType)
        {
            _testClassType = testClassType;
        }

        public void Start()
        {
            var config = new FunctionalTestConfig
            {
                TestClassType = _testClassType
            };

            _host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls(_url)
                .ConfigureServices(s => s.AddSingleton(config))
                .UseStartup<Startup>()
                .Build();

            _host.Start();

            HttpClient = new HttpClient
            {
                BaseAddress = new Uri(_url)
            };
        }

        public HttpClient HttpClient { get; private set; }

        public void Dispose()
        {
            _host?.Dispose();
            HttpClient?.Dispose();
        }
    }
}


text:
Rails.application.routes.draw do
  get 'matches/index'

  mount JasmineRails::Engine => '/specs' if defined?(JasmineRails)
  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
  root 'matches#index'
  resources :matches
  resources :groups
  resources :projects

  post 'groups/destroy_multiple' => 'groups#destroy_multiple'

  get 'google/fetch' => 'google#index'

  post 'google/authorize' => 'google#complete_authorization'

  get 'google/fetch/data' => 'google#projects_groups_fetch'

  post 'google/write/matches' => 'google#write_matches'
  get 'google/fetch/matches' => 'google#fetch_matches'

  get 'google/settings' => 'google#settings'
  put 'google/settings' => 'google#save_preferences'

  get 'login' => 'login#index'
  post 'login/attempt' => 'login#attempt'
  post 'login/logout' => 'login#logout'

  get '*path' => 'application#errors'

end


text:
using System.ComponentModel.DataAnnotations;

namespace RezRouting.Demos.MvcWalkthrough2.Controllers.Manufacturers
{
    /// <summary>
    /// The values submitted to create a manufacturer
    /// </summary>
    public class CreateManufacturerRequest
    {
        [Required]
        public string Name { get; set; }
    }
}


text:
__revision__ = "test/Repository/JavaH.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"

"""
Test building Java applications when using Repositories.
"""

import os

import TestSCons

python = TestSCons.python

test = TestSCons.TestSCons()

where_javac, java_version = test.java_where_javac()
where_java = test.java_where_java()
where_javah = test.java_where_javah()

java = where_java
javac = where_javac
javah = where_javah

###############################################################################

#
test.subdir('rep1', ['rep1', 'src'],
            'work1',
            'work2',
            'work3')

#
rep1_classes = test.workpath('rep1', 'classes')
work1_classes = test.workpath('work1', 'classes')
work3_classes = test.workpath('work3', 'classes')

#
opts = '-Y ' + test.workpath('rep1')

#
test.write(['rep1', 'SConstruct'], """
env = Environment(tools = ['javac', 'javah'],
                  JAVAC = r'%s',
                  JAVAH = r'%s')
classes = env.Java(target = 'classes', source = 'src')
env.JavaH(target = 'outdir', source = classes)
""" % (javac, javah))

test.write(['rep1', 'src', 'Foo1.java'], """\
public class Foo1
{
     public static void main(String[] args)
     {
          System.out.println("rep1/src/Foo1.java");

     }
}
""")

test.write(['rep1', 'src', 'Foo2.java'], """\
public class Foo2
{
     public static void main(String[] args)
     {
          System.out.println("rep1/src/Foo2.java");

     }
}
""")

test.write(['rep1', 'src', 'Foo3.java'], """\
public class Foo3
{
     public static void main(String[] args)
     {
          System.out.println("rep1/src/Foo3.java");

     }
}
""")

# Make the repository non-writable,
# so we'll detect if we try to write into it accidentally.
test.writable('repository', 0)

#
test.run(chdir = 'work1', options = opts, arguments = ".")

test.run(program = java,
         arguments = "-cp %s Foo1" % work1_classes,
         stdout = "rep1/src/Foo1.java\n")

test.run(program = java,
         arguments = "-cp %s Foo2" % work1_classes,
         stdout = "rep1/src/Foo2.java\n")

test.run(program = java,
         arguments = "-cp %s Foo3" % work1_classes,
         stdout = "rep1/src/Foo3.java\n")

test.fail_test(not os.path.exists(test.workpath('work1', 'outdir', 'Foo1.h')))
test.fail_test(not os.path.exists(test.workpath('work1', 'outdir', 'Foo2.h')))
test.fail_test(not os.path.exists(test.workpath('work1', 'outdir', 'Foo3.h')))

test.up_to_date(chdir = 'work1', options = opts, arguments = ".")

#
test.subdir(['work1', 'src'])

test.write(['work1', 'src', 'Foo1.java'], """\
public class Foo1
{
     public static void main(String[] args)
     {
          System.out.println("work1/src/Foo1.java");

     }
}
""")

test.write(['work1', 'src', 'Foo2.java'], """\
public class Foo2
{
     public static void main(String[] args)
     {
          System.out.println("work1/src/Foo2.java");

     }
}
""")

test.write(['work1', 'src', 'Foo3.java'], """\
public class Foo3
{
     public static void main(String[] args)
     {
          System.out.println("work1/src/Foo3.java");

     }
}
""")

test.run(chdir = 'work1', options = opts, arguments = ".")

test.run(program = java,
         arguments = "-cp %s Foo1" % work1_classes,
         stdout = "work1/src/Foo1.java\n")

test.run(program = java,
         arguments = "-cp %s Foo2" % work1_classes,
         stdout = "work1/src/Foo2.java\n")

test.run(program = java,
         arguments = "-cp %s Foo3" % work1_classes,
         stdout = "work1/src/Foo3.java\n")

test.up_to_date(chdir = 'work1', options = opts, arguments = ".")

#
test.writable('rep1', 1)

test.run(chdir = 'rep1', options = opts, arguments = ".")

test.run(program = java,
         arguments = "-cp %s Foo1" % rep1_classes,
         stdout = "rep1/src/Foo1.java\n")

test.run(program = java,
         arguments = "-cp %s Foo2" % rep1_classes,
         stdout = "rep1/src/Foo2.java\n")

test.run(program = java,
         arguments = "-cp %s Foo3" % rep1_classes,
         stdout = "rep1/src/Foo3.java\n")

test.up_to_date(chdir = 'rep1', options = opts, arguments = ".")

#
test.writable('repository', 0)

#
test.up_to_date(chdir = 'work2', options = opts, arguments = ".")

#
test.write(['work3', 'SConstruct'], """
env = Environment(tools = ['javac', 'javah'],
                  JAVAC = r'%s',
                  JAVAH = r'%s')
classes = env.Java(target = 'classes', source = 'src')
hfiles = env.JavaH(target = 'outdir', source = classes)
Local(hfiles)
""" % (javac, javah))

test.run(chdir = 'work3', options = opts, arguments = ".")

test.fail_test(os.path.exists(test.workpath('work3', 'classes', 'Foo1.class')))
test.fail_test(os.path.exists(test.workpath('work3', 'classes', 'Foo2.class')))
test.fail_test(os.path.exists(test.workpath('work3', 'classes', 'Foo3.class')))

test.fail_test(not os.path.exists(test.workpath('work3', 'outdir', 'Foo1.h')))
test.fail_test(not os.path.exists(test.workpath('work3', 'outdir', 'Foo2.h')))
test.fail_test(not os.path.exists(test.workpath('work3', 'outdir', 'Foo3.h')))

#
# If the Java builder were to interact with Repositories like the
# other builders, then we'd uncomment the following test(s).
#
# This tests that, if the .class files are built in the repository,
# then a local build says that everything is up-to-date.  However,
# because the destination target is a directory ("classes") not a
# file, we don't detect that the individual .class files are
# already there, and think things must be rebuilt.
#
#test.up_to_date(chdir = 'work2', options = opts, arguments = ".")
#
#test.subdir(['work2', 'src'])
#
#test.write(['work2', 'src', 'Foo1.java'], """\
#public class Foo1
#{
#     public static void main(String[] args)
#     {
#          System.out.println("work2/src/Foo1.java");
#
#     }
#}
#""")
#
#test.write(['work2', 'src', 'Foo2.java'], """\
#public class Foo2
#{
#     public static void main(String[] args)
#     {
#          System.out.println("work2/src/Foo2.java");
#
#     }
#}
#""")
#
#test.write(['work2', 'src', 'Foo3.java'], """\
#public class Foo3
#{
#     public static void main(String[] args)
#     {
#          System.out.println("work2/src/Foo3.java");
#
#     }
#}
#""")
#
#test.run(chdir = 'work2', options = opts, arguments = ".")
#
#test.run(program = java,
#         arguments = "-cp %s Foo1" % work2_classes,
#         stdout = "work2/src/Foo1.java\n")
#
#test.run(program = java,
#         arguments = "-cp %s Foo2" % work2_classes,
#         stdout = "work2/src/Foo2.java\n")
#
#test.run(program = java,
#         arguments = "-cp %s Foo3" % work2_classes,
#         stdout = "work2/src/Foo3.java\n")
#
#test.up_to_date(chdir = 'work2', options = opts, arguments = ".")

test.pass_test()

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
package org.ovirt.engine.core.searchbackend;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.ovirt.engine.core.common.utils.CommonConstants;

public final class SearchObjects {
    // objects
    public static final String VDS_OBJ_NAME = "HOST";
    public static final String VDS_PLU_OBJ_NAME = "HOSTS";
    public static final String VM_OBJ_NAME = "VM";
    public static final String VM_PLU_OBJ_NAME = "VMS";
    public static final String AUDIT_OBJ_NAME = "EVENT";
    public static final String AUDIT_PLU_OBJ_NAME = "EVENTS";
    public static final String AD_USER_OBJ_NAME = "ADUSER";
    public static final String AD_USER_PLU_OBJ_NAME = "ADUSERS";
    public static final String AD_GROUP_OBJ_NAME = "ADGROUP";
    public static final String AD_GROUP_PLU_OBJ_NAME = "ADGROUPS";
    public static final String TEMPLATE_OBJ_NAME = "TEMPLATE";
    public static final String TEMPLATE_PLU_OBJ_NAME = "TEMPLATES";
    public static final String VDC_USER_OBJ_NAME = "USER";
    public static final String VDC_USER_PLU_OBJ_NAME = "USERS";
    public static final String VDC_GROUP_OBJ_NAME = "GROUP";
    public static final String VDC_GROUP_PLU_OBJ_NAME = "GROUPS";
    public static final String VDC_POOL_OBJ_NAME = "POOL";
    public static final String VDC_POOL_PLU_OBJ_NAME = "POOLS";
    public static final String VDC_CLUSTER_OBJ_NAME = "CLUSTER";
    public static final String VDC_CLUSTER_PLU_OBJ_NAME = "CLUSTERS";
    public static final String VDC_STORAGE_POOL_OBJ_NAME = "DATACENTER";
    public static final String VDC_STORAGE_DOMAIN_OBJ_NAME = "STORAGE";
    public static final String VDC_STORAGE_DOMAIN_PLU_OBJ_NAME = "STORAGES";
    public static final String VDC_STORAGE_DOMAIN_IMAGE_OBJ_NAME = "VMIMAGE";
    public static final String DISK_OBJ_NAME = "DISK";
    public static final String DISK_PLU_OBJ_NAME = "DISKS";
    public static final String GLUSTER_VOLUME_OBJ_NAME = "VOLUME";
    public static final String GLUSTER_VOLUME_PLU_OBJ_NAME = "VOLUMES";
    public static final String QUOTA_OBJ_NAME = "QUOTA";
    public static final String QUOTA_PLU_OBJ_NAME = "QUOTAS";
    public static final String NETWORK_OBJ_NAME = "NETWORK";
    public static final String NETWORK_PLU_OBJ_NAME = "NETWORKS";
    public static final String VDS_NETWORK_INTERFACE_OBJ_NAME = "NIC";
    public static final String VM_NETWORK_INTERFACE_OBJ_NAME = "VNIC";
    public static final String NETWORK_CLUSTER_OBJ_NAME = "CLUSTER_NETWORK";
    public static final String NETWORK_HOST_OBJ_NAME = "HOST_NETWORK";
    public static final String PROVIDER_OBJ_NAME = "PROVIDER";
    public static final String PROVIDER_PLU_OBJ_NAME = "PROVIDERS";
    public static final String INSTANCE_TYPE_OBJ_NAME = "INSTANCETYPE";
    public static final String INSTANCE_TYPE_PLU_OBJ_NAME = "INSTANCETYPES";
    public static final String IMAGE_TYPE_OBJ_NAME = "IMAGETYPE";
    public static final String IMAGE_TYPE_PLU_OBJ_NAME = "IMAGETYPES";

    //special searches
    private static final String ALERT = "EVENTS: severity=alert";
    private static final String ERROR = "Events: severity=error";
    private static final String HOST_BY_CPU = "Host: sortby cpu_usage desc";
    private static final String DATACENTER_BY_NAME = "DataCenter: sortby name";
    private static final String VM_BY_STATUS = "Vms: status=Up or status=PoweringUp or status=MigratingTo or status=WaitForLaunch or status=RebootInProgress or status=PoweringDown or status=Paused or status=Unknown sortby cpu_usage desc";

    private static final Set<String> SAFE_SEARCH_EXPR = Collections.unmodifiableSet(new HashSet<String>() {
        {
            final char SEPARATOR = ':';

            add(getName(VDS_OBJ_NAME));
            add(getName(VDS_PLU_OBJ_NAME));
            add(getName(VM_OBJ_NAME));
            add(getName(VM_PLU_OBJ_NAME));
            add(getName(AUDIT_OBJ_NAME));
            add(getName(AUDIT_PLU_OBJ_NAME));
            add(getName(TEMPLATE_OBJ_NAME));
            add(getName(TEMPLATE_PLU_OBJ_NAME));
            add(getName(VDC_USER_OBJ_NAME));
            add(getName(VDC_USER_PLU_OBJ_NAME));
            add(getName(VDC_GROUP_OBJ_NAME));
            add(getName(VDC_GROUP_PLU_OBJ_NAME));
            add(getName(VDC_POOL_OBJ_NAME));
            add(getName(VDC_POOL_PLU_OBJ_NAME));
            add(getName(VDC_CLUSTER_OBJ_NAME));
            add(getName(VDC_CLUSTER_PLU_OBJ_NAME));
            add(getName(VDC_STORAGE_POOL_OBJ_NAME));
            add(getName(VDC_STORAGE_DOMAIN_OBJ_NAME));
            add(getName(VDC_STORAGE_DOMAIN_PLU_OBJ_NAME));
            add(getName(VDC_STORAGE_DOMAIN_IMAGE_OBJ_NAME));
            add(getName(DISK_OBJ_NAME));
            add(getName(DISK_PLU_OBJ_NAME));
            add(getName(GLUSTER_VOLUME_OBJ_NAME));
            add(getName(GLUSTER_VOLUME_PLU_OBJ_NAME));
            add(getName(QUOTA_OBJ_NAME));
            add(getName(QUOTA_PLU_OBJ_NAME));
            add(getName(NETWORK_OBJ_NAME));
            add(getName(NETWORK_PLU_OBJ_NAME));
            add(getName(PROVIDER_OBJ_NAME));
            add(getName(PROVIDER_PLU_OBJ_NAME));
            add(getName(ALERT));
            add(getName(ERROR));
            add(getName(HOST_BY_CPU));
            add(getName(DATACENTER_BY_NAME));
            add(getName(VM_BY_STATUS));
            add(getName(INSTANCE_TYPE_OBJ_NAME));
            add(getName(INSTANCE_TYPE_PLU_OBJ_NAME));
            add(getName(IMAGE_TYPE_OBJ_NAME));
            add(getName(IMAGE_TYPE_PLU_OBJ_NAME));
        }
    });

    private static String getName(String name) {
        return name.toLowerCase() + CommonConstants.QUERY_RETURN_TYPE_SEPARATOR;
    }

    /**
     * Determines if a search expression is safe.
     * @param expr the expression to check.
     * @return boolean
     */
    public static boolean isSafeExpression(String expr) {
        return SAFE_SEARCH_EXPR.contains(expr.toLowerCase());
    }
}


text:
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Orchestrate.Io
{
    public static class RequestExceptionUtility
    {
        public static async Task<RequestException> Make(HttpResponseMessage response)
        {
            string requestId = response.Headers.GetValues("x-orchestrate-req-id").FirstOrDefault();
            string rawJson = await response.Content.ReadAsStringAsync();

            var error = JsonConvert.DeserializeObject<Error>(rawJson);
            if (error != null && error.Code != null)
            {
                if (error.Code.Equals("items_not_found"))
                    return new NotFoundException(response.StatusCode, rawJson, requestId);

                if (error.Code.Equals("api_bad_request"))
                    return new BadRequestException(response.StatusCode, rawJson, requestId);

                if (error.Code.Equals("patch_conflict"))
                    return new PatchConflictException(response.StatusCode, rawJson, requestId);
            }

            return new RequestException(response.StatusCode, rawJson, requestId);
        }
    }
}


text:
FactoryGirl.define do
  factory :course, :class => 'Course' do
    sequence(:name) { |n| "Course #{n}"}
    sequence(:description) { |n| "Description #{n}" }
    sequence(:status) { |n| "#{n}"}
  end
end


text:
#ifndef _ASM_POWERPC_DEBUG_H
#define _ASM_POWERPC_DEBUG_H

#include <asm/hw_breakpoint.h>

struct pt_regs;

extern struct dentry *powerpc_debugfs_root;

#if defined(CONFIG_DEBUGGER) || defined(CONFIG_KEXEC)

extern int (*__debugger)(struct pt_regs *regs);
extern int (*__debugger_ipi)(struct pt_regs *regs);
extern int (*__debugger_bpt)(struct pt_regs *regs);
extern int (*__debugger_sstep)(struct pt_regs *regs);
extern int (*__debugger_iabr_match)(struct pt_regs *regs);
extern int (*__debugger_break_match)(struct pt_regs *regs);
extern int (*__debugger_fault_handler)(struct pt_regs *regs);

#define DEBUGGER_BOILERPLATE(__NAME) \
static inline int __NAME(struct pt_regs *regs) \
{ \
	if (unlikely(__ ## __NAME)) \
		return __ ## __NAME(regs); \
	return 0; \
}

DEBUGGER_BOILERPLATE(debugger)
DEBUGGER_BOILERPLATE(debugger_ipi)
DEBUGGER_BOILERPLATE(debugger_bpt)
DEBUGGER_BOILERPLATE(debugger_sstep)
DEBUGGER_BOILERPLATE(debugger_iabr_match)
DEBUGGER_BOILERPLATE(debugger_break_match)
DEBUGGER_BOILERPLATE(debugger_fault_handler)

#else
static inline int debugger(struct pt_regs *regs) { return 0; }
static inline int debugger_ipi(struct pt_regs *regs) { return 0; }
static inline int debugger_bpt(struct pt_regs *regs) { return 0; }
static inline int debugger_sstep(struct pt_regs *regs) { return 0; }
static inline int debugger_iabr_match(struct pt_regs *regs) { return 0; }
static inline int debugger_break_match(struct pt_regs *regs) { return 0; }
static inline int debugger_fault_handler(struct pt_regs *regs) { return 0; }
#endif

void set_breakpoint(struct arch_hw_breakpoint *brk);
void __set_breakpoint(struct arch_hw_breakpoint *brk);
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
extern void do_send_trap(struct pt_regs *regs, unsigned long address,
			 unsigned long error_code, int signal_code, int brkpt);
#else

extern void do_break(struct pt_regs *regs, unsigned long address,
		     unsigned long error_code);
#endif

#endif /* _ASM_POWERPC_DEBUG_H */


text:
<?php
//core
define('CORE_LIBS', CORE . DS . 'libs');
//helpers
define('CORE_HELPERS', CORE . DS . 'helpers');
//vendors
define('CORE_VENDORS', CORE . DS . 'vendors');


text:
namespace FileSystemSyncher.Commons
{
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;

    public sealed class ConfigurationOptions
    {
        public ConfigurationOptions(string sourceDirectory, string destinationDirectory)
        {
            string sourceFullPath = Path.GetFullPath(sourceDirectory).TrimEnd('\\');
            SourceDirectory = new DirectoryInfo(sourceFullPath);
            if (!SourceDirectory.Exists)
            {
                throw new ConfigurationErrorsException("The folder in the source path does not exist");
            }

            string destinationPath = destinationDirectory;
            if (!string.IsNullOrWhiteSpace(destinationDirectory))
            {
                destinationPath = destinationPath.TrimEnd('\\');
            }

            DestinationDirectory = new DirectoryInfo(destinationPath);

            Whitelist = Enumerable.Empty<string>();
            BlackList = Enumerable.Empty<string>();
        }

        public DirectoryInfo SourceDirectory { get; }

        public DirectoryInfo DestinationDirectory { get; }

        public IEnumerable<string> Whitelist { get; set; }

        public IEnumerable<string> BlackList { get; set; }
    }
}


text:
using namespace cgreen;
#endif

TestSuite *messaging_tests();
TestSuite *assertion_tests();
#ifdef __cplusplus
TestSuite *cpp_assertion_tests();
#endif
TestSuite *vector_tests();
TestSuite *constraint_tests();
TestSuite *parameter_tests();
TestSuite *mock_tests();
TestSuite *breadcrumb_tests();
TestSuite *cute_reporter_tests();
TestSuite *unit_tests();
TestSuite *collector_tests();

int main(int argc, char **argv) {
    int suite_result;
    TestSuite *suite = create_test_suite();
    TestReporter *reporter = create_text_reporter();
    add_suite(suite, messaging_tests());
    add_suite(suite, assertion_tests());
#ifdef __cplusplus
    add_suite(suite, cpp_assertion_tests());
#endif
    add_suite(suite, vector_tests());
    add_suite(suite, constraint_tests());
    add_suite(suite, parameter_tests());
    add_suite(suite, mock_tests());
    add_suite(suite, breadcrumb_tests());
    add_suite(suite, cute_reporter_tests());
    add_suite(suite, unit_tests());
    if (argc > 1) {
        suite_result = run_single_test(suite, argv[1], reporter);
    } else {
        suite_result = run_test_suite(suite, reporter);
    }

    destroy_test_suite(suite);
    destroy_reporter(reporter);

    return suite_result;
}