text:
using System.Linq;
using Newtonsoft.Json.Linq;

namespace SlimDX.Generator
{
	static class CompositingEngine
	{
        public static void Compose(JObject baseLayer, JObject nextLayer)
		{
			// Top-level scalar properties are always replaced.
			foreach (var pair in nextLayer)
			{
                if (pair.Value.Type != JTokenType.Array)
					baseLayer[pair.Key] = pair.Value;
			}

			ComposeArrays(baseLayer, nextLayer, "dependencies");
			ComposeArrays(baseLayer, nextLayer, "translations");

			ComposeEnumerations(baseLayer, nextLayer);
            ComposeStructures(baseLayer, nextLayer);
            ComposeInterfaces(baseLayer, nextLayer);
            ComposeFunctions(baseLayer, nextLayer);
		}

		static void ComposeEnumerations(JObject baseLayer, JObject newLayer)
		{
            JArray baseArray;
            JArray newArray;
			if (!GetItemArrays("enumerations", baseLayer, newLayer, out baseArray, out newArray))
				return;

            foreach (var item in newArray)
			{
				var flags = GetFlags(item as JObject);
                var oldItem = FindObjectByKey(baseArray, item.Value<string>("key"));
                if ((flags == CompositionFlags.Replace || flags == CompositionFlags.Remove || flags == CompositionFlags.None) && oldItem != null)
                    oldItem.Remove();

				if (flags == CompositionFlags.Add || flags == CompositionFlags.None || flags == CompositionFlags.Replace)
                    baseArray.Add(item);
			}
		}

        static void ComposeStructures(JObject baseLayer, JObject newLayer)
        {
            JArray baseArray;
            JArray newArray;
            if (!GetItemArrays("structures", baseLayer, newLayer, out baseArray, out newArray))
                return;

            foreach (var item in newArray)
            {
                var flags = GetFlags(item as JObject);
                var oldItem = FindObjectByKey(baseArray, item.Value<string>("key"));
                if ((flags == CompositionFlags.Replace || flags == CompositionFlags.Remove || flags == CompositionFlags.None) && oldItem != null)
                    oldItem.Remove();

                if (flags == CompositionFlags.Add || flags == CompositionFlags.None || flags == CompositionFlags.Replace)
                    baseArray.Add(item);
            }
        }

        static void ComposeInterfaces(JObject baseLayer, JObject newLayer)
        {
            JArray baseArray;
            JArray newArray;
            if (!GetItemArrays("interfaces", baseLayer, newLayer, out baseArray, out newArray))
                return;

            foreach (var item in newArray)
            {
                var flags = GetFlags(item as JObject);
                var oldItem = FindObjectByKey(baseArray, item.Value<string>("key"));
                if ((flags == CompositionFlags.Replace || flags == CompositionFlags.Remove || flags == CompositionFlags.None) && oldItem != null)
                    oldItem.Remove();

                if (flags == CompositionFlags.Add || flags == CompositionFlags.None || flags == CompositionFlags.Replace)
                    baseArray.Add(item);
            }
        }

        static void ComposeFunctions(JObject baseLayer, JObject newLayer)
        {
            JArray baseArray;
            JArray newArray;
            if (!GetItemArrays("functions", baseLayer, newLayer, out baseArray, out newArray))
                return;

            foreach (var item in newArray)
            {
                var flags = GetFlags(item as JObject);
                var oldItem = FindObjectByKey(baseArray, item.Value<string>("key"));
                if ((flags == CompositionFlags.Replace || flags == CompositionFlags.Remove || flags == CompositionFlags.None) && oldItem != null)
                    oldItem.Remove();

                if (flags == CompositionFlags.Add || flags == CompositionFlags.None || flags == CompositionFlags.Replace)
                    baseArray.Add(item);
            }
        }

		static void ComposeArrays(JObject baseLayer, JObject newLayer, string name)
		{
            JArray baseArray;
            JArray newArray;
			if (!GetItemArrays(name, baseLayer, newLayer, out baseArray, out newArray))
				return;

            foreach (var item in newArray)
			{
                if (!baseArray.Contains(item))
                    baseArray.Add(item);
			}
		}

		#region Helpers

        static bool GetItemArrays(string name, JObject baseLayer, JObject newLayer, out JArray baseArray, out JArray newArray)
		{
            baseArray = null;
            newArray = null;

			JToken newLayerItems;
			if (!newLayer.TryGetValue(name, out newLayerItems))
				return false;

            JToken baseLayerItems;
			if (!baseLayer.TryGetValue(name, out baseLayerItems))
			{
				baseLayerItems = new JArray();
				baseLayer.Add(name, baseLayerItems);
			}

            baseArray = baseLayerItems as JArray;
            newArray = newLayerItems as JArray;
			return true;
		}

		static CompositionFlags GetFlags(JObject item)
		{
            JToken compositing;
            if (item.TryGetValue("compositing", out compositing))
            {
                switch (compositing.Value<string>())
                {
                    case "add":
                        return CompositionFlags.Add;
                    case "remove":
                        return CompositionFlags.Remove;
                    case "replace":
                        return CompositionFlags.Replace;
                }
            }

			return CompositionFlags.None;
		}

		static JObject FindObjectByKey(JArray array, string key)
		{
			foreach (var item in array)
			{
                JToken token;
                if ((item as JObject).TryGetValue("key", out token) && token.Value<string>() == key)
                    return item as JObject;
			}

			return null;
		}

		#endregion
	}
}


text:
package com.github.timeu.dygraphsgwt.client.callbacks;

import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Element;
import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsIgnore;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

/**
 * Dygraphs lets you add annotations (markers) to individual points on your
 * chart. These markers have a short bit of text or an icon that's displayed
 * over the chart, plus a longer description that appears when you hover over them.
 *
 * Created by uemit.seren on 7/29/15.
 */

@JsType(isNative = true,namespace = JsPackage.GLOBAL,name="Object")
public class Annotation {

    /**
     * The name of the series to which the annotated point belongs.
     *  @Required
     */
    public String series;

    /**
     *  The x value of the point.
     *  This should be the same as the value you specified in your CSV file, e.g. "2010-09-13".
     *  @Required
     */
    public String x;

    /**
     *  Specify in place of shortText to mark the annotation with an image rather than text.
     *  If you specify this, you must specify width and height.
     */
    public String icon;

    /**
     *  Width (in pixels) of the annotation flag or icon.
     */
    public Double width;

    /**
     * Height (in pixels) of the annotation flag or icon.
     */
    public Double height;

    /**
     * Height of the tick mark (in pixels) connecting the point to its flag or icon.
     */
    public Integer tickHeight;

    /**
     * Text that will appear on the annotation's flag.
     */
    public String shortText;

    /**
     * A longer description of the annotation which will appear when the user hovers over it.
     */
    public String text;

    /**
     * Handler that is executed when the user clicks on the annotation.
     */
    public AnnotationClickHandler clickHandler;

    /**
     * Handler that is executed when the user moves the mouse over an annotation
     */
    public AnnotationMouseOverHandler mouseOverHandler;

    /**
     * Handler that is executed when the user moves the mouse out of an annotation
     */
    public AnnotationMouseOutHandler mouseOutHandler;

    /**
     * Handler that is executed when the user double clicks on the annotation.
     */
    public AnnotationDbClickHandler dblClickHandler;

    /**
     * The DOM Div element of the annotation
     */
    public DivElement div;

    /**
     * If true, attach annotations to the x-axis, rather than to actual points.
     */
    public boolean attachAtBottom;

    /**
     *  The parsed x-Value
     */
    public Double xval;

    /**
     * CSS class to use for styling the annotation.
     */
    public String cssClass;
}

redpajama_set_name: RedPajamaGithub


text:
import unittest
import os
from worldengine.draw import _biome_colors, Image, draw_simple_elevation, elevation_color, \
    draw_elevation, draw_riversmap, draw_grayscale_heightmap, draw_ocean, draw_precipitation, \
    draw_world, draw_temperature_levels, draw_biome
from worldengine.biome import Biome
from worldengine.world import World

class PixelCollector:

    def __init__(self, width, height):
        self.pixels = {}
        self.width = width
        self.height = height
        for y in range(height):
            for x in range(width):
                self.pixels[x, y] = (0, 0, 0, 0)

    def set_pixel(self, x, y, color):
        if len(color) == 3:
            color = color + (255,)
        self.pixels[(x, y)] = color

    def __getitem__(self, item):
        return self.pixels[item]

    def __setitem__(self, key, value):
        self.pixels[key] = value

class TestBase(unittest.TestCase):

    def setUp(self):
        tests_dir = os.path.dirname(os.path.realpath(__file__))
        self.tests_data_dir = os.path.abspath(os.path.join(
            tests_dir, "../../worldengine-data/tests/data"))
        self.tests_blessed_images_dir = os.path.abspath(
            os.path.join(tests_dir, "../../worldengine-data/tests/images"))
        self.assertTrue(
            os.path.isdir(self.tests_data_dir),
            "worldengine-data doesn't exist, please clone it before continuing.")

    def _assert_is_valid_color(self, color, color_name):
        r, g, b = color
        self.assertTrue(0.0 <= r <= 1.0, "red component %s is not in [0,1]: %f" % (color_name, r))
        self.assertTrue(0.0 <= g <= 1.0, "green component %s is not in [0,1]: %f" % (color_name, g))
        self.assertTrue(0.0 <= b <= 1.0, "blue component %s is not in [0,1]: %f" % (color_name, b))

    def _assert_are_colors_equal(self, expected, actual):
        if len(expected) == 3:
            expected = expected + (255,)
        if len(actual) == 3:
            actual = actual + (255,)
        self.assertEqual(expected, actual)

    def _assert_img_equal(self, blessed_image_name, drawn_image):
        blessed_img = Image.open("%s/%s.png" % (self.tests_blessed_images_dir, blessed_image_name))
        blessed_img_pixels = blessed_img.load()

        blessed_img_width, blessed_img_height = blessed_img.size
        self.assertEqual(blessed_img_width, drawn_image.width)
        self.assertEqual(blessed_img_height, drawn_image.height)
        for y in range(blessed_img_height):
            for x in range(blessed_img_width):
                blessed_pixel = blessed_img_pixels[x, y]
                drawn_pixel = drawn_image[x, y]
                self.assertEqual(blessed_pixel, drawn_pixel,
                                 "Pixels at %i, %i are different. Blessed %s, drawn %s"
                                 % (x, y, blessed_pixel, drawn_pixel))

