text:
swift-itertools
===============

A port of Python's [`itertools`][itertools] and related things to Swift.

    [itertools]: https://docs.python.org/3/library/itertools.html

Background
==========

Developers in functional languages have long known the benefits of
writing programs as a chain of list transformations, but lazy
languages like Haskell have shown that this can be taken much
farther. Python's `Iterator` protocol (along with related features)
captures most of the benefit of lazy lists. Over the years, much of
the relevant part of the Haskell standard prelude has been ported to
Python (some as part of the standard library, mostly in the
`itertools` module, and some in third-party modules like Erik Rose's
[`more-itertools`][more-itertools], and Python developers have found
new uses for this functionality (e.g., see David Beazley's
[Generator Tricks for Systems Programmers][gentricks]). Many newer
languages, like Scala and Clojure, have taken advantage of the
experience of Haskell and Python to provide similar functionality.

    [more-itertools]: https://github.com/erikrose/more-itertools
	[gentricks]: http://www.dabeaz.com/generators-uk/

Swift's `Generator` protocol is almost identical to Python's
`Iterator` protocol, allowing for the same style of
programming. However, its standard library provides only the most
basic functions for processing them--`map` and `filter` and not much
else. This library is an attempt to rectify that problem by porting
useful functions from Python, Scala, Clojure, and Haskell to Swift,
starting with most of Python's `itertools` module.

To understand some of these functions, it may help to think at a
higher level of abstraction, of monads rather than specifically
sequences, optional values, etc.. However, experience with Python and
Scala developers have shown that this is a tough hurdle for many
people, so I've kept things on the concrete level; there are no
functions to lift a function to any monad, etc., just functions that
deal with sequences, optionals, etc.

The resulting library should probably be called `gentools` or
`seqtools` (since what Python calls `Iterator` and `Iterable`, Swift
calls `Generator` and `Sequence`), but since `itertools` is such a
well-known (and searchable) name, it seemed more appropriate.

Writing this library has also given me a good opportunity to learn
Swift. See the blog [Stupid Swift Ideas][] for some of what I've
discovered along the way.

    [Stupid Swift Ideas]: http://stupidswiftideas.blogspot.com

Static types and homogenous sequences
=====================================

In keeping with Swift's nature as a traditional static-typed language,
its collections are homogenous, so `Sequence` and `Generator` are
meant to be implemented by homogenous collections, which are generic
types parameterized on the element type. (The protocols themselves are
_not_ generic; instead, they use associated types, which can be bound
to the parameters in implementing types. See [Generics][] in the Swift
Language Guide for details.) While heterogeneous
collections can be implemented either Java-style (by parameterizing on
`any` or `AnyObject`) or ObjC-style (by bridging a class like
`NSArray` that implements the `NSFastEnumeration` protocol) and
casting back and forth, general-purpose functions like these should
work on generic, homogenous sequences.

    [Generics]: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Generics.html

Because Swift attempts to be a stricter static language than Java or
C#, more on the lines with C++ (or even Haskell), some familiarity
with the C++ standard-library algorithms derived from [STL][] may be
useful. However, it's worth noting that many of the techniques and
concepts from that library don't seem to be portable to Swift. For
example, many C++ functions that a sequence (or, rather, a pair of
`iterator`s--which doesn't mean the same thing as in either Python or
Swift--but that can be ignored, as a Swift `Generator` is equivalent
to a C++ input iterator that knows its own `end`) of type `T`, and a
function that operates on objects of any type `U` for which `T` is
convertible to `U`. There doesn't seem to be any way to define such a
constraint in Swift, so the corresponding functions require a function
on type `T` itself.

    [STL]: http://en.wikipedia.org/wiki/Standard_Template_Library

Similarly, while C++ makes it possible to define a function over a
variable number of heterogeneous parameters (by using template
parameter packs), Scala does not; variadic arguments must all be of
the same type.

Differences from Python
=======================

A Python `Iterator` is a Swift `Generator`; the only major difference
is that the `next` method doesn't have double underscores.

A Python `Iterable` is a Swift `Sequence`; the only major difference
is that the iter method is called `generate` (and doesn't have double
underscores).

Unlike Python, where every `Iterator` must also be an `Iterable` that
returns `self` when you ask for an iterator, Swift appears to have no
such constraint. It seems like at least some `Generator` types are
written this way, so there's no reason not to do the same thing
here. But it does affect the usefulness of these functions. In Python,
the `itertools` functions take any kind of `Iterable`, which
automatically means they work on any `Iterator` (consuming it); the
Swift equivalent, taking any kind of `Sequence`, means not working on
some `Generator`s. Fortunately, since we're only returning `Sequence`s
that are `Generator`s, at least you can chain `itertools` functions
together the same way as in Python.

The existing stuff in Swift's standard library (`map`, etc.) seems to
set a precedent that functions should come last whenever possible
(which makes sense, given the quasi-Ruby-style special handling for
closure arguments), and failing that, sequences should come
first. That's not the same as the standard in Python, but it makes
sense to follow the local Swift standards, so we'll do that.

In Python, variadic parameters can be followed by optional parameters,
making those optional parameters keyword-only. Swift allows for
variadic, optional, and keyword-only parameters, but doesn't allow any
way to combine them all in a single function.

Some functions can't be as flexible as they are in Python (or at least
I can't figure out how to do so...), sometimes because of the
homogenous sequence issue, but sometimes because of limitations of the
language. Such cases have been split into separate functions.

Utility functions and types
===========================

`Addable`
    Protocol for types where `T+T->T` makes sense. `Int` and `Float`
    are already registered.

`array(sequence: Sequence)` --> `T[]`
    Turns any `Sequence` of `T` into an `Array` of `T`. If the
    sequence isn't repeatable, it will be consumed. If it's infinite,
    this will of course hang forever.

`defaultify(value: T?, defvalue: T)` --> `value! or defvalue`
    Supplies a default value for an optional. (May not be necessary
	with future compilers, but for now it's needed to work around a
	compiler crash from the obvious way to do this concisely inline.)

`negate(T->Bool)` --> `T->Bool`
    Takes a predicate and returns the opposite predicate.

`zipopt(T?, U?)` --> `(T, U)?`
    Given two optional values, returns an optional tuple, nil if
    either value is nil.

Folding functions
=================

While Swift does have a builtin `reduce(sequence, start, function)`,
just running `reduce([1, 2, 3, 4], 0, {$0+$1})` takes about 8 seconds
on my laptop. Also, neither function nor start can be defaulted, which
means we really need four separate functions to handle all of the
cases. (For a more general `reduce` that includes a `transform`
function as well, we'd need 8, but the three-arg `reduce` plus `map`
should make that unnecessary.) So:

`sum1(sequence: Sequence<T>)` -->
    `s[0] + s[1] + ...`
	It is an error to call this on an empty sequence.

`sum(sequence: Sequence<T>, start: T)` -->
    `start + s[0] + s[1] + ...`

`fold1(sequence: Sequence<T>, combine: (T, T)->T` -->
    `combine(combine(...(s[0], s[1]), s[2]), ...)`
	It is an error to call this on an empty sequence.

`fold(sequence: Sequence<T>, start: T, combine: (T, T)->T` -->
    `combine(combine(...(start, s[0]), s[1]), ...)`

Infinite Iterators
==================

`counter(start: Int = 0, step: Int = 1)` -->
    `start, start+step, start+step*2, ...`
	Named `counter` to avoid collision with the builtin `count`.
    Only counts integers, a restriction Python doesn't enforce.

`cycle(sequence: Sequence)` -->
    `s[0], s[1], ..., s[n-1], s[0], s[1], ...`
	Stashes the values, so it works with non-repeatable sequences.
	(Which may not be an issue in Swift; maybe non-repeatble
    Generators generally aren't sequences?)

`repeat(obj: T, times: Int)` -->
    `obj, obj, ...` (`times` copies)
	Does not allow infinite repeat, unlike Python. Also note that
	there seems to be a type `Repeat(count: Int, repeatedValue: T)`
	in the stdlib but undocumented.

Iterators terminating on shortest input sequence
================================================
`accumulate(sequence: Sequence, f: (T, T)->T)` -->
    `s[0], f(s[0], s[1]), f(f(s[0], s[1]), s[2]), ...`
	The function does not have a default value, unlike Python.
	See `cumulative_sum` for a version that does.

`cumulative_sum(sequence: Sequence of Addable, f: (T, T)->T = { $0+$1 })` -->
    `s[0], s[0]+s[1], s[0]+s[1]+s[2], ...`
	The function defaults to addition, which is why `cumulative_sum`
    only works on `Addable` types. See `accumulate` for a version that
    works on all sequences. (Currently disabled because of compiler crash.)

`chain(sequences: Sequence...)` -->
    `s0[0], s0[1], ..., s0[n0-1], s1[0], ..., s1[n1-1], ...`

`chain_sequences(sequences: Sequence of Sequences)` -->
    `s[0][0], s[0][1], ..., s[0][n0-1], s[1][0], ..., s[1][n1-1], ...`
	This is the equivalent of chain.from_iterable in Python.

`compress(data: Sequence, selectors: Sequence of Bool)` -->
    `d[0] if s[0], d[1] if s[1], ...`
	As usual, unlike Python, the selectors here must be actual Bools.
	To compress based on integers, see `compress_nz`.

`compress_nz(data: Sequence, selectors: Sequence of Int)` -->
    `d[0] if s[0]!=0, d[1] if s[1]!=0, ...`
	To compress based on Bools, see `compress`.

`dropwhile(sequence: Sequence, predicate: T->Bool)` -->
    `s[n], s[n+1], ...` (starting when `predicate(s[n-1])` fails)

`filterfalse(sequence: Sequence, predicate: T->Bool)` -->
    `s[0] if !p(s[0]), s[1] if !p(s[1]), ...`

`groupby(sequence: Sequence, key: T->U)` -->
    `(key(s[0]), [s[0], s[1], ...]), (key(s[n]), [s[n], s[n+1], ...]), ...`
	Unlike the Python version, the key function is not optional; see
    `groupby_nokey` to group equal objects without a key function.
	Also unlike Python, groupby doesn't return sub-iterators, it
    returns arrays. (Not just because it would be a ton of work to
    return sub-Generator objects, but because people often find
    groupby hard to work with in Python...)

`groupby_nokey(sequence: Sequence)` -->
    `(s[0], [s[0], s[1], ...]), (s[n], [s[n], s[n+1], ...]), ...`
	Groups equal values, without a key function. To use a key
    function, see `groupby`.

`islice(sequence: Sequence, start=0, stop=nil, step=1)` -->
    `s[start], s[start+step], ..., s[start+n*step]`
    Unlike the Python version, you can't call this with a single
	positional argument as `stop`, but then that's a weird design in
    Python anyway. Use keyword arguments.

`starmap(sequence: Sequence of tuples, f)` -->
    `f(*s[0]), f(*s[1]), ...`
    Does not exist, because (a) tuples aren't sequences,
    (b) there doesn't seem to be any way to convert from even a homogenous
    sequence to a tuple or vice-versa, and (c) even if you could, there
    doesn't seem to be any way to call a function given its arguments as
    a tuple.

`tee(sequence: Sequence, n: Int)` -->
    `[s0, s1, ..., sn-1]`
	This should tee a single (possibly non-repeatable) Sequence into n
    separate copies, all of which contain all of the elements of the
    original. Unfortunately, it seems to be impossible to implement
    without a compiler crash.

`zip(s0: Sequence of T0, s1: sequence of T1)` -->
    `(s0[0], s1[0]), (s0[1], s1[1]), ...`
	Unlike the Python version, this only handles exactly two
    sequences, because there doesn't seem to be any way to accept
    variadic arguments of different Sequence types, or to build a
    tuple with a dynamically-specified number of elements.

`zip_longest(s0: Sequence of T0?, s1: sequence of T1?)` -->
    `(s0[0], s1[0]), (s0[1], s1[1]), ..., (nil, s1[n]), ...`
	Unlike the Python version, this only handles exactly two sequences
    (like `zip`). It also requires both sequences to be of optional
    values, and fills missing values with `nil`. See also `zip_fill`.

`zip_fill(s0: Sequence of T0, s1: sequence of T1, f0: T0, f1: T1)` -->
    `(s0[0], s1[0]), (s0[1], s1[1]), ..., (f0, s1[n]), ...`
	Unlike the Python version, this only handles exactly two sequences
    (like `zip`). Also unlike the Python version, it requires two
    separate fill values. See also `zip_longest`.

Combinatoric generators
=======================

`product(s0: Sequence of T, s1: Sequence of T, ...)` -->
    `(s0[0], s1[0]), (s0[0], s0[1]), ..., (s0[1], s1[0]), ...`
	Unlike Python's `product`, this cannot be used for heterogeneous
	lists of sequences (see `product2`), or for a single sequence with
    a `repeat` parameter (see `self_product`).

`product2(s0: Sequence of T0, s1: Sequence of T1)` -->
    `(s0[0], s1[0]), (s0[0], s0[1]), ..., (s0[1], s1[0]), ...`
	Unlike Python's `product`, this does not take an arbitrary number
    of arguments, it takes exactly two. For a single sequence and a
    `repeat` value, see `self_product`.

`self_product(s: Sequence of T, repeat: Int)` -->
    `(s[0], s[0]), (s[0], s[1]), ..., (s[1], s[0]), ...`
	This is equivalent to `product(s, repeat)` in Python.

`permutations`, `combinations`, `combinations_with_replacement` later

Recipes
=======

`take(s: Sequence of T, n: Int)` -->
    `[s[0], s[1], ..., s[n]]`

`tabulate(function: Int->T)` -->
    `function(0), function(1), ...`
	Unlike the Python version, this doesn't take an optional start
    value `n`, because we need to put `function` last to preserve the
    usual trailing-closure style. See `tabulate_n`.

`tabulate_n(n: Int, function: Int->T)` -->
    `function(n), function(n+1), ...`

`consume(sequence: Sequence, n: Int?)` -->
    `nil`
	Note that when called on an actual `Sequence` that creates new
	`Generator`s on each call, rather than one that wraps a
    `Generator` and returns `self`, this will have no visible effect,
	and that seems to be much more common with Swift's stdlib than
    Python's.

`nth(sequence: Sequence, n: Int)` -->
    `s[n] or nil`
	Unlike the Python version, this does not take an optional default
	value (because that would change the type from T? to T). See
	`nth_default`.

`nth_default(sequence: Sequence, n: Int, defvalue: T)` -->
    `s[n] or defvalue`


text:
    <title>#${ticket.id}: ${ticket['summary']}</title>

    Ticket #${ticket.id} (${ticket['status']} ${ticket['type']})

${ticket['summary']}

          ${field['label']}:
          ${ticket[field['name']] or 'None'}

      <py:if test="category == 'created'">

Description

${description}

      </py:if>

    <py:if test="has_changes">

Changes: (by ${author})

          ${change} changed
          from ${short_changes[change][0]}
          to ${short_changes[change][1]}.

          ${change}:

${content}

    </py:if>
    <py:if test="attachment">

Attachments:

File ${attachment.filename} added<py:if test="attachment.description">: ${attachment.description}</py:if>

    </py:if>
    <py:if test="comment">

Comments: (by ${author})

${comment}

    </py:if>

Ticket URL: ${ticket_link}

    ${project_name} ${project_link}

    ${project_desc}

redpajama_set_name: RedPajamaGithub


text:
/*jslint browser: true, devel: true, onevar: true, undef: true, regexp: true, bitwise: true, newcap: true*/
/*globals doodle*/
(function () {
  var text_sprite_static_properties,
      /*DEBUG*/
      type_check = doodle.utils.debug.type_check,
      range_check = doodle.utils.debug.range_check,
      reference_check = doodle.utils.debug.reference_check,
      /*END_DEBUG*/
      hex_to_rgb_str = doodle.utils.hex_to_rgb_str,
      FontStyle = doodle.FontStyle,
      FontVariant = doodle.FontVariant,
      FontWeight = doodle.FontWeight,
      TextAlign = doodle.TextAlign,
      TextBaseline = doodle.TextBaseline;

  /**
   * A text sprite to display.
   * @name doodle.createText
   * @class
   * @augments doodle.Sprite
   * @param {string=} text Text to display.
   * @return {doodle.Text} A text object.
   * @throws {SyntaxError} Invalid parameters.
   * @throws {TypeError} Text argument not a string.
   */
  doodle.Text = doodle.createText = function (text) {
    var text_sprite = Object.create(doodle.createSprite());

    Object.defineProperties(text_sprite, text_sprite_static_properties);
    //properties that require privacy
    Object.defineProperties(text_sprite, (function () {
      var $text = '',
          font_family = "sans-serif",
          font_size = 10,//px
          font_height = font_size,
          font_style = FontStyle.NORMAL,
          font_variant = FontVariant.NORMAL,
          font_weight = FontWeight.NORMAL,
          text_align = TextAlign.START,
          text_baseline = TextBaseline.ALPHABETIC,
          text_color = "#000000",
          text_strokecolor = "#000000",
          text_strokewidth = 1,
          text_bgcolor;

      /**
       * @name redraw
       * @private
       */
      function redraw () {
        //if not part of the scene graph we'll have to whip up a context
        var $ctx = text_sprite.context || document.createElement('canvas').getContext('2d'),
            sprite_width,
            sprite_height,
            graphics = text_sprite.graphics,
            extrema_minX = 0,
            extrema_maxX = 0,
            extrema_minY = 0,
            extrema_maxY = 0;

        //need to apply font style to measure width, but don't save it
        $ctx.save();
        $ctx.font = (font_style +' '+ font_variant +' '+ font_weight +' '+
                     font_size+"px" +' '+ font_family);
        sprite_width = $ctx.measureText($text).width;
        sprite_height = font_size;
        //estimate font height since there's no built-in functionality
        font_height = $ctx.measureText("m").width;
        $ctx.restore();

        //clears sprite dimensions and drawing commands
        text_sprite.graphics.clear();
        text_sprite.graphics.draw(function (ctx) {
          if (text_bgcolor) {
            ctx.fillStyle = text_bgcolor;
            ctx.fillRect(0, 0, sprite_width, sprite_height);
          }
          ctx.lineWidth = text_strokewidth; //why do i need to set this?
          ctx.textAlign = text_align;
          ctx.textBaseline = text_baseline;
          ctx.font = (font_style +' '+ font_variant +' '+ font_weight +' '+
                      font_size+"px" +' '+ font_family);
          if (text_color) {
            ctx.fillStyle = text_color;
            ctx.fillText($text, 0, 0);
          }
          if (text_strokecolor) {
            ctx.strokeStyle = text_strokecolor;
            ctx.strokeText($text, 0, 0);
          }
        });

        //assign sprite dimensions after graphics.clear()
        text_sprite.width = sprite_width;
        text_sprite.height = sprite_height;

        //calculate bounding box extrema
        switch (text_baseline) {
        case TextBaseline.TOP:
          extrema_minY = font_size - font_height;
          extrema_maxY = font_size;
          break;
        case TextBaseline.MIDDLE:
          extrema_minY = -font_height/2;
          extrema_maxY = font_height/2;
          break;
        case TextBaseline.BOTTOM:
          extrema_minY = -font_size;
          break;
        case TextBaseline.HANGING:
          extrema_minY = font_size - font_height;
          extrema_maxY = font_size;
          break;
        case TextBaseline.ALPHABETIC:
          extrema_minY = -font_height;
          break;
        case TextBaseline.IDEOGRAPHIC:
          extrema_minY = -font_size;
          break;
        }

        switch (text_align) {
        case TextAlign.START:
          break;
        case TextAlign.END:
          extrema_minX = -sprite_width;
          break;
        case TextAlign.LEFT:
          break;
        case TextAlign.RIGHT:
          extrema_minX = -sprite_width;
          break;
        case TextAlign.CENTER:
          extrema_minX = -sprite_width/2;
          break;
        }

        //set extrema for bounds
        graphics.__minX = extrema_minX;
        graphics.__maxX = extrema_maxX;
        graphics.__minY = extrema_minY;
        graphics.__maxY = extrema_maxY;
      }

      return {
        /**
         * @name text
         * @return {String}
         * @throws {TypeError}
         * @property
         */
        'text': {
          enumerable: true,
          configurable: false,
          get: function () { return $text; },
          set: function (textVar) {
            /*DEBUG*/
            type_check(textVar, 'string', {label:'Text.text', id:this.id});
            /*END_DEBUG*/
            $text = textVar;
            redraw();
          }
        },

        /**
         * @name font
         * @return {String}
         * @throws {TypeError}
         * @throws {SyntaxError}
         * @throws {ReferenceError}
         * @property
         */
        'font': {
          enumerable: true,
          configurable: false,
          get: function () {
            return (font_style +' '+ font_variant +' '+ font_weight +' '+ font_size+"px" +' '+ font_family);
          },
          set: function (fontVars) {
            var len;
            /*DEBUG*/
            type_check(fontVars, 'string', {label:'Text.font', id:this.id});
            /*END_DEBUG*/
            //parse elements from string
            fontVars = fontVars.split(' ');
            len = fontVars.length;
            /*DEBUG*/
            if (len < 2 || len > 5) {
              throw new SyntaxError(this+".font: Invalid font string.");
            }
            /*END_DEBUG*/
            //fill in unspecified values with defaults
            if (len === 2) {
              fontVars.unshift(FontStyle.NORMAL, FontVariant.NORMAL, FontWeight.NORMAL);
            } else if (len === 3) {
              fontVars.splice(1, 0, FontVariant.NORMAL, FontWeight.NORMAL);
            } else if (len === 4) {
              fontVars.splice(1, 0, FontVariant.NORMAL);
            }
            /*DEBUG*/
            if (fontVars.length !== 5) {
              throw new ReferenceError(this+".font::fontArgs: Unable to parse font string.");
            }
            /*END_DEBUG*/
            text_sprite.fontStyle = fontVars[0];
            text_sprite.fontVariant = fontVars[1];
            text_sprite.fontWeight = fontVars[2];
            text_sprite.fontSize = fontVars[3];
            text_sprite.fontFamily = fontVars[4];
          }
        },

        /**
         * @name fontFamily
         * @return {String}
         * @throws {TypeError}
         * @property
         */
        'fontFamily': {
          enumerable: true,
          configurable: false,
          get: function () { return font_family; },
          set: function (fontFamilyVar) {
            /*DEBUG*/
            type_check(fontFamilyVar, 'string', {label:'Text.fontFamily', id:this.id});
            /*END_DEBUG*/
            font_family = fontFamilyVar;
            redraw();
          }
        },

        /**
         * @name fontSize
         * @return {Number} In pixels.
         * @throws {TypeError}
         * @property
         */
        'fontSize': {
          enumerable: true,
          configurable: false,
          get: function () { return font_size; },
          set: function (fontSizeVar) {
            if (typeof fontSizeVar === 'string') {
              fontSizeVar = window.parseInt(fontSizeVar, 10);
            }
            /*DEBUG*/
            type_check(fontSizeVar,'number', {label:'Text.fontSize', id:this.id});
            /*END_DEBUG*/
            font_size = fontSizeVar;
            redraw();
          }
        },

        /**
         * @name fontStyle
         * @return {FontStyle}
         * @throws {TypeError}
         * @throws {SyntaxError}
         * @property
         */
        'fontStyle': {
          enumerable: true,
          configurable: false,
          get: function () { return font_style; },
          set: function (fontStyleVar) {
            /*DEBUG*/
            type_check(fontStyleVar,'string', {label:'Text.fontStyle', id:this.id});
            reference_check(fontStyleVar === FontStyle.NORMAL || fontStyleVar === FontStyle.ITALIC || fontStyleVar === FontStyle.OBLIQUE,
                            {label:'Text.fontStyle', id:this.id, message:"Invalid FontStyle property"});
            /*END_DEBUG*/
            font_style = fontStyleVar;
            redraw();
          }
        },

        /**
         * @name fontVariant
         * @return {FontVariant}
         * @throws {TypeError}
         * @throws {SyntaxError}
         * @property
         */
        'fontVariant': {
          enumerable: true,
          configurable: false,
          get: function () { return font_variant; },
          set: function (fontVariantVar) {
            /*DEBUG*/
            type_check(fontVariantVar,'string', {label:'Text.fontVariant', id:this.id});
            reference_check(fontVariantVar === FontVariant.NORMAL || fontVariantVar === FontVariant.SMALL_CAPS,
                            {label:'Text.fontVariant', id:this.id, message:"Invalid FontVariant property"});
            /*END_DEBUG*/
            font_variant = fontVariantVar;
            redraw();
          }
        },

        /**
         * @name fontWeight
         * @return {FontWeight}
         * @throws {TypeError}
         * @throws {SyntaxError}
         * @property
         */
        'fontWeight': {
          enumerable: true,
          configurable: false,
          get: function () { return font_weight; },
          set: function (fontWeightVar) {
            /*DEBUG*/
            if (typeof fontWeightVar === 'string') {
              reference_check(fontWeightVar === FontWeight.NORMAL || fontWeightVar === FontVariant.BOLD || fontWeightVar === FontVariant.BOLDER || fontWeightVar === FontVariant.LIGHTER,
                              {label:'Text.fontWeight', id:this.id, message:"Invalid FontWeight property"});
            } else if (typeof fontWeightVar === 'number') {
              range_check(fontWeightVar === 100 || fontWeightVar === 200 ||
                          fontWeightVar === 300 || fontWeightVar === 400 ||
                          fontWeightVar === 500 || fontWeightVar === 600 ||
                          fontWeightVar === 700 || fontWeightVar === 800 ||
                          fontWeightVar === 900, {label:'Text.fontWeight', id:this.id, message:"Invalid font weight."});
            } else {
              throw new RangeError(this.id + " Text.fontWeight(weight): Invalid font weight.");
            }
            /*END_DEBUG*/
            font_weight = fontWeightVar;
            redraw();
          }
        },

        /**
         * @name align
         * @return {TextAlign}
         * @throws {TypeError}
         * @throws {SyntaxError}
         * @property
         */
        'align': {
          enumerable: true,
          configurable: false,
          get: function () { return text_align; },
          set: function (alignVar) {
            /*DEBUG*/
            type_check(alignVar,'string', {label:'Text.align', id:this.id});
            reference_check(alignVar === TextAlign.START || alignVar === TextAlign.END || alignVar === TextAlign.LEFT || alignVar === TextAlign.RIGHT || alignVar === TextAlign.CENTER,
                            {label:'Text.align', id:this.id, message:"Invalid TextAlign property."});
            /*END_DEBUG*/
            text_align = alignVar;
            redraw();
          }
        },

        /**
         * @name baseline
         * @return {TextBaseline}
         * @throws {TypeError}
         * @throws {SyntaxError}
         * @property
         */
        'baseline': {
          enumerable: true,
          configurable: false,
          get: function () { return text_baseline; },
          set: function (baselineVar) {
            /*DEBUG*/
            type_check(baselineVar,'string', {label:'Text.baseline', id:this.id});
            reference_check(baselineVar === TextBaseline.TOP || baselineVar === TextBaseline.MIDDLE || baselineVar === TextBaseline.BOTTOM || baselineVar === TextBaseline.HANGING || baselineVar === TextBaseline.ALPHABETIC || baselineVar === TextBaseline.IDEOGRAPHIC,
                            {label:'Text.baseline', id:this.id, message:"Invalid TextBaseline property."});
            /*END_DEBUG*/
            text_baseline = baselineVar;
            redraw();
          }
        },

        /**
         * @name strokeWidth
         * @return {Number}
         * @throws {TypeError}
         * @throws {RangeError}
         * @property
         */
        'strokeWidth': {
          enumerable: true,
          configurable: false,
          get: function () { return text_strokewidth; },
          set: function (widthVar) {
            /*DEBUG*/
            type_check(widthVar,'number', {label:'Text.strokeWidth', id:this.id});
            range_check(widthVar > 0, {label:'Text.strokeWidth', id:this.id, message:"Stroke width must be greater than zero."});
            /*END_DEBUG*/
            text_strokewidth = widthVar;
          }
        },

        /**
         * @name color
         * @return {Color}
         * @throws {TypeError}
         * @property
         */
        'color': {
          enumerable: true,
          configurable: false,
          get: function () { return text_color; },
          set: function (color) {
            if (typeof color === 'number') {
              color = hex_to_rgb_str(color);
            }
            /*DEBUG*/
            if (color !== null && color !== false) {
              type_check(color,'string', {label:'Text.color', id:this.id});
            }
            /*END_DEBUG*/
            text_color = color;
          }
        },

        /**
         * @name strokeColor
         * @return {Color}
         * @throws {TypeError}
         * @property
         */
        'strokeColor': {
          enumerable: true,
          configurable: false,
          get: function () { return text_strokecolor; },
          set: function (color) {
            if (typeof color === 'number') {
              color = hex_to_rgb_str(color);
            }
            /*DEBUG*/
            if (color !== null && color !== false) {
              type_check(color,'string', {label:'Text.strokeColor', id:this.id});
            }
            /*END_DEBUG*/
            text_strokecolor = color;
          }
        },

        /**
         * @name backgroundColor
         * @return {Color}
         * @throws {TypeError}
         * @property
         */
        'backgroundColor': {
          enumerable: true,
          configurable: false,
          get: function () { return text_bgcolor; },
          set: function (color) {
            if (typeof color === 'number') {
              color = hex_to_rgb_str(color);
            }
            /*DEBUG*/
            if (color !== null && color !== false) {
              type_check(color,'string', {label:'Text.backgroundColor', id:this.id});
            }
            /*END_DEBUG*/
            text_bgcolor = color;
          }
        }

      };
    }()));

    switch (arguments.length) {
    case 0:
      break;
    case 1:
      //passed function or text string
      if (typeof arguments[0] === 'function') {
        arguments[0].call(text_sprite);
        text = undefined;
      } else {
        /*DEBUG*/
        type_check(text,'string', {label:'Text', id:this.id, message:"Invalid initialization."});
        /*END_DEBUG*/
        text_sprite.text = text;
      }
      break;
    default:
      /*DEBUG*/
      throw new SyntaxError("[object Text](text): Invalid number of parameters.");
      /*END_DEBUG*/
    }

    return text_sprite;
  };

  text_sprite_static_properties = {
    /**
     * Returns the string representation of the specified object.
     * @name toString
     * @return {string}
     * @override
     */
    'toString': {
      enumerable: false,
      writable: false,
      configurable: false,
      value: function () { return "[object Text]"; }
    }
  };

}());//end class closure


text:
using System;
#if !CORLIB_ONLY
using System.ComponentModel;
#endif // !CORLIB_ONLY
#if NETFX_CORE
using System.Reflection;
#endif

namespace MsgPack.Serialization
{
	///
	///		This is intened to MsgPack for CLI internal use. Do not use this type from application directly.
	///		Helper methods for enum message pack serializer.
	///
#if !CORLIB_ONLY
	[EditorBrowsable( EditorBrowsableState.Never )]
#endif // !CORLIB_ONLY
	public static class EnumMessagePackSerializerHelpers
	{
		///
		///		Determines <see cref="EnumSerializationMethod"/> for the target.
		///
		/// <param name="context">Context information.</param>
		/// <param name="enumType">The target enum type.</param>
		/// <param name="enumMemberSerializationMethod">The method argued by the member.</param>
		/// <returns>Determined <see cref="EnumSerializationMethod"/> for the target.</returns>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="context"/> is <c>null</c>.
		///		Or <paramref name="enumType"/> is <c>null</c>.
		/// </exception>
		[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "enumType should be Type of Enum" )]
		public static EnumSerializationMethod DetermineEnumSerializationMethod(
			SerializationContext context,
			Type enumType,
			EnumMemberSerializationMethod enumMemberSerializationMethod
		)
		{
			if ( context == null )
			{
				throw new ArgumentNullException( "context" );
			}

			if ( enumType == null )
			{
				throw new ArgumentNullException( "enumType" );
			}

			EnumSerializationMethod method = context.EnumSerializationMethod;
			switch ( enumMemberSerializationMethod )
			{
				case EnumMemberSerializationMethod.ByName:
				{
					method = EnumSerializationMethod.ByName;
					break;
				}
				case EnumMemberSerializationMethod.ByUnderlyingValue:
				{
					method = EnumSerializationMethod.ByUnderlyingValue;
					break;
				}
				default:
				{
#if NETFX_CORE
					var messagePackEnumAttribute =
						enumType.GetTypeInfo().GetCustomAttribute<MessagePackEnumAttribute>();
					if ( messagePackEnumAttribute != null)
					{
						method = messagePackEnumAttribute.SerializationMethod;
#else
					var messagePackEnumAttributes =
						enumType.GetCustomAttributes( typeof( MessagePackEnumAttribute ), true );
					if ( messagePackEnumAttributes.Length > 0 )
					{
						// ReSharper disable once PossibleNullReferenceException
						method = ( messagePackEnumAttributes[ 0 ] as MessagePackEnumAttribute ).SerializationMethod;
#endif // NETFX_CORE
					}

					break;
				}
			}

			return method;
		}
	}
}


text:
Resque::Lifecycle extends Resque's default enqueueing process to add a simple timestamp to the payload of
each enqueued job. This allows easy measurement of queue throughput by inspecting the creation time of the
head element on the queue.

### Usage

```Ruby
require 'resque'
require 'resque-lifecycle'

module Resque
  include Resque::Lifecycle
end
```

Authors
=======

[Brandon Mitchell](https://github.com/bitbckt) & [Michael Grosser](http://grosser.it)

michael@grosser.it

License: MIT

[![Build Status](https://travis-ci.org/grosser/resque-lifecycle.png)](https://travis-ci.org/grosser/resque-lifecycle)


text:
package com.trifork.hotruby.classes;

import java.util.TimeZone;

import com.trifork.hotruby.callable.PublicMethod0;
import com.trifork.hotruby.callable.PublicMethod1;
import com.trifork.hotruby.callable.PublicMethod2;
import com.trifork.hotruby.objects.IRubyObject;
import com.trifork.hotruby.objects.RubyFixnum;
import com.trifork.hotruby.objects.RubyFloat;
import com.trifork.hotruby.objects.RubyString;
import com.trifork.hotruby.objects.RubyTime;
import com.trifork.hotruby.runtime.LoadedRubyRuntime;
import com.trifork.hotruby.runtime.MetaClass;
import com.trifork.hotruby.runtime.PublicMethodN;
import com.trifork.hotruby.runtime.RubyBlock;

public class RubyClassTime
	extends RubyBaseClassTime
{
	@Override
	public void init(MetaClass meta) {
		super.init(meta);

		meta.register_instance_method("new", new PublicMethod0() {
			@Override
			public IRubyObject call(IRubyObject receiver, RubyBlock block) {
				return new RubyTime();
			}
		});

		meta.register_instance_method("inspect", new PublicMethod0() {
			@Override
			public IRubyObject call(IRubyObject receiver, RubyBlock block) {
				return new RubyString(((RubyTime) receiver).inspect());
			}
		});

		meta.register_module_method("local", new PublicMethodN() {
			@Override
			public IRubyObject call(IRubyObject receiver, IRubyObject[] args, RubyBlock block) {
				return RubyTime.initialize(args, TimeZone.getDefault());
			}
		});

		meta.register_module_method("gm", new PublicMethodN() {
			@Override
			public IRubyObject call(IRubyObject receiver, IRubyObject[] args, RubyBlock block) {
				return RubyTime.initialize(args, TimeZone.getTimeZone("UTC"));
			}
		});

		meta.register_module_method("at", new PublicMethod2() {
            @Override
			public IRubyObject call(IRubyObject receiver, IRubyObject expr,
					RubyBlock b) {
            	if (expr instanceof RubyTime) {
					return new RubyTime((RubyTime) expr);
            	}
				return new RubyTime(RubyFixnum.induced_from(expr).longValue(), null);
			}

			@Override
			public IRubyObject call(IRubyObject receiver, IRubyObject expr1,
					IRubyObject expr2, RubyBlock b) {
				long secs = RubyFixnum.induced_from(expr1).longValue();
				long usecs = RubyFixnum.induced_from(expr2).longValue();
				long msecs = (secs * 1000) + (usecs / 1000);
				return new RubyTime(msecs, null);
			}

        	@Override
        	public int getArity() {
        		return 2;
        	}
		});

		meta.register_instance_method("-", new PublicMethod1() {
			@Override
			public IRubyObject call(IRubyObject receiver, IRubyObject arg, RubyBlock block) {
				return ((RubyTime)receiver).subtract(arg);
			}
		});

		meta.register_instance_method("to_f",
				new PublicMethod0() {
				@Override
				public IRubyObject call(IRubyObject receiver, RubyBlock block) {
					return ((RubyTime) receiver).to_f();
				}
			});

	}

}


text:
from lib.aws.exception import AwsServiceException

class EBErrorCode(object):
    '''Elastic Beanstalk error code'''

    TooManyApplicationsException = u'TooManyApplicationsException'
    TooManyConfigurationTemplates = u'TooManyConfigurationTemplates'
    OperationInProgress = u'OperationInProgress'

    SourceBundleDeletion = u'SourceBundleDeletion'
    S3LocationNotInServiceRegion = u'S3LocationNotInServiceRegion'

class ElasticBeanstalkException(AwsServiceException):
    def __init__(self, ex):
        if not issubclass(ex.__class__, AwsServiceException):
            raise AttributeError(u'Must initialize from instance of AwsServiceException subclass.')
        super(ElasticBeanstalkException, self).__init__(ex.message, ex.code, ex.http_code)

class TooManyApplicationsException(ElasticBeanstalkException):
    pass

class TooManyApplicationVersionsException(ElasticBeanstalkException):
    pass

class TooManyEnvironmentsException(ElasticBeanstalkException):
    pass

class AlreadyExistException(ElasticBeanstalkException):
    pass

class OperationInProgressException(ElasticBeanstalkException):
    pass

class ApplicationHasRunningEnvException(ElasticBeanstalkException):
    pass

class SourceBundleDeletionException(ElasticBeanstalkException):
    pass

class S3LocationNotInServiceRegionException(ElasticBeanstalkException):
    pass


text:
package org.greatage.inject.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * This annotation marks methods inside the IoC module as service build points that will build service instances with
 * specified unique id, scope and override option. Such methods can get as arguments other services, collection, list
 * and map for unordered, ordered and mapped configurations respectively.
 *
 * @author Ivan Khalopik
 * @since 1.0
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Build {

	Class value() default void.class;

	/**
	 * This property defines if service definition will be overridden or not.
	 */
	boolean override() default false;

	boolean eager() default false;
}


text:
package powerapi.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import powerapi.common.utils.DateFormatUtil;
import powerapi.common.utils.HttpUtil;
import powerapi.common.utils.JsonUtil;
import powerapi.dto.RequestDto;
import powerapi.entity.AutoTest;
import powerapi.entity.Function;
import powerapi.entity.Project;
import powerapi.entity.UnitTest;
import powerapi.service.AutoTestService;
import powerapi.service.FunctionService;
import powerapi.service.ProjectService;
import powerapi.service.UnitTestService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Melon on 17/3/14.
 */
@Controller
@RequestMapping("/auto")
public class AutoTestController extends BaseController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private AutoTestService autoTestService;

    @Autowired
    private FunctionService functionService;

    @Autowired
    private UnitTestService unitTestService;

//    @Resource
//    private AmqpTemplate amqpTemplate;

    @RequestMapping("/view")
    public String view(ModelMap model) {

        List<AutoTest> autoTests = autoTestService.findFinishedTest(getCurrentUser().getId());
        model.addAttribute("finished", autoTests);

        return "/test/auto";
    }

    @RequestMapping("/detail")
    public String detail(ModelMap model, @RequestParam(value = "id", required = true) Long id) {

        AutoTest autoTest = autoTestService.selectById(id);
        List<UnitTest> testList = unitTestService.findAutoTestList(id);
        model.addAttribute("autoTest", autoTest);
        model.addAttribute("testList", testList);
        return "/test/detail";
    }

    /**
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/projects", method = RequestMethod.GET)
    public String list() {
        List<Project> projects = projectService.getProjectList(getCurrentUser().getId());
        return JsonUtil.getInstance().setList(projects).result();
    }

    /**
     * 获取正在进行测试的数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/testing", method = RequestMethod.GET)
    public String loadtesting() {

        List<AutoTest> tests = autoTestService.findTesting(getCurrentUser().getId());
        return JsonUtil.getInstance().setList(tests).result();
    }

    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test(@RequestParam(value = "title", required = true) String title,
                       @RequestParam(value = "pId", required = true) Long pId,
                       @RequestParam(value = "headers", required = true) String headers) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("title", title);
        params.put("pId", pId);
        params.put("headers", headers);
        params.put("uId", getCurrentUser().getId());
//        amqpTemplate.convertAndSend("queueTestKey", JSON.toJSONString(params));
        return JsonUtil.getInstance().setStatus(1).result();
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam(value = "id", required = true) Long id) {

        return JsonUtil.getInstance().setStatus(autoTestService.deleteById(id) == true ? 1 : 0).result();
    }

}


text:
import numpy as np
from numpy.linalg import eigvals

def run_experiment(niter = 100):
	K = 100
	results = []
	for _ in range(niter):
		mat = np.random.randn(K, K)
		max_eigenvalue = np.abs(eigvals(mat)).max()
		results.append(max_eigenvalue)
	return results

some_results = run_experiment()
print(np.max(some_results))


text:
package org.usergrid.persistence.query.ir.result;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.junit.Test;
import org.usergrid.utils.UUIDUtils;

/**
 * @author tnine
 *
 */
public class IntersectionIteratorTest {

  @Test
  public void mutipleIterators() {

    UUID id1 = UUIDUtils.minTimeUUID(1);
    UUID id2 = UUIDUtils.minTimeUUID(2);
    UUID id3 = UUIDUtils.minTimeUUID(3);
    UUID id4 = UUIDUtils.minTimeUUID(4);
    UUID id5 = UUIDUtils.minTimeUUID(5);
    UUID id6 = UUIDUtils.minTimeUUID(6);
    UUID id7 = UUIDUtils.minTimeUUID(7);
    UUID id8 = UUIDUtils.minTimeUUID(8);
    UUID id9 = UUIDUtils.minTimeUUID(9);
    UUID id10 = UUIDUtils.minTimeUUID(10);

    // we should get intersection on 1, 3, and 8
    InOrderIterator first = new InOrderIterator(100);
    first.add(id1);
    first.add(id2);
    first.add(id3);
    first.add(id8);
    first.add(id9);

    InOrderIterator second = new InOrderIterator(100);
    second.add(id1);
    second.add(id2);
    second.add(id3);
    second.add(id4);
    second.add(id8);
    second.add(id10);

    InOrderIterator third = new InOrderIterator(100);
    third.add(id1);
    third.add(id3);
    third.add(id5);
    third.add(id6);
    third.add(id7);
    third.add(id8);

    InOrderIterator fourth = new InOrderIterator(100);
    fourth.add(id1);
    fourth.add(id2);
    fourth.add(id3);
    fourth.add(id6);
    fourth.add(id8);
    fourth.add(id10);

    IntersectionIterator intersection = new IntersectionIterator(100);
    intersection.addIterator(first);
    intersection.addIterator(second);
    intersection.addIterator(third);
    intersection.addIterator(fourth);

    Iterator<UUID> union = intersection.next().iterator();

    // now make sure it's right, only 1, 3 and 8 intersect
    assertTrue(union.hasNext());
    assertEquals(id1, union.next());

    assertTrue(union.hasNext());
    assertEquals(id3, union.next());

    assertTrue(union.hasNext());
    assertEquals(id8, union.next());

    assertFalse(union.hasNext());
  }

  @Test
  public void oneIterator() {

    UUID id1 = UUIDUtils.minTimeUUID(1);
    UUID id2 = UUIDUtils.minTimeUUID(2);
    UUID id3 = UUIDUtils.minTimeUUID(3);
    UUID id4 = UUIDUtils.minTimeUUID(4);

    // we should get intersection on 1, 3, and 8
    InOrderIterator first = new InOrderIterator(100);
    first.add(id1);
    first.add(id2);
    first.add(id3);
    first.add(id4);

    IntersectionIterator intersection = new IntersectionIterator(100);
    intersection.addIterator(first);

    // now make sure it's right, only 1, 3 and 8 intersect
    assertTrue(intersection.hasNext());

    Set<UUID> page = intersection.next();

    Iterator<UUID> union = page.iterator();

    assertEquals(id1, union.next());

    assertTrue(union.hasNext());
    assertEquals(id2, union.next());

    assertTrue(union.hasNext());
    assertEquals(id3, union.next());

    assertTrue(union.hasNext());
    assertEquals(id4, union.next());

    assertFalse(union.hasNext());
  }

  @Test
  public void noIterator() {
    IntersectionIterator union = new IntersectionIterator(100);

    // now make sure it's right, only 1, 3 and 8 intersect
    assertFalse(union.hasNext());
  }

  @Test
  public void largeIntersection() {

    int size = 10000;
    int firstIntersection = 100;
    int secondIntersection = 200;

    UUID[] firstSet = new UUID[size];
    UUID[] secondSet = new UUID[size];
    UUID[] thirdSet = new UUID[size];

    InOrderIterator first = new InOrderIterator(100);
    InOrderIterator second = new InOrderIterator(100);
    InOrderIterator third = new InOrderIterator(100);

    List<UUID> results = new ArrayList<UUID>(size / secondIntersection);

    for (int i = 0; i < size; i++) {
      firstSet[i] = UUIDUtils.newTimeUUID();
      // every 100 elements, set the element equal to the first set. This way we
      // have intersection

      if (i % firstIntersection == 0) {
        secondSet[i] = firstSet[i];
      } else {
        secondSet[i] = UUIDUtils.newTimeUUID();
      }

      if (i % secondIntersection == 0) {
        thirdSet[i] = firstSet[i];
        results.add(firstSet[i]);
      }

      else {
        thirdSet[i] = UUIDUtils.newTimeUUID();
      }
    }

    first.add(firstSet);

    reverse(secondSet);
    //reverse the second
    second.add(secondSet);
    third.add(thirdSet);

    //now itersect them and make sure we get all results in a small set

    int numPages = 2;
    int pageSize = results.size()/numPages;

    IntersectionIterator intersection = new IntersectionIterator(pageSize);
    intersection.addIterator(first);
    intersection.addIterator(second);
    intersection.addIterator(third);

    assertTrue(intersection.hasNext());

    Iterator<UUID> expected = results.iterator();
    Set<UUID> resultSet = intersection.next();
    Iterator<UUID> union = resultSet.iterator();

    while(union.hasNext()){
      assertTrue(expected.hasNext());
      assertEquals(expected.next(), union.next());
    }

    //now get the 2nd page
    resultSet = intersection.next();
    union = resultSet.iterator();

    while(union.hasNext()){
      assertTrue(expected.hasNext());
      assertEquals(expected.next(), union.next());
    }

    //no more elements
    assertFalse(intersection.hasNext());
    assertFalse(expected.hasNext());
  }

  /**
   * Tests that when there are multiple iterators, and one in the "middle" of the list returns no results, it will short circuit since no results will be
   * possible
   */
  @Test
  public void mutipleIteratorsNoIntersection() {

    UUID id1 = UUIDUtils.minTimeUUID(1);
    UUID id2 = UUIDUtils.minTimeUUID(2);
    UUID id3 = UUIDUtils.minTimeUUID(3);
    UUID id4 = UUIDUtils.minTimeUUID(4);
    UUID id5 = UUIDUtils.minTimeUUID(5);
    UUID id6 = UUIDUtils.minTimeUUID(6);
    UUID id7 = UUIDUtils.minTimeUUID(7);
    UUID id8 = UUIDUtils.minTimeUUID(8);
    UUID id9 = UUIDUtils.minTimeUUID(9);
    UUID id10 = UUIDUtils.minTimeUUID(10);

    // we should get intersection on 1, 3, and 8
    InOrderIterator first = new InOrderIterator(100);
    first.add(id1);
    first.add(id2);
    first.add(id3);
    first.add(id8);
    first.add(id9);

    InOrderIterator second = new InOrderIterator(100);
    second.add(id1);
    second.add(id2);
    second.add(id3);
    second.add(id4);
    second.add(id8);
    second.add(id10);

    InOrderIterator third = new InOrderIterator(100);

    InOrderIterator fourth = new InOrderIterator(100);
    fourth.add(id1);
    fourth.add(id2);
    fourth.add(id3);
    fourth.add(id6);
    fourth.add(id8);
    fourth.add(id10);

    IntersectionIterator intersection = new IntersectionIterator(100);
    intersection.addIterator(first);
    intersection.addIterator(second);
    intersection.addIterator(third);
    intersection.addIterator(fourth);

    Iterator<UUID> union = intersection.next().iterator();

    // now make sure it's right, only 1, 3 and 8 intersect
    assertFalse(union.hasNext());
  }

  private void reverse(UUID[] array){

    UUID temp = null;

    for(int i = 0; i < array.length/2; i ++){
      temp = array[i];
      array[i] = array[array.length-i-1];
      array[array.length-i-1] = temp;
    }
  }
}


text:
/* */
"format register";
define(["exports","aurelia-metadata","aurelia-path"], function (exports, _aureliaMetadata, _aureliaPath) {
  "use strict";

  var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };

  var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };

  var Metadata = _aureliaMetadata.Metadata;
  var Origin = _aureliaMetadata.Origin;
  var relativeToFile = _aureliaPath.relativeToFile;
  var ViewStrategy = exports.ViewStrategy = (function () {
    function ViewStrategy() {}

    _prototypeProperties(ViewStrategy, {
      normalize: {
        value: function normalize(value) {
          if (typeof value === "string") {
            value = new UseView(value);
          }

          if (value && !(value instanceof ViewStrategy)) {
            throw new Error("The view must be a string or an instance of ViewStrategy.");
          }

          return value;
        },
        writable: true,
        configurable: true
      },
      getDefault: {
        value: function getDefault(target) {
          var strategy, annotation;

          if (typeof target !== "function") {
            target = target.constructor;
          }

          annotation = Origin.get(target);
          strategy = Metadata.on(target).first(ViewStrategy);

          if (!strategy) {
            if (!annotation) {
              throw new Error("Cannot determinte default view strategy for object.", target);
            }

            strategy = new ConventionalView(annotation.moduleId);
          } else if (annotation) {
            strategy.moduleId = annotation.moduleId;
          }

          return strategy;
        },
        writable: true,
        configurable: true
      }
    }, {
      makeRelativeTo: {
        value: function makeRelativeTo(baseUrl) {},
        writable: true,
        configurable: true
      },
      loadViewFactory: {
        value: function loadViewFactory(viewEngine, options) {
          throw new Error("A ViewStrategy must implement loadViewFactory(viewEngine, options).");
        },
        writable: true,
        configurable: true
      }
    });

    return ViewStrategy;
  })();
  var UseView = exports.UseView = (function (ViewStrategy) {
    function UseView(path) {
      this.path = path;
    }

    _inherits(UseView, ViewStrategy);

    _prototypeProperties(UseView, null, {
      loadViewFactory: {
        value: function loadViewFactory(viewEngine, options) {
          if (!this.absolutePath && this.moduleId) {
            this.absolutePath = relativeToFile(this.path, this.moduleId);
          }

          return viewEngine.loadViewFactory(this.absolutePath || this.path, options, this.moduleId);
        },
        writable: true,
        configurable: true
      },
      makeRelativeTo: {
        value: function makeRelativeTo(file) {
          this.absolutePath = relativeToFile(this.path, file);
        },
        writable: true,
        configurable: true
      }
    });

    return UseView;
  })(ViewStrategy);
  var ConventionalView = exports.ConventionalView = (function (ViewStrategy) {
    function ConventionalView(moduleId) {
      this.moduleId = moduleId;
      this.viewUrl = ConventionalView.convertModuleIdToViewUrl(moduleId);
    }

    _inherits(ConventionalView, ViewStrategy);

    _prototypeProperties(ConventionalView, {
      convertModuleIdToViewUrl: {
        value: function convertModuleIdToViewUrl(moduleId) {
          return moduleId + ".html";
        },
        writable: true,
        configurable: true
      }
    }, {
      loadViewFactory: {
        value: function loadViewFactory(viewEngine, options) {
          return viewEngine.loadViewFactory(this.viewUrl, options, this.moduleId);
        },
        writable: true,
        configurable: true
      }
    });

    return ConventionalView;
  })(ViewStrategy);
  var NoView = exports.NoView = (function (ViewStrategy) {
    function NoView() {
      if (Object.getPrototypeOf(NoView) !== null) {
        Object.getPrototypeOf(NoView).apply(this, arguments);
      }
    }

    _inherits(NoView, ViewStrategy);

    _prototypeProperties(NoView, null, {
      loadViewFactory: {
        value: function loadViewFactory() {
          return Promise.resolve(null);
        },
        writable: true,
        configurable: true
      }
    });

    return NoView;
  })(ViewStrategy);
  exports.__esModule = true;
});


text:
<component name="CopyrightManager">
  <settings default="yongjia" />
</component>


text:
package com.atasoft.flangeassist.fragments;

import android.os.*;
import android.support.v4.app.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import com.atasoft.flangeassist.*;

public class TorqueFragment extends Fragment implements OnClickListener
{
    View thisFrag;
	public static final int[] EIGHT_BASE = {1,5,3,7,2,6,4,8};
	public static final int[] FOUR_BASE = {1,3,2,4};
	public static final String[] PAT_STRINGS = {"4-point", "8-point", "8-point alternate"};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.torquepat, container, false);
        thisFrag = v;
        setupSpinners();

        Button b = (Button) v.findViewById(R.id.submit);
        b.setOnClickListener(this);

        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
			case R.id.submit:
				submit();
				break;
        }
    }

	private void setupSpinners() {
		Spinner patSpin = (Spinner) thisFrag.findViewById(R.id.patSpin);
		ArrayAdapter<String> patAd = new ArrayAdapter<String>(getActivity(),
					android.R.layout.simple_spinner_item, PAT_STRINGS);
		patSpin.setAdapter(patAd);
	}

	private void submit() {
		Spinner patSpin = (Spinner) thisFrag.findViewById(R.id.patSpin);
		int selectedPos = patSpin.getSelectedItemPosition();
		int[] patBase = selectedPos > 0 ? EIGHT_BASE : FOUR_BASE;
		boolean isReverse = selectedPos == 2 ? true : false;

		String torqueString = genTorquePattern(patBase, isReverse);

		TextView patReturn = (TextView) thisFrag.findViewById(R.id.torqueReturn);
		patReturn.setText(torqueString);
	}

	private String genTorquePattern(int[] patBase, boolean isReverse) {
		String errInt = getString(R.string.errInt);
		String errEven = getString(R.string.errEven);
		String retString = "";
		EditText studBox = (EditText) thisFrag.findViewById(R.id.studBox);
		int studInt = parseInputInt(studBox);

		if (studInt < 8 || studInt > 1000) return errInt;
		int rem = studInt % 4;
		if (rem > 0) return errEven;

		if(!isReverse){
			for(int i = 0; i < patBase.length; i++) { //Muchos elegante
				for(int j = 0; j + patBase[i] <= studInt; j = j + patBase[patBase.length - 1]) {
					retString = retString + ", " + Integer.toString(patBase[i] + j);
				}
			}
		} else {  //Reverso mode
			//if 8 divisible, odd base offset is 8, else 4
			int startSub = studInt % 8 > 0 ? 4 : 8;
			for(int i = 0; i < patBase.length; i++){
				if(patBase[i] <= 4) {  //1 through 4 count from top
					retString += ", " + patBase[i];
					for(int j = studInt - startSub + patBase[i]; j > patBase[i]; j-=8){
						retString += ", " + Integer.toString(j);
					}
				} else {  //5 through 8 are normal 8 pt
					for(int j = patBase[i]; j <= studInt; j+=8) {
						retString += ", " + Integer.toString(j);
					}
				}
			}
		}
		return retString.substring(2);
	}

	private int parseInputInt(EditText editText) {
		try {
			return Integer.parseInt(editText.getText().toString());
		} catch (NumberFormatException e) {
			return 0;
		}
	}
}


