text:
"""Tests for Bijector."""

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

import abc
import math

import numpy as np
import six
import tensorflow as tf

distributions = tf.contrib.distributions
bijectors = tf.contrib.distributions.bijector
rng = np.random.RandomState(42)

def assert_finite(array):
  if not np.isfinite(array).all():
    raise AssertionError("array was not all finite. %s" % array[:15])

def assert_strictly_increasing(array):
  np.testing.assert_array_less(0.0, np.diff(array))

def assert_strictly_decreasing(array):
  np.testing.assert_array_less(np.diff(array), 0.0)

def assert_strictly_monotonic(array):
  if array[0] < array[-1]:
    assert_strictly_increasing(array)
  else:
    assert_strictly_decreasing(array)

def assert_scalar_congruency(
    bijector, lower_x, upper_x, n=10000, rtol=0.01, sess=None):
  """Assert `bijector`'s forward/inverse/inverse_log_det_jacobian are congruent.

  We draw samples `X ~ U(lower_x, upper_x)`, then feed these through the
  `bijector` in order to check that:

  1. the forward is strictly monotonic.
  2. the forward/inverse methods are inverses of each other.
  3. the jacobian is the correct change of measure.

  This can only be used for a Bijector mapping open subsets of the real line
  to themselves.  This is due to the fact that this test compares the pdf
  before/after transformation with the Lebesgue measure on the line.

  Args:
    bijector:  Instance of Bijector
    lower_x:  Python scalar.
    upper_x:  Python scalar.  Must have `lower_x < upper_x`, and both must be in
      the domain of the `bijector`.  The `bijector` should probably not produce
      huge variation in values in the interval `(lower_x, upper_x)`, or else
      the variance based check of the Jacobian will require small `rtol` or
      huge `n`.
    n:  Number of samples to draw for the checks.
    rtol:  Positive number.  Used for the Jacobian check.
    sess:  `tf.Session`.  Defaults to the default session.

  Raises:
    AssertionError:  If tests fail.
  """

  # Checks and defaults.
  assert bijector.shaper is None or bijector.shaper.event_ndims.eval() == 0
  if sess is None:
    sess = tf.get_default_session()

  # Should be monotonic over this interval
  ten_x_pts = np.linspace(lower_x, upper_x, num=10).astype(np.float32)
  if bijector.dtype is not None:
    ten_x_pts = ten_x_pts.astype(bijector.dtype.as_numpy_dtype)
  forward_on_10_pts = bijector.forward(ten_x_pts)

  # Set the lower/upper limits in the range of the bijector.
  lower_y, upper_y = sess.run(
      [bijector.forward(lower_x), bijector.forward(upper_x)])
  if upper_y < lower_y:  # If bijector.forward is a decreasing function.
    lower_y, upper_y = upper_y, lower_y

  # Uniform samples from the domain, range.
  uniform_x_samps = distributions.Uniform(a=lower_x, b=upper_x).sample(n)
  uniform_y_samps = distributions.Uniform(a=lower_y, b=upper_y).sample(n)

  # These compositions should be the identity.
  inverse_forward_x = bijector.inverse(bijector.forward(uniform_x_samps))
  forward_inverse_y = bijector.forward(bijector.inverse(uniform_y_samps))

  # For a < b, and transformation y = y(x),
  # (b - a) = \int_a^b dx = \int_{y(a)}^{y(b)} |dx/dy| dy
  # "change_measure_dy_dx" below is a Monte Carlo approximation to the right
  # hand side, which should then be close to the left, which is (b - a).
  dy_dx = tf.exp(bijector.inverse_log_det_jacobian(uniform_y_samps))
  # E[|dx/dy|] under Uniform[lower_y, upper_y]
  # = \int_{y(a)}^{y(b)} |dx/dy| dP(u), where dP(u) is the uniform measure
  expectation_of_dy_dx_under_uniform = tf.reduce_mean(dy_dx)
  # dy = dP(u) * (upper_y - lower_y)
  change_measure_dy_dx = ((upper_y - lower_y) *
                          expectation_of_dy_dx_under_uniform)

  # We'll also check that dy_dx = 1 / dx_dy.
  dx_dy = tf.exp(bijector.forward_log_det_jacobian(
      bijector.inverse(uniform_y_samps)))

  (
      forward_on_10_pts_v,
      dy_dx_v,
      dx_dy_v,
      change_measure_dy_dx_v,
      uniform_x_samps_v,
      uniform_y_samps_v,
      inverse_forward_x_v,
      forward_inverse_y_v,
  ) = sess.run(
      [
          forward_on_10_pts,
          dy_dx,
          dx_dy,
          change_measure_dy_dx,
          uniform_x_samps,
          uniform_y_samps,
          inverse_forward_x,
          forward_inverse_y,
      ])

  assert_strictly_monotonic(forward_on_10_pts_v)
  # Composition of forward/inverse should be the identity.
  np.testing.assert_allclose(
      inverse_forward_x_v, uniform_x_samps_v, atol=1e-5, rtol=1e-3)
  np.testing.assert_allclose(
      forward_inverse_y_v, uniform_y_samps_v, atol=1e-5, rtol=1e-3)
  # Change of measure should be correct.
  np.testing.assert_allclose(upper_x - lower_x,
                             change_measure_dy_dx_v,
                             atol=0, rtol=rtol)
  # Inverse Jacobian should be equivalent to the reciprocal of the forward
  # Jacobian.
  np.testing.assert_allclose(dy_dx_v, np.divide(1., dx_dy_v),
                             atol=1e-5, rtol=1e-3)

def assert_bijective_and_finite(bijector, x, y, atol=0, rtol=1e-5, sess=None):
  """Assert that forward/inverse (along with jacobians) are inverses and finite.

  It is recommended to use x and y values that are very very close to the edge
  of the Bijector's domain.

  Args:
    bijector:  A Bijector instance.
    x:  np.array of values in the domain of bijector.forward.
    y:  np.array of values in the domain of bijector.inverse.
    atol:  Absolute tolerance.
    rtol:  Relative tolerance.
    sess:  TensorFlow session.  Defaults to the default session.

  Raises:
    AssertionError:  If tests fail.
  """
  sess = sess or tf.get_default_session()

  # These are the incoming points, but people often create a crazy range of
  # values for which these end up being bad, especially in 16bit.
  assert_finite(x)
  assert_finite(y)
  np.testing.assert_array_less(0, y)

  f_x = bijector.forward(x)
  g_y = bijector.inverse(y)

  (
      x_from_x, y_from_y, ildj_f_x, fldj_x, ildj_y, fldj_g_y, f_x_v, g_y_v,
  ) = sess.run(
      [bijector.inverse(f_x),
       bijector.forward(g_y),
       bijector.inverse_log_det_jacobian(f_x),
       bijector.forward_log_det_jacobian(x),
       bijector.inverse_log_det_jacobian(y),
       bijector.forward_log_det_jacobian(g_y),
       f_x,
       g_y,
      ])

  assert_finite(x_from_x)
  assert_finite(y_from_y)
  assert_finite(ildj_f_x)
  assert_finite(fldj_x)
  assert_finite(ildj_y)
  assert_finite(fldj_g_y)
  assert_finite(f_x_v)
  assert_finite(g_y_v)

  np.testing.assert_allclose(x_from_x, x, atol=atol, rtol=rtol)
  np.testing.assert_allclose(y_from_y, y, atol=atol, rtol=rtol)
  np.testing.assert_allclose(-ildj_f_x, fldj_x, atol=atol, rtol=rtol)
  np.testing.assert_allclose(-ildj_y, fldj_g_y, atol=atol, rtol=rtol)

class BaseBijectorTest(tf.test.TestCase):
  """Tests properties of the Bijector base-class."""

  def testBijector(self):
    with self.test_session():
      with self.assertRaisesRegexp(
          TypeError,
          ("Can't instantiate abstract class Bijector "
           "with abstract methods __init__")):
        bijectors.Bijector()

class IntentionallyMissingError(Exception):
  pass

class BrokenBijectorWithInverseAndInverseLogDetJacobian(bijectors.Bijector):
  """Bijector with broken directions.

  This BrokenBijector implements _inverse_and_inverse_log_det_jacobian.
  """

  def __init__(self, forward_missing=False, inverse_missing=False):
    super(BrokenBijectorWithInverseAndInverseLogDetJacobian, self).__init__(
        batch_ndims=0,
        event_ndims=0,
        validate_args=False,
        name="BrokenBijectorDual")
    self._forward_missing = forward_missing
    self._inverse_missing = inverse_missing

  def _forward(self, x):
    if self._forward_missing:
      raise IntentionallyMissingError
    return 2. * x

  def _inverse_and_inverse_log_det_jacobian(self, y):
    if self._inverse_missing:
      raise IntentionallyMissingError
    return y / 2., -tf.log(2.)

  def _forward_log_det_jacobian(self, x):  # pylint:disable=unused-argument
    if self._forward_missing:
      raise IntentionallyMissingError
    return tf.log(2.)

class BrokenBijectorSeparateInverseAndInverseLogDetJacobian(bijectors.Bijector):
  """Forward and inverse are not inverses of each other.

  This BrokenBijector implements _inverse and _inverse_log_det_jacobian as
  separate functions.
  """

  def __init__(self, forward_missing=False, inverse_missing=False):
    super(BrokenBijectorSeparateInverseAndInverseLogDetJacobian, self).__init__(
        batch_ndims=0,
        event_ndims=0,
        validate_args=False,
        name="broken")
    self._forward_missing = forward_missing
    self._inverse_missing = inverse_missing

  def _forward(self, x):
    if self._forward_missing:
      raise IntentionallyMissingError
    return 2 * x

  def _inverse(self, y):
    if self._inverse_missing:
      raise IntentionallyMissingError
    return y / 2.

  def _inverse_log_det_jacobian(self, y):  # pylint:disable=unused-argument
    if self._inverse_missing:
      raise IntentionallyMissingError
    return -tf.log(2.)

  def _forward_log_det_jacobian(self, x):  # pylint:disable=unused-argument
    if self._forward_missing:
      raise IntentionallyMissingError
    return tf.log(2.)

@six.add_metaclass(abc.ABCMeta)
class BijectorCachingTest(object):

  @abc.abstractproperty
  def broken_bijector_cls(self):
    # return a BrokenBijector type Bijector, since this will test the caching.
    raise IntentionallyMissingError("Not implemented")

  def testCachingOfForwardResultsWhenCalledOneByOne(self):
    broken_bijector = self.broken_bijector_cls(inverse_missing=True)
    with self.test_session():
      x = tf.constant(1.1)

      # Call forward and forward_log_det_jacobian one-by-one (not together).
      y = broken_bijector.forward(x)
      _ = broken_bijector.forward_log_det_jacobian(x)

      # Now, everything should be cached if the argument is y.
      try:
        broken_bijector.inverse(y)
        broken_bijector.inverse_log_det_jacobian(y)
        broken_bijector.inverse_and_inverse_log_det_jacobian(y)
      except IntentionallyMissingError:
        raise AssertionError("Tests failed!  Cached values not used.")

  def testCachingOfInverseResultsWhenCalledOneByOne(self):
    broken_bijector = self.broken_bijector_cls(forward_missing=True)
    with self.test_session():
      y = tf.constant(1.1)

      # Call inverse and inverse_log_det_jacobian one-by-one (not together).
      x = broken_bijector.inverse(y)
      _ = broken_bijector.inverse_log_det_jacobian(y)

      # Now, everything should be cached if the argument is x.
      try:
        broken_bijector.forward(x)
        broken_bijector.forward_log_det_jacobian(x)
      except IntentionallyMissingError:
        raise AssertionError("Tests failed!  Cached values not used.")

  def testCachingOfInverseResultsWhenCalledTogether(self):
    broken_bijector = self.broken_bijector_cls(forward_missing=True)
    with self.test_session():
      y = tf.constant(1.1)

      # Call inverse and inverse_log_det_jacobian one-by-one (not together).
      x, _ = broken_bijector.inverse_and_inverse_log_det_jacobian(y)

      # Now, everything should be cached if the argument is x.
      try:
        broken_bijector.forward(x)
        broken_bijector.forward_log_det_jacobian(x)
      except IntentionallyMissingError:
        raise AssertionError("Tests failed!  Cached values not used.")

class SeparateCallsBijectorCachingTest(BijectorCachingTest, tf.test.TestCase):
  """Test caching with BrokenBijectorSeparateInverseAndInverseLogDetJacobian.

  These bijectors implement forward, inverse,... all as separate functions.
  """

  @property
  def broken_bijector_cls(self):
    return BrokenBijectorSeparateInverseAndInverseLogDetJacobian

class JointCallsBijectorCachingTest(BijectorCachingTest, tf.test.TestCase):
  """Test caching with BrokenBijectorWithInverseAndInverseLogDetJacobian.

  These bijectors implement _inverse_and_inverse_log_det_jacobian, which is two
  functionalities together.
  """

  @property
  def broken_bijector_cls(self):
    return BrokenBijectorWithInverseAndInverseLogDetJacobian

class IdentityBijectorTest(tf.test.TestCase):
  """Tests correctness of the Y = g(X) = X transformation."""

  def testBijector(self):
    with self.test_session():
      bijector = bijectors.Identity()
      self.assertEqual("identity", bijector.name)
      x = [[[0.],
            [1.]]]
      self.assertAllEqual(x, bijector.forward(x).eval())
      self.assertAllEqual(x, bijector.inverse(x).eval())
      self.assertAllEqual(0., bijector.inverse_log_det_jacobian(x).eval())
      self.assertAllEqual(0., bijector.forward_log_det_jacobian(x).eval())
      rev, jac = bijector.inverse_and_inverse_log_det_jacobian(x)
      self.assertAllEqual(x, rev.eval())
      self.assertAllEqual(0., jac.eval())

  def testScalarCongruency(self):
    with self.test_session():
      bijector = bijectors.Identity()
      assert_scalar_congruency(bijector, lower_x=-2., upper_x=2.)

class ExpBijectorTest(tf.test.TestCase):
  """Tests correctness of the Y = g(X) = exp(X) transformation."""

  def testBijector(self):
    with self.test_session():
      bijector = bijectors.Exp(event_ndims=1)
      self.assertEqual("exp", bijector.name)
      x = [[[1.],
            [2.]]]
      y = np.exp(x)
      self.assertAllClose(y, bijector.forward(x).eval())
      self.assertAllClose(x, bijector.inverse(y).eval())
      self.assertAllClose(-np.sum(np.log(y), axis=-1),
                          bijector.inverse_log_det_jacobian(y).eval())
      self.assertAllClose(-bijector.inverse_log_det_jacobian(np.exp(x)).eval(),
                          bijector.forward_log_det_jacobian(x).eval())
      rev, jac = bijector.inverse_and_inverse_log_det_jacobian(y)
      self.assertAllClose(x, rev.eval())
      self.assertAllClose(-np.sum(np.log(y), axis=-1), jac.eval())

  def testScalarCongruency(self):
    with self.test_session():
      bijector = bijectors.Exp()
      assert_scalar_congruency(bijector, lower_x=-2., upper_x=1.5, rtol=0.05)

  def testBijectiveAndFinite(self):
    with self.test_session():
      bijector = bijectors.Exp(event_ndims=0)
      x = np.linspace(-10, 10, num=10).astype(np.float32)
      y = np.logspace(-10, 10, num=10).astype(np.float32)
      assert_bijective_and_finite(bijector, x, y)

class PowerTransformBijectorTest(tf.test.TestCase):
  """Tests correctness of the power transformation."""

  def testBijector(self):
    with self.test_session():
      c = 0.2
      bijector = bijectors.PowerTransform(power=c, event_ndims=1,
                                          validate_args=True)
      self.assertEqual("power_transform", bijector.name)
      x = np.array([[[-1.],
                     [2.],
                     [-5.+1e-4]]])
      y = (1. + x * c)**(1. / c)
      self.assertAllClose(y, bijector.forward(x).eval())
      self.assertAllClose(x, bijector.inverse(y).eval())
      self.assertAllClose((c - 1.) * np.sum(np.log(y), axis=-1),
                          bijector.inverse_log_det_jacobian(y).eval())
      self.assertAllClose(-bijector.inverse_log_det_jacobian(y).eval(),
                          bijector.forward_log_det_jacobian(x).eval(),
                          rtol=1e-4, atol=0.)
      rev, jac = bijector.inverse_and_inverse_log_det_jacobian(y)
      self.assertAllClose(x, rev.eval())
      self.assertAllClose((c - 1.) * np.sum(np.log(y), axis=-1), jac.eval())

  def testScalarCongruency(self):
    with self.test_session():
      bijector = bijectors.PowerTransform(power=0.2, validate_args=True)
      assert_scalar_congruency(bijector, lower_x=-2., upper_x=1.5, rtol=0.05)

  def testBijectiveAndFinite(self):
    with self.test_session():
      bijector = bijectors.PowerTransform(power=0.2, event_ndims=0,
                                          validate_args=True)
      x = np.linspace(-4.999, 10, num=10).astype(np.float32)
      y = np.logspace(0.001, 10, num=10).astype(np.float32)
      assert_bijective_and_finite(bijector, x, y, rtol=1e-3)

class InlineBijectorTest(tf.test.TestCase):
  """Tests correctness of the inline constructed bijector."""

  def testBijector(self):
    with self.test_session():
      exp = bijectors.Exp(event_ndims=1)
      inline = bijectors.Inline(
          forward_fn=tf.exp,
          inverse_fn=tf.log,
          inverse_log_det_jacobian_fn=(
              lambda y: -tf.reduce_sum(tf.log(y), reduction_indices=-1)),
          forward_log_det_jacobian_fn=(
              lambda x: tf.reduce_sum(x, reduction_indices=-1)),
          name="exp")

      self.assertEqual(exp.name, inline.name)
      x = [[[1., 2.],
            [3., 4.],
            [5., 6.]]]
      y = np.exp(x)
      self.assertAllClose(y, inline.forward(x).eval())
      self.assertAllClose(x, inline.inverse(y).eval())
      self.assertAllClose(-np.sum(np.log(y), axis=-1),
                          inline.inverse_log_det_jacobian(y).eval())
      self.assertAllClose(-inline.inverse_log_det_jacobian(y).eval(),
                          inline.forward_log_det_jacobian(x).eval())
      rev, jac = inline.inverse_and_inverse_log_det_jacobian(y)
      self.assertAllClose(x, rev.eval())
      self.assertAllClose(-np.sum(np.log(y), axis=-1), jac.eval())

  def testShapeGetters(self):
    with self.test_session():
      bijector = bijectors.Inline(
          forward_event_shape_fn=lambda x: tf.concat(0, (x, [1])),
          get_forward_event_shape_fn=lambda x: x.as_list() + [1],
          inverse_event_shape_fn=lambda x: x[:-1],
          get_inverse_event_shape_fn=lambda x: x[:-1],
          name="shape_only")
      x = tf.TensorShape([1, 2, 3])
      y = tf.TensorShape([1, 2, 3, 1])
      self.assertAllEqual(y, bijector.get_forward_event_shape(x))
      self.assertAllEqual(y.as_list(),
                          bijector.forward_event_shape(x.as_list()).eval())
      self.assertAllEqual(x, bijector.get_inverse_event_shape(y))
      self.assertAllEqual(x.as_list(),
                          bijector.inverse_event_shape(y.as_list()).eval())

class ScaleAndShiftBijectorTest(tf.test.TestCase):
  """Tests correctness of the Y = scale * x + shift transformation."""

  def testProperties(self):
    with self.test_session():
      mu = -1.
      sigma = 2.
      bijector = bijectors.ScaleAndShift(
          shift=mu, scale=sigma)
      self.assertEqual("scale_and_shift", bijector.name)

  def testNoBatchScalar(self):
    with self.test_session() as sess:
      def static_run(fun, x):
        return fun(x).eval()

      def dynamic_run(fun, x_value):
        x_value = np.array(x_value)
        x = tf.placeholder(tf.float32, name="x")
        return sess.run(fun(x), feed_dict={x: x_value})

      for run in (static_run, dynamic_run):
        mu = -1.
        sigma = 2.  # Scalar.
        bijector = bijectors.ScaleAndShift(
            shift=mu, scale=sigma)
        self.assertEqual(0, bijector.shaper.batch_ndims.eval())  # "no batches"
        self.assertEqual(0, bijector.shaper.event_ndims.eval())  # "is scalar"
        x = [1., 2, 3]  # Three scalar samples (no batches).
        self.assertAllClose([1., 3, 5], run(bijector.forward, x))
        self.assertAllClose([1., 1.5, 2.], run(bijector.inverse, x))
        self.assertAllClose([-math.log(2.)],
                            run(bijector.inverse_log_det_jacobian, x))

  def testWeirdSampleNoBatchScalar(self):
    with self.test_session() as sess:
      def static_run(fun, x):
        return fun(x).eval()

      def dynamic_run(fun, x_value):
        x_value = np.array(x_value)
        x = tf.placeholder(tf.float32, name="x")
        return sess.run(fun(x), feed_dict={x: x_value})

      for run in (static_run, dynamic_run):
        mu = -1.
        sigma = 2.  # Scalar.
        bijector = bijectors.ScaleAndShift(
            shift=mu, scale=sigma)
        self.assertEqual(0, bijector.shaper.batch_ndims.eval())  # "no batches"
        self.assertEqual(0, bijector.shaper.event_ndims.eval())  # "is scalar"
        x = [[1., 2, 3],
             [4, 5, 6]]  # Weird sample shape.
        self.assertAllClose([[1., 3, 5],
                             [7, 9, 11]],
                            run(bijector.forward, x))
        self.assertAllClose([[1., 1.5, 2.],
                             [2.5, 3, 3.5]],
                            run(bijector.inverse, x))
        self.assertAllClose([-math.log(2.)],
                            run(bijector.inverse_log_det_jacobian, x))

  def testOneBatchScalar(self):
    with self.test_session() as sess:
      def static_run(fun, x):
        return fun(x).eval()

      def dynamic_run(fun, x_value):
        x_value = np.array(x_value)
        x = tf.placeholder(tf.float32, name="x")
        return sess.run(fun(x), feed_dict={x: x_value})

      for run in (static_run, dynamic_run):
        mu = [1.]
        sigma = [1.]  # One batch, scalar.
        bijector = bijectors.ScaleAndShift(
            shift=mu, scale=sigma)
        self.assertEqual(
            1, bijector.shaper.batch_ndims.eval())  # "one batch dim"
        self.assertEqual(
            0, bijector.shaper.event_ndims.eval())  # "is scalar"
        x = [1.]  # One sample from one batches.
        self.assertAllClose([2.], run(bijector.forward, x))
        self.assertAllClose([0.], run(bijector.inverse, x))
        self.assertAllClose([0.],
                            run(bijector.inverse_log_det_jacobian, x))

  def testTwoBatchScalar(self):
    with self.test_session() as sess:
      def static_run(fun, x):
        return fun(x).eval()

      def dynamic_run(fun, x_value):
        x_value = np.array(x_value)
        x = tf.placeholder(tf.float32, name="x")
        return sess.run(fun(x), feed_dict={x: x_value})

      for run in (static_run, dynamic_run):
        mu = [1., -1]
        sigma = [1., 1]  # Univariate, two batches.
        bijector = bijectors.ScaleAndShift(
            shift=mu, scale=sigma)
        self.assertEqual(
            1, bijector.shaper.batch_ndims.eval())  # "one batch dim"
        self.assertEqual(
            0, bijector.shaper.event_ndims.eval())  # "is scalar"
        x = [1., 1]  # One sample from each of two batches.
        self.assertAllClose([2., 0], run(bijector.forward, x))
        self.assertAllClose([0., 2], run(bijector.inverse, x))
        self.assertAllClose([0., 0],
                            run(bijector.inverse_log_det_jacobian, x))

  def testNoBatchMultivariate(self):
    with self.test_session() as sess:
      def static_run(fun, x):
        return fun(x).eval()

      def dynamic_run(fun, x_value):
        x_value = np.array(x_value)
        x = tf.placeholder(tf.float32, name="x")
        return sess.run(fun(x), feed_dict={x: x_value})

      for run in (static_run, dynamic_run):
        mu = [1., -1]
        # Note:  sigma is -1 * identity matrix.
        sigma = -np.eye(2, dtype=np.float32)
        bijector = bijectors.ScaleAndShift(
            shift=mu, scale=sigma, event_ndims=1)
        self.assertEqual(0, bijector.shaper.batch_ndims.eval())  # "no batches"
        self.assertEqual(1, bijector.shaper.event_ndims.eval())  # "is vector"
        x = [1., 1]
        # matmul(sigma, x) + shift
        # = [-1, -1] + [1, -1]
        self.assertAllClose([0., -2], run(bijector.forward, x))
        self.assertAllClose([0., -2], run(bijector.inverse, x))
        self.assertAllClose([0.], run(bijector.inverse_log_det_jacobian, x))

        # x is a 2-batch of 2-vectors.
        # The first vector is [1, 1], the second is [-1, -1].
        # Each undergoes matmul(sigma, x) + shift.
        x = [[1., 1],
             [-1., -1]]
        self.assertAllClose([[0., -2],
                             [2., 0]],
                            run(bijector.forward, x))
        self.assertAllClose([[0., -2],
                             [2., 0]],
                            run(bijector.inverse, x))
        self.assertAllClose([0.], run(bijector.inverse_log_det_jacobian, x))

      # When mu is a scalar and x is multivariate then the location is
      # broadcast.
      for run in (static_run, dynamic_run):
        mu = 1.
        sigma = np.eye(2, dtype=np.float32)
        bijector = bijectors.ScaleAndShift(
            shift=mu, scale=sigma, event_ndims=1)
        self.assertEqual(0, bijector.shaper.batch_ndims.eval())  # "no batches"
        self.assertEqual(1, bijector.shaper.event_ndims.eval())  # "is vector"
        x = [1., 1]
        self.assertAllClose([2., 2], run(bijector.forward, x))
        self.assertAllClose([0., 0], run(bijector.inverse, x))
        self.assertAllClose([0.], run(bijector.inverse_log_det_jacobian, x))
        x = [[1., 1]]
        self.assertAllClose([[2., 2]], run(bijector.forward, x))
        self.assertAllClose([[0., 0]], run(bijector.inverse, x))
        self.assertAllClose([0.], run(bijector.inverse_log_det_jacobian, x))

  def testNoBatchMultivariateFullDynamic(self):
    with self.test_session() as sess:
      x = tf.placeholder(tf.float32, name="x")
      mu = tf.placeholder(tf.float32, name="mu")
      sigma = tf.placeholder(tf.float32, name="sigma")
      event_ndims = tf.placeholder(tf.int32, name="event_ndims")

      x_value = np.array([[1., 1]], dtype=np.float32)
      mu_value = np.array([1., -1], dtype=np.float32)
      sigma_value = np.eye(2, dtype=np.float32)
      event_ndims_value = np.array(1, dtype=np.int32)
      feed_dict = {x: x_value, mu: mu_value, sigma: sigma_value, event_ndims:
                   event_ndims_value}

      bijector = bijectors.ScaleAndShift(
          shift=mu, scale=sigma, event_ndims=event_ndims)
      self.assertEqual(0, sess.run(bijector.shaper.batch_ndims, feed_dict))
      self.assertEqual(1, sess.run(bijector.shaper.event_ndims, feed_dict))
      self.assertAllClose([[2., 0]], sess.run(bijector.forward(x), feed_dict))
      self.assertAllClose([[0., 2]], sess.run(bijector.inverse(x), feed_dict))
      self.assertAllClose(
          [0.], sess.run(bijector.inverse_log_det_jacobian(x), feed_dict))

  def testBatchMultivariate(self):
    with self.test_session() as sess:
      def static_run(fun, x):
        return fun(x).eval()

      def dynamic_run(fun, x_value):
        x_value = np.array(x_value, dtype=np.float32)
        x = tf.placeholder(tf.float32, name="x")
        return sess.run(fun(x), feed_dict={x: x_value})

      for run in (static_run, dynamic_run):
        mu = [[1., -1]]
        sigma = np.array([np.eye(2, dtype=np.float32)])
        bijector = bijectors.ScaleAndShift(
            shift=mu, scale=sigma, event_ndims=1)
        self.assertEqual(
            1, bijector.shaper.batch_ndims.eval())  # "one batch dim"
        self.assertEqual(
            1, bijector.shaper.event_ndims.eval())  # "is vector"
        x = [[[1., 1]]]
        self.assertAllClose([[[2., 0]]], run(bijector.forward, x))
        self.assertAllClose([[[0., 2]]], run(bijector.inverse, x))
        self.assertAllClose([0.], run(bijector.inverse_log_det_jacobian, x))

  def testBatchMultivariateFullDynamic(self):
    with self.test_session() as sess:
      x = tf.placeholder(tf.float32, name="x")
      mu = tf.placeholder(tf.float32, name="mu")
      sigma = tf.placeholder(tf.float32, name="sigma")
      event_ndims = tf.placeholder(tf.int32, name="event_ndims")

      x_value = np.array([[[1., 1]]], dtype=np.float32)
      mu_value = np.array([[1., -1]], dtype=np.float32)
      sigma_value = np.array([np.eye(2, dtype=np.float32)])
      event_ndims_value = np.array(1, dtype=np.int32)
      feed_dict = {x: x_value, mu: mu_value, sigma: sigma_value,
                   event_ndims: event_ndims_value}

      bijector = bijectors.ScaleAndShift(
          shift=mu, scale=sigma, event_ndims=event_ndims)
      self.assertEqual(1, sess.run(bijector.shaper.batch_ndims, feed_dict))
      self.assertEqual(1, sess.run(bijector.shaper.event_ndims, feed_dict))
      self.assertAllClose([[[2., 0]]], sess.run(bijector.forward(x), feed_dict))
      self.assertAllClose([[[0., 2]]], sess.run(bijector.inverse(x), feed_dict))
      self.assertAllClose(
          [0.], sess.run(bijector.inverse_log_det_jacobian(x), feed_dict))

  def testNoBatchMultivariateRaisesWhenSingular(self):
    with self.test_session():
      mu = [1., -1]
      sigma = [[0., 1.], [1., 1.]]  # Has zero on the diag!
      bijector = bijectors.ScaleAndShift(
          shift=mu, scale=sigma, event_ndims=1, validate_args=True)
      with self.assertRaisesOpError("Singular"):
        bijector.forward([1., 1.]).eval()

  def testEventNdimsLargerThanOneRaises(self):
    with self.test_session():
      mu = [1., -1]
      sigma = [[1., 1.], [1., 1.]]
      bijector = bijectors.ScaleAndShift(
          shift=mu, scale=sigma, event_ndims=2, validate_args=True)
      with self.assertRaisesOpError("event_ndims"):
        bijector.forward([1., 1.]).eval()

  def testNonSquareMatrixScaleRaises(self):
    # event_ndims = 1, so we expected a matrix, but will only feed a vector.
    with self.test_session():
      mu = [1., -1]
      sigma = [[1., 1., 1.], [1., 1., 1.]]
      bijector = bijectors.ScaleAndShift(
          shift=mu, scale=sigma, event_ndims=1, validate_args=True)
      with self.assertRaisesOpError("square"):
        bijector.forward([1., 1.]).eval()

  def testScaleZeroScalarRaises(self):
    with self.test_session():
      mu = -1.
      sigma = 0.  # Scalar, leads to non-invertible bijector
      bijector = bijectors.ScaleAndShift(
          shift=mu, scale=sigma, validate_args=True)
      with self.assertRaisesOpError("Singular"):
        bijector.forward(1.).eval()

  def testScalarCongruency(self):
    with self.test_session():
      bijector = bijectors.ScaleAndShift(shift=3.6, scale=0.42, event_ndims=0)
      assert_scalar_congruency(bijector, lower_x=-2., upper_x=2.)

  def testScalarCongruencyWithNegativeScale(self):
    with self.test_session():
      bijector = bijectors.ScaleAndShift(shift=3.6, scale=-0.42, event_ndims=0)
      assert_scalar_congruency(bijector, lower_x=-2., upper_x=2.)

class SoftplusBijectorTest(tf.test.TestCase):
  """Tests the correctness of the Y = g(X) = Log[1 + exp(X)] transformation."""

  def _softplus(self, x):
    return np.log(1 + np.exp(x))

  def _softplus_inverse(self, y):
    return np.log(np.exp(y) - 1)

  def _softplus_ildj_before_reduction(self, y):
    """Inverse log det jacobian, before being reduced."""
    return -np.log(1 - np.exp(-y))

  def testBijectorForwardInverseEventDimsZero(self):
    with self.test_session():
      bijector = bijectors.Softplus(event_ndims=0)
      self.assertEqual("softplus", bijector.name)
      x = 2 * rng.randn(2, 10)
      y = self._softplus(x)

      self.assertAllClose(y, bijector.forward(x).eval())
      self.assertAllClose(x, bijector.inverse(y).eval())
      self.assertAllClose(
          x, bijector.inverse_and_inverse_log_det_jacobian(y)[0].eval())

  def testBijectorLogDetJacobianEventDimsZero(self):
    with self.test_session():
      bijector = bijectors.Softplus(event_ndims=0)
      y = 2 * rng.rand(2, 10)
      # No reduction needed if event_dims = 0.
      ildj = self._softplus_ildj_before_reduction(y)

      self.assertAllClose(ildj, bijector.inverse_log_det_jacobian(y).eval())
      self.assertAllClose(
          ildj, bijector.inverse_and_inverse_log_det_jacobian(y)[1].eval())

  def testBijectorForwardInverseEventDimsOne(self):
    with self.test_session():
      bijector = bijectors.Softplus(event_ndims=1)
      self.assertEqual("softplus", bijector.name)
      x = 2 * rng.randn(2, 10)
      y = self._softplus(x)

      self.assertAllClose(y, bijector.forward(x).eval())
      self.assertAllClose(x, bijector.inverse(y).eval())
      self.assertAllClose(
          x, bijector.inverse_and_inverse_log_det_jacobian(y)[0].eval())

  def testBijectorLogDetJacobianEventDimsOne(self):
    with self.test_session():
      bijector = bijectors.Softplus(event_ndims=1)
      y = 2 * rng.rand(2, 10)
      ildj_before = self._softplus_ildj_before_reduction(y)
      ildj = np.sum(ildj_before, axis=1)

      self.assertAllClose(ildj, bijector.inverse_log_det_jacobian(y).eval())
      self.assertAllClose(
          ildj, bijector.inverse_and_inverse_log_det_jacobian(y)[1].eval())

  def testScalarCongruency(self):
    with self.test_session():
      bijector = bijectors.Softplus(event_ndims=0)
      assert_scalar_congruency(bijector, lower_x=-2., upper_x=2.)

  def testBijectiveAndFinite32bit(self):
    with self.test_session():
      bijector = bijectors.Softplus(event_ndims=0)
      x = np.linspace(-20., 20., 100).astype(np.float32)
      y = np.logspace(-10, 10, 100).astype(np.float32)
      assert_bijective_and_finite(bijector, x, y, rtol=1e-2, atol=1e-2)

  def testBijectiveAndFinite16bit(self):
    with self.test_session():
      bijector = bijectors.Softplus(event_ndims=0)
      # softplus(-20) is zero, so we can't use such a large range as in 32bit.
      x = np.linspace(-10., 20., 100).astype(np.float16)
      # Note that float16 is only in the open set (0, inf) for a smaller
      # logspace range.  The actual range was (-7, 4), so use something smaller
      # for the test.
      y = np.logspace(-6, 3, 100).astype(np.float16)
      assert_bijective_and_finite(bijector, x, y, rtol=1e-1, atol=1e-3)

class SoftmaxCenteredBijectorTest(tf.test.TestCase):
  """Tests correctness of the Y = g(X) = exp(X) / sum(exp(X)) transformation."""

  def testBijectorScalar(self):
    with self.test_session():
      softmax = bijectors.SoftmaxCentered()  # scalar by default
      self.assertEqual("softmax_centered", softmax.name)
      x = np.log([[2., 3, 4],
                  [4., 8, 12]])
      y = [[[2./3, 1./3],
            [3./4, 1./4],
            [4./5, 1./5]],
           [[4./5, 1./5],
            [8./9, 1./9],
            [12./13, 1./13]]]
      self.assertAllClose(y, softmax.forward(x).eval())
      self.assertAllClose(x, softmax.inverse(y).eval())
      self.assertAllClose(-np.sum(np.log(y), axis=2),
                          softmax.inverse_log_det_jacobian(y).eval(),
                          atol=0., rtol=1e-7)
      self.assertAllClose(-softmax.inverse_log_det_jacobian(y).eval(),
                          softmax.forward_log_det_jacobian(x).eval(),
                          atol=0., rtol=1e-7)

  def testBijectorVector(self):
    with self.test_session():
      softmax = bijectors.SoftmaxCentered(event_ndims=1)
      self.assertEqual("softmax_centered", softmax.name)
      x = np.log([[2., 3, 4],
                  [4., 8, 12]])
      y = [[0.2, 0.3, 0.4, 0.1],
           [0.16, 0.32, 0.48, 0.04]]
      self.assertAllClose(y, softmax.forward(x).eval())
      self.assertAllClose(x, softmax.inverse(y).eval())
      self.assertAllClose(-np.sum(np.log(y), axis=1),
                          softmax.inverse_log_det_jacobian(y).eval(),
                          atol=0., rtol=1e-7)
      self.assertAllClose(-softmax.inverse_log_det_jacobian(y).eval(),
                          softmax.forward_log_det_jacobian(x).eval(),
                          atol=0., rtol=1e-7)

  def testShapeGetters(self):
    with self.test_session():
      for x, y, b in (
          (tf.TensorShape([]),
           tf.TensorShape([2]),
           bijectors.SoftmaxCentered(event_ndims=0, validate_args=True)),
          (tf.TensorShape([4]),
           tf.TensorShape([5]),
           bijectors.SoftmaxCentered(event_ndims=1, validate_args=True))):
        self.assertAllEqual(y, b.get_forward_event_shape(x))
        self.assertAllEqual(y.as_list(),
                            b.forward_event_shape(x.as_list()).eval())
        self.assertAllEqual(x, b.get_inverse_event_shape(y))
        self.assertAllEqual(x.as_list(),
                            b.inverse_event_shape(y.as_list()).eval())

  def testBijectiveAndFinite(self):
    with self.test_session():
      softmax = bijectors.SoftmaxCentered(event_ndims=1)
      x = np.linspace(-50, 50, num=10).reshape(5, 2).astype(np.float32)
      # Make y values on the simplex with a wide range.
      y_0 = np.ones(5).astype(np.float32)
      y_1 = (1e-5 * rng.rand(5)).astype(np.float32)
      y_2 = (1e1 * rng.rand(5)).astype(np.float32)
      y = np.array([y_0, y_1, y_2])
      y /= y.sum(axis=0)
      y = y.T  # y.shape = [5, 3]
      assert_bijective_and_finite(softmax, x, y)

class SigmoidCenteredBijectorTest(tf.test.TestCase):
  """Tests correctness of the Y = g(X) = (1 + exp(-X))^-1 transformation."""

  def testBijector(self):
    with self.test_session():
      sigmoid = bijectors.SigmoidCentered()
      self.assertEqual("sigmoid_centered", sigmoid.name)
      x = np.log([[2., 3, 4],
                  [4., 8, 12]])
      y = [[[2./3, 1./3],
            [3./4, 1./4],
            [4./5, 1./5]],
           [[4./5, 1./5],
            [8./9, 1./9],
            [12./13, 1./13]]]
      self.assertAllClose(y, sigmoid.forward(x).eval())
      self.assertAllClose(x, sigmoid.inverse(y).eval())
      self.assertAllClose(-np.sum(np.log(y), axis=2),
                          sigmoid.inverse_log_det_jacobian(y).eval(),
                          atol=0., rtol=1e-7)
      self.assertAllClose(-sigmoid.inverse_log_det_jacobian(y).eval(),
                          sigmoid.forward_log_det_jacobian(x).eval(),
                          atol=0., rtol=1e-7)

class CholeskyOuterProductBijectorTest(tf.test.TestCase):
  """Tests the correctness of the Y = X * X^T transformation."""

  def testBijectorMatrix(self):
    with self.test_session():
      bijector = bijectors.CholeskyOuterProduct(event_ndims=2,
                                                validate_args=True)
      self.assertEqual("cholesky_outer_product", bijector.name)
      x = [[[1., 0],
            [2, 1]],
           [[math.sqrt(2.), 0],
            [math.sqrt(8.), 1]]]
      y = np.matmul(x, np.transpose(x, axes=(0, 2, 1)))
      # Fairly easy to compute differentials since we have 2x2.
      dx_dy = [[[2.*1, 0, 0],
                [2, 1, 0],
                [0, 2*2, 2*1]],
               [[2*math.sqrt(2.), 0, 0],
                [math.sqrt(8.), math.sqrt(2.), 0],
                [0, 2*math.sqrt(8.), 2*1]]]
      ildj = -np.sum(
          np.log(np.asarray(dx_dy).diagonal(offset=0, axis1=1, axis2=2)),
          axis=1)
      self.assertAllEqual((2, 2, 2), bijector.forward(x).get_shape())
      self.assertAllEqual((2, 2, 2), bijector.inverse(y).get_shape())
      self.assertAllClose(y, bijector.forward(x).eval())
      self.assertAllClose(x, bijector.inverse(y).eval())
      self.assertAllClose(ildj,
                          bijector.inverse_log_det_jacobian(y).eval(),
                          atol=0., rtol=1e-7)
      self.assertAllClose(-bijector.inverse_log_det_jacobian(y).eval(),
                          bijector.forward_log_det_jacobian(x).eval(),
                          atol=0., rtol=1e-7)

  def testBijectorScalar(self):
    with self.test_session():
      bijector = bijectors.CholeskyOuterProduct(event_ndims=0,
                                                validate_args=True)
      self.assertEqual("cholesky_outer_product", bijector.name)
      x = [[[1., 5],
            [2, 1]],
           [[math.sqrt(2.), 3],
            [math.sqrt(8.), 1]]]
      y = np.square(x)
      ildj = -math.log(2.) - np.log(x)
      self.assertAllClose(y, bijector.forward(x).eval())
      self.assertAllClose(x, bijector.inverse(y).eval())
      self.assertAllClose(ildj,
                          bijector.inverse_log_det_jacobian(y).eval(),
                          atol=0., rtol=1e-7)
      self.assertAllClose(-bijector.inverse_log_det_jacobian(y).eval(),
                          bijector.forward_log_det_jacobian(x).eval(),
                          atol=0., rtol=1e-7)

  def testScalarCongruency(self):
    with self.test_session():
      bijector = bijectors.CholeskyOuterProduct(event_ndims=0,
                                                validate_args=True)
      assert_scalar_congruency(bijector, lower_x=1e-3, upper_x=1.5, rtol=0.05)

class ChainBijectorTest(tf.test.TestCase):
  """Tests the correctness of the Y = Chain(bij1, bij2, bij3) transformation."""

  def testBijector(self):
    with self.test_session():
      chain = bijectors.Chain((bijectors.Exp(event_ndims=1),
                               bijectors.Softplus(event_ndims=1)))
      self.assertEqual("chain_of_exp_of_softplus", chain.name)
      x = np.asarray([[[1., 2.],
                       [2., 3.]]])
      self.assertAllClose(1. + np.exp(x), chain.forward(x).eval())
      self.assertAllClose(np.log(x - 1.), chain.inverse(x).eval())
      self.assertAllClose(-np.sum(np.log(x - 1.), axis=2),
                          chain.inverse_log_det_jacobian(x).eval())
      self.assertAllClose(np.sum(x, axis=2),
                          chain.forward_log_det_jacobian(x).eval())

  def testBijectorIdentity(self):
    with self.test_session():
      chain = bijectors.Chain()
      self.assertEqual("identity", chain.name)
      x = np.asarray([[[1., 2.],
                       [2., 3.]]])
      self.assertAllClose(x, chain.forward(x).eval())
      self.assertAllClose(x, chain.inverse(x).eval())
      self.assertAllClose(0., chain.inverse_log_det_jacobian(x).eval())
      self.assertAllClose(0., chain.forward_log_det_jacobian(x).eval())

  def testScalarCongruency(self):
    with self.test_session():
      bijector = bijectors.Chain((bijectors.Exp(),
                                  bijectors.Softplus()))
      assert_scalar_congruency(bijector, lower_x=1e-3, upper_x=1.5, rtol=0.05)

  def testShapeGetters(self):
    with self.test_session():
      bijector = bijectors.Chain((
          bijectors.SoftmaxCentered(event_ndims=1, validate_args=True),
          bijectors.SoftmaxCentered(event_ndims=0, validate_args=True)))
      x = tf.TensorShape([])
      y = tf.TensorShape([2+1])
      self.assertAllEqual(y, bijector.get_forward_event_shape(x))
      self.assertAllEqual(y.as_list(),
                          bijector.forward_event_shape(x.as_list()).eval())
      self.assertAllEqual(x, bijector.get_inverse_event_shape(y))
      self.assertAllEqual(x.as_list(),
                          bijector.inverse_event_shape(y.as_list()).eval())

class InvertBijectorTest(tf.test.TestCase):
  """Tests the correctness of the Y = Invert(bij) transformation."""

  def testBijector(self):
    with self.test_session():
      for fwd in [
          bijectors.Identity(),
          bijectors.Exp(event_ndims=1),
          bijectors.ScaleAndShift(
              shift=[0., 1.], scale=[[2., 0], [0, 3.]], event_ndims=1),
          bijectors.Softplus(event_ndims=1),
          bijectors.SoftmaxCentered(event_ndims=1),
          bijectors.SigmoidCentered(),
      ]:
        rev = bijectors.Invert(fwd)
        self.assertEqual("_".join(["invert", fwd.name]), rev.name)
        x = [[[1., 2.],
              [2., 3.]]]
        self.assertAllClose(fwd.inverse(x).eval(),
                            rev.forward(x).eval())
        self.assertAllClose(fwd.forward(x).eval(),
                            rev.inverse(x).eval())
        self.assertAllClose(fwd.forward_log_det_jacobian(x).eval(),
                            rev.inverse_log_det_jacobian(x).eval())
        self.assertAllClose(fwd.inverse_log_det_jacobian(x).eval(),
                            rev.forward_log_det_jacobian(x).eval())
        inv, jac = rev.inverse_and_inverse_log_det_jacobian(x)
        self.assertAllClose(fwd.forward(x).eval(),
                            inv.eval())
        self.assertAllClose(fwd.forward_log_det_jacobian(x).eval(),
                            jac.eval())

  def testScalarCongruency(self):
    with self.test_session():
      bijector = bijectors.Invert(bijectors.Exp())
      assert_scalar_congruency(bijector, lower_x=1e-3, upper_x=1.5, rtol=0.05)

  def testShapeGetters(self):
    with self.test_session():
      bijector = bijectors.Invert(bijectors.SigmoidCentered(
          validate_args=True))
      x = tf.TensorShape([2])
      y = tf.TensorShape([])
      self.assertAllEqual(y, bijector.get_forward_event_shape(x))
      self.assertAllEqual(y.as_list(),
                          bijector.forward_event_shape(x.as_list()).eval())
      self.assertAllEqual(x, bijector.get_inverse_event_shape(y))
      self.assertAllEqual(x.as_list(),
                          bijector.inverse_event_shape(y.as_list()).eval())

if __name__ == "__main__":
  tf.test.main()


text:
<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: class_blockpermission.php 27449 2012-02-01 05:32:35Z zhangguosheng $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class block_permission {

	function block_permission() {}

	function &instance() {
		static $object;
		if(empty($object)) {
			$object = new block_permission();
		}
		return $object;
	}

	function add_users_perm($bid, $users) {
		if(($uids = C::t('common_block_permission')->insert_by_bid($bid, $users))) {
			$this->_update_member_allowadmincp($uids);
		}

	}

	function _update_member_allowadmincp($uids) {
		if(!empty($uids)) {
			$userperms = C::t('common_block_permission')->fetch_permission_by_uid($uids);
			foreach(C::t('common_member')->fetch_all($uids, false, 0) as $uid => $v) {
				$v['allowadmincp'] = setstatus(4, empty($userperms[$uid]['allowmanage']) ? 0 : 1, $v['allowadmincp']);
				if($userperms[$uid]['allowrecommend'] > 0 ) {
					if($userperms[$uid]['allowrecommend'] == $userperms[$uid]['needverify']) {
						$v['allowadmincp'] = setstatus(5, 1, $v['allowadmincp']);
						$v['allowadmincp'] = setstatus(6, 0, $v['allowadmincp']);
					} else {
						$v['allowadmincp'] = setstatus(5, 0, $v['allowadmincp']);
						$v['allowadmincp'] = setstatus(6, 1, $v['allowadmincp']);
					}
				} else {
					$v['allowadmincp'] = setstatus(5, 0, $v['allowadmincp']);
					$v['allowadmincp'] = setstatus(6, 0, $v['allowadmincp']);
				}
				C::t('common_member')->update($uid, array('allowadmincp'=>$v['allowadmincp']));
			}
		}
	}

	function delete_users_perm($bid, $users) {
		$bid = intval($bid);
		if($bid && $users) {
			C::t('common_block_permission')->delete_by_bid_uid_inheritedtplname($bid, $users, '');
			C::t('common_block_favorite')->delete_by_uid_bid($users, $bid);
			$this->_update_member_allowadmincp($users);
		}
	}

	function delete_inherited_perm_by_bid($bids, $inheritedtplname = '', $uid = 0) {
		if(!is_array($bids)) $bids = array($bids);
		if($bids) {
			$uid = intval($uid);
			C::t('common_block_permission')->delete_by_bid_uid_inheritedtplname($bids, $users, empty($inheritedtplname) ? true : $inheritedtplname);
			if($uid) {
				C::t('common_block_favorite')->delete_by_uid_bid($uid, $bids);
				$this->_update_member_allowadmincp(array($uid));
			}
		}
	}

	function remake_inherited_perm($bid) {
		$bid = intval($bid);
		if($bid) {
			if(($targettplname = C::t('common_template_block')->fetch_targettplname_by_bid($bid))) {
				$tplpermsission = & template_permission::instance();
				$userperm = $tplpermsission->get_users_perm_by_template($targettplname);
				$this->add_users_blocks($userperm, $bid, $targettplname);
			}
		}
	}

	function get_perms_by_bid($bid, $uid = 0) {
		$perms = array();
		$bid = intval($bid);
		$uid = intval($uid);
		if($bid) {
			$perms = C::t('common_block_permission')->fetch_all_by_bid($bid, $uid);
		}
		return $perms;
	}

	function add_users_blocks($users, $bids, $tplname = '') {
		if(($uids = C::t('common_block_permission')->insert_batch($users, $bids, $tplname))) {
			$this->_update_member_allowadmincp($uids);
		}
	}

	function delete_perm_by_inheritedtpl($tplname, $uids) {
		if(!empty($uids) && !is_array($uids)) $uids = array($uids);
		if($tplname) {
			C::t('common_block_permission')->delete_by_bid_uid_inheritedtplname(FALSE, $uids, $tplname);
			if($uids) {
				$this->_update_member_allowadmincp($uids);
			}
		}
	}

	function delete_perm_by_template($templates) {
		if($templates) {
			C::t('common_block_permission')->delete_by_bid_uid_inheritedtplname(FALSE, FALSE, $templates);
		}
	}
	function get_bids_by_template($tplname) {
		return $tplname ? C::t('common_template_block')->fetch_all_bid_by_targettplname_notinherited($tplname, 0) : array();
	}
}

class template_permission {
	function template_permission() {}

	function &instance() {
		static $object;
		if(empty($object)) {
			$object = new template_permission();
		}
		return $object;
	}

	function add_users($tplname, $users) {
		$templates = $this->_get_templates_subs($tplname);
		$this->_add_users_templates($users, $templates);

		$blockpermission = & block_permission::instance();
		$bids = $blockpermission->get_bids_by_template($templates);
		$blockpermission->add_users_blocks($users, $bids, $tplname);
	}

	function delete_users($tplname, $uids) {
		$uids = !is_array($uids) ? array($uids) : $uids;
		$uids = array_map('intval', $uids);
		$uids = array_filter($uids);
		if($uids) {
			C::t('common_template_permission')->delete_by_targettplname_uid_inheritedtplname($tplname, $uids, '');
		}
		$this->delete_perm_by_inheritedtpl($tplname, $uids);
	}

	function add_blocks($tplname, $bids){
		$users = $this->get_users_perm_by_template($tplname);
		if($users) {
			$blockpermission = & block_permission::instance();
			$blockpermission->add_users_blocks($users, $bids, $tplname);
		}
	}

	function get_users_perm_by_template($tplname){
		$perm = array();
		if($tplname) {
			$perm = C::t('common_template_permission')->fetch_all_by_targettplname($tplname);
		}
		return $perm;
	}

	function _add_users_templates($users, $templates, $uptplname = '') {
		C::t('common_template_permission')->insert_batch($users, $templates, $uptplname);
	}

	function delete_allperm_by_tplname($tplname){
		if($tplname) {
			$tplname = is_array($tplname) ? $tplname : array($tplname);
			$blockpermission = & block_permission::instance();
			$blockpermission->delete_perm_by_template($tplname);
			$tplnames = dimplode($tplname);
			C::t('common_template_permission')->delete_by_targettplname_uid_inheritedtplname($tplnames);
			C::t('common_template_permission')->delete_by_targettplname_uid_inheritedtplname(false, false, $tplnames);
		}
	}
	function delete_inherited_perm_by_tplname($templates, $inheritedtplname = '', $uid = 0) {
		if($templates && !is_array($templates)) {
			$templates = $this->_get_templates_subs($templates);
		}
		if($templates) {
			$uid = intval($uid);
			C::t('common_template_permission')->delete_by_targettplname_uid_inheritedtplname($templates, $uid, $inheritedtplname ? $inheritedtplname : true);

			$blockpermission = & block_permission::instance();
			$blocks = $blockpermission->get_bids_by_template($templates);
			$blockpermission->delete_inherited_perm_by_bid($blocks, $inheritedtplname, $uid);
		}
	}

	function delete_perm_by_inheritedtpl($tplname, $uids = array()) {
		if($uids && !is_array($uids)) $uids = array($uids);
		if($tplname) {
			C::t('common_template_permission')->delete_by_targettplname_uid_inheritedtplname(false, $uids, $tplname);
			$blockpermission = & block_permission::instance();
			$blockpermission->delete_perm_by_inheritedtpl($tplname, $uids);
		}
	}

	function remake_inherited_perm($tplname, $parenttplname) {
		if($tplname && $parenttplname) {
			$users = $this->get_users_perm_by_template($parenttplname);
			$templates = $this->_get_templates_subs($tplname);
			$this->_add_users_templates($users, $templates, $parenttplname);

			$blockpermission = & block_permission::instance();
			$bids = $blockpermission->get_bids_by_template($templates);
			$blockpermission->add_users_blocks($users, $bids, $parenttplname);
		}
	}

	function _get_templates_subs($tplname){
		global $_G;
		$tplpre = 'portal/list_';
		$cattpls = array($tplname);
		if(substr($tplname, 0, 12) == $tplpre){
			loadcache('portalcategory');
			$portalcategory = $_G['cache']['portalcategory'];
			$catid = intval(str_replace($tplpre, '', $tplname));
			if(isset($portalcategory[$catid]) && !empty($portalcategory[$catid]['children'])) {
				$children = array();
				foreach($portalcategory[$catid]['children'] as $cid) {
					if(!$portalcategory[$cid]['notinheritedblock']) {
						$cattpls[] = $tplpre.$cid;
						if(!empty($portalcategory[$cid]['children'])) {
							$children = array_merge($children, $portalcategory[$cid]['children']);
						}
					}
				}
				if(!empty($children)) {
					foreach($children as $cid) {
						if(!$portalcategory[$cid]['notinheritedblock']) {
							$cattpls[] = $tplpre.$cid;
						}
					}
				}
			}
		}
		return $cattpls;
	}

	function _get_templates_ups($tplname){
		global $_G;
		$tplpre = 'portal/list_';
		$cattpls = array($tplname);
		if(substr($tplname, 0, 12) == $tplpre){
			loadcache('portalcategory');
			$portalcategory = $_G['cache']['portalcategory'];
			$catid = intval(str_replace($tplpre, '', $tplname));
			if(isset($portalcategory[$catid]) && !$portalcategory[$catid]['notinheritedblock']) {
				$upid = $portalcategory[$catid]['upid'];
				while(!empty($upid)) {
					$cattpls[] = $tplpre.$upid;
					$upid = !$portalcategory[$upid]['notinheritedblock'] ? $portalcategory[$upid]['upid'] : 0;
				}
			}
		}
		return $cattpls;
	}

}

?>

redpajama_set_name: RedPajamaGithub


text:
package io.druid.data.input.impl;

import au.com.bytecode.opencsv.CSVParser;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.metamx.common.collect.Utils;
import com.metamx.common.logger.Logger;
import com.metamx.common.parsers.ParseException;
import com.metamx.common.parsers.Parser;
import com.metamx.common.parsers.ParserUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by saligia on 17-3-29.
 */
public class CSVParse implements Parser<String, Object> {
    private static final Logger log = new Logger(CSVParse.class);
    private final String listDelimiter;
    private final Splitter listSplitter;
    private final Function<String, Object> valueFunction;
    private final CSVParser parser;
    private ArrayList<String> fieldNames;

    public CSVParse(Optional<String> listDelimiter, char separator, char quotechar ) {
        this.parser = new CSVParser(separator,quotechar);
        this.fieldNames = null;
        this.listDelimiter = listDelimiter.isPresent()?(String)listDelimiter.get():"\u0001";
        this.listSplitter = Splitter.on(this.listDelimiter);
        this.valueFunction = new Function() {
            @Override
            public Object apply(Object input) {
                return ((String)input).contains(CSVParse.this.listDelimiter)?Lists.newArrayList(Iterables.transform(CSVParse.this.listSplitter.split((String)input), ParserUtils.nullEmptyStringFunction)):ParserUtils.nullEmptyStringFunction.apply((String) input);
            }
        };
    }

    public CSVParse(Optional<String> listDelimiter,char separator, char quotechar, Iterable<String> fieldNames) {
        this(listDelimiter,separator,quotechar);
        this.setFieldNames(fieldNames);
    }

    public CSVParse(Optional<String> listDelimiter,char separator, char quotechar, String header) {
        this(listDelimiter,separator,quotechar);
        this.setFieldNames(header);
    }

    public String getListDelimiter() {
        return this.listDelimiter;
    }

    public List<String> getFieldNames() {
        return this.fieldNames;
    }

    public void setFieldNames(Iterable<String> fieldNames) {
        ParserUtils.validateFields(fieldNames);
        this.fieldNames = Lists.newArrayList(fieldNames);
    }

    public void setFieldNames(String header) {
        try {
            this.setFieldNames((Iterable) Arrays.asList(this.parser.parseLine(header)));
        } catch (Exception var3) {
            throw new ParseException(var3, "Unable to parse header [%s]", new Object[]{header});
        }
    }

    public Map<String, Object> parse(String input) {
        try {
            String[] e = this.parser.parseLine(input);
            if(this.fieldNames == null) {
                this.setFieldNames((Iterable)ParserUtils.generateFieldNames(e.length));
            }

            return Utils.zipMapPartial(this.fieldNames, Iterables.transform(Lists.newArrayList(e), this.valueFunction));
        } catch (Exception var3) {
            throw new ParseException(var3, "Unable to parse row [%s]", new Object[]{input});
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bubble"
        android:layout_centerInParent="true"
        android:gravity="center"
        />

</RelativeLayout>


text:
FROM node:9-alpine

WORKDIR /asimov-deploy/
COPY package.json .
ENV NODE_ENV production

RUN apk add --no-cache --virtual .gyp \
        python \
        make \
        g++ && \
        npm set progress=false && \
        npm config set depth 0 && \
        npm install && \
        npm cache verify && \
        apk del .gyp

# RUN npm set progress=false && \
#     npm config set depth 0 && \
#     npm install && \
#     npm cache clean

COPY  . /asimov-deploy/

EXPOSE 3333

CMD [ "npm", "start" ]


text:
using System;
using System.Web.Mvc;
using System.Web.Routing;
using Hardcore.Web.Mvc;

namespace Hardcore.Web.Test.WebCtrlAndSrvFactoring
{
    partial class CommonMvcControllersFactoryBehavior
    {
        class TestControllerNameResolver : IMvcControllerNameResolver
        {
            public Type GetControllerType(RequestContext requestContext, string controllerName)
            {
                if (controllerName == "Test") return typeof(TestController);
                throw new InvalidOperationException();
            }
        }

        class TestController : Controller
        {
            public int ControlValue { get; }
            public bool Released { get; private set; }
            public bool Disposed { get; private set; }

            public TestController()
            {

            }

            public TestController(int controlValue)
            {
                ControlValue = controlValue;
            }

            public void Release()
            {
                Released = true;
            }

            protected override void Dispose(bool disposing)
            {
                base.Dispose(disposing);
                Disposed = true;
            }
        }

        class TestControllerFactory : IMvcControllerFactory
        {
            private readonly int _controlValue;

            public TestControllerFactory(int controlValue = 0)
            {
                _controlValue = controlValue;
            }

            public IController CreateInstance(RequestContext requestContext)
            {
                return new TestController(_controlValue);
            }

            public void ReleaseInstance(IController controller)
            {
                ((TestController) controller).Release();
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.newdawn.slick.openal.SoundStore (Slick - The 2D Library)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.newdawn.slick.openal.SoundStore

Packages that use SoundStore

org.newdawn.slick.openal
This package contains the nitty gritty sound manipulation code for using OpenAL with standard audio formats.

Uses of SoundStore in org.newdawn.slick.openal

Methods in org.newdawn.slick.openal that return SoundStore

static SoundStore
SoundStore.get()

          Get the single instance of this class

Constructors in org.newdawn.slick.openal with parameters of type SoundStore

MODSound(SoundStore store,
         java.io.InputStream in)

          Create a mod sound to be played back

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2006 New Dawn Software. All Rights Reserved.


text:
title: Telerik.Web.UI.ToolTipScrolling
page_title: Client-side API Reference
description: Client-side API Reference
slug: Telerik.Web.UI.ToolTipScrolling
---

# enum Telerik.Web.UI.ToolTipScrolling

## Inheritance Hierarchy

* *[Telerik.Web.UI.ToolTipScrolling]({%slug Telerik.Web.UI.ToolTipScrolling%})*

## Fields

### Auto `0`

### None `1`

### X `2`

### Y `3`

### Both `4`

### Default `5`


text:
.class Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;
.super Ljava/lang/Object;
.source "WifiConfigStore.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/wifi/WifiConfigStore;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "DelayedDiskWrite"
.end annotation

# static fields
.field private static final TAG:Ljava/lang/String; = "DelayedDiskWrite"

.field private static sDiskWriteHandler:Landroid/os/Handler;

.field private static sDiskWriteHandlerThread:Landroid/os/HandlerThread;

.field private static sWriteSequence:I

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 693
    const/4 v0, 0x0

    sput v0, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    return-void
.end method

.method private constructor <init>()V
    .locals 0

    .prologue
    .line 688
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method static synthetic access$000(Ljava/util/List;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 688
    invoke-static {p0}, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->onWriteCalled(Ljava/util/List;)V

    return-void
.end method

.method private static loge(Ljava/lang/String;)V
    .locals 1
    .parameter "s"

    .prologue
    .line 831
    const-string v0, "DelayedDiskWrite"

    invoke-static {v0, p0}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 832
    return-void
.end method

.method private static onWriteCalled(Ljava/util/List;)V
    .locals 17
    .parameter
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/List",
            "<",
            "Landroid/net/wifi/WifiConfiguration;",
            ">;)V"
        }
    .end annotation

    .prologue
    .line 717
    .local p0, networks:Ljava/util/List;,"Ljava/util/List<Landroid/net/wifi/WifiConfiguration;>;"
    const/4 v9, 0x0

    .line 719
    .local v9, out:Ljava/io/DataOutputStream;
    :try_start_0
    new-instance v10, Ljava/io/DataOutputStream;

    new-instance v14, Ljava/io/BufferedOutputStream;

    new-instance v15, Ljava/io/FileOutputStream;

    invoke-static {}, Landroid/net/wifi/WifiConfigStore;->access$100()Ljava/lang/String;

    move-result-object v16

    invoke-direct/range {v15 .. v16}, Ljava/io/FileOutputStream;-><init>(Ljava/lang/String;)V

    invoke-direct {v14, v15}, Ljava/io/BufferedOutputStream;-><init>(Ljava/io/OutputStream;)V

    invoke-direct {v10, v14}, Ljava/io/DataOutputStream;-><init>(Ljava/io/OutputStream;)V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_4
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_5

    .line 722
    .end local v9           #out:Ljava/io/DataOutputStream;
    .local v10, out:Ljava/io/DataOutputStream;
    const/4 v14, 0x2

    :try_start_1
    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V

    .line 724
    invoke-interface/range {p0 .. p0}, Ljava/util/List;->iterator()Ljava/util/Iterator;

    move-result-object v4

    :goto_0
    invoke-interface {v4}, Ljava/util/Iterator;->hasNext()Z

    move-result v14

    if-eqz v14, :cond_a

    invoke-interface {v4}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/net/wifi/WifiConfiguration;
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0
    .catch Ljava/io/IOException; {:try_start_1 .. :try_end_1} :catch_0

    .line 725
    .local v0, config:Landroid/net/wifi/WifiConfiguration;
    const/4 v13, 0x0

    .line 728
    .local v13, writeToFile:Z
    :try_start_2
    iget-object v8, v0, Landroid/net/wifi/WifiConfiguration;->linkProperties:Landroid/net/LinkProperties;

    .line 729
    .local v8, linkProperties:Landroid/net/LinkProperties;
    sget-object v14, Landroid/net/wifi/WifiConfigStore$1;->$SwitchMap$android$net$wifi$WifiConfiguration$IpAssignment:[I

    iget-object v15, v0, Landroid/net/wifi/WifiConfiguration;->ipAssignment:Landroid/net/wifi/WifiConfiguration$IpAssignment;

    invoke-virtual {v15}, Landroid/net/wifi/WifiConfiguration$IpAssignment;->ordinal()I

    move-result v15

    aget v14, v14, v15

    packed-switch v14, :pswitch_data_0

    .line 770
    const-string v14, "Ignore invalid ip assignment while writing"

    invoke-static {v14}, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->loge(Ljava/lang/String;)V

    .line 774
    :goto_1
    :pswitch_0
    sget-object v14, Landroid/net/wifi/WifiConfigStore$1;->$SwitchMap$android$net$wifi$WifiConfiguration$ProxySettings:[I

    iget-object v15, v0, Landroid/net/wifi/WifiConfiguration;->proxySettings:Landroid/net/wifi/WifiConfiguration$ProxySettings;

    invoke-virtual {v15}, Landroid/net/wifi/WifiConfiguration$ProxySettings;->ordinal()I

    move-result v15

    aget v14, v14, v15

    packed-switch v14, :pswitch_data_1

    .line 797
    const-string v14, "Ignthisore invalid proxy settings while writing"

    invoke-static {v14}, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->loge(Ljava/lang/String;)V

    .line 800
    :goto_2
    :pswitch_1
    if-eqz v13, :cond_0

    .line 801
    const-string v14, "id"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 802
    #calls: Landroid/net/wifi/WifiConfigStore;->configKey(Landroid/net/wifi/WifiConfiguration;)I
    invoke-static {v0}, Landroid/net/wifi/WifiConfigStore;->access$200(Landroid/net/wifi/WifiConfiguration;)I

    move-result v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_0
    .catch Ljava/lang/NullPointerException; {:try_start_2 .. :try_end_2} :catch_1
    .catch Ljava/io/IOException; {:try_start_2 .. :try_end_2} :catch_0

    .line 807
    .end local v8           #linkProperties:Landroid/net/LinkProperties;
    :cond_0
    :goto_3
    :try_start_3
    const-string v14, "eos"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V
    :try_end_3
    .catchall {:try_start_3 .. :try_end_3} :catchall_0
    .catch Ljava/io/IOException; {:try_start_3 .. :try_end_3} :catch_0

    goto :goto_0

    .line 810
    .end local v0           #config:Landroid/net/wifi/WifiConfiguration;
    .end local v13           #writeToFile:Z
    :catch_0
    move-exception v2

    move-object v9, v10

    .line 811
    .end local v10           #out:Ljava/io/DataOutputStream;
    .local v2, e:Ljava/io/IOException;
    .restart local v9       #out:Ljava/io/DataOutputStream;
    :goto_4
    :try_start_4
    const-string v14, "Error writing data file"

    invoke-static {v14}, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->loge(Ljava/lang/String;)V
    :try_end_4
    .catchall {:try_start_4 .. :try_end_4} :catchall_4

    .line 813
    if-eqz v9, :cond_1

    .line 815
    :try_start_5
    invoke-virtual {v9}, Ljava/io/DataOutputStream;->close()V
    :try_end_5
    .catch Ljava/lang/Exception; {:try_start_5 .. :try_end_5} :catch_3

    .line 820
    :cond_1
    :goto_5
    const-class v15, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;

    monitor-enter v15

    .line 821
    :try_start_6
    sget v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    add-int/lit8 v14, v14, -0x1

    sput v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    if-nez v14, :cond_2

    .line 822
    sget-object v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandler:Landroid/os/Handler;

    invoke-virtual {v14}, Landroid/os/Handler;->getLooper()Landroid/os/Looper;

    move-result-object v14

    invoke-virtual {v14}, Landroid/os/Looper;->quit()V

    .line 823
    const/4 v14, 0x0

    sput-object v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandler:Landroid/os/Handler;

    .line 824
    const/4 v14, 0x0

    sput-object v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandlerThread:Landroid/os/HandlerThread;

    .line 826
    :cond_2
    monitor-exit v15
    :try_end_6
    .catchall {:try_start_6 .. :try_end_6} :catchall_2

    .line 828
    .end local v2           #e:Ljava/io/IOException;
    :goto_6
    return-void

    .line 731
    .end local v9           #out:Ljava/io/DataOutputStream;
    .restart local v0       #config:Landroid/net/wifi/WifiConfiguration;
    .restart local v8       #linkProperties:Landroid/net/LinkProperties;
    .restart local v10       #out:Ljava/io/DataOutputStream;
    .restart local v13       #writeToFile:Z
    :pswitch_2
    :try_start_7
    const-string v14, "ipAssignment"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 732
    iget-object v14, v0, Landroid/net/wifi/WifiConfiguration;->ipAssignment:Landroid/net/wifi/WifiConfiguration$IpAssignment;

    invoke-virtual {v14}, Landroid/net/wifi/WifiConfiguration$IpAssignment;->toString()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 733
    invoke-virtual {v8}, Landroid/net/LinkProperties;->getLinkAddresses()Ljava/util/Collection;

    move-result-object v14

    invoke-interface {v14}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v5

    .local v5, i$:Ljava/util/Iterator;
    :goto_7
    invoke-interface {v5}, Ljava/util/Iterator;->hasNext()Z

    move-result v14

    if-eqz v14, :cond_5

    invoke-interface {v5}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v7

    check-cast v7, Landroid/net/LinkAddress;

    .line 734
    .local v7, linkAddr:Landroid/net/LinkAddress;
    const-string v14, "linkAddress"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 735
    invoke-virtual {v7}, Landroid/net/LinkAddress;->getAddress()Ljava/net/InetAddress;

    move-result-object v14

    invoke-virtual {v14}, Ljava/net/InetAddress;->getHostAddress()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 736
    invoke-virtual {v7}, Landroid/net/LinkAddress;->getNetworkPrefixLength()I

    move-result v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V
    :try_end_7
    .catchall {:try_start_7 .. :try_end_7} :catchall_0
    .catch Ljava/lang/NullPointerException; {:try_start_7 .. :try_end_7} :catch_1
    .catch Ljava/io/IOException; {:try_start_7 .. :try_end_7} :catch_0

    goto :goto_7

    .line 804
    .end local v5           #i$:Ljava/util/Iterator;
    .end local v7           #linkAddr:Landroid/net/LinkAddress;
    .end local v8           #linkProperties:Landroid/net/LinkProperties;
    :catch_1
    move-exception v2

    .line 805
    .local v2, e:Ljava/lang/NullPointerException;
    :try_start_8
    new-instance v14, Ljava/lang/StringBuilder;

    invoke-direct {v14}, Ljava/lang/StringBuilder;-><init>()V

    const-string v15, "Failure in writing "

    invoke-virtual {v14, v15}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v14

    iget-object v15, v0, Landroid/net/wifi/WifiConfiguration;->linkProperties:Landroid/net/LinkProperties;

    invoke-virtual {v14, v15}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v14

    invoke-virtual {v14, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v14

    invoke-virtual {v14}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v14

    invoke-static {v14}, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->loge(Ljava/lang/String;)V
    :try_end_8
    .catchall {:try_start_8 .. :try_end_8} :catchall_0
    .catch Ljava/io/IOException; {:try_start_8 .. :try_end_8} :catch_0

    goto/16 :goto_3

    .line 813
    .end local v0           #config:Landroid/net/wifi/WifiConfiguration;
    .end local v2           #e:Ljava/lang/NullPointerException;
    .end local v13           #writeToFile:Z
    :catchall_0
    move-exception v14

    move-object v9, v10

    .end local v10           #out:Ljava/io/DataOutputStream;
    .restart local v9       #out:Ljava/io/DataOutputStream;
    :goto_8
    if-eqz v9, :cond_3

    .line 815
    :try_start_9
    invoke-virtual {v9}, Ljava/io/DataOutputStream;->close()V
    :try_end_9
    .catch Ljava/lang/Exception; {:try_start_9 .. :try_end_9} :catch_2

    .line 820
    :cond_3
    :goto_9
    const-class v15, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;

    monitor-enter v15

    .line 821
    :try_start_a
    sget v16, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    add-int/lit8 v16, v16, -0x1

    sput v16, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    if-nez v16, :cond_4

    .line 822
    sget-object v16, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandler:Landroid/os/Handler;

    invoke-virtual/range {v16 .. v16}, Landroid/os/Handler;->getLooper()Landroid/os/Looper;

    move-result-object v16

    invoke-virtual/range {v16 .. v16}, Landroid/os/Looper;->quit()V

    .line 823
    const/16 v16, 0x0

    sput-object v16, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandler:Landroid/os/Handler;

    .line 824
    const/16 v16, 0x0

    sput-object v16, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandlerThread:Landroid/os/HandlerThread;

    .line 826
    :cond_4
    monitor-exit v15
    :try_end_a
    .catchall {:try_start_a .. :try_end_a} :catchall_1

    .line 813
    throw v14

    .line 738
    .end local v9           #out:Ljava/io/DataOutputStream;
    .restart local v0       #config:Landroid/net/wifi/WifiConfiguration;
    .restart local v5       #i$:Ljava/util/Iterator;
    .restart local v8       #linkProperties:Landroid/net/LinkProperties;
    .restart local v10       #out:Ljava/io/DataOutputStream;
    .restart local v13       #writeToFile:Z
    :cond_5
    :try_start_b
    invoke-virtual {v8}, Landroid/net/LinkProperties;->getRoutes()Ljava/util/Collection;

    move-result-object v14

    invoke-interface {v14}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v5

    :goto_a
    invoke-interface {v5}, Ljava/util/Iterator;->hasNext()Z

    move-result v14

    if-eqz v14, :cond_8

    invoke-interface {v5}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v12

    check-cast v12, Landroid/net/RouteInfo;

    .line 739
    .local v12, route:Landroid/net/RouteInfo;
    const-string v14, "gateway"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 740
    invoke-virtual {v12}, Landroid/net/RouteInfo;->getDestination()Landroid/net/LinkAddress;

    move-result-object v1

    .line 741
    .local v1, dest:Landroid/net/LinkAddress;
    if-eqz v1, :cond_6

    .line 742
    const/4 v14, 0x1

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V

    .line 743
    invoke-virtual {v1}, Landroid/net/LinkAddress;->getAddress()Ljava/net/InetAddress;

    move-result-object v14

    invoke-virtual {v14}, Ljava/net/InetAddress;->getHostAddress()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 744
    invoke-virtual {v1}, Landroid/net/LinkAddress;->getNetworkPrefixLength()I

    move-result v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V

    .line 748
    :goto_b
    invoke-virtual {v12}, Landroid/net/RouteInfo;->getGateway()Ljava/net/InetAddress;

    move-result-object v14

    if-eqz v14, :cond_7

    .line 749
    const/4 v14, 0x1

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V

    .line 750
    invoke-virtual {v12}, Landroid/net/RouteInfo;->getGateway()Ljava/net/InetAddress;

    move-result-object v14

    invoke-virtual {v14}, Ljava/net/InetAddress;->getHostAddress()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    goto :goto_a

    .line 746
    :cond_6
    const/4 v14, 0x0

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V

    goto :goto_b

    .line 752
    :cond_7
    const/4 v14, 0x0

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V

    goto :goto_a

    .line 755
    .end local v1           #dest:Landroid/net/LinkAddress;
    .end local v12           #route:Landroid/net/RouteInfo;
    :cond_8
    invoke-virtual {v8}, Landroid/net/LinkProperties;->getDnses()Ljava/util/Collection;

    move-result-object v14

    invoke-interface {v14}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v5

    :goto_c
    invoke-interface {v5}, Ljava/util/Iterator;->hasNext()Z

    move-result v14

    if-eqz v14, :cond_9

    invoke-interface {v5}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Ljava/net/InetAddress;

    .line 756
    .local v6, inetAddr:Ljava/net/InetAddress;
    const-string v14, "dns"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 757
    invoke-virtual {v6}, Ljava/net/InetAddress;->getHostAddress()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    goto :goto_c

    .line 759
    .end local v6           #inetAddr:Ljava/net/InetAddress;
    :cond_9
    const/4 v13, 0x1

    .line 760
    goto/16 :goto_1

    .line 762
    .end local v5           #i$:Ljava/util/Iterator;
    :pswitch_3
    const-string v14, "ipAssignment"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 763
    iget-object v14, v0, Landroid/net/wifi/WifiConfiguration;->ipAssignment:Landroid/net/wifi/WifiConfiguration$IpAssignment;

    invoke-virtual {v14}, Landroid/net/wifi/WifiConfiguration$IpAssignment;->toString()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 764
    const/4 v13, 0x1

    .line 765
    goto/16 :goto_1

    .line 776
    :pswitch_4
    invoke-virtual {v8}, Landroid/net/LinkProperties;->getHttpProxy()Landroid/net/ProxyProperties;

    move-result-object v11

    .line 777
    .local v11, proxyProperties:Landroid/net/ProxyProperties;
    invoke-virtual {v11}, Landroid/net/ProxyProperties;->getExclusionList()Ljava/lang/String;

    move-result-object v3

    .line 778
    .local v3, exclusionList:Ljava/lang/String;
    const-string/jumbo v14, "proxySettings"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 779
    iget-object v14, v0, Landroid/net/wifi/WifiConfiguration;->proxySettings:Landroid/net/wifi/WifiConfiguration$ProxySettings;

    invoke-virtual {v14}, Landroid/net/wifi/WifiConfiguration$ProxySettings;->toString()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 780
    const-string/jumbo v14, "proxyHost"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 781
    invoke-virtual {v11}, Landroid/net/ProxyProperties;->getHost()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 782
    const-string/jumbo v14, "proxyPort"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 783
    invoke-virtual {v11}, Landroid/net/ProxyProperties;->getPort()I

    move-result v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeInt(I)V

    .line 784
    const-string v14, "exclusionList"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 785
    invoke-virtual {v10, v3}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 786
    const/4 v13, 0x1

    .line 787
    goto/16 :goto_2

    .line 789
    .end local v3           #exclusionList:Ljava/lang/String;
    .end local v11           #proxyProperties:Landroid/net/ProxyProperties;
    :pswitch_5
    const-string/jumbo v14, "proxySettings"

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V

    .line 790
    iget-object v14, v0, Landroid/net/wifi/WifiConfiguration;->proxySettings:Landroid/net/wifi/WifiConfiguration$ProxySettings;

    invoke-virtual {v14}, Landroid/net/wifi/WifiConfiguration$ProxySettings;->toString()Ljava/lang/String;

    move-result-object v14

    invoke-virtual {v10, v14}, Ljava/io/DataOutputStream;->writeUTF(Ljava/lang/String;)V
    :try_end_b
    .catchall {:try_start_b .. :try_end_b} :catchall_0
    .catch Ljava/lang/NullPointerException; {:try_start_b .. :try_end_b} :catch_1
    .catch Ljava/io/IOException; {:try_start_b .. :try_end_b} :catch_0

    .line 791
    const/4 v13, 0x1

    .line 792
    goto/16 :goto_2

    .line 813
    .end local v0           #config:Landroid/net/wifi/WifiConfiguration;
    .end local v8           #linkProperties:Landroid/net/LinkProperties;
    .end local v13           #writeToFile:Z
    :cond_a
    if-eqz v10, :cond_b

    .line 815
    :try_start_c
    invoke-virtual {v10}, Ljava/io/DataOutputStream;->close()V
    :try_end_c
    .catch Ljava/lang/Exception; {:try_start_c .. :try_end_c} :catch_4

    .line 820
    :cond_b
    :goto_d
    const-class v15, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;

    monitor-enter v15

    .line 821
    :try_start_d
    sget v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    add-int/lit8 v14, v14, -0x1

    sput v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    if-nez v14, :cond_c

    .line 822
    sget-object v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandler:Landroid/os/Handler;

    invoke-virtual {v14}, Landroid/os/Handler;->getLooper()Landroid/os/Looper;

    move-result-object v14

    invoke-virtual {v14}, Landroid/os/Looper;->quit()V

    .line 823
    const/4 v14, 0x0

    sput-object v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandler:Landroid/os/Handler;

    .line 824
    const/4 v14, 0x0

    sput-object v14, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandlerThread:Landroid/os/HandlerThread;

    .line 826
    :cond_c
    monitor-exit v15
    :try_end_d
    .catchall {:try_start_d .. :try_end_d} :catchall_3

    move-object v9, v10

    .line 827
    .end local v10           #out:Ljava/io/DataOutputStream;
    .restart local v9       #out:Ljava/io/DataOutputStream;
    goto/16 :goto_6

    .line 816
    :catch_2
    move-exception v15

    goto/16 :goto_9

    .line 826
    :catchall_1
    move-exception v14

    :try_start_e
    monitor-exit v15
    :try_end_e
    .catchall {:try_start_e .. :try_end_e} :catchall_1

    throw v14

    .line 816
    .local v2, e:Ljava/io/IOException;
    :catch_3
    move-exception v14

    goto/16 :goto_5

    .line 826
    :catchall_2
    move-exception v14

    :try_start_f
    monitor-exit v15
    :try_end_f
    .catchall {:try_start_f .. :try_end_f} :catchall_2

    throw v14

    .line 816
    .end local v2           #e:Ljava/io/IOException;
    .end local v9           #out:Ljava/io/DataOutputStream;
    .restart local v10       #out:Ljava/io/DataOutputStream;
    :catch_4
    move-exception v14

    goto :goto_d

    .line 826
    :catchall_3
    move-exception v14

    :try_start_10
    monitor-exit v15
    :try_end_10
    .catchall {:try_start_10 .. :try_end_10} :catchall_3

    throw v14

    .line 813
    .end local v10           #out:Ljava/io/DataOutputStream;
    .restart local v9       #out:Ljava/io/DataOutputStream;
    :catchall_4
    move-exception v14

    goto/16 :goto_8

    .line 810
    :catch_5
    move-exception v2

    goto/16 :goto_4

    .line 729
    nop

    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_2
        :pswitch_3
        :pswitch_0
    .end packed-switch

    .line 774
    :pswitch_data_1
    .packed-switch 0x1
        :pswitch_4
        :pswitch_5
        :pswitch_1
    .end packed-switch
.end method

.method static write(Ljava/util/List;)V
    .locals 3
    .parameter
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/List",
            "<",
            "Landroid/net/wifi/WifiConfiguration;",
            ">;)V"
        }
    .end annotation

    .prologue
    .line 699
    .local p0, networks:Ljava/util/List;,"Ljava/util/List<Landroid/net/wifi/WifiConfiguration;>;"
    const-class v1, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;

    monitor-enter v1

    .line 700
    :try_start_0
    sget v0, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    add-int/lit8 v0, v0, 0x1

    sput v0, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sWriteSequence:I

    const/4 v2, 0x1

    if-ne v0, v2, :cond_0

    .line 701
    new-instance v0, Landroid/os/HandlerThread;

    const-string v2, "WifiConfigThread"

    invoke-direct {v0, v2}, Landroid/os/HandlerThread;-><init>(Ljava/lang/String;)V

    sput-object v0, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandlerThread:Landroid/os/HandlerThread;

    .line 702
    sget-object v0, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandlerThread:Landroid/os/HandlerThread;

    invoke-virtual {v0}, Landroid/os/HandlerThread;->start()V

    .line 703
    new-instance v0, Landroid/os/Handler;

    sget-object v2, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandlerThread:Landroid/os/HandlerThread;

    invoke-virtual {v2}, Landroid/os/HandlerThread;->getLooper()Landroid/os/Looper;

    move-result-object v2

    invoke-direct {v0, v2}, Landroid/os/Handler;-><init>(Landroid/os/Looper;)V

    sput-object v0, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandler:Landroid/os/Handler;

    .line 705
    :cond_0
    monitor-exit v1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 707
    sget-object v0, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite;->sDiskWriteHandler:Landroid/os/Handler;

    new-instance v1, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite$1;

    invoke-direct {v1, p0}, Landroid/net/wifi/WifiConfigStore$DelayedDiskWrite$1;-><init>(Ljava/util/List;)V

    invoke-virtual {v0, v1}, Landroid/os/Handler;->post(Ljava/lang/Runnable;)Z

    .line 713
    return-void

    .line 705
    :catchall_0
    move-exception v0

    :try_start_1
    monitor-exit v1
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    throw v0
.end method


text:
package wikipedia;

/**
 * Manage the queries to Wikipedia related to their textual information.
 * @author kemoadrian
 *
 */
public class WikiTextResult {

	public static final String test = "22989";

	private Query query;

	/**
	 * Get the text of a queried page.
	 * @return a {@link String} with the text from the queried page
	 */
	public String text() {
		return query.pages.page.extract;
	}

	/**
	 * Store the result of a query to Wikipedia in an object {@link Query}.
	 * @author kemoadrian
	 *
	 */
	static class Query {
		public static String[] pageids;
		public Pages pages;
	}

	/**
	 * Store the a list of Wikipedia pages in an object {@link Pages}.
	 * @author kemoadrian
	 *
	 */
	static class Pages {
		Page page;
	}

	/**
	 * Store a Wikipedia page in an object {@link Page}.
	 * @author kemoadrian
	 *
	 */
	static class Page {
		String extract;
	}

}


text:
package net.wolfesoftware.jax.ast;

public class PrimitiveType extends ParseElement
{
    private final KeywordElement keywordElement;
    private PrimitiveType(KeywordElement keywordElement)
    {
        this.keywordElement = keywordElement;
    }

    @Override
    protected void decompile(String indentation, StringBuilder out)
    {
        keywordElement.decompile(indentation, out);
    }

    public static final int TYPE = 0x2527055c;
    public int getElementType()
    {
        return TYPE;
    }

    @Override
    protected boolean isSingletonLike()
    {
        return true;
    }

    public static final PrimitiveType VOID = new PrimitiveType(KeywordElement.VOID);
    public static final PrimitiveType INT = new PrimitiveType(KeywordElement.INT);
    public static final PrimitiveType BYTE = new PrimitiveType(KeywordElement.BYTE);
    public static final PrimitiveType FLOAT = new PrimitiveType(KeywordElement.FLOAT);
    public static final PrimitiveType DOUBLE = new PrimitiveType(KeywordElement.DOUBLE);
    public static final PrimitiveType BOOLEAN = new PrimitiveType(KeywordElement.BOOLEAN);
}


text:
package jp.fieldnotes.hatunatu.dao.annotation.tiger;

import java.lang.annotation.*;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SqlFile {
    String value() default "";
}


text:
package com.evolveum.midpoint.schema.processor;

/**
 * @author semancik
 *
 */
public class SearchHierarchyConstraints {

	ResourceObjectIdentification baseContext;
	SearchHierarchyScope scope;

	public SearchHierarchyConstraints(ResourceObjectIdentification baseContext, SearchHierarchyScope scope) {
		super();
		this.baseContext = baseContext;
		this.scope = scope;
	}

	public ResourceObjectIdentification getBaseContext() {
		return baseContext;
	}

	public SearchHierarchyScope getScope() {
		return scope;
	}

}


text:
<?php

    use Railpage\Users\Users;
    use Railpage\Users\Admin;
    use Railpage\Users\Base;
    use Railpage\Users\User;
    use Railpage\Warnings\Warning;

    class NoUserTest extends PHPUnit_Framework_TestCase {

        public function test_isUsernameAvailable() {

            $User = new User;
            $User->username = "phpunit3";
            $User->contact_email = "michael+phpunit3@railpage.com.au";
            $User->setPassword("letmein1234");

            $this->assertTrue($User->isUsernameAvailable("phpunit3"));

            $User->commit();

            $this->assertFalse($User->isUsernameAvailable("phpunit3"));
            $this->assertFalse($User->isUsernameAvailable());

            $Base = new Base;
            $this->assertFalse($Base->username_available("phpunit3"));
            $this->assertTrue($Base->username_available("blahsdfsfa"));

            $Admin = new Admin;
            $this->assertFalse($Admin->username_available("phpunit3"));

            $User = new User;
            $this->setExpectedException("Exception", "Cannot check if username is available because no username was provided");
            $this->assertFalse($User->isUsernameAvailable());

        }

        public function test_isEmailAvailable() {

            $User = new User;
            $User->username = "phpunit4";
            $User->contact_email = "michael+phpunit4@railpage.com.au";
            $User->setPassword("letmein1234");

            $this->assertTrue($User->isEmailAvailable("michael+phpunit4@railpage.com.au"));

            $User->commit();

            $this->assertFalse($User->isEmailAvailable("michael+phpunit4@railpage.com.au"));
            $this->assertFalse($User->isEmailAvailable());

            $Base = new Base;
            $this->assertFalse($Base->email_available("michael+phpunit4@railpage.com.au"));
            $this->assertTrue($Base->email_available("michael+phpunit87654@railpage.com.au"));
            $this->assertfalse($Base->email_available());

            $Admin = new Admin;
            $this->assertFalse($Admin->email_available("michael+phpunit4@railpage.com.au"));

            $User = new User;
            $this->setExpectedException("Exception", "Cannot check if email address is available because no email address was provided");
            $this->assertFalse($User->isEmailAvailable());

        }

        public function test_validateNewUser_EmptyUsername() {

            $this->setExpectedException("Exception", "Username cannot be empty");

            $User = new User;

            $User->validate();

        }

        public function test_validateNewUser_EmtpyEmail() {

            $this->setExpectedException("Exception", "User must have an email address");

            $User = new User;

            $User->username = "testblah";
            $User->validate();

        }

        public function test_validateNewUser_InvalidEmail() {

            $email = "adfsdafaf";

            $this->setExpectedException("Exception", sprintf("%s is not a valid email address", $email));

            $User = new User;

            $User->username = "testblah";
            $User->contact_email = $email;
            $User->validate();

        }

        public function test_validateNewUser_EmptyPassword() {

            $this->setExpectedException("Exception", "Password is empty");

            $User = new User;

            $User->username = "testblah";
            $User->contact_email = "blah@railpage.com.au";
            $User->provider = "railpage";
            $User->validate();

        }

        public function test_validateNewUser_EmptyPasswordSuccess() {

            $User = new User;

            $User->username = "testblah";
            $User->contact_email = "blah@railpage.com.au";
            $User->provider = "google";
            $User->validate();
            $this->assertEquals("", $User->password);

        }

        public function test_validateNewUser_DefaultTheme() {

            $User = new User;

            $User->username = "testblah";
            $User->contact_email = "blah@railpage.com.au";
            $User->provider = "google";
            $User->default_theme = NULL;

            $User->validate();

        }

    }


text:
package com.example.dateasy.adapter;

import java.util.List;

import com.example.dateasy.R;
import com.example.dateasy.activity.TypeActivity;
import com.example.dateasy.consts.Const;
import com.example.dateasy.util.Utils;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * 首页轮转的图片Adapter
 *
 * @author Xu
 *
 */
public class FavouriteAdvViewPagerAdapter extends PagerAdapter implements
		OnClickListener {
	private List<Integer> imageList;
	private Context mContext;

	public FavouriteAdvViewPagerAdapter(Context mContext,
			List<Integer> imageList) {
		this.imageList = imageList;
		this.mContext = mContext;
	}

	@Override
	public int getCount() {
		return imageList.size();
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object);
	}

	@Override
	public Object instantiateItem(ViewGroup container, final int position) {
		ImageView iv = new ImageView(mContext);
		iv.setBackgroundResource(imageList.get(position));
		switch (position) {
		case 1:
			iv.setId(R.id.img2_id);
			break;

		case 2:
			iv.setId(R.id.img3_id);
			break;

		case 3:
			iv.setId(R.id.img4_id);
			break;

		case 4:
			iv.setId(R.id.img5_id);
			break;

		case 5:
			iv.setId(R.id.img0_id);
			break;

		case 0:
			iv.setId(R.id.img1_id);
			break;
		}
		container.addView(iv);
		iv.setOnClickListener(this);
		return iv;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Bundle bundle = new Bundle();
		switch (v.getId()) {
		case R.id.img1_id:
			bundle.putString("NAME", Const.OTHERS);
			bundle.putInt("IMAGE", imageList.get(0));
			Utils.toAnotherActivity(mContext, TypeActivity.class, bundle);
			break;

		case R.id.img2_id:
			bundle.putString("NAME", Const.ACTIVITY_SIGNUP);
			bundle.putInt("IMAGE", imageList.get(1));
			Utils.toAnotherActivity(mContext, TypeActivity.class, bundle);
			break;

		case R.id.img3_id:
			bundle.putString("NAME", Const.MEETING);
			bundle.putInt("IMAGE", imageList.get(2));
			Utils.toAnotherActivity(mContext, TypeActivity.class, bundle);
			break;

		case R.id.img4_id:
			bundle.putString("NAME", Const.OUTDOOR_ACTIVITIES);
			bundle.putInt("IMAGE", imageList.get(3));
			Utils.toAnotherActivity(mContext, TypeActivity.class, bundle);
			break;

		case R.id.img5_id:
			bundle.putString("NAME", Const.GATHERING);
			bundle.putInt("IMAGE", imageList.get(4));
			Utils.toAnotherActivity(mContext, TypeActivity.class, bundle);
			break;

		case R.id.img0_id:
			bundle.putString("NAME", Const.ENTERTAINMENT);
			bundle.putInt("IMAGE", imageList.get(5));
			Utils.toAnotherActivity(mContext, TypeActivity.class, bundle);
			break;
		}
	}

}


text:
'use strict';
var path = require('path');
module.exports = function (grunt, workspaceName) {
  var defaultWorkspacePath = path.join('..', workspaceName);
  var alternativeWorkspacePath = path.join('.', workspaceName);

  if (grunt.file.isDir(defaultWorkspacePath)) {
    return defaultWorkspacePath;
  } else if (grunt.file.isDir(alternativeWorkspacePath)) {
    return alternativeWorkspacePath;
  }
  // also if it does not exist, return the default path
  return defaultWorkspacePath;
};