text:
"""Tests for fused_batch_norm related functionality in tensorflow.ops.nn."""

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

import numpy as np

from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_grad
from tensorflow.python.ops import nn_impl
from tensorflow.python.platform import test

class BatchNormalizationTest(test.TestCase):

  def _batch_norm(self, x, mean, var, offset, scale, epsilon):
    # We compute the batch norm manually in this function because
    # nn_impl.batch_normalization does not support float16 yet.
    # TODO(reedwm): Add float16 support to nn_impl.batch_normalization.
    inv = math_ops.rsqrt(var + epsilon) * scale
    y = math_ops.cast(x, scale.dtype) * inv + (offset - mean * inv)
    return math_ops.cast(y, x.dtype)

  def _inference_ref(self, x, scale, offset, mean, var, epsilon, data_format):
    if data_format not in ['NHWC', 'NCHW']:
      raise ValueError('data_format must be NCHW or NHWC, '
                       'got %s.' % data_format)
    if data_format == 'NCHW':
      x = array_ops.transpose(x, [0, 2, 3, 1])
    y = self._batch_norm(x, mean, var, offset, scale, epsilon)
    if data_format == 'NCHW':
      y = array_ops.transpose(y, [0, 3, 1, 2])
    return y.eval()

  def _test_inference(self,
                      x_shape,
                      x_dtype,
                      scale_shape,
                      scale_dtype,
                      use_gpu=True,
                      data_format='NHWC'):
    np.random.seed(1)
    x_val = np.random.random_sample(x_shape).astype(x_dtype)
    scale_val = np.random.random_sample(scale_shape).astype(scale_dtype)
    offset_val = np.random.random_sample(scale_shape).astype(scale_dtype)
    mean_val = np.random.random_sample(scale_shape).astype(scale_dtype)
    var_val = np.random.random_sample(scale_shape).astype(scale_dtype)

    with self.test_session(use_gpu=use_gpu) as sess:
      x = constant_op.constant(x_val, name='x')
      scale = constant_op.constant(scale_val, name='scale')
      offset = constant_op.constant(offset_val, name='offset')
      mean = constant_op.constant(mean_val, name='mean')
      var = constant_op.constant(var_val, name='variance')
      epsilon = 0.001
      y, _, _ = nn_impl.fused_batch_norm(
          x,
          scale,
          offset,
          mean=mean,
          variance=var,
          epsilon=epsilon,
          data_format=data_format,
          is_training=False)
      y_val = sess.run(y)
      y_ref = self._inference_ref(x, scale, offset, mean, var, epsilon,
                                  data_format)
    # An atol value of 1e-3 is too small for float16's, because some adjacent
    # float16 values that y_val can take are greater than 1e-3 apart, e.g.
    # 2.16602 and 2.16797.
    atol = 2e-3 if x_dtype == np.float16 else 1e-3
    self.assertAllClose(y_ref, y_val, atol=atol)

  def _training_ref(self, x, scale, offset, epsilon, data_format):
    if data_format not in ['NHWC', 'NCHW']:
      raise ValueError('data_format must be NCHW or NHWC, '
                       'got %s.' % data_format)
    if data_format == 'NCHW':
      x = array_ops.transpose(x, [0, 2, 3, 1])
    mean, var = nn_impl.moments(
        math_ops.cast(x, scale.dtype), [0, 1, 2], keep_dims=False)
    y = self._batch_norm(x, mean, var, offset, scale, epsilon)
    if data_format == 'NCHW':
      y = array_ops.transpose(y, [0, 3, 1, 2])
    return y.eval(), mean.eval(), var.eval()

  def _test_training(self,
                     x_shape,
                     x_dtype,
                     scale_shape,
                     scale_dtype,
                     use_gpu=True,
                     data_format='NHWC'):
    np.random.seed(1)
    x_val = np.random.random_sample(x_shape).astype(x_dtype)
    scale_val = np.random.random_sample(scale_shape).astype(scale_dtype)
    offset_val = np.random.random_sample(scale_shape).astype(scale_dtype)
    with self.test_session(use_gpu=use_gpu) as sess:
      x = constant_op.constant(x_val, name='x')
      scale = constant_op.constant(scale_val, name='scale')
      offset = constant_op.constant(offset_val, name='offset')
      epsilon = 0.001
      y, mean, var = nn_impl.fused_batch_norm(
          x,
          scale,
          offset,
          epsilon=epsilon,
          data_format=data_format,
          is_training=True)
      y_val, mean_val, var_val = sess.run([y, mean, var])
      y_ref, mean_ref, var_ref = self._training_ref(x, scale, offset, epsilon,
                                                    data_format)
    y_atol = 2e-3 if x_dtype == np.float16 else 1e-3
    self.assertAllClose(y_ref, y_val, atol=y_atol)
    self.assertAllClose(mean_ref, mean_val, atol=1e-3)
    # This is for Bessel's correction. tf.nn.moments uses n, instead of n-1, as
    # the denominator in the formula to calculate variance, while
    # tf.nn.fused_batch_norm has Bessel's correction built in.
    sample_size = x_val.size / scale_val.size
    var_ref = var_ref * sample_size / (max(sample_size - 1.0, 1.0))
    self.assertAllClose(var_ref, var_val, atol=1e-3)

  def _compute_gradient_error_float16(self, x, x32, x_shape, y, y32, y_shape):
    """Computes the gradient error for float16 inputs and/or outputs.

    This returns the same value as gradient_checker.compute_gradient_error. The
    difference is that gradient_checker.compute_gradient_error does not
    numerically compute the gradients in a numerically stable way for float16
    tensors. To fix this, this function requires float32 versions of x and y to
    numerically compute the gradients, to compare with the float16 symbolically
    computed gradients.

    Args:
      x: The input tensor.
      x32: A float32 version of x.
      x_shape: The shape of x.
      y: The output tensor.
      y32: A float32 version of y. Must be calculated based on x32, not x.
      y_shape: The shape of y.

    Returns:
      The maximum error in between the two Jacobians, as in
      gradient_checker.compute_gradient_error.
    """
    x_init_val = np.random.random_sample(x_shape).astype(np.float16)
    x32_init_val = x_init_val.astype(np.float32)

    # TODO(reedwm): Do not perform the unnecessary computations in
    # compute_gradient, since they double the computation time of this function.
    theoretical_grad, _ = gradient_checker.compute_gradient(
        x, x_shape, y, y_shape, delta=1e-3, x_init_value=x_init_val)
    _, numerical_grad = gradient_checker.compute_gradient(
        x32, x_shape, y32, y_shape, delta=1e-3, x_init_value=x32_init_val)
    return np.fabs(theoretical_grad - numerical_grad).max()

  def _test_gradient(self,
                     x_shape,
                     x_dtype,
                     scale_shape,
                     scale_dtype,
                     use_gpu=True,
                     data_format='NHWC',
                     is_training=True):
    np.random.seed(1)
    x_val = np.random.random_sample(x_shape).astype(x_dtype)
    scale_val = np.random.random_sample(scale_shape).astype(scale_dtype)
    offset_val = np.random.random_sample(scale_shape).astype(scale_dtype)

    with self.test_session(use_gpu=use_gpu):
      x = constant_op.constant(x_val, name='x')
      scale = constant_op.constant(scale_val, name='scale')
      offset = constant_op.constant(offset_val, name='offset')
      if is_training:
        pop_mean = None
        pop_var = None
      else:
        pop_mean = np.random.random_sample(scale_shape).astype(scale_dtype)
        pop_var = np.random.random_sample(scale_shape).astype(scale_dtype)
      y, _, _ = nn_impl.fused_batch_norm(
          x,
          scale,
          offset,
          mean=pop_mean,
          variance=pop_var,
          data_format=data_format,
          is_training=is_training)
      if x_dtype != np.float16:
        err_x = gradient_checker.compute_gradient_error(x, x_shape, y, x_shape)
        err_scale = gradient_checker.compute_gradient_error(
            scale, scale_shape, y, x_shape)
        err_offset = gradient_checker.compute_gradient_error(
            offset, scale_shape, y, x_shape)
      else:
        x32 = constant_op.constant(x_val, name='x32', dtype=dtypes.float32)
        y32, _, _ = nn_impl.fused_batch_norm(
            x32,
            scale,
            offset,
            mean=pop_mean,
            variance=pop_var,
            data_format=data_format,
            is_training=is_training)
        err_x = self._compute_gradient_error_float16(x, x32, x_shape, y, y32,
                                                     x_shape)
        err_scale = self._compute_gradient_error_float16(
            scale, scale, scale_shape, y, y32, x_shape)
        err_offset = self._compute_gradient_error_float16(
            offset, offset, scale_shape, y, y32, x_shape)

    x_err_tolerance = 2e-3 if x_dtype == np.float16 else 1e-3
    scale_err_tolerance = 1e-3
    self.assertLess(err_x, x_err_tolerance)
    self.assertLess(err_scale, scale_err_tolerance)
    self.assertLess(err_offset, scale_err_tolerance)

  def _test_grad_grad(self,
                      x_shape,
                      x_dtype,
                      scale_shape,
                      scale_dtype,
                      use_gpu=True,
                      data_format='NHWC',
                      is_training=True,
                      err_tolerance=1e-3):
    np.random.seed(1)
    x_val = np.random.random_sample(x_shape).astype(x_dtype)
    grad_y_val = np.random.random_sample(x_shape).astype(x_dtype)
    scale_val = np.random.random_sample(scale_shape).astype(scale_dtype)
    offset_val = np.random.random_sample(scale_shape).astype(scale_dtype)

    with self.test_session(use_gpu=use_gpu) as sess:
      x = constant_op.constant(x_val, name='x')
      grad_y = constant_op.constant(grad_y_val, name='grad_y')
      scale = constant_op.constant(scale_val, name='scale')
      offset = constant_op.constant(offset_val, name='offset')
      if is_training:
        pop_mean = None
        pop_var = None
      else:
        pop_mean = np.random.random_sample(scale_shape).astype(scale_dtype)
        pop_var = np.random.random_sample(scale_shape).astype(scale_dtype)
      y, _, _ = nn_impl.fused_batch_norm(
          x,
          scale,
          offset,
          mean=pop_mean,
          variance=pop_var,
          data_format=data_format,
          is_training=is_training)
      grad_x, grad_scale, grad_offset = gradients_impl.gradients(
          y, [x, scale, offset], grad_y)

      if is_training:
        epsilon = y.op.get_attr('epsilon')
        data_format = y.op.get_attr('data_format')
        grad_vals = sess.run([grad_x, grad_scale, grad_offset])
        grad_internal = nn_grad._BatchNormGrad(grad_y, x, scale, pop_mean, pop_var, epsilon, data_format)
        grad_internal_vals = sess.run(list(grad_internal))
        for grad_val, grad_internal_val in zip(grad_vals, grad_internal_vals):
          self.assertAllClose(grad_val, grad_internal_val, atol=err_tolerance)

      if x_dtype != np.float16:
        err_grad_grad_y_1 = gradient_checker.compute_gradient_error(
            grad_y, x_shape, grad_x, x_shape)
        err_grad_grad_y_2 = gradient_checker.compute_gradient_error(
            grad_y, x_shape, grad_scale, scale_shape)
        err_grad_grad_y_3 = gradient_checker.compute_gradient_error(
            grad_y, x_shape, grad_offset, scale_shape)
        # In freeze mode, grad_x is not a function of x.
        if is_training:
          err_grad_x_1 = gradient_checker.compute_gradient_error(
              x, x_shape, grad_x, x_shape)
        err_grad_x_2 = gradient_checker.compute_gradient_error(
            x, x_shape, grad_scale, scale_shape)

        err_grad_scale = gradient_checker.compute_gradient_error(
            scale, scale_shape, grad_x, x_shape)
      else:
        x32 = constant_op.constant(x_val, dtype=dtypes.float32, name='x32')
        grad_y32 = constant_op.constant(
            grad_y_val, dtype=dtypes.float32, name='grad_y32')
        y32, _, _ = nn_impl.fused_batch_norm(
            x32,
            scale,
            offset,
            mean=pop_mean,
            variance=pop_var,
            data_format=data_format,
            is_training=is_training)
        grad_x32, grad_scale32, grad_offset32 = gradients_impl.gradients(
            y32, [x32, scale, offset], grad_y32)
        err_grad_grad_y_1 = self._compute_gradient_error_float16(
            grad_y, grad_y32, x_shape, grad_x, grad_x32, x_shape)
        err_grad_grad_y_2 = self._compute_gradient_error_float16(
            grad_y, grad_y32, x_shape, grad_scale, grad_scale32, scale_shape)
        err_grad_grad_y_3 = self._compute_gradient_error_float16(
            grad_y, grad_y32, x_shape, grad_offset, grad_offset32, scale_shape)
        # In freeze mode, grad_x is not a function of x.
        if is_training:
          err_grad_x_1 = self._compute_gradient_error_float16(
              x, x32, x_shape, grad_x, grad_x32, x_shape)
        err_grad_x_2 = self._compute_gradient_error_float16(
            x, x32, x_shape, grad_scale, grad_scale32, scale_shape)

        err_grad_scale = self._compute_gradient_error_float16(
            scale, scale, scale_shape, grad_x, grad_x32, x_shape)

    self.assertLess(err_grad_grad_y_1, err_tolerance)
    self.assertLess(err_grad_grad_y_2, err_tolerance)
    self.assertLess(err_grad_grad_y_3, err_tolerance)
    if is_training:
      self.assertLess(err_grad_x_1, err_tolerance)
    self.assertLess(err_grad_x_2, err_tolerance)
    self.assertLess(err_grad_scale, err_tolerance)

  def testInferenceShape1(self):
    x_shape = [1, 1, 6, 1]
    for dtype in [np.float16, np.float32]:
      if test.is_gpu_available(cuda_only=True):
        self._test_inference(
            x_shape, dtype, [1], np.float32, use_gpu=True, data_format='NHWC')
        self._test_inference(
            x_shape, dtype, [1], np.float32, use_gpu=True, data_format='NCHW')
      self._test_inference(
          x_shape, dtype, [1], np.float32, use_gpu=False, data_format='NHWC')

  def testInferenceShape2(self):
    x_shape = [1, 1, 6, 2]
    if test.is_gpu_available(cuda_only=True):
      for dtype in [np.float16, np.float32]:
        self._test_inference(
            x_shape, dtype, [2], np.float32, use_gpu=True, data_format='NHWC')
        self._test_inference(
            x_shape, dtype, [2], np.float32, use_gpu=False, data_format='NHWC')

  def testInferenceShape3(self):
    x_shape = [1, 2, 1, 6]
    if test.is_gpu_available(cuda_only=True):
      for dtype in [np.float16, np.float32]:
        self._test_inference(
            x_shape, dtype, [2], np.float32, use_gpu=True, data_format='NCHW')

  def testInferenceShape4(self):
    x_shape = [27, 131, 127, 6]
    for dtype in [np.float16, np.float32]:
      if test.is_gpu_available(cuda_only=True):
        self._test_inference(
            x_shape, dtype, [131], np.float32, use_gpu=True, data_format='NCHW')
        self._test_inference(
            x_shape, dtype, [6], np.float32, use_gpu=True, data_format='NHWC')
      self._test_inference(
          x_shape, dtype, [6], np.float32, use_gpu=False, data_format='NHWC')

  def testTrainingShape1(self):
    x_shape = [1, 1, 6, 1]
    for dtype in [np.float16, np.float32]:
      if test.is_gpu_available(cuda_only=True):
        self._test_training(
            x_shape, dtype, [1], np.float32, use_gpu=True, data_format='NHWC')
        self._test_training(
            x_shape, dtype, [1], np.float32, use_gpu=True, data_format='NCHW')
      self._test_training(
          x_shape, dtype, [1], np.float32, use_gpu=False, data_format='NHWC')

  def testTrainingShape2(self):
    x_shape = [1, 1, 6, 2]
    for dtype in [np.float16, np.float32]:
      if test.is_gpu_available(cuda_only=True):
        self._test_training(
            x_shape, dtype, [2], np.float32, use_gpu=True, data_format='NHWC')
      self._test_training(
          x_shape, dtype, [2], np.float32, use_gpu=False, data_format='NHWC')

  def testTrainingShape3(self):
    x_shape = [1, 2, 1, 6]
    if test.is_gpu_available(cuda_only=True):
      for dtype in [np.float16, np.float32]:
        self._test_training(
            x_shape, dtype, [2], np.float32, use_gpu=True, data_format='NCHW')

  def testTrainingShape4(self):
    x_shape = [27, 131, 127, 6]
    for dtype in [np.float16, np.float32]:
      if test.is_gpu_available(cuda_only=True):
        self._test_training(
            x_shape, dtype, [131], np.float32, use_gpu=True, data_format='NCHW')
        self._test_training(
            x_shape, dtype, [6], np.float32, use_gpu=True, data_format='NHWC')
      self._test_training(
          x_shape, dtype, [6], np.float32, use_gpu=False, data_format='NHWC')

  def testBatchNormGradShape1(self):
    for is_training in [True, False]:
      x_shape = [1, 1, 6, 1]
      for dtype in [np.float16, np.float32]:
        if test.is_gpu_available(cuda_only=True):
          self._test_gradient(
              x_shape,
              dtype, [1],
              np.float32,
              use_gpu=True,
              data_format='NHWC',
              is_training=is_training)
          self._test_gradient(
              x_shape,
              dtype, [1],
              np.float32,
              use_gpu=True,
              data_format='NCHW',
              is_training=is_training)
        self._test_gradient(
            x_shape,
            dtype, [1],
            np.float32,
            use_gpu=False,
            data_format='NHWC',
            is_training=is_training)

  def testBatchNormGradShape2(self):
    for is_training in [True, False]:
      x_shape = [1, 1, 6, 2]
      for dtype in [np.float16, np.float32]:
        if test.is_gpu_available(cuda_only=True):
          self._test_gradient(
              x_shape,
              dtype, [2],
              np.float32,
              use_gpu=True,
              data_format='NHWC',
              is_training=is_training)
        self._test_gradient(
            x_shape,
            dtype, [2],
            np.float32,
            use_gpu=False,
            data_format='NHWC',
            is_training=is_training)

  def testBatchNormGradShape3(self):
    for is_training in [True, False]:
      x_shape = [1, 2, 1, 6]
      if test.is_gpu_available(cuda_only=True):
        for dtype in [np.float16, np.float32]:
          self._test_gradient(
              x_shape,
              dtype, [2],
              np.float32,
              use_gpu=True,
              data_format='NCHW',
              is_training=is_training)

  def testBatchNormGradShape4(self):
    for is_training in [True, False]:
      x_shape = [5, 7, 11, 4]
      for dtype in [np.float16, np.float32]:
        if test.is_gpu_available(cuda_only=True):
          self._test_gradient(
              x_shape,
              dtype, [7],
              np.float32,
              use_gpu=True,
              data_format='NCHW',
              is_training=is_training)
          self._test_gradient(
              x_shape,
              dtype, [4],
              np.float32,
              use_gpu=True,
              data_format='NHWC',
              is_training=is_training)
        self._test_gradient(
            x_shape,
            dtype, [4],
            np.float32,
            use_gpu=False,
            data_format='NHWC',
            is_training=is_training)

  def _testBatchNormGradGrad(self, config):
    shape = config['shape']
    err_tolerance = config['err_tolerance']
    dtype = config['dtype']
    for is_training in [True, False]:
      if test.is_gpu_available(cuda_only=True):
        self._test_grad_grad(
            shape,
            dtype, [shape[3]],
            np.float32,
            use_gpu=True,
            data_format='NHWC',
            is_training=is_training,
            err_tolerance=err_tolerance)
        self._test_grad_grad(
            shape,
            dtype, [shape[1]],
            np.float32,
            use_gpu=True,
            data_format='NCHW',
            is_training=is_training,
            err_tolerance=err_tolerance)
      self._test_grad_grad(
          shape,
          dtype, [shape[3]],
          np.float32,
          use_gpu=False,
          data_format='NHWC',
          is_training=is_training,
          err_tolerance=err_tolerance)

  def testBatchNormGradGradConfig1(self):
    config = {
        'shape': [2, 3, 4, 5],
        'err_tolerance': 1e-2,
        'dtype': np.float32,
    }
    self._testBatchNormGradGrad(config)

  def testBatchNormGradGradConfig2(self):
    config = {
        'shape': [2, 3, 2, 2],
        'err_tolerance': 1e-3,
        'dtype': np.float32,
    }
    self._testBatchNormGradGrad(config)

  def testBatchNormGradGradConfig3(self):
    config = {
        'shape': [2, 3, 4, 5],
        'err_tolerance': 1e-2,
        'dtype': np.float16,
    }
    self._testBatchNormGradGrad(config)

  def testBatchNormGradGradConfig4(self):
    config = {
        'shape': [2, 3, 2, 2],
        'err_tolerance': 2e-3,
        'dtype': np.float16,
    }
    self._testBatchNormGradGrad(config)

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