text:
#pragma once

#include "EB_Entity.h"
#include "../../Core/C_Vec2.h"
#include "../../Core/C_Timer.h"

/**
@brief An Entity that uses a spritesheet for animation.
@author Jamie Slowgrove
*/
class EB_Animated : public EB_Entity
{
public:
	/**
	@brief Constructs the Animated Entity.
	@param sprite A pointer to the objects Texture.
	@param pos The position of the Entity.
	@param dimensions The dimensions of the Entity.
	@param animationFrames The number of animation frames in the spritesheet.
	@param spriteDimensions The dimensions of the sprite.
	@param animationLength The length of each animation frame.
	@param iD The ID of the Entity type.
	@param universalSpeed A pointer for the universal speed of the game.
	*/
	EB_Animated(C_Texture* sprite, C_Vec2 pos, C_Vec2 dimensions, int animationFrames,
		C_Vec2 spriteDimensions, float animationLength, std::string iD, float* universalSpee);

	/**
	@brief Destructs the Animated Entity object.
	*/
	~EB_Animated();

	/**
	@brief A pure virtual function that updates the Entity.
	@param dt The delta time.
	*/
	virtual void update(float dt) = 0;

	/**
	@brief Draws the StormCloud to the screen.
	@param renderer A pointer to the SDL renderer.
	*/
	void draw(SDL_Renderer* renderer);

protected:
	///The number of animation frames in the spritesheet
	int animationFrames;
	///The dimensions of the sprite in the spritesheet.
	C_Vec2 spriteDimensions;
	///The index of the current sprite in the spritesheet.
	C_Vec2 spriteIndex;
	///The animation timer.
	C_Timer animationTimer;

	/**
	@brief A virtual function that animates the sprite.
	@param dt The delta time.
	*/
	virtual void animate(float dt);
};