text:
"""Test cases for eager execution using XLA."""

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

import numpy as np

from tensorflow.compiler.tests import xla_test
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.eager import function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.layers import convolutional
from tensorflow.python.layers import pooling
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import embedding_ops
from tensorflow.python.ops import gen_random_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.platform import googletest
from tensorflow.python.training import adam

class EagerTest(xla_test.XLATestCase):

  def testBasic(self):
    with self.test_scope():
      three = constant_op.constant(3)
      five = constant_op.constant(5)
      product = three * five
      self.assertAllEqual(15, product)

  def testGradientTape(self):
    with self.test_scope():

      x = constant_op.constant(1.0)
      y = constant_op.constant(10.0)
      with backprop.GradientTape(persistent=True) as tape:
        tape.watch(x)
        tape.watch(y)
        a = x + y + x * y
      da_dx = tape.gradient(a, x)
      da_dy = tape.gradient(a, y)

    self.assertEqual(11.0, da_dx.numpy())
    self.assertEqual(2.0, da_dy.numpy())

  def testExecuteListOutputLen0(self):
    with self.test_scope():
      empty = constant_op.constant([], dtype=dtypes.float32)
      result = array_ops.unstack(empty, 0)
      self.assertTrue(isinstance(result, list))
      self.assertEqual(0, len(result))

  def testExecuteListOutputLen1(self):
    with self.test_scope():
      split_dim = constant_op.constant(1)
      value = constant_op.constant([[0., 1., 2.], [3., 4., 5.]])
      result = array_ops.split(value, 1, axis=split_dim)
      self.assertTrue(isinstance(result, list))
      self.assertEqual(1, len(result))
      self.assertAllEqual([[0, 1, 2], [3, 4, 5]], result[0])

  def testExecuteListOutputLen3(self):
    with self.test_scope():
      split_dim = constant_op.constant(1)
      value = constant_op.constant([[0., 1., 2.], [3., 4., 5.]])
      result = array_ops.split(value, 3, axis=split_dim)
      self.assertTrue(isinstance(result, list))
      self.assertEqual(3, len(result))
      self.assertAllEqual([[0], [3]], result[0])
      self.assertAllEqual([[1], [4]], result[1])
      self.assertAllEqual([[2], [5]], result[2])

  def testBasicGraph(self):
    # Run some ops eagerly
    with self.test_scope():
      three = constant_op.constant(3)
      five = constant_op.constant(5)
      product = three * five
      self.assertAllEqual(15, product)

    # Run some ops graphly
    with context.graph_mode(), self.cached_session():
      with self.test_scope():
        three = constant_op.constant(3)
        five = constant_op.constant(5)
        product = three * five
        self.assertAllEqual(15, self.evaluate(product))

  def testDegenerateSlices(self):
    with self.test_scope():
      npt = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3)
      t = constant_op.constant(npt)
      # degenerate by offering a forward interval with a negative stride
      self.assertAllEqual(npt[0:-1:-1, :, :], t[0:-1:-1, :, :])
      # degenerate with a reverse interval with a positive stride
      self.assertAllEqual(npt[-1:0, :, :], t[-1:0, :, :])
      # empty interval in every dimension
      self.assertAllEqual(npt[-1:0, 2:2, 2:3:-1], t[-1:0, 2:2, 2:3:-1])

  def testIdentity(self):
    with self.test_scope():
      self.assertAllEqual(2, array_ops.identity(2))

  def testRandomOps(self):
    with self.test_scope():
      tensor = gen_random_ops.random_uniform((2, 2), dtypes.float32)
      row0 = tensor[0].numpy()
      row1 = tensor[1].numpy()
      # It should be very unlikely to rng to generate two equal rows.
      self.assertFalse((row0 == row1).all())

  def testIdentityOnVariable(self):
    with self.test_scope():
      v = resource_variable_ops.ResourceVariable(True)
      i = array_ops.identity(v)
    self.assertAllEqual(True, i.numpy())

  def testAssignAddVariable(self):
    with self.test_scope():
      v = resource_variable_ops.ResourceVariable(1.0)
      v.assign_add(2.0)
    self.assertEqual(3.0, v.numpy())

  def testReadAssignRead(self):
    with self.test_scope():
      v = resource_variable_ops.ResourceVariable(1.0)
      val1 = v.read_value()
      v.assign_add(2.0)
      val2 = v.read_value()
    self.assertEqual(1.0, val1.numpy())
    self.assertEqual(3.0, val2.numpy())

  def testGradient(self):
    def f(x):
      return x

    with self.test_scope():
      grad_fn = backprop.gradients_function(f)
      self.assertAllEqual(2., grad_fn(1., dy=2.)[0])

  def testVariableGradient(self):
    with self.test_scope():
      v0 = resource_variable_ops.ResourceVariable(1.0)

      def f():
        x = v0 * v0
        return x

      grads = backprop.implicit_grad(f)()
    self.assertEqual(2., grads[0][0].numpy())

  def testMultipleVariableReads(self):
    # This test makes sure consecutive variable reads don't copy
    # the underlying memory.
    with self.test_scope():
      # Create 128MiB variables
      var = resource_variable_ops.ResourceVariable(
          array_ops.ones([32, 1024, 1024]))

      # Read the same variable 100 times. If the underlying tensor
      # is not copied, this is a trivial operation. If it is copied,
      # this will eat over 13GB and OOM.
      values = []
      for _ in range(100):
        values.append(var.value())

  # The shape, shape_n, size, and rank are tested here because their
  # execution kernels (as opposed to compilation only tf2xla kernels)
  # are distincts from tf2xla kernels.

  def testShape(self):
    def const(value):
      return array_ops.shape(
          constant_op.constant(value)).numpy()

    def ones(value):
      return array_ops.shape(
          array_ops.ones(value)).numpy()

    with self.test_scope():
      # Shapes of directly constructed tensors
      self.assertAllEqual([], const(3))
      self.assertAllEqual([3], const([1.0, 2.0, 3.0]))
      self.assertAllEqual([2, 2], const([[1.0, 2.0], [3.0, 4.0]]))
      self.assertAllEqual([2, 1, 2], const([[[1.0, 2.0]], [[3.0, 4.0]]]))

      # Shapes of tensors created by op running on device
      # We make this distinction because directly constructed tensors
      # are treated differently in a few places that can influence shape:
      #  - they always have on_host_tensor
      #  - they and their shapes can be cached
      #  - they end up on device via a copy, instead of as program output
      self.assertAllEqual([], ones([]))
      self.assertAllEqual([3], ones([3]))
      self.assertAllEqual([2, 2], ones([2, 2]))
      self.assertAllEqual([2, 1, 2], ones([2, 1, 2]))

  def testShapeN(self):
    with self.test_scope():
      # Shapes of directly constructed tensors
      shapes = array_ops.shape_n([
          constant_op.constant(1.0),
          constant_op.constant([1.0, 2.0, 3.0]),
          constant_op.constant([[1.0, 2.0], [3.0, 4.0]])])
      self.assertAllEqual(
          [[], [3], [2, 2]],
          [x.numpy().tolist() for x in shapes])

      # Shapes of tensors created by op running on device
      shapes = array_ops.shape_n([
          array_ops.ones([]),
          array_ops.ones([3]),
          array_ops.ones([2, 2])])
      self.assertAllEqual(
          [[], [3], [2, 2]],
          [x.numpy().tolist() for x in shapes])

  def testSize(self):
    with self.test_scope():
      self.assertEqual(
          1, array_ops.size(constant_op.constant(1.0)).numpy())
      self.assertEqual(
          3, array_ops.size(constant_op.constant([1.0, 2.0, 3.0])).numpy())
      self.assertEqual(
          4, array_ops.size(
              constant_op.constant([[1.0, 2.0], [3.0, 4.0]])).numpy())

  def testRank(self):
    with self.test_scope():
      self.assertEqual(
          0, array_ops.rank(constant_op.constant(1.0)).numpy())
      self.assertEqual(
          1, array_ops.rank(constant_op.constant([1.0, 2.0, 3.0])).numpy())
      self.assertEqual(
          2, array_ops.rank(
              constant_op.constant([[1.0, 2.0], [3.0, 4.0]])).numpy())

  def testAdam(self):
    with self.test_scope():
      optimizer = adam.AdamOptimizer(0.1)
      x = resource_variable_ops.ResourceVariable(10.0)
      with backprop.GradientTape() as tape:
        y = x * x
      dy_dx = tape.gradient(y, x)
      optimizer.apply_gradients([(dy_dx, x)])
      self.assertAlmostEqual(9.9, x.numpy(), places=3)

  def testAdamSparse(self):
    with ops.device('/cpu:0'):
      # Create 2-D embedding for 3 objects on CPU because sparse/sliced updates
      # are not implemented on TPU.
      embedding_matrix = resource_variable_ops.ResourceVariable(
          array_ops.ones([3, 2]))

    with self.test_scope():
      with backprop.GradientTape() as tape:
        embedding = embedding_ops.embedding_lookup(embedding_matrix, [1])
        y = math_ops.reduce_sum(embedding)
      dy_dx = tape.gradient(y, embedding_matrix)
      self.assertIsInstance(dy_dx, ops.IndexedSlices)
      optimizer = adam.AdamOptimizer(0.1)
      # The gradient application operations will run on CPU because optimizer
      # updates are always collocated with the variable.
      optimizer.apply_gradients([(dy_dx, embedding_matrix)])

      # This assign_add will run on CPU because when an input to an
      # operation is a resource, this operation is placed on the resource's
      # device by the eager runtime.
      embedding_matrix.assign_add(array_ops.ones([3, 2]))

    self.assertAllClose([[2.0, 2.0],
                         [1.9, 1.9],
                         [2.0, 2.0]], embedding_matrix.numpy())