class TestDraw(TestBase):

    def setUp(self):
        super(TestDraw, self).setUp()

    def test_biome_colors(self):
        self.assertEqual(Biome.all_names(), _biome_colors.keys().sort())

    def test_elevation_color(self):
        for i in range(0, 20):
            v = i / 2.0
            c = ra, ga, ba = elevation_color(v)
            delta = 0.0000001
            c_low = rb, gb, bb = elevation_color(v - delta)
            c_high = rc, gc, bc = elevation_color(v + delta)

            # we want values to be in range
            self._assert_is_valid_color(c, "color for %f" % v)
            self._assert_is_valid_color(c_low, "color for %f (low)" % (v - delta))
            self._assert_is_valid_color(c_high, "color for %f (high)" % (v + delta))

            # we look for discontinuities
            # TODO verify this
            #self.assertAlmostEqual(ra, rb, 5, "value %f, red, low, from %f to %f" % (v, ra, rb))
            #self.assertAlmostEqual(ra, rc, 5, "value %f, red, high, from %f to %f" % (v, ra, rc))
            #self.assertAlmostEqual(ga, gb, 5, "value %f, green, low, from %f to %f" % (v, ga, gb))
            #self.assertAlmostEqual(ga, gc, 5, "value %f, green, high, from %f to %f" % (v, ga, gc))
            #self.assertAlmostEqual(ba, bb, 5, "value %f, blue, low, from %f to %f" % (v, ba, bb))
            #self.assertAlmostEqual(ba, bc, 5, "value %f, blue, high, from %f to %f" % (v, ba, bc))

    def test_draw_simple_elevation(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        data = w.elevation['data']
        target = PixelCollector(w.width, w.height)
        draw_simple_elevation(data, w.width, w.height, w.sea_level(), target)
        self._assert_img_equal("simple_elevation_28070", target)

    def test_draw_elevation_shadow(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        data = w.elevation['data']
        target = PixelCollector(w.width, w.height)
        draw_elevation(w, True, target)
        self._assert_img_equal("elevation_28070_shadow", target)

    def test_draw_elevation_no_shadow(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        data = w.elevation['data']
        target = PixelCollector(w.width, w.height)
        draw_elevation(w, False, target)
        self._assert_img_equal("elevation_28070_no_shadow", target)

    def test_draw_river_map(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        target = PixelCollector(w.width, w.height)
        draw_riversmap(w, target)
        self._assert_img_equal("riversmap_28070", target)

    def test_draw_grayscale_heightmap(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        target = PixelCollector(w.width, w.height)
        draw_grayscale_heightmap(w, target)
        self._assert_img_equal("grayscale_heightmap_28070", target)

    def test_draw_ocean(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        target = PixelCollector(w.width, w.height)
        draw_ocean(w.ocean, target)
        self._assert_img_equal("ocean_28070", target)

    def test_draw_precipitation(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        target = PixelCollector(w.width, w.height)
        draw_precipitation(w, target)
        self._assert_img_equal("precipitation_28070", target)

    def test_draw_world(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        target = PixelCollector(w.width, w.height)
        draw_world(w, target)
        self._assert_img_equal("world_28070", target)

    def test_draw_temperature_levels(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        target = PixelCollector(w.width, w.height)
        draw_temperature_levels(w, target)
        self._assert_img_equal("temperature_28070", target)

    def test_draw_biome(self):
        w = World.open_protobuf("%s/seed_28070.world" % self.tests_data_dir)
        target = PixelCollector(w.width, w.height)
        draw_biome(w, target)
        self._assert_img_equal("biome_28070", target)

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


text:
import { module, test } from 'qunit';
import { assertionInjector } from '../assertions';

module('assertions', {
  beforeEach() {
    assertionInjector();
  }
});

test('can inject custom assertions', function(assert) {
  assert.expect(2);

  assert.doubleTrouble();
});


text:
package fpinscala.gettingstarted

// A comment!
/* Another comment */
/** A documentation comment */
object MyModule {
  def abs(n: Int): Int =
    if (n < 0) -n
    else n

  private def formatAbs(x: Int) = {
    val msg = "The absolute value of %d is %d"
    msg.format(x, abs(x))
  }

  def main(args: Array[String]): Unit = {
    println(formatAbs(-42))
    (0 to 10).foreach(n => println(fib(n)))
  }

  // A definition of factorial, using a local, tail recursive function
  def factorial(n: Int): Int = {
    @annotation.tailrec
    def go(n: Int, acc: Int): Int =
      if (n <= 0) acc
      else go(n-1, n*acc)

    go(n, 1)
  }

  // Another implementation of `factorial`, this time with a `while` loop
  def factorial2(n: Int): Int = {
    var acc = 1
    var i = n
    while (i > 0) { acc *= i; i -= 1 }
    acc
  }

  // Exercise 1: Write a function to compute the nth fibonacci number

  def fib(n: Int): Int = {
    @annotation.tailrec
    def loop(prev: Int, cur: Int, n: Int): Int = {
      if (n == 0) cur + prev
      else loop(cur, prev + cur, n - 1)
    }
    loop(1, 0, n)
  }

  // This definition and `formatAbs` are very similar..
  private def formatFactorial(n: Int) = {
    val msg = "The absolute value of %d is %d."
    msg.format(n, factorial(n))
  }

  // We can generalize `formatAbs` and `formatFactorial` to
  // accept a _function_ as a parameter
  def formatResult(name: String, n: Int, f: Int => Int) = {
    val msg = "The %s of %d is %d."
    msg.format(name, n, f(n))
  }
}

object FormatAbsAndFactorial {

  import MyModule._

  // Now we can use our general `formatResult` function
  // with both `abs` and `factorial`
  def main(args: Array[String]): Unit = {
    println(formatResult("absolute value", -42, abs))
    println(formatResult("factorial", 7, factorial))
  }
}

// Functions get passed around so often in FP that it's
// convenient to have syntax for constructing a function
// *without* having to give it a name
object AnonymousFunctions {
  import MyModule._

  // Some examples of anonymous functions:
  def main(args: Array[String]): Unit = {
    println(formatResult("absolute value", -42, abs))
    println(formatResult("factorial", 7, factorial))
    println(formatResult("increment", 7, (x: Int) => x + 1))
    println(formatResult("increment2", 7, (x) => x + 1))
    println(formatResult("increment3", 7, x => x + 1))
    println(formatResult("increment4", 7, _ + 1))
    println(formatResult("increment5", 7, x => { val r = x + 1; r }))
  }
}

object MonomorphicBinarySearch {

  // First, a binary search implementation, specialized to `Double`,
  // another primitive type in Scala, representing 64-bit floating
  // point numbers
  // Ideally, we could generalize this to work for any `Array` type,
  // so long as we have some way of comparing elements of the `Array`
  def binarySearch(ds: Array[Double], key: Double): Int = {
    @annotation.tailrec
    def go(low: Int, mid: Int, high: Int): Int = {
      if (low > high) -mid - 1
      else {
        val mid2 = (low + high) / 2
        val d = ds(mid2) // We index into an array using the same
                         // syntax as function application
        if (d == key) mid2
        else if (d > key) go(low, mid2, mid2-1)
        else go(mid2 + 1, mid2, high)
      }
    }
    go(0, 0, ds.length - 1)
  }

}

object PolymorphicFunctions {

  def main(args: Array[String]): Unit = {
    def gt(a: Int, b: Int) = a > b

    println(isSorted(Array(1,2,3,4), gt))

    println(isSorted(Array(1,3,2,3,4), gt))

    println(isSorted(Array(1,2,4,3), gt))

  }

  // Here's a polymorphic version of `binarySearch`, parameterized on
  // a function for testing whether an `A` is greater than another `A`.
  def binarySearch[A](as: Array[A], key: A, gt: (A,A) => Boolean): Int = {
    @annotation.tailrec
    def go(low: Int, mid: Int, high: Int): Int = {
      if (low > high) -mid - 1
      else {
        val mid2 = (low + high) / 2
        val a = as(mid2)
        val greater = gt(a, key)
        if (!greater && !gt(key,a)) mid2
        else if (greater) go(low, mid2, mid2-1)
        else go(mid2 + 1, mid2, high)
      }
    }
    go(0, 0, as.length - 1)
  }

  // Exercise 2: Implement a polymorphic function to check whether
  // an `Array[A]` is sorted
  def isSorted[A](as: Array[A], gt: (A,A) => Boolean): Boolean = {
    @annotation.tailrec
    def loop(n: Int): Boolean = {
      if (n == as.length) true
      else if (gt(as(n), as(n-1))) loop(n + 1)
      else false
    }

    // zero or one elements is considered sorted
    if (as.length < 2) true
    else loop(1)
  }

  // Polymorphic functions are often so constrained by their type
  // that they only have one implementation! Here's an example:

  def partial1[A,B,C](a: A, f: (A,B) => C): B => C =
    (b: B) => f(a, b)

  // Exercise 3: Implement `curry`.

  // Note that `=>` associates to the right, so we could
  // write the return type as `A => B => C`
  def curry[A,B,C](f: (A, B) => C): A => (B => C) =
    (a) => ((b) => f(a, b))

  // NB: The `Function2` trait has a `curried` method already

  // Exercise 4: Implement `uncurry`
  def uncurry[A,B,C](f: A => B => C): (A, B) => C =
    (a, b) => f(a)(b)

  /*
  NB: There is a method on the `Function` object in the standard library,
  `Function.uncurried` that you can use for uncurrying.

  Note that we can go back and forth between the two forms. We can curry
  and uncurry and the two forms are in some sense "the same". In FP jargon,
  we say that they are _isomorphic_ ("iso" = same; "morphe" = shape, form),
  a term we inherit from category theory.
  */

  // Exercise 5: Implement `compose`

  def compose[A,B,C](f: B => C, g: A => B): A => C =
    a => f(g(a))
}


text:
package com.martinvana.random_number_generator.statistics.histogram;

public interface IHistogram {
    void push(double x);

    void reset();

    void reset(int buckets, double minV, double maxV);
}


text:
namespace eja
{
	class entity;

	class message_unpacker final : public message_list
	{
		make_factory(message_unpacker);

	public:
		message_unpacker() { }
		message_unpacker(const message_unpacker& comp) : message_list(comp) { }
		template <typename T> message_unpacker(const T& t) { push_back(t); }

		// Operator
		template <typename T> message_unpacker& operator=(const T& t);

		// Utility
		bool valid() const { return !empty(); }
		bool empty() const { return message_list::empty(); }

		void unpack(const void* input, const size_t input_size);
		void unpack(const std::string& input) { return unpack(input.c_str(), input.size()); }
		void unpack(const char* input) { return unpack(input, strlen(input)); }

		// Static
		template <typename T> static ptr create(const T& t);
	};

	// Operator
	template <typename T>
	message_unpacker& message_unpacker::operator=(const T& t)
	{
		assign(1, t);

		return *this;
	}

	// Static
	template <typename T>
	message_unpacker::ptr message_unpacker::create(const T& t)
	{
		const auto packer = std::make_shared<message_unpacker>();
		packer->push_back(t);

		return packer;
	}
}

#endif


text:
<?php

class Google_Service_Datastore_BeginTransactionRequest extends Google_Model
{
}


text:
void sq1_executeOnMainThread(void (^block)())
{
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    dispatch_queue_set_specific(dispatch_get_main_queue(), &onceToken, &onceToken, NULL);
  });

  if (dispatch_get_specific(&onceToken) == &onceToken) {
    block();
  } else {
    dispatch_async(dispatch_get_main_queue(), block);
  }
}


text:
# jscodeshift [![Build Status](https://travis-ci.org/facebook/jscodeshift.svg?branch=master)](https://travis-ci.org/facebook/jscodeshift)

jscodeshift is a toolkit for running codemods over multiple JS files.
It provides:

- A runner, which executes the provided transform for each file passed to it.
  It also outputs a summary of how many files have (not) been transformed.
- A wrapper around [recast][], providing a different API.  Recast is an
  AST-to-AST transform tool and also tries to preserve the style of original code
  as much as possible.

## Install

Get jscodeshift from [npm][]:

```
$ npm install -g jscodeshift
```

This will install the runner as `jscodeshift`.

## Usage (CLI)

The CLI provides the following options:

```text
$ jscodeshift --help

Usage: jscodeshift <path>... [options]

path     Files or directory to transform

Options:
   -t FILE, --transform FILE   Path to the transform file  [./transform.js]
   -c, --cpus                  (all by default) Determines the number of processes started.
   -v, --verbose               Show more information about the transform process  [0]
   -d, --dry                   Dry run (no changes are made to files)
   -p, --print                 Print output, useful for development
   --babel                     Apply Babel to transform files  [true]
   --extensions                File extensions the transform file should be applied to  [js]
```

This passes the source of all passed through the transform module specified
with `-t` or `--transform` (defaults to `transform.js` in the current
directory). The next section explains the structure of the transform module.

## Transform module

The transform is simply a module that exports a function of the form:

```js
module.exports = function(fileInfo, api, options) {
  // transform `fileInfo.source` here
  // ...
  // return changed source
  return source;
};
```

### Arguments

#### `fileInfo`

Holds information about the currently processed file.

Property    | Description
------------|------------
path        | File path
source      | File content

#### `api`

This object exposes the `jscodeshift` library and helper functions from the
runner.

Property    | Description
------------|------------
jscodeshift | A reference to the jscodeshift library
stats       | A function to collect statistics during `--dry` runs

`jscodeshift` is a reference to the wrapper around recast and provides a
jQuery-like API to navigate and transform the AST. Here is a quick example,
a more detailed description can be found below.

```js
/**
 * This replaces every occurence of variable "foo".
 */
module.exports = function(fileInfo, api) {
  return api.jscodeshift(fileInfo.source)
    .findVariableDeclarators('foo')
    .renameTo('bar')
    .toSource();
}
```

**Note:** This api is exposed for convenience, but you don't have to use it.
You can use any tool to modify the source.

`stats` is a function that only works when the `--dry` options is set. It accepts
a string, and will simply count how often it was called with that value.

At the end, the CLI will report those values. This can be useful while
developing the transform, e.g. to find out how often a certain construct
appears in the source(s).

#### `options`

Contains all options that have been passed to runner. This allows you to pass
additional options to the transform. For example, if the CLI is called with

```
$ jscodeshift -t myTransforms fileA fileB --foo=bar
```

`options` would contain `{foo: 'bar'}`. jscodeshift uses [nomnom][] to parse
command line options.

#### Return value

The return value of the function determines the status of the transformation:

- If a string is returned and it is different from passed source, the
  transform is considered to be successful.
- If a string is returned but it's the same as the source, the transform
  is considered to be unsuccessful.
- If nothing is returned, the file is not supposed to be transformed (which is
  ok).

The CLI provides a summary of the transformation at the end. You can get more
detailed information by setting the `-v` option to `1` or `2`.

You can collect even more stats via the `stats` function as explained above.

### Example

```text
$ jscodeshift -t myTransform.js src
Processing 10 files...
Spawning 2 workers with 5 files each...
All workers done.
Results: 0 errors 2 unmodifed 3 skipped 5 ok
```

## The jscodeshift API

As already mentioned, jscodeshift also provides a wrapper around [recast][].
In order to properly use the jscodeshift API, one has to understand the basic
building blocks of recast (and ASTs) as well.

### Core Concepts

#### AST nodes

An AST node is a plain JavaScript object with a specific set of fields, in
accordance with the [Mozilla Parser API][]. The primary way to identify nodes
is via their `type`.

For example, string literals are represented via `Literal` nodes, which
have the structure

```js
// "foo"
{
  type: 'Literal',
  value: 'foo',
  raw: '"foo"'
}
```

It's OK to not know the structure of every AST node type.
The [(esprima) AST explorer][ast-explorer] is an online tool to inspect the AST
for a given piece of JS code.

#### Path objects

Recast itself relies heavily on [ast-types][] which defines methods to traverse
the AST, access node fields and build new nodes. ast-types wraps every AST node
into a *path object*. Paths contain meta-information and helper methods to
process AST nodes.

For example, the child-parent relationship between two nodes is not explicitly
defined. Given a plain AST node, it is not possible to traverse the tree *up*.
Given a path object however, the parent can be traversed to via `path.parent`.

For more information about the path object API, please have a look at
[ast-types][].

#### Builders

To make creating AST nodes a bit simpler and "safer", ast-types defines a couple
of *builder methods*, which are also exposed on `jscodeshift`.

For example, the following creates an AST equivalent to `foo(bar)`:

```js
// inside a module transform
var j = jscodeshift;
// foo(bar);
var ast = j.callExpression(
  j.identifier('foo'),
  [j.identifier('bar')]
);
```

The signature of each builder function is best learned by having a look at the
[definition files](https://github.com/benjamn/ast-types/blob/master/def/).

### Collections and Traversal

In order to transform the AST, you have to traverse it and find the nodes that
need to be changed. jscodeshift is built around the idea of **collections** of
paths and thus provides a different way of processing an AST than recast or
ast-types.

A collection has methods to process the nodes inside a collection, often
resulting in a new collection. This results in a fluent interface, which can
make the transform more readable.

Collections are "typed" which means that the type of a collection is the
"lowest" type all AST nodes in the collection have in common. That means you
cannot call a method for a `FunctionExpression` collection on a `Identifier`
collection.

Here is an example of how one would find/traverse all `Identifier` nodes with
jscodeshift and with recast:

```js
// recast
var ast = recast.parse(src);
recast.visit(ast, {
  visitIdentifier: function(path) {
    // do something with path
    return false;
  }
});

// jscodeshift
jscodeshift(src)
  .find(jscodeshift.Identifier)
  .forEach(function(path) {
    // do something with path
  });
```

To learn about the provided methods, have a look at the
[Collection.js](src/Collection.js) and its [extensions](src/collections/).

### Extensibility

jscodeshift provides an API to extend collections. By moving common operators
into helper functions (which can be stored separately in other modules), a
transform can be made more readable.

There are two types of extensions: generic extensions and type-specific
extensions. **Generic extensions** are applicable to all collections. As such,
they typically don't access specific node data, but rather traverse the AST from
the nodes in the collection. **Type-specific** extensions work only on specific
node types and are not callable on differently typed collections.

#### Examples

```js
// Adding a method to all Identifiers
jscodeshift.registerMethods({
	logNames: function() {
		return this.forEach(function(path) {
			console.log(path.node.name);
		});
	}
}, jscodeshift.Identifier);

// Adding a method to all collections
jscodeshift.registerMethods({
	findIdentifiers: function() {
		return this.find(jscodeshift.Identifier);
	}
});

jscodeshift(ast).findIdentifiers().logNames();
jscodeshift(ast).logNames(); // error, unless `ast` only consists of Identifier nodes
```

[npm]: https://www.npmjs.com/
[Mozilla Parser API]: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API
[recast]: https://github.com/benjamn/recast
[ast-types]: https://github.com/benjamn/ast-types
[ast-explorer]: http://felix-kling.de/esprima_ast_explorer/
[nomnom]: https://www.npmjs.com/package/nomnom


text:
class A{
private static class B{}
}

class C extends A.<caret>B{}


text:
const cityFunctions = require('./db/cities')

module.exports = {
  findCityById: cityFunctions.findCityById
}


text:
using System;
using Newtonsoft.Json.Linq;
using Skybrud.Integrations.BorgerDk;
using Skybrud.Umbraco.BorgerDk.Notifications;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Serialization;

#pragma warning disable 1591

namespace Skybrud.Umbraco.BorgerDk.Caching {

    /// <summary>
    /// Cache refresher for <see cref="BorgerDkCache"/>.
    /// </summary>
    public class BorgerDkCacheRefresher : PayloadCacheRefresherBase<BorgerDkCacheRefresherNotification, BorgerDkCacheRefresher.JsonPayload> {

        private readonly BorgerDkService _borgerDkService;
        private readonly BorgerDkCache _borgerDkCache;

        #region Properties

        /// <summary>
        /// Gets the unique ID associated with this cache refresher.
        /// </summary>
        public static readonly Guid UniqueId = Guid.Parse("1F28970B-746B-451A-9B57-7A8AD394F1C8");

        /// <summary>
        /// Gets the unique ID associated with this cache refresher.
        /// </summary>
        public override Guid RefresherUniqueId => UniqueId;

        /// <summary>
        /// gets the name of this cache refresher.
        /// </summary>
        public override string Name => "BorgerDkCacheRefresher";

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance based on the specified DI dependencies.
        /// </summary>
        public BorgerDkCacheRefresher(AppCaches appCaches,
            IJsonSerializer jsonSerializer,
            IEventAggregator eventAggregator,
            ICacheRefresherNotificationFactory factory,
            BorgerDkService borgerDkService,
            BorgerDkCache borgerDkCache) : base(appCaches, jsonSerializer, eventAggregator, factory) {
            _borgerDkService = borgerDkService;
            _borgerDkCache = borgerDkCache;
        }

        #endregion

        #region Member methods

        /// <inheritdoc/>
        public override void RefreshAll() {
            Console.WriteLine("RefreshAll()");
            _borgerDkCache.RefreshAll();
        }

        /// <inheritdoc/>
        public override void Refresh(string json) {

            Console.WriteLine("Refresh(string)");

            var payloads = Deserialize(json);

            foreach (JsonPayload payload in payloads) {

                string uniqueId = BorgerDkUtils.GetUniqueId(payload.Domain, payload.Municipality, payload.ArticleId);

                Console.WriteLine($"BorgerDkCacheRefresher received payload that {uniqueId} was updated.");

                BorgerDkArticle article = _borgerDkService.GetArticleById(payload.Domain, payload.Municipality, payload.ArticleId);

                if (article == null) {
                    Console.WriteLine(" - Article not found in database");
                } else {
                    Console.WriteLine(" - Article found in the database.");
                    _borgerDkCache.AddOrUpdate(article);
                }

            }

        }

        /// <inheritdoc/>
        public override void Refresh(JsonPayload[] payloads) {

            Console.WriteLine("Refresh(payloads)");

            foreach (JsonPayload payload in payloads) {

                Console.WriteLine(payload.GetType());
                Console.WriteLine(JObject.FromObject(payload));

                string uniqueId = BorgerDkUtils.GetUniqueId(payload.Domain, payload.Municipality, payload.ArticleId);

                Console.WriteLine($"BorgerDkCacheRefresher received payload that {uniqueId} was updated.");

                BorgerDkArticle article = _borgerDkService.GetArticleById(payload.Domain, payload.Municipality, payload.ArticleId);

                if (article == null) {
                    Console.WriteLine(" - Article not found in database");
                } else {
                    Console.WriteLine(" - Article found in the database.");
                    _borgerDkCache.AddOrUpdate(article);
                }

            }

        }

        #endregion

        public class JsonPayload {

            public string Domain { get; }

            public int Municipality { get; }

            public int ArticleId { get; }

            public JsonPayload(string domain, int municipality, int articleId) {
                Domain = domain;
                Municipality = municipality;
                ArticleId = articleId;
            }

            public JsonPayload(BorgerDkArticle article) {
                Domain = article.Domain;
                Municipality = article.Municipality.Code;
                ArticleId = article.Id;
            }

        }

    }

}


text:
require File.expand_path('../spec_helper', File.dirname(__FILE__))

module Redex
  describe MatchList do
    before :each do
      dictionary_path = File.expand_path("spec/dictionary_files/cast")
      doc_path = File.expand_path("spec/document_files/episodes.txt")

      @dict = Redex::Dictionary.import(dictionary_path)
      @doc = Redex::Document.import(doc_path, :type => :episode_doc)

      @mac_item = @dict.items.select { |item| item.value == "Mac" }.first
      @dennis_item = @dict.items.select { |item| item.value == "Dennis" }.first
      @frank_item = @dict.items.select { |item| item.value == "Frank" }.first
      @dee_item = @dict.items.select { |item| item.value == "Dee" }.first

      @first_match = SectionMatch.new(@frank_item, @doc.line(1), :episode_section)
      @first_match.location = :start
      @second_match = ContentMatch.new(@mac_item, @doc.line(2), :episode_content)
      @third_match = ContentMatch.new(@dennis_item, @doc.line(2), :other_content)
      @fourth_match = SectionMatch.new(@dee_item, @doc.line(6), :episode_section)
      @fourth_match.location = :end

      @matches = MatchList.new
      @matches << @first_match
      @matches << @second_match
      @matches << @third_match
      @matches << @fourth_match
    end

    describe "#of_class" do
      before(:each) { @content_matches = @matches.of_class ContentMatch }
      it "should return only matches of the specified class" do
        @content_matches.length.should == 2
        @content_matches.all? { |match| match.should be_a ContentMatch }
      end

      it "should return a MatchList object" do
        @content_matches.should be_a MatchList
      end
    end

    describe "#of_type" do
      before(:each) { @episode_content_matches = @matches.of_type :episode_content }
      it "should return only matches for the specified content type" do
        @episode_content_matches.size.should == 1
        @episode_content_matches.first.type.should == :episode_content
      end

      it "should return a MatchList object" do
        @episode_content_matches.should be_a MatchList
      end
    end

    describe "#at_location" do
      before(:each) { @start_matches = @matches.at_location :start }
      it "should return matches signaling the start of a section" do
        @start_matches.size.should == 1
        @start_matches.first.location.should == :start
      end

      it "should return a MatchList object" do
        @start_matches.should be_a MatchList
      end
    end
  end
end


text:
Home

WYSIWYG Summernote

WYSIWYG Summernote

Summernote WYSIWYG Editor

						Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with
						my name printed on it? Do you see a little Asian child with a blank expression on his face
						sitting outside on a mechanical helicopter that shakes when you put quarters in it? No?
						Well, that's what you see at a toy store. And you must think you're in a toy store, because
						you're here shopping for an infant named Jeb.

						Do you see a little Asian child with a blank expression on his face
						sitting outside on a mechanical helicopter that shakes when you put quarters in it? No?
						Well, that's what you see at a toy store. And you must think you're in a toy store, because
						you're here shopping for an infant named Jeb.

						Well, that's what you see at a toy store. And you must think you're in a toy store, because
						you're here shopping for an infant named Jeb. Do you see a slender plastic tag clipped to my
						shirt with my name printed on it? Do you see a little Asian child with a blank expression on
						his face sitting outside on a mechanical helicopter that shakes when you put quarters in it?


text:
<ng-template tdLoading="project.load">
  <md-card *ngIf="project">
    <md-card-title>{{ project.title }}</md-card-title>
    <md-card-subtitle>{{ project.words | digits }} words / {{ project.documents }} documents</md-card-subtitle>
    <md-divider></md-divider>
    <md-list>
      <md-list-item>
        <md-icon md-list-avatar>description</md-icon>

Summary

{{ project.summary }}

      </md-list-item>
      <md-divider md-inset></md-divider>
      <md-list-item>
        <md-icon md-list-avatar>access_time</md-icon>

{{ project.updated_date | timeAgo }}

Last Updated

      </md-list-item>
      <md-divider md-inset></md-divider>
      <md-list-item>
        <md-icon md-list-avatar>today</md-icon>

{{ project.created_date | timeAgo }}

Created

      </md-list-item>
    </md-list>
    <md-divider></md-divider>
    <md-card-actions>

        <button md-button color="primary" class="text-upper" [routerLink]="['/editor', project.id]">
          <md-icon>folder_open</md-icon> Open Project
        </button>

        <button md-button color="accent" class="text-upper" [routerLink]="['/projects', project.id, 'edit']">
          <md-icon>edit</md-icon>
          Edit
        </button>
        <button md-button color="warn" class="text-upper" (click)="deleteProject()">
          <md-icon>delete</md-icon>
          Delete
        </button>

    </md-card-actions>
  </md-card>
</ng-template>


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>System DataSource</title>

System DataSource

PV syntax

        The standard prefix for the datasource is sys:// which can be omitted if configured as the default datasource.

Syntax	Description

sys://time	Local date and time

sys://free_mb	Free Java VM memory in MB

sys://used_mb	Used Java VM memory in MB

sys://max_mb	Maximum available Java VM memory in MB

sys://user	User Name

sys://host_name	Host name

sys://qualified_host_name	Full Host Name

sys://system.*	Any system property, e.g. "sys://system.user.name"


text:
/*
 * generated by Xtext
 */
package at.fhj.gaar.androidapp.ui;

import org.eclipse.xtext.ui.guice.AbstractGuiceAwareExecutableExtensionFactory;
import org.osgi.framework.Bundle;

import com.google.inject.Injector;

import at.fhj.gaar.androidapp.ui.internal.AppDslActivator;

/**
 * This class was generated. Customizations should only happen in a newly
 * introduced subclass.
 */
public class AppDslExecutableExtensionFactory extends AbstractGuiceAwareExecutableExtensionFactory {

	@Override
	protected Bundle getBundle() {
		return AppDslActivator.getInstance().getBundle();
	}

	@Override
	protected Injector getInjector() {
		return AppDslActivator.getInstance().getInjector(AppDslActivator.AT_FHJ_GAAR_ANDROIDAPP_APPDSL);
	}

}


text:
package org.openforis.collect.earth.app.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openforis.collect.earth.app.EarthConstants;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Abstract class containing common methods for servlets using JSon communication.
 * @author Alfonso Sanchez-Paus Diaz
 *
 */
public abstract class JsonPocessorServlet extends DataAccessingServlet {
	Gson gson = new GsonBuilder().create();

	protected Map<String, String> extractRequestData(HttpServletRequest request) {
		Map<String, String> collectedData = new HashMap<>();

		Enumeration<String> enParams = request.getParameterNames();
		while (enParams.hasMoreElements()) {

			String paramName = enParams.nextElement();
			String[] values = request.getParameterValues(paramName);
			if (values.length == 1) {
				collectedData.put(paramName, values[0]);
			} else {
				int i = 1;
				for (String val : values) {
					collectedData.put(paramName + "_" + i, val); //$NON-NLS-1$
					i++;
				}
			}
		}
		return collectedData;
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {

	}

	protected void setJsonResponse(HttpServletResponse response, Map<String, ? extends Object> collectedData) throws IOException {
		setResponseHeaders(response);
		PrintWriter out = response.getWriter();
		if (collectedData != null && collectedData.size() > 0) {
			String json = gson.toJson(collectedData);
			out.println(json);
		}
		out.close();
	}

	protected void setJsonResponse(HttpServletResponse response, Object data) throws IOException {
		setResponseHeaders(response);
		PrintWriter out = response.getWriter();
		if (data != null) {
			String json = gson.toJson(data);
			out.println(json);
		}
		out.close();
	}

	private void setResponseHeaders(HttpServletResponse response) {
		response.setContentType("application/json"); //$NON-NLS-1$
		response.setStatus(HttpServletResponse.SC_OK);
		response.setHeader("Cache-control", "no-cache, no-store"); //$NON-NLS-1$ //$NON-NLS-2$
		response.setHeader("Pragma", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
		response.setHeader("Expires", "-1"); //$NON-NLS-1$ //$NON-NLS-2$
		response.setHeader("Date", new SimpleDateFormat(EarthConstants.DATE_FORMAT_HTTP, Locale.ENGLISH).format(new Date())); //$NON-NLS-1$
		response.setHeader("Access-Control-Allow-Origin", "*"); //$NON-NLS-1$ //$NON-NLS-2$
		response.setHeader("Access-Control-Allow-Methods", "POST"); //$NON-NLS-1$ //$NON-NLS-2$
		response.setHeader("Access-Control-Allow-Headers", "Content-Type"); //$NON-NLS-1$ //$NON-NLS-2$
		response.setHeader("Access-Control-Max-Age", "86400"); //$NON-NLS-1$ //$NON-NLS-2$
	}

	protected void setResult(boolean success, String message, Map<String, String> collectedData) {
		collectedData.put("type", success ? "success" : "error"); // success,error,warning //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		collectedData.put("message", message); //$NON-NLS-1$
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
              version="2.2">

    <application>
        <locale-config>
            <default-locale>en</default-locale>
        </locale-config>
        <resource-bundle>
            <base-name>messages</base-name>
            <var>i18n</var>
        </resource-bundle>
    </application>
</faces-config>


text:
{% extends 'share_layout/base.html' %}
{% load blog_tags %}
{% load cache %}
{% block header %}
    {% if tag_name %}
        {% if statuscode == '404' %}
            <title>404 NotFound</title>
        {% elif statuscode == '403' %}
            <title>Permission Denied</title>
        {% elif statuscode == '500' %}
            <title>500 Error</title>
        {% else %}
            <title></title>
        {% endif %}
        {% comment %}<meta name="description" content="{{ page_type }}:{{ tag_name }}"/>{% endcomment %}
    {% else %}
        <title>{{ SITE_NAME }} | {{ SITE_DESCRIPTION }}</title>
    {% endif %}
    <meta name="description" content="{{ SITE_SEO_DESCRIPTION }}"/>
    <meta name="keywords" content="{{ SITE_KEYWORDS }}"/>
    <meta property="og:type" content="blog"/>
    <meta property="og:title" content="{{ SITE_NAME }}"/>
    <meta property="og:description" content="{{ SITE_DESCRIPTION }}"/>
    <meta property="og:url" content="{{ SITE_BASE_URL }}"/>
    <meta property="og:site_name" content="{{ SITE_NAME }}"/>
{% endblock %}
{% block content %}

{{ message }}

{% endblock %}

{% block sidebar %}
    {% load_sidebar user 'i' %}
{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
	<soap:Body>
		<FooResponse xmlns="http://www.friendly-tech.com">
			<FooResult>
				<result xmlns="http://www.friendly-tech.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
					<response_code>200</response_code>
					<error_code>201</error_code>
					<message>error</message>
				</result>
			</FooResult>
		</FooResponse>
	</soap:Body>
</soap:Envelope>


text:
Please notice that the `%` operator is not equivalent to the one described in the problem description
([see Wikipedia entry for Modulo operation](https://en.wikipedia.org/wiki/Modulo_operation)).


text:
Note from Ixcoin Core developers...

	Everything in this directory is under review, portions have been changed, however the work is incomplete, and it's content and/or functionality under review.


text:
FROM debian:jessie

ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && \
    apt-get install -y build-essential && \
    apt-get clean


text:
// Provides the base implementation for all model implementations
sap.ui.define(['jquery.sap.global', 'sap/ui/core/format/NumberFormat', 'sap/ui/model/CompositeType', 'sap/ui/model/FormatException', 'sap/ui/model/ParseException', 'sap/ui/model/ValidateException'],
	function(jQuery, NumberFormat, CompositeType, FormatException, ParseException, ValidateException) {
	"use strict";

	/**
	 * Constructor for a Currency type.
	 *
	 * @class
	 * This class represents the currency composite type.
	 *
	 * @extends sap.ui.model.CompositeType
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @public
	 * @param {object} [oFormatOptions] Formatting options. For a list of all available options, see {@link sap.ui.core.format.NumberFormat#constructor NumberFormat}.
	 * @param {object} [oFormatOptions.source] Additional set of format options to be used if the property in the model is not of type string and needs formatting as well.
	 * 										   If an empty object is given, the grouping is disabled and a dot is used as decimal separator.
	 * @param {object} [oConstraints] Value constraints
	 * @param {float} [oConstraints.minimum] Smallest value allowed for this type
	 * @param {float} [oConstraints.maximum] Largest value allowed for this type
	 * @alias sap.ui.model.type.Currency
	 */
	var Currency = CompositeType.extend("sap.ui.model.type.Currency", /** @lends sap.ui.model.type.Currency.prototype  */ {

		constructor : function () {
			CompositeType.apply(this, arguments);
			this.sName = "Currency";
			this.bUseRawValues = true;
		}

	});

	/**
	 * Format the given array containing amount and currency code to an output value of type string.
	 * Other internal types than 'string' are not supported by the Currency type.
	 * If a source format has been defined for this type, the formatValue does also accept
	 * a string value as input, which will be parsed into an array using the source format.
	 * If aValues is not defined or null, null will be returned.
	 *
	 * @function
	 * @name sap.ui.model.type.Currency.prototype.formatValue
	 * @param {array|string} vValue the array of values or string value to be formatted
	 * @param {string} sInternalType the target type
	 * @return {any} the formatted output value
	 *
	 * @public
	 */
	Currency.prototype.formatValue = function(vValue, sInternalType) {
		var aValues = vValue;
		if (vValue == undefined || vValue == null) {
			return null;
		}
		if (this.oInputFormat) {
			aValues = this.oInputFormat.parse(vValue);
		}
		if (!Array.isArray(aValues)) {
			throw new FormatException("Cannot format currency: " + vValue + " has the wrong format");
		}
		if (aValues[0] == undefined || aValues[0] == null) {
			return null;
		}
		switch (this.getPrimitiveType(sInternalType)) {
			case "string":
				return this.oOutputFormat.format(aValues);
			case "int":
			case "float":
			case "any":
			default:
				throw new FormatException("Don't know how to format currency to " + sInternalType);
		}
	};

	/**
	 * Parse a string value to an array containing amount and currency. Parsing of other
	 * internal types than 'string' is not supported by the Currency type.
	 * In case a source format has been defined, after parsing the currency is formatted
	 * using the source format and a string value is returned instead.
	 *
	 * @function
	 * @name sap.ui.model.type.Currency.prototype.parseValue
	 * @param {any} vValue the value to be parsed
	 * @param {string} sInternalType the source type
	 * @param {array} aCurrentValues the current values of all binding parts
	 * @return {array|string} the parse result array
	 *
	 * @public
	 */
	Currency.prototype.parseValue = function(vValue, sInternalType) {
		var vResult, oBundle;
		switch (this.getPrimitiveType(sInternalType)) {
			case "string":
				vResult = this.oOutputFormat.parse(vValue);
				if (!Array.isArray(vResult)) {
					oBundle = sap.ui.getCore().getLibraryResourceBundle();
					throw new ParseException(oBundle.getText("Currency.Invalid", [vValue]));
				}
				break;
			case "int":
			case "float":
			default:
				throw new ParseException("Don't know how to parse Currency from " + sInternalType);
		}
		if (this.oInputFormat) {
			vResult = this.oInputFormat.format(vResult);
		}
		return vResult;
	};

	Currency.prototype.validateValue = function(vValue) {
		if (this.oConstraints) {
			var oBundle = sap.ui.getCore().getLibraryResourceBundle(),
				aViolatedConstraints = [],
				aMessages = [],
				aValues = vValue,
				iValue;
			if (this.oInputFormat) {
				aValues = this.oInputFormat.parse(vValue);
			}
			iValue = aValues[0];
			jQuery.each(this.oConstraints, function(sName, oContent) {
				switch (sName) {
					case "minimum":
						if (iValue < oContent) {
							aViolatedConstraints.push("minimum");
							aMessages.push(oBundle.getText("Currency.Minimum", [oContent]));
						}
						break;
					case "maximum":
						if (iValue > oContent) {
							aViolatedConstraints.push("maximum");
							aMessages.push(oBundle.getText("Currency.Maximum", [oContent]));
						}
				}
			});
			if (aViolatedConstraints.length > 0) {
				throw new ValidateException(aMessages.join(" "), aViolatedConstraints);
			}
		}
	};

	Currency.prototype.setFormatOptions = function(oFormatOptions) {
		this.oFormatOptions = oFormatOptions;
		this._createFormats();
	};

	/**
	 * Called by the framework when any localization setting changed
	 * @private
	 */
	Currency.prototype._handleLocalizationChange = function() {
		this._createFormats();
	};

	/**
	 * Create formatters used by this type
	 * @private
	 */
	Currency.prototype._createFormats = function() {
		var oSourceOptions = this.oFormatOptions.source;
		this.oOutputFormat = NumberFormat.getCurrencyInstance(this.oFormatOptions);
		if (oSourceOptions) {
			if (jQuery.isEmptyObject(oSourceOptions)) {
				oSourceOptions = {
					groupingEnabled: false,
					groupingSeparator: ",",
					decimalSeparator: "."
				};
			}
			this.oInputFormat = NumberFormat.getCurrencyInstance(oSourceOptions);
		}
	};

	return Currency;

});


text:
{% extends base_template %}

{% block content %}

Model display page.

{% endblock %}


text:
package com.planet_ink.coffee_mud.Abilities.Properties;

import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Prop_ClanEquipment extends Property implements TriggeredAffect
{
	@Override
	public String ID()
	{
		return "Prop_ClanEquipment";
	}

	@Override
	public String name()
	{
		return "Clan Equipment";
	}

	@Override
	public boolean bubbleAffect()
	{
		return true;
	}

	@Override
	public long flags()
	{
		return Ability.FLAG_CASTER;
	}

	@Override
	protected int canAffectCode()
	{
		return Ability.CAN_ITEMS;
	}

	protected boolean	activated		= false;
	protected String	type			= "";
	protected int		TypeOfEffect	= 0;
	protected int		WeaponType		= 0;
	protected int		PowerLevel		= 0;
	protected long		LastChecked		= 0;
	protected boolean	notAgain		= false;
	protected String	clanName		= "";
	protected String	clanType		= "";
	String				lastMessage		= null;
	protected CharStats	EQadjCharStats	= null;
	protected String	secretWord		= CMProps.getAnyListFileValue(CMProps.ListFile.MAGIC_WORDS);

	@Override
	public int triggerMask()
	{
		if(affected instanceof Weapon)
			return TriggeredAffect.TRIGGER_HITTING_WITH;
		if(affected instanceof Armor)
			return TriggeredAffect.TRIGGER_BEING_HIT;
		return TriggeredAffect.TRIGGER_USE;
	}

	@Override
	public String accountForYourself()
	{
		// My slightly complicated way of showing the clan effect when ID'd
		final StringBuffer id=new StringBuffer(L("@x1 @x2 Bonus: ",clanType,clanName));
		if((affected instanceof Weapon)&&(!(affected instanceof Wand))&&(TypeOfEffect<1000))
		{
			id.append("Does "+(1*PowerLevel)+"-"+(6*PowerLevel)+" additional "+type.toLowerCase()+" damage.");
		}
		else
		if((affected instanceof Armor)&&(TypeOfEffect<1000)&&(!(affected instanceof Shield)))
		{
			id.append("Raises "+type.toLowerCase()+" resistance by "+(PowerLevel*5)+".");
		}
		if((affected instanceof Armor)&&(TypeOfEffect<1000)&&(affected instanceof Shield))
		{
			id.append("Causes "+(1*PowerLevel)+"-"+(3*PowerLevel)+" "+type.toLowerCase()+" damage to melee attackers.");
		}
		if((affected instanceof Wand)&&(TypeOfEffect<1000))
		{
			id.append("Does "+(1*PowerLevel)+"-"+(6*PowerLevel)+" "+type.toLowerCase()+" damage when the user says `"+secretWord+"` to the target.");
		}
		return id.toString();
	}

	@Override
	public void setMiscText(String text)
	{
		super.setMiscText(text);
		final Vector<String> V=CMParms.parse(text);
		if(V.size()<4)
		{
			return;
		}
		type=V.elementAt(0);
		PowerLevel=Integer.valueOf(V.elementAt(1)).intValue();
		clanName=V.elementAt(2);
		clanType=V.elementAt(3);
		secretWord=getWandWord(text); // try to randomize the spell word a
										// little
		// Armor
		this.EQadjCharStats=(CharStats)CMClass.getCommon("DefaultCharStats");
		initAdjustments(EQadjCharStats);
		if(type.equalsIgnoreCase("PARALYSIS"))
		{
			TypeOfEffect=CMMsg.TYP_PARALYZE;
			WeaponType=Weapon.TYPE_STRIKING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_PARALYSIS,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("FIRE"))
		{
			TypeOfEffect=CMMsg.TYP_FIRE;
			WeaponType=Weapon.TYPE_BURNING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_FIRE,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("COLD"))
		{
			TypeOfEffect=CMMsg.TYP_COLD;
			WeaponType=Weapon.TYPE_FROSTING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_COLD,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("WATER"))
		{
			TypeOfEffect=CMMsg.TYP_WATER;
			WeaponType=Weapon.TYPE_SLASHING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_WATER,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("GAS"))
		{
			TypeOfEffect=CMMsg.TYP_GAS;
			WeaponType=Weapon.TYPE_GASSING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_GAS,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("MIND"))
		{
			TypeOfEffect=CMMsg.TYP_MIND;
			WeaponType=Weapon.TYPE_STRIKING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_MIND,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("ACID"))
		{
			TypeOfEffect=CMMsg.TYP_ACID;
			WeaponType=Weapon.TYPE_MELTING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_ACID,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("ELECTRIC"))
		{
			TypeOfEffect=CMMsg.TYP_ELECTRIC;
			WeaponType=Weapon.TYPE_BURNING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_ELECTRIC,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("POISON"))
		{
			TypeOfEffect=CMMsg.TYP_POISON;
			WeaponType=Weapon.TYPE_STRIKING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_POISON,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("DISEASE"))
		{
			TypeOfEffect=CMMsg.TYP_DISEASE;
			WeaponType=Weapon.TYPE_STRIKING;
			this.EQadjCharStats.setStat(CharStats.STAT_SAVE_DISEASE,PowerLevel*5);
		}
		else
		if(type.equalsIgnoreCase("HEALTH"))
		{
			TypeOfEffect=1001;
			WeaponType=Weapon.TYPE_BURSTING;
		}
		else
		if(type.equalsIgnoreCase("MAGIC"))
		{
			TypeOfEffect=1002;
			WeaponType=Weapon.TYPE_BURSTING;
		}
		else
		if(type.equalsIgnoreCase("SPEED"))
		{
			TypeOfEffect=1003;
		}
	}

	public boolean useAsWand(MOB mob, int level)
	{
		int manaRequired=50;
		// For simplicity, there's no charges BUT use costs a flat 10% mana
		manaRequired=(int)CMath.div(mob.maxState().getMana(),10);
		manaRequired-=(5*level);
		if(manaRequired<5)
			manaRequired=5;

		if(manaRequired>mob.curState().getMana())
		{
			mob.tell(L("You don't have enough mana."));
			return false;
		}
		mob.curState().adjMana(-manaRequired,mob.maxState());
		return true;
	}

	public static String getWandWord(String from)
	{
		int hash=from.hashCode();
		if(hash<0)
		{
			hash=hash*-1;
		}
		return CMProps.getListFileChoiceFromIndexedListByHash(CMProps.ListFile.MAGIC_WORDS,hash);
	}

	public boolean checkWave(MOB mob, String message, Wand me)
	{
		if((mob.isMine(me))&&(!me.amWearingAt(Wearable.IN_INVENTORY)))
		{
			final int x=message.toUpperCase().indexOf(secretWord.toUpperCase());
			return (x>=0);
		}
		return false;
	}

	/*
	 * ********************** Staff/Wand Clan Eq **********************
	 */
	public void waveIfAble(MOB mob, Environmental afftarget, String message, Wand me)
	{
		if((mob.isMine(me))&&(afftarget!=null)&&(afftarget instanceof MOB)&&(!me.amWearingAt(Wearable.IN_INVENTORY)))
		{
			MOB target=null;
			if((mob.location()!=null))
			{
				target=(MOB)afftarget;
			}
			final int x=message.toUpperCase().indexOf(secretWord.toUpperCase());
			if(x>=0)
			{
				message=message.substring(x+secretWord.length());
				final int y=message.indexOf('\'');
				if(y>=0)
				{
					message=message.substring(0,y);
				}
				message=message.trim();
				final Ability wandUse=mob.fetchAbility("Skill_WandUse");
				if((wandUse==null)||(!wandUse.proficiencyCheck(mob,0,false)))
				{
					mob.tell(L("@x1 glows faintly for a moment, then fades.",me.name()));
				}
				else
				{
					wandUse.setInvoker(mob);
					if(useAsWand(mob,wandUse.abilityCode()))
					{
						mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("@x1 glows brightly.",me.name()));
						final int flameDamage=CMLib.dice().roll(1,6*PowerLevel,1*PowerLevel);
						CMLib.combat().postDamage(mob,target,null,flameDamage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|TypeOfEffect,WeaponType,
								L("^F^<FIGHT^>The magic of @x1 <DAMAGE> <T-NAME>!^</FIGHT^>^?",clanName));
						wandUse.helpProficiency(mob, 0);
						return;
					}
				}
			}
		}
	}

	public static void initAdjustments(CharStats adjCharStats)
	{
		// ensure we get no NULL errors
		for(final int i : CharStats.CODES.SAVING_THROWS())
			adjCharStats.setStat(i,0);
	}

	@Override
	public void affectCharStats(MOB affectedMOB, CharStats affectedStats)
	{
		if(EQadjCharStats==null)
		{
			setMiscText(text());
			/*
			 * ************************* Armor-based Resistances
			 * *************************
			 */
		}
		if((affected!=null)&&(affected instanceof Armor)&&(!(affected instanceof Shield))&&(activated)
				&&(!((Armor)affected).amWearingAt(Wearable.IN_INVENTORY)))
		{
			for(final int i : CharStats.CODES.SAVING_THROWS())
				affectedStats.setStat(i,affectedStats.getStat(i)+EQadjCharStats.getStat(i));
		}
		super.affectCharStats(affectedMOB,affectedStats);
	}

	@Override
	public void executeMsg(final Environmental myHost, final CMMsg msg)
	{
		super.executeMsg(myHost,msg);
		if(((System.currentTimeMillis()-LastChecked)>TimeManager.MILI_HOUR)&&(affected!=null))
		{
			if((clanName!=null)&&(clanName.length()>0)&&(CMLib.clans().getClan(clanName)==null))
				affected.delEffect(this);
			LastChecked=System.currentTimeMillis();
		}
		MOB mob=null;
		MOB source=null;
		if((affected!=null)&&(affected instanceof Item))
		{
			if((((Item)affected).owner()!=null)&&((Item)affected).owner() instanceof MOB)
			{
				mob=(MOB)((Item)affected).owner();
			}
		}
		// if held by the wrong clan, it is inactive.
		if((mob!=null)&&(mob.getClanRole(clanName)!=null))
			activated=true;
		else
			activated=false;
		if(!activated)
			return;
		source=msg.source();
		/*
		 * ********************** Weapon addtl. Damage
		 * **********************
		 */
		if((msg.source().location()!=null)&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)&&(msg.value()>0)&&(msg.tool()==affected)&&(!notAgain)
				&&(msg.target() instanceof MOB)&&(msg.tool() instanceof Weapon)&&(!(msg.tool() instanceof Wand))&&(TypeOfEffect<1000)
				&&(!((MOB)msg.target()).amDead()))
		{
			final double flameDamage=CMLib.dice().roll(1,6*PowerLevel,1*PowerLevel);
			final String str=L("^F^<FIGHT^>The magic of @x1 <DAMAGE> <T-NAME>!^</FIGHT^>^?",clanName);
			CMLib.combat().postDamage(msg.source(),(MOB)msg.target(),null,(int)Math.round(flameDamage),
					CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|TypeOfEffect,WeaponType,str);
		}
		/*
		 * ********************** Shield Thorns Damage **********************
		 */
		if((mob!=null)&&(msg.amITarget(mob))&&(affected instanceof Shield)&&(!((Shield)affected).amWearingAt(Wearable.IN_INVENTORY))
		&&(TypeOfEffect<1000)&&(!msg.amISource(mob)))
		{
			if((CMLib.dice().rollPercentage()>32+msg.source().charStats().getStat(CharStats.STAT_DEXTERITY))
			&&(msg.source().rangeToTarget()==0)
			&&((lastMessage==null)||(lastMessage.indexOf("The magic around")<0))
			&&((msg.targetMajor(CMMsg.MASK_HANDS))||(msg.targetMajor(CMMsg.MASK_MOVE))))
			{
				final CMMsg msg2=CMClass.getMsg(mob,source,this,CMMsg.MSG_CAST_ATTACK_VERBAL_SPELL,null);
				if((source!=null)&&(source.location().okMessage(source,msg2)))
				{
					source.location().send(source,msg2);
					if(msg2.value()<=0)
					{
						final int damage=CMLib.dice().roll(1,3*PowerLevel,1*PowerLevel);
						CMLib.combat().postDamage(mob,source,this,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|TypeOfEffect,WeaponType,
								L("^F^<FIGHT^>The magic of @x1 around <S-NAME> <DAMAGE> <T-NAME>!^</FIGHT^>^?",clanName));
						if((!source.isInCombat())&&(source.isMonster())&&(source!=mob)&&(source.location()==mob.location())&&(source.location().isInhabitant(mob))&&(CMLib.flags().canBeSeenBy(mob,source)))
							CMLib.combat().postAttack(source,mob,source.fetchWieldedItem());
					}
				}
			}
		}
		/*
		 * ************************* Staff/Wand Message Watch
		 * *************************
		 */
		if(affected instanceof Wand)
		{
			switch(msg.targetMinor())
			{
			case CMMsg.TYP_WAND_USE:
				if(msg.amITarget(this)&&((msg.tool()==null)||(msg.tool() instanceof Physical)))
					waveIfAble(mob,msg.tool(),msg.targetMessage(),(Wand)affected);
				break;
			case CMMsg.TYP_SPEAK:
				if(msg.sourceMinor()==CMMsg.TYP_SPEAK)
				{
					boolean alreadyWanding=false;
					final List<CMMsg> trailers =msg.trailerMsgs();
					if(trailers!=null)
					{
						for(final CMMsg msg2 : trailers)
						{
							if((msg2.targetMinor()==CMMsg.TYP_WAND_USE)
							&&(msg2.target() == this))
								alreadyWanding=true;
						}
					}
					final String said=CMStrings.getSayFromMessage(msg.sourceMessage());
					if((!alreadyWanding)
					&&(said != null)
					&&(checkWave(mob,said,(Wand)affected)))
						msg.addTrailerMsg(CMClass.getMsg(msg.source(),this,msg.target(),CMMsg.NO_EFFECT,null,CMMsg.MASK_ALWAYS|CMMsg.TYP_WAND_USE,said,CMMsg.NO_EFFECT,null));
				}
				break;
			default:
				break;
			}
		}
	}
}


text:
/****************************************************************************
 *   Author:  Juergen Pfeifer, 1995,1997                                    *
 ****************************************************************************/

#include "form.priv.h"

MODULE_ID("$Id: fld_ftchoice.c,v 1.9 2004/12/11 21:44:57 tom Exp $")

/*---------------------------------------------------------------------------
|   Facility      :  libnform
|   Function      :  int set_fieldtype_choice(
|                          FIELDTYPE *typ,
|                          bool (* const next_choice)(FIELD *,const void *),
|                          bool (* const prev_choice)(FIELD *,const void *))
|
|   Description   :  Define implementation of enumeration requests.
|
|   Return Values :  E_OK           - success
|                    E_BAD_ARGUMENT - invalid arguments
+--------------------------------------------------------------------------*/
NCURSES_EXPORT(int)
set_fieldtype_choice(FIELDTYPE *typ,
		     bool (*const next_choice) (FIELD *, const void *),
		     bool (*const prev_choice) (FIELD *, const void *))
{
  T((T_CALLED("set_fieldtype_choice(%p,%p,%p)"), typ, next_choice, prev_choice));

  if (!typ || !next_choice || !prev_choice)
    RETURN(E_BAD_ARGUMENT);

  typ->status |= _HAS_CHOICE;
  typ->next = next_choice;
  typ->prev = prev_choice;
  RETURN(E_OK);
}

/* fld_ftchoice.c ends here */


text:
package test.encoding;

import junit.framework.TestCase;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.TypeMapping;
import org.apache.axis.encoding.TypeMappingRegistry;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.RPCParam;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.server.AxisServer;
import org.apache.axis.utils.JavaUtils;

import javax.xml.namespace.QName;
import java.util.Vector;

/**
 * Test deserialization of SOAP responses
 */
public class TestBeanDeser extends TestCase {

    private String header;
    private String footer;
    private AxisServer server = new AxisServer();

    public TestBeanDeser(String name) {
        this(name, Constants.URI_DEFAULT_SCHEMA_XSI,
                Constants.URI_DEFAULT_SCHEMA_XSD);
    }

    public TestBeanDeser(String name, String NS_XSI, String NS_XSD) {
        super(name);

        header =
            "<?xml version=\"1.0\"?>\n" +
            "<SOAP-ENV:Envelope\n" +
            "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
            "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\n" +
            "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
            "xmlns:xsd-cr=\"http://www.w3.org/2000/10/XMLSchema\"\n" +
            "xmlns:xsd-lc=\"http://www.w3.org/1999/XMLSchema\"\n" +
            "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
            "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"+
            "<SOAP-ENV:Body>\n";
        footer =
            "</SOAP-ENV:Body>\n"+
            "</SOAP-ENV:Envelope>\n";

        TypeMappingRegistry tmr = server.getTypeMappingRegistry();
        TypeMapping tm = (TypeMapping) tmr.createTypeMapping();
        tm.setSupportedEncodings(new String[]{Constants.URI_DEFAULT_SOAP_ENC});
        tmr.register(Constants.URI_DEFAULT_SOAP_ENC, tm);
        tm.register(test.encoding.RETURN.class,
                new QName("urn:test.encoding", "RETURN"),
                new org.apache.axis.encoding.ser.BeanSerializerFactory(
                        test.encoding.RETURN.class,
                        new QName("urn:test.encoding", "RETURN")),
                new org.apache.axis.encoding.ser.BeanDeserializerFactory(
                        test.encoding.RETURN.class,
                        new QName("urn:test.encoding", "RETURN")));
    }

    /**
     * Verify that two objects have the same value, handling arrays...
     */
    private static boolean equals(Object obj1, Object obj2) {
        if ((obj1 == null) || (obj2 == null)) return (obj1 == obj2);
        if (obj1.equals(obj2)) return true;
        return false;
    }

    /**
     * Verify that a given XML deserialized produces the expected result
     */
    protected void deserialize(String data, Object expected)
            throws Exception {
        deserialize(data, expected, false);
    }

    protected void deserialize(String data, Object expected, boolean tryConvert)
            throws Exception {
        Message message = new Message(header + data + footer);
        message.setMessageContext(new MessageContext(server));

        SOAPEnvelope envelope = (SOAPEnvelope) message.getSOAPEnvelope();
        assertNotNull("SOAP envelope should not be null", envelope);

        RPCElement body = (RPCElement) envelope.getFirstBody();
        assertNotNull("SOAP body should not be null", body);

        Vector arglist = body.getParams();
        assertNotNull("arglist", arglist);
        assertTrue("param.size()<=0 {Should be > 0}", arglist.size() > 0);

        RPCParam param = (RPCParam) arglist.get(0);
        assertNotNull("SOAP param should not be null", param);

        Object result = param.getObjectValue();
        if (!equals(result, expected)) {
            // Try to convert to the expected class
            if (tryConvert) {
                Object result2 = JavaUtils.convert(result, expected.getClass());
                if (!equals(result2, expected)) {
                    assertEquals("The result is not what is expected.", expected, result);
                }
            } else {
                assertEquals("The result is not what is expected.", expected, result);
            }
        }
    }

    // Struct Return
    public void testReturn() throws Exception {
        test.encoding.RETURN ret = new test.encoding.RETURN();
        ret.setTYPE("000");
        ret.setID("001");
        ret.setNUMBER("002");
        ret.setMESSAGE("003");
        ret.setLOGNO("004");
        ret.setLOGMSGNO("005");
        ret.setMESSAGEV1("006");
        ret.setMESSAGEV2("007");
        ret.setMESSAGEV3("008");
        ret.setMESSAGEV4("009");
        String response =
                "<ser-root:SrvResponse xmlns:ser-root=\"urn:test.encoding\">\n"+
                "  <ser-root:RETURN xsi:type=\"ser-root:RETURN\">\n"+
                "    <TYPE xsi:type=\"xsd:string\">000</TYPE>\n"+
                "    <ID xsi:type=\"xsd:string\">001</ID>\n"+
                "    <NUMBER xsi:type=\"xsd:string\">002</NUMBER>\n"+
                "    <MESSAGE xsi:type=\"xsd:string\">003</MESSAGE>\n"+
                "    <LOG_NO xsi:type=\"xsd:string\">004</LOG_NO>\n"+
                "    <LOG_MSG_NO xsi:type=\"xsd:string\">005</LOG_MSG_NO>\n"+
                "    <MESSAGE_V1 xsi:type=\"xsd:string\">006</MESSAGE_V1>\n"+
                "    <MESSAGE_V2 xsi:type=\"xsd:string\">007</MESSAGE_V2>\n"+
                "    <MESSAGE_V3 xsi:type=\"xsd:string\">008</MESSAGE_V3>\n"+
                "    <MESSAGE_V4 xsi:type=\"xsd:string\">009</MESSAGE_V4>\n"+
                "  </ser-root:RETURN>\n"+
                "</ser-root:SrvResponse>";
        deserialize(response,ret,true);
    }

    /*
    // Struct Return - variation
    public void testReturn2() throws Exception {
        test.encoding.RETURN ret = new test.encoding.RETURN();
        ret.setTYPE("000");
        ret.setID("001");
        ret.setNUMBER("002");
        ret.setMESSAGE("003");
        ret.setLOGNO("004");
        ret.setLOGMSGNO("005");
        ret.setMESSAGEV1("006");
        ret.setMESSAGEV2("007");
        ret.setMESSAGEV3("008");
        ret.setMESSAGEV4("009");
        String response =
                "<SrvResponse xmlns=\"urn:test.encoding\">\n"+
                "  <RETURN>\n"+
                "    <TYPE xsi:type=\"xsd:string\">000</TYPE>\n"+
                "    <ID xsi:type=\"xsd:string\">001</ID>\n"+
                "    <NUMBER xsi:type=\"xsd:string\">002</NUMBER>\n"+
                "    <MESSAGE xsi:type=\"xsd:string\">003</MESSAGE>\n"+
                "    <LOG_NO xsi:type=\"xsd:string\">004</LOG_NO>\n"+
                "    <LOG_MSG_NO xsi:type=\"xsd:string\">005</LOG_MSG_NO>\n"+
                "    <MESSAGE_V1 xsi:type=\"xsd:string\">006</MESSAGE_V1>\n"+
                "    <MESSAGE_V2 xsi:type=\"xsd:string\">007</MESSAGE_V2>\n"+
                "    <MESSAGE_V3 xsi:type=\"xsd:string\">008</MESSAGE_V3>\n"+
                "    <MESSAGE_V4 xsi:type=\"xsd:string\">009</MESSAGE_V4>\n"+
                "  </RETURN>\n"+
                "</SrvResponse>";
        deserialize(response,ret,true);
    }
    */

    public static void main(String [] args) throws Exception
    {
        TestBeanDeser tester = new TestBeanDeser("test");
        tester.testReturn();
    }
}


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

<TITLE>
StaticMethodTransformer
</TITLE>

<META NAME="date" CONTENT="2010-03-06">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.deuce.transform.asm.method

Class StaticMethodTransformer

java.lang.Object
  org.deuce.objectweb.asm.MethodAdapter
      org.deuce.transform.asm.method.StaticMethodTransformer

All Implemented Interfaces:
org.deuce.objectweb.asm.MethodVisitor

public class StaticMethodTransformer
extends org.deuce.objectweb.asm.MethodAdapter

Field Summary

static java.lang.String
CLASS_BASE

Fields inherited from class org.deuce.objectweb.asm.MethodAdapter

mv

Constructor Summary

StaticMethodTransformer(org.deuce.objectweb.asm.MethodVisitor mv,
                        org.deuce.objectweb.asm.MethodVisitor staticMethod,
                        java.util.List<Field> fields,
                        java.lang.String staticField,
                        java.lang.String className,
                        java.lang.String fieldsHolderName)

Method Summary

 void
visitCode()

          Starts the visit of the method's code, if any (i.e. non abstract method).

 void
visitEnd()

          Visits the end of the method.

Methods inherited from class org.deuce.objectweb.asm.MethodAdapter

visitAnnotation, visitAnnotationDefault, visitAttribute, visitFieldInsn, visitFrame, visitIincInsn, visitInsn, visitIntInsn, visitJumpInsn, visitLabel, visitLdcInsn, visitLineNumber, visitLocalVariable, visitLookupSwitchInsn, visitMaxs, visitMethodInsn, visitMultiANewArrayInsn, visitParameterAnnotation, visitTableSwitchInsn, visitTryCatchBlock, visitTypeInsn, visitVarInsn

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

CLASS_BASE

public static final java.lang.String CLASS_BASE

See Also:
Constant Field Values

Constructor Detail

StaticMethodTransformer

public StaticMethodTransformer(org.deuce.objectweb.asm.MethodVisitor mv,
                               org.deuce.objectweb.asm.MethodVisitor staticMethod,
                               java.util.List<Field> fields,
                               java.lang.String staticField,
                               java.lang.String className,
                               java.lang.String fieldsHolderName)

Method Detail

visitCode

public void visitCode()

Description copied from interface: org.deuce.objectweb.asm.MethodVisitor

Starts the visit of the method's code, if any (i.e. non abstract method).

Specified by:
visitCode in interface org.deuce.objectweb.asm.MethodVisitor
Overrides:
visitCode in class org.deuce.objectweb.asm.MethodAdapter

visitEnd

public void visitEnd()

Description copied from interface: org.deuce.objectweb.asm.MethodVisitor

Visits the end of the method. This method, which is the last one to be
 called, is used to inform the visitor that all the annotations and
 attributes of the method have been visited.

Specified by:
visitEnd in interface org.deuce.objectweb.asm.MethodVisitor
Overrides:
visitEnd in class org.deuce.objectweb.asm.MethodAdapter

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package es.bhavishchandnani.myrestaurant.adapters;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import es.bhavishchandnani.myrestaurant.R;
import es.bhavishchandnani.myrestaurant.model.Dish;
import es.bhavishchandnani.myrestaurant.views.DishItemViewHolder;
import es.bhavishchandnani.myrestaurant.views.OnElementClick;
import es.bhavishchandnani.myrestaurant.views.OnElementLongClick;

import static android.content.ContentValues.TAG;

public class DishesAdapter extends RecyclerView.Adapter<DishItemViewHolder> {

    private final LayoutInflater layoutInflater;
    private final List<Dish> dishes;

    private OnElementClick<Dish> listener;
    private OnElementLongClick<Dish> onElementLongClickListener;

    public DishesAdapter(Context context, List<Dish> dishes) {
        this.layoutInflater = LayoutInflater.from(context);
        this.dishes = dishes;
    }

    @Override
    public DishItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.item_dish, parent, false);
        return new DishItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(DishItemViewHolder item, final int position) {
        final Dish dish = dishes.get(position);

        item.setDish(dish);

        item.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: clicked item "+position);
                if (listener != null){
                    listener.clickedOn(dish, position);
                }
            }
        });

        item.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                onElementLongClickListener.longClickedOn(dish, position);
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        return dishes.size();
    }

    public void setOnElementClickListener(@NonNull final OnElementClick listener){
        this.listener =  listener;
    }

    public void setOnElementLongClickListener(OnElementLongClick<Dish> onElementLongClickListener) {
        this.onElementLongClickListener = onElementLongClickListener;
    }
}