text:
"""
Unit tests for the Function2D class.
"""

import math
import unittest
from raysect.core.math.function.float.function2d.autowrap import PythonFunction2D

# TODO: expand tests to cover the cython interface
class TestFunction2D(unittest.TestCase):

    def setUp(self):

        self.ref1 = lambda x, y: 10 * x + 5 * y
        self.ref2 = lambda x, y: x * x + y * y

        self.f1 = PythonFunction2D(self.ref1)
        self.f2 = PythonFunction2D(self.ref2)

    def test_call(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        for x in v:
            for y in v:
                self.assertEqual(self.f1(x, y), self.ref1(x, y), "Function2D call did not match reference function value.")

    def test_negate(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        r = -self.f1
        for x in v:
            for y in v:
                self.assertEqual(r(x, y), -self.ref1(x, y), "Function2D negate did not match reference function value.")

    def test_add_scalar(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        r1 = 8 + self.f1
        r2 = self.f1 + 65
        for x in v:
            for y in v:
                self.assertEqual(r1(x, y), 8 + self.ref1(x, y), "Function2D add scalar (K + f()) did not match reference function value.")
                self.assertEqual(r2(x, y), self.ref1(x, y) + 65, "Function2D add scalar (f() + K) did not match reference function value.")

    def test_sub_scalar(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        r1 = 8 - self.f1
        r2 = self.f1 - 65
        for x in v:
            for y in v:
                self.assertEqual(r1(x, y), 8 - self.ref1(x, y), "Function2D subtract scalar (K - f()) did not match reference function value.")
                self.assertEqual(r2(x, y), self.ref1(x, y) - 65, "Function2D subtract scalar (f() - K) did not match reference function value.")

    def test_mul_scalar(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        r1 = 5 * self.f1
        r2 = self.f1 * -7.8
        for x in v:
            for y in v:
                self.assertEqual(r1(x, y), 5 * self.ref1(x, y), "Function2D multiply scalar (K * f()) did not match reference function value.")
                self.assertEqual(r2(x, y), self.ref1(x, y) * -7.8, "Function2D multiply scalar (f() * K) did not match reference function value.")

    def test_div_scalar(self):
        v = [-1e10, -7, -0.001, 0.00003, 10, 2.3e49]
        r1 = 5 / self.f1
        r2 = self.f1 / -7.8
        for x in v:
            for y in v:
                self.assertEqual(r1(x, y), 5 / self.ref1(x, y), "Function2D divide scalar (K / f()) did not match reference function value.")
                self.assertAlmostEqual(r2(x, y), self.ref1(x, y) / -7.8, delta=abs(r2(x, y)) * 1e-12, msg="Function2D divide scalar (f() / K) did not match reference function value.")

        r = 5 / self.f1
        with self.assertRaises(ZeroDivisionError, msg="ZeroDivisionError not raised when function returns zero."):
            r(0, 0)

    def test_mod_function2d_scalar(self):
        # Note that Function2D objects work with doubles, so the floating modulo
        # operator is used rather than the integer one. For accurate testing we
        # therefore need to use the math.fmod operator rather than % in Python.
        v = [-10, -7, -0.001, 0.00003, 10, 12.3]
        r1 = 5 % self.f1
        r2 = self.f1 % -7.8
        for x in v:
            for y in v:
                self.assertAlmostEqual(r1(x, y), math.fmod(5, self.ref1(x, y)), 15, "Function2D modulo scalar (K % f()) did not match reference function value.")
                self.assertAlmostEqual(r2(x, y), math.fmod(self.ref1(x, y), -7.8), 15, "Function2D modulo scalar (f() % K) did not match reference function value.")
        with self.assertRaises(ZeroDivisionError, msg="ZeroDivisionError not raised when function returns 0."):
            r1(0, 0)
        with self.assertRaises(ZeroDivisionError, msg="ZeroDivisionError not raised when modulo scalar is 0."):
            self.f1 % 0

    def test_pow_function2d_scalar(self):
        v = [-10, -7, -0.001, 0.00003, 10, 12.3]
        r1 = 5 ** self.f1
        r2 = self.f1 ** -7.8
        r3 = (-5) ** self.f1
        for x in v:
            for y in v:
                self.assertAlmostEqual(r1(x, y), 5 ** self.ref1(x, y), 15, "Function2D power scalar (K ** f()) did not match reference function value.")
                if self.ref1(x, y) < 0:
                    with self.assertRaises(ValueError, msg="ValueError not raised when base is negative and exponent non-integral."):
                        r2(x, y)
                elif not float(self.ref1(x, y)).is_integer():
                    with self.assertRaises(ValueError, msg="ValueError not raised when base is negative and exponent non-integral."):
                        r3(x, y)
                else:
                    self.assertAlmostEqual(r2(x, y), self.ref1(x, y) ** -7.8, 15, "Function2D power scalar (f() ** K) did not match reference function value.")
        with self.assertRaises(ZeroDivisionError, msg="ZeroDivisionError not raised when base is 0 and exponent negative."):
            r2(0, 0)
        with self.assertRaises(ZeroDivisionError, msg="ZeroDivisionError not raised when base is 0 and exponent negative."):
            r4 = 0 ** self.f1
            r4(-1, 0)

    def test_richcmp_scalar(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        for x in v:
            for y in v:
                ref_value = self.ref1(x, y)
                higher_value = ref_value + abs(ref_value) + 1
                lower_value = ref_value - abs(ref_value) - 1
                self.assertEqual(
                    (self.f1 == ref_value)(x, y), 1.0,
                    msg="Function2D equals scalar (f() == K) did not return true when it should."
                )
                self.assertEqual(
                    (ref_value == self.f1)(x, y), 1.0,
                    msg="Scalar equals Function2D (K == f()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 == higher_value)(x, y), 0.0,
                    msg="Function2D equals scalar (f() == K) did not return false when it should."
                )
                self.assertEqual(
                    (higher_value == self.f1)(x, y), 0.0,
                    msg="Scalar equals Function2D (K == f()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 != higher_value)(x, y), 1.0,
                    msg="Function2D not equals scalar (f() != K) did not return true when it should."
                )
                self.assertEqual(
                    (higher_value != self.f1)(x, y), 1.0,
                    msg="Scalar not equals Function2D (K != f()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 != ref_value)(x, y), 0.0,
                    msg="Function2D not equals scalar (f() != K) did not return false when it should."
                )
                self.assertEqual(
                    (ref_value != self.f1)(x, y), 0.0,
                    msg="Scalar not equals Function2D (K != f()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 < higher_value)(x, y), 1.0,
                    msg="Function2D less than scalar (f() < K) did not return true when it should."
                )
                self.assertEqual(
                    (lower_value < self.f1)(x, y), 1.0,
                    msg="Scalar less than Function2D (K < f()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 < lower_value)(x, y), 0.0,
                    msg="Function2D less than scalar (f() < K) did not return false when it should."
                )
                self.assertEqual(
                    (higher_value < self.f1)(x, y), 0.0,
                    msg="Scalar less than Function2D (K < f()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 > lower_value)(x, y), 1.0,
                    msg="Function2D greater than scalar (f() > K) did not return true when it should."
                )
                self.assertEqual(
                    (higher_value > self.f1)(x, y), 1.0,
                    msg="Scalar greater than Function2D (K > f()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 > higher_value)(x, y), 0.0,
                    msg="Function2D greater than scalar (f() > K) did not return false when it should."
                )
                self.assertEqual(
                    (lower_value > self.f1)(x, y), 0.0,
                    msg="Scalar greater than Function2D (K > f()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 <= higher_value)(x, y), 1.0,
                    msg="Function2D less equals scalar (f() <= K) did not return true when it should."
                )
                self.assertEqual(
                    (lower_value <= self.f1)(x, y), 1.0,
                    msg="Scalar less equals Function2D (K <= f()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 <= ref_value)(x, y), 1.0,
                    msg="Function2D less equals scalar (f() <= K) did not return true when it should."
                )
                self.assertEqual(
                    (ref_value <= self.f1)(x, y), 1.0,
                    msg="Scalar less equals Function2D (K <= f()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 <= lower_value)(x, y), 0.0,
                    msg="Function2D less equals scalar (f() <= K) did not return false when it should."
                )
                self.assertEqual(
                    (higher_value <= self.f1)(x, y), 0.0,
                    msg="Scalar less equals Function2D (K <= f()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 >= lower_value)(x, y), 1.0,
                    msg="Function2D greater equals scalar (f() >= K) did not return true when it should."
                )
                self.assertEqual(
                    (higher_value >= self.f1)(x, y), 1.0,
                    msg="Scalar greater equals Function2D (K >= f()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 >= ref_value)(x, y), 1.0,
                    msg="Function2D greater equals scalar (f() >= K) did not return true when it should."
                )
                self.assertEqual(
                    (ref_value >= self.f1)(x, y), 1.0,
                    msg="Scalar greater equals Function2D (K >= f()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 >= higher_value)(x, y), 0.0,
                    msg="Function2D greater equals scalar (f() >= K) did not return false when it should."
                )
                self.assertEqual(
                    (lower_value >= self.f1)(x, y), 0.0,
                    msg="Scalar greater equals Function2D (K >= f()) did not return false when it should."
                )

    def test_add_function2d(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        r1 = self.f1 + self.f2
        r2 = self.ref1 + self.f2
        r3 = self.f1 + self.ref2
        for x in v:
            for y in v:
                self.assertEqual(r1(x, y), self.ref1(x, y) + self.ref2(x, y), "Function2D add function (f1() + f2()) did not match reference function value.")
                self.assertEqual(r2(x, y), self.ref1(x, y) + self.ref2(x, y), "Function2D add function (p1() + f2()) did not match reference function value.")
                self.assertEqual(r3(x, y), self.ref1(x, y) + self.ref2(x, y), "Function2D add function (f1() + p2()) did not match reference function value.")

    def test_sub_function2d(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        r = self.f1 - self.f2
        r2 = self.ref1 - self.f2
        r3 = self.f1 - self.ref2
        for x in v:
            for y in v:
                self.assertEqual(r(x, y), self.ref1(x, y) - self.ref2(x, y), "Function2D subtract function (f1() - f2()) did not match reference function value.")
                self.assertEqual(r2(x, y), self.ref1(x, y) - self.ref2(x, y), "Function2D subtract function (p1() - f2()) did not match reference function value.")
                self.assertEqual(r3(x, y), self.ref1(x, y) - self.ref2(x, y), "Function2D subtract function (f1() - p2()) did not match reference function value.")

    def test_mul_function2d(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        r1 = self.f1 * self.f2
        r2 = self.ref1 * self.f2
        r3 = self.f1 * self.ref2
        for x in v:
            for y in v:
                self.assertEqual(r1(x, y), self.ref1(x, y) * self.ref2(x, y), "Function2D multiply function (f1() * f2()) did not match reference function value.")
                self.assertEqual(r2(x, y), self.ref1(x, y) * self.ref2(x, y), "Function2D multiply function (p1() * f2()) did not match reference function value.")
                self.assertEqual(r3(x, y), self.ref1(x, y) * self.ref2(x, y), "Function2D multiply function (f1() * p2()) did not match reference function value.")

    def test_div_function2d(self):
        v = [-1e10, -7, -0.001, 0.00003, 10, 2.3e49]
        r1 = self.f1 / self.f2
        r2 = self.ref1 / self.f2
        r3 = self.f1 / self.ref2
        for x in v:
            for y in v:
                self.assertAlmostEqual(r1(x, y), self.ref1(x, y) / self.ref2(x, y), delta=abs(r1(x, y)) * 1e-12, msg="Function2D divide function (f1() / f2()) did not match reference function value.")
                self.assertAlmostEqual(r2(x, y), self.ref1(x, y) / self.ref2(x, y), delta=abs(r2(x, y)) * 1e-12, msg="Function2D divide function (p1() / f2()) did not match reference function value.")
                self.assertAlmostEqual(r3(x, y), self.ref1(x, y) / self.ref2(x, y), delta=abs(r3(x, y)) * 1e-12, msg="Function2D divide function (f1() / p2()) did not match reference function value.")

        with self.assertRaises(ZeroDivisionError, msg="ZeroDivisionError not raised when function returns zero."):
            r1(0, 0)

    def test_mod_function2d(self):
        v = [-1e10, -7, -0.001, 0.00003, 10, 2.3e9]
        r1 = self.f1 % self.f2
        r2 = self.ref1 % self.f2
        r3 = self.f1 % self.ref2
        for x in v:
            for y in v:
                self.assertAlmostEqual(r1(x, y), math.fmod(self.ref1(x, y), self.ref2(x, y)), delta=abs(r1(x, y)) * 1e-12, msg="Function2D modulo function (f1() % f2()) did not match reference function value.")
                self.assertAlmostEqual(r2(x, y), math.fmod(self.ref1(x, y), self.ref2(x, y)), delta=abs(r2(x, y)) * 1e-12, msg="Function2D modulo function (p1() % f2()) did not match reference function value.")
                self.assertAlmostEqual(r3(x, y), math.fmod(self.ref1(x, y), self.ref2(x, y)), delta=abs(r3(x, y)) * 1e-12, msg="Function2D modulo function (f1() % p2()) did not match reference function value.")

        with self.assertRaises(ZeroDivisionError, msg="ZeroDivisionError not raised when function returns zero."):
            r1(0, 0)

    def test_pow_function2d_function2d(self):
        v = [-3.0, -0.7, -0.001, 0.00003, 2]
        r1 = self.f1 ** self.f2
        r2 = self.ref1 ** self.f2
        r3 = self.f1 ** self.ref2
        for x in v:
            for y in v:
                if self.ref1(x, y) < 0 and not float(self.ref2(x, y)).is_integer():
                    with self.assertRaises(ValueError, msg="ValueError not raised when base is negative and exponent non-integral (1/3)."):
                        r1(x, y)
                    with self.assertRaises(ValueError, msg="ValueError not raised when base is negative and exponent non-integral (2/3)."):
                        r2(x, y)
                    with self.assertRaises(ValueError, msg="ValueError not raised when base is negative and exponent non-integral (3/3)."):
                        r3(x, y)
                else:
                    self.assertAlmostEqual(r1(x, y), self.ref1(x, y) ** self.ref2(x, y), 15, "Function2D power function (f1() ** f2()) did not match reference function value.")
                    self.assertAlmostEqual(r2(x, y), self.ref1(x, y) ** self.ref2(x, y), 15, "Function2D power function (p1() ** f2()) did not match reference function value.")
                    self.assertAlmostEqual(r3(x, y), self.ref1(x, y) ** self.ref2(x, y), 15, "Function2D power function (f1() ** p2()) did not match reference function value.")
        with self.assertRaises(ZeroDivisionError, msg="ZeroDivisionError not raised when f1() == 0 and f2() is negative."):
            r4 = PythonFunction2D(lambda x, y: 0) ** self.f1
            r4(-1, 0)

    def test_pow_3_arguments(self):
        v = [-10, -7, -0.001, 0.00003, 2]
        r1 = pow(self.f1, 5, 3)
        r2 = pow(5, self.f1, 3)
        r3 = pow(5, self.f1, self.f2)
        r4 = pow(self.f2, self.f1, self.f2)
        r5 = pow(self.f2, self.ref1, self.ref2)
        r6 = pow(self.ref2, self.f1, self.f2)
        # Can't use 3 argument pow() if all arguments aren't integers, so
        # use fmod(a, b) % c instead
        for x in v:
            for y in v:
                self.assertEqual(r1(x, y), math.fmod(self.ref1(x, y) ** 5, 3), "Function2D 3 argument pow(f1(), A, B) did not match reference value.")
                self.assertEqual(r2(x, y), math.fmod(5 ** self.ref1(x, y), 3), "Function2D 3 argument pow(A, f1(), B) did not match reference value.")
                self.assertEqual(r3(x, y), math.fmod(5 ** self.ref1(x, y), self.ref2(x, y)), "Function2D 3 argument pow(A, f1(), f2()) did not match reference value.")
                self.assertEqual(r4(x, y), math.fmod(self.ref2(x, y) ** self.ref1(x, y), self.ref2(x, y)), "Function2D 3 argument pow(f2(), f1(), f2()) did not match reference value.")
                self.assertEqual(r5(x, y), math.fmod(self.ref2(x, y) ** self.ref1(x, y), self.ref2(x, y)), "Function2D 3 argument pow(f2(), p1(), p2()) did not match reference value.")
                self.assertEqual(r6(x, y), math.fmod(self.ref2(x, y) ** self.ref1(x, y), self.ref2(x, y)), "Function2D 3 argument pow(p2(), f1(), f2()) did not match reference value.")

    def test_abs(self):
        v = [-1e10, -7, -0.001, 0.0, 0.0003, 10, 2.3e49]
        for x in v:
            for y in v:
                self.assertEqual(abs(self.f1)(x, y), abs(self.ref1(x, y)),
                                 msg="abs(Function2D) did not match reference value")

    def test_richcmp_function_callable(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        for x in v:
            for y in v:
                ref_value = self.ref1
                higher_value = lambda x, y: self.ref1(x, y) + abs(self.ref1(x, y)) + 1
                lower_value = lambda x, y: self.ref1(x, y) - abs(self.ref1(x, y)) - 1
                self.assertEqual(
                    (self.f1 == ref_value)(x, y), 1.0,
                    msg="Function2D equals callable (f1() == f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 == higher_value)(x, y), 0.0,
                    msg="Function2D equals callable (f1() == f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 != higher_value)(x, y), 1.0,
                    msg="Function2D not equals callable (f1() != f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 != ref_value)(x, y), 0.0,
                    msg="Function2D not equals callable (f1() != f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 < higher_value)(x, y), 1.0,
                    msg="Function2D less than callable (f1() < f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 < lower_value)(x, y), 0.0,
                    msg="Function2D less than callable (f1() < f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 > lower_value)(x, y), 1.0,
                    msg="Function2D greater than callable (f1() > f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 > higher_value)(x, y), 0.0,
                    msg="Function2D greater than callable (f1() > f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 <= higher_value)(x, y), 1.0,
                    msg="Function2D less equals callable (f1() <= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 <= ref_value)(x, y), 1.0,
                    msg="Function2D less equals callable (f1() <= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 <= lower_value)(x, y), 0.0,
                    msg="Function2D less equals callable (f1() <= f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 >= lower_value)(x, y), 1.0,
                    msg="Function2D equals callable (f1() >= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 >= ref_value)(x, y), 1.0,
                    msg="Function2D greater equals callable (f1() >= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 >= higher_value)(x, y), 0.0,
                    msg="Function2D equals callable (f1() >= f2()) did not return false when it should."
                )

    def test_richcmp_callable_function(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        for x in v:
            for y in v:
                ref_value = self.ref1
                higher_value = lambda x, y: self.ref1(x, y) + abs(self.ref1(x, y)) + 1
                lower_value = lambda x, y: self.ref1(x, y) - abs(self.ref1(x, y)) - 1
                self.assertEqual(
                    (ref_value == self.f1)(x, y), 1.0,
                    msg="Callable equals Function2D (f1() == f2()) did not return true when it should."
                )
                self.assertEqual(
                    (higher_value == self.f1)(x, y), 0.0,
                    msg="Callable equals Function2D (f1() == f2()) did not return false when it should."
                )
                self.assertEqual(
                    (higher_value != self.f1)(x, y), 1.0,
                    msg="Callable not equals Function2D (f1() != f2()) did not return true when it should."
                )
                self.assertEqual(
                    (ref_value != self.f1)(x, y), 0.0,
                    msg="Callable not equals Function2D (f1() != f2()) did not return false when it should."
                )
                self.assertEqual(
                    (lower_value < self.f1)(x, y), 1.0,
                    msg="Callable less than Function2D (f1() < f2()) did not return true when it should."
                )
                self.assertEqual(
                    (higher_value < self.f1)(x, y), 0.0,
                    msg="Callable less than Function2D (f1() < f2()) did not return false when it should."
                )
                self.assertEqual(
                    (higher_value > self.f1)(x, y), 1.0,
                    msg="Callable greater than Function2D (f1() > f2()) did not return true when it should."
                )
                self.assertEqual(
                    (lower_value > self.f1)(x, y), 0.0,
                    msg="Callable greater than Function2D (f1() > f2()) did not return false when it should."
                )
                self.assertEqual(
                    (lower_value <= self.f1)(x, y), 1.0,
                    msg="Callable less equals Function2D (f1() <= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (ref_value <= self.f1)(x, y), 1.0,
                    msg="Callable less equals Function2D (f1() <= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (higher_value <= self.f1)(x, y), 0.0,
                    msg="Callable less equals Function2D (f1() <= f2()) did not return false when it should."
                )
                self.assertEqual(
                    (higher_value >= self.f1)(x, y), 1.0,
                    msg="Callable equals Function2D (f1() >= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (ref_value >= self.f1)(x, y), 1.0,
                    msg="Callable greater equals Function2D (f1() >= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (lower_value >= self.f1)(x, y), 0.0,
                    msg="Callable equals Function2D (f1() >= f2()) did not return false when it should."
                )

    def test_richcmp_function_function(self):
        v = [-1e10, -7, -0.001, 0.0, 0.00003, 10, 2.3e49]
        for x in v:
            for y in v:
                ref_value = self.f1
                higher_value = self.f1 + abs(self.f1) + 1
                lower_value = self.f1 - abs(self.f1) - 1
                self.assertEqual(
                    (self.f1 == ref_value)(x, y), 1.0,
                    msg="Function2D equals Function2D (f1() == f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 == higher_value)(x, y), 0.0,
                    msg="Function2D equals Function2D (f1() == f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 != higher_value)(x, y), 1.0,
                    msg="Function2D not equals Function2D (f1() != f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 != ref_value)(x, y), 0.0,
                    msg="Function2D not equals Function2D (f1() != f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 < higher_value)(x, y), 1.0,
                    msg="Function2D less than Function2D (f1() < f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 < lower_value)(x, y), 0.0,
                    msg="Function2D less than Function2D (f1() < f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 > lower_value)(x, y), 1.0,
                    msg="Function2D greater than Function2D (f1() > f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 > higher_value)(x, y), 0.0,
                    msg="Function2D greater than Function2D (f1() > f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 <= higher_value)(x, y), 1.0,
                    msg="Function2D less equals Function2D (f1() <= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 <= ref_value)(x, y), 1.0,
                    msg="Function2D less equals Function2D (f1() <= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 <= lower_value)(x, y), 0.0,
                    msg="Function2D less equals Function2D (f1() <= f2()) did not return false when it should."
                )
                self.assertEqual(
                    (self.f1 >= lower_value)(x, y), 1.0,
                    msg="Function2D equals Function2D (f1() >= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 >= ref_value)(x, y), 1.0,
                    msg="Function2D greater equals Function2D (f1() >= f2()) did not return true when it should."
                )
                self.assertEqual(
                    (self.f1 >= higher_value)(x, y), 0.0,
                    msg="Function2D equals Function2D (f1() >= f2()) did not return false when it should."
                )


text:
@interface YMButton : UIButton

@property (nonatomic,strong) NSIndexPath * appendIndexPath;

@end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 330340 $ -->

<book xml:id="book.kadm5" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <title>Kerberos V</title>
 <titleabbrev>KADM5</titleabbrev>

 <!-- {{{ preface -->
 <preface xml:id="intro.kadm5">
  &reftitle.intro;
  <simpara>
   These package allows you to access Kerberos V administration servers.
   You can create, modify, and delete Kerberos V principals and policies.
  </simpara>
  <simpara>
   More information about Kerberos can be found at <link
   xlink:href="&url.kerberos.info;">&url.kerberos.info;</link>.
  </simpara>
  <simpara>
   Documentation for Kerberos and KADM5 can be found at <link
   xlink:href="&url.kerberos.docs;">&url.kerberos.docs;</link>.
  </simpara>
 </preface>
 <!-- }}} -->

 &reference.kadm5.setup;
 &reference.kadm5.constants;
 &reference.kadm5.examples;
 &reference.kadm5.reference;

</book>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
//***********************************************************************/
//    Author                    : Garry
//    Original Date             : Oct,15 2005
//    Module Name               : PCI_DRV.H
//    Module Funciton           :
//                                This module countains PCI local system bus driver's definition
//                                code.
//    Last modified Author      :
//    Last modified Date        :
//    Last modified Content     :
//                                1.
//                                2.
//    Lines number              :
//***********************************************************************/

#ifndef __PCI_DRV_H__
#define __PCI_DRV_H__

#ifdef __cplusplus
extern "C" {
#endif

//
//The implementation of PciBusDriver routine.
//This is the entry routine for all system bus drivers,it is called by DeviceManager when
//this object is initializing.
//This routine checks if there is(are) PCI bus(es) in system,if not,returns FALSE,else,scan
//all PCI buses,configure all devices reside on the PCI buses,and returns TRUE.
//
BOOL PciBusDriver(__DEVICE_MANAGER* lpDevMgr);

//
//Constants used by PCI driver.
//
#define CONFIG_REGISTER          0xCF8    //Configure register used to read configure space.
#define DATA_REGISTER            0xCFC    //Data register.

//
//Common  part for all kinds of pre-defined headers.
//
#define PCI_CONFIG_OFFSET_VENDOR        0x00
#define PCI_CONFIG_OFFSET_DEVICE        0x02
#define PCI_CONFIG_OFFSET_COMMAND       0x04
#define PCI_CONFIG_OFFSET_STATUS        0x06
#define PCI_CONFIG_OFFSET_REVISION      0x08
#define PCI_CONFIG_OFFSET_CLASS         0x09
#define PCI_CONFIG_OFFSET_CACHELINESZ   0x0C
#define PCI_CONFIG_OFFSET_LATENCY       0x0D
#define PCI_CONFIG_OFFSET_HDRTYPE       0x0E
#define PCI_CONFIG_OFFSET_BIST          0x0F

//
//Configure space content for normal PCI device(Header type 0).
//
#define PCI_CONFIG_OFFSET_BASE1         0x10
#define PCI_CONFIG_OFFSET_BASE2         0x14
#define PCI_CONFIG_OFFSET_BASE3         0x18
#define PCI_CONFIG_OFFSET_BASE4         0x1C
#define PCI_CONFIG_OFFSET_BASE5         0x20
#define PCI_CONFIG_OFFSET_BASE6         0x24

#define PCI_CONFIG_OFFSET_CIS           0x28
#define PCI_CONFIG_OFFSET_SUBSYSID      0x2C
#define PCI_CONFIG_OFFSET_SYSID         0x2E
#define PCI_CONFIG_OFFSET_ROMBASE       0x30
#define PCI_CONFIG_OFFSET_CAP           0x34

#define PCI_CONFIG_OFFSET_INTLINE       0x3C
#define PCI_CONFIG_OFFSET_INTPIN        0x3D
#define PCI_CONFIG_OFFSET_MINGNT        0x3E
#define PCI_CONFIG_OFFSET_MAXLAT        0x3F

//
//Configure space content for PCI-PCI bridge(Header type 1).
//
#define PCI_CONFIG_OFFSET_PRIMARY       0x18
#define PCI_CONFIG_OFFSET_SECONDARY     0x19
#define PCI_CONFIG_OFFSET_SUBORDINAGE   0x1A
//#define PCI_CONFIG_OFFSET_LATENCY       0x1B

#define PCI_CONFIG_OFFSET_IOBASE        0x1C
#define PCI_CONFIG_OFFSET_IOLIMIT       0x1D
#define PCI_CONFIG_OFFSET_SECONDSTATUS  0x1E
#define PCI_CONFIG_OFFSET_MEMBASE       0x20
#define PCI_CONFIG_OFFSET_MEMLIMIT      0x22
#define PCI_CONFIG_OFFSET_PREMEMBASE    0x24
#define PCI_CONFIG_OFFSET_PREMEMLIMIT   0x26
#define PCI_CONFIG_OFFSET_PREMEMBASEUP  0X28
#define PCI_CONFIG_OFFSET_PREMEMLIMITUP 0x2C
#define PCI_CONFIG_OFFSET_IOBASEUP      0x30
#define PCI_CONFIG_OFFSET_IOLIMITUP     0x32
#define PCI_CONFIG_OFFSET_BCONTROL      0x3E

//
//The following defines used to indicate which part of __IDENTIFIER structure is
//set.Please refer to __IDENTIFIER's definition.
//
#define PCI_IDENTIFIER_MASK_VENDOR      0x01
#define PCI_IDENTIFIER_MASK_DEVICE      0x02
#define PCI_IDENTIFIER_MASK_CLASS       0x04
#define PCI_IDENTIFIER_MASK_HDRTYPE     0x08
#define PCI_IDENTIFIER_MASK_ALL         (0x01 | 0x02 | 0x04 | 0x08)

//
//Define a structure to contain PCI device specific information.
//
//BEGIN_DEFINE_OBJECT(__PCI_DEVICE_INFO)
typedef struct{
	DWORD             dwDeviceType;
	DWORD             DeviceNum   : 5;
	DWORD             FunctionNum : 3;
	DWORD             dwClassCode;
	UCHAR             ucPrimary;     //For PCI-PCI bridge only.
	UCHAR             ucSecondary;   //For PCI-PCI bridge only.
	UCHAR             ucSubordinate; //For PCI-PCI bridge only.
} __PCI_DEVICE_INFO;
//END_DEFINE_OBJECT()

//
//Device type's definition.
//
#define PCI_DEVICE_TYPE_BRIDGE       0x00000001
#define PCI_DEVICE_TYPE_NORMAL       0x00000002
#define PCI_DEVICE_TYPE_CARDBUS      0x00000004
#define PCI_DEVICE_TYPE_UNSUPPORTED  0x00000008
#define PCI_DEVICE_TYPE_EMPTY        0x00000000

#ifdef __cplusplus
}
#endif

#endif //__PCI_DRV_H__


text:
import EmberObject from '@ember/object';
let name;
import { module, test } from 'qunit';
import require from 'require';
import wait from 'ember-test-helpers/wait';
import { setupEIApp, destroyEIApp } from '../helpers/setup-destroy-ei-app';

let EmberDebug;
let port, adapter;
let App;
let EmberInspector;

module("Ember Debug", function(hooks) {
  hooks.beforeEach(async function() {
    EmberDebug = require('ember-debug/main').default;
    EmberDebug.Port = EmberDebug.Port.extend({
      init() {},
      send(n/*, m*/) {
        name = n;
      }
    });

    App = await setupEIApp.call(this, EmberDebug);

    EmberInspector = EmberDebug;
    port = EmberDebug.port;
    adapter = EmberDebug.get('port.adapter');
  });

  hooks.afterEach(async function() {
    name = null;
    await destroyEIApp.call(this, EmberDebug, App);
  });

  function cantSend(obj, assert) {
    try {
      EmberInspector.inspect(obj);
      assert.ok(false);
    } catch (e) {
      // Intentionally empty
    }
  }

  test("EmberInspector#inspect sends inspectable objects", function(assert) {
    let obj = EmberObject.create();
    EmberInspector.inspect(obj);
    assert.equal(name, "objectInspector:updateObject");
    name = null;
    obj = [];
    EmberInspector.inspect(obj);
    assert.equal(name, "objectInspector:updateObject");
    cantSend(1, assert);
    cantSend({}, assert);
    cantSend("a", assert);
    cantSend(null, assert);
  });

  test("Errors are caught and handled by EmberDebug", async function t(assert) {
    assert.expect(1);
    const error = new Error('test error');
    port.on('test:errors', () => {
      throw error;
    });

    const handleError = adapter.handleError;
    adapter.reopen({
      handleError(e) {
        assert.equal(e, error, 'Error handled');
      }
    });

    port.messageReceived('test:errors', {});

    await wait();
    adapter.reopen({ handleError });
  });
});


text:
<?php $this->load->view('partials/header'); ?>

<?php $this->load->view('partials/sidebar'); ?>

                    <?php echo $categorie->title; ?>

                        <a href="<?php echo site_url('categorie/lister'); ?>"><button class="btn btn-outline btn-sm btn-labeled btn-primary">Retour</button>

                            <img src="<?php echo $categorie->image; ?>" alt="<?php echo $categorie->title; ?>" class="img-thumbnail">

Description :

                                    <?php echo $categorie->description; ?>

            Les films de la catégorie <?php echo $categorie->title; ?>

                <?php
                if (!empty($moviesforcat)) {

                    foreach ($moviesforcat as $movieforcat) { ?>

                            <img class="img-responsive" src="<?php echo $movieforcat->image; ?>" alt="<?php echo $movieforcat->title; ?>">
                            <a href="<?php echo site_url('movie/voir/' . $movieforcat->id); ?>" class="text-bg text-bold"><?php echo $movieforcat->title; ?>

                            <a href="<?php echo site_url('movie/voir/' . $movieforcat->id); ?>"><button class="btn btn-flat btn-sm btn-labeled btn-info">voir</button>

                    <?php } ?>

                <?php } else { ?>

                            <button type="button" class="close" data-dismiss="alert"></button>
                            Aucun film dans cette catégorie

                <?php  } ?>

<?php $this->load->view('partials/footer'); ?>


text:
/********************************************/
var UserService = require('../../user');

exports.ready = function () {

	this.state = 'ready';

	if (this.room.isReady()) {
		return this.room_send('start', this.room.newGame(), true);

	} else {
		return this.room_send('ready');
	}
}

exports.play = function (data) {
	var self = this;
	return this.room.play(this.id, data).then(function (move) {
		if (move.winner) {
			UserService.saveWinner(move.winner).then(console.log).done();
		}
		return self.room_send('play', move, true);
	});
}


text:
import { PRESS_EVENT_TIMER_NAME } from '../constants';
import TouchEnvironmentActivation from './TouchEnvironmentActivation';

export default class PressActivation extends TouchEnvironmentActivation {
    constructor ({
        onIsActiveChanged,
        pressDurationInMs,
        pressMoveThreshold
    }) {
        super({ onIsActiveChanged });

        this.pressDurationInMs = pressDurationInMs;
        this.pressMoveThreshold = pressMoveThreshold;
    }

    touchStarted({ position }) {
        this.initPressEventCriteria(position);
        this.setPressEventTimer();
    }

    touchMoved({ position }) {
        if (this.isActive) {
            return;
        }

        this.setPressEventCriteria(position);
    }

    setPressEventTimer() {
        this.timers.push({
            name: PRESS_EVENT_TIMER_NAME,
            id: setTimeout(() => {
                if (Math.abs(this.currentElTop - this.initialElTop) < this.pressMoveThreshold) {
                    this.activate();
                }
            }, this.pressDurationInMs)
        });
    }

    setPressEventCriteria(position) {
        this.currentElTop = position.y;
    }

    initPressEventCriteria(position) {
        const top = position.y
        this.initialElTop = top;
        this.currentElTop = top;
    }
}


text:
using Google.Api;
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Monitoring.V3;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Google.Monitoring.V3.Snippets
{
    public class GeneratedGroupServiceClientSnippets
    {
        public async Task GetGroupAsync()
        {
            // Snippet: GetGroupAsync(string,CallSettings)
            // Additional: GetGroupAsync(string,CancellationToken)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]");
            // Make the request
            Group response = await groupServiceClient.GetGroupAsync(formattedName);
            // End snippet
        }

        public void GetGroup()
        {
            // Snippet: GetGroup(string,CallSettings)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]");
            // Make the request
            Group response = groupServiceClient.GetGroup(formattedName);
            // End snippet
        }

        public async Task CreateGroupAsync()
        {
            // Snippet: CreateGroupAsync(string,Group,CallSettings)
            // Additional: CreateGroupAsync(string,Group,CancellationToken)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatProjectName("[PROJECT]");
            Group group = new Group();
            // Make the request
            Group response = await groupServiceClient.CreateGroupAsync(formattedName, group);
            // End snippet
        }

        public void CreateGroup()
        {
            // Snippet: CreateGroup(string,Group,CallSettings)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatProjectName("[PROJECT]");
            Group group = new Group();
            // Make the request
            Group response = groupServiceClient.CreateGroup(formattedName, group);
            // End snippet
        }

        public async Task UpdateGroupAsync()
        {
            // Snippet: UpdateGroupAsync(Group,CallSettings)
            // Additional: UpdateGroupAsync(Group,CancellationToken)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            Group group = new Group();
            // Make the request
            Group response = await groupServiceClient.UpdateGroupAsync(group);
            // End snippet
        }

        public void UpdateGroup()
        {
            // Snippet: UpdateGroup(Group,CallSettings)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            Group group = new Group();
            // Make the request
            Group response = groupServiceClient.UpdateGroup(group);
            // End snippet
        }

        public async Task DeleteGroupAsync()
        {
            // Snippet: DeleteGroupAsync(string,CallSettings)
            // Additional: DeleteGroupAsync(string,CancellationToken)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]");
            // Make the request
            await groupServiceClient.DeleteGroupAsync(formattedName);
            // End snippet
        }

        public void DeleteGroup()
        {
            // Snippet: DeleteGroup(string,CallSettings)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]");
            // Make the request
            groupServiceClient.DeleteGroup(formattedName);
            // End snippet
        }

        public async Task ListGroupMembersAsync()
        {
            // Snippet: ListGroupMembersAsync(string,string,int?,CallSettings)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]");
            // Make the request
            IPagedAsyncEnumerable<ListGroupMembersResponse,MonitoredResource> response =
                groupServiceClient.ListGroupMembersAsync(formattedName);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((MonitoredResource item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;
            IAsyncEnumerable<FixedSizePage<MonitoredResource>> fixedSizePages = response.AsPages().WithFixedSize(pageSize);
            await fixedSizePages.ForEachAsync((FixedSizePage<MonitoredResource> page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (MonitoredResource item in page)
                {
                    Console.WriteLine(item);
                }
            });
            // End snippet
        }

        public void ListGroupMembers()
        {
            // Snippet: ListGroupMembers(string,string,int?,CallSettings)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]");
            // Make the request
            IPagedEnumerable<ListGroupMembersResponse,MonitoredResource> response =
                groupServiceClient.ListGroupMembers(formattedName);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (MonitoredResource item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;
            foreach (FixedSizePage<MonitoredResource> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (MonitoredResource item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }

    }
}


text:
//$LAB.script('http://maps.googleapis.com/maps/api/js?sensor=true').wait()

var fpSrc = [ 'fp/fp.min.js' ];
if (node_env == 'development') {
    fpSrc = [
         'fp/core/universe.js'
         , 'fp/core/catastrophe.js'
         , 'fp/core/agent/agent.js' , 'fp/core/agent/culture.js' , 'fp/core/agent/beliefs.js' , 'fp/core/agent/desires.js' , 'fp/core/agent/capabilities.js' , 'fp/core/agent/characteristics.js' , 'fp/core/agent/plans.js'
         , 'fp/core/campaign.js', 'fp/core/cell.js', 'fp/core/world.js', 'fp/core/wave.js', 'fp/core/resource.js', 'fp/core/species.js', 'fp/core/terrain.js', 'fp/core/tile.js'
         , 'fp/core/module-manager.js' , 'fp/core/module.js', 'fp/core/lifecycle.js', 'fp/core/statistics.js'

        , 'fp/core/agent/defaults/default_cultures.js'

        , 'fp/profile/profile.js', 'fp/profile/profile_class.js', 'fp/event/event.js'
         , 'fp/graphics/drawing.js', 'fp/graphics/orientation.js', 'fp/graphics/isometric.js', 'fp/graphics/fullscreen.js', 'fp/graphics/stick-figure.js'

         , 'fp/ui/dialogs/dialogs.js'
         , 'fp/ui/controls.js'
         , 'fp/ui/keyboard.js'
         , 'fp/ui/mouse.js'
         , 'fp/ui/editor.js'
         , 'fp/ui/general-ui.js'
         , 'fp/ui/world-gallery.js'
         , 'fp/ui/world-ui.js'
         , 'fp/ui/notice.js'
         , 'fp/ui/profile-ui.js'
         , 'fp/ui/resource-ui.js'
         , 'fp/ui/graph.js'
         , 'fp/ui/slider.js'
         , 'fp/ui/module-editor.js'
         , 'fp/ui/parameters.js'
         , 'fp/ui/console.js'
         , 'fp/ui/storyboard.js'
         , 'fp/ui/google-map.js'

         , 'fp/utils/fp-utils.js', 'fp/utils/log.js', 'fp/utils/recording.js', 'fp/utils/url-params.js'
        , 'fp/utils/comms.js'
        , 'fp/game.js'
    ];

}

$LAB
    .setOptions({BasePath:'/javascripts/'})

    // Load JQuery
//   .script('jquery/jquery-1.7.1.min.js')

    // Load JQuery UI & Plug-ins
    .script([

//        'jquery-ui-1.8.16.custom/js/jquery-ui-1.8.16.custom.min.js'
//        , 'jquery.balloon/jquery.balloon.js'
        , 'jquery/jquery.zoom.js'
    ])

    // Load other libraries
    .script([
    , 'flot-0.7/flot/jquery.flot.min.js'
    , 'jq-console/jqconsole-2.7.min.js'
    , 'jstat-2.0/jstat.js'
    , 'one-color/one-color-all.js'
    , 'socket.io/socket.io.js'
    , 'sylvester/sylvester.js'
    , 'underscore/underscore-min.js'
    ])

        // Load FiercePlanet other plugins
   .script(
        fpSrc
    )

    .script([
     , 'fp/default-module/default-module.js'
     , 'fp/default-module/resources/tbl.js'
     , 'fp/default-module/resources/cos.js'
     , 'fp/default-module/resources/resource_types.js'
     , 'fp/default-module/worlds/basic.js'
     , 'fp/default-module/worlds/additional.js'
    ])
    .wait(function() {
        FiercePlanet.GoogleMapUtils.initMaps();
        var m = urlParams.module;
        $LAB.setOptions({BasePath:'/javascripts/'}).script([
            , 'fp-modules/trials/wv/wv-module.js'
        ]).wait(function() {
                // Add callbacks to lifecycle
                FiercePlanet.Game.setupLifecycle();

//                $('#moduleEditor').show();
                WorldVisionModule.init();

                FiercePlanet.Orientation.initialiseParameters($('#world-container').width(), $('#world-container').height());

                Lifecycle._initialiseGame();
                console.log(FiercePlanet.Orientation.cellWidth)

                FiercePlanet.GeneralUI.worldInfo();

                // Draw the game
                //Lifecycle.newWorld();

            })

        /*
            DefaultModule.init();
            $('#content-pane').show();
            if (window.location.pathname === '/mobile') {
                Universe.settings.mobile = true;
                Universe.settings.useInlineResourceSwatch = true;
                FiercePlanet.Orientation.worldWidth = $(window).width();
                FiercePlanet.Orientation.worldHeight = $(window).height() - 160;
            }
            FiercePlanet.Game.loadGame();
            */
        var world = urlParams.world;
        if (!_.isUndefined(world)) {
            Lifecycle.currentWorldNumber = localStorage.currentWorldNumber = world;
        }
    })


text:
package com.microsoft.awt.components

import org.scalajs.angularjs.AngularJsHelper._
import org.scalajs.angularjs.{Controller, Q, Scope}
import com.microsoft.awt.models.EntitySearchResult

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
import scala.util.{Failure, Success}

/**
  * Represents a abstract controller with Auto Completion capability
  * @author lawrence.daniels@gmail.com
  */
abstract class AutoCompletionController($scope: AutoCompletionScope, $q: Q, reactiveSearchSvc: ReactiveSearchService) extends Controller {

  $scope.autoCompleteSearch = (searchTerm: String) => {
    val deferred = $q.defer[js.Array[EntitySearchResult]]()
    reactiveSearchSvc.search(searchTerm, maxResults = 20) onComplete {
      case Success(response) => deferred.resolve(response)
      case Failure(e) => deferred.reject(e.displayMessage)
    }
    deferred.promise
  }

}

/**
  * Auto Completion Scope
  * @author lawrence.daniels@gmail.com
  */
@js.native
trait AutoCompletionScope extends Scope {
  var autoCompleteSearch: js.Function1[String, js.Promise[js.Array[EntitySearchResult]]] = js.native

}


text:
package org.apache.axis2.transport.testkit.axis2;

import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.description.TransportOutDescription;
import org.apache.axis2.transport.testkit.axis2.client.AxisTestClientContextConfigurator;
import org.apache.axis2.transport.testkit.axis2.endpoint.AxisTestEndpointContextConfigurator;

/**
 * Resource used to create the {@link TransportInDescription} and
 * {@link TransportOutDescription} objects for a transport under test.
 * <p>
 * Note that this resource is used on both client and server side.
 * If the transport needs different configurations on client and server side,
 * use {@link AxisTestClientContextConfigurator} and/or
 * {@link AxisTestEndpointContextConfigurator}.
 */
public interface TransportDescriptionFactory {
    TransportOutDescription createTransportOutDescription() throws Exception;

    /**
     * Create a TransportInDescription for the transport under test.
     *
     * @return the transport description
     * @throws Exception
     */
    TransportInDescription createTransportInDescription() throws Exception;
}


text:
.. default-intersphinx:: rbt0.7

===========================
RBTools 0.7.6 Release Notes
===========================

**Release date:** April 26, 2016

New Features
============

rbt api-get
-----------

.. program:: rbt api-get

* rbt api-get can now be used outside of a checkout.

  When passing :option:`--server`, :rbtcommand:`rbt api-get` can be used
  anywhere, making it useful for more types of integrations.

Team Foundation Server
----------------------

.. program:: rbt post

* Added support for specifying the path to the :command:`tf.exe` command for
  TFS.

  The :command:`tf.exe` path can now be specified by using the
  :option:`--tf-cmd` option on the command line, or by setting
  ``TF_CMD`` in :file:`.reviewboardrc`.

  Patch by Brandon Martin.

* Added support for using :option:`--exclude` on TFS.

  Patch by Brandon Martin.

* Added support for branch (copy) operations on TFS.

  Branched/copied files can now be posted against Review Board when using
  `Power Pack`_ 1.4.1 or higher. These can also be combined with edit
  operations.

  Based on work by Brandon Martin.

.. _Power Pack: https://www.reviewboard.org/powerpack/

API
---

.. currentmodule:: rbtools.api.resource

* Added pagination helpers for all :py:class:`ListResources <ListResource>`.

  This introduces :py:func:`ListResource.all_pages`, which yields every page
  of the resource, and :py:func:`ListResource.all_items`, which yields every
  item on the page. These should help with processing pages of information
  from the API in a consistent way.

Performance Improvements
========================

* Reduced the work needed to look up ClearCase and Subversion repositories.

  For ClearCase and Subversion, it's necessary to fetch a list of all
  compatible repositories in order to compare certain information. We now
  take advantage of server-side filtering to reduce the set of repositories
  we have to scan through.

  Patch by Joshua Olson.

* Improved performance when locally scanning ClearCase repositories.

Bug Fixes
=========

General
-------

* When running in a non-interactive console, RBTools commands will no longer
  hang prompting for login credentials.

  It's up to the caller to ensure that RBTools has a valid session cookie or
  credentials (such as an API token) provided on the command line or in
  :file:`.reviewboardrc`.

  Patch by Vadim Zeitlin.

rbt post
--------

* Fixed posting commit IDs for non-Perforce clients.

  Patch by Ben Asher.

* The summary of a commit is no longer lost if passing a custom summary and
  guessing the description from the commit message.

  If the summary is passed on the command line but the description is guessed
  from the commit message, the first line of the commit message would be lost.
  This change improves that by concatenating the summary and description back
  together if the summary line isn't being used for the review request.

  Based on work by Alexander Goncahrov.

rbt setup-repo
--------------

* Improved the fuzzy matching of repositories, to help more accurately
  return possibly matching results.

  Patch by H W Tovetjärn.

Mercurial
---------

* Fixed broken parent commit IDs when using relative, negative, or short
  revisions. (:bug:`3915`)

  When referencing a relative revision (those starting with a ``^``), or
  specifying a negative or short revision number, hgweb would fail to find
  the matching commits. We now normalize those revisions.

  Patch by André Klitzing.

Perforce
--------

* Fixed a crash when posting a changelist that included a deleted symbolic
  link. (:bug:`4037`)

  This was supposed to log that the file would be skipped, but there was
  an error with the logging call.

  Patch by Akis Kalligeros.

* Fixed a Unicode mismatch when updating an existing review request from a
  changeset using :option:`rbt post -u`.

* Fixed a bad update call that would lead to an empty but harmless "CRITICAL"
  error message.

Team Foundation Server
----------------------

* Fixed :rbtcommand:`rbt setup-repo` with TFS repositories.

* Fixed properly decoding the character set of XML files coming from TFS.

Contributors
============

* Akis Kalligeros
* Alexander Goncahrov
* André Klitzing
* Barret Rennie
* Ben Asher
* Brandon Martin
* Christian Hammond
* David Trowbridge
* H W Tovetjärn
* Joshua Olson
* Vadim Zeitlin


text:
新增會員分類

 Home

會員分類管理

新增會員分類

                    <button class="btn btn-info btn-sm" data-widget="collapse" data-toggle="tooltip" title="Collapse"></button>
                    <button class="btn btn-info btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove"></button>

                <form action="/manager/CustomerType/add_customertype" class="form-horizontal" method="post"  enctype="multipart/form-data">

                      會員分類名稱

                        <input type="text" class="form-control" name="title" placeholder="分類名稱">

                    <button type="submit" class="btn btn-primary">建立分類</button>
                    <button type="button" class="btn btn-default" onClick="location.href='/manager/CustomerType'">取消</button>
                  </form>


text:
package fj;

import fj.data.Validation;
import fj.function.Try3;

import static fj.data.Validation.fail;
import static fj.data.Validation.success;

/**
 * Created by MarkPerry on 6/04/2014.
 */
public class F3Functions {

    /**
     * Partial application.
     *
     * @param a The A to which to apply this function.
     * @return The function partially applied to the given argument.
     */
    static public  F2 f(final F3 f, final A a) {
        return (b, c) -> f.f(a, b, c);
    }

}


text:
package com.example.secrets;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class ImportExport extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_import_export);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.import_export, menu);
		return true;
	}

	public void importFunction(View v){
		final Intent sender = getIntent();
		final String fileName = sender.getExtras().getString("FileName");
		final String resultedFileName = sender.getExtras().getString("ResultedFile");
		CaesarCode.decryptFile(fileName, resultedFileName);
		Toast message = Toast.makeText(ImportExport.this, "Your file has been decrypted", Toast.LENGTH_SHORT);
		message.show();
	}

	public void exportFunction(View v){
		final Intent sender = getIntent();
		final String fileName = sender.getExtras().getString("FileName");
		final String resultedFileName = sender.getExtras().getString("ResultedFile");
		try {
			CaesarCode.encryptFile(fileName, resultedFileName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Toast message = Toast.makeText(ImportExport.this, "Your file has been encrypted", Toast.LENGTH_SHORT);
		message.show();
	}

	public void IEBackFunction(View v){
		Intent intent = new Intent(ImportExport.this, MainActivity.class);
		startActivity(intent);

	}

}


text:
extern crate postgres;

use regex::Regex;
use error::Error;
use super::Driver;
use self::postgres::{Connection, SslMode};

const CREATE_SCHEMA_QUERY: &'static str = "create schema if not exists accelerate";
const CREATE_TABLE_QUERY: &'static str = "create table if not exists accelerate.record (name text not null)";
const GET_RECORDS_QUERY: &'static str = "select name from accelerate.record order by name";
const ADD_RECORD_QUERY: &'static str = "insert into accelerate.record (name) values ($1)";
const SUB_RECORD_QUERY: &'static str = "delete from accelerate.record where name = $1";

pub struct PostgresDriver {
  connection: Connection,
}

impl PostgresDriver {
  pub fn connect(conn_string: &str) -> Result<Self, Error> {
    let connection = try!(Connection::connect(conn_string, SslMode::None));

    try!(connection.execute(CREATE_SCHEMA_QUERY, &[]));
    try!(connection.execute(CREATE_TABLE_QUERY, &[]));

    Ok(PostgresDriver {
      connection: connection,
    })
  }

  pub fn will_accept_connection(conn_string: &str) -> bool {
    let conn_string_re = Regex::new(r"^(pg|postgres|postgresql)://").unwrap();
    conn_string_re.is_match(conn_string)
  }
}

impl Driver for PostgresDriver {
  fn get_records(&self) -> Result<Vec<String>, Error> {
    Ok(try!(self.connection.query(GET_RECORDS_QUERY, &[])).iter().map(|row| row.get(0)).collect())
  }

  fn add_record(&mut self, record: &str) -> Result<(), Error> {
    let rows_updated = try!(self.connection.execute(ADD_RECORD_QUERY, &[&record]));
    if rows_updated != 1 {
      Err(error!("The number of rows added to the record table was {}, only 1 should have been added.", rows_updated))
    } else {
      Ok(())
    }
  }

  fn sub_record(&mut self, record: &str) -> Result<(), Error> {
    let rows_updated = try!(self.connection.execute(SUB_RECORD_QUERY, &[&record]));
    if rows_updated != 1 {
      Err(error!("The number of rows removed was {}, only 1 should have been removed.", rows_updated))
    } else {
      Ok(())
    }
  }

  fn execute(&mut self, query: String) -> Result<(), Error> {
    try!(self.connection.batch_execute(&query));
    Ok(())
  }
}


text:
import React, { Component} from 'react';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        {this.props.children}
      </div>
    );
  }
}

export default App;


text:
using Stove.Domain.Entities;

namespace Stove.Couchbase.Filters.Action
{
    public interface ICouchbaseActionFilterExecuter
    {
        void ExecuteCreationAuditFilter<TEntity, TPrimaryKey>(TEntity entity) where TEntity : class, IEntity<TPrimaryKey>;

        void ExecuteModificationAuditFilter<TEntity, TPrimaryKey>(TEntity entity) where TEntity : class, IEntity<TPrimaryKey>;

        void ExecuteDeletionAuditFilter<TEntity, TPrimaryKey>(TEntity entity) where TEntity : class, IEntity<TPrimaryKey>;
    }
}


text:
using System.Data;
using HomeBudget.Constants;
using HomeBudget.Dao.Base.Interfaces;
using HomeBudget.Forms.EntityForms;
using HomeBudget.Views.Base;
using HomeManager.GUI.Enums;

namespace HomeBudget.Views.Impl
{
    public class MonthlyIncomeActionView : BaseActionView
    {
        private readonly IMonthlyIncomeRepository _monthlyIncomeRepository;

        public MonthlyIncomeActionView(IMonthlyIncomeRepository monthlyIncomeRepository)
        {
            _monthlyIncomeRepository = monthlyIncomeRepository;
        }

        public override void AddNewRecord()
        {
            OpenEntityFormRecord(new MonthlyIncomeEntityForm(_monthlyIncomeRepository));
        }
        public override string Caption
        {
            get { return "Venituri lunare"; }
        }

        public override DataTable GetOverviewData()
        {
            return GetDataTableFromView(DatabaseView.MONTHLY_INCOME);
        }

        public override ViewTypeEnum View
        {
            get { return ViewTypeEnum.MonthlyIncome; }
        }
        public override void OpenRecord(int id)
        {
            OpenEntityFormRecord(new MonthlyIncomeEntityForm(_monthlyIncomeRepository), id);
        }

        public override void DeleteRecord(int id)
        {
            _monthlyIncomeRepository.Delete(id);
        }
    }
}


text:
#ifndef _DEFINED_ASW_PICKUP_WEAPON_H
#define _DEFINED_ASW_PICKUP_WEAPON_H

#include "asw_pickup.h"

class CASW_Player;
class CASW_Weapon;
class CASW_Marine;

class CASW_Pickup_Weapon : public CASW_Pickup
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon, CASW_Pickup );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	static bool VismonCallback( CBaseEntity *pPickup, CBasePlayer *pViewingPlayer );

	virtual void Spawn( void );
	virtual void ActivateUseIcon( CASW_Marine* pMarine, int nHoldType );	// player has used this item
	virtual void InitFrom(CASW_Marine* pMarine,CASW_Weapon* pWeapon);  // sets the pickup up with the contents of the specified marine+weapon
	virtual const char* GetWeaponClass() { return "asw_weapon_rifle"; }
	virtual void InitWeapon(CASW_Marine* pMarine, CASW_Weapon* pWeapon);
	virtual bool AllowedToPickup(CASW_Marine *pMarine);

	virtual int GetNumClips() { return m_iClips; }
	virtual int GetNumBulletsInGun() { return m_iBulletsInGun; }
	virtual int GetSecondary() { return m_iSecondary; }

	CNetworkVar(int, m_iBulletsInGun);
	CNetworkVar(int, m_iClips);
	CNetworkVar(int, m_iSecondary);
};

class CASW_Pickup_Weapon_Rifle : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Rifle, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_rifle"; }
};

class CASW_Pickup_Weapon_PRifle : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_PRifle, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_prifle"; }
};

class CASW_Pickup_Weapon_Autogun : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Autogun, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_autogun"; }
};

class CASW_Pickup_Weapon_Shotgun : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Shotgun, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_shotgun"; }
};

class CASW_Pickup_Weapon_Assault_Shotgun : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Assault_Shotgun, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_vindicator"; }
};

class CASW_Pickup_Weapon_Flamer : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Flamer, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_flamer"; }
};

class CASW_Pickup_Weapon_Railgun : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Railgun, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_railgun"; }
};

class CASW_Pickup_Weapon_Ricochet : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Ricochet, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_ricochet"; }
};

class CASW_Pickup_Weapon_Flechette : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Flechette, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_flechette"; }
};