text:
class AutoC4Cyber {
    init(autoc4, options) {
        if (this.options = options, this.autoc4 = autoc4, this.options.keys) {
            let cursor = 0;
            document.addEventListener("keydown", (e => {
                cursor = e.keyCode == this.options.keys[cursor] ? cursor + 1 : 0, cursor == this.options.keys.length && (document.querySelectorAll(this.options.target).forEach((e => e.classList.toggle(this.options.class))),
                cursor = 0);
            }));
        }
        return this;
    }
    onMessage(autoc4, message) {
        message.payloadBytes[0] ? document.querySelectorAll(this.options.target).forEach((e => e.classList.add(this.options.class))) : document.querySelectorAll(this.options.target).forEach((e => e.classList.remove(this.options.class)));
    }
    onConnect(autoc4, o) {}
    onConnectionFailure(autoc4, error) {}
}

export default autoc4 => autoc4.registerModuleType("cyber", (() => new AutoC4Cyber));
//# sourceMappingURL=cyber.js.map

redpajama_set_name: RedPajamaGithub


text:
module ArticleJSON
  module Export
    module FacebookInstantArticle
      module Elements
        class Image < Base
          include ArticleJSON::Export::Common::HTML::Elements::Image
        end
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FixtureBuilder\ExpressionLanguage;