class EagerFunctionTest(xla_test.XLATestCase):

  def testBasic(self):
    with self.test_scope():
      matmul = function.defun(math_ops.matmul)
      t = constant_op.constant([[1.0, 2.0], [3.0, 4.0]])
      sq = matmul(t, t, transpose_a=True)
      self.assertAllEqual(sq.numpy().reshape(-1), [10, 14, 14, 20])

  def testConv(self):
    if 'GPU' in self.device:
      # TODO(b/32333178)
      self.skipTest('Current implementation of RandomStandardNormal kernel '
                    'is very slow on GPU, and has been blacklisted.')
    with self.test_scope():
      data_format = 'channels_last'
      conv = convolutional.Conv2D(
          filters=1, kernel_size=2, padding='VALID',
          data_format=data_format, activation=nn_ops.relu,
          kernel_initializer=init_ops.ones_initializer(),
          bias_initializer=init_ops.zeros_initializer())
      pool = pooling.MaxPooling2D(2, 2, data_format=data_format)

      def model(x):
        x = conv(x)
        return pool(x)
      model = function.defun(model)

      x = array_ops.ones([1, 4, 4, 1])
      y = model(x)
      self.assertAllEqual(y.numpy(), [[[[4.]]]])

  def testReadVariable(self):
    with self.test_scope():
      v = resource_variable_ops.ResourceVariable(1.0)

      @function.defun
      def f():
        return v.read_value()

      var = f()
      self.assertEqual(1.0, var.numpy())

  def testUpdateVariable(self):
    with self.test_scope():
      v = resource_variable_ops.ResourceVariable(1.0)

      def f(v):
        v.assign_add(1.0)
        return v

      f = function.defun(f)

      var = f(v)
      self.assertEqual(2.0, var.numpy())

  def testReturnResourceHandle(self):
    with self.test_scope():
      v = resource_variable_ops.ResourceVariable([[1.0, 2.0], [3.0, 4.0]])

      def f(v):
        return v.handle

      f = function.defun(f)
      handle = f(v)
      self.assertAllEqual(v.numpy(),
                          resource_variable_ops.read_variable_op(
                              handle, dtypes.float32).numpy())

  def testReturnMultipleResourceHandles(self):
    with self.test_scope():
      v1 = resource_variable_ops.ResourceVariable(1.25)
      v2 = resource_variable_ops.ResourceVariable(2.0)

      def f(v):
        return v.handle, 3.0 * v, v2.handle, v + v2

      f = function.defun(f)
      v1_handle, v1_times_3, v2_handle, variable_sum = f(v1)
      self.assertAllEqual(v1.numpy(),
                          resource_variable_ops.read_variable_op(
                              v1_handle, dtypes.float32).numpy())
      self.assertEqual(3.75, v1_times_3.numpy())
      self.assertAllEqual(v2.numpy(),
                          resource_variable_ops.read_variable_op(
                              v2_handle, dtypes.float32).numpy())
      self.assertEqual(3.25, variable_sum.numpy())

  def testAllArgumentKinds(self):
    """Test a complex function that takes different argument kinds.

    tf2xla machinery that translates, compiles, and runs defuns
    classifies arguments into: compile-time constants, regular tensors,
    and resources. This test creates a function with a mix of all these
    kinds. Moreover, the order of function arguments is intentionally mixed up.

    This also tests the case when the same argument is a compile-time constant
    as well as used in an operation that normally expects its inputs to be
    in device memory - addition in this case.
    """
    with self.test_scope():
      def foo(c1, r1, v1, c2, v2, r2):
        # c1 and c2 are compile-time constants
        # r1 and r2 are regular tensors
        # v1 and v2 are resource variables
        a = c1 + r1
        b = math_ops.cast(c2, dtypes.float32) + v2
        c = array_ops.slice(v1, c1, c2)
        d = r2 * v2
        return a, b, c, d

      foo = function.defun(foo)

      c1 = [0, 0]
      c2 = array_ops.ones([2], dtype=dtypes.int32)

      r1 = array_ops.ones([2])
      r2 = [[2., 2.], [3., 3.]]

      v1 = resource_variable_ops.ResourceVariable([[1., 2.], [3., 4.]])
      v2 = resource_variable_ops.ResourceVariable([[10., 20.], [30., 40.]])

      a, b, c, d = foo(c1, r1, v1, c2, v2, r2)

      self.assertAllEqual([1, 1], a.numpy())
      self.assertAllEqual([[11., 21.], [31., 41.]], b.numpy())
      self.assertAllEqual([[1.]], c.numpy())
      self.assertAllEqual([[20., 40.], [90., 120.]], d.numpy())

  def testDefunInGradientTape(self):
    with self.test_scope():
      v0 = resource_variable_ops.ResourceVariable(5.0)

      @function.defun
      def f(x):
        x = v0 * v0 * x
        return x

      x = constant_op.constant(3.0)
      with backprop.GradientTape() as tape:
        y = f(x)
      dy = tape.gradient(y, v0)

    self.assertEqual(75, y.numpy())
    self.assertEqual(30, dy.numpy())

  def testGradientTapeInDefun(self):
    with self.test_scope():
      v0 = resource_variable_ops.ResourceVariable(5.0)

      @function.defun
      def f():
        x = constant_op.constant(1.0)
        with backprop.GradientTape() as tape:
          y = v0 * x
        dy = tape.gradient(y, v0)
        return dy

      dy = f()
      self.assertEqual(1.0, dy.numpy())

  def testSliceInDefun(self):
    with self.test_scope():

      @function.defun
      def f(x, y):
        return x[0::2, y:, ...]

      x = array_ops.ones([2, 3, 4], dtype=dtypes.float32)
      y = array_ops.ones([], dtype=dtypes.int32)
      with backprop.GradientTape() as tape:
        tape.watch(x)
        tape.watch(y)
        z = f(x, y)
      dz = tape.gradient(z, x)

      self.assertAllEqual(np.ones([1, 2, 4]), z.numpy())
      self.assertAllEqual((2, 3, 4), dz.shape.as_list())

  def testNestedDefun(self):
    with self.test_scope():

      @function.defun
      def times_two(x):
        return 2. * x

      @function.defun
      def two_x_plus_1(x):
        return times_two(x) + 1.

      x = constant_op.constant([2., 3., 4.])
      y = two_x_plus_1(x)
      self.assertAllEqual([5., 7., 9.], y.numpy())

  def testNestedDefunWithVariable(self):
    with self.test_scope():
      v0 = resource_variable_ops.ResourceVariable(5.0)

      @function.defun
      def g(x):
        x = v0 * x
        return x

      @function.defun
      def f(x):
        x = g(v0 * x)
        return x

      x = constant_op.constant(3.0)
      y = f(x)

    self.assertEqual(75.0, y.numpy())

  def testNestedDefunInGradientTape(self):
    with self.test_scope():
      v0 = resource_variable_ops.ResourceVariable(5.0)

      @function.defun
      def g(x):
        x = v0 * x
        return x

      @function.defun
      def f(x):
        x = g(v0 * x)
        return x

      x = constant_op.constant(3.0)
      with backprop.GradientTape() as tape:
        y = f(x)
      dy = tape.gradient(y, v0)

    self.assertEqual(75, y.numpy())
    self.assertEqual(30, dy.numpy())

  def testNestedDefunInGradientTapeDifferentVars(self):
    with self.test_scope():
      v0 = resource_variable_ops.ResourceVariable(5.0)
      v1 = resource_variable_ops.ResourceVariable(3.0)

      @function.defun
      def g(x):
        x = v1 * x
        return x

      @function.defun
      def f(x):
        x = g(v0 * x)
        return x

      x = constant_op.constant(3.0)
      with backprop.GradientTape(persistent=True) as tape:
        y = f(x)
      dy_v0 = tape.gradient(y, v0)
      dy_v1 = tape.gradient(y, v1)

    self.assertEqual(45, y.numpy())
    self.assertEqual(9, dy_v0.numpy())
    self.assertEqual(15, dy_v1.numpy())

  def testWhileInDefun(self):
    with self.test_scope():
      @def_function.function
      def f(start):
        c = lambda x: math_ops.less(x, 13.0)
        b = lambda x: math_ops.add(x, 1.0)
        return control_flow_ops.while_loop(c, b, [start])

      y = f(constant_op.constant(3.0))
    self.assertEqual(13.0, y.numpy())

  def testAutoGraphWhileInDefun(self):
    with self.test_scope():
      @def_function.function
      def f(start):
        x = start
        while x < 13.0:
          x += 1.0
        return x

      y = f(constant_op.constant(3.0))
    self.assertEqual(13.0, y.numpy())

  def testCondInDefun(self):
    with self.test_scope():
      @def_function.function
      def f(pred, value):
        fn1 = lambda: math_ops.add(value, 1.0)
        fn2 = lambda: math_ops.subtract(value, 1.0)
        return control_flow_ops.cond(pred, fn1, fn2)

      plus_one = f(constant_op.constant(True), constant_op.constant(10.0))
      minus_one = f(constant_op.constant(False), constant_op.constant(10.0))
    self.assertEqual(11.0, plus_one.numpy())
    self.assertEqual(9.0, minus_one.numpy())

  def testAutoGraphCondInDefun(self):
    with self.test_scope():
      @def_function.function
      def f(pred, value):
        if pred:
          return value + 1.0
        else:
          return value - 1.0

      plus_one = f(constant_op.constant(True), constant_op.constant(10.0))
      minus_one = f(constant_op.constant(False), constant_op.constant(10.0))
    self.assertEqual(11.0, plus_one.numpy())
    self.assertEqual(9.0, minus_one.numpy())

class ExcessivePaddingTest(xla_test.XLATestCase):
  """Test that eager execution works with TPU flattened tensors.

  Tensors that would normally be excessively padded when written
  to TPU memory are reshaped to 1-D flat tensors.

  This test case verifies that such tensors work with eager execution.

  The flattening currently only happens on TPU, but tests should work
  fine with all backends as flattening is transparent.
  """

  def testFromConstant(self):
    with self.test_scope():
      # Create constant of shape [100, 2, 1]. This tensor would be
      # excessively padded on TPU.
      tensor = constant_op.constant(100 * [[[10.0], [2.0]]])
      # Use reduce_sum since it requires correctly working with
      # a particular dimension.
      reduced = math_ops.reduce_sum(tensor, axis=1)
      self.assertAllEqual(100 * [[12.0]], reduced)

  def testFromOperation(self):
    with self.test_scope():
      tensor = array_ops.ones([3, 100, 2, 2])
      reduced = math_ops.reduce_sum(tensor, axis=[0, 2, 3])
      self.assertAllEqual(100 * [12.0], reduced)

  def testAsFunctionInput(self):
    with self.test_scope():

      @function.defun
      def f(x):
        return math_ops.reduce_sum(x, axis=2)

      tensor = constant_op.constant(100 * [[[10.0, 2.0]]])
      reduced = f(tensor)
      self.assertAllEqual(100 * [[12.0]], reduced)

  def testAsFunctionOutput(self):
    with self.test_scope():

      @function.defun
      def f(x):
        return x * constant_op.constant(100 * [[[10.0, 2.0]]])

      y = f(3)
      reduced = math_ops.reduce_sum(y, axis=2)
      self.assertAllEqual(100 * [[36.0]], reduced)

def multiple_tpus():
  devices = context.context().devices()
  return len([d for d in devices if 'device:TPU:' in d]) > 1

class MultiDeviceTest(xla_test.XLATestCase):
  """Test running TPU computation on more than one core."""

  def testBasic(self):
    if not multiple_tpus():
      self.skipTest('MultiDeviceTest requires multiple TPU devices.')

    # Compute 10 on TPU core 0
    with ops.device('device:TPU:0'):
      two = constant_op.constant(2)
      five = constant_op.constant(5)
      ten = two * five
      self.assertAllEqual(10, ten)

    # Compute 6 on TPU core 1
    with ops.device('device:TPU:1'):
      two = constant_op.constant(2)
      three = constant_op.constant(3)
      six = two * three
      self.assertAllEqual(6, six)

    # Copy 10 and 6 to CPU and sum them
    self.assertAllEqual(16, ten + six)

if __name__ == '__main__':
  ops.enable_eager_execution(
      config=config_pb2.ConfigProto(log_device_placement=True))
  googletest.main()


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

namespace Microsoft.Azure.Commands.RedisCache
{
    using Microsoft.Azure.Common.Authentication;
    using Microsoft.Azure.Common.Authentication.Models;
    using Microsoft.Azure.Management.Redis;
    using Microsoft.Azure.Management.Redis.Models;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Commands.Common;
    using System.Collections;
    using System.Collections.Generic;

    public class RedisCacheClient
    {
        private RedisManagementClient _client;
        public RedisCacheClient(AzureContext context)
        {
            _client = AzureSession.ClientFactory.CreateClient<RedisManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager);
        }
        public RedisCacheClient() { }

        public RedisCreateOrUpdateResponse CreateOrUpdateCache(string resourceGroupName, string cacheName, string location, string redisVersion, string skuFamily, int skuCapacity, string skuName, Hashtable redisConfiguration, bool? enableNonSslPort)
        {
            RedisCreateOrUpdateParameters parameters = new RedisCreateOrUpdateParameters
                                                    {
                                                        Location = location,
                                                        Properties = new RedisProperties
                                                        {
                                                            RedisVersion = redisVersion,
                                                            Sku = new Sku() {
                                                                Name = skuName,
                                                                Family = skuFamily,
                                                                Capacity = skuCapacity
                                                            }
                                                        }
                                                    };

            if (redisConfiguration != null)
            {
                parameters.Properties.RedisConfiguration = new Dictionary<string, string>();
                foreach (object key in redisConfiguration.Keys)
                {
                    parameters.Properties.RedisConfiguration.Add(key.ToString(), redisConfiguration[key].ToString());
                }
            }

            if (enableNonSslPort.HasValue)
            {
                parameters.Properties.EnableNonSslPort = enableNonSslPort.Value;
            }
            RedisCreateOrUpdateResponse response = _client.Redis.CreateOrUpdate(resourceGroupName: resourceGroupName, name: cacheName, parameters: parameters);
            return response;
        }

