text:
from __future__ import absolute_import, print_function

import os
from commoncode.testcase import FileBasedTesting

from textcode import analysis
from textcode .analysis import Token

from licensedcode import detect
from licensedcode.detect import LicenseMatch
from licensedcode.models import Rule
from licensedcode import models
from unittest.case import skipIf

TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')

"""
Test the core license detection mechanics.
"""

class TestLicenseMatch(FileBasedTesting):
    test_data_dir = TEST_DATA_DIR

    def test_single_contained_matche_is_filtered(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=5), score=100)
        contained = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=4), score=100)
        m5 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        result = detect.filter_overlapping_matches([m1, contained, m5])
        assert [m1, m5] == result

    def test_multiple_contained_matches_are_filtered(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=5), score=100)

        r2 = Rule(text_file='r2', licenses=['apache-2.0', 'gpl'])
        contained1 = LicenseMatch(rule=r2, query_position=analysis.Token(start=1, end=2), score=100)

        r3 = Rule(text_file='r3', licenses=['apache-2.0', 'gpl'])
        contained2 = LicenseMatch(rule=r3, query_position=analysis.Token(start=3, end=4), score=100)

        r5 = Rule(text_file='r5', licenses=['apache-2.0', 'gpl'])
        m5 = LicenseMatch(rule=r5, query_position=analysis.Token(start=1, end=6), score=100)

        result = detect.filter_overlapping_matches([m1, contained1, contained2, m5])
        assert [m1, m5] == result

    def test_multiple_nested_contained_matches_are_filtered(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=5), score=100)
        contained = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=4), score=100)
        in_contained = LicenseMatch(rule=r1, query_position=analysis.Token(start=2, end=3), score=100)
        m5 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        result = detect.filter_overlapping_matches([m1, contained, in_contained, m5])
        assert [m1, m5] == result

    def test_contained_matches_are_filtered(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        contained1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=5), score=100)
        same_span1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)
        same_span2 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        result = detect.filter_overlapping_matches([contained1, same_span1, same_span2])
        assert [contained1, same_span2] == result

    def test_contiguous_non_overlapping_matches_are_not_filtered(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=2), score=100)
        m2 = LicenseMatch(rule=r1, query_position=analysis.Token(start=3, end=6), score=100)
        m5 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        result = detect.filter_overlapping_matches([m1, m2, m5])
        assert [m1, m5] == result

    def test_non_contiguous_matches_are_not_filtered(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=2), score=100)
        m2 = LicenseMatch(rule=r1, query_position=analysis.Token(start=4, end=6), score=100)
        m5 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        result = detect.filter_overlapping_matches([m1, m2, m5])
        assert [m1, m5] == result

    def test_non_contiguous_or_overlapping_contained_matches_are_filtered(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=2), score=100)
        m2 = LicenseMatch(rule=r1, query_position=analysis.Token(start=3, end=6), score=100)
        m3 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)
        m4 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=7), score=100)
        m5 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        result = detect.filter_overlapping_matches([m1, m2, m3, m4, m5])
        assert [m4] == result

    def test_non_contiguous_or_overlapping_contained_matches_touching_boundaries_are_filtered(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=2), score=100)

        r2 = Rule(text_file='r2', licenses=['apache-2.0', 'gpl'])
        m2 = LicenseMatch(rule=r2, query_position=analysis.Token(start=3, end=7), score=100)

        r3 = Rule(text_file='r3', licenses=['apache-2.0', 'gpl'])
        m3 = LicenseMatch(rule=r3, query_position=analysis.Token(start=0, end=6), score=100)

        r6 = Rule(text_file='r6', licenses=['apache-2.0', 'gpl'])
        m6 = LicenseMatch(rule=r6, query_position=analysis.Token(start=1, end=7), score=100)

        r5 = Rule(text_file='r5', licenses=['apache-2.0', 'gpl'])
        m5 = LicenseMatch(rule=r5, query_position=analysis.Token(start=1, end=6), score=100)

        r4 = Rule(text_file='r4', licenses=['apache-2.0', 'gpl'])
        m4 = LicenseMatch(rule=r4, query_position=analysis.Token(start=0, end=7), score=100)

        result = detect.filter_overlapping_matches([m1, m2, m3, m4, m5, m6])
        assert [m4] == result

    def test_matches_with_same_span_are_filtered_if_licenses_are_different(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=2), score=100)
        r2 = Rule(text_file='r2', licenses=['apache-1.1'])
        m2 = LicenseMatch(rule=r2, query_position=analysis.Token(start=0, end=2), score=100)
        m5 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        result = detect.filter_overlapping_matches([m1, m2, m5])
        assert [m2, m5] == result

    def test_matches_with_same_span_are_filtered_if_licenses_are_the_same(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=2), score=100)
        m5 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        r2 = Rule(text_file='r2', licenses=['apache-2.0'])
        m2 = LicenseMatch(rule=r2, query_position=analysis.Token(start=0, end=2), score=100)

        result = detect.filter_overlapping_matches([m1, m2, m5])
        assert [m2, m5] == result

    def test_matches_with_same_span_are_filtered_if_licenses_are_the_same_with_different_expressions(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=2), score=100)
        m5 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)

        r2 = Rule(text_file='r2', licenses=['gpl', 'apache-2.0'])
        m2 = LicenseMatch(rule=r2, query_position=analysis.Token(start=0, end=2), score=100)

        result = detect.filter_overlapping_matches([m1, m2, m5])
        assert [m2, m5] == result

    def test_matches_with_partially_overlapping_spans_are_merged_if_license_are_the_same(self):
        r1 = Rule(text_file='r1', licenses=['apache-1.1'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=10), score=100)
        m2 = LicenseMatch(rule=r1, query_position=analysis.Token(start=1, end=6), score=100)
        r2 = Rule(text_file='r2', licenses=['gpl', 'apache-2.0'])
        m3 = LicenseMatch(rule=r2, query_position=analysis.Token(start=5, end=15), score=100)

        result = detect.filter_overlapping_matches([m1, m2, m3])
        assert [m1, m3] == result

    def test_match_is_same(self):
        r1 = Rule(text_file='r1', licenses=['apache-2.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=2))
        r2 = Rule(text_file='r2', licenses=['gpl', 'apache-2.0'])
        m2 = LicenseMatch(rule=r2, query_position=analysis.Token(start=0, end=2))

        assert m1.is_same(m2)
        assert m2.is_same(m1)

    def test_match_is_not_same(self):
        r1 = Rule(text_file='r1', licenses=['apache-1.0', 'gpl'])
        m1 = LicenseMatch(rule=r1, query_position=analysis.Token(start=0, end=2))
        r2 = Rule(text_file='r2', licenses=['gpl', 'apache-2.0'])
        m2 = LicenseMatch(rule=r2, query_position=analysis.Token(start=0, end=2))

        assert not m1.is_same(m2)
        assert not m2.is_same(m1)

        r3 = Rule(text_file='r3', licenses=['apache-1.0', 'gpl'])
        m3 = LicenseMatch(rule=r3, query_position=analysis.Token(start=0, end=2))

        assert m1.is_same(m3)
        assert m3.is_same(m1)

        r4 = Rule(text_file='r4', licenses=['apache-1.0', 'gpl'])
        m4 = LicenseMatch(rule=r4, query_position=analysis.Token(start=1, end=2))

        assert not m1.is_same(m4)
        assert not m4.is_same(m1)

class TestDetectLicenseRule(FileBasedTesting):
    test_data_dir = TEST_DATA_DIR

    def create_test_file(self, text):
        tf = self.get_temp_file()
        with open(tf, 'wb') as of:
            of.write(text)
        return tf

    def test_match_with_empty_query_does_not_return_matches(self):
        ftr = Rule(text_file=self.create_test_file('A one. A two. A three.'))
        index = detect.LicenseIndex([ftr])
        matches = index.match([''])
        assert [] == matches

    def test_match_does_not_return_incorrect_matches(self):
        ftr = Rule(text_file=self.create_test_file('A one. A two. A three.'))
        index = detect.LicenseIndex([ftr])
        docs = [
            u'some other path', u'some junk',
            u'some path', u'some other junk'
        ]
        for d in docs:
            matches = index.match([d])
            assert [] == matches

    def test_match_index_return_one_match_with_correct_offsets(self):
        ftr = Rule(text_file=self.create_test_file('A one. A two. A three.'))
        index = detect.LicenseIndex([ftr])
        query_doc = (u'/some/path/', u'some junk. A one. A two. A three.')
        #                              t1   t2    t3 t4  t5 t6  t7 t8
        #                                         1111111111222222222233
        #                              012345678901234567890123456789012

        matches = index.match([query_doc[1]])
        assert 1 == len(matches)
        match = matches[0]
        qpos = match.query_position
        # abs pos are zero-based
        # lines are one-based, char are zero-based on line
        expected = Token(start=2, end=7,
                         start_line=1, start_char=11,
                         end_line=1, end_char=32,)
        assert expected == qpos

    def test_simple_detection_against_same_text(self):
        tf1 = self.get_test_loc('detect/mit/mit.c')
        ftr = Rule(text_file=tf1, licenses=['mit'])
        index = detect.LicenseIndex([ftr])

        matches = index.match(tf1)
        assert 1 == len(matches)
        match = matches[0]
        assert ftr == match.rule
        assert 0 == match.span.start
        assert 86 == match.span.end

    def test_simple_detection_exact(self):
        tf1 = self.get_test_loc('detect/mit/mit.c')
        ftr = Rule(text_file=tf1, licenses=['mit'])
        index = detect.LicenseIndex([ftr])

        tf2 = self.get_test_loc('detect/mit/mit2.c')
        matches = index.match(tf2)
        assert 1 == len(matches)
        match = matches[0]
        assert ftr == match.rule
        assert 5 == match.span.start
        assert 91 == match.span.end

    def test_simple_detection_exact2(self):
        tf1 = self.get_test_loc('detect/mit/mit.c')
        ftr = Rule(text_file=tf1, licenses=['mit'])
        index = detect.LicenseIndex([ftr])

        tf2 = self.get_test_loc('detect/mit/mit3.c')
        matches = index.match(tf2)
        assert 1 == len(matches)
        match = matches[0]
        assert ftr == match.rule
        assert 0 == match.span.start
        assert 86 == match.span.end

    def test_simple_detection_exact_should_return_no_result(self):
        tf1 = self.get_test_loc('detect/mit/mit.c')
        ftr = Rule(text_file=tf1, licenses=['mit'])
        index = detect.LicenseIndex([ftr])

        tf2 = self.get_test_loc('detect/mit/mit4.c')
        matches = index.match(tf2, minimum_score=100)
        assert not matches

    def test_simple_detection_text_shorter_than_ngram_len_using_trigrams(self):
        tf1 = self.get_test_loc('detect/string/mit.txt')
        ftr = Rule(text_file=tf1, licenses=['mit'])
        index = detect.LicenseIndex([ftr])  # default to ngram_len=3

        tf2 = self.get_test_loc('detect/string/mit2.txt')
        tf3 = self.get_test_loc('detect/string/mit3.txt')
        tf4 = self.get_test_loc('detect/string/mit4.txt')

        docs = [
            (tf1, 1, [Token(start=0, start_line=1, start_char=0, end_line=1, end_char=11, end=1)]),
            (tf4, 1, [Token(start=1, start_line=1, start_char=4, end_line=1, end_char=15, end=2)]),
            (tf2, 2, [Token(start=6, start_line=1, start_char=20, end_line=1, end_char=31, end=7),
                      Token(start=8, start_line=1, start_char=32, end_line=1, end_char=43, end=9)]),
            (tf3, 2, [Token(start=6, start_line=1, start_char=20, end_line=1, end_char=31, end=7),
                      Token(start=8, start_line=2, start_char=0, end_line=2, end_char=11, end=9)]),
        ]

        for loc, expect_mlen, expect_matches_posits in docs:
            matches = list(index.match(loc))
            assert expect_mlen == len(matches)
            for i, m in enumerate(matches):
                expected_pos = expect_matches_posits[i]
                assert expected_pos == m.query_position

    def test_bsd_rule_detection(self):
        tf1 = self.get_test_loc('detect/mit/t1.txt')
        ftr = Rule(text_file=tf1, licenses=['bsd-original'])
        index = detect.LicenseIndex([ftr])

        test_doc = self.get_test_loc('detect/mit/t2.txt')
        matches = index.match(test_doc)
        assert 1 == len(matches)
        expected = Token(start=0, start_line=1, start_char=0, end_line=27, end_char=59, end=241)
        assert expected == matches[0].query_position

    def check_detection(self, doc_file, rule_file, expected_matches):
        test_rule = self.get_test_loc(rule_file)
        ftr = Rule(text_file=test_rule, licenses=['mit'])
        index = detect.LicenseIndex([ftr])

        test_doc = self.get_test_loc(doc_file)
        matches = index.match(test_doc)
        assert 1 == len(matches)
        assert expected_matches == matches[0].query_position

    def test_comment_format_1(self):
        expected = Token(start=0, start_line=1, start_char=2, end_line=9, end_char=52, end=86)
        self.check_detection('detect/commentformat/license2.txt', 'detect/commentformat/license1.txt', expected)

    def test_comment_format_2(self):
        expected = Token(start=0, start_line=1, start_char=3, end_line=9, end_char=53, end=86)
        self.check_detection('detect/commentformat/license3.txt', 'detect/commentformat/license1.txt', expected)

    def test_comment_format_3(self):
        expected = Token(start=0, start_line=1, start_char=3, end_line=9, end_char=53, end=86)
        self.check_detection('detect/commentformat/license4.txt', 'detect/commentformat/license1.txt', expected)

    def test_comment_format_4(self):
        expected = Token(start=0, start_line=1, start_char=0, end_line=10, end_char=50, end=86)
        self.check_detection('detect/commentformat/license5.txt', 'detect/commentformat/license1.txt', expected)

    def test_comment_format_5(self):
        expected = Token(start=0, start_line=1, start_char=2, end_line=9, end_char=52, end=86)
        self.check_detection('detect/commentformat/license6.txt', 'detect/commentformat/license1.txt', expected)

    def test_comment_format_6(self):
        expected = Token(start=0, start_line=1, start_char=2, end_line=9, end_char=52, end=86)
        self.check_detection('detect/commentformat/license6.txt', 'detect/commentformat/license3.txt', expected)

    def test_special_characters_detection(self):
        tf1 = self.get_test_loc('detect/specialcharacter/kerberos.txt')
        tf2 = self.get_test_loc('detect/specialcharacter/kerberos1.txt')
        tf3 = self.get_test_loc('detect/specialcharacter/kerberos2.txt')
        tf4 = self.get_test_loc('detect/specialcharacter/kerberos3.txt')
        docs = [
            tf1,
            tf2,
            tf3,
            tf4
        ]

        for loc in docs:
            ftr = Rule(text_file=loc, licenses=['kerberos'])
            index = detect.LicenseIndex([ftr])
            matches = index.match(loc)
            assert 1 == len(matches)

    def test_overlap_detection(self):
        #  test this containment relationship between test and index licenses:
        #   * Index licenses:
        #
        #   +-license 2 --------+
        #   |  +-license 1 --+  |
        #   |  +-------------+  |
        #   +-------------------+
        #
        #   * License texts to detect:
        #
        #   +- license 3 -----------+
        #   | +-license 2 --------+ |
        #   | |  +-license 1 --+  | |
        #   | |  +-------------+  | |
        #   | +-------------------+ |
        #   +-----------------------+
        #
        #   +-license 4 --------+
        #   |  +-license 1 --+  |
        #   |  +-------------+  |
        #   +-------------------+

        tf1 = self.get_test_loc('detect/overlap/license.txt')
        tf2 = self.get_test_loc('detect/overlap/license2.txt')
        tf3 = self.get_test_loc('detect/overlap/license3.txt')
        tf4 = self.get_test_loc('detect/overlap/license4.txt')

        # setup index
        ftr1 = Rule(text_file=tf1, licenses=['overlap_license'])
        ftr2 = Rule(text_file=tf2, licenses=['overlap_license'])
        index = detect.LicenseIndex([ftr1, ftr2])

        # test : 1 contains nothing: return 1
        matches = index.match(tf1)
        assert 1 == len(matches)
        match = matches[0]
        assert ftr1 == match.rule

        # test : 2 contains 1: return 2
        matches = index.match(tf2)
        assert 1 == len(matches)
        match = matches[0]
        assert ftr2 == match.rule

        # test : 3 contains 2 that contains 1: return 2
        matches = index.match(tf3)
        assert 1 == len(matches)
        match = matches[0]
        assert ftr2 == match.rule

        # test : 4 contains 1: return 1
        matches = index.match(tf4)
        assert 1 == len(matches)
        match = matches[0]
        assert ftr1 == match.rule

    def test_fulltext_detection_works_with_partial_overlap_from_location(self):
        # setup
        test_rule = self.get_test_loc('detect/templates/license3.txt')
        ftr = Rule(text_file=test_rule, licenses=['mylicense'])
        index = detect.LicenseIndex([ftr])
        # test
        test_doc = self.get_test_loc('detect/templates/license4.txt')
        matches = index.match(test_doc)
        assert 1 == len(matches)
        expected = Token(start=1, start_line=1, start_char=7, end_line=4, end_char=67, end=42)
        assert expected == matches[0].query_position

class TestDetectLicenseRuleTemplate(FileBasedTesting):
    test_data_dir = TEST_DATA_DIR

    def create_test_file(self, text):
        tf = self.get_temp_file()
        with open(tf, 'wb') as of:
            of.write(text)
        return tf

    def test_index_template(self):
        ttr = Rule(text_file=self.create_test_file(u'A one. A {{}}two. A three.'), template=True)
        index = detect.LicenseIndex([ttr])
        expected = {
            1: {},
            2: {},
            3: {u'two a three':
                   {0: [Token(start=3, start_line=0, start_char=13, end_line=0, end_char=25, end=5, gap=0, value=u'two a three', length=3)]
                   },
               u'a one a':
                   {0: [Token(start=0, start_line=0, start_char=0, end_line=0, end_char=8, end=2, gap=5, value=u'a one a', length=3)]}},
            4: {},
        }
        assert expected == index.license_index.indexes

    def test_index_template2(self):
        ttr = Rule(text_file=self.create_test_file(u'A one. A {{10}}two. A three.'), template=True)
        index = detect.LicenseIndex([ttr])
        expected = {
            u'a one a':
                {0: [Token(start=0, start_line=0, start_char=0, end_line=0, end_char=8, end=2, gap=10, value=u'a one a')]},
            u'two a three':
                {0: [Token(start=3, start_line=0, start_char=15, end_line=0, end_char=27, end=5, gap=0, value=u'two a three')]}
        }
        assert expected == index.license_index.indexes[3]

    def test_simple_detection_xcon_crlf_template(self):
        # setup
        tf1_text = u'''X11 License
        Copyright (C) 1996 X Consortium
        Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium.
        X Window System is a trademark of X Consortium, Inc.
        '''
        ttr = Rule(text_file=self.create_test_file(tf1_text), licenses=['x-consortium'], template=True)
        index = detect.LicenseIndex([ttr])

        # test
        doc = self.get_test_loc('detect/simple_detection/x11-xconsortium_text.txt')
        matches = index.match(doc)
        expected = Token(start=0, start_line=1, start_char=0, end_line=13, end_char=51, end=216)
        assert expected == matches[0].query_position

    def test_detection_template_with_inter_gap_smaller_than_ngram_len(self):
        # in this template text there are only 2 tokens between the two
        # templates: this is smaller than the ngram_len of 3 and can never be
        # caught by this length
        tf1_text = u'''Redistributions in binary form must
        {{}} reproduce the {{}}above copyright notice'''
        ttr = Rule(text_file=self.create_test_file(tf1_text), licenses=['mylicense'], template=True)
        index = detect.LicenseIndex([ttr])  # default to ngram_len=3

        # test
        tf2 = u'''Redistributions in binary form must nexB company
        reproduce the word for word above copyright notice.'''.splitlines()
        matches = index.match(tf2)
        expected = Token(start=0, start_line=1, start_char=0, end_line=2, end_char=58, end=14)
        assert 1 == len(matches)
        assert expected == matches[0].query_position

    def test_detection_template_with_inter_gap_equal_to_ngram_len(self):
        # in this template there are 3 tokens between the two templates: len is
        # same as ngram_len of 3
        tf1_text = u'''Redistributions in binary form must
        {{}} reproduce the stipulated {{}}above copyright notice'''
        ttr = Rule(text_file=self.create_test_file(tf1_text), licenses=['mylicense'], template=True)
        index = detect.LicenseIndex([ttr])  # default to ngram_len=3

        # test
        tf2_text = (u'''Redistributions in binary form must nexB company
        reproduce the stipulated word for word above copyright notice.'''
        .splitlines())
        matches = index.match(tf2_text)
        expected = Token(start=0, start_line=1, start_char=0, end_line=2, end_char=69, end=15)
        assert 1 == len(matches)
        assert expected == matches[0].query_position

    def test_detection_template_with_inter_gap_bigger_than_ngram_len(self):
        # setup in this template there are only 4 tokens between the two
        # templates: this is bigger than the ngram_len of 3
        tf1_text = u'''Redistributions in binary form must
        {{}} reproduce as is stipulated {{}}above copyright notice'''
        ttr = Rule(text_file=self.create_test_file(tf1_text), licenses=['mylicense'], template=True)
        index = detect.LicenseIndex([ttr])  # default to ngram_len=3

        # test
        tf2_text = (u'''Redistributions in binary form must nexB company
        reproduce as is stipulated the word for word above copyright notice.'''
        .splitlines())
        matches = index.match(tf2_text)
        expected = Token(start=0, start_line=1, start_char=0, end_line=2, end_char=75, end=17)
        assert 1 == len(matches)
        assert expected == matches[0].query_position

    def test_template_detection_publicdomain(self):
        # setup
        tf5 = self.get_test_loc('detect/templates/license5.txt')
        ttr = Rule(text_file=tf5, licenses=['public-domain'], template=True)
        index = detect.LicenseIndex([ttr])

        # test
        tf6 = self.get_test_loc('detect/templates/license6.txt')
        matches = index.match(tf6)
        assert 1 == len(matches)
        expected = Token(start=82, start_line=16, start_char=0, end_line=18, end_char=67, end=118)
        assert expected == matches[0].query_position

    def test_template_detection_with_short_tokens_around_gaps(self):
        # failed when a gapped token starts at a beginning of rule and at a
        # position less than ngram length
        # setup
        tf7 = self.get_test_loc('detect/templates/license7.txt')
        ttr = Rule(text_file=tf7, template=True)

        # use quadri grams by default
        index = detect.LicenseIndex([ttr])

        # test the index
        quad_grams_index = index.license_index.indexes[4]
        assert 205 == len(quad_grams_index)
        assert u'software without prior written' in quad_grams_index

        # test
        tf8 = self.get_test_loc('detect/templates/license8.txt')
        matches = index.match(tf8)
        assert 1 == len(matches)
        expected = Token(start=0, start_line=1, start_char=0, end_line=40, end_char=34, end=276)
        assert expected == matches[0].query_position

    def test_template_detection_works_for_sun_bcl(self):
        # setup
        rule_dir = self.get_test_loc('detect/rule_template/rules')
        rules = models.load_rules(rule_dir)
        index = detect.get_license_index(rules)

        # test
        qdoc = self.get_test_loc('detect/rule_template/query.txt')
        matches = index.match(qdoc)
        assert 1 == len(matches)

def detect_license(location=None, minimum_score=100):
        for match in detect.get_license_matches(location, minimum_score=100):
            for detected_license in match.rule.licenses:
                yield (detected_license,
                       match.query_position.start_line, match.query_position.end_line,
                       match.query_position.start_char, match.query_position.end_char,
                       match.rule.identifier,
                       match.score,)

class TestMatchPositionsAccuracy(FileBasedTesting):
    test_data_dir = TEST_DATA_DIR

    def check_position(self, test_path, expected):
        """
        Check license detection in file or folder against expected result.
        """
        test_location = self.get_test_loc(test_path)
        results = []
        for match in detect.get_license_matches(test_location, minimum_score=100):
            for detected in match.rule.licenses:
                result = (detected,
                          match.query_position.start_line,
                          match.query_position.end_line,
                          match.query_position.start_char,
                          match.query_position.end_char,
                          # match.rule.identifier,
                          # match.score
                          )
                results.append(result)
        assert expected == results

    def test_match_has_correct_positions_basic(self):
        expected = [
            ('gpl-2.0', 1, 1, 0, 50),
            ('gpl-2.0', 2, 2, 0, 50),
            ('gpl-2.0', 3, 3, 0, 50)
        ]
        self.check_position('positions/license.txt', expected)

    def test_match_has_correct_positions_1(self):
        expected = [
            ('apache-2.0', 1, 2, 0, 46),
            ('apache-2.0', 3, 4, 0, 46),
            ('apache-2.0', 5, 6, 0, 46),
            ('apache-2.0', 7, 8, 0, 46),
            ('apache-2.0', 9, 10, 0, 46)
        ]
        self.check_position('positions/license1.txt', expected)

    def test_match_has_correct_positions_2(self):
        expected = [
        ]
        self.check_position('positions//license2.txt', expected)

    def test_match_has_correct_positions_3(self):
        # we had a weird error where the lines were not computed correctly
        # when we had more than one files detected at a time
        expected = [
            ('apache-2.0', 1, 2, 0, 46),
            ('apache-2.0', 3, 4, 0, 46),
            ('apache-2.0', 5, 6, 0, 46),
            ('apache-2.0', 7, 8, 0, 46),
            ('apache-2.0', 9, 10, 0, 46)
        ]
        self.check_position('positions/license3.txt', expected)

    def test_match_has_correct_positions_4(self):
        expected = [
            ('apache-2.0', 3, 4, 0, 46),
        ]
        self.check_position('positions/license4.txt', expected)

    def test_match_has_correct_positions_in_binary_lkms_1(self):
        expected = [
            ('bsd-new', 26, 26, 0, 20),
            ('gpl-2.0', 26, 26, 0, 20),
        ]
        self.check_position('positions/ath_pci.ko', expected)

    def test_match_has_correct_positions_in_binary_lkms_2(self):
        expected = [
            ('gpl-2.0', 24, 24, 0, 11),
        ]
        self.check_position('positions/eeepc_acpi.ko', expected)

    def test_match_has_correct_positions_in_binary_lkms_3(self):
        expected = [
            ('bsd-new', 3, 3, 0, 20),
            ('gpl-2.0', 3, 3, 0, 20),
        ]
        self.check_position('positions/wlan_xauth.ko', expected)

class TestToFix(FileBasedTesting):
    test_data_dir = TEST_DATA_DIR

    @skipIf(True, 'Needs review')
    def test_detection_in_complex_json(self):
        # NOTE: this test cannot pass as we do not have several of the licenses
        # listed in this JSON
        test_file = self.get_test_loc('detect/json/all.json')
        import json
        item_map = json.load(test_file)
        for item in item_map:
            itemid = item_map[item
        ]['id',
        ]
            content = itemid + ' \n ' + item_map[item
        ]['url',
        ] + ' \n ' + item_map[item
        ]['title',
        ]
            tmp_file = self.get_temp_file()
            fh = open(tmp_file, 'w')
            fh.write(content)
            fh.close()


text:
package master

import (
	"k8s.io/kubernetes/pkg/api/rest"
	"k8s.io/kubernetes/pkg/apis/batch"
	batchapiv1 "k8s.io/kubernetes/pkg/apis/batch/v1"
	batchapiv2alpha1 "k8s.io/kubernetes/pkg/apis/batch/v2alpha1"
	"k8s.io/kubernetes/pkg/genericapiserver"
	jobetcd "k8s.io/kubernetes/pkg/registry/job/etcd"
)

type BatchRESTStorageProvider struct{}

var _ RESTStorageProvider = &BatchRESTStorageProvider{}

func (p BatchRESTStorageProvider) NewRESTStorage(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) {
	apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(batch.GroupName)

	if apiResourceConfigSource.AnyResourcesForVersionEnabled(batchapiv2alpha1.SchemeGroupVersion) {
		apiGroupInfo.VersionedResourcesStorageMap[batchapiv2alpha1.SchemeGroupVersion.Version] = p.v2alpha1Storage(apiResourceConfigSource, restOptionsGetter)
		apiGroupInfo.GroupMeta.GroupVersion = batchapiv2alpha1.SchemeGroupVersion
	}
	if apiResourceConfigSource.AnyResourcesForVersionEnabled(batchapiv1.SchemeGroupVersion) {
		apiGroupInfo.VersionedResourcesStorageMap[batchapiv1.SchemeGroupVersion.Version] = p.v1Storage(apiResourceConfigSource, restOptionsGetter)
		apiGroupInfo.GroupMeta.GroupVersion = batchapiv1.SchemeGroupVersion
	}

	return apiGroupInfo, true
}

func (p BatchRESTStorageProvider) v1Storage(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) map[string]rest.Storage {
	version := batchapiv1.SchemeGroupVersion

	storage := map[string]rest.Storage{}
	if apiResourceConfigSource.ResourceEnabled(version.WithResource("jobs")) {
		jobsStorage, jobsStatusStorage := jobetcd.NewREST(restOptionsGetter(batch.Resource("jobs")))
		storage["jobs"] = jobsStorage
		storage["jobs/status"] = jobsStatusStorage
	}
	return storage
}

func (p BatchRESTStorageProvider) v2alpha1Storage(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) map[string]rest.Storage {
	version := batchapiv2alpha1.SchemeGroupVersion

	storage := map[string]rest.Storage{}
	if apiResourceConfigSource.ResourceEnabled(version.WithResource("jobs")) {
		jobsStorage, jobsStatusStorage := jobetcd.NewREST(restOptionsGetter(batch.Resource("jobs")))
		storage["jobs"] = jobsStorage
		storage["jobs/status"] = jobsStatusStorage
	}
	return storage
}

redpajama_set_name: RedPajamaGithub


text:
package org.bioconductor.packages.caMachineLearning.service.globus;

import org.bioconductor.packages.caMachineLearning.service.CaMachineLearningImpl;

import java.rmi.RemoteException;

/**
 * DO NOT EDIT:  This class is autogenerated!
 *
 * This class implements each method in the portType of the service.  Each method call represented
 * in the port type will be then mapped into the unwrapped implementation which the user provides
 * in the CaMachineLearningImpl class.  This class handles the boxing and unboxing of each method call
 * so that it can be correclty mapped in the unboxed interface that the developer has designed and
 * has implemented.  Authorization callbacks are automatically made for each method based
 * on each methods authorization requirements.
 *
 * @created by Introduce Toolkit version 1.2
 *
 */
public class CaMachineLearningProviderImpl{

	CaMachineLearningImpl impl;

	public CaMachineLearningProviderImpl() throws RemoteException {
		impl = new CaMachineLearningImpl();
	}

    public org.bioconductor.packages.caMachineLearning.stubs.LearnResponse learn(org.bioconductor.packages.caMachineLearning.stubs.LearnRequest params) throws RemoteException {
    org.bioconductor.packages.caMachineLearning.stubs.LearnResponse boxedResult = new org.bioconductor.packages.caMachineLearning.stubs.LearnResponse();
    boxedResult.setMachineLearningResultCollection(impl.learn(params.getSingleChannelExpressionDataCollection().getSingleChannelExpressionDataCollection(),params.getCagridMachineLearningParameters().getMachineLearningParameters()));
    return boxedResult;
  }

    public org.bioconductor.packages.caMachineLearning.stubs.CreateCaMachineLearningSessionResponse createCaMachineLearningSession(org.bioconductor.packages.caMachineLearning.stubs.CreateCaMachineLearningSessionRequest params) throws RemoteException {
    org.bioconductor.packages.caMachineLearning.stubs.CreateCaMachineLearningSessionResponse boxedResult = new org.bioconductor.packages.caMachineLearning.stubs.CreateCaMachineLearningSessionResponse();
    boxedResult.setSessionIdentifier(impl.createCaMachineLearningSession());
    return boxedResult;
  }

    public org.bioconductor.packages.caMachineLearning.stubs.InvokeLearnResponse invokeLearn(org.bioconductor.packages.caMachineLearning.stubs.InvokeLearnRequest params) throws RemoteException {
    org.bioconductor.packages.caMachineLearning.stubs.InvokeLearnResponse boxedResult = new org.bioconductor.packages.caMachineLearning.stubs.InvokeLearnResponse();
    impl.invokeLearn(params.getSessionIdentifier().getSessionIdentifier(),params.getCagridMachineLearningParameters().getMachineLearningParameters());
    return boxedResult;
  }

    public org.bioconductor.packages.caMachineLearning.stubs.GetStatusResponse getStatus(org.bioconductor.packages.caMachineLearning.stubs.GetStatusRequest params) throws RemoteException {
    org.bioconductor.packages.caMachineLearning.stubs.GetStatusResponse boxedResult = new org.bioconductor.packages.caMachineLearning.stubs.GetStatusResponse();
    boxedResult.setStatus(impl.getStatus(params.getSessionIdentifier().getSessionIdentifier()));
    return boxedResult;
  }

    public org.bioconductor.packages.caMachineLearning.stubs.GetRpackageSessionInfoResponse getRpackageSessionInfo(org.bioconductor.packages.caMachineLearning.stubs.GetRpackageSessionInfoRequest params) throws RemoteException {
    org.bioconductor.packages.caMachineLearning.stubs.GetRpackageSessionInfoResponse boxedResult = new org.bioconductor.packages.caMachineLearning.stubs.GetRpackageSessionInfoResponse();
    boxedResult.setResponse(impl.getRpackageSessionInfo());
    return boxedResult;
  }

}


text:
package io.chthonic.mythos.javaexample.ui.layouts;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import io.chthonic.mythos.javaexample.App;
import io.chthonic.mythos.javaexample.ui.presenters.DahPresenter;
import io.chthonic.mythos.javaexample.ui.vus.DahVu;
import io.chthonic.mythos.mvp.MVPDispatcher;
import io.chthonic.mythos.mvp.MVPLayout;
import io.chthonic.mythos.mvp.PresenterCacheBasic;
import kotlin.jvm.functions.Function4;

/**
 * Created by jhavatar on 3/12/2016.
 */
public class DahLayout extends MVPLayout<DahPresenter, DahVu> {

    private static final int MVP_UID = DahLayout.class.getSimpleName().hashCode();

    public DahLayout(@NonNull Context context) {
        super(context);
    }

    public DahLayout(@NonNull Context context, String lifecycleCallbackKey) {
        super(context, lifecycleCallbackKey);
    }

    public DahLayout(@NonNull Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DahLayout(@NonNull Context context, @NonNull AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public DahLayout(@NonNull Context context, @NonNull AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @NonNull
    @Override
    protected MVPDispatcher<DahPresenter, DahVu> createMVPDispatcher() {
        return new MVPDispatcher<>(MVP_UID,
                new PresenterCacheBasic<>(new DahPresenter(), true),
                new Function4<LayoutInflater, Activity, Fragment, ViewGroup, DahVu>() {
                    @Override
                    public DahVu invoke(LayoutInflater layoutInflater, Activity activity, Fragment fragment, ViewGroup parentView) {
                        return new DahVu(layoutInflater, activity, fragment, parentView);
                    }
                });
    }

    @Override
    protected void registerLifecycleCallback() {
        String key = getLifecycleCallbackKey();
        if (key != null) {
            App.lifecycleManager.registerCallback(key, this.getLifecycleCallback());
        }
    }

    @Override
    protected void unregisterLifecycleCallback() {
        String key = getLifecycleCallbackKey();
        if (key != null) {
            App.lifecycleManager.unregisterCallback(key, this.getLifecycleCallback());
        }
    }
}


text:
package com.alibaba.nacos.plugin.auth.api;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class IdentityContextTest {

    private static final String TEST = "test";

    private IdentityContext identityContext;

    @Before
    public void setUp() throws Exception {
        identityContext = new IdentityContext();
    }

    @Test
    public void testGetParameter() {
        assertNull(identityContext.getParameter(TEST));
        identityContext.setParameter(TEST, TEST);
        assertEquals(TEST, identityContext.getParameter(TEST));
    }

    @Test
    public void testGetParameterWithDefaultValue() {
        assertEquals(TEST, identityContext.getParameter(TEST, TEST));
        identityContext.setParameter(TEST, TEST + "new");
        assertEquals(TEST + "new", identityContext.getParameter(TEST, TEST));
        long actual = identityContext.getParameter(TEST, 1L);
        assertEquals(1L, actual);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetParameterWithNullDefaultValue() {
        identityContext.getParameter(TEST, null);
    }
}


text:
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory'
import { setContext } from 'apollo-link-context';

const graphQlDomain = process.env.REACT_APP_GRAPHQL_DOMAIN || 'http://localhost:3000'

const httpLink = createHttpLink({
  uri: `${graphQlDomain}/graphql`,
});

// with guidance from https://www.apollographql.com/docs/react/recipes/authentication.html
const authLink = setContext((_, { headers }) => {
  // Note: An incorrect password will yield a confusing error message from the cors response: "No Access-Control-Allow-Origin' header is present on the requested resource."
  const credentials = process.env.REACT_APP_GRAPHQL_CREDENTIALS || ''
  // convert it to the correct form
  const token = new Buffer(credentials).toString('base64')

  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: `Basic ${token}`
    }
  }
});

const apolloClient = new ApolloClient({
  cache: new InMemoryCache(),
  link: authLink.concat(httpLink),
  connectToDevTools: true
})

export default apolloClient


text:
package com.lin.java.strategy.main;

/**
 * Created by never on 12/21/2015.
 */
public interface strategy {
    public int doOperation(int num1, int num2);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Linnaea 8: 490 (1833)

#### Original name
Puccinia linkii Klotzsch

### Remarks
null


text:
#include "globus_gram_protocol.h"
#include "globus_preload.h"

#define test_assert(assertion, message) \
    if (!(assertion)) \
    { \
        printf message; \
        return 1; \
    }

#define TEST_CASE(x) { #x, x }

#define ARRAY_LEN(x) ((int) (sizeof(x)/sizeof(x[0])))

typedef struct
{
    char * name;
    int (*test_function)(void);
}
test_case;

char *                                  job_id = "http://example.org:43343/1/2";

/*
 * Test case:
 *
 * PURPOSE:
 *     Check that
 *     globus_gram_protocol_pack_status_update_message_with_extensions()
 *     generates messages which can be parsed with GRAM2 parser if no
 *     extensions are present.
 *
 * STEPS:
 *     - Creates a message
 *       globus_gram_protocol_pack_status_update_message_with_extensions()
 *       with an empty hash table.
 *     - Parses message
 *     - Verifies that all standard attributes match expected values
 */
int
test_pack_with_empty_extensions(void)
{
    globus_byte_t *                     message;
    globus_size_t                       message_size;
    globus_hashtable_t                  hashtable;
    int                                 rc;
    char *                              job_contact = NULL;
    int                                 status = 0;
    int                                 failure_code = 0;

    rc = globus_hashtable_init(
            &hashtable,
            89,
            globus_hashtable_string_hash,
            globus_hashtable_string_keyeq);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error initializing hash table (out of memory?)\n"));

    rc = globus_gram_protocol_pack_status_update_message_with_extensions(
            job_id,
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            0,
            &hashtable,
            &message,
            &message_size);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error constructing test message: %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    rc = globus_gram_protocol_unpack_status_update_message(
            message,
            message_size,
            &job_contact,
            &status,
            &failure_code);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error parsing test message: %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    /* check that expected attributes were parsed correctly */
    test_assert(
            strcmp(job_contact, job_id) == 0,
            ("# job contact mismatch '%s', expected '%s'\n",
             job_contact,
             job_id));
    test_assert(
            status == GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            ("# job status mismatch '%d', expected '%d'\n",
             status,
             GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE));
    test_assert(
            failure_code == 0,
            ("# failure code mismatch '%d', expected '%d'\n",
             failure_code,
             0));

    globus_gram_protocol_hash_destroy(&hashtable);

    free(message);

    return 0;
}
/* test_pack_with_empty_extensions() */

/*
 * Test case:
 *
 * PURPOSE:
 *     Check that
 *     globus_gram_protocol_pack_status_update_message_with_extensions()
 *     generates messages which can be parsed with GRAM2 parser if some
 *     extensions are present.
 *
 * STEPS:
 *     - Creates a message
 *       globus_gram_protocol_pack_status_update_message_with_extensions()
 *       with a non-empty hash table.
 *     - Parses message
 *     - Verifies that all standard attributes match expected values
 */
int
test_pack_with_extensions(void)
{
    globus_byte_t *                     message;
    globus_size_t                       message_size;
    globus_hashtable_t                  hashtable;
    globus_gram_protocol_extension_t *  entry;
    int                                 rc;
    char *                              job_contact = NULL;
    int                                 status = 0;
    int                                 failure_code = 0;

    rc = globus_hashtable_init(
            &hashtable,
            89,
            globus_hashtable_string_hash,
            globus_hashtable_string_keyeq);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error initializing hash table (out of memory?)\n"));

    entry = malloc(sizeof(globus_gram_protocol_extension_t));
    test_assert(
            entry != NULL,
            ("# Error creating extension\n"));
    entry->attribute = strdup("attribute");
    test_assert(
            entry->attribute != NULL,
            ("# Error creating extension attribute name\n"));
    entry->value = strdup("value");
    test_assert(
            entry->value != NULL,
            ("# Error creating extension attribute value\n"));

    rc = globus_hashtable_insert(&hashtable, entry->attribute, entry);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error inserting extension attribute to hashtable\n"));

    rc = globus_gram_protocol_pack_status_update_message_with_extensions(
            job_id,
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            0,
            &hashtable,
            &message,
            &message_size);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error constructing test message: %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    rc = globus_gram_protocol_unpack_status_update_message(
            message,
            message_size,
            &job_contact,
            &status,
            &failure_code);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error parsing test message: %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    /* check that expected attributes were parsed correctly */
    test_assert(
            strcmp(job_contact, job_id) == 0,
            ("# job contact mismatch '%s', expected '%s'\n",
             job_contact,
             job_id));
    test_assert(
            status == GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            ("# job status mismatch '%d', expected '%d'\n",
             status,
             GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE));
    test_assert(
            failure_code == 0,
            ("# failure code mismatch '%d', expected '%d'\n",
             failure_code,
             0));

    free(job_contact);

    globus_gram_protocol_hash_destroy(&hashtable);

    free(message);

    return 0;
}
/* test_pack_with_extensions() */

/* Test case:
 * PURPOSE:
 *     Make sure
 *     globus_gram_protocol_pack_status_update_message_with_extensions()
 *     handles NULL job id, hashtable, message, or message size.
 * TEST STEPS:
 *   - Call globus_gram_protocol_unpack_status_update_message_to_hash() with
 *     NULL message and verify that result is NULL_PARAM error
 *   - Call globus_gram_protocol_unpack_status_update_message_to_hash() with
 *     NULL hashtable pointer and verify that result is NULL_PARAM error.
 */
int
test_null_param(void)
{
    globus_byte_t *                     message;
    globus_size_t                       message_size;
    globus_hashtable_t                  hashtable;
    int                                 rc;

    rc = globus_hashtable_init(
            &hashtable,
            89,
            globus_hashtable_string_hash,
            globus_hashtable_string_keyeq);
    test_assert(rc == GLOBUS_SUCCESS,
            ("# Error constructing hashtable (out of memory?)\n"));

    /* Null job id */
    rc = globus_gram_protocol_pack_status_update_message_with_extensions(
            NULL /* job_id */,
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            0,
            &hashtable,
            &message,
            &message_size);
    test_assert(
            rc == GLOBUS_GRAM_PROTOCOL_ERROR_NULL_PARAMETER,
            ("# With null job_id, expected "
             "GLOBUS_GRAM_PROTOCOL_ERROR_NULL_PARAMETER, got %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    rc = globus_gram_protocol_pack_status_update_message_with_extensions(
            job_id,
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            0,
            NULL,
            &message,
            &message_size);
    test_assert(
            rc == GLOBUS_GRAM_PROTOCOL_ERROR_NULL_PARAMETER,
            ("# With null extensions, expected "
             "GLOBUS_GRAM_PROTOCOL_ERROR_NULL_PARAMETER, got %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    rc = globus_gram_protocol_pack_status_update_message_with_extensions(
            job_id,
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            0,
            &hashtable,
            NULL,
            &message_size);
    test_assert(
            rc == GLOBUS_GRAM_PROTOCOL_ERROR_NULL_PARAMETER,
            ("# With null reply, expected "
             "GLOBUS_GRAM_PROTOCOL_ERROR_NULL_PARAMETER, got %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));
    rc = globus_gram_protocol_pack_status_update_message_with_extensions(
            job_id,
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            0,
            &hashtable,
            &message,
            NULL);
    test_assert(
            rc == GLOBUS_GRAM_PROTOCOL_ERROR_NULL_PARAMETER,
            ("# With null replysize, expected "
             "GLOBUS_GRAM_PROTOCOL_ERROR_NULL_PARAMETER, got %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    globus_hashtable_destroy(&hashtable);

    return 0;
}
/* test_null_param() */

int
test_null_extension_value(void)
{
    globus_byte_t *                     message;
    globus_size_t                       message_size;
    globus_hashtable_t                  hashtable;
    globus_gram_protocol_extension_t    entry;
    int                                 rc;

    rc = globus_hashtable_init(
            &hashtable,
            89,
            globus_hashtable_string_hash,
            globus_hashtable_string_keyeq);
    test_assert(rc == GLOBUS_SUCCESS,
            ("# Error constructing hashtable (out of memory?)\n"));
    entry.attribute = "attribute";
    entry.value = NULL;

    rc = globus_hashtable_insert(&hashtable, entry.attribute, &entry);
    test_assert(rc == GLOBUS_SUCCESS,
            ("# Error adding extension to attribute\n"));

    rc = globus_gram_protocol_pack_status_update_message_with_extensions(
            job_id,
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            0,
            &hashtable,
            &message,
            &message_size);
    test_assert(
            rc == GLOBUS_GRAM_PROTOCOL_ERROR_HTTP_PACK_FAILED,
            ("# With null job_id, expected "
             "GLOBUS_GRAM_PROTOCOL_ERROR_HTTP_PACK_FAILED, got %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    globus_hashtable_destroy(&hashtable);

    return 0;
}
/* test_null_extension_value() */

int main(int argc, char * argv[])
{
    test_case                           tests[] =
    {
        TEST_CASE(test_pack_with_empty_extensions),
        TEST_CASE(test_pack_with_extensions),
        TEST_CASE(test_null_param),
        TEST_CASE(test_null_extension_value)
    };
    int                                 i;
    int                                 rc;
    int                                 not_ok = 0;

    LTDL_SET_PRELOADED_SYMBOLS();
    printf("1..%d\n", ARRAY_LEN(tests));

    globus_module_activate(GLOBUS_GRAM_PROTOCOL_MODULE);
    for (i = 0; i < ARRAY_LEN(tests); i++)
    {
        rc = tests[i].test_function();

        if (rc != 0)
        {
            not_ok++;
            printf("not ok - %s\n", tests[i].name);
        }
        else
        {
            printf("ok - %s\n", tests[i].name);
        }
    }
    globus_module_deactivate(GLOBUS_GRAM_PROTOCOL_MODULE);

    return not_ok;
}


text:
package org.activiti.spring.components.config.java;

import org.activiti.engine.ProcessEngine;

/**
 * callback for any configurations that want to override the defaults
 * @author Josh Long
 */
public interface ActivitiConfigurer {

    /***
     * Build up the {@link ProcessEngine process engine}. The process engine
     * itself will be used to factory other components like the {@link org.activiti.engine.RuntimeService runtime service}.
     *
     * @throws Exception
     */
    ProcessEngine processEngine() throws Exception ;

}


text:
module.exports = {
  launch: {
    args: [
      // Required for Docker version of Puppeteer
      '--no-sandbox',
      '--disable-setuid-sandbox',
      // This will write shared memory files into /tmp instead of /dev/shm,
      // because Docker's default for /dev/shm is 64MB
      '--disable-dev-shm-usage',
    ],
  },
};


text:
#ifndef BlynkSimpleSparkCore_h
#define BlynkSimpleSparkCore_h

#include "BlynkSparkCore.h"

static BlynkTransportSparkCore _blynkTransport;
BlynkSparkCore Blynk(_blynkTransport);

#include "BlynkWidgets.h"

#endif


text:
<?php

namespace Cubiche\Infrastructure\Cqrs\Tests\Fixtures\Command;

use Cubiche\Core\Cqrs\Command\Command;
use Cubiche\Core\Validator\Assertion;
use Cubiche\Core\Validator\Mapping\ClassMetadata;

/**
 * CreateUserCommand class.
 *
 * @author Ivannis Suárez Jerez <ivannis.suarez@gmail.com>
 */
class CreateUserCommand extends Command
{
    /**
     * @var string
     */
    protected $username;

    /**
     * @var string
     */
    protected $password;

    /**
     * @var string
     */
    protected $email;

    /**
     * CreateUserCommand constructor.
     *
     * @param string $username
     * @param string $password
     * @param string $email
     */
    public function __construct($username, $password, $email)
    {
        $this->setUsername($username);
        $this->setPassword($password);
        $this->setEmail($email);
    }

    /**
     * @return string
     */
    public function username()
    {
        return $this->username;
    }

    /**
     * @param string $username
     */
    protected function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return string
     */
    public function password()
    {
        return $this->password;
    }

    /**
     * @param string $password
     */
    protected function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * @return string
     */
    public function email()
    {
        return $this->email;
    }

    /**
     * @param string $email
     */
    protected function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * {@inheritdoc}
     */
    public static function loadValidatorMetadata(ClassMetadata $classMetadata)
    {
        $classMetadata->addPropertyConstraint('username', Assertion::string()->notBlank());
        $classMetadata->addPropertyConstraint('password', Assertion::string()->notBlank());
        $classMetadata->addPropertyConstraint('email', Assertion::email()->notBlank());
    }
}


text:
/**
 * @author Alexey A. Petrenko
 */
/*
 * THE FILE HAS BEEN AUTOGENERATED BY INTEL IJH TOOL.
 * Please be aware that all changes made to this file manually
 * will be overwritten by the tool if it runs again.
 */

#include <jni.h>

/* Header for class org.apache.harmony.awt.gl.font.NativeFont */

#ifndef _ORG_APACHE_HARMONY_AWT_GL_FONT_NATIVEFONT_H
#define _ORG_APACHE_HARMONY_AWT_GL_FONT_NATIVEFONT_H

#ifdef __cplusplus
extern "C" {
#endif

/* Static final fields */

#undef org_apache_harmony_awt_gl_font_NativeFont_DriverStringOptionsCmapLookup
#define org_apache_harmony_awt_gl_font_NativeFont_DriverStringOptionsCmapLookup 1L

#undef org_apache_harmony_awt_gl_font_NativeFont_DriverStringOptionsVertical
#define org_apache_harmony_awt_gl_font_NativeFont_DriverStringOptionsVertical 2L

#undef org_apache_harmony_awt_gl_font_NativeFont_DriverStringOptionsRealizedAdvance
#define org_apache_harmony_awt_gl_font_NativeFont_DriverStringOptionsRealizedAdvance 4L

#undef org_apache_harmony_awt_gl_font_NativeFont_DriverStringOptionsLimitSubpixel
#define org_apache_harmony_awt_gl_font_NativeFont_DriverStringOptionsLimitSubpixel 8L

/* Native methods */

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getFontFamiliesNames()[Ljava/lang/String;
 */
JNIEXPORT jobjectArray JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getFontFamiliesNames(JNIEnv *, jclass);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.embedFontNative(Ljava/lang/String;)Z
 */
JNIEXPORT jstring JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_embedFontNative(JNIEnv *, jclass,
    jstring);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.initializeFont(Lorg/apache/harmony/awt/gl/font/WindowsFont;Ljava/lang/String;II)J
 */
JNIEXPORT jlong JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_initializeFont(JNIEnv *, jclass,
    jobject, jstring, jint, jint);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.canDisplayCharNative(JC)Z
 */
JNIEXPORT jboolean JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_canDisplayCharNative(JNIEnv *, jclass,
    jlong, jchar);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getFamilyNative(J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getFamilyNative(JNIEnv *, jclass,
    jlong);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getFontNameNative(J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getFontNameNative(JNIEnv *, jclass,
    jlong);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.pFontFree(J)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_pFontFree(JNIEnv *, jclass,
    jlong);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getItalicAngleNative(J)F
 */
JNIEXPORT jfloat JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getItalicAngleNative(JNIEnv *, jclass,
    jlong);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.enumSystemFonts()V
 */
JNIEXPORT void JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_enumSystemFonts(JNIEnv *, jclass);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getFonts()[Ljava/lang/String;
 */
JNIEXPORT jobjectArray JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getFonts(JNIEnv *, jclass);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getNativeLineMetrics(JIZZI)[F
 */
JNIEXPORT jfloatArray JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getNativeLineMetrics(JNIEnv *, jclass,
    jlong, jint, jboolean, jboolean, jint);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getGlyphInfoNative(JCI)[F
 */
JNIEXPORT jfloatArray JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getGlyphInfoNative(JNIEnv *, jclass,
    jlong, jchar, jint);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getGlyphPxlInfoNative(JC)[I
 */
JNIEXPORT jintArray JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getGlyphPxlInfoNative(JNIEnv *, jclass,
    jlong, jchar);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getGlyphCodesNative(JLjava/lang/String;I)[I
 */
JNIEXPORT jintArray JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getGlyphCodesNative(JNIEnv *, jclass,
    jlong, jstring, jint);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getGlyphCodeNative(JC)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getGlyphCodeNative(JNIEnv *, jclass,
    jlong, jchar);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.RemoveFontResource(Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_RemoveFontResource(JNIEnv *, jclass,
    jstring);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.NativeInitGlyphImage(Lorg/apache/harmony/awt/gl/font/Glyph;)[B
 */
JNIEXPORT jbyteArray JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_NativeInitGlyphImage(JNIEnv *, jclass,
    jobject);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.nativeInitLCIDsTable([Ljava/lang/String;[S)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_nativeInitLCIDsTable(JNIEnv *, jclass,
    jobjectArray, jshortArray);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getGlyphOutline(JCJI)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getGlyphOutline(JNIEnv *, jclass,
    jlong, jchar, jlong, jint);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.getExtraMetricsNative(JII)[F
 */
JNIEXPORT jfloatArray JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_getExtraMetricsNative(JNIEnv *, jclass,
    jlong, jint, jint);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.setAntialiasing
 */
JNIEXPORT void JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_setAntialiasing(JNIEnv *, jclass,
    jlong, jboolean);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.gdiPlusDrawText(JLjava/lang/String;IJFF)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_gdiPlusDrawText(JNIEnv *, jclass,
    jlong, jstring, jint, jlong, jfloat, jfloat);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.gdiPlusDrawDriverChar(JCJFFI[D)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_gdiPlusDrawDriverChar(JNIEnv *, jclass,
    jlong, jchar, jlong, jfloat, jfloat, jint, jdoubleArray);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.gdiPlusDrawDriverString(JLjava/lang/String;IJFF[DI[D)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_gdiPlusDrawDriverString(JNIEnv *, jclass,
    jlong, jstring, jint, jlong, jfloat, jfloat, jdoubleArray, jint, jdoubleArray);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.gdiPlusDrawDriverChars(J[CIJ[DI[D)I
 */
JNIEXPORT jint JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_gdiPlusDrawDriverChars(JNIEnv *, jclass,
    jlong, jcharArray, jint, jlong, jdoubleArray, jint, jdoubleArray);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.gdiPlusReleaseHDC(JJ)V
 */
JNIEXPORT void JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_gdiPlusReleaseHDC(JNIEnv *, jclass,
    jlong, jlong);

/*
 * Method: org.apache.harmony.awt.gl.font.NativeFont.gdiPlusGetHDC(J)J
 */
JNIEXPORT jlong JNICALL
Java_org_apache_harmony_awt_gl_font_NativeFont_gdiPlusGetHDC(JNIEnv *, jclass,
    jlong);

#ifdef __cplusplus
}
#endif

#endif /* _ORG_APACHE_HARMONY_AWT_GL_FONT_NATIVEFONT_H */


text:
package net.dstc.mkts.data.jcr;

import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.UUID;
import javax.jcr.RepositoryException;
import mockit.Mock;
import mockit.MockUp;
import mockit.Mocked;
import net.dstc.mkts.data.SurveyDO;
import net.dstc.mkts.data.SurveyStatus;
import net.dstc.mkts.data.SurveyTargetDO;
import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl;

/**
 *
 * @author Patrizio Bruno <desertconsulting@gmail.com>
 */
public class JcrSurveyDAOTest {

    public JcrSurveyDAOTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Mocked
    RepositoryConfig config;

    @Mocked
    ObjectContentManagerImpl objectContentManager;

    @Test
    public void testConstructorHandlingRepositoryException() throws RepositoryException {
        System.out.println("JcrSurveyDAO");

        new MockUp<RepositoryImpl>() {
            @Mock
            public RepositoryImpl create(RepositoryConfig config) throws RepositoryException {
                throw new RepositoryException();
            }
        };

        JcrSurveyDAO dao = new JcrSurveyDAO();
        dao.shutdown();
    }

    /**
     * Test of add method, of class JcrSurveyDAO.
     */
    @Test
    public void testAdd(@Mocked RepositoryImpl repository) {

        System.out.println("add");
        JcrSurveyDAO instance = new JcrSurveyDAO();
        SurveyDO survey = instance.createSurvey();
        instance.add(survey);
        instance.shutdown();
    }

    /**
     * Test of list method, of class JcrSurveyDAO.
     */
    @Test
    public void testListWithNullQuery(@Mocked RepositoryImpl repository) {
        System.out.println("list");
        SurveyDO query = null;
        JcrSurveyDAO instance = new JcrSurveyDAO();
        Collection<SurveyDO> expResult = Collections.emptyList();
        Collection<SurveyDO> result = instance.list(query);
        assertEquals(expResult, result);
        instance.shutdown();
    }

    /**
     * Test of list method, of class JcrSurveyDAO.
     */
    @Test
    public void testListWithQuery(@Mocked RepositoryImpl repository) {
        System.out.println("list");
        JcrSurveyDAO instance = new JcrSurveyDAO();
        SurveyDO query = instance.createSurvey();
        query.setTarget(instance.createSurveyTarget());
        query.setStartDate(new Date());
        query.setTitle("test");
        query.setStatus(SurveyStatus.READY);

        Collection<SurveyDO> expResult = Collections.emptyList();
        Collection<SurveyDO> result = instance.list(query);
        assertEquals(expResult, result);
        instance.shutdown();
    }

    @Test
    public void testJcrSurveyDOEquals(@Mocked RepositoryImpl repository) {
        System.out.println("JcrSurveyDO.equals");
        JcrSurveyDO surveyA = new JcrSurveyDO();
        surveyA.setTarget(new JcrSurveyTargetDO());

        JcrSurveyDO surveyB = new JcrSurveyDO();

        JcrSurveyDO surveyC = new JcrSurveyDO();
        JcrSurveyTargetDO targetC = new JcrSurveyTargetDO();
        targetC.setCountry("TS");
        surveyC.setTarget(targetC);

        JcrSurveyDO surveyD = new JcrSurveyDO();
        surveyD.setTarget(new JcrSurveyTargetDO());

        assertNotEquals(surveyA, null);
        assertNotEquals(surveyA, "");
        assertEquals(surveyA, surveyA);
        assertNotEquals(surveyA, surveyB);
        assertNotEquals(surveyB, surveyA);
        assertNotEquals(surveyA, surveyC);
        assertNotEquals(surveyA, surveyD);
    }

    @Test
    public void testJcrTargetSurveyDOEquals(@Mocked RepositoryImpl repository) {
        System.out.println("JcrSurveyTargetDO.equals");
        JcrSurveyTargetDO targetA = new JcrSurveyTargetDO();
        JcrSurveyTargetDO targetB = new JcrSurveyTargetDO();

        assertNotEquals(targetA, null);
        assertNotEquals(targetA, "");
        assertEquals(targetA, targetA);
        assertEquals(targetA, targetB);
    }

    @Test
    public void testSearch(@Mocked RepositoryImpl repository) {
        System.out.println("search");
        SurveyDO query = new JcrSurveyDO();
        query.setStartDate(new Date());
        query.setStatus(SurveyStatus.READY);
        query.setTitle("test");

        SurveyTargetDO target = new JcrSurveyTargetDO();
        query.setTarget(target);

        target.setCountry("IT");
        target.setGender("M");
        target.setMaxAge(80);
        target.setMinAge(30);
        target.setMaxIncome(50000);
        target.setMinIncome(35000);
        JcrSurveyDAO instance = new JcrSurveyDAO();
        Collection<SurveyDO> expResult = Collections.emptyList();
        Collection<SurveyDO> result = instance.list(query);
        assertEquals(expResult, result);
        instance.shutdown();
    }

    /**
     * Test of get method, of class JcrSurveyDAO.
     */
    @Test
    public void testGet(@Mocked RepositoryImpl repository) {
        System.out.println("get");
        String id = "";
        JcrSurveyDAO instance = new JcrSurveyDAO();
        SurveyDO expResult = null;
        SurveyDO result = instance.get(id);
        assertEquals(expResult, result);
        instance.shutdown();
    }

    /**
     * Test of delete method, of class JcrSurveyDAO.
     */
    @Test
    public void testDelete(@Mocked RepositoryImpl repository) {
        System.out.println("delete");
        String id = "";
        JcrSurveyDAO instance = new JcrSurveyDAO();
        instance.delete(id);
        instance.shutdown();
    }

    /**
     * Test of update method, of class JcrSurveyDAO.
     */
    @Test
    public void testUpdate(@Mocked RepositoryImpl repository) {
        System.out.println("update");
        SurveyDO s = new JcrSurveyDO();
        s.setId("/survey/" + UUID.randomUUID());
        JcrSurveyDAO instance = new JcrSurveyDAO();
        instance.update(s);
        instance.shutdown();
    }

    /**
     * Test of createSurvey method, of class JcrSurveyDAO.
     */
    @Test
    public void testCreateSurvey(@Mocked RepositoryImpl repository) {
        System.out.println("createSurvey");
        JcrSurveyDAO instance = new JcrSurveyDAO();
        SurveyDO result = instance.createSurvey();
        assertTrue(result instanceof JcrSurveyDO);
        instance.shutdown();
    }

    /**
     * Test of createSurveyTarget method, of class JcrSurveyDAO.
     */
    @Test
    public void testCreateSurveyTarget(@Mocked RepositoryImpl repository) {
        System.out.println("createSurveyTarget");
        JcrSurveyDAO instance = new JcrSurveyDAO();
        SurveyTargetDO expResult = new JcrSurveyTargetDO();
        SurveyTargetDO result = instance.createSurveyTarget();
        assertEquals(expResult, result);
        instance.shutdown();
    }
}


text:
+++
author = "George Czabania"
date = "2015-02-25"
title = "terminal.sexy"
link = "Github"
image = "/assets/terminal.sexy/screenshot.jpg"

[commits]
  first = "2014-04-10"
  total = "113"

[links]
  Github = "https://github.com/stayradiated/terminal.sexy"
  Site = "https://terminal.sexy"
  Blog-Post = "/blog/terminal.sexy"
+++

Create, view and edit terminal colorschemes. Supports importing and exporting
configuration files between many different. My favorite feature is that you can
import a buffer output from tmux and it will display it in the browser using
your custom color scheme.

A lot of the code I wrote for this project was put into external libraries on
npm, so that they could be used for other projects as well. These libraries
include:

- [colr](https://github.com/stayradiated/colr) - convert between color formats
  (rgb, hsl, etc.)
- [termio](https://github.com/stayradiated/termio) - convert ansi escape codes
  into html
- [termcolors](https://github.com/stayradiated/termcolors) - import and export
  between multiple terminal color scheme formats
- [react-ranger](https://github.com/stayradiated/react-ranger) - column browser
  (used for the scheme and template file browser)
- [react-colorpicker](https://github.com/stayradiated/react-colorpicker) -
  simple colorpicker for react

Other dependencies that were used include:

- [React](https://www.npmjs.com/package/react) - a JavaScript library for
  building user interfaces.
- [Golden Layout](https://www.npmjs.com/package/golden-layout) - The ultimate
  JavaScript layout manager
- [Bluebird](https://www.npmjs.com/package/bluebird) - Full featured
  Promises/A+ implementation with exceptionally good performance
- [Reflux](https://www.npmjs.com/package/reflux) - A simple library for
  uni-directional dataflow application architecture inspired by ReactJS Flux
- [Lodash](https://www.npmjs.com/package/lodash) - Function utilities
- [HUSL](https://www.npmjs.com/package/husl) - Replacement for the HSL color
  space


text:
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;

namespace SimpleNet.ServiceHost.Helpers
{
    public static class ServiceRunner
    {
        [ExcludeFromCodeCoverage]
        public static void RunInteractive(ServiceBase[] servicesToRun)
        {
            Console.WriteLine(@"Services running in interactive mode.");
            Console.WriteLine();

            MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
                BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (ServiceBase service in servicesToRun)
            {
                try
                {
                    Trace.TraceInformation(@"Starting {0}...", service.ServiceName);
                    onStartMethod.Invoke(service, new object[] { new string[] { } });
                    Trace.TraceInformation(@"Starting {0}...... Started", service.ServiceName);
                }
                catch (Exception ex)
                {
                    Trace.TraceError(@"Starting {0}...... FAILED!!{1}{1}{2}{1}", service.ServiceName, Environment.NewLine, ex);
                }
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(@"Press any key to stop the services and end the process...");
            Console.Read();
            Console.WriteLine();

            MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (ServiceBase service in servicesToRun)
            {
                Trace.Write( String.Format( @"Stopping {0}...", service.ServiceName ) );
                onStopMethod.Invoke(service, null);
                Trace.WriteLine(@"Stopped");
            }

            Console.WriteLine(@"All services stopped.");
            // Keep the console alive for a second to allow the user to see the message.
            Thread.Sleep(1000);
        }
    }
}


text:
SET DEFINE OFF;
CREATE UNIQUE INDEX AFW_12_MEMBR_STRUC_PK ON AFW_12_MEMBR_STRUC
(SEQNC)
LOGGING
/


text:
nz_meshblock_geojson
============================

Meshblocks converted to GeoJSON of Statistics New Zealand meshblocks

### Use with Bower:

Add the following to your bower.json:

```
"nz_meshblock_geojson": "git://github.com/tuttinator/nz_meshblock_geojson#1.0.0"
```

#### Use with bower-rails:

Add the following to your Bowerfile:

```
asset 'nz_meshblock_geojson', '1.0.0', github: 'tuttinator/nz_meshblock_geojson'
```

### Contributing

Feel free to fork and send pull requests, or open issues if you run into
any mistakes.


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>jQuery Validation</title>

		<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">

		<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

					<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-6">
            Toggle navigation

          </button>
					JQ validation

							Example

							Options

							Github

 Examples

							Basis

							Callback

							Expand

							Regular

Html

									<textarea class="form-control" rows="18">

<form class="form-horizontal" role="form" id="basis-form">
  <div class="form-group">
    <label class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" placeholder="Input Email" data-type='email'></div>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" placeholder="Input Password" data-type='password'></div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="button" class="btn btn-default">Submit</button></div>
  </div>
</form>
										</textarea>

JS

$('.form-horizontal').validation();

RUN

									<form class="form-horizontal" role="form" id="basis-form">

											Email

												<input type="email" class="form-control" placeholder="Input Email" data-type='email'>

											Password

												<input type="password" class="form-control" placeholder="Input Password" data-type='password'>

												<button type="button" class="btn btn-default">Submit</button>

									</form>

Html

									<textarea class="form-control" rows="18">

<form class="form-horizontal" role="form" id="callback-form">
  <div class="form-group">
    <label class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" placeholder="Input Email" data-type='email'></div>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" placeholder="Input Password" data-type='password'></div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="button" class="btn btn-default">Submit</button></div>
  </div>
</form>
										</textarea>

JS

$('#callback-form').validation({
	validationcallBack: function(status, dom, errorMsg, defaultValue) {
		status || layer.tips(errorMsg,dom);
	}
});

RUN

									<form class="form-horizontal" role="form" id="callback-form">

											Email

												<input type="email" class="form-control" placeholder="Input Email" data-type='email'>

											Password

												<input type="password" class="form-control" placeholder="Input Password" data-type='password'>

												<button type="button" class="btn btn-default">Submit</button>

									</form>

Html

									<textarea class="form-control" rows="23">

<form class="form-horizontal" role="form" id="expand-form">
  <div class="form-group">
    <label class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" placeholder="Input Email" data-type='email'></div>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">Zip code</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" placeholder="Input Zip code" data-type='zip'></div>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" placeholder="Input Password" data-type='password'></div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="button" class="btn btn-default">Submit</button></div>
  </div>
</form>
										</textarea>

JS

$('#expand-form').validation({
	validationcallBack: function(status, dom, errorMsg, defaultValue) {
		status || layer.tips(errorMsg, dom);
	},
	addOnRules: {
		zip: {
			validate: function(value) {
				return /^[1-9]\d{5}(?!\d)$/.test(value);
			},
			errorMsg: 'Input Zip code',
			defaultValue: '400000'
		}
	}
})

RUN

									<form class="form-horizontal" role="form" id="expand-form">

											Email

												<input type="email" class="form-control" placeholder="Input Email" data-type='email'>

											Zip code

												<input type="email" class="form-control" placeholder="Input Zip code" data-type='zip'>

											Password

												<input type="password" class="form-control" placeholder="Input Password" data-type='password'>

												<button type="button" class="btn btn-default">Submit</button>

									</form>

Html

									<textarea class="form-control" rows="20">
<form class="form-horizontal" role="form">
	<div class="form-group">
		<label class="col-sm-2 control-label">Email</label>
		<div class="col-sm-10">
			<input type="email" class="form-control" placeholder="Input Email" data-type='email'>
		</div>
	</div>
	<div class="form-group">
		<label class="col-sm-2 control-label">Password</label>
		<div class="col-sm-10">
			<input type="password" class="form-control" placeholder="Input Password" data-type='password'>
		</div>
	</div>
	<div class="form-group">
		<div class="col-sm-offset-2 col-sm-10">
			<button type="button" class="btn btn-default">Submit</button>
		</div>
	</div>
</form>
										</textarea>

JS

$('#regular-form').validation({
	validationcallBack: function(status, dom, errorMsg, defaultValue) {
		status || layer.tips(errorMsg, dom);
	}
})

RUN

									<form class="form-horizontal" role="form" id="regular-form">

											Id Card

												<input type="email" class="form-control" placeholder="Input Id Card" data-type='reg' data-reg='/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/'>

											Zip code

												<input type="email" class="form-control" placeholder="Input Zip code" data-type='zip'>

											Password

												<input type="password" class="form-control" placeholder="Input Password" data-type='password'>

												<button type="button" class="btn btn-default">Submit</button>

									</form>


text:
package manager;

/**
 *
 * @author Andrew M. Teller(https://github.com/AndrewMiTe)
 */
public interface DataItem {

  /**
   * Returns the required input that this data item satisfies. Returns a null
   * value if it fulfills no required input.
   * @return the required input that the item satisfies.
   */
  public RequiredInput getRequirement();

  /**
   * @param requirement requirement that the text fulfills.
   * @return this data item.
   */
  public DataItem setRequirement(RequiredInput requirement);

}


text:
package org.apache.geode.cache.query.internal.parse;

import antlr.Token;

import org.apache.geode.cache.query.internal.QCompiler;
import org.apache.geode.cache.query.internal.Support;

public class ASTUnary extends GemFireAST {
  private static final long serialVersionUID = -3906821390970046083L;

  public ASTUnary(Token t) {
    super(t);
  }

  public ASTUnary() {}

  @Override
  public void compile(QCompiler compiler) {
    if (getType() == OQLLexerTokenTypes.TOK_MINUS) {
      GemFireAST child = (GemFireAST) getFirstChild();
      int tokenType = child.getType();
      if (tokenType == OQLLexerTokenTypes.NUM_INT || tokenType == OQLLexerTokenTypes.NUM_LONG
          || tokenType == OQLLexerTokenTypes.NUM_FLOAT
          || tokenType == OQLLexerTokenTypes.NUM_DOUBLE) {
        Support.Assert(child.getNextSibling() == null);
        child.setText('-' + child.getText());
        child.compile(compiler);
      } else {
        super.compile(compiler);
        compiler.unaryMinus();
      }
    } else {
      super.compile(compiler);
      compiler.not();
    }
  }
}


text:
<?php

namespace PHPCI\Controller;

use b8;
use b8\Exception\HttpException\NotFoundException;
use PHPCI\BuildFactory;
use PHPCI\Model\Build;
use PHPCI\Service\BuildService;

/**
* Build Controller - Allows users to run and view builds.
* @author       Dan Cryer <dan@block8.co.uk>
* @package      PHPCI
* @subpackage   Web
*/
class BuildController extends \PHPCI\Controller
{
    /**
     * @var \PHPCI\Store\BuildStore
     */
    protected $buildStore;

    /**
     * @var \PHPCI\Service\BuildService
     */
    protected $buildService;

    public function init()
    {
        $this->buildStore = b8\Store\Factory::getStore('Build');
        $this->buildService = new BuildService($this->buildStore);
    }

    /**
    * View a specific build.
    */
    public function view($buildId)
    {
        try {
            $build = BuildFactory::getBuildById($buildId);
        } catch (\Exception $ex) {
            $build = null;
        }

        if (empty($build)) {
            throw new NotFoundException('Build with ID: ' . $buildId . ' does not exist.');
        }

        $this->view->plugins  = $this->getUiPlugins();
        $this->view->build    = $build;
        $this->view->data     = $this->getBuildData($build);

        $title = 'Build #' . $build->getId() . ' - ' . $build->getProjectTitle();
        $this->config->set('page_title', $title);
    }

    protected function getUiPlugins()
    {
        $rtn = array();
        $path = APPLICATION_PATH . 'public/assets/js/build-plugins/';
        $dir = opendir($path);

        while ($item = readdir($dir)) {
            if (substr($item, 0, 1) == '.' || substr($item, -3) != '.js') {
                continue;
            }

            $rtn[] = $item;
        }

        return $rtn;
    }

    /**
    * AJAX call to get build data:
    */
    public function data($buildId)
    {
        die($this->getBuildData(BuildFactory::getBuildById($buildId)));
    }

    /**
     * AJAX call to get build meta:
     */
    public function meta($buildId)
    {
        $build  = BuildFactory::getBuildById($buildId);
        $key = $this->getParam('key', null);
        $numBuilds = $this->getParam('num_builds', 1);
        $data = null;

        if ($key && $build) {
            $data = $this->buildStore->getMeta($key, $build->getProjectId(), $buildId, $numBuilds);
        }

        die(json_encode($data));
    }

    /**
    * Get build data from database and json encode it:
    */
    protected function getBuildData($build)
    {
        $data               = array();
        $data['status']     = (int)$build->getStatus();
        $data['log']        = $this->cleanLog($build->getLog());
        $data['created']    = !is_null($build->getCreated()) ? $build->getCreated()->format('Y-m-d H:i:s') : null;
        $data['started']    = !is_null($build->getStarted()) ? $build->getStarted()->format('Y-m-d H:i:s') : null;
        $data['finished']   = !is_null($build->getFinished()) ? $build->getFinished()->format('Y-m-d H:i:s') : null;

        return json_encode($data);
    }

    /**
    * Create a build using an existing build as a template:
    */
    public function rebuild($buildId)
    {
        $copy   = BuildFactory::getBuildById($buildId);

        if (empty($copy)) {
            throw new NotFoundException('Build with ID: ' . $buildId . ' does not exist.');
        }

        $build = $this->buildService->createDuplicateBuild($copy);

        header('Location: '.PHPCI_URL.'build/view/' . $build->getId());
        exit;
    }

    /**
    * Delete a build.
    */
    public function delete($buildId)
    {
        if (empty($_SESSION['user']) || !$_SESSION['user']->getIsAdmin()) {
            throw new \Exception('You do not have permission to do that.');
        }

        $build = BuildFactory::getBuildById($buildId);

        if (empty($build)) {
            throw new NotFoundException('Build with ID: ' . $buildId . ' does not exist.');
        }

        $this->buildService->deleteBuild($build);

        header('Location: '.PHPCI_URL.'project/view/' . $build->getProjectId());
        exit;
    }

    /**
    * Parse log for unix colours and replace with HTML.
    */
    protected function cleanLog($log)
    {
        $log = str_replace('[0;32m', '', $log);
        $log = str_replace('[0;31m', '', $log);
        $log = str_replace('[0m', '', $log);

        return $log;
    }
}


text:
package org.apache.drill.exec.server.options;

import java.util.HashMap;

import org.apache.drill.exec.server.options.OptionValue.OptionType;

public class QueryOptionManager extends InMemoryOptionManager {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SessionOptionManager.class);

  public QueryOptionManager(OptionManager sessionOptions) {
    super(sessionOptions, new HashMap<String, OptionValue>());
  }

  @Override
  boolean supportsOption(OptionValue value) {
    return value.type == OptionType.QUERY;
  }

}


text:
package com.team254.frc2013.commands;

import com.team254.frc2013.Constants;
import com.team254.lib.util.ThrottledPrinter;
import com.team254.lib.util.Util;
import edu.wpi.first.wpilibj.DriverStation;

/**
 * Controls the robot drive train using the standard Team 254 scheme.
 *
 * @author richard@team254.com (Richard Lin)
 */
public class CheesyDriveCommand extends CommandBase {
  private double oldWheel = 0.0;
  private double quickStopAccumulator;
  private double throttleDeadband = 0.02;
  private double wheelDeadband = 0.02;
  ThrottledPrinter p = new ThrottledPrinter(.1);

  public CheesyDriveCommand() {
    requires(drive);
  }

  protected void initialize() {
    drive.disableControllers() ;
  }

  protected void execute() {
    if (DriverStation.getInstance().isAutonomous()) {
      return;
    }
    boolean isQuickTurn = controlBoard.getQuickTurn();
    boolean isHighGear = controlBoard.getHighGear();
    drive.shift(isHighGear);

    double wheelNonLinearity;

    double wheel = handleDeadband(controlBoard.rightStick.getX(), wheelDeadband);
    double throttle = -handleDeadband(controlBoard.leftStick.getY(), throttleDeadband);

    double negInertia = wheel - oldWheel;
    oldWheel = wheel;

    if (isHighGear) {
      wheelNonLinearity = 0.6;
      // Apply a sin function that's scaled to make it feel better.
      wheel = Math.sin(Math.PI / 2.0 * wheelNonLinearity * wheel) /
          Math.sin(Math.PI / 2.0 * wheelNonLinearity);
      wheel = Math.sin(Math.PI / 2.0 * wheelNonLinearity * wheel) /
          Math.sin(Math.PI / 2.0 * wheelNonLinearity);
    } else {
      wheelNonLinearity = 0.5;
      // Apply a sin function that's scaled to make it feel better.
      wheel = Math.sin(Math.PI / 2.0 * wheelNonLinearity * wheel) /
          Math.sin(Math.PI / 2.0 * wheelNonLinearity);
      wheel = Math.sin(Math.PI / 2.0 * wheelNonLinearity * wheel) /
          Math.sin(Math.PI / 2.0 * wheelNonLinearity);
      wheel = Math.sin(Math.PI / 2.0 * wheelNonLinearity * wheel) /
          Math.sin(Math.PI / 2.0 * wheelNonLinearity);
    }

    double leftPwm, rightPwm, overPower;
    double sensitivity = 1.7;

    double angularPower;
    double linearPower;

    // Negative inertia!
    double negInertiaAccumulator = 0.0;
    double negInertiaScalar;
    if (isHighGear) {
      negInertiaScalar = 5.0;
      sensitivity = Constants.sensitivityHigh.getDouble();
    } else {
      if (wheel * negInertia > 0) {
        negInertiaScalar = 2.5;
      } else {
        if (Math.abs(wheel) > 0.65) {
          negInertiaScalar = 5.0;
        } else {
          negInertiaScalar = 3.0;
        }
      }
      sensitivity = Constants.sensitivityLow.getDouble();

      if (Math.abs(throttle) > 0.1) {
       // sensitivity = 1.0 - (1.0 - sensitivity) / Math.abs(throttle);
      }
    }
    double negInertiaPower = negInertia * negInertiaScalar;
    negInertiaAccumulator += negInertiaPower;

    wheel = wheel + negInertiaAccumulator;
    if (negInertiaAccumulator > 1) {
      negInertiaAccumulator -= 1;
    } else if (negInertiaAccumulator < -1) {
      negInertiaAccumulator += 1;
    } else {
      negInertiaAccumulator = 0;
    }
    linearPower = throttle;

    // Quickturn!
    if (isQuickTurn) {
      if (Math.abs(linearPower) < 0.2) {
        double alpha = 0.1;
        quickStopAccumulator = (1 - alpha) * quickStopAccumulator + alpha *
            Util.limit(wheel, 1.0) * 5;
      }
      overPower = 1.0;
      if (isHighGear) {
        sensitivity = 1.0;
      } else {
        sensitivity = 1.0;
      }
      angularPower = wheel;
    } else {
      overPower = 0.0;
      angularPower = Math.abs(throttle) * wheel * sensitivity - quickStopAccumulator;
      if (quickStopAccumulator > 1) {
        quickStopAccumulator -= 1;
      } else if (quickStopAccumulator < -1) {
        quickStopAccumulator += 1;
      } else {
        quickStopAccumulator = 0.0;
      }
    }

    rightPwm = leftPwm = linearPower;
    leftPwm += angularPower;
    rightPwm -= angularPower;

    if (leftPwm > 1.0) {
      rightPwm -= overPower * (leftPwm - 1.0);
      leftPwm = 1.0;
    } else if (rightPwm > 1.0) {
      leftPwm -= overPower * (rightPwm - 1.0);
      rightPwm = 1.0;
    } else if (leftPwm < -1.0) {
      rightPwm += overPower * (-1.0 - leftPwm);
      leftPwm = -1.0;
    } else if (rightPwm < -1.0) {
      leftPwm += overPower * (-1.0 - rightPwm);
      rightPwm = -1.0;
    }

    drive.setLeftRightPower(leftPwm, rightPwm);
  }

  protected boolean isFinished() {
    return false;
  }

  protected void end() {
  }

  protected void interrupted() {
  }

  public double handleDeadband(double val, double deadband) {
    return (Math.abs(val) > Math.abs(deadband)) ? val : 0.0;
  }
}