use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use ReflectionClass;

/**
 * @covers \Nelmio\Alice\FixtureBuilder\ExpressionLanguage\TokenType
 */
class TokenTypeTest extends TestCase
{
    /**
     * @var string[]
     */
    private $constants;

    protected function setUp(): void
    {
        $reflClass = new ReflectionClass(TokenType::class);
        $this->constants = $reflClass->getConstants();
    }

    public function testIsImmutable(): void
    {
        static::assertTrue(true, 'Nothing to do.');
    }

    /**
     * @testdox Test that the static values used to control the input are grouping all the constants.
     */
    public function testStaticValues(): void
    {
        $reflClass = new ReflectionClass(TokenType::class);
        $reflProp = $reflClass->getProperty('values');
        $reflProp->setAccessible(true);
        $values = $reflProp->getValue($reflClass);

        static::assertCount(count($this->constants), $values);
        foreach ($this->constants as $constant) {
            static::assertTrue($values[$constant]);
        }
    }

    /**
     * @dataProvider provideAcceptableTypes
     */
    public function testCanCreateType(string $typeConstant): void
    {
        $type = new TokenType($typeConstant);
        static::assertEquals($type->getValue(), constant(sprintf('%s::%s', TokenType::class, $typeConstant)));
    }

    public function testThrowsAnExceptionIfAnInvalidTypeIsGiven(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Expected type to be a known token type but got "unknown".');

        new TokenType('unknown');
    }

    public function provideAcceptableTypes()
    {
        $reflClass = new ReflectionClass(TokenType::class);
        $constants = $reflClass->getConstants();

        foreach ($constants as $constant) {
            yield [$constant];
        }
    }
}


text:
module.exports = function(environment) {
    var Dimension = require("../less/tree/dimension"),
        Expression = require("../less/tree/expression"),
        functionRegistry = require("./../less/functions/function-registry");

    function imageSize(functionContext, filePathNode) {
        var filePath = filePathNode.value;
        var currentFileInfo = functionContext.currentFileInfo;
        var currentDirectory = currentFileInfo.relativeUrls ?
        currentFileInfo.currentDirectory : currentFileInfo.entryPath;

        var fragmentStart = filePath.indexOf('#');
        var fragment = '';
        if (fragmentStart !== -1) {
            fragment = filePath.slice(fragmentStart);
            filePath = filePath.slice(0, fragmentStart);
        }

        var fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);

        if (!fileManager) {
            throw {
                type: "File",
                message: "Can not set up FileManager for " + filePathNode
            };
        }

        var fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);

        if (fileSync.error) {
            throw fileSync.error;
        }

        var sizeOf = require('image-size');
        return sizeOf(fileSync.filename);
    }

    var imageFunctions = {
        "image-size": function(filePathNode) {
            var size = imageSize(this, filePathNode);
            return new Expression([
                new Dimension(size.width, "px"),
                new Dimension(size.height, "px")
            ]);
        },
        "image-width": function(filePathNode) {
            var size = imageSize(this, filePathNode);
            return new Dimension(size.width, "px");
        },
        "image-height": function(filePathNode) {
            var size = imageSize(this, filePathNode);
            return new Dimension(size.height, "px");
        }
    };

    functionRegistry.addMultiple(imageFunctions);
};


text:
using UnityEngine;
using System.Collections;

public class RenderTexturesDrawingOrder : MonoBehaviour
{	//This class draws all the render textures at an order specified here. If you want to combine multiple instances of this gameobject to implement things like stereoscopy or multiscopy you need to disable this and use the render textures as you please.
    [Tooltip("The order here determines the drawing order on screen.")]
    public CreateRenderTexture[] rendTextures;

    void OnGUI()
    {
        if (Event.current.type.Equals(EventType.Repaint))//only draw once a frame
        {
            for (int i = 0; i < rendTextures.Length; i++)
            {
                if (rendTextures[i].gameObject.activeInHierarchy)
                {
                    if (rendTextures[i].fullScreen)
                    {
                        Graphics.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), rendTextures[i].rendTex);     //if the render texture is from the whole screen draw the render texture full screen
                    }
                    else    //if not, draw it appropriately for foveated rendering at the right size and location.
                    {
                        Graphics.DrawTexture(new Rect(rendTextures[i].uviewport.focusPoint.x - (Screen.height * rendTextures[i].uviewport.regionResolutionMultiplier / 2), Screen.height - rendTextures[i].uviewport.focusPoint.y - (Screen.height * rendTextures[i].uviewport.regionResolutionMultiplier / 2), Screen.height * rendTextures[i].uviewport.regionResolutionMultiplier, Screen.height * rendTextures[i].uviewport.regionResolutionMultiplier), rendTextures[i].rendTex);
                    }
                }
            }
        }
    }

}


text:
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace WebApiAsyncETagStrategy
{
    public class ETagHandler
    {
        public class Funcs<TApiModel>
        {
            public Funcs(
                Func<Task<EntityTagHeaderValue>> getCurrentETag,
                Func<Task<TApiModel>> getCurrentModel,
                Func<TApiModel, Task<EntityTagHeaderValue>> getETagFromModel)
            {
                GetCurrentETag = getCurrentETag;
                GetCurrentModel = getCurrentModel;
                GetETagFromModel = getETagFromModel;
            }

            public Func<Task<EntityTagHeaderValue>> GetCurrentETag { get; protected set; }
            public Func<Task<TApiModel>> GetCurrentModel { get; protected set; }
            public Func<TApiModel, Task<EntityTagHeaderValue>> GetETagFromModel { get; protected set; }
        }

        public async Task<HttpResponseMessage> Handle<TApiModel>(HttpRequestMessage request, Funcs<TApiModel> funcs)
            where TApiModel : class
        {
            var requestETag = request.Headers.IfNoneMatch.FirstOrDefault();
            if (requestETag != null)
            {
                var entityETag = await funcs.GetCurrentETag();
                if (entityETag.Equals(requestETag))
                {
                    var notModifiedResponse = request.CreateResponse(HttpStatusCode.NotModified);
                    notModifiedResponse.Headers.ETag = entityETag;
                    return notModifiedResponse;
                }
            }

            var model = await funcs.GetCurrentModel();
            if (model == null)
            {
                return request.CreateResponse(HttpStatusCode.NotFound);
            }

            var response = request.CreateResponse(HttpStatusCode.OK, model);
            response.Headers.ETag = await funcs.GetETagFromModel(model);
            return response;
        }
    }
}


text:
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Validation;

namespace Orchard.ContentManagement.MetaData.Services {
    /// <summary>
    /// The content definition reader is used to import both content type and content part definitions from a XML format.
    /// </summary>
    public class ContentDefinitionReader : IContentDefinitionReader {
        /// <summary>
        /// The settings formatter to be used to convert the settings between a XML format and a dictionary.
        /// </summary>
        private readonly ISettingsFormatter _settingsFormatter;

        /// <summary>
        /// Initializes a new instance of the <see cref="ContentDefinitionReader"/> class.
        /// </summary>
        /// <param name="settingsFormatter">The settings formatter to be used to convert the settings between a dictionary and an XML format.</param>
        public ContentDefinitionReader(ISettingsFormatter settingsFormatter) {
            Argument.ThrowIfNull(settingsFormatter, "settingsFormatter");

            _settingsFormatter = settingsFormatter;
        }

        /// <summary>
        /// Merges a given content type definition provided in a XML format into a content type definition builder.
        /// </summary>
        /// <param name="element">The XML content type definition.</param>
        /// <param name="contentTypeDefinitionBuilder">The content type definition builder.</param>
        public void Merge(XElement element, ContentTypeDefinitionBuilder contentTypeDefinitionBuilder) {
            Argument.ThrowIfNull(element, "element");
            Argument.ThrowIfNull(contentTypeDefinitionBuilder, "contentTypeDefinitionBuilder");

            // Merge name
            contentTypeDefinitionBuilder.Named(XmlConvert.DecodeName(element.Name.LocalName));

            // Merge settings
            foreach (var setting in _settingsFormatter.Map(element)) {
                contentTypeDefinitionBuilder.WithSetting(setting.Key, setting.Value);
            }

            // Merge parts
            foreach (var iter in element.Elements()) {
                var partElement = iter;
                var partName = XmlConvert.DecodeName(partElement.Name.LocalName);
                if (partName == "remove") {
                    var nameAttribute = partElement.Attribute("name");
                    if (nameAttribute != null) {
                        contentTypeDefinitionBuilder.RemovePart(nameAttribute.Value);
                    }
                }
                else {
                    contentTypeDefinitionBuilder.WithPart(
                        partName,
                        partBuilder => {
                            foreach (var setting in _settingsFormatter.Map(partElement)) {
                                partBuilder.WithSetting(setting.Key, setting.Value);
                            }
                        });
                }
            }
        }

        /// <summary>
        /// Merges a given content part definition provided in a XML format into a content part definition builder.
        /// </summary>
        /// <param name="element">The XML content type definition.</param>
        /// <param name="contentPartDefinitionBuilder">The content part definition builder.</param>
        public void Merge(XElement element, ContentPartDefinitionBuilder contentPartDefinitionBuilder) {
            Argument.ThrowIfNull(element, "element");
            Argument.ThrowIfNull(contentPartDefinitionBuilder, "contentPartDefinitionBuilder");

            // Merge name
            contentPartDefinitionBuilder.Named(XmlConvert.DecodeName(element.Name.LocalName));

            // Merge settings
            foreach (var setting in _settingsFormatter.Map(element)) {
                contentPartDefinitionBuilder.WithSetting(setting.Key, setting.Value);
            }

            // Merge fields
            foreach (var iter in element.Elements()) {
                var fieldElement = iter;
                var fieldParameters = XmlConvert.DecodeName(fieldElement.Name.LocalName).Split(new[] { '.' }, 2);
                var fieldName = fieldParameters.FirstOrDefault();
                var fieldType = fieldParameters.Skip(1).FirstOrDefault();
                if (fieldName == "remove") {
                    var nameAttribute = fieldElement.Attribute("name");
                    if (nameAttribute != null) {
                        contentPartDefinitionBuilder.RemoveField(nameAttribute.Value);
                    }
                }
                else {
                    contentPartDefinitionBuilder.WithField(
                        fieldName,
                        fieldBuilder => {
                            fieldBuilder.OfType(fieldType);
                            foreach (var setting in _settingsFormatter.Map(fieldElement)) {
                                fieldBuilder.WithSetting(setting.Key, setting.Value);
                            }
                        });
                }
            }
        }
    }
}


text:
#define _HWVIDEO_INTERNAL_
#include "hwvideo.h"
#include <stdio.h>
#include "mystring.h"

#define MIN(x,y) (((LONG)x)<((LONG)y) ? (x) : (y))
#define MAX(x,y) (((LONG)x)>((LONG)y) ? (x) : (y))

GID OverlayGid = GID_DONTCARE;
GDDMODEINFO SysModeInfo;
HWVIDEOSETUP CurrentSetup;
PBYTE VRAMLinear;
ULONG  Handle = 0xffffffff; //handle of VRAM allocation
ULONG  BufferID = 0xffffffff;
BYTE   FreeBuf;
ULONG  BufOffset = 0xffffffff;
ULONG  BufCrop = 0;
ULONG  BufSize = 0;
BOOL   TripleBuffer = FALSE;
ULONG  HWScanAlign, HWFlags;
RECTL  CropRect = {0};
RECTL  DstBound = {0};

//utility functions
ULONG    AllocVRAM(ULONG Width, ULONG Height,ULONG Size) {
ULONG rc;
VRAMIN   vramin;
VRAMALLOCIN vramallocin;
VRAMALLOCOUT vramallocout;
      vramin.ulLength = sizeof(VRAMIN);
      vramin.ulFunction = VRAM_ALLOCATE;
      vramin.pIn = &vramallocin;
      vramallocin.ulLength = sizeof(VRAMALLOCIN);
      vramallocin.ulFlags = 0;
      vramallocin.ulID = 0xffffffff;
      vramallocin.ulFunction = VRAM_ALLOCATE;
      vramallocin.ulHandle = Handle;
      vramallocin.ulWidth = Width;
      vramallocin.ulHeight = Height;
      vramallocin.ulSize = Size;
      vramallocout.ulLength = sizeof(VRAMALLOCOUT);
      rc = VMIEntry(0, VMI_CMD_VRAM, &vramin, &vramallocout);
      if (rc) return rc;
      BufferID = vramallocout.ulID;
      // assume, that VRAM allocated with scanline granularity
      BufOffset = vramallocout.ptlStart.y*SysModeInfo.ulScanLineSize;
      return RC_SUCCESS;
}

ULONG      FreeVRAM(void) {
ULONG rc;
VRAMIN   vramin;
VRAMALLOCIN vramallocin;
VRAMALLOCOUT vramallocout;
      vramin.ulLength = sizeof(VRAMIN);
      vramin.ulFunction = VRAM_DEALLOCATE;
      vramin.pIn = &vramallocin;
      vramallocin.ulLength = sizeof(VRAMALLOCIN);
      vramallocin.ulFlags = 0;
      vramallocin.ulID = BufferID;
      vramallocin.ulFunction = VRAM_DEALLOCATE;
      vramallocin.ulHandle = Handle;
      vramallocout.ulLength = sizeof(VRAMALLOCOUT);
      rc = VMIEntry(0, VMI_CMD_VRAM, &vramin, &vramallocout);
      if (rc) return rc;
      BufOffset = 0xffffffff;
      BufferID = 0xffffffff;
      return RC_SUCCESS;
}

//clip destination window to screen rectangle, crop source and change BufCrop
//cropping offset of source buffer
//return 0, if success, !=0 if destination window out of screen completely
ULONG ClipRect(PHWVIDEOSETUP pSetup) {
LONG offsetleft,offsetright,offsettop,offsetbottom,croptop,cropleft,cropbottom,cropright;
ULONG hiscal,viscal;
       //first check parameters, we does not enable small window
       if (((CropRect.xRight-CropRect.xLeft)<8) ||
           ((CropRect.yBottom-CropRect.yTop)<8))  {
           return HWVIDEO_ERROR_PARAMETER;
       }
       if (((pSetup->rctlDstRect.yBottom - pSetup->rctlDstRect.yTop)<16) ||
           ((pSetup->rctlDstRect.xRight - pSetup->rctlDstRect.xLeft)<16)) {
           return HWVIDEO_ERROR_PARAMETER;
       }
       //
       //calculate inverce scaling factors from non-clipped values
       hiscal = ((CropRect.xRight - CropRect.xLeft)<<20)/(pSetup->rctlDstRect.xRight - pSetup->rctlDstRect.xLeft);
       viscal = ((CropRect.yBottom - CropRect.yTop)<<20)/(pSetup->rctlDstRect.yBottom - pSetup->rctlDstRect.yTop);
       //calc top and left "out of bounds" parts
       offsettop = -MIN(0,pSetup->rctlDstRect.yTop - DstBound.yTop);
       offsetleft = -MIN(0,pSetup->rctlDstRect.xLeft - DstBound.xLeft);
       // if destination rectangle completely out of screen, just return
       if (offsettop >= (pSetup->rctlDstRect.yBottom-pSetup->rctlDstRect.yTop)) {
          return HWVIDEO_ERROR_PARAMETER;
       }
       if (offsetleft >= (pSetup->rctlDstRect.xRight-pSetup->rctlDstRect.xLeft)) {
          return HWVIDEO_ERROR_PARAMETER;
       }

       offsetright = -MIN(0,(DstBound.xRight - pSetup->rctlDstRect.xRight));
       offsetbottom = -MIN(0,(DstBound.yBottom - pSetup->rctlDstRect.yBottom));

       if (offsetbottom >= (pSetup->rctlDstRect.yBottom - pSetup->rctlDstRect.yTop)) {
          return HWVIDEO_ERROR_PARAMETER;
       }
       if (offsetright >= (pSetup->rctlDstRect.xRight - pSetup->rctlDstRect.xLeft)) {
          return HWVIDEO_ERROR_PARAMETER;
       }
       cropleft = (offsetleft*hiscal)>>20;
       cropright = (offsetright*hiscal)>>20;
       croptop = (offsettop*viscal)>>20;
       cropbottom = (offsetbottom*viscal)>>20;
       //adjust with user-defined cropping
       cropleft += CropRect.xLeft;
       croptop += CropRect.yTop;
       cropright += pSetup->szlSrcSize.cx - CropRect.xRight - 1;
       cropbottom += pSetup->szlSrcSize.cy - CropRect.yBottom;// - 1; - attempt to fix "blinked line at bottom" bug
       //HWVIDEO GRADD interface does not support offset in the source image
       //but we can adjust buffer start to needed value
       BufCrop = croptop * pSetup->ulSrcPitch + cropleft*2; //for Y422 only!
       cropleft -= (BufCrop & HWScanAlign)/2;             //for Y422 only!
       BufCrop &= ~HWScanAlign;
       pSetup->rctlDstRect.xLeft += offsetleft;
       pSetup->rctlDstRect.xRight -= offsetright;
       pSetup->rctlDstRect.yTop += offsettop;
       pSetup->rctlDstRect.yBottom -= offsetbottom;
       pSetup->szlSrcSize.cx -= (cropleft + cropright);
       pSetup->szlSrcSize.cy -= (croptop + cropbottom);
       return HWVIDEO_DONE;

}

ULONG APIENTRY _DLL_InitTerm (HMODULE hmod, ULONG fTerm) {
   if (fTerm) {
//      DosBeep(100,100);
      HWVIDEOClose();
      return 1;
   }

   return 1;
}

ULONG APIENTRY HWVIDEOInit(void) {
ULONG rc;
VMIQCI ChainInfo;
PCHAININFO pChain;
PGRADDINFO pGradd;
INITPROCOUT initprocout;
HWEXTENSION hwext;
VRAMIN      vramin;
VRAMREGISTERIN vramregisterin;
VRAMREGISTEROUT vramregisterout;

    if (Handle != 0xffffffff) {
       return HWVIDEO_DONE;
    }
    rc = VMIEntry(GID_DONTCARE, VMI_CMD_INITPROC, NULL, &initprocout);
    if (rc)
       return HWVIDEO_ERROR_NO_HW;
    VRAMLinear = (PBYTE)(initprocout.ulVRAMVirt);
    rc = VMIEntry(GID_DONTCARE, VMI_CMD_QUERYCHAININFO, NULL, &ChainInfo);
    if (rc)
       return HWVIDEO_ERROR_NO_HW;

    pChain = ChainInfo.pciHead;
    while ((pChain != NULL) && (OverlayGid == GID_DONTCARE)) {
         pGradd = pChain->pGraddList;
         while (pGradd) {
           if (pGradd->pCapsInfo->pszFunctionClassID) {
              if (strlen(pGradd->pCapsInfo->pszFunctionClassID) == strlen(VA2_FUNCTION_CLASS))
                 if ((memcmp(pGradd->pCapsInfo->pszFunctionClassID, VA2_FUNCTION_CLASS, 20)) == 0) {
                    OverlayGid = pGradd->gid;
                    break;
                 }
           }
           pGradd = pGradd->pNextGraddInfo;
         }
         pChain = pChain->pNextChainInfo;
   }
   if (OverlayGid == GID_DONTCARE)
      return HWVIDEO_ERROR_NO_HW;
   //OK. We already find Overlay (if it present)
   //this time we need to register for VRAM allocation
   vramin.ulLength = sizeof(VRAMIN);
   vramin.ulFunction = VRAM_REGISTER;
   vramin.pIn = &vramregisterin;
   vramregisterin.ulLength = sizeof(VRAMREGISTERIN);
   vramregisterin.ulFlags = VRAM_REGISTER_HANDLE;
   vramregisterout.ulLength = sizeof(VRAMREGISTEROUT);
   rc = VMIEntry(0, VMI_CMD_VRAM, &vramin, &vramregisterout);
   if (rc)
      return HWVIDEO_ERROR_NO_HW; //if registration failed we can't use hw
   Handle = vramregisterout.ulHandle;
   //This time we need to query accelerator availability
   hwext.ulLength = sizeof(HWEXTENSION);
   hwext.ulXSubFunction = EXT_CMD_HWVIDEO_CONNECT;
   hwext.cScrChangeRects = 0;
   hwext.pXP1 = &Handle;
   hwext.ulXFlags = 0; //X_REQUESTHW;
   rc = VMIEntry(OverlayGid, VMI_CMD_EXTENSION, &hwext, &SysModeInfo);
   if (rc) {
      //HW already used by another process
      vramregisterin.ulFlags = 0;
      vramregisterin.ulHandle = Handle;
      vramin.ulFunction = VRAM_DEREGISTER;
      VMIEntry(0, VMI_CMD_VRAM, &vramin, &vramregisterout);
      Handle = 0xffffffff;
      return  rc;
   }
   //set cropping to default value
   CropRect.xLeft = 0;
   CropRect.xRight = 0xffff;
   CropRect.yTop = 0;
   CropRect.yBottom = 0xffff;
   memset(&DstBound, 0, sizeof(RECTL));
   //Overlay was not used yet, so we got it
   return HWVIDEO_DONE;
}

ULONG APIENTRY HWVIDEOCaps(PHWVIDEOCAPS pCaps) {
ULONG rc,temp;
HWEXTENSION hwext;
   //first, we need to check are we posess HW?
   if (Handle == 0xffffffff) return HWVIDEO_ERROR_NO_HW;
   //second check for needed amount of allocated memory
   if ((!pCaps) || (pCaps->ulLength < sizeof(HWVIDEOCAPS))) return HWVIDEO_ERROR_PARAMETER;
   hwext.ulLength = sizeof(HWEXTENSION);
   hwext.ulXSubFunction = EXT_CMD_HWVIDEO_QUERYCAPS;
   hwext.cScrChangeRects = 0;
   hwext.ulXFlags = X_REQUESTHW;
   rc = VMIEntry(OverlayGid, VMI_CMD_EXTENSION, &hwext, pCaps);
   if (!rc) {
      //if call successed, we need to
      HWScanAlign = pCaps->ulScanAlign;
      HWFlags = pCaps->ulCapsFlags;
      memcpy(&DstBound, &(pCaps->rctlDstMargin), sizeof(RECTL));
      //convert margins from HW to PM coordinates
      temp = pCaps->rctlDstMargin.yTop;
      pCaps->rctlDstMargin.yTop = SysModeInfo.ulVertResolution-1-pCaps->rctlDstMargin.yTop;
      pCaps->rctlDstMargin.yBottom = SysModeInfo.ulVertResolution-1-pCaps->rctlDstMargin.yBottom;
   }
   return rc;
}

ULONG APIENTRY HWVIDEOSetup(PHWVIDEOSETUP pSetup) {
ULONG rc;
HWEXTENSION hwext;
HWVIDEOSETUP tempsetup;
      //first check for viewport closing case
      if (!pSetup) {
         //we must free allocated buffers this time and hide video
         hwext.ulLength = sizeof(HWEXTENSION);
         hwext.ulXSubFunction = EXT_CMD_HWVIDEO_HIDE;
         hwext.cScrChangeRects = 0;
         hwext.ulXFlags = X_REQUESTHW;
         hwext.pXP1 = &Handle;
         rc = VMIEntry(OverlayGid, VMI_CMD_EXTENSION, &hwext, NULL);
         if (BufferID != 0xffffffff) {
            FreeVRAM();
         }
         //invalidate current setup
         CurrentSetup.szlSrcSize.cx = 0;
         CurrentSetup.szlSrcSize.cy = 0;
         BufOffset = 0xffffffff;
         return HWVIDEO_DONE;
      }
      //check, are Cropping present and valid
      if (pSetup->ulLength>40)
         if ((pSetup->szlSrcSize.cx < (pSetup->rctlSrcRect.xRight - pSetup->rctlSrcRect.xLeft))||
            (pSetup->szlSrcSize.cy < (pSetup->rctlSrcRect.yBottom - pSetup->rctlSrcRect.yTop))) {
            CurrentSetup.szlSrcSize.cx = 0;
            CurrentSetup.szlSrcSize.cy = 0;
            FreeVRAM();
            return HWVIDEO_ERROR_PARAMETER;
         }
      //check, are we need to reallocate buffers
      if ((CurrentSetup.szlSrcSize.cx != pSetup->szlSrcSize.cx)||
          (CurrentSetup.szlSrcSize.cy != pSetup->szlSrcSize.cy)||
          (CurrentSetup.fccColor != pSetup->fccColor)) {
//          fl|=1; //source changed
          if (BufferID != 0xffffffff) {
             FreeVRAM();
          }
          if (!pSetup->ulSrcPitch) {
             pSetup->ulSrcPitch = (pSetup->szlSrcSize.cx*2+HWScanAlign)&~HWScanAlign;
          }

          BufSize = pSetup->ulSrcPitch;

          //this must be calculation for different formats
          BufSize = ((BufSize+HWScanAlign)&~HWScanAlign)*pSetup->szlSrcSize.cy;

          TripleBuffer = TRUE;
          FreeBuf = 1;
          rc = AllocVRAM(pSetup->szlSrcSize.cx, pSetup->szlSrcSize.cy*3, BufSize*3);
          if (rc) {
             TripleBuffer = FALSE;
             rc = AllocVRAM(pSetup->szlSrcSize.cx, pSetup->szlSrcSize.cy*2, BufSize*2);
             if (rc) {
                BufOffset = 0xffffffff;
                return HWVIDEO_ERROR_LOW_VRAM;
             }
          }
          //OK, we got allocated buffer
      }
      //save new setup as current
      memcpy(&CurrentSetup, pSetup, sizeof(HWVIDEOSETUP ) > pSetup->ulLength ? pSetup->ulLength : sizeof(HWVIDEOSETUP));
      //copy new setup to temporary place
      memcpy(&tempsetup, pSetup, sizeof(HWVIDEOSETUP) > pSetup->ulLength ? pSetup->ulLength : sizeof(HWVIDEOSETUP));
      //convert destination coordinates
      tempsetup.rctlDstRect.yTop = SysModeInfo.ulVertResolution-CurrentSetup.rctlDstRect.yTop-1;
      tempsetup.rctlDstRect.yBottom = SysModeInfo.ulVertResolution-CurrentSetup.rctlDstRect.yBottom-1;
      /* Check for cropping stuff */
      if (pSetup->ulLength>40) {
         memcpy(&CropRect, &(pSetup->rctlSrcRect), sizeof(RECTL));
      }else {
         //old client, which does not handle source cropping
         CropRect.xLeft = 0;
         CropRect.yTop = 0;
         CropRect.xRight = pSetup->szlSrcSize.cx-1;
         CropRect.yBottom = pSetup->szlSrcSize.cy-1;
      }

      rc = ClipRect(&tempsetup);

      if (rc) {
         CurrentSetup.szlSrcSize.cx = 0;
         CurrentSetup.szlSrcSize.cy = 0;
         return rc;
      }

      hwext.ulLength = sizeof(HWEXTENSION);
      hwext.ulXSubFunction = EXT_CMD_HWVIDEO_SETUP;
      hwext.cScrChangeRects = 0;
      hwext.ulXFlags = X_REQUESTHW;
      hwext.pXP1 = &tempsetup;
      rc = VMIEntry(OverlayGid, VMI_CMD_EXTENSION, &hwext, NULL);
      if (rc) {
         //if HW can't handle this setup we need invalidate current setup
         CurrentSetup.szlSrcSize.cx = 0;
         CurrentSetup.szlSrcSize.cy = 0;
         FreeVRAM();
      }
      return rc;
}

ULONG APIENTRY HWVIDEOBeginUpdate(PVOID *ppBuffer, PULONG pulPhysBuffer){
ULONG offs;
//ULONG rc;
//HWREQIN hwreq;
      //first, we need to check are we posess HW?
      if (Handle==0xffffffff) return HWVIDEO_ERROR_NO_HW;

      //if there are no correct setup, then nothing to do
      if (BufOffset==0xffffffff) {
         return HWVIDEO_ERROR;
      }

/*    This is comment out, because it seems that it not really needed,
      but this can produce traps if FS session active
      hwreq.ulLength=sizeof(HWREQIN);
      hwreq.ulFlags=REQUEST_HW;
      hwreq.cScrChangeRects=0;
      rc=VMIEntry(OverlayGid,VMI_CMD_REQUESTHW,&hwreq,NULL);
      if (rc) {
         //we can't grab VMAN semaphore or we in background
         hwreq.ulFlags=0;
         VMIEntry(OverlayGid,VMI_CMD_REQUESTHW,&hwreq,NULL);
         return HWVIDEO_ERROR_BACKGROUND;
      }
*/
      offs=BufOffset+FreeBuf*BufSize;
      //calculate pointer to buffer
      *ppBuffer=(PVOID)(VRAMLinear+offs);
      //calculate physical address of buffer
      *pulPhysBuffer=(ULONG)(SysModeInfo.pbVRAMPhys+offs);
      return HWVIDEO_DONE;
}

ULONG APIENTRY HWVIDEOEndUpdate(void){
ULONG rc;
//HWREQIN hwreq;
HWEXTENSION hwext;
      //first, we need to check are we posess HW?
      if (Handle==0xffffffff) return HWVIDEO_ERROR_NO_HW;

      //if there are no correct setup, then nothing to do
      if (BufOffset==0xffffffff) {
         return HWVIDEO_ERROR;
      }
      //release VMAN semaphore
/*      hwreq.ulLength=sizeof(HWREQIN);
      hwreq.ulFlags=0;
      hwreq.cScrChangeRects=0;
      rc=VMIEntry(OverlayGid,VMI_CMD_REQUESTHW,&hwreq,NULL);
      if (rc) {
         //we can't release HW or we are in background???
         return HWVIDEO_ERROR_BACKGROUND;
      }*/
      hwext.ulLength=sizeof(HWEXTENSION);
      hwext.ulXSubFunction=EXT_CMD_HWVIDEO_DISPLAY;
      hwext.cScrChangeRects=0;
      hwext.ulXFlags=X_REQUESTHW;
      hwext.pXP1=(PVOID)(BufOffset+FreeBuf*BufSize+BufCrop);
      rc=VMIEntry(OverlayGid,VMI_CMD_EXTENSION,&hwext,NULL);
      if (rc) {
         return HWVIDEO_ERROR;
      }
      //we need to separate triple with double buffering
      if (TripleBuffer) {
         FreeBuf=(FreeBuf+1)==3? 0 : FreeBuf+1;
      } else {
         FreeBuf^=1;
      }
      return HWVIDEO_DONE;
}

ULONG APIENTRY HWVIDEOGetAttrib(ULONG ulAttribNum,PHWATTRIBUTE pAttrib){
HWEXTENSION hwext;
ULONG rc;
      if (Handle!=0xffffffff) {
         hwext.ulLength=sizeof(HWEXTENSION);
         hwext.ulXSubFunction=EXT_CMD_HWVIDEO_GETATTRIB;
         hwext.cScrChangeRects=0;
         hwext.ulXFlags=X_REQUESTHW;
         hwext.pXP1=pAttrib;
         rc=VMIEntry(OverlayGid,VMI_CMD_EXTENSION,&hwext,(PVOID)ulAttribNum);
         if (rc) {
            return rc;
         }
         return HWVIDEO_DONE;
      }
      return HWVIDEO_ERROR_NO_HW;

}

ULONG APIENTRY HWVIDEOSetAttrib(ULONG ulAttribNum,PHWATTRIBUTE pAttrib){
HWEXTENSION hwext;
ULONG rc;
      if (Handle!=0xffffffff) {
         hwext.ulLength=sizeof(HWEXTENSION);
         hwext.ulXSubFunction=EXT_CMD_HWVIDEO_SETATTRIB;
         hwext.cScrChangeRects=0;
         hwext.ulXFlags=X_REQUESTHW;
         hwext.pXP1=pAttrib;
         rc=VMIEntry(OverlayGid,VMI_CMD_EXTENSION,&hwext,(PVOID)ulAttribNum);
         if (rc) {
            return HWVIDEO_ERROR_PARAMETER;
         }
         return HWVIDEO_DONE;
      }
      return HWVIDEO_ERROR_NO_HW;
}

ULONG APIENTRY HWVIDEOClose(void){
ULONG rc;
HWEXTENSION hwext;
VRAMIN      vramin;
VRAMREGISTERIN vramregisterin;
VRAMREGISTEROUT vramregisterout;

      // in termination case, we need to free accelerator and VRAM
      if (Handle != 0xffffffff) {
         hwext.ulLength = sizeof(HWEXTENSION);
         hwext.ulXSubFunction = EXT_CMD_HWVIDEO_DISCONNECT;
         hwext.cScrChangeRects = 0;
         hwext.ulXFlags = X_REQUESTHW;
         hwext.pXP1 = &Handle;
         rc = VMIEntry(OverlayGid, VMI_CMD_EXTENSION, &hwext, NULL);
         //deregistering _MUST_ free all allocations for this handle
         //this can be true for any VRAM manager
         vramin.ulLength = sizeof(VRAMIN);
         vramin.ulFunction = VRAM_DEREGISTER;
         vramin.pIn = &vramregisterin;
         vramregisterin.ulLength = sizeof(VRAMREGISTERIN);
         vramregisterin.ulFlags = 0;
         vramregisterin.ulHandle = Handle;
         vramregisterout.ulLength = sizeof(VRAMREGISTEROUT);
         rc = VMIEntry(0, VMI_CMD_VRAM, &vramin, &vramregisterout);
         Handle = 0xffffffff;
         BufferID = 0xffffffff;
         BufOffset = 0xffffffff;
         BufCrop = 0;
         BufSize = 0;
         TripleBuffer = FALSE;
         CropRect.xLeft = 0;
         CropRect.xRight = 0xffff;
         CropRect.yTop = 0;
         CropRect.yBottom = 0xffff;
         memset(&DstBound, 0, sizeof(RECTL));
         OverlayGid = GID_DONTCARE;
         CurrentSetup.szlSrcSize.cx = 0;
         CurrentSetup.szlSrcSize.cy = 0;
      }

      return HWVIDEO_DONE;
}


text:
@interface NCInfoView ()
@property (nonatomic, strong) NSTextView *textView;
@end

@implementation NCInfoView

-(void)setupStuff {

	// Setting up the scroll view
	NSScrollView *scrollview = [[NSScrollView alloc] initWithFrame:[self bounds]];
	NSSize contentSize = [scrollview contentSize];
	[scrollview setBorderType:NSNoBorder];
	[scrollview setHasVerticalScroller:YES];
	[scrollview setHasHorizontalScroller:NO];
	[scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

	// Setting up the text view
	NSTextView *theTextView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, contentSize.width, contentSize.height)];
	[theTextView setMinSize:NSMakeSize(0.0, contentSize.height)];
	[theTextView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
	[theTextView setVerticallyResizable:YES];
	[theTextView setHorizontallyResizable:NO];
	[theTextView setAutoresizingMask:NSViewWidthSizable];
	[[theTextView textContainer] setContainerSize:NSMakeSize(contentSize.width, FLT_MAX)];
	[[theTextView textContainer] setWidthTracksTextView:YES];

	// Assembling the pieces
	[scrollview setDocumentView:theTextView];

	[self addSubview:scrollview];
	self.textView = theTextView;
	self.textView.string = @"Empty";
}

-(void)demo {
	[self analyzePath:[@"~/Desktop" stringByExpandingTildeInPath]];
}

-(void)analyzePath:(NSString*)path {
	NSParameterAssert(path);
	NCInspectFile *pp = [[NCInspectFile alloc] initWithPath:path];
	[pp obtain];
	NSAttributedString *s = [pp result];
	[self.textView setEditable:YES];
	self.textView.string = @"";
	[self.textView insertText:s];
	[self.textView setEditable:NO];
}

- (void)awakeFromNib
{

	[self setupStuff];
}

//
//	Don't draw background
//
- (BOOL)drawsBackground
{
	return	NO;
}

@end


text:
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![code style][style]][style-url]
[![chat][chat]][chat-url]

  <img width="100" height="100" title="Load Options"
    src="https://michael-ciniawsky.github.io/postcss-load-options/logo.svg"

Load Options

Install

```bash
npm i -D postcss-load-options
```

Usage

### `package.json`

Create **`postcss`** section in your projects **`package.json`**.

```
App
  |– client
  |– public
  |
  |- package.json
```

```json
{
  "dependencies": {
    "sugarss": "0.2.0"
  },
  "postcss": {
    "parser": "sugarss",
    "map": false,
    "from": "path/to/src/file.css",
    "to": "path/to/dest/file.css"
  }
}
```

### `.postcssrc`

Create a **`.postcssrc`** file.

```
App
  |– client
  |– public
  |
  |- (.postcssrc|.postcssrc.json|.postcssrc.yaml)
  |- package.json
```

**`JSON`**
```json
{
  "parser": "sugarss",
  "map": false,
  "from": "path/to/src/file.css",
  "to": "path/to/dest/file.css"
}
```

**`YAML`**
```yaml
parser: sugarss
map: false
from: "/path/to/src.sss"
to: "/path/to/dest.css"
```

### `postcss.config.js` or `.postcssrc.js`

You may need some JavaScript logic to generate your config. For this case you can use a file named **`postcss.config.js`** or **`.postcssrc.js`**.

```
App
  |– client
  |– public
  |
  |- (postcss.config.js|.postcssrc.js)
  |- package.json
```

```js
module.exports = (ctx) => {
  return {
    parser: ctx.sugar ? 'sugarss' : false,
    map: ctx.env === 'development' ? ctx.map || false,
    from: 'path/to/src/file.css',
    to: 'path/to/dest/file.css'
  }
}
```

Options

**`parser`**:

```js
'parser': 'sugarss'
```

**`syntax`**:

```js
'syntax': 'postcss-scss'
```
**`stringifier`**:

```js
'stringifier': 'midas'
```

[**`map`**:](https://github.com/postcss/postcss/blob/master/docs/source-maps.md)

```js
'map': 'inline'
```

**`from`**:

```js
from: 'path/to/dest/file.css'
```

**`to`**:

```js
to: 'path/to/dest/file.css'
```

### Context

When using a function `(postcss.config.js)`, it is possible to pass context to `postcss-load-options`, which will be evaluated before loading your options. By default `ctx.env (process.env.NODE_ENV)` and `ctx.cwd (process.cwd())` are available.

Example

###

```js
const { readFileSync } = require('fs')

const postcss = require('postcss')
const optionsrc = require('postcss-load-options')

const sss =  readFileSync('index.sss', 'utf8')

const ctx = { sugar: true,  map: 'inline' }

optionsrc(ctx).then((options) => {
  postcss()
    .process(sss, options)
    .then(({ css }) => console.log(css))
}))
```

Maintainers

      Michael Ciniawsky

[npm]: https://img.shields.io/npm/v/postcss-load-options.svg
[npm-url]: https://npmjs.com/package/postcss-load-options

[node]: https://img.shields.io/node/v/postcss-load-options.svg
[node-url]: https://nodejs.org/

[deps]: https://david-dm.org/michael-ciniawsky/postcss-load-options.svg
[deps-url]: https://david-dm.org/michael-ciniawsky/postcss-load-options

[tests]: http://img.shields.io/travis/michael-ciniawsky/postcss-load-options.svg
[tests-url]: https://travis-ci.org/michael-ciniawsky/postcss-load-options

[cover]: https://coveralls.io/repos/github/michael-ciniawsky/postcss-load-options/badge.svg
[cover-url]: https://coveralls.io/github/michael-ciniawsky/postcss-load-options

[style]: https://img.shields.io/badge/code%20style-standard-yellow.svg
[style-url]: http://standardjs.com/

[chat]: https://img.shields.io/gitter/room/postcss/postcss.svg
[chat-url]: https://gitter.im/postcss/postcss


text:
Oskari.registerLocalization({
  "lang": "sv",
  "key": "MyFourthBundle",
  "value": {
    "tooltip": "Click me!",
    "toolClicked": "Tool clicked"
  }
});


text:
package org.ivnbl.gametools.il2cod.services.ui

trait ModuleServiceListener {
  def moduleRegistered(service: ModuleService, adminModule: AdminModule)

  def moduleUnregistered(service: ModuleService, adminModule: AdminModule)
}


text:
class BookmarksController < ApplicationController
  include AuthorizationHelper
  include Scoring
  helper_method :specific_average_score
  helper_method :total_average_score

  def action_allowed?
    case params[:action]
    when 'list'
      current_role_name =~ /^(Student|Instructor|Teaching Assistant)$/
    when 'new', 'create', 'bookmark_rating', 'save_bookmark_rating_score'
      current_role_name.eql? 'Student'
    when 'edit', 'update', 'destroy'
      # edit, update, delete bookmarks can only be done by owner
      current_user_has_student_privileges? && current_user_created_bookmark_id?(params[:id])
    end
    @current_role_name = current_role_name
  end

  def list
    @bookmarks = Bookmark.where(topic_id: params[:id])
    @topic = SignUpTopic.find(params[:id])
  end

  def new
    @topic = SignUpTopic.find(params[:id])
    @bookmark = Bookmark.new
  end

  def create
    params[:url] = params[:url].gsub!(%r{http://}, '') if params[:url].start_with?('http://')
    params[:url] = params[:url].gsub!(%r{https://}, '') if params[:url].start_with?('https://')
    begin
      Bookmark.create(url: create_bookmark_params[:url], title: create_bookmark_params[:title], description: create_bookmark_params[:description], user_id: session[:user].id, topic_id: create_bookmark_params[:topic_id])
      ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].name, 'Your bookmark has been successfully created!', request)
      flash[:success] = 'Your bookmark has been successfully created!'
    rescue StandardError
      ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].name, $ERROR_INFO, request)
      flash[:error] = $ERROR_INFO
    end
    redirect_to action: 'list', id: params[:topic_id]
  end

  def edit
    @bookmark = Bookmark.find(params[:id])
  end

  def update
    @bookmark = Bookmark.find(params[:id])
    @bookmark.update_attributes(url: update_bookmark_params[:bookmark][:url], title: update_bookmark_params[:bookmark][:title], description: update_bookmark_params[:bookmark][:description])
    ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].name, 'Your bookmark has been successfully updated!', request)
    flash[:success] = 'Your bookmark has been successfully updated!'
    redirect_to action: 'list', id: @bookmark.topic_id
  end

  def destroy
    @bookmark = Bookmark.find(params[:id])
    @bookmark.destroy
    ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].name, 'Your bookmark has been successfully deleted!', request)
    flash[:success] = 'Your bookmark has been successfully deleted!'
    redirect_to action: 'list', id: @bookmark.topic_id
  end

  def bookmark_rating
    @bookmark = Bookmark.find(params[:id])
  end

  def save_bookmark_rating_score
    @bookmark = Bookmark.find(params[:id])
    @bookmark_rating = BookmarkRating.where(bookmark_id: @bookmark.id, user_id: session[:user].id).first
    if @bookmark_rating.blank?
      BookmarkRating.create(bookmark_id: @bookmark.id, user_id: session[:user].id, rating: create_bookmark_params[:rating])
    else
      @bookmark_rating.update_attribute('rating', create_bookmark_params[:rating].to_i)
    end
    redirect_to action: 'list', id: @bookmark.topic_id
  end

  # calculate average questionnaire score for 'Your rating' for specific bookmark
  def specific_average_score(bookmark)
    if bookmark.nil?
      '-'
    else
      assessment = SignUpTopic.find(bookmark.topic_id).assignment
      questions = assessment.questionnaires.where(type: 'BookmarkRatingQuestionnaire').flat_map(&:questions)
      responses = BookmarkRatingResponseMap.where(
        reviewed_object_id: assessment.id,
        reviewee_id: bookmark.id,
        reviewer_id: AssignmentParticipant.find_by(user_id: current_user.id).id
      ).flat_map { |r| Response.where(map_id: r.id) }
      score = assessment_score(response: responses, questions: questions)
      if score.nil?
        return '-'
      else
        (score * 5.0 / 100.0).round(2)
      end
    end
  end

  # calculate average questionnaire score for 'Avg. rating' for specific bookmark
  def total_average_score(bookmark)
    if bookmark.nil?
      '-'
    else
      assessment = SignUpTopic.find(bookmark.topic_id).assignment
      questions = assessment.questionnaires.where(type: 'BookmarkRatingQuestionnaire').flat_map(&:questions)
      responses = BookmarkRatingResponseMap.where(
        reviewed_object_id: assessment.id,
        reviewee_id: bookmark.id
      ).flat_map { |r| Response.where(map_id: r.id) }
      totalScore = aggregate_assessment_scores(responses, questions)
      if totalScore[:avg].nil?
        return '-'
      else
        (totalScore[:avg] * 5.0 / 100.0).round(2)
      end
    end
  end

  private

  # TODO: Create a common definition for both create and update to reduce it to single params method
  # Change create method to take bookmark param as required.
  def create_bookmark_params
    params.permit(:url, :title, :description, :topic_id, :rating, :id)
  end

  def update_bookmark_params
    params.require(:bookmark).permit(:url, :title, :description)
  end
end


text:
package com.ulargui.healthylinkx_android;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

public class SelectedProviders extends CallService{
    private ArrayList<String[]> outputlist = new ArrayList<String[]> ();

    protected ArrayList<String[]> Output(){return outputlist;}

    SelectedProviders(AsyncResponse a, String npi1, String npi2, String npi3){
        super(a);

		String url= "";
        int i=1;
		if (npi1 != null && !npi1.isEmpty()){
			if (!url.isEmpty()) url+="&";
			url+="NPI" + i + "=" + npi1;
            i++;
		}
		if (npi2 != null && !npi2.isEmpty()){
			if (!url.isEmpty()) url+="&";
            url+="NPI" + i + "=" + npi2;
            i++;
		}
		if (npi3 != null && !npi3.isEmpty()){
			if (!url.isEmpty()) url+="&";
            url+="NPI" + i + "=" + npi3;
            i++;
		}

        call( MyAppConstants.BASE_URL + "/shortlist?" + url);
    }

    protected void onPostExecute(String result){
        outputlist.clear();
        String[] transaction = new String[1];

        try {
            JSONObject rootObject = new JSONObject(result);

            transaction[0]=rootObject.getString("Transaction");
            outputlist.add(transaction);

            JSONArray jArray = rootObject.getJSONArray("Providers");
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject oneObject = jArray.getJSONObject(i);

				String[] tmp = new String[5];
                tmp[0] = oneObject.getString("NPI");
                tmp[1] = oneObject.getString("Provider_Full_Name");
                tmp[2] = oneObject.getString("Provider_Full_Street");
                tmp[3] = oneObject.getString("Provider_Full_City");
                tmp[4] = oneObject.getString("Provider_Business_Practice_Location_Address_Telephone_Number");

                outputlist.add(tmp);
            }
        } catch (JSONException e) {
            outputlist.clear();
        } finally {
            super.onPostExecute(result);
        }
    }
}