        public AzureOperationResponse DeleteCache(string resourceGroupName, string cacheName)
        {
            return _client.Redis.Delete(resourceGroupName: resourceGroupName, name: cacheName);
        }

        public RedisGetResponse GetCache(string resourceGroupName, string cacheName)
        {
            return _client.Redis.Get(resourceGroupName: resourceGroupName, name: cacheName);
        }

        public RedisListResponse ListCaches(string resourceGroupName)
        {
            if (string.IsNullOrEmpty(resourceGroupName))
            {
                return _client.Redis.List(null);
            }
            else
            {
                return _client.Redis.List(resourceGroupName: resourceGroupName);
            }
        }

        public RedisListResponse ListCachesUsingNextLink(string nextLink)
        {
            return _client.Redis.ListNext(nextLink: nextLink);
        }

        public AzureOperationResponse RegenerateAccessKeys(string resourceGroupName, string cacheName, RedisKeyType keyType)
        {
            return _client.Redis.RegenerateKey(resourceGroupName: resourceGroupName, name: cacheName, parameters: new RedisRegenerateKeyParameters() { KeyType = keyType });
        }

        public RedisListKeysResponse GetAccessKeys(string resourceGroupName, string cacheName)
        {
            return _client.Redis.ListKeys(resourceGroupName: resourceGroupName, name: cacheName);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface AUEntityMapping : AUObjectMapping

- (id)initWithEntityForName:(NSString *)entityName;
+ (instancetype)mappingForEntityForName:(NSString *)entityName;

@property (nonatomic, copy, readonly) NSString* entityName;

- (id)objectWithManagedObjectContext:(NSManagedObjectContext *)context;
@end


text:
package com.intellij.util.lang;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.xxh3.Xx3UnencodedString;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.LongBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.*;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.EnumSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Predicate;

final class FileLoader implements Loader {
  private static final EnumSet<StandardOpenOption> READ_OPTIONS = EnumSet.of(StandardOpenOption.READ);
  private static final EnumSet<StandardOpenOption> WRITE_OPTIONS = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE);

  private static final AtomicInteger totalLoaders = new AtomicInteger();
  private static final AtomicLong totalScanning = new AtomicLong();
  private static final AtomicLong totalSaving = new AtomicLong();
  private static final AtomicLong totalReading = new AtomicLong();

  private static final Boolean doFsActivityLogging = false;
  // find . -name "classpath.index" -delete
  private static final short indexFileVersion = 24;

  private final @NotNull Predicate<String> nameFilter;
  private final @NotNull Path path;

  FileLoader(@NotNull Path path) {
    this.path = path;
    this.nameFilter = __ -> true;
  }

  private FileLoader(@NotNull Path path, @NotNull Predicate<String> nameFilter) {
    this.path = path;
    this.nameFilter = nameFilter;
  }

  static @NotNull FileLoader createCachingFileLoader(Path file,
                                                     @Nullable CachePoolImpl cachePool,
                                                     Predicate<? super Path> cachingCondition,
                                                     boolean isClassPathIndexEnabled,
                                                     ClasspathCache cache) {
    if (cachePool == null) {
      LoaderData data = buildData(file, isClassPathIndexEnabled);
      FileLoader loader = new FileLoader(file, data.nameFilter);
      cache.applyLoaderData(data, loader);
      return loader;
    }

    ClasspathCache.IndexRegistrar data = cachePool.loaderIndexCache.get(file);
    if (data == null) {
      LoaderData loaderData = buildData(file, isClassPathIndexEnabled);
      FileLoader loader = new FileLoader(file, loaderData.nameFilter);
      if (cachingCondition != null && cachingCondition.test(file)) {
        cachePool.loaderIndexCache.put(file, loaderData);
      }
      cache.applyLoaderData(loaderData, loader);
      return loader;
    }
    else {
      FileLoader loader = new FileLoader(file, data.getNameFilter());
      cache.applyLoaderData(data, loader);
      return loader;
    }
  }

  @Override
  public @NotNull Path getPath() {
    return path;
  }

  @Override
  public void processResources(@NotNull String dir,
                               @NotNull Predicate<? super String> fileNameFilter,
                               @NotNull BiConsumer<? super String, ? super InputStream> consumer)
    throws IOException {
    try (DirectoryStream<Path> paths = Files.newDirectoryStream(path.resolve(dir))) {
      for (Path childPath : paths) {
        String name = path.relativize(childPath).toString();
        if (fileNameFilter.test(name) && Files.isRegularFile(childPath)) {
          try (InputStream stream = new BufferedInputStream(Files.newInputStream(childPath))) {
            consumer.accept(name, stream);
          }
        }
      }
    }
    catch (NotDirectoryException | NoSuchFileException ignore) {
    }
  }

  private static void buildPackageAndNameCache(Path startDir,
                                               ClasspathCache.LoaderDataBuilder context,
                                               StrippedLongArrayList nameHashes) {
    // FileVisitor is not used to avoid getting file attributes for class files
    // (.class extension is a strong indicator that it is file and not a directory)
    Deque<Path> dirCandidates = new ArrayDeque<>();
    dirCandidates.add(startDir);
    Path dir;
    int rootDirAbsolutePathLength = startDir.toString().length();
    while ((dir = dirCandidates.pollFirst()) != null) {
      try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir)) {
        boolean containsClasses = false;
        boolean containsResources = false;
        for (Path file : dirStream) {
          String path = getRelativeResourcePath(file.toString(), rootDirAbsolutePathLength);
          if (path.endsWith(ClasspathCache.CLASS_EXTENSION)) {
            nameHashes.add(Xx3UnencodedString.hashUnencodedString(path));
            containsClasses = true;
          }
          else {
            nameHashes.add(Xx3UnencodedString.hashUnencodedString(path));
            containsResources = true;
            if (!path.endsWith(".svg") && !path.endsWith(".png") && !path.endsWith(".xml")) {
              dirCandidates.addLast(file);
            }
          }
        }

        if (containsClasses || containsResources) {
          String relativeResourcePath = getRelativeResourcePath(dir.toString(), rootDirAbsolutePathLength);
          if (containsClasses) {
            context.addClassPackage(relativeResourcePath);
          }
          if (containsResources) {
            context.addResourcePackage(relativeResourcePath);
          }
        }
      }
      catch (NoSuchFileException | NotDirectoryException ignore) {
      }
      catch (IOException e) {
        //noinspection UseOfSystemOutOrSystemErr
        e.printStackTrace(System.err);
      }
    }
  }

  private static @NotNull String getRelativeResourcePath(@NotNull String path, int startPathLength) {
    String relativePath = path.substring(startPathLength).replace(File.separatorChar, '/');
    return relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
  }

  @Override
  public @Nullable Resource getResource(@NotNull String name) {
    Path file = path.resolve(name);
    return Files.exists(file) ? new FileResource(file) : null;
  }

  @Override
  public @Nullable Class<?> findClass(String fileName, String className, ClassPath.ClassDataConsumer classConsumer) throws IOException {
    Path file = path.resolve(fileName);
    byte[] data;
    try {
      data = Files.readAllBytes(file);
    }
    catch (NoSuchFileException e) {
      return null;
    }
    return classConsumer.consumeClassData(className, data, this);
  }

  private static @Nullable LoaderData readFromIndex(Path index) {
    long started = System.nanoTime();
    boolean isOk = false;
    short version = -1;
    try (SeekableByteChannel channel = Files.newByteChannel(index, READ_OPTIONS)) {
      ByteBuffer buffer = DirectByteBufferPool.DEFAULT_POOL.allocate((int)channel.size());
      try {
        do {
          channel.read(buffer);
        }
        while (buffer.hasRemaining());
        buffer.flip();

        // little endian - native order for Intel and Apple ARM
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        version = buffer.getShort();
        if (version == indexFileVersion) {
          long[] classPackageHashes = new long[buffer.getInt()];
          long[] resourcePackageHashes = new long[buffer.getInt()];
          LongBuffer longBuffer = buffer.asLongBuffer();
          longBuffer.get(classPackageHashes);
          longBuffer.get(resourcePackageHashes);
          buffer.position(buffer.position() + (longBuffer.position() * Long.BYTES));
          LoaderData loaderData = new LoaderData(resourcePackageHashes, classPackageHashes, new NameFilter(new Xor16(buffer)));
          isOk = true;
          return loaderData;
        }
      }
      finally {
        DirectByteBufferPool.DEFAULT_POOL.release(buffer);
      }
    }
    catch (NoSuchFileException ignore) {
      isOk = true;
    }
    catch (Exception e) {
      //noinspection UseOfSystemOutOrSystemErr
      System.err.println("Cannot read classpath index (version=" + version + ", module=" + index.getParent().getFileName() + ")");
      //noinspection CallToPrintStackTrace
      e.printStackTrace();
    }
    finally {
      if (!isOk) {
        try {
          Files.deleteIfExists(index);
        }
        catch (IOException ignore) {
        }
      }
      totalReading.addAndGet(System.nanoTime() - started);
    }

    return null;
  }

  private static void saveIndex(@NotNull LoaderData data, @NotNull Path indexFile) throws IOException {
    long started = System.nanoTime();
    ByteBuffer buffer = DirectByteBufferPool.DEFAULT_POOL.allocate(Short.BYTES + data.approximateSizeInBytes());
    try {
      buffer.order(ByteOrder.LITTLE_ENDIAN);

      buffer.putShort(indexFileVersion);
      data.save(buffer);
      assert buffer.remaining() == 0;
      buffer.flip();
      try (SeekableByteChannel channel = Files.newByteChannel(indexFile, WRITE_OPTIONS)) {
        do {
          channel.write(buffer);
        }
        while (buffer.hasRemaining());
      }
    }
    finally {
      DirectByteBufferPool.DEFAULT_POOL.release(buffer);
      totalSaving.addAndGet(System.nanoTime() - started);
    }
  }

  private static @NotNull LoaderData buildData(@NotNull Path path, boolean isClassPathIndexEnabled) {
    Path indexFile = isClassPathIndexEnabled ? path.resolve("classpath.index") : null;
    LoaderData loaderData = indexFile == null ? null : readFromIndex(indexFile);

    int nsMsFactor = 1_000_000;
    int currentLoaders = totalLoaders.incrementAndGet();
    long currentScanningTime;
    if (loaderData == null) {
      long started = System.nanoTime();

      StrippedLongArrayList nameHashes = new StrippedLongArrayList();

      ClasspathCache.LoaderDataBuilder loaderDataBuilder = new ClasspathCache.LoaderDataBuilder();
      buildPackageAndNameCache(path, loaderDataBuilder, nameHashes);
      loaderData = new LoaderData(loaderDataBuilder.resourcePackageHashes.toArray(),
                                  loaderDataBuilder.classPackageHashes.toArray(),
                                  new NameFilter(Xor16.construct(nameHashes.elements(), 0, nameHashes.size())));
      long doneNanos = System.nanoTime() - started;
      currentScanningTime = totalScanning.addAndGet(doneNanos);
      if (doFsActivityLogging) {
        //noinspection UseOfSystemOutOrSystemErr
        System.out.println("Scanned: " + path + " for " + (doneNanos / nsMsFactor) + "ms");
      }

      if (isClassPathIndexEnabled) {
        try {
          Path tempFile = indexFile.getParent().resolve("classpath.index.tmp");
          saveIndex(loaderData, tempFile);
          try {
            Files.move(tempFile, indexFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
          }
          catch (AtomicMoveNotSupportedException e) {
            Files.move(tempFile, indexFile, StandardCopyOption.REPLACE_EXISTING);
          }
        }
        catch (IOException e) {
          //noinspection CallToPrintStackTrace
          e.printStackTrace();
        }
      }
    }
    else {
      currentScanningTime = totalScanning.get();
    }

    if (doFsActivityLogging) {
      //noinspection UseOfSystemOutOrSystemErr
      System.out.println("Scanning: " + (currentScanningTime / nsMsFactor) + "ms" +
                         ", loading: " + (totalReading.get() / nsMsFactor) + "ms for " + currentLoaders + " loaders");
    }
    return loaderData;
  }

  private static final class FileResource implements Resource {
    private URL url;
    private final Path file;

    FileResource(@NotNull Path file) {
      this.file = file;
    }

    @Override
    public @NotNull URL getURL() {
      URL result = this.url;
      if (result == null) {
        try {
          result = file.toUri().toURL();
        }
        catch (MalformedURLException e) {
          throw new RuntimeException(e);
        }
        url = result;
      }
      return result;
    }

    @Override
    public @NotNull InputStream getInputStream() throws IOException {
      return new BufferedInputStream(Files.newInputStream(file), 32_000);
    }

    @Override
    public byte @NotNull [] getBytes() throws IOException {
      return Files.readAllBytes(file);
    }

    @Override
    public String toString() {
      return file.toString();
    }
  }

  @Override
  public String toString() {
    return "FileLoader(path=" + path + ')';
  }

  @Override
  public boolean containsName(String name) {
    return nameFilter.test(name);
  }

  private static final class LoaderData implements ClasspathCache.IndexRegistrar {
    private final long[] resourcePackageHashes;
    private final long[] classPackageHashes;
    private final @NotNull NameFilter nameFilter;

    LoaderData(long[] resourcePackageHashes, long[] classPackageHashes, @NotNull NameFilter nameFilter) {
      this.resourcePackageHashes = resourcePackageHashes;
      this.classPackageHashes = classPackageHashes;
      this.nameFilter = nameFilter;
    }

    @Override
    public int classPackageCount() {
      return classPackageHashes.length;
    }

    @Override
    public int resourcePackageCount() {
      return resourcePackageHashes.length;
    }

    @Override
    public @NotNull Predicate<String> getNameFilter() {
      return nameFilter;
    }

    @Override
    public long[] classPackages() {
      return classPackageHashes;
    }

    @Override
    public long[] resourcePackages() {
      return resourcePackageHashes;
    }

    int approximateSizeInBytes() {
      return Integer.BYTES * 2 +
             classPackageHashes.length * Long.BYTES +
             resourcePackageHashes.length * Long.BYTES +
             nameFilter.filter.sizeInBytes();
    }

    void save(@NotNull ByteBuffer buffer) {
      buffer.putInt(classPackageHashes.length);
      buffer.putInt(resourcePackageHashes.length);
      LongBuffer longBuffer = buffer.asLongBuffer();
      longBuffer.put(classPackageHashes);
      longBuffer.put(resourcePackageHashes);
      buffer.position(buffer.position() + longBuffer.position() * Long.BYTES);
      nameFilter.filter.write(buffer);
    }
  }

  private static final class NameFilter implements Predicate<String> {
    final Xor16 filter;

    NameFilter(Xor16 filter) {
      this.filter = filter;
    }

    @Override
    public boolean test(String name) {
      if (name.isEmpty()) {
        return true;
      }

      int lastIndex = name.length() - 1;
      int end = name.charAt(lastIndex) == '/' ? lastIndex : name.length();
      return filter.mightContain(Xx3UnencodedString.hashUnencodedStringRange(name, 0, end));
    }
  }
}