class CASW_Pickup_Weapon_FireExtinguisher : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_FireExtinguisher, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_fire_extinguisher"; }
};

class CASW_Pickup_Weapon_Pistol : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Pistol, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_pistol"; }
};

class CASW_Pickup_Weapon_Mining_Laser : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Mining_Laser, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_mining_laser"; }
};

class CASW_Pickup_Weapon_Chainsaw : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Chainsaw, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_chainsaw"; }
};

class CASW_Pickup_Weapon_PDW : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_PDW, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_pdw"; }
};

class CASW_Pickup_Weapon_Grenades : public CASW_Pickup_Weapon
{
public:
	DECLARE_CLASS( CASW_Pickup_Weapon_Grenades, CASW_Pickup_Weapon );
	DECLARE_SERVERCLASS();
	DECLARE_DATADESC();

	virtual void Precache( void );
	virtual void Spawn( void );
	virtual const char* GetWeaponClass() { return "asw_weapon_grenades"; }
};

#endif /* _DEFINED_ASW_PICKUP_WEAPON_H */


text:
require File.join(File.expand_path(File.dirname(__FILE__)), 'rack/server_status')

if defined? Rails
  case Rails::VERSION::MAJOR
    when 3
      class Rack::ServerStatus::Railtie < Rails::Railtie
        initializer('rack-server-status.prepend') { |app| app.config.middleware.insert(0, Rack::ServerStatus) }
      end
  end
end


text:
import { expect } from 'chai'
import { serverBuilder } from 'rxjs-grpc'

import isServerBuilder from '../src/is-server-builder'

import { sample } from './grpc-namespaces'

describe('isServerBuilder', () => {
  it('should return true for an instance of ServerBuilder', () => {
    const server = serverBuilder<sample.ServerBuilder>(
      `${__dirname}/sample.proto`,
      'sample'
    )
    expect(isServerBuilder(server)).to.equal(true)
  })

  it('should return false when not an instance of ServerBuilder', () => {
    expect(isServerBuilder({})).to.equal(false)
    expect(isServerBuilder(undefined)).to.equal(false)
    expect(isServerBuilder(null)).to.equal(false)
  })
})


text:
<!DOCTYPE html>

    <title>My Wisdom-based file server</title>
    <link rel="stylesheet" href="/libs/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="/libs/css/bootstrap-theme.min.css"/>

My Wisdom-based file server

                Flash message

        <form action="#" enctype="multipart/form-data" method="POST" th:attr="action=${#routes.route('upload')}">
            <fieldset>
                <input type="file" name="upload"/>
                <input type="submit" value="Upload"/>
            </fieldset>
        </form>

Files:

                    Name
                    Size
                    Download link

                    Sample Name
                    Description
                    link


text:
pubminer
========

Publication data miner.  Currently supports only conferences found in the DBLP bibliography.

### Usage

Use the documentation included in the python script by running

``` python miner.py -h ```

### Output

The publication data is output as JSON populated with whatever fields are found with each mined publication.  Usually a publication contains at least a title and author entry.  See included ```popl-sample.dat``` for sample output.

### Examples

Mine Principles of Programming Languages (POPL) conference publications:

``` python miner.py popl ```

Mine POPL publications without citation data, limiting to the last 10 conferences, and put the output in ```popl10.dat```:

``` python miner.py popl -nc -l 10 -f popl10.dat ```


text:
package org.mapfish.print.processor.http;

import com.google.common.base.Predicate;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mapfish.print.TestHttpClientFactory;
import org.mapfish.print.http.MfClientHttpRequestFactory;
import org.mapfish.print.processor.http.matcher.AcceptAllMatcher;
import org.mapfish.print.processor.http.matcher.AddressHostMatcher;
import org.mapfish.print.processor.http.matcher.LocalHostMatcher;
import org.mapfish.print.processor.http.matcher.URIMatcher;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.mock.http.client.MockClientHttpRequest;

import javax.annotation.Nullable;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class RestrictUrisProcessorTest {
    static final TestHttpClientFactory requestFactory = new TestHttpClientFactory();

    @BeforeClass
    public static void setUp() throws Exception {
        requestFactory.registerHandler(new Predicate<URI>() {
            @Override
            public boolean apply(@Nullable URI input) {
                return true;
            }
        }, new TestHttpClientFactory.Handler() {
            @Override
            public MockClientHttpRequest handleRequest(URI uri, HttpMethod httpMethod) {
                assertEquals("localhost", uri.getHost());
                return null;
            }
        });
    }

    @Test
    public void testCreateFactoryWrapperLegalRequest() throws Exception {
        final RestrictUrisProcessor restrictUrisProcessor = createLocalhostOnly();
        ClientHttpFactoryProcessorParam params = new ClientHttpFactoryProcessorParam();
        final MfClientHttpRequestFactory factoryWrapper = restrictUrisProcessor.createFactoryWrapper(params, requestFactory);
        factoryWrapper.createRequest(new URI("http://localhost:8080/geoserver/wms"), HttpMethod.GET);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testCreateFactoryWrapperIllegalRequest() throws Exception {
        final RestrictUrisProcessor restrictUrisProcessor = createLocalhostOnly();
        ClientHttpFactoryProcessorParam params = new ClientHttpFactoryProcessorParam();
        final ClientHttpRequestFactory factoryWrapper = restrictUrisProcessor.createFactoryWrapper(params, requestFactory);
        factoryWrapper.createRequest(new URI("http://www.google.com/q"), HttpMethod.GET);
    }

    @Test
    public void testRejectWithLegalRequest() throws Exception {
        final RestrictUrisProcessor restrictUrisProcessor = createDenyInternal();
        ClientHttpFactoryProcessorParam params = new ClientHttpFactoryProcessorParam();
        final ClientHttpRequestFactory factoryWrapper = restrictUrisProcessor.createFactoryWrapper(params, requestFactory);
        factoryWrapper.createRequest(new URI("http://localhost/q"), HttpMethod.GET);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testRejectWithIllegalRequest() throws Exception {
        final RestrictUrisProcessor restrictUrisProcessor = createDenyInternal();
        ClientHttpFactoryProcessorParam params = new ClientHttpFactoryProcessorParam();
        final ClientHttpRequestFactory factoryWrapper = restrictUrisProcessor.createFactoryWrapper(params, requestFactory);
        factoryWrapper.createRequest(new URI("http://192.168.12.23/q"), HttpMethod.GET);
    }

    private RestrictUrisProcessor createLocalhostOnly() {
        final RestrictUrisProcessor processor = new RestrictUrisProcessor();
        processor.setMatchers(Collections.singletonList(new LocalHostMatcher()));
        return processor;
    }

    private RestrictUrisProcessor createDenyInternal() {
        final RestrictUrisProcessor processor = new RestrictUrisProcessor();
        List<URIMatcher> matchers = new ArrayList<URIMatcher>();
        AddressHostMatcher addressHostMatcher = new AddressHostMatcher();
        addressHostMatcher.setIp("192.168.12.0");
        addressHostMatcher.setMask("255.255.255.0");
        addressHostMatcher.setReject(true);
        matchers.add(addressHostMatcher);
        matchers.add(new AcceptAllMatcher());
        processor.setMatchers(matchers);
        return processor;
    }
}