text:
package com.qingbo.ginkgo.ygb.common.util;

import java.io.IOException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传文件工具类,将文件上传至远程服务器
 * @author hongwei
 * @date 2014-08-06
 */
public class UploadUtil {
	private static Logger logger = LoggerFactory.getLogger(UploadUtil.class);
	private static HttpClient httpClient = HttpClients.createDefault();
	private static ContentType textUtf8 = ContentType.create("text/plain", Consts.UTF_8);

	//上传相关
	private static String upload_direct = "upload_direct";
	private static String upload_contract = "upload_contract";
	private static String upload_temp = "upload_temp";
	private static String upload_confirm = "upload_confirm";
	private static String upload_trash = "upload_trash";

	//存储相关
//	private static String uploads_file = "uploads_file";
//	private static String uploads_temp_file = "uploads_temp_file";
//	private static String uploads_trash_file = "uploads_trash_file";

	//访问相关
//	private static String uploads = "uploads";
//	private static String uploads_temp = "uploads_temp";

	public static String upload(String type, MultipartFile file) {
		return uploadImpl(type, file, GinkgoConfig.getProperty(upload_direct));
	}

	public static String contract(String type, MultipartFile file) {
		return uploadImpl(type, file, GinkgoConfig.getProperty(upload_contract));
	}

	/**
	 * 上传图片到服务器(表单提交时可直接上传图片到服务器/uploads目录)
	 */
	public static String uploadImage(MultipartFile file) {
		return uploadImpl("image", file, GinkgoConfig.getProperty(upload_direct));
	}

	public static String temp(String type, MultipartFile file) {
		return uploadImpl(type, file, GinkgoConfig.getProperty(upload_temp));
	}

	/**
	 * 临时上传文件(通常不会在Controller里使用)
	 */
	public static String tempImage(MultipartFile file) {
		return uploadImpl("image", file, GinkgoConfig.getProperty(upload_temp));
	}

	/**
	 * 确定图片有效(对于uploadify上传的图片,需要确定其有效,并移动文件至/uploads目录,而uploadify默认上传至uploads/temp目录)
	 */
	public static boolean confirm(String path) {
		return pathImpl(path, GinkgoConfig.getProperty(upload_confirm));
	}

	/**
	 * 移动图片到垃圾箱
	 */
	public static boolean trash(String path) {
		return pathImpl(path, GinkgoConfig.getProperty(upload_trash));
	}

	private static String uploadImpl(String type, MultipartFile file, String uri) {
		if(file==null || file.isEmpty()) return null;

		try {
			HttpEntity entity = MultipartEntityBuilder.create()
					.setMode(HttpMultipartMode.RFC6532)
					.addTextBody("type", type, textUtf8)
					.addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY, file.getOriginalFilename())
					.build();

			HttpUriRequest request = RequestBuilder.post()
					.setUri(uri)
					.setEntity(entity)
					.build();

			HttpResponse response = httpClient.execute(request);
			String string = EntityUtils.toString(response.getEntity());
			logger.info("upload "+file.getOriginalFilename()+" ("+file.getSize()/1024+"K) to: " + uri);
			logger.info(string);
			return string;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static boolean pathImpl(String path, String uri) {
		if(path == null || path.length() == 0) return false;

		HttpEntity entity = MultipartEntityBuilder.create()
				.setMode(HttpMultipartMode.RFC6532)
				.addTextBody("path", path, textUtf8)
				.build();

		HttpUriRequest request = RequestBuilder.post()
				.setUri(uri)
				.setEntity(entity)
				.build();

		try {
			HttpResponse response = httpClient.execute(request);
			String string = EntityUtils.toString(response.getEntity());
			boolean result = "1".equals(string);
			logger.info(uri+"?path="+path+" result: "+result);
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}


text:
============
 Development
============

Because the basic data is imported into an environment, users have access to the
full python ecosystem and are encouraged to expand upon these visualizations
and analysis functions.

If you come up with something useful, you can contact the authors
easiest by filing a bug request (either with a bug or feature) on
`the Github site <https://github.com/mattbellis/hmis>`_. You can either send
us snippets of code that we can include in the ``scripts_and_examples`` directory
or fork us and file a *pull request*.

redpajama_set_name: RedPajamaGithub


text:
"""Tests for structs.py"""

from collections import OrderedDict
import unittest

try:
    from unittest.mock import call, MagicMock, patch
except ImportError:
    from mock import call, MagicMock, patch

from convutils import structs

class TestSortedTupleKeysDict(unittest.TestCase):
    """Tests for SortedTupleKeysDict"""

    def setUp(self):
        self.d = structs.SortedTupleKeysDict((
            ((2, 1), 'x'),
            (('a',), 'waka'),
            (('c', 'b'), 'spam')
        ))

    def test_empty_init(self):
        structs.SortedTupleKeysDict()

    def test_contains(self):
        self.assertTrue((1, 2) in self.d)
        self.assertTrue((2, 1) in self.d)
        self.assertTrue(('a',) in self.d)
        self.assertTrue(('b', 'c') in self.d)
        self.assertFalse(('b', 'd') in self.d)

    def test_get(self):
        self.assertEqual(self.d.get(('c', 'b')), 'spam')
        self.assertEqual(self.d.get(('b', 'c')), 'spam')
        self.assertEqual(self.d.get(('b', 'd')), None)

    def test_getitem(self):
        self.assertEqual(self.d[('c', 'b')], 'spam')
        self.assertEqual(self.d[('b', 'c')], 'spam')
        self.assertEqual(self.d[(2, 1)], 'x')

    def test_getitem_raises_key_error(self):
        with self.assertRaises(KeyError):
            self.d[('m', 'n')]

    def test_setitem(self):
        self.d[(2, 1)] = 'y'
        self.assertEqual(self.d[(1, 2)], 'y')
        self.d[('m', 'n')] = 5
        self.assertEqual(self.d[('m', 'n')], 5)

    def test_del(self):
        self.assertTrue((1, 2) in self.d)
        del self.d[(2, 1)]
        self.assertFalse((1, 2) in self.d)

    def test_len(self):
        self.assertEqual(len(self.d), 3)

class TwoWaySetDictTests(unittest.TestCase):

    def setize_kv_pairs(self, kv_pairs):
        """Helper function to turn sets in the values of
        dictionary key-value pairs (items) into frozensets.

        Returns a set of key-value pairs with values as frozensets.

        :param kv_pairs: the key-value pairs from dict.items()

        """
        frozen_kv_pairs = ((k, frozenset(v)) for (k, v) in kv_pairs)
        setized_kv_pairs = set(frozen_kv_pairs)
        return setized_kv_pairs

    def check_items_and_reverse_store(
            self,
            two_way_dict,
            expected_items,
            expected_reverse_store
        ):
        """Check the internals of the two-way dictionary.

        :param two_way_dict: a TwoWaySetDict instance
        :param expected_items: a set of the expected key-value pairs
        :param expected_reverse_store: a dictionary of what's expected
            for TwoWaySetDict._reverse_store()

        """
        items = self.setize_kv_pairs(two_way_dict.items())
        self.assertEqual(items, expected_items)
        self.assertEqual(
                two_way_dict._reverse_store,
                expected_reverse_store
        )

    def setUp(self):
        self.two_way_dict = structs.TwoWaySetDict()

    def test_init_empty(self):
        two_way_dict = structs.TwoWaySetDict()
        expected_items = set()
        expected_reverse_store = {}
        self.check_items_and_reverse_store(
                two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_init_bad_items(self):
        """Check __init__ raises error if items has a value that's not a
        set.

        """
        self.assertRaises(
                ValueError,
                structs.TwoWaySetDict,
                [('a', set([1])), ('b', 2)]
        )

    def test_init_bad_kwargs(self):
        """Check __init__ raises error if **kwargs has a value that's
        not a set.

        """
        try:
            structs.TwoWaySetDict(a=set([1]), b=2)
        except ValueError:
            pass
        else:
            raise AssertionError("ValueError not raised")

    def test_init_with_items(self):
        two_way_dict = structs.TwoWaySetDict(
                [('a', set([1])), ('b', set([1, 2]))]
        )
        expected_items = set([
                ('a', frozenset([1])),
                ('b', frozenset([1, 2]))
        ])
        expected_reverse_store = {1: set(['a', 'b']), 2: set(['b'])}
        self.check_items_and_reverse_store(
                two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_init_with_kwargs(self):
        two_way_dict = structs.TwoWaySetDict(
                a=set([1]),
                b=set([1, 2])
        )
        expected_items = set([
                ('a', frozenset([1])),
                ('b', frozenset([1, 2]))
        ])
        expected_reverse_store = {1: set(['a', 'b']), 2: set(['b'])}
        self.check_items_and_reverse_store(
                two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_init_with_items_and_kwargs(self):
        two_way_dict = structs.TwoWaySetDict(
                [('a', set([3]))],
                a=set([1]),
                b=set([1, 2])
        )
        expected_items = set([
                ('a', frozenset([1])),
                ('b', frozenset([1, 2]))
        ])
        expected_reverse_store = {1: set(['a', 'b']), 2: set(['b'])}
        self.check_items_and_reverse_store(
                two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_setitem_raises_ValueError_if_not_set(self):
        try:
            self.two_way_dict['a'] = 1
        except ValueError:
            pass
        else:
            raise AssertionError("ValueError not raised")

    def test_assign_one_entry(self):
        self.two_way_dict['a'] = set([1])
        expected_items = set([('a', frozenset([1]))])
        expected_reverse_store = {1 : set('a')}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_reassign_entry(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['a'] = set([2, 3])
        expected_items = set([('a', frozenset([2, 3]))])
        expected_reverse_store = {2: set('a'), 3: set('a')}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_insert_multiple_entries_uncommon_value(self):
        self.two_way_dict['a'] = set([1])
        self.two_way_dict['b'] = set([2])
        expected_items = set([
                ('a', frozenset([1])),
                ('b', frozenset([2]))
        ])
        expected_reverse_store = {1: set(['a']), 2: set(['b'])}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_insert_multiple_entries_common_value(self):
        self.two_way_dict['a'] = set([1])
        self.two_way_dict['b'] = set([1])
        expected_items = set([
                ('a', frozenset([1])),
                ('b', frozenset([1]))
        ])
        expected_reverse_store = {1: set(['a', 'b'])}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_insert_entry_multiple_values(self):
        self.two_way_dict['a'] = set([1, 2])
        expected_items = set([('a', frozenset([1, 2]))])
        expected_reverse_store = {1: set(['a']), 2: set(['a'])}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_del_raises_KeyError(self):
        try:
            del self.two_way_dict['unknown key']
        except KeyError:
            pass
        else:
            raise AssertionError("KeyError not raised")

    def test_del_no_item(self):
        self.two_way_dict['a'] = set()
        del self.two_way_dict['a']
        expected_items = set()
        expected_reverse_store = {}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_del_one_key(self):
        self.two_way_dict['a'] = set([1, 2])
        del self.two_way_dict['a']
        expected_items = set()
        expected_reverse_store = {}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_del_multiple_keys(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([2])
        del self.two_way_dict['a']
        expected_items = set([('b', frozenset([2]))])
        expected_reverse_store = {2: set(['b'])}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_copy(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        twd_copy = self.two_way_dict.copy()
        expected_items = set([
                ('a', frozenset([1, 2])),
                ('b', frozenset([1]))
        ])
        expected_reverse_store = {1: set(['a', 'b']), 2: set(['a'])}
        self.check_items_and_reverse_store(
                twd_copy,
                expected_items,
                expected_reverse_store
        )

    def test_clear(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        self.two_way_dict.clear()
        expected_items = set()
        expected_reverse_store = {}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_item_has_key_raises_KeyError(self):
        self.two_way_dict['a'] = set([1, 2])
        self.assertRaises(
                KeyError,
                self.two_way_dict.item_has_key,
                'unknown item',
                'a'
        )

    def test_item_has_key_false(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        result = self.two_way_dict.item_has_key(2, 'b')
        self.assertEqual(result, False)

    def test_item_has_key_true(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        result = self.two_way_dict.item_has_key(2, 'a')
        self.assertEqual(result, True)

    def test_get_item_keys_raises_KeyError(self):
        self.assertRaises(
                KeyError,
                self.two_way_dict.get_item_keys,
                'unknown_item'
        )

    def test_get_item_keys(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        self.assertEqual(
                self.two_way_dict.get_item_keys(1),
                set(['a', 'b'])
        )
        self.assertEqual(
                self.two_way_dict.get_item_keys(2),
                set(['a'])
        )

    def test_add_item_raises_KeyError(self):
        self.assertRaises(
                KeyError,
                self.two_way_dict.add_item,
                'unknown key',
                1
        )

    def test_add_item_empty_set(self):
        self.two_way_dict['a'] = set()
        self.two_way_dict.add_item('a', 1)
        expected_items = set([('a', frozenset([1]))])
        expected_reverse_store = {1: set(['a'])}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_add_item_single_key(self):
        self.two_way_dict['a'] = set([1])
        self.two_way_dict.add_item('a', 2)
        expected_items = set([('a', frozenset([1, 2]))])
        expected_reverse_store = {1: set(['a']), 2: set(['a'])}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_add_item_multiple_keys(self):
        self.two_way_dict['a'] = set([1])
        self.two_way_dict['b'] = set([2])
        self.two_way_dict.add_item('a', 2)
        expected_items = set([
                ('a', frozenset([1, 2])),
                ('b', frozenset([2]))
        ])
        expected_reverse_store = {1: set(['a']), 2: set(['a', 'b'])}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_remove_item_raises_KeyError_key(self):
        self.assertRaises(
                KeyError,
                self.two_way_dict.remove_item,
                'unknown key',
                1
        )

    def test_remove_item_raises_KeyError_item(self):
        self.two_way_dict['a'] = set()
        self.assertRaises(
                KeyError,
                self.two_way_dict.remove_item,
                'a',
                1
        )

    def test_remove_item_single_key(self):
        self.two_way_dict['a'] = set([1])
        self.two_way_dict.remove_item('a', 1)
        expected_items = set([('a', frozenset())])
        expected_reverse_store = {}
        self.check_items_and_reverse_store(
                self.two_way_dict,
                expected_items,
                expected_reverse_store
        )

    def test_remove_item_multiple_keys(self):
        self.two_way_dict['a'] = set([1])
        self.two_way_dict['b'] = set([1])
        self.two_way_dict.remove_item('a', 1)
        expected_items = set([
                ('a', frozenset()),
                ('b', frozenset([1]))
        ])
        expected_reverse_store = {1: set(['b'])}

    def test_remove_item_from_all_keys_raises_KeyError(self):
        self.assertRaises(
                KeyError,
                self.two_way_dict.remove_item_from_all_keys,
                'unknown item'
        )

    def test_remove_item_from_all_keys(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        self.two_way_dict.remove_item_from_all_keys(1)
        expected_items = set([
                ('a', frozenset()),
                ('b', frozenset([2]))
        ])
        expected_reverse_store = {2: set(['b'])}

    def test_len(self):
        self.assertEqual(len(self.two_way_dict), 0)
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        self.assertEqual(len(self.two_way_dict), 2)

    def test_reverse_items(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        expected = [(1, set(('a', 'b'))), (2, set(('a'),))]
        result = list(self.two_way_dict.reverse_iteritems())
        self.assertEqual(result, expected)
        result = self.two_way_dict.reverse_items()
        self.assertEqual(result, expected)

    def test_has_item(self):
        self.two_way_dict['a'] = set([1, 2])
        self.two_way_dict['b'] = set([1])
        self.assertTrue(self.two_way_dict.has_item(1))
        self.assertFalse(self.two_way_dict.has_item(3))

class TestSampleListDict(unittest.TestCase):
    """Tests for sample_list_dict() and sample_list_dict_low_mem()"""

    def setUp(self):
        self.case = OrderedDict((
            ('key1', [1, 5, 9]),
            ('key2', [6, 42]),
            ('key3', [7, 9001])
        ))
        self.expected = {
            'key1': [5, 9],
            'key3': [7]
        }

    def test_sample_list_dict(self):
        sampled_values = [('key1', 5), ('key1', 9), ('key3', 7)]
        randmock = MagicMock(return_value=sampled_values)
        with patch('random.sample', randmock):
            result = structs.sample_list_dict(self.case, 3)
            self.assertEqual(result, self.expected)

    def test_sample_list_dict_low_mem(self):
        randmock = MagicMock(return_value=[1, 2, 5])
        with patch('random.sample', randmock):
            result = structs.sample_list_dict_low_mem(self.case, 1)
            self.assertEqual(result, self.expected)

if __name__ == '__main__':
    unittest.main()


text:
package aima.test.core.unit.logic.planning;

import aima.core.logic.fol.kb.data.Literal;
import aima.core.logic.planning.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * @author samagra
 */
public class LevelTest {
    Problem spareTireProblem;

    @Before
    public void setup() {
        spareTireProblem = PlanningProblemFactory.spareTireProblem();
    }

    @Test
    public void firstLevelTest() {
        Level firstLevel = new Level(null, spareTireProblem, "At(Spare,Trunk)^At(Flat,Axle) ^~At(Spare,Axle)^~At(Flat,Ground)^~At(Spare,Ground)");
        List<Literal> firstLevelExpected = Utils.parse("At(Spare,Trunk)^At(Flat,Axle)" +
                "^~At(Spare,Axle)^~At(Flat,Ground)^~At(Spare,Ground)");
        //test for level objects
        Assert.assertTrue(firstLevel.getLevelObjects().containsAll(firstLevelExpected));
        Assert.assertEquals(7, firstLevel.getLevelObjects().size());
        //test for next links
        Assert.assertEquals(2, firstLevel.getNextLinks().get(firstLevelExpected.get(1)).size());
        Assert.assertEquals(1, firstLevel.getNextLinks().get(firstLevelExpected.get(3)).size());
        ActionSchema removeAction = new ActionSchema("Remove", null,
                "At(Spare,Trunk)",
                "~At(Spare,Trunk)^At(Spare,Ground)");
        Assert.assertTrue(firstLevel.getNextLinks().get(firstLevelExpected.get(0)).contains(removeAction));
    }

    @Test
    public void secondLevelTest() {
        Level firstLevel = new Level(null, spareTireProblem, "At(Spare,Trunk)^At(Flat,Axle) ^~At(Spare,Axle)^~At(Flat,Ground)^~At(Spare,Ground)");
        Level secondLevel = new Level(firstLevel, spareTireProblem);
        //TODO:test for level objects
        Assert.assertEquals(10, secondLevel.getLevelObjects().size());//7 No-ops and three actions
        //TODO:test for next links
        /*for (Object object :
                secondLevel.getNextLinks().keySet()) {
            System.out.println("For=====   "+object.toString());
            for (Object obj :
                    secondLevel.getNextLinks().get(object)) {
                System.out.println(obj.toString());
            }
            System.out.println("*************");
        }*/
        Assert.assertEquals(10, secondLevel.getNextLinks().keySet().size());
        //TODO:Test for mutexes
        /*for (Object object :
        secondLevel.getMutexLinks().keySet()) {
            System.out.println("For=====   "+object.toString());
            for (Object obj :
                    secondLevel.getMutexLinks().get(object)) {
                System.out.println("With ==="+obj.toString());
            }
            System.out.println("*************");
        }*/
        //TODO:test for previous links
        /*for (Object object :
                secondLevel.getPrevLinks().keySet()) {
            System.out.println("For=====   " + object.toString());
            for (Object obj :
                    secondLevel.getPrevLinks().get(object)) {
                System.out.println(obj.toString());
            }
            System.out.println("*************");
        }*/

    }

    @Test
    public void thirdLevelTest() {
        Level firstLevel = new Level(null, spareTireProblem, "At(Spare,Trunk)^At(Flat,Axle) ^~At(Spare,Axle)^~At(Flat,Ground)^~At(Spare,Ground)");
        Level secondLevel = new Level(firstLevel, spareTireProblem);
        Level thirdLevel = new Level(secondLevel, spareTireProblem);
        //TODO:Test for level objects
        /*for (Object obj :
                thirdLevel.getLevelObjects()) {
            System.out.println(obj.toString());
        }
        */
        //TODO:Test for nextLinks
        /*for (Object object :
                thirdLevel.getNextLinks().keySet()) {
            System.out.println("For=====   "+object.toString());
            for (Object obj :
                    thirdLevel.getNextLinks().get(object)) {
                System.out.println(obj.toString());
            }
            System.out.println("*************");
        }*/
        //TODO:Test for mutex links
        /*for (Object object :
                thirdLevel.getMutexLinks().keySet()) {
            System.out.println("For=====   "+object.toString());
            for (Object obj :
                    thirdLevel.getMutexLinks().get(object)) {
                System.out.println("With ==="+obj.toString());
            }
            System.out.println("*************");
        }*/
        //TODO:test for prev links
        /*for (Object object :
                thirdLevel.getPrevLinks().keySet()) {
            System.out.println("For=====   " + object.toString());
            for (Object obj :
                    thirdLevel.getPrevLinks().get(object)) {
                System.out.println(obj.toString());
            }
            System.out.println("*************");
        }*/
    }
}


text:
<?php

interface IModel
{

    /**
     * Accepts a SQL query as a string
     * and execute it into the database.
     *
     * @param $query
     * @param array $params
     * @return bool|DataObject
     */
    function query ($query, $params = NULL);

    /**
     */

    /**
     * Accepts a SQL query as a string
     * and executes it into the database.
     * Afterwards it returns the selected data as a DataObject.
     *
     * @param $query
     * @param array $params
     * @return bool|DataObject
     */
    function fetch ($query, $params = NULL);

    /**
     * Accepts a SQL query as a string
     * and executes it into the database.
     * Afterwards it returns the selected data as an array with DataObjects.
     *
     * @param $query
     * @param array $params
     * @return bool|DataObject
     */
    function fetchAll ($query, $params = NULL);

}


text:
<?php

namespace Stillat\Numeral\Languages;

/*
 * Original notice
 * -------------------------------------------------------------
 *
 * numbro.js language configuration
 * language : Swedish
 * locale : Sweden
 * author : Benjamin Van Ryseghem (benjamin.vanryseghem.com)
 */

class Language_svSE extends AbstractLanguage
{
    public static $code = 'sv-SE';

    protected $delimiters = [
        'thousands' => ' ',
        'decimal' => ','
    ];

    protected $currency = [
        'symbol' => 'kr',
        'position' => 'postfix',
        'spaceSeparated' => true
    ];

    protected $abbreviations = [
        'thousand' => 't',
        'million' => 'M',
        'billion' => 'md',
        'trillion' => 'tmd'
    ];

}


text:
package com.google.security.zynamics.binnavi.debug.connection.packets.replyparsers;

import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.debug.connection.DebugCommandType;
import com.google.security.zynamics.binnavi.debug.connection.interfaces.ClientReader;
import com.google.security.zynamics.binnavi.debug.connection.packets.parsers.MessageParserException;
import com.google.security.zynamics.binnavi.debug.connection.packets.parsers.RegisterValuesParser;
import com.google.security.zynamics.binnavi.debug.connection.packets.replies.RegistersReply;
import com.google.security.zynamics.binnavi.debug.models.targetinformation.RegisterValues;

import java.io.IOException;

/**
 * Parser responsible for parsing replies to Read Registers requests.
 */
public final class RegistersParser extends AbstractReplyParser<RegistersReply> {
  /**
   * Creates a new Read Registers reply parser.
   *
   * @param clientReader Used to read messages sent by the debug client.
   */
  public RegistersParser(final ClientReader clientReader) {
    super(clientReader, DebugCommandType.RESP_REGISTERS_SUCCESS);
  }

  @Override
  protected RegistersReply parseError(final int packetId) throws IOException {
    return new RegistersReply(packetId, parseInteger(), null);
  }

  @Override
  public RegistersReply parseSuccess(final int packetId, final int argumentCount)
      throws IOException {
    final byte[] data = parseData();
    try {
      final RegisterValues registerValues = RegisterValuesParser.parse(data);
      return new RegistersReply(packetId, 0, registerValues);
    } catch (final MessageParserException exception) {
      CUtilityFunctions.logException(exception);
      return new RegistersReply(packetId, PARSER_ERROR, null);
    }
  }
}


text:
var fs = require('fs');
var path = require('path');
var Options = require('wrap-options');

function die(message) {
    console.error('[CONFIG]', message);
    process.exit(1);
}

var configPath = process.env.CONFIG || process.argv[2];

if (!configPath) {
    die('Config path missing');
}

configPath = path.resolve(configPath);

function parse(configText) {
    return new Options(JSON.parse(configText));
}

function loadSync() {
    var configText = fs.readFileSync(configPath, { encoding: 'utf8' });
    return parse(configText);
}

function load(callback) {
    fs.readFile(configPath, { encoding: 'utf8' }, function (err, configText) {
        var config;
        try {
            config = parse(configText);
        } catch (err) {
            return callback(new Error('Invalid config file: ' + err.message));
        }

        callback(null, config);
    });
}

var reloadListeners = [];

function watch(onReload) {
    reloadListeners.push(onReload);
}

function reload(callback) {
    load(function (error, config) {
        callback = callback || function () {};
        if (error) {
            callback(error);
        } else {
            exports.__proto__ = config;
            reloadListeners.forEach(function (listener) {
                listener(exports);
            });
            callback();
        }
    });
}

function Config() {
    this.watch = watch;
    this.reload = reload;
}

exports = module.exports = new Config();

try {
    exports.__proto__ = loadSync();
} catch (err) {
    die('Invalid config file: ' + err.message);
}


text:
"""Treadmill Identity Group CLI

Create, delete and manage identity groups.
"""

from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

import logging

import click

from treadmill import cli
from treadmill import context
from treadmill import restclient

_LOGGER = logging.getLogger(__name__)

_EXCEPTIONS = []
_EXCEPTIONS.extend(restclient.CLI_REST_EXCEPTIONS)

_ON_EXCEPTIONS = cli.handle_exceptions(_EXCEPTIONS)

_REST_PATH = '/identity-group/'

def init():  # pylint: disable=R0912
    """Configures identity group."""
    formatter = cli.make_formatter('identity-group')
    ctx = {}

    @click.group()
    @click.option('--cell', required=True,
                  envvar='TREADMILL_CELL',
                  callback=cli.handle_context_opt,
                  expose_value=False)
    @click.option('--api', help='API url to use.',
                  metavar='URL',
                  envvar='TREADMILL_RESTAPI')
    def monitor_group(api):
        """Manage identity group configuration"""
        ctx['api'] = api

    @monitor_group.command()
    @click.option('-n', '--count', type=int, help='Identity count')
    @click.argument('name')
    @_ON_EXCEPTIONS
    def configure(count, name):
        """Configure application monitor"""
        restapi = context.GLOBAL.cell_api(ctx['api'])
        url = _REST_PATH + name

        if count is not None:
            data = {'count': count}
            try:
                _LOGGER.debug('Creating identity group: %s', name)
                restclient.post(restapi, url, payload=data)
            except restclient.AlreadyExistsError:
                _LOGGER.debug('Updating identity group: %s', name)
                restclient.put(restapi, url, payload=data)

        _LOGGER.debug('Retrieving identity group: %s', name)
        monitor_entry = restclient.get(restapi, url)
        cli.out(formatter(monitor_entry.json()))

    @monitor_group.command(name='list')
    @_ON_EXCEPTIONS
    def _list():
        """List configured identity groups"""
        restapi = context.GLOBAL.cell_api(ctx['api'])
        response = restclient.get(restapi, '/identity-group/')
        cli.out(formatter(response.json()))

    @monitor_group.command()
    @click.argument('name', nargs=1, required=True)
    @_ON_EXCEPTIONS
    def delete(name):
        """Delete identity group"""
        restapi = context.GLOBAL.cell_api(ctx['api'])
        url = _REST_PATH + name
        restclient.delete(restapi, url)

    del delete
    del _list
    del configure

    return monitor_group


text:
package com.choimeetsworld.reminder.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.choimeetsworld.reminder.database.Database;
import com.choimeetsworld.reminder.models.Notification;
import com.choimeetsworld.reminder.utils.NotificationUtil;

public class SnoozeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Database database = new Database(context.getApplicationContext());
        Notification notification = database.getNotification(intent.getIntExtra("NOTIFICATION_ID", 0));
        NotificationUtil.createNotification(context, notification, intent);
        database.close();
    }
}


text:
class WorkshopInvitation < ActiveRecord::Base
  include InvitationConcerns

  belongs_to :workshop
  has_one :waiting_list, foreign_key: :invitation_id

  validates :workshop, :member, presence: true
  validates :member_id, uniqueness: { scope: %i[workshop_id role] }
  validates_inclusion_of :role, in: ['Student', 'Coach'], allow_nil: true

  scope :year, -> (year) { joins(:workshop).where('EXTRACT(year FROM workshops.date_and_time) = ?', year) }
  scope :accepted, -> { where(attending: true) }
  scope :attended, -> { where(attended: true) }
  scope :to_students, -> { where(role: 'Student') }
  scope :to_coaches, -> { where(role: 'Coach') }
  scope :order_by_latest, -> { joins(:workshop).order('workshops.date_and_time desc') }
  scope :last_six_months, -> { joins(:workshop).where(workshops: { date_and_time: 6.months.ago...Time.zone.now}) }
  scope :not_reminded, -> { where(reminded_at: nil) }
  scope :on_waiting_list, -> { joins(:waiting_list) }

  def waiting_list_position
    @waiting_list_position ||= WaitingList.by_workshop(self.workshop)
                                          .where_role(self.role)
                                          .where(auto_rsvp: true)
                                          .order(:created_at)
                                          .map(&:invitation_id)
                                          .index(self.id) + 1
  end

  def parent
    workshop
  end

  def email
    if for_student?
      WorkshopInvitationMailer.invite_student(self.workshop, self.member, self).deliver_now
    end
  end
end


text:
/*
 * This file re-exports all symbols contained in this directory.
 *
 * Why is this file not `index.ts`?
 *
 * There seems to be an inconsistent path resolution of an `index.ts` file
 * when only the parent directory is referenced. This could be due to the
 * node module resolution configuration differing from rollup and/or typescript.
 *
 * With commit
 * https://github.com/angular/angular/commit/d5e3f2c64bd13ce83e7c70788b7fc514ca4a9918
 * the `instructions.ts` file was moved to `instructions/instructions.ts` and an
 * `index.ts` file was used to re-export everything. Having had file names that were
 * importing from `instructions' directly (not the from the sub file or the `index.ts`
 * file) caused strange CI issues. `index.ts` had to be renamed to `all.ts` for this
 * to work.
 *
 * Jira Issue = FW-1184
 */
export * from './alloc_host_vars';
export * from './attribute';
export * from './attribute_interpolation';
export * from './change_detection';
export * from './container';
export * from './storage';
export * from './di';
export * from './element';
export * from './element_container';
export * from './embedded_view';
export * from './get_current_view';
export * from './interpolation';
export * from './listener';
export * from './namespace';
export * from './next_context';
export * from './projection';
export * from './property';
export * from './property_interpolation';
export * from './select';
export * from './styling';
export {styleSanitizer as ɵɵstyleSanitizer} from '../styling_next/instructions';
export * from './text';
export * from './text_interpolation';


text:
package org.compass.annotations.test.reference;

import java.util.ArrayList;

import org.compass.annotations.test.AbstractAnnotationsTestCase;
import org.compass.core.CompassHits;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;
import org.compass.core.config.CompassConfiguration;

/**
 * @author kimchy
 */
public class ReferenceTests extends AbstractAnnotationsTestCase {

    protected void addExtraConf(CompassConfiguration conf) {
        conf.addClass(A.class).addClass(B.class);
    }

    public void testSimpleReference() {
        CompassSession session = openSession();
        CompassTransaction tr = session.beginTransaction();

        A a = new A();
        a.id = 1;
        a.value = "avalue";

        B b = new B();
        b.id = 1;
        b.value = "bvalue";
        a.b = b;

        B b1 = new B();
        b1.id = 2;
        b1.value = "bvalue1";

        B b2 = new B();
        b2.id = 3;
        b2.value = "bvalue2";
        ArrayList<B> bValues = new ArrayList<B>();
        bValues.add(b1);
        bValues.add(b2);
        a.bValues = bValues;

        session.save(b);
        session.save(b1);
        session.save(b2);
        session.save(a);

        a = (A) session.load(A.class, 1);
        assertEquals("avalue", a.value);
        assertEquals("bvalue", a.b.value);
        assertEquals("bvalue1", a.bValues.get(0).value);
        assertEquals("bvalue2", a.bValues.get(1).value);
        b = (B) session.load(B.class, 1);
        assertEquals("bvalue", b.value);

        CompassHits hits = session.find("bvalue");
        assertEquals(1, hits.length());
        b = (B) hits.data(0);
        assertEquals("bvalue", b.value);

        hits = session.find("avalue");
        assertEquals(1, hits.length());
        a = (A) hits.data(0);
        assertEquals("avalue", a.value);
        assertEquals("bvalue", a.b.value);

        tr.commit();
        session.close();
    }

}


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System;

namespace Sce.Atf
{
    ///
    /// Interface for documents
    public interface IDocument : IResource
    {
        ///
        /// Gets whether the document is read-only
        bool IsReadOnly
        {
            get;
        }

        ///
        /// Gets or sets whether the document is dirty (does it differ from its file)
        bool Dirty
        {
            get;
            set;
        }

        ///
        /// Event that is raised when the Dirty property changes
        event EventHandler DirtyChanged;
    }
}


text:
<?php

namespace Magento\Email\Model\Template;

class Config
{
    /**
     * @var \Magento\Email\Model\Template\Config\Data
     */
    protected $_dataStorage;

    /**
     * @var \Magento\Framework\Module\Dir\Reader
     */
    protected $_moduleReader;

    /**
     * @param \Magento\Email\Model\Template\Config\Data $dataStorage
     * @param \Magento\Framework\Module\Dir\Reader $moduleReader
     */
    public function __construct(
        \Magento\Email\Model\Template\Config\Data $dataStorage,
        \Magento\Framework\Module\Dir\Reader $moduleReader
    ) {
        $this->_dataStorage = $dataStorage;
        $this->_moduleReader = $moduleReader;
    }

    /**
     * Retrieve unique identifiers of all available email templates
     *
     * @return string[]
     */
    public function getAvailableTemplates()
    {
        return array_keys($this->_dataStorage->get());
    }

    /**
     * Retrieve translated label of an email template
     *
     * @param string $templateId
     * @return string
     */
    public function getTemplateLabel($templateId)
    {
        return __($this->_getInfo($templateId, 'label'));
    }

    /**
     * Retrieve type of an email template
     *
     * @param string $templateId
     * @return string
     */
    public function getTemplateType($templateId)
    {
        return $this->_getInfo($templateId, 'type');
    }

    /**
     * Retrieve fully-qualified name of a module an email template belongs to
     *
     * @param string $templateId
     * @return string
     */
    public function getTemplateModule($templateId)
    {
        return $this->_getInfo($templateId, 'module');
    }

    /**
     * Retrieve full path to an email template file
     *
     * @param string $templateId
     * @return string
     */
    public function getTemplateFilename($templateId)
    {
        $module = $this->getTemplateModule($templateId);
        $file = $this->_getInfo($templateId, 'file');
        return $this->_moduleReader->getModuleDir('view', $module) . '/email/' . $file;
    }

    /**
     * Retrieve value of a field of an email template
     *
     * @param string $templateId Name of an email template
     * @param string $fieldName Name of a field value of which to return
     * @return string
     * @throws \UnexpectedValueException
     */
    protected function _getInfo($templateId, $fieldName)
    {
        $data = $this->_dataStorage->get();
        if (!isset($data[$templateId])) {
            throw new \UnexpectedValueException("Email template '{$templateId}' is not defined.");
        }
        if (!isset($data[$templateId][$fieldName])) {
            throw new \UnexpectedValueException(
                "Field '{$fieldName}' is not defined for email template '{$templateId}'."
            );
        }
        return $data[$templateId][$fieldName];
    }
}


text:
- Toggle should be a button.
- Toggle should have `aria-haspopup` attribute set to `true`.
- Should use keyboard model advocated under [ARIA Practices](https://www.w3.org/TR/wai-aria-practices/#menu)
-- Space or enter should toggle the menu
-- If button has focus, pressing down should open the menu, else moves focus within into the menu.
-- When menu is open, up and down controls move focus within the menu.
-- Menu can be closed by pressing `Escape`.


text:
package abra;

import java.io.IOException;

import joptsimple.OptionParser;
import joptsimple.OptionSet;

/**
 * Abstract base class for helping with options parsing.
 *
 * @author Lisle E. Mose (lmose at unc dot edu)
 */
public abstract class Options {
	protected static final String HELP = "help";

	private OptionSet options;

    protected void printHelp() {
        try {
        	getOptionParser().printHelpOn(System.err);
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("IOException encountered when attempting to output help.");
        }
    }

    public void parseOptions(String[] args) {

        try {
            options = getOptionParser().parse(args);

            if (options.has(HELP)) {
                printHelp();
            } else {
                validate();
            }
        } catch (joptsimple.OptionException e) {
            System.err.println(e.getMessage());
            printHelp();
        }
    }

    protected OptionSet getOptions() {
    	return options;
    }

    abstract protected OptionParser getOptionParser();

    abstract protected void validate();
}


text:
/** Automatically generated file. DO NOT MODIFY */
package com.frrahat.cricscorer;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="popup.css">

__MSG_popupUnlockerText__

      <input id="password-input" type="password">
      <button id="unlock-btn">__MSG_popupUnlockerBtnText__</button>

          __MSG_extensionName__

            <input type="text" placeholder="example.com">
            ⊕

__MSG_popupValidationErrorText__

            <select></select>

            __MSG_popupRemoveSiteText__

            __MSG_imgBlockText__

↓

__MSG_mediaBlockText__

__MSG_videoHideText__

__MSG_flashHideText__

__MSG_canvasHideText__

__MSG_svgHideText__

          __MSG_leaveReview__
          __MSG_closeButton__


text:
typedef __complex__ double Value;
struct LorentzVector
{
  LorentzVector & operator+=(const LorentzVector & a) {
    theX += a.theX;
    theY += a.theY;
    theZ += a.theZ;
    theT += a.theT;
    return *this;
  }

  Value theX;
  Value theY;
  Value theZ;
  Value theT;
};

inline LorentzVector
operator+(LorentzVector a, const LorentzVector & b) {
  return a += b;
}

Value ex, et;
LorentzVector sum() {
  LorentzVector v1; v1.theX =ex; v1.theY =ex+et; v1.theZ =ex-et;   v1.theT =et;
  return v1+v1;
}


text:
$(document).ready(function() {
    // Set the selected page
    var page = $("meta[name='selected_page']").attr('content');
    if (page) {
        $("."+page).addClass("selected");
    }

    // Show flash status
    if (!$("#flash").hasClass('hidden')) {
        hideFlash();
    }
});

(function($) {
    $.mustache = function(template, view, partials) {
        return Mustache.to_html(template, view, partials);
    };
})(jQuery);

$( function() {
        $('.list .checkbox input:checkbox').click(update_context_selector);
        if ($('.list .checkbox').length != 0) {
            $('.ShiftCheckbox').shiftcheckbox();
        }
});

/* Generate fragment of random numbers */
jQuery._uuid_default_prefix = '';
jQuery._uuidlet = function () {
  return (((1+Math.random())*0x10000|0).toString(16).substring(1));
};

/* Generates random uuid */
jQuery.uuid = function (p) {
	if (typeof(p) == 'object' && typeof(p.prefix) == 'string') {
		jQuery._uuid_default_prefix = p.prefix;
	} else {
		p = p || jQuery._uuid_default_prefix || '';
		return(p+jQuery._uuidlet()+jQuery._uuidlet()+"-"+jQuery._uuidlet()+"-"+jQuery._uuidlet()+"-"+jQuery._uuidlet()+"-"+jQuery._uuidlet()+jQuery._uuidlet()+jQuery._uuidlet());
	};
};

function toggle_checked() {
    var c_status = $("meta[name='check_status']").attr('content');
    var new_status = (c_status=='false') ? true : false;
    $("meta[name='check_status']").attr('content', new_status);
    var node_list = $('.list .checkbox input:checkbox');
    node_list.attr('checked', new_status);
    var row = node_list.parent().parent();

    if (new_status == true) {
        row.addClass('context-menu-selection');
    } else {
        row.removeClass('context-menu-selection');
    }
}

function update_context_selector() {
    var row = $(this).parent().parent();

    if($(this).attr('checked')) {
        row.addClass('context-menu-selection');
    } else {
        row.removeClass('context-menu-selection');
    }
}

function toggleFieldset(field) {
    var parent_field = $(field).parent();

    if (parent_field.hasClass('collapsed')) {
        parent_field.removeClass('collapsed');
        parent_field.children("div").slideDown();
    } else {
        parent_field.addClass('collapsed');
        parent_field.children("div").slideUp();
    }
}

function hideFlash() {
    $("#flash").delay(2000)
        .animate({height: 0, opacity: 0}, 'slow', null,
                function() {
                $("#flash").addClass('hidden');
            });
}

function showFlash() {
    $("#flash").removeClass('hidden');
    hideFlash();
}

function clear_checked() {
    // Remove the checkboxes
    $(".list input[type='checkbox']:checked")
        .each(function () {
            $(this).attr('checked', false);
            $(this).parent().parent()
                .removeClass('context-menu-selection');
        });

    // Remove any extra variables set in the outgoing params
}

function apply_function() {
    if ($('#cb_add_group').attr('checked')) {
        var selected = $("#function").val();
        this['run_'+ selected]();
    } else {
        document.query_form.submit();
    }
}

function run_add_group() {
    var selected = $("#selected_group").val();
    var ids = new Array();

    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nodes/addgroups',
        data: {'groups': selected, 'ids': ids},
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_remove_group() {
    var selected = $("#selected_group").val();
    var ids = new Array();

    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nodes/removegroups',
        data: { 'groups': selected, 'ids': ids },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_disable_host() {
    var ids = new Array();
    var pool = $("input[name='pool']").val();
    var ports = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
            ports.push($(this).parent()
                  .parent().find(".port").text());
        });

    $.ajax({
        url: '/loadbalancer/disablehost.json',
        data: { 'ids': ids , 'pool': pool, 'ports': ports },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });

}

function run_enable_host() {
    var ids = new Array();
    var pool = $("input[name='pool']").val();
    var ports = new Array();

    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
            ports.push($(this).parent()
                      .parent().find(".port").text());
            });

    $.ajax({
        url: '/loadbalancer/enablehost.json',
        data: { 'ids': ids, 'pool': pool, 'ports': ports },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_add_lb() {
    var ids = new Array();
    var pool = $("#selected_group").val();
    var port = $("#lb_port").val();
    var ports = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });
    for (id in ids) {
        ports.push(port);
    }
    $.ajax({
        url: '/loadbalancer/addhost.json',
        data: { 'ids': ids, 'pool': pool, 'ports': ports },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_remove_lb() {
    var ids = new Array();
    var pool = $("input[name='pool']").val();
    var ports = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
            ports.push($(this).parent()
                      .parent().find(".port").text());
        });

    $.ajax({
        url: '/loadbalancer/removehost.json',
        data: { 'ids': ids, 'pool': pool, 'ports': ports },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_enable_nagios() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nodes/nagios/enable',
        data: { 'ids': ids },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_disable_nagios() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nodes/nagios/disable',
        data: { 'ids': ids },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_enable_puppet() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nodes/puppet/enable',
        data: { 'ids': ids },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_disable_puppet() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nodes/puppet/disable',
        data: { 'ids': ids },
        success: function(data) {
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_edit_flags() {
    $.ajax({
        url: '/nodes/flags/edit',
        success: function(data) {
                $.modal(data);
        }
    });
}

function run_clear_flags() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nodes/flags/clear',
        data:  { 'ids': ids },
        success: function(data) {
        }
    });

    // Remove scheduled downtime
    $.ajax({
        url: '/nagios/remove_host_downtime',
        type: 'POST',
        data: JSON.stringify({ 'data' : {
              'ids': ids }
        }),
        success: function(data) {
          console.log(data);
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function call_update_flags() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
                ids.push(parseInt($(this).attr('name')));
            });

    var flags = new Array();
    $("#simplemodal-data input[type='checkbox']:checked")
        .each(function() {
                flags.push($(this).attr('name'));
            });

    var description = $("#simplemodal-data textarea")
        .attr('value');
    var username = $("#simplemodal-data input[name='user']")
        .attr('value');

    if (!description) {
        alert('Description can not be empty');
        return null;
    }

    var d = new Date();
    var month = d.getMonth() + 1;
    var date = d.getDate();
    var hours = d.getHours();
    var minutes = d.getMinutes();
    var ampm = 'am';
    if (month < 10) {
      month = '0' + month;
    }
    if (date < 10) {
      date = '0' + date;
    }
    if (hours < 12) {
      ampm = 'am';
    } else {
      ampm = 'pm';
    }
    if (hours > 12) {
      hours = hours - 12;
    }
    if (hours < 10) {
      hours = '0' + hours;
    }
    if (minutes < 10) {
      minutes = '0' + minutes;
    }
    var start_time = month + '/' + date + '/' + d.getUTCFullYear() +
      ' ' + hours + ':' + minutes + ' ' + ampm;
    var end_time = '';

    $.ajax({
        url: '/nodes/flags/update',
          data: { 'ids': ids,
            'flags': flags,
            'description': description,
            'user': username },
          success: function(data) {
          $.ajax({
              url: '/nagios/schedule_host_downtime',
              type: 'POST',
              data: JSON.stringify({ 'data' : {
                    'ids': ids,
                    'start_time': start_time,
                    'end_time': end_time,
                    'comment': 'Downtime for: ' + flags.join(', '),
                    'author': username,}
                }),
              success: function(data) {
                console.log(data);
              }
            });
        }
      });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function run_export_csv() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    var href = '/nodes/export_csv?';
    var first = true;
    for (id in ids) {
        if (!first) { href += '&'; }
        href += "ids[]=" + ids[id];
        if (first) { first = false; }
    }
    window.location = href;
}

function run_batch_edit() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
            ids.push(parseInt($(this).attr('name')));
        });

    var href = '/nodes/batchedit?';
    var first = true;
    href += 'field=' + $('#selected_field').val();
    for (id in ids) {
        href += '&';
        href += "ids[]=" + ids[id];
    }
    window.location = href;
}

function run_nagios_options() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
             ids.push(parseInt($(this).attr('name')));
        });
    var sel_func = $('#selected_function').val();
    $.ajax({
            url: '/nagios/' + sel_func,
            type: "GET",
            data: { 'ids': ids },
            success: function(data) {
                if (sel_func == 'schedule_downtime') {
                    $.modal(data);
                    $("#start_time").datetimepicker({
                            ampm: true
                        });
                    $("#end_time").datetimepicker({
                            ampm: true
                                });
                    $("#start_time").blur();
                } else {
                    console.log(data);
                }
            }
        });

    $(this).ajaxStop(function() {
            if (sel_func != 'schedule_downtime') {
                location.reload(true);
            }
    });
}

function run_update_game() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
             ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/games/batch_update_games',
        type: 'POST',
          data: JSON.stringify({
            'ids': ids,
            'game': $('#game').val()
          }),
        success: function(data) {
            console.log(data);
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function flash_error(message) {
}

function add_filter() {
    var select = $("#add_filter_select");
    var field = select.val();
    $("#tr_" + field).attr('style', '');
    $("#cb_" + field).attr('checked', 'true');
    toggle_filter(field);
    select.val(0);

    $("#add_filter_select option[value="+field+"]")
        .attr('disabled', 'disabled');
}

function remove_filters() {
    if ($('#cb_add_group').attr('checked')) {
        if (!$('#filters').hasClass('collapsed')) {
            toggleFieldset('#filters legend');
        }

        $("#filters input[type='checkbox']").attr('checked', '');
        $('#add_filter_select option').attr('disabled', '');

    } else {
        toggleFieldset($('#options legend'));
        toggleFieldset($('#filters legend'));
    }
}

function toggle_filter(field) {
    //console.log(field);
}

function toggle_operator(field) {
    //console.log('operator toggled: %s');
}

function update_options() {
    var selected_func = $('#function').val();

    if (selected_func == 'add_group' ||
            selected_func == 'remove_group') {
        $.ajax({
            url: '/menus/grouplist',
            data: {},
            type: "POST",
            success: function(data) {
                $('.selected_secondary').html(data);
            }
        });
        $('#options_info').html('');
        $('#options_info').attr('style', 'display: none;');
        $('.selected_secondary').html(' Loading...');
    } else if (selected_func == 'enable_host' ||
            selected_func == 'disable_host') {
        $('#options_info').html('');
        $('#options_info').attr('style', '');
        $('.selected_secondary').html('');
    } else if (selected_func == 'add_lb') {
        $.ajax({
            url: '/menus/loadbalancerlist',
            data: {},
            type: "POST",
            success: function(data) {
                $('.selected_secondary').html(data);
            }
        });
        $('#options_info').html('Port: <input type="text" name="port" id="lb_port">');
        $('#options_info').attr('style', '');
        $('.selected_secondary').html(' Loading...');
    } else if (selected_func == 'batch_edit') {
        $.ajax({
            url: '/menus/batcheditlist',
            data: {},
            type: "POST",
            success: function(data) {
                $('#options_info').html(data);
            }
        });
    } else if (selected_func == 'nagios_options') {
        $.ajax({
            url: '/menus/nagios',
            data: {},
            type: "POST",
            success: function(data) {
                $('#options_info').html(data);
            }
        });
    } else if (selected_func == 'update_game') {
      $.ajax({
          url: '/menus/games',
          data: {},
          type: "POST",
          success: function(data) {
            $('#options_info').html(data);
          }
        });
    } else {
        $('#options_info').html('');
        $('#options_info').attr('style', '');
        $('.selected_secondary').html('');
    }
}

function call_schedule_downtime() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
             ids.push(parseInt($(this).attr('name')));
        });
    var start_time = $('#start_time').val();
    var end_time = $('#end_time').val();
    var comment = $('#comment').val();
    var author = $('#loggedas a').text();

    $.ajax({
        url: '/nagios/schedule_host_downtime',
        type: 'POST',
            data: JSON.stringify({ 'data' : {
            'ids': ids,
            'start_time': start_time,
            'end_time': end_time,
            'comment': comment,
            'author': author,}
        }),
        success: function(data) {
            console.log(data);
        }
        });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function call_enable_host_svc() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
             ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nagios/enable_host_svc',
        type: 'POST',
        data: { 'ids': ids },
        success: function(data) {
            console.log(data);
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function call_disable_host_svc() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
             ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nagios/disable_host_svc',
        type: 'POST',
        data: { 'ids': ids, },
        success: function(data) {
            console.log(data);
        }
    });

    $(this).ajaxStop(function() {
        location.reload(true);
    });
}

function call_remove_all_monitors() {
    var ids = new Array();
    $(".list input[type='checkbox']:checked")
        .each(function() {
             ids.push(parseInt($(this).attr('name')));
        });

    $.ajax({
        url: '/nagios/remove_all_monitors',
        type: 'POST',
        data: { 'ids': ids, },
        success: function(data) {
            console.log(data);
        }
    });
}

function create_downtime_date(d) {
  function pad(n) {
    return n<10 ? '0'+n : n;
  }

  return d.getUTCFullYear()+'-'
    + pad(d.getUTCMonth()+1)+'-'
    + pad(d.getUTCDate())+'T'
    + pad(d.getUTCHours())+':'
    + pad(d.getUTCMinutes())+':'
    + pad(d.getUTCSeconds())+'Z'
}


text:
#include <memory>
#include <string>

#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/tensor_util.h"
#include "paddle/fluid/operators/collective/c_embedding_op.h"
#include "paddle/fluid/platform/device/npu/npu_info.h"
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"

namespace paddle {
namespace operators {

template <typename T>
inline void FillNPU(Tensor *dst,
                    T val,
                    const framework::ExecutionContext &context) {
  Tensor value(dst->type());
  value.mutable_data<T>({1}, context.GetPlace());
  FillNpuTensorWithConstant<T>(&value, static_cast<T>(val));

  auto stream =
      context.template device_context<paddle::platform::NPUDeviceContext>()
          .stream();

  const auto &runner = NpuOpRunner(
      "FillD", {value}, {*dst}, {{"dims", phi::vectorize(dst->dims())}});
  runner.Run(stream);
}

template <typename T>
void shard_index(const Tensor &table_t,
                 const Tensor &ids_t,
                 int64_t start_idx,
                 const Tensor &id_t,
                 const framework::ExecutionContext &context) {
  const int height = table_t.dims()[0];

  auto stream =
      context.template device_context<paddle::platform::NPUDeviceContext>()
          .stream();
  phi::DenseTensor id_t_d;
  id_t_d.mutable_data<T>(ids_t.dims(), context.GetPlace());
  FillNPU(&id_t_d, static_cast<T>(0.0), context);
  id_t_d.Resize(ids_t.dims());

  phi::DenseTensor id_t_u;
  id_t_u.mutable_data<T>(ids_t.dims(), context.GetPlace());
  FillNPU(&id_t_u, static_cast<T>(height - 1), context);
  id_t_u.Resize(ids_t.dims());

  phi::DenseTensor id_matched_d;
  id_matched_d.mutable_data<bool>(ids_t.dims(), context.GetPlace());
  phi::DenseTensor id_matched_u;
  id_matched_u.mutable_data<bool>(ids_t.dims(), context.GetPlace());
  phi::DenseTensor ignore_tensor;
  ignore_tensor.mutable_data<T>(ids_t.dims(), context.GetPlace());
  FillNPU(&ignore_tensor, static_cast<T>(height), context);
  ignore_tensor.Resize(ids_t.dims());

  NpuOpRunner sub_runner;
#if (CANN_VERSION_CODE >= 503003)
  Tensor factor_tensor(ids_t.type());
  factor_tensor.mutable_data<T>({1}, context.GetPlace());
  paddle::framework::TensorFromVector(std::vector<T>{static_cast<T>(start_idx)},
                                      context.device_context(),
                                      &factor_tensor);
  sub_runner.SetType("Sub")
      .AddInput(ids_t)
      .AddInput(factor_tensor)
      .AddOutput(id_t);
#else
  sub_runner.SetType("Sub")
      .AddInput(ids_t)
      .AddInput(std::vector<T>{static_cast<T>(start_idx)})
      .AddOutput(id_t);
#endif
  sub_runner.Run();

  NpuOpRunner lessequal1_runner;
  lessequal1_runner.SetType("LessEqual")
      .AddInput(id_t)
      .AddInput(id_t_u)
      .AddOutput(id_matched_u);
  lessequal1_runner.Run();

  NpuOpRunner lessequal2_runner;
  lessequal2_runner.SetType("LessEqual")
      .AddInput(id_t_d)
      .AddInput(id_t)
      .AddOutput(id_matched_d);
  lessequal2_runner.Run();

  NpuOpRunner("Equal", {id_matched_u, id_matched_d}, {id_matched_d}, {})
      .Run(stream);
  NpuOpRunner("Select", {id_matched_d, id_t, ignore_tensor}, {id_t}, {})
      .Run(stream);
}

template <typename TIds, typename T>
void NPUGetIdsEmbedding(const framework::ExecutionContext &context) {
  auto *table_t = context.Input<LoDTensor>("W");
  auto *ids_t = context.Input<LoDTensor>("Ids");
  auto *output_t = context.Output<LoDTensor>("Out");
  const int64_t start_idx = context.Attr<int64_t>("start_index");

  auto stream =
      context.template device_context<paddle::platform::NPUDeviceContext>()
          .stream();

  phi::DenseTensor ids_t_local;
  ids_t_local.mutable_data<TIds>(ids_t->dims(), context.GetPlace());
  shard_index<TIds>(*table_t, *ids_t, start_idx, ids_t_local, context);

  auto pad_shape = phi::make_ddim({table_t->dims()[0] + 1, table_t->dims()[1]});
  phi::DenseTensor table_t_pad;

  size_t mem_size = table_t->numel() * phi::SizeOf(table_t->dtype());
  size_t line_mem_size = table_t->dims()[1] * phi::SizeOf(table_t->dtype());
  PADDLE_ENFORCE_EQ(line_mem_size % 64,
                    0,
                    platform::errors::InvalidArgument(
                        "NPU only accept the second dim must align by 64"));

  VLOG(10) << "mem_size:" << mem_size << ",line_mem_size:" << line_mem_size
           << ", pad_shape:" << pad_shape << ", table_dims:" << table_t->dims();

  uint8_t *pad_data = reinterpret_cast<uint8_t *>(
      table_t_pad.mutable_data<T>(pad_shape, context.GetPlace()));
  platform::NPUMemcpyAsync(pad_data,
                           table_t->data<T>(),
                           mem_size,
                           ACL_MEMCPY_DEVICE_TO_DEVICE,
                           stream,
                           mem_size);
  platform::NPUMemsetAsync(
      pad_data + mem_size, 0, line_mem_size, stream, line_mem_size);

  output_t->mutable_data<T>(context.GetPlace());
  NpuOpRunner runner;
  runner.SetType("GatherV2")
      .AddInput(table_t_pad)
      .AddInput(ids_t_local)
      .AddInput(std::vector<int32_t>{0})
#if (CANN_VERSION_CODE >= 503003)
      .AddAttrs({{"batch_dims", 0}})
#endif
      .AddOutput(*output_t);
  runner.Run();
}

template <typename T>
class CEmbeddingNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    auto *ids_t = context.Input<LoDTensor>("Ids");

    const auto &index_type = framework::TransToProtoVarType(ids_t->dtype());
    if (index_type == framework::proto::VarType::INT32) {
      NPUGetIdsEmbedding<int32_t, T>(context);
    } else {
      PADDLE_THROW(platform::errors::Unavailable(
          "NPU c_embedding ids only support int32."));
    }
  }
};

template <typename TIds, typename T>
void NPUUpdateEmbedding(const framework::ExecutionContext &context) {
  // get inputs
  const int64_t start_idx = context.Attr<int64_t>("start_index");
  auto ids_t = context.Input<LoDTensor>("Ids");
  auto d_output_t = context.Input<LoDTensor>(framework::GradVarName("Out"));
  auto table_t = context.Input<phi::DenseTensor>("W");
  auto table_grad_t = context.Output<LoDTensor>(framework::GradVarName("W"));

  VLOG(10) << "ids_t:" << ids_t << ", d_output_t:" << d_output_t
           << ", table_t:" << table_t << ", table_grad_t" << table_grad_t;

  auto stream =
      context.template device_context<paddle::platform::NPUDeviceContext>()
          .stream();

  // convert ids_t to local valid
  phi::DenseTensor ids_t_local;
  ids_t_local.mutable_data<TIds>(ids_t->dims(), context.GetPlace());
  shard_index<TIds>(*table_t, *ids_t, start_idx, ids_t_local, context);

  // padding table_t -> table_t_pad
  auto pad_shape = phi::make_ddim({table_t->dims()[0] + 1, table_t->dims()[1]});
  phi::DenseTensor table_t_pad;

  // set table_t_pad to zero
  uint8_t *pad_data = reinterpret_cast<uint8_t *>(
      table_t_pad.mutable_data<T>(pad_shape, context.GetPlace()));
  size_t table_t_pad_mem_size =
      table_t_pad.numel() *
      framework::SizeOfType(
          framework::TransToProtoVarType(table_t_pad.dtype()));
  platform::NPUMemsetAsync(
      pad_data, 0, table_t_pad_mem_size, stream, table_t_pad_mem_size);

  // NOTE(zhiqiu): It seems in cann 20.1, the first input and output
  // can be different tensor, but in cann 20.2+, it does inplace operation.
  // Thus, the first input and output should be same tensor.
  const auto &runner_scatter =
      NpuOpRunner("ScatterAdd",
                  {table_t_pad, ids_t_local, *d_output_t},
                  {table_t_pad},
                  {{"use_locking", true}});
  runner_scatter.Run(stream);

  // copy table_t_pad to table_t
  T *dst = table_grad_t->mutable_data<T>(table_t->dims(), context.GetPlace());
  const size_t mem_size =
      table_grad_t->numel() * phi::SizeOf(table_grad_t->dtype());

  // check align
  size_t line_mem_size =
      table_grad_t->dims()[1] * phi::SizeOf(table_grad_t->dtype());
  PADDLE_ENFORCE_EQ(line_mem_size % 64,
                    0,
                    platform::errors::InvalidArgument(
                        "NPU only accept the second dim must align by 64"));

  platform::NPUMemcpyAsync(
      dst, pad_data, mem_size, ACL_MEMCPY_DEVICE_TO_DEVICE, stream, mem_size);
}

template <typename T>
class CEmbeddingGradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    auto *ids_t = context.Input<LoDTensor>("Ids");

    const auto &index_type = framework::TransToProtoVarType(ids_t->dtype());
    if (index_type == framework::proto::VarType::INT32) {
      NPUUpdateEmbedding<int32_t, T>(context);
    } else {
      PADDLE_THROW(
          platform::errors::Unavailable("c_embedding ids only support int32."));
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;
REGISTER_OP_NPU_KERNEL(c_embedding,
                       ops::CEmbeddingNPUKernel<float>,
                       ops::CEmbeddingNPUKernel<double>,
                       ops::CEmbeddingNPUKernel<plat::float16>);
REGISTER_OP_NPU_KERNEL(c_embedding_grad,
                       ops::CEmbeddingGradNPUKernel<float>,
                       ops::CEmbeddingGradNPUKernel<double>,
                       ops::CEmbeddingGradNPUKernel<plat::float16>);


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

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:singleLine="true"
        android:textColor="@color/black_primary_text"
        android:textSize="16sp"
        tools:text="Library Title"
        />

    <TextView
        android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:singleLine="false"
        android:textColor="@color/black_primary_text"
        android:textSize="12sp"
        tools:text="Library Description"
        />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="8dp"
        android:background="@color/black_dividers"
        />

</LinearLayout>


text:
import React from 'react';
import toaster from 'toastr';
import { mount } from 'enzyme';
import { CreateDocument } from '../../components/CreateDocument';
import mockData from '../../../server/tests/mockData';

toaster.info = jest.fn(message => '');
const mockUser = mockData.regularUser;
const mockDocument = mockData.document;
mockDocument.createdAt = new Date().toDateString();
mockDocument.id = 1;
mockDocument.owner = 1;

const mockBtn = {
  target: {
    id: 'public',
    value: 'public',
    name: 'accessRight'
  }
};
const mockEvent = {
  preventDefault: jest.fn(),
  target: {
    name: 'password',
    value: 'test'
  }
};

const setup = () => {
  const props = {
    createDocStatus: '',
    errorMessage: '',
    upsertDocument: jest.fn(),
    getDocument: jest.fn(),
    match: {
      params: {
        documentId: 1
      }
    }
  };
  const Wrapper = mount(
    <CreateDocument {...props} />
  );
  return {
    props,
    Wrapper
  };
};

describe('Create Document components', () => {
  const { Wrapper, props } = setup();
  Wrapper.setProps({
    document: mockDocument,
    status: 'success'
  });

  it('should render a required textbox for document title', () => {
    const txtTitle = Wrapper.find('#title').props();
    expect(txtTitle.required).toEqual(true);
    expect(txtTitle.placeholder).toEqual('Title');
    expect(txtTitle.className).toEqual('validate');
  });

  it('should render a group radio button for document access rights', () => {
    const rdbPrivate = Wrapper.find('#private').props();
    expect(rdbPrivate.id).toEqual('private');

    const rdbPublic = Wrapper.find('#public').props();
    expect(rdbPublic.id).toEqual('public');

    const rdbRole = Wrapper.find('#role').props();
    expect(rdbRole.id).toEqual('role');

    const myDocumentsTab = Wrapper.find('#public').props();
    myDocumentsTab.onChange(mockBtn);
    const stateAccessRight = Wrapper.state('accessRight');
    expect(stateAccessRight).toBe(mockBtn.target.id);
  });

  describe('submit button', () => {
    const btnSubmit = Wrapper.find('#btnsubmit').props();

    it('should have a type "submit" ', () => {
      expect(btnSubmit.type).toBe('submit');
    });

    it('should call the saveDocument action when every field is valid ', () => {
           // set user profile in localstorage
      localStorage.setItem('userInfo', JSON.stringify(mockUser));
      Wrapper.setState({
        accessRight: 'role'
      });
      const btnSubmit1 = Wrapper.find('#btnsubmit').props();
      btnSubmit1.onClick(mockEvent);
      expect(props.upsertDocument.mock.calls.length).toBe(1);
    });

    it('should display a message, when a fields is invalid', () => {
      const btnSubmit2 = Wrapper.find('#btnsubmit').props();
      Wrapper.setState({
        accessRight: null,
        title: 'ab'
      });
      btnSubmit2.onClick(mockEvent);
      const messageState = Wrapper.state('message');
      const isSubString = messageState.includes('Please');
      expect(isSubString).toEqual(true);
    });
  });

  it('should display a message from \'upsertDocument\' actions', () => {
    Wrapper.setProps({
      messageFrom: 'upsertDocument',
      message: 'document has been updated successfully',
    });
    const messageState = Wrapper.state('message');
    const isSubString = messageState.includes('successfully');
    expect(isSubString).toEqual(true);
  });
});


text:
package com.cidic.sdx.dggl.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.cidic.sdx.dggl.dao.FeedbackDao;
import com.cidic.sdx.dggl.model.Feedback;
import com.cidic.sdx.dggl.model.HotMatchModel;

@Repository
@Component
@Qualifier(value = "feedbackDaoImpl")
public class FeedbackDaoImpl implements FeedbackDao {

	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	@Override
	public void createFeedback(Feedback feedback) {
		Session session = sessionFactory.getCurrentSession();
		session.save(feedback);
	}

	@Override
	public List<HotMatchModel> getFeedbackListPageByUserId(int userId,int limit, int offset) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "select m.innerClothId as innerClothId,m.outClothId as outClothId, m.trousersId as trousersId,"
				+ "f.userId as userId,m.id as matchlistId,m.modelurl as modelurl,"
				+ " count(*) as countLike from Feedback f inner join f.matchlist m where f.userId = ? group by f.matchlist order by countLike";
		Query query = session.createQuery(hql);
        query.setParameter(0, userId);
        query.setFirstResult(offset);
        query.setMaxResults(limit);
        @SuppressWarnings("unchecked")
		List list = query.list();

        List<HotMatchModel> hotList = new ArrayList<HotMatchModel>(10);
        HotMatchModel hotMatchModel = null;
        for(int i=0;i<list.size();i++)
        {
        	hotMatchModel = new HotMatchModel();
            Object []o = (Object[])list.get(i);
            int innerClothId = (Integer)o[0];
            int outClothId = (Integer)o[1];
            int trousersId = (Integer)o[2];
            int userid = (Integer)o[3];
            int matchlistId = (Integer)o[4];
            String modelurl = (String)o[5];
            int countLike = ((Number)o[6]).intValue();
            hotMatchModel.setModelurl(modelurl);
            hotMatchModel.setInnerClothId(innerClothId);
            hotMatchModel.setOutClothId(outClothId);
            hotMatchModel.setTrousersId(trousersId);
            hotMatchModel.setUserId(userid);
            hotMatchModel.setMatchlistId(matchlistId);
            hotMatchModel.setCountLike(countLike);
            hotList.add(hotMatchModel);
        }
        return hotList;
	}

	@Override
	public List<HotMatchModel> getTopThreeDataByUserId(int userId){
		Session session = sessionFactory.getCurrentSession();
		String hql = "select m.innerClothId as innerClothId,m.outClothId as outClothId, m.trousersId as trousersId,f.userId as userId,"
				+ " m.id as matchlistId,m.modelurl as modelurl,"
				+ " count(*) as countLike from Feedback f inner join f.matchlist m where f.userId = ? group by f.matchlist order by countLike";
		Query query = session.createQuery(hql);
        query.setParameter(0, userId);
        query.setFirstResult(0);
        query.setMaxResults(3);
        @SuppressWarnings("unchecked")
		List list = query.list();

        List<HotMatchModel> hotList = new ArrayList<HotMatchModel>(3);
        HotMatchModel hotMatchModel = null;
        for(int i=0;i<list.size();i++)
        {
        	hotMatchModel = new HotMatchModel();
            Object []o = (Object[])list.get(i);
            int innerClothId = (Integer)o[0];
            int outClothId = (Integer)o[1];
            int trousersId = (Integer)o[2];
            int userid = (Integer)o[3];
            int matchlistId = (Integer)o[4];
            String modelurl = (String)o[5];
            int countLike = ((Number)o[6]).intValue();
            hotMatchModel.setModelurl(modelurl);
            hotMatchModel.setInnerClothId(innerClothId);
            hotMatchModel.setOutClothId(outClothId);
            hotMatchModel.setTrousersId(trousersId);
            hotMatchModel.setUserId(userid);
            hotMatchModel.setMatchlistId(matchlistId);
            hotMatchModel.setCountLike(countLike);
            hotList.add(hotMatchModel);
        }
        return hotList;
	}

	public Optional<Feedback> getFeedbackByUserIdAndMatchlistID(int userId, int matchlistId, int vipId){
		Session session = sessionFactory.getCurrentSession();
		String hql = " from Feedback where userId = ? and matchlistId = ? and vipId = ?";
		Query query = session.createQuery(hql);
		query.setParameter(0, userId);
        query.setParameter(1, matchlistId);
        query.setParameter(2, vipId);
        query.setMaxResults(1);
        query.setCacheable(true);
        Optional<Feedback> optFeedback = Optional.ofNullable((Feedback)query.uniqueResult());
        return optFeedback;
	}

	public int deleteFeedback(int userId, int matchlistId){
		Session session = sessionFactory.getCurrentSession();
		String sql = " delete from feedback where likeId= " + userId + " and matchlistId=" + matchlistId;
		Query query = session.createSQLQuery(sql);
		return query.executeUpdate();
	}

	@Override
	public List<String> getFeedbackVipName(int userId, int matchlistId) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "select v.vipname from Feedback f, Vipuser v where f.vipId = v.id and f.userId = ? and matchlistId = ?";
		Query query = session.createQuery(hql);
        query.setParameter(0, userId);
        query.setParameter(1, matchlistId);
        query.setFirstResult(0);
        query.setMaxResults(9);
        @SuppressWarnings("unchecked")
		List list = query.list();

        List<String> listResult = new ArrayList<String>(10);

        for(int i=0;i<list.size();i++)
        {
            listResult.add((String)list.get(i));
        }
        return listResult;
	}

	@Override
	public List<Feedback> getFeedbackDataByVipIdAndMatchlistIds(List<Integer> ids, int vipId, int userId) {
		Session session = sessionFactory.getCurrentSession();
		String hql = " from Feedback f where f.vipId = (:vipId) and f.userId = (:userId) and f.matchlist.id in (:ids)";
		Query query = session.createQuery(hql);
		query.setParameter("vipId", vipId);
        query.setParameterList("ids", ids);
        query.setParameter("userId", userId);
        @SuppressWarnings("unchecked")
        List<Feedback> list = query.list();
		return list;
	}

	@Override
	public List<HotMatchModel> getFeedbackListPage(int limit, int offset) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "select m.innerClothId as innerClothId,m.outClothId as outClothId, m.trousersId as trousersId,"
				+ "f.userId as userId,m.id as matchlistId,m.modelurl as modelurl,"
				+ " count(*) as countLike from Feedback f inner join f.matchlist m group by f.matchlist order by countLike desc";
		Query query = session.createQuery(hql);
        query.setFirstResult(offset);
        query.setMaxResults(limit);
        @SuppressWarnings("unchecked")
		List list = query.list();

        List<HotMatchModel> hotList = new ArrayList<HotMatchModel>(10);
        HotMatchModel hotMatchModel = null;
        for(int i=0;i<list.size();i++)
        {
        	hotMatchModel = new HotMatchModel();
            Object []o = (Object[])list.get(i);
            int innerClothId = (Integer)o[0];
            int outClothId = (Integer)o[1];
            int trousersId = (Integer)o[2];
            int userid = (Integer)o[3];
            int matchlistId = (Integer)o[4];
            String modelurl = (String)o[5];
            int countLike = ((Number)o[6]).intValue();
            hotMatchModel.setModelurl(modelurl);
            hotMatchModel.setInnerClothId(innerClothId);
            hotMatchModel.setOutClothId(outClothId);
            hotMatchModel.setTrousersId(trousersId);
            hotMatchModel.setUserId(userid);
            hotMatchModel.setMatchlistId(matchlistId);
            hotMatchModel.setCountLike(countLike);
            hotList.add(hotMatchModel);
        }
        return hotList;
	}

	@Override
	public int getFeedbackCount() {
		Session session = sessionFactory.getCurrentSession();
		String sql = "select count(*) from (select count(*) from feedback feedback0_  inner join matchlist matchlist1 on feedback0_.matchlistId=matchlist1.Id  group by"
				+ " feedback0_.matchlistId  ) countFeedback";
		Query query = session.createSQLQuery(sql);

        return Integer.parseInt(query.uniqueResult().toString());
	}
}


text:
// This file is part of Hangfire.
// Copyright © 2013-2014 Sergey Odinokov.
//
// Hangfire is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3
// of the License, or any later version.
//
// Hangfire is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with Hangfire. If not, see <http://www.gnu.org/licenses/>.

using System;
using Hangfire.Storage;

namespace Hangfire.States
{
    public class ApplyStateContext : StateContext
    {
        public ApplyStateContext(StateContext context, IState newState, string oldStateName)
            : base(context)
        {
            if (newState == null) throw new ArgumentNullException("newState");

            OldStateName = oldStateName;
            NewState = newState;
            JobExpirationTimeout = TimeSpan.FromDays(1);
        }

        // Hiding the connection from filters, because their methods are being
        // executed inside a transaction. This property can break them.
        private new IStorageConnection Connection { get { return base.Connection; } }

        public string OldStateName { get; private set; }
        public IState NewState { get; private set; }
        public TimeSpan JobExpirationTimeout { get; set; }
    }
}