text:
//
//  GreystripeBannerCustomEvent.h
//  MoPub
//
//  Copyright (c) 2012 MoPub, Inc. All rights reserved.
//

#import "MPBannerCustomEvent.h"
#import "GSAdDelegate.h"

/*
 * Compatible with version 4.2.1 of the Greystripe SDK.
 */

@interface GreystripeBannerCustomEvent : MPBannerCustomEvent <GSAdDelegate>

@end


text:
module Gdshowsdb
  class SongRefDBExtractor
    def self.from_db
      raw_db = SongRef.order(:name)
      Gdshowsdb::SongRefDBExtractor.new(raw_db)
    end

    def initialize(song_ref_list)
      @song_ref_list = song_ref_list
    end

    def extract
      @song_ref_list.map do |song_ref|
        song_ref.attributes.convert_to_sym.reject {|k,v| k == :slug || k == :song_occurences_count }
      end
    end
  end
end


text:
#include <Uefi/UefiBaseType.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/PcdLib.h>
#include <Library/IoLib.h>
#include <Library/CbParseLib.h>

#include <IndustryStandard/Acpi.h>

#include "Coreboot.h"

/**
  Convert a packed value from cbuint64 to a UINT64 value.

  @param  val      The pointer to packed data.

  @return          the UNIT64 value after convertion.

**/
UINT64
cb_unpack64 (
  IN struct cbuint64 val
  )
{
  return LShiftU64 (val.hi, 32) | val.lo;
}

/**
  Returns the sum of all elements in a buffer of 16-bit values.  During
  calculation, the carry bits are also been added.

  @param  Buffer      The pointer to the buffer to carry out the sum operation.
  @param  Length      The size, in bytes, of Buffer.

  @return Sum         The sum of Buffer with carry bits included during additions.

**/
UINT16
CbCheckSum16 (
  IN UINT16   *Buffer,
  IN UINTN    Length
  )
{
  UINT32 Sum, TmpValue;
  UINTN  Idx;
  UINT8  *TmpPtr;

  Sum = 0;
  TmpPtr = (UINT8 *)Buffer;
  for(Idx = 0; Idx < Length; Idx++) {
    TmpValue  = TmpPtr[Idx];
    if (Idx % 2 == 1) {
      TmpValue <<= 8;
    }

    Sum += TmpValue;

    // Wrap
    if (Sum >= 0x10000) {
      Sum = (Sum + (Sum >> 16)) & 0xFFFF;
    }
  }

  return (UINT16)((~Sum) & 0xFFFF);
}

/**
  Find coreboot record with given Tag from the memory Start in 4096
  bytes range.

  @param  Start              The start memory to be searched in
  @param  Tag                The tag id to be found

  @retval NULL              The Tag is not found.
  @retval Others            The poiter to the record found.

**/
VOID *
EFIAPI
FindCbTag (
  IN  VOID     *Start,
  IN  UINT32   Tag
  )
{
  struct cb_header   *Header;
  struct cb_record   *Record;
  UINT8              *TmpPtr;
  UINT8              *TagPtr;
  UINTN              Idx;
  UINT16             CheckSum;

  Header = NULL;
  TmpPtr = (UINT8 *)Start;
  for (Idx = 0; Idx < 4096; Idx += 16, TmpPtr += 16) {
    Header = (struct cb_header *)TmpPtr;
    if (Header->signature == CB_HEADER_SIGNATURE) {
      break;
    }
  }

  if (Idx >= 4096) {
    return NULL;
  }

  if ((Header == NULL) || (Header->table_bytes == 0)) {
    return NULL;
  }

  //
  // Check the checksum of the coreboot table header
  //
  CheckSum = CbCheckSum16 ((UINT16 *)Header, sizeof (*Header));
  if (CheckSum != 0) {
    DEBUG ((EFI_D_ERROR, "Invalid coreboot table header checksum\n"));
    return NULL;
  }

  CheckSum = CbCheckSum16 ((UINT16 *)(TmpPtr + sizeof (*Header)), Header->table_bytes);
  if (CheckSum != Header->table_checksum) {
    DEBUG ((EFI_D_ERROR, "Incorrect checksum of all the coreboot table entries\n"));
    return NULL;
  }

  TagPtr = NULL;
  TmpPtr += Header->header_bytes;
  for (Idx = 0; Idx < Header->table_entries; Idx++) {
    Record = (struct cb_record *)TmpPtr;
    if (Record->tag == CB_TAG_FORWARD) {
      TmpPtr = (VOID *)(UINTN)((struct cb_forward *)(UINTN)Record)->forward;
      if (Tag == CB_TAG_FORWARD) {
        return TmpPtr;
      } else {
        return FindCbTag (TmpPtr, Tag);
      }
    }
    if (Record->tag == Tag) {
      TagPtr = TmpPtr;
      break;
    }
    TmpPtr += Record->size;
  }

  return TagPtr;
}

/**
  Find the given table with TableId from the given coreboot memory Root.

  @param  Root               The coreboot memory table to be searched in
  @param  TableId            Table id to be found
  @param  pMemTable          To save the base address of the memory table found
  @param  pMemTableSize      To save the size of memory table found

  @retval RETURN_SUCCESS            Successfully find out the memory table.
  @retval RETURN_INVALID_PARAMETER  Invalid input parameters.
  @retval RETURN_NOT_FOUND          Failed to find the memory table.

**/
RETURN_STATUS
EFIAPI
FindCbMemTable (
  IN  struct cbmem_root  *Root,
  IN  UINT32             TableId,
  OUT VOID               **pMemTable,
  OUT UINT32             *pMemTableSize
  )
{
  UINTN                Idx;
  BOOLEAN              IsImdEntry;
  struct cbmem_entry  *Entries;

  if ((Root == NULL) || (pMemTable == NULL)) {
    return RETURN_INVALID_PARAMETER;
  }
  //
  // Check if the entry is CBMEM or IMD
  // and handle them separately
  //
  Entries = Root->entries;
  if (Entries[0].magic == CBMEM_ENTRY_MAGIC) {
    IsImdEntry = FALSE;
  } else {
    Entries = (struct cbmem_entry *)((struct imd_root *)Root)->entries;
    if (Entries[0].magic == IMD_ENTRY_MAGIC) {
      IsImdEntry = TRUE;
    } else {
      return RETURN_NOT_FOUND;
    }
  }

  for (Idx = 0; Idx < Root->num_entries; Idx++) {
    if (Entries[Idx].id == TableId) {
      if (IsImdEntry) {
        *pMemTable = (VOID *) ((UINTN)Entries[Idx].start + (UINTN)Root);
      } else {
        *pMemTable = (VOID *) (UINTN)Entries[Idx].start;
      }
      if (pMemTableSize != NULL) {
        *pMemTableSize = Entries[Idx].size;
      }

      DEBUG ((EFI_D_INFO, "Find CbMemTable Id 0x%x, base %p, size 0x%x\n",
        TableId, *pMemTable, Entries[Idx].size));
      return RETURN_SUCCESS;
    }
  }

  return RETURN_NOT_FOUND;
}

/**
  Acquire the memory information from the coreboot table in memory.

  @param  MemInfoCallback     The callback routine
  @param  pParam              Pointer to the callback routine parameter

  @retval RETURN_SUCCESS     Successfully find out the memory information.
  @retval RETURN_NOT_FOUND   Failed to find the memory information.

**/
RETURN_STATUS
EFIAPI
CbParseMemoryInfo (
  IN  CB_MEM_INFO_CALLBACK  MemInfoCallback,
  IN  VOID                  *pParam
  )
{
  struct cb_memory         *rec;
  struct cb_memory_range   *Range;
  UINT64                   Start;
  UINT64                   Size;
  UINTN                    Index;

  //
  // Get the coreboot memory table
  //
  rec = (struct cb_memory *)FindCbTag (0, CB_TAG_MEMORY);
  if (rec == NULL) {
    rec = (struct cb_memory *)FindCbTag ((VOID *)(UINTN)PcdGet32 (PcdCbHeaderPointer), CB_TAG_MEMORY);
  }

  if (rec == NULL) {
    return RETURN_NOT_FOUND;
  }

  for (Index = 0; Index < MEM_RANGE_COUNT(rec); Index++) {
    Range = MEM_RANGE_PTR(rec, Index);
    Start = cb_unpack64(Range->start);
    Size = cb_unpack64(Range->size);
    DEBUG ((EFI_D_INFO, "%d. %016lx - %016lx [%02x]\n",
            Index, Start, Start + Size - 1, Range->type));

    MemInfoCallback (Start, Size, Range->type, pParam);
  }

  return RETURN_SUCCESS;
}

/**
  Acquire the coreboot memory table with the given table id

  @param  TableId            Table id to be searched
  @param  pMemTable          Pointer to the base address of the memory table
  @param  pMemTableSize      Pointer to the size of the memory table

  @retval RETURN_SUCCESS     Successfully find out the memory table.
  @retval RETURN_INVALID_PARAMETER  Invalid input parameters.
  @retval RETURN_NOT_FOUND   Failed to find the memory table.

**/
RETURN_STATUS
EFIAPI
CbParseCbMemTable (
  IN  UINT32     TableId,
  OUT VOID       **pMemTable,
  OUT UINT32     *pMemTableSize
  )
{
  struct cb_memory         *rec;
  struct cb_memory_range   *Range;
  UINT64                   Start;
  UINT64                   Size;
  UINTN                    Index;

  if (pMemTable == NULL) {
    return RETURN_INVALID_PARAMETER;
  }
  *pMemTable = NULL;

  //
  // Get the coreboot memory table
  //
  rec = (struct cb_memory *)FindCbTag (0, CB_TAG_MEMORY);
  if (rec == NULL) {
    rec = (struct cb_memory *)FindCbTag ((VOID *)(UINTN)PcdGet32 (PcdCbHeaderPointer), CB_TAG_MEMORY);
  }

  if (rec == NULL) {
    return RETURN_NOT_FOUND;
  }

  for (Index = 0; Index < MEM_RANGE_COUNT(rec); Index++) {
    Range = MEM_RANGE_PTR(rec, Index);
    Start = cb_unpack64(Range->start);
    Size = cb_unpack64(Range->size);

    if ((Range->type == CB_MEM_TABLE) && (Start > 0x1000)) {
      if (FindCbMemTable ((struct  cbmem_root *)(UINTN)(Start + Size - DYN_CBMEM_ALIGN_SIZE), TableId, pMemTable, pMemTableSize) == RETURN_SUCCESS)
        return RETURN_SUCCESS;
    }
  }

  return RETURN_NOT_FOUND;
}

/**
  Acquire the acpi table from coreboot

  @param  pMemTable          Pointer to the base address of the memory table
  @param  pMemTableSize      Pointer to the size of the memory table

  @retval RETURN_SUCCESS     Successfully find out the memory table.
  @retval RETURN_INVALID_PARAMETER  Invalid input parameters.
  @retval RETURN_NOT_FOUND   Failed to find the memory table.

**/
RETURN_STATUS
EFIAPI
CbParseAcpiTable (
  OUT VOID       **pMemTable,
  OUT UINT32     *pMemTableSize
  )
{
  return CbParseCbMemTable (SIGNATURE_32 ('I', 'P', 'C', 'A'), pMemTable, pMemTableSize);
}

/**
  Acquire the smbios table from coreboot

  @param  pMemTable          Pointer to the base address of the memory table
  @param  pMemTableSize      Pointer to the size of the memory table

  @retval RETURN_SUCCESS     Successfully find out the memory table.
  @retval RETURN_INVALID_PARAMETER  Invalid input parameters.
  @retval RETURN_NOT_FOUND   Failed to find the memory table.

**/
RETURN_STATUS
EFIAPI
CbParseSmbiosTable (
  OUT VOID       **pMemTable,
  OUT UINT32     *pMemTableSize
  )
{
  return CbParseCbMemTable (SIGNATURE_32 ('T', 'B', 'M', 'S'), pMemTable, pMemTableSize);
}

/**
  Find the required fadt information

  @param  pPmCtrlReg         Pointer to the address of power management control register
  @param  pPmTimerReg        Pointer to the address of power management timer register
  @param  pResetReg          Pointer to the address of system reset register
  @param  pResetValue        Pointer to the value to be writen to the system reset register
  @param  pPmEvtReg          Pointer to the address of power management event register
  @param  pPmGpeEnReg        Pointer to the address of power management GPE enable register

  @retval RETURN_SUCCESS     Successfully find out all the required fadt information.
  @retval RETURN_NOT_FOUND   Failed to find the fadt table.

**/
RETURN_STATUS
EFIAPI
CbParseFadtInfo (
  OUT UINTN      *pPmCtrlReg,
  OUT UINTN      *pPmTimerReg,
  OUT UINTN      *pResetReg,
  OUT UINTN      *pResetValue,
  OUT UINTN      *pPmEvtReg,
  OUT UINTN      *pPmGpeEnReg
  )
{
  EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER  *Rsdp;
  EFI_ACPI_DESCRIPTION_HEADER                   *Rsdt;
  UINT32                                        *Entry32;
  UINTN                                         Entry32Num;
  EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE     *Fadt;
  EFI_ACPI_DESCRIPTION_HEADER                   *Xsdt;
  UINT64                                        *Entry64;
  UINTN                                         Entry64Num;
  UINTN                                         Idx;
  RETURN_STATUS                                 Status;

  Rsdp = NULL;
  Status = RETURN_SUCCESS;

  Status = CbParseAcpiTable ((VOID **)&Rsdp, NULL);
  if (RETURN_ERROR(Status)) {
    return Status;
  }

  if (Rsdp == NULL) {
    return RETURN_NOT_FOUND;
  }

  DEBUG ((EFI_D_INFO, "Find Rsdp at %p\n", Rsdp));
  DEBUG ((EFI_D_INFO, "Find Rsdt 0x%x, Xsdt 0x%lx\n", Rsdp->RsdtAddress, Rsdp->XsdtAddress));

  //
  // Search Rsdt First
  //
  Rsdt     = (EFI_ACPI_DESCRIPTION_HEADER *)(UINTN)(Rsdp->RsdtAddress);
  if (Rsdt != NULL) {
    Entry32  = (UINT32 *)(Rsdt + 1);
    Entry32Num = (Rsdt->Length - sizeof(EFI_ACPI_DESCRIPTION_HEADER)) >> 2;
    for (Idx = 0; Idx < Entry32Num; Idx++) {
      if (*(UINT32 *)(UINTN)(Entry32[Idx]) == EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) {
        Fadt = (EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)(UINTN)(Entry32[Idx]);
        if (pPmCtrlReg != NULL) {
          *pPmCtrlReg = Fadt->Pm1aCntBlk;
        }
        DEBUG ((EFI_D_INFO, "PmCtrl Reg 0x%x\n", Fadt->Pm1aCntBlk));

        if (pPmTimerReg != NULL) {
          *pPmTimerReg = Fadt->PmTmrBlk;
        }
        DEBUG ((EFI_D_INFO, "PmTimer Reg 0x%x\n", Fadt->PmTmrBlk));

        if (pResetReg != NULL) {
          *pResetReg = (UINTN)Fadt->ResetReg.Address;
        }
        DEBUG ((EFI_D_INFO, "Reset Reg 0x%lx\n", Fadt->ResetReg.Address));

        if (pResetValue != NULL) {
          *pResetValue = Fadt->ResetValue;
        }
        DEBUG ((EFI_D_INFO, "Reset Value 0x%x\n", Fadt->ResetValue));

        if (pPmEvtReg != NULL) {
          *pPmEvtReg = Fadt->Pm1aEvtBlk;
          DEBUG ((EFI_D_INFO, "PmEvt Reg 0x%x\n", Fadt->Pm1aEvtBlk));
        }

        if (pPmGpeEnReg != NULL) {
          *pPmGpeEnReg = Fadt->Gpe0Blk + Fadt->Gpe0BlkLen / 2;
          DEBUG ((EFI_D_INFO, "PmGpeEn Reg 0x%x\n", *pPmGpeEnReg));
        }

        //
        // Verify values for proper operation
        //
        ASSERT(Fadt->Pm1aCntBlk != 0);
        ASSERT(Fadt->PmTmrBlk != 0);
        ASSERT(Fadt->ResetReg.Address != 0);
        ASSERT(Fadt->Pm1aEvtBlk != 0);
        ASSERT(Fadt->Gpe0Blk != 0);

        DEBUG_CODE_BEGIN ();
          BOOLEAN    SciEnabled;

          //
          // Check the consistency of SCI enabling
          //

          //
          // Get SCI_EN value
          //
          if (Fadt->Pm1CntLen == 4) {
            SciEnabled = (IoRead32 (Fadt->Pm1aCntBlk) & BIT0)? TRUE : FALSE;
          } else {
            //
            // if (Pm1CntLen == 2), use 16 bit IO read;
            // if (Pm1CntLen != 2 && Pm1CntLen != 4), use 16 bit IO read as a fallback
            //
            SciEnabled = (IoRead16 (Fadt->Pm1aCntBlk) & BIT0)? TRUE : FALSE;
          }

          if (!(Fadt->Flags & EFI_ACPI_5_0_HW_REDUCED_ACPI) &&
              (Fadt->SmiCmd == 0) &&
              !SciEnabled) {
            //
            // The ACPI enabling status is inconsistent: SCI is not enabled but ACPI
            // table does not provide a means to enable it through FADT->SmiCmd
            //
            DEBUG ((DEBUG_ERROR, "ERROR: The ACPI enabling status is inconsistent: SCI is not"
              " enabled but the ACPI table does not provide a means to enable it through FADT->SmiCmd."
              " This may cause issues in OS.\n"));
            ASSERT (FALSE);
          }
        DEBUG_CODE_END ();
        return RETURN_SUCCESS;
      }
    }
  }

  //
  // Search Xsdt Second
  //
  Xsdt     = (EFI_ACPI_DESCRIPTION_HEADER *)(UINTN)(Rsdp->XsdtAddress);
  if (Xsdt != NULL) {
    Entry64  = (UINT64 *)(Xsdt + 1);
    Entry64Num = (Xsdt->Length - sizeof(EFI_ACPI_DESCRIPTION_HEADER)) >> 3;
    for (Idx = 0; Idx < Entry64Num; Idx++) {
      if (*(UINT32 *)(UINTN)(Entry64[Idx]) == EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) {
        Fadt = (EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)(UINTN)(Entry64[Idx]);
        if (pPmCtrlReg)
          *pPmCtrlReg = Fadt->Pm1aCntBlk;
        DEBUG ((EFI_D_ERROR, "PmCtrl Reg 0x%x\n", Fadt->Pm1aCntBlk));

        if (pPmTimerReg)
          *pPmTimerReg = Fadt->PmTmrBlk;
        DEBUG ((EFI_D_ERROR, "PmTimer Reg 0x%x\n", Fadt->PmTmrBlk));

        if (pResetReg)
          *pResetReg = (UINTN)Fadt->ResetReg.Address;
        DEBUG ((EFI_D_ERROR, "Reset Reg 0x%lx\n", Fadt->ResetReg.Address));

        if (pResetValue)
          *pResetValue = Fadt->ResetValue;
        DEBUG ((EFI_D_ERROR, "Reset Value 0x%x\n", Fadt->ResetValue));

        if (pPmEvtReg != NULL) {
          *pPmEvtReg = Fadt->Pm1aEvtBlk;
           DEBUG ((EFI_D_INFO, "PmEvt Reg 0x%x\n", Fadt->Pm1aEvtBlk));
        }

        if (pPmGpeEnReg != NULL) {
          *pPmGpeEnReg = Fadt->Gpe0Blk + Fadt->Gpe0BlkLen / 2;
          DEBUG ((EFI_D_INFO, "PmGpeEn Reg 0x%x\n", *pPmGpeEnReg));
        }
        return RETURN_SUCCESS;
      }
    }
  }

  return RETURN_NOT_FOUND;
}

/**
  Find the serial port information

  @param  pRegBase           Pointer to the base address of serial port registers
  @param  pRegAccessType     Pointer to the access type of serial port registers
  @param  pRegWidth          Pointer to the register width in bytes
  @param  pBaudrate          Pointer to the serial port baudrate
  @param  pInputHertz        Pointer to the input clock frequency
  @param  pUartPciAddr       Pointer to the UART PCI bus, dev and func address

  @retval RETURN_SUCCESS     Successfully find the serial port information.
  @retval RETURN_NOT_FOUND   Failed to find the serial port information .

**/
RETURN_STATUS
EFIAPI
CbParseSerialInfo (
  OUT UINT32      *pRegBase,
  OUT UINT32      *pRegAccessType,
  OUT UINT32      *pRegWidth,
  OUT UINT32      *pBaudrate,
  OUT UINT32      *pInputHertz,
  OUT UINT32      *pUartPciAddr
  )
{
  struct cb_serial    *CbSerial;

  CbSerial = FindCbTag (0, CB_TAG_SERIAL);
  if (CbSerial == NULL) {
    CbSerial = FindCbTag ((VOID *)(UINTN)PcdGet32 (PcdCbHeaderPointer), CB_TAG_SERIAL);
  }

  if (CbSerial == NULL) {
    return RETURN_NOT_FOUND;
  }

  if (pRegBase != NULL) {
    *pRegBase = CbSerial->baseaddr;
  }

  if (pRegWidth != NULL) {
    *pRegWidth = CbSerial->regwidth;
  }

  if (pRegAccessType != NULL) {
    *pRegAccessType = CbSerial->type;
  }

  if (pBaudrate != NULL) {
    *pBaudrate = CbSerial->baud;
  }

  if (pInputHertz != NULL) {
    *pInputHertz = CbSerial->input_hertz;
  }

  if (pUartPciAddr != NULL) {
    *pUartPciAddr = CbSerial->uart_pci_addr;
  }

  return RETURN_SUCCESS;
}

/**
  Search for the coreboot table header

  @param  Level              Level of the search depth
  @param  HeaderPtr          Pointer to the pointer of coreboot table header

  @retval RETURN_SUCCESS     Successfully find the coreboot table header .
  @retval RETURN_NOT_FOUND   Failed to find the coreboot table header .

**/
RETURN_STATUS
EFIAPI
CbParseGetCbHeader (
  IN  UINTN  Level,
  OUT VOID   **HeaderPtr
  )
{
  UINTN Index;
  VOID  *TempPtr;

  if (HeaderPtr == NULL) {
    return RETURN_NOT_FOUND;
  }

  TempPtr = NULL;
  for (Index = 0; Index < Level; Index++) {
    TempPtr = FindCbTag (TempPtr, CB_TAG_FORWARD);
    if (TempPtr == NULL) {
      break;
    }
  }

  if ((Index >= Level) && (TempPtr != NULL)) {
    *HeaderPtr = TempPtr;
    return RETURN_SUCCESS;
  }

  return RETURN_NOT_FOUND;
}

/**
  Find the video frame buffer information

  @param  pFbInfo            Pointer to the FRAME_BUFFER_INFO structure

  @retval RETURN_SUCCESS     Successfully find the video frame buffer information.
  @retval RETURN_NOT_FOUND   Failed to find the video frame buffer information .

**/
RETURN_STATUS
EFIAPI
CbParseFbInfo (
  OUT FRAME_BUFFER_INFO       *pFbInfo
  )
{
  struct cb_framebuffer       *CbFbRec;

  if (pFbInfo == NULL) {
    return RETURN_INVALID_PARAMETER;
  }

  CbFbRec = FindCbTag (0, CB_TAG_FRAMEBUFFER);
  if (CbFbRec == NULL) {
    CbFbRec = FindCbTag ((VOID *)(UINTN)PcdGet32 (PcdCbHeaderPointer), CB_TAG_FRAMEBUFFER);
  }

  if (CbFbRec == NULL) {
    return RETURN_NOT_FOUND;
  }

  DEBUG ((EFI_D_INFO, "Found coreboot video frame buffer information\n"));
  DEBUG ((EFI_D_INFO, "physical_address: 0x%lx\n", CbFbRec->physical_address));
  DEBUG ((EFI_D_INFO, "x_resolution: 0x%x\n", CbFbRec->x_resolution));
  DEBUG ((EFI_D_INFO, "y_resolution: 0x%x\n", CbFbRec->y_resolution));
  DEBUG ((EFI_D_INFO, "bits_per_pixel: 0x%x\n", CbFbRec->bits_per_pixel));
  DEBUG ((EFI_D_INFO, "bytes_per_line: 0x%x\n", CbFbRec->bytes_per_line));

  DEBUG ((EFI_D_INFO, "red_mask_size: 0x%x\n", CbFbRec->red_mask_size));
  DEBUG ((EFI_D_INFO, "red_mask_pos: 0x%x\n", CbFbRec->red_mask_pos));
  DEBUG ((EFI_D_INFO, "green_mask_size: 0x%x\n", CbFbRec->green_mask_size));
  DEBUG ((EFI_D_INFO, "green_mask_pos: 0x%x\n", CbFbRec->green_mask_pos));
  DEBUG ((EFI_D_INFO, "blue_mask_size: 0x%x\n", CbFbRec->blue_mask_size));
  DEBUG ((EFI_D_INFO, "blue_mask_pos: 0x%x\n", CbFbRec->blue_mask_pos));
  DEBUG ((EFI_D_INFO, "reserved_mask_size: 0x%x\n", CbFbRec->reserved_mask_size));
  DEBUG ((EFI_D_INFO, "reserved_mask_pos: 0x%x\n", CbFbRec->reserved_mask_pos));

  pFbInfo->LinearFrameBuffer    = CbFbRec->physical_address;
  pFbInfo->HorizontalResolution = CbFbRec->x_resolution;
  pFbInfo->VerticalResolution   = CbFbRec->y_resolution;
  pFbInfo->BitsPerPixel         = CbFbRec->bits_per_pixel;
  pFbInfo->BytesPerScanLine     = (UINT16)CbFbRec->bytes_per_line;
  pFbInfo->Red.Mask             = (1 << CbFbRec->red_mask_size) - 1;
  pFbInfo->Red.Position         = CbFbRec->red_mask_pos;
  pFbInfo->Green.Mask           = (1 << CbFbRec->green_mask_size) - 1;
  pFbInfo->Green.Position       = CbFbRec->green_mask_pos;
  pFbInfo->Blue.Mask            = (1 << CbFbRec->blue_mask_size) - 1;
  pFbInfo->Blue.Position        = CbFbRec->blue_mask_pos;
  pFbInfo->Reserved.Mask        = (1 << CbFbRec->reserved_mask_size) - 1;
  pFbInfo->Reserved.Position    = CbFbRec->reserved_mask_pos;

  return RETURN_SUCCESS;
}


text:
package org.wallride.autoconfigure;

import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration;
import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templateresolver.TemplateResolver;

import javax.inject.Inject;
import java.util.HashSet;
import java.util.Set;

@Configuration
public class WallRideMailConfiguration extends MailSenderAutoConfiguration {

	@Inject
	private WallRideResourceResourceResolver wallRideResourceResourceResolver;

	@Inject
	private WallRideThymeleafDialect wallRideThymeleafDialect;

	@Inject
	private Environment environment;

	@Inject
	private ThymeleafProperties properties;

	@Bean(name = "emailTemplateResolver")
	public TemplateResolver emailTemplateResolver() {
		TemplateResolver resolver = new TemplateResolver();
		resolver.setResourceResolver(wallRideResourceResourceResolver);
		resolver.setPrefix(environment.getRequiredProperty("spring.thymeleaf.prefix.mail"));
		resolver.setSuffix(this.properties.getSuffix());
		resolver.setTemplateMode(this.properties.getMode());
		resolver.setCharacterEncoding(this.properties.getEncoding().name());
		resolver.setCacheable(this.properties.isCache());
		resolver.setOrder(1);
		return resolver;
	}

	@Bean(name = "emailTemplateEngine")
	public SpringTemplateEngine emailTemplateEngine() {
		SpringTemplateEngine engine = new SpringTemplateEngine();
		Set<TemplateResolver> resolvers = new HashSet<>();
		resolvers.add(emailTemplateResolver());
		engine.setTemplateResolvers(resolvers);

		Set<IDialect> dialects = new HashSet<>();
		dialects.add(wallRideThymeleafDialect);
		engine.setAdditionalDialects(dialects);
		return engine;
	}
}


text:
import { applyStyleWhenSettingIsTrue } from '../module-utils'
import styles from './styles'

export default {
  defineSettings: () => ({
    'sideMenu.fixPosition': {
      defaultValue: false
    }
  }),

  runBeforeDom () {
    applyStyleWhenSettingIsTrue('sideMenu.fixPosition', styles)
  }
}


text:
package com.marshalchen.common.demoofui.sampleModules;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.marshalchen.common.commonUtils.basicUtils.HandlerUtils;
import  com.nineoldandroids.animation.Animator;
import  com.nineoldandroids.animation.ObjectAnimator;
import  com.nineoldandroids.animation.ValueAnimator;
import com.marshalchen.common.ui.HomeasUpActionbarActivity;
import com.marshalchen.common.demoofui.R;
import com.marshalchen.common.uimodule.simplemodule.HoloCircularProgressBar;

/**
 * Created by cym on 14-6-26.
 */
public class CircularBarActivity extends HomeasUpActionbarActivity {
    //    @InjectView(R.id.photoView)
//    PhotoView photoView;
    @InjectView(R.id.circularProgressBar)
    HoloCircularProgressBar circularProgressBar;
    private ObjectAnimator mProgressBarAnimator;
    protected boolean mAnimationHasEnded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.circular_progress_bar_activity);
        ButterKnife.inject(this);
        if (mProgressBarAnimator != null) {
            mProgressBarAnimator.cancel();
        }
        animate(circularProgressBar, null, 0f, 1000);
        circularProgressBar.setMarkerProgress(0f);
        HandlerUtils.sendMessageHandler(tooneAnimateHandler, 0, 500);
        HandlerUtils.sendMessageHandler(autoAnimateHandler, 0, 3500);
    }

    Handler tooneAnimateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            animate(circularProgressBar, null, 1f, 1000);
            circularProgressBar.setMarkerProgress(1f);
            circularProgressBar.setProgressColor(Color.CYAN);
        }
    };

    Handler autoAnimateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            animate(circularProgressBar, new Animator.AnimatorListener() {

                @Override
                public void onAnimationCancel(final Animator animation) {
                    animation.end();
                }

                @Override
                public void onAnimationEnd(final Animator animation) {
                    if (!mAnimationHasEnded) {
                        animate(circularProgressBar, this);
                    } else {
                        mAnimationHasEnded = false;
                    }
                }

                @Override
                public void onAnimationRepeat(final Animator animation) {
                }

                @Override
                public void onAnimationStart(final Animator animation) {
                }
            });
        }
    };

    private void animate(final HoloCircularProgressBar progressBar, final Animator.AnimatorListener listener) {
        final float progress = (float) (Math.random() * 2);
        int duration = 3000;
        animate(progressBar, listener, progress, duration);
    }

    private void animate(final HoloCircularProgressBar progressBar, final Animator.AnimatorListener listener,
                         final float progress, final int duration) {

        mProgressBarAnimator = ObjectAnimator.ofFloat(progressBar, "progress", progress);
        mProgressBarAnimator.setDuration(duration);

        mProgressBarAnimator.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationCancel(final Animator animation) {
            }

            @Override
            public void onAnimationEnd(final Animator animation) {
                progressBar.setProgress(progress);
            }

            @Override
            public void onAnimationRepeat(final Animator animation) {
            }

            @Override
            public void onAnimationStart(final Animator animation) {
            }
        });
        if (listener != null) {
            mProgressBarAnimator.addListener(listener);
        }
        mProgressBarAnimator.reverse();
        mProgressBarAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(final ValueAnimator animation) {
                progressBar.setProgress((Float) animation.getAnimatedValue());
            }
        });
        progressBar.setMarkerProgress(progress);
        mProgressBarAnimator.start();
    }

}


text:
set -e
THIS_DIR=$(dirname "${BASH_SOURCE[0]}")
COMMON_NAME=${COMMON_NAME:-"stratum.local"}

mkdir -p "$THIS_DIR/certs"
rm -rf "$THIS_DIR/certs/*"

SERVER_CONF_FILE="$(mktemp)"

echo "[ req ]
default_bits           = 2048
distinguished_name     = stratum
prompt                 = no

[ stratum ]
C                      = US
ST                     = CA
L                      = Menlo Park
O                      = Open Networking Foundation
OU                     = Stratum
CN                     = $COMMON_NAME
" > "$SERVER_CONF_FILE"

# Generate Private keys and certificates for CA
openssl genrsa -out "$THIS_DIR/certs/ca.key" 2048
openssl req -x509 -nodes -new -config "$THIS_DIR/ca.conf" -key "$THIS_DIR/certs/ca.key" \
                  -days 365 -out "$THIS_DIR/certs/ca.crt"

# Generate Private keys and certificate signing request(CSR) for Stratum gRPC server
openssl genrsa -out "$THIS_DIR/certs/stratum.key" 2048
openssl req -new -config "$SERVER_CONF_FILE" -key "$THIS_DIR/certs/stratum.key" -out "$THIS_DIR/certs/stratum.csr"

# Sing a certificate for Stratum with CA
openssl x509 -req -in "$THIS_DIR/certs/stratum.csr" -CA "$THIS_DIR/certs/ca.crt" \
             -CAkey "$THIS_DIR/certs/ca.key" -CAcreateserial \
             -out "$THIS_DIR/certs/stratum.crt" -days 30

# (Optional) Generate Private keys and certificate for gRPC client
openssl genrsa -out "$THIS_DIR/certs/client.key" 2048
openssl req -new -config "$THIS_DIR/grpc-client.conf" -key "$THIS_DIR/certs/client.key" -out "$THIS_DIR/certs/client.csr"
openssl x509 -req -in "$THIS_DIR/certs/client.csr" -CA "$THIS_DIR/certs/ca.crt" \
             -CAkey "$THIS_DIR/certs/ca.key" -CAcreateserial \
             -out "$THIS_DIR/certs/client.crt" -days 30

# Cleanup
rm "$SERVER_CONF_FILE"


text:
<?php namespace Menthol\Flexible;

use AspectMock\Test as am;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Facade;
use Mockery as m;

function date()
{
    return ProxyTest::$functions->date();
}

class ProxyTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var \Mockery\Mock
     */
    private $proxy;

    /**
     * @var \Mockery\Mock
     */
    private $model;

    /**
     * @var \Mockery\Mock
     */
    private $index;

    /**
     * @var \Mockery\Mock
     */
    private $client;

    /**
     * @var \Mockery\Mock
     */
    public static $functions;

    protected function setUp()
    {
        parent::setUp();

        self::$functions = m::mock();

        $this->index = m::mock('Menthol\Flexible\Index');
        $this->model = m::mock('Husband')->makePartial();
        $this->client = m::mock('Elasticsearch\Client');

        $this->model->shouldReceive('getTable')
            ->once()
            ->andReturn('Husbands');

        Facade::clearResolvedInstances();
        App::shouldReceive('make')
            ->with('Elasticsearch')
            ->once()
            ->andReturn($this->client);

        App::shouldReceive('make')
            ->with('menthol.flexible.index', m::type('array'))
            ->once()
            ->andReturn($this->index);

        $this->proxy = new Proxy($this->model);

        self::$functions->shouldReceive('date')->andReturn('9999');
    }

    protected function tearDown()
    {
        m::close();
        am::clean();
    }

    /**
     * @test
     */
    public function it_can_get_config()
    {
        $this->assertEquals([
            'model' => $this->model,
            'type' => 'Husband',
            'client' => $this->client,
            'index' => $this->index,
            'autocomplete' => ['name', 'wife.name'],
            'suggest' => ['name'],
            'text_start' => ['name', 'wife.children.name'],
            'text_middle' => ['name', 'wife.children.name'],
            'text_end' => ['name', 'wife.children.name'],
            'word_start' => ['name', 'wife.children.name'],
            'word_middle' => ['name', 'wife.children.name'],
            'word_end' => ['name', 'wife.children.name']
        ],
            $this->proxy->getConfig());
    }

    /**
     * @test
     */
    public function it_can_get_model()
    {
        $this->assertEquals($this->model, $this->proxy->getModel());
    }

    /**
     * @test
     */
    public function it_can_get_index()
    {
        $this->assertEquals($this->index, $this->proxy->getIndex());
    }

    /**
     * @test
     */
    public function it_can_get_type()
    {
        $this->assertEquals('Husband', $this->proxy->getType());
    }

    /**
     * @test
     */
    public function it_can_get_client()
    {
        $this->assertEquals($this->client, $this->proxy->getClient());
    }

    /**
     * @test
     */
    public function it_can_search()
    {
        /**
         *
         * Set
         *
         */
        $query = m::mock('Menthol\Flexible\Query');

        /**
         *
         * Expectation
         *
         */
        $query->shouldReceive('execute')->andReturn('result');

        App::shouldReceive('make')
            ->with('menthol.flexible.query', ['proxy' => $this->proxy, 'term' => '*', 'options' => ['option']])
            ->once()
            ->andReturn($query);

        /**
         *
         * Assertion
         *
         */
        $result = $this->proxy->search('*', ['option']);

        $this->assertEquals('result', $result);
    }

    /**
     * @test
     */
    public function it_can_search_with_a_query()
    {
        /**
         *
         * Set
         *
         */
        $queryMock = m::mock('Menthol\Flexible\Query');

        $query['index'] = 'my_index';
        $query['type'] = 'my_type';
        $query['body']['query']['match']['testField'] = 'abc';

        /**
         *
         * Expectation
         *
         */
        $queryMock->shouldReceive('execute')->andReturn('result');

        App::shouldReceive('make')
            ->with('menthol.flexible.query', [
                'proxy' => $this->proxy,
                'term' => null,
                'options' => array_merge(['query' => $query], ['option'])])
            ->once()
            ->andReturn($queryMock);

        /**
         *
         * Assertion
         *
         */
        $result = $this->proxy->searchByQuery($query, ['option']);

        $this->assertEquals('result', $result);
    }

    /**
     * @test
     */
    public function it_can_search_for_a_single_document()
    {
        /**
         *
         * Set
         *
         */
        $query['index'] = 'my_index';
        $query['type'] = 'my_type';
        $query['id'] = 'abc';

        /**
         *
         * Expectation
         *
         */
        $this->index->shouldReceive('getName')->andReturn('index');
        $this->client->shouldReceive('get')->andReturn(['hit']);

        App::shouldReceive('make')
            ->with('menthol.flexible.response.result', ['hit'])
            ->once()
            ->andReturn('result');

        /**
         *
         * Assertion
         *
         */
        $result = $this->proxy->searchById('abc');

        $this->assertEquals('result', $result);
    }

    /**
     * @test
     */
    public function it_can_reindex_when_alias_does_not_exist()
    {
        /**
         *
         * Set
         *
         */
        $indexDouble = am::double('Menthol\Flexible\Index', ['refresh' => null, 'clean' => null, 'updateAliases' => null]);
        $indexMock = m::mock('Menthol\Flexible\Index');

        /**
         *
         * Expectation
         *
         */
        $this->index->shouldReceive('getName')->andReturn('Husband');
        $this->index->shouldReceive('exists')->once()->andReturn(true);
        $this->index->shouldReceive('delete')->once()->andReturn();

        App::shouldReceive('make')
            ->with('menthol.flexible.index', ['name' => 'Husband_9999', 'proxy' => $this->proxy])
            ->andReturn($indexMock);

        $indexMock->shouldReceive('create')->once()->andReturn();
        $indexMock->shouldReceive('aliasExists')->once()->andReturn(false);
        $indexMock->shouldReceive('import')->andReturn();

        /**
         *
         * Assertion
         *
         */
        $this->proxy->reindex();

        $indexDouble->verifyInvoked('refresh', 'Husband');
        $indexDouble->verifyInvoked('clean', 'Husband');
    }

    /**
     * @test
     */
    public function it_can_reindex_when_alias_exists()
    {
        /**
         *
         * Set
         *
         */
        $indexDouble = am::double('Menthol\Flexible\Index', [
            'refresh' => null,
            'clean' => null,
            'updateAliases' => null,
            'getAlias' => ['mockIndex' => 'aliases']
        ]);
        $indexMock = m::mock('Menthol\Flexible\Index');

        $operations[] = [
            'add' => [
                'alias' => 'Husband',
                'index' => 'Husband_9999'
            ],
            'remove' => [
                'alias' => 'Husband',
                'index' => 'mockIndex'
            ]
        ];

        $actions[] = ['actions' => $operations];
        $test = $this;

        /**
         *
         * Expectation
         *
         */
        $this->index->shouldReceive('getName')->andReturn('Husband');

        $indexMock->shouldReceive('create')->once()->andReturn();
        $indexMock->shouldReceive('aliasExists')->once()->andReturn(true);
        $indexMock->shouldReceive('import')->andReturn();

        App::shouldReceive('make')
            ->with('menthol.flexible.index', ['name' => 'Husband_9999', 'proxy' => $this->proxy])
            ->andReturn($indexMock);

        /**
         *
         * Assertion
         *
         */
        $this->proxy->reindex();

        $indexDouble->verifyInvoked('refresh', 'Husband');
        $indexDouble->verifyInvoked('clean', 'Husband');
        $indexDouble->verifyInvoked('updateAliases', function ($calls) use ($test, $actions) {
            $test->assertEquals($actions, $calls[0]);
        });
    }

    /**
     * @test
     */
    public function it_should_index()
    {
        $this->assertEquals(true, $this->proxy->shouldIndex());
    }

    /**
     * @test
     */
    public function it_should_refresh_docs()
    {
        /**
         *
         * Expectation
         *
         */
        $this->model->shouldReceive('transform')
            ->with(true)
            ->andReturn('body');

        $this->model->shouldReceive('getEsId')
            ->andReturn(1);

        $this->client->shouldReceive('index')
            ->with([
                'id' => '1',
                'index' => 'Husband',
                'type' => 'Husband',
                'body' => 'body'
            ])
            ->andReturn();

        $this->index->shouldReceive('getName')
            ->andReturn('Husband');

        /**
         *
         * Assertion
         *
         */
        $this->proxy->refreshDoc($this->model);
    }

    /**
     * @test
     */
    public function it_should_delete_docs()
    {
        /**
         *
         * Expectation
         *
         */
        $this->client->shouldReceive('delete')
            ->with([
                'id' => 1,
                'index' => 'Husband',
                'type' => 'Husband'
            ])
            ->andReturn();

        $this->index->shouldReceive('getName')
            ->andReturn('Husband');

        /**
         *
         * Assertion
         *
         */
        $this->proxy->deleteDoc(1);
    }

    /**
     * @test
     */
    public function it_should_enable_indexing_globally()
    {
        /**
         * Assertions
         */
        $this->proxy->enableIndexing();

        $this->assertEquals(\Husband::$__es_enable, true);
    }

    /**
     * @test
     */
    public function it_should_disable_indexing_globally()
    {
        /**
         * Assertions
         */
        $this->proxy->disableIndexing();

        $this->assertEquals(\Husband::$__es_enable, false);
    }

}


text:
title: Installation
---

# Installation

## Download

You can download this addon by requiring it with composer:

```bash
composer require anomaly/pages-module
```

You can also download this addon via the [Addons module](/documentation/addons-module).

## Install

You can install this addon with the `addon:install` command:

```bash
php artisan addon:install anomaly.module.pages
```

> The Pages module comes installed with PyroCMS out of the box.{.tip}


text:
// +build tools

package hack

// Add tools that hack scripts depend on here, to ensure they are vendored.
import (
	_ "github.com/client9/misspell/cmd/misspell"
	_ "github.com/go-bindata/go-bindata/v3"
	_ "k8s.io/code-generator/cmd/client-gen"
	_ "k8s.io/code-generator/cmd/deepcopy-gen"
	_ "k8s.io/code-generator/cmd/informer-gen"
	_ "k8s.io/code-generator/cmd/lister-gen"
	_ "sigs.k8s.io/controller-tools/cmd/controller-gen"
)


text:
package com.betfair.cougar.netutil.nio.message;

import com.betfair.cougar.netutil.nio.CougarProtocol;
import com.betfair.cougar.netutil.nio.CougarProtocolEncoder;
import org.apache.mina.common.ByteBuffer;

import java.util.HashMap;
import java.util.Map;

public abstract class AbstractMessage implements ProtocolMessage {

    @Override
    public ByteBuffer getSerialisedForm(byte protocolVersion) {
        return CougarProtocolEncoder.encode(this, protocolVersion);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Baked Salmon Packets</title>
      <categories>
        <cat>Fish</cat></categories>
      <yield>4</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>4</qty>
          <unit/></amt>
        <item>Salmon filets</item></ing>
      <ing>
        <amt>
          <qty>4</qty>
          <unit>teaspoons</unit></amt>
        <item>Butter</item></ing>
      <ing>
        <amt>
          <qty>8</qty>
          <unit/></amt>
        <item>Thyme sprigs, fresh</item></ing>
      <ing>
        <amt>
          <qty>8</qty>
          <unit/></amt>
        <item>Parsley sprigs, fresh</item></ing>
      <ing>
        <amt>
          <qty>4</qty>
          <unit/></amt>
        <item>Garlic cloves, minced</item></ing>
      <ing>
        <amt>
          <qty>4</qty>
          <unit>tablespoons</unit></amt>
        <item>White wine, dry</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Salt</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Black pepper, ground</item></ing></ingredients>
    <directions>
      <step>  Preheat oven to 400 degrees. Place 4 large pieces of foil on a working
  surface, shiny side down. Spray the inside with vegetable cooking spray.
  Place a fish filet on each piece of foil. Evenly divide thyme, parsley,
  garlic, salt, pepper, and wine among the fish. Dot each filet with one
  teaspoon of butter and then securely fold and seal the edges. Place the
  packets on a baking sheet and bake for 10-12 minutes. Place packets on
  plates and open carefully.

  SOURCE: Meg Woodard, R.D., Lucky Nutritionist, printed in Lucky
  :       Supermarket ad dated 3/13/1996.

  Typed for you by Lawren Freebody @ Salata BBS

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>


text:
namespace chromeos {

class UserImageModel;

// Interface for dependency injection between UserImageScreen and its actual
// representation, either views based or WebUI.
class UserImageView {
 public:
  virtual ~UserImageView() {}

  virtual void Bind(UserImageModel& model) = 0;

  virtual void Unbind() = 0;

  // Prepare the contents to showing.
  virtual void PrepareToShow() = 0;

  // Shows the contents of the screen.
  virtual void Show() = 0;

  // Hides the contents of the screen.
  virtual void Hide() = 0;

  // Hides curtain with spinner.
  virtual void HideCurtain() = 0;
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_LOGIN_SCREENS_USER_IMAGE_VIEW_H_


text:
using System;
using System.Collections.Generic;

using ASC.Core;
using ASC.Files.Core;
using ASC.Files.Core.Security;

namespace ASC.Api.Calendar.Attachments
{
    public class SecurityAdapter : IFileSecurity
    {
        private BusinessObjects.Calendar calendarObj;
        private BusinessObjects.Event eventObj;

        public SecurityAdapter()
        {
        }

        public SecurityAdapter(string data)
        {
            if (int.TryParse(data, out int id))
            {
                using (var provider = new BusinessObjects.DataProvider())
                {
                    eventObj = provider.GetEventById(id);
                    if (eventObj != null) {
                        calendarObj = provider.GetCalendarById(Convert.ToInt32(eventObj.CalendarId));
                    }
                }
            }
        }

        public SecurityAdapter(BusinessObjects.Event eventObj, BusinessObjects.Calendar calendarObj)
        {
            this.eventObj = eventObj;
            this.calendarObj = calendarObj;
        }

        public bool CanRead(FileEntry entry, Guid userId)
        {
            if (entry == null) return false;

            if (userId == FileConstant.ShareLinkId)
            {
                return true;
            }

            if (eventObj != null)
            {
                return eventObj.OwnerId == userId || eventObj.SharingOptions.PublicItems.Find(x => x.Id == userId) != null;
            }

            return false;
        }

        public bool CanCustomFilterEdit(FileEntry file, Guid userId)
        {
            return false;
        }

        public bool CanComment(FileEntry entry, Guid userId)
        {
            return false;
        }

        public bool CanFillForms(FileEntry entry, Guid userId)
        {
            return false;
        }

        public bool CanReview(FileEntry entry, Guid userId)
        {
            return false;
        }

        public bool CanCreate(FileEntry entry, Guid userId)
        {
            return false;
        }

        public bool CanDelete(FileEntry entry, Guid userId)
        {
            if (eventObj != null)
            {
                return eventObj.OwnerId == userId
                    || SecurityContext.PermissionResolver.Check(CoreContext.Authentication.GetAccountByID(userId), eventObj,
                                                                    null, CalendarAccessRights.FullAccessAction)
                    || SecurityContext.PermissionResolver.Check(CoreContext.Authentication.GetAccountByID(userId), calendarObj,
                                                                    null, CalendarAccessRights.FullAccessAction);
            }

            return false;
        }

        public bool CanEdit(FileEntry entry, Guid userId)
        {
            return false;
        }

        public IEnumerable<Guid> WhoCanRead(FileEntry entry)
        {
            var list = new List<Guid> { FileConstant.ShareLinkId };

            if (eventObj != null)
            {
                list.Add(eventObj.OwnerId);

                foreach (var item in eventObj.SharingOptions.PublicItems)
                {
                    list.Add(item.Id);
                }
            }

            return list;
        }

        public bool CanDownload(FileEntry entry, Guid userId)
        {
            return CanRead(entry, userId);
        }
    }
}


text:
require 'test/unit'
require_relative 'addcust'

class TestAddCustomer < Test::Unit::TestCase
  def test_add
    c = Customer.new("Ima", "Customer")
    f = File.open("tmpfile", "w") do |f|
      c.append_name_to_file(f)
    end
    f = File.open("tmpfile") do |f|
      assert_equal("Ima Customer", f.gets)
    end
  ensure
    File.delete("tmpfile") if File.exist?("tmpfile")
  end
end


text:
"""Module for testing the show hostmachinelist command."""

import unittest

if __name__ == "__main__":
    import utils
    utils.import_depends()

from brokertest import TestBrokerCommand

class TestShowHostMachineList(TestBrokerCommand):

    def testshowhostmachinelist(self):
        command = "show hostmachinelist"
        out = self.commandtest(command.split(" "))
        self.matchoutput(out, "unittest00.one-nyp.ms.com,ut3c1n3", command)
        self.matchoutput(out, "unittest02.one-nyp.ms.com,ut3c5n10", command)

    def testshowhostmachinelistarchetype(self):
        command = "show hostmachinelist --archetype aquilon"
        out = self.commandtest(command.split(" "))
        self.matchoutput(out, "unittest00.one-nyp.ms.com,ut3c1n3", command)
        self.matchoutput(out, "unittest02.one-nyp.ms.com,ut3c5n10", command)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestShowHostMachineList)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
/* modrdn.c - shell backend modrdn function */
/* $OpenLDAP: pkg/ldap/servers/slapd/back-shell/modrdn.c,v 1.28.2.6 2011/01/04 23:50:43 kurt Exp $ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
 * Copyright 1998-2011 The OpenLDAP Foundation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */
/* Portions Copyright (c) 1995 Regents of the University of Michigan.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that this notice is preserved and that due credit is given
 * to the University of Michigan at Ann Arbor. The name of the University
 * may not be used to endorse or promote products derived from this
 * software without specific prior written permission. This software
 * is provided ``as is'' without express or implied warranty.
 */
/* ACKNOWLEDGEMENTS:
 * This work was originally developed by the University of Michigan
 * (as part of U-MICH LDAP).
 */

#include "portable.h"

#include <stdio.h>

#include <ac/socket.h>
#include <ac/string.h>

#include "slap.h"
#include "shell.h"

int
shell_back_modrdn(
    Operation	*op,
    SlapReply	*rs )
{
	struct shellinfo	*si = (struct shellinfo *) op->o_bd->be_private;
	AttributeDescription *entry = slap_schema.si_ad_entry;
	Entry e;
	FILE			*rfp, *wfp;

	if ( si->si_modrdn == NULL ) {
		send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
		    "modrdn not implemented" );
		return( -1 );
	}

	e.e_id = NOID;
	e.e_name = op->o_req_dn;
	e.e_nname = op->o_req_ndn;
	e.e_attrs = NULL;
	e.e_ocflags = 0;
	e.e_bv.bv_len = 0;
	e.e_bv.bv_val = NULL;
	e.e_private = NULL;

	if ( ! access_allowed( op, &e, entry, NULL,
			op->oq_modrdn.rs_newSup ? ACL_WDEL : ACL_WRITE,
			NULL ) )
	{
		send_ldap_error( op, rs, LDAP_INSUFFICIENT_ACCESS, NULL );
		return -1;
	}

	if ( forkandexec( si->si_modrdn, &rfp, &wfp ) == (pid_t)-1 ) {
		send_ldap_error( op, rs, LDAP_OTHER,
		    "could not fork/exec" );
		return( -1 );
	}

	/* write out the request to the modrdn process */
	fprintf( wfp, "MODRDN\n" );
	fprintf( wfp, "msgid: %ld\n", (long) op->o_msgid );
	print_suffixes( wfp, op->o_bd );
	fprintf( wfp, "dn: %s\n", op->o_req_dn.bv_val );
	fprintf( wfp, "newrdn: %s\n", op->oq_modrdn.rs_newrdn.bv_val );
	fprintf( wfp, "deleteoldrdn: %d\n", op->oq_modrdn.rs_deleteoldrdn ? 1 : 0 );
	if ( op->oq_modrdn.rs_newSup != NULL ) {
		fprintf( wfp, "newSuperior: %s\n", op->oq_modrdn.rs_newSup->bv_val );
	}
	fclose( wfp );

	/* read in the results and send them along */
	read_and_send_results( op, rs, rfp );
	fclose( rfp );
	return( 0 );
}