text:
// Uses Node, AMD or browser globals to create a module.
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals (root is window)
        root.lightbox = factory(root.jQuery);
    }
}(this, function ($) {

  function Lightbox(options) {
    this.album = [];
    this.currentImageIndex = void 0;
    this.init();

    // options
    this.options = $.extend({}, this.constructor.defaults);
    this.option(options);
  }

  // Descriptions of all options available on the demo site:
  // http://lokeshdhakar.com/projects/lightbox2/index.html#options
  Lightbox.defaults = {
    albumLabel: 'Imagen %1 of %2',
    alwaysShowNavOnTouchDevices: false,
    fadeDuration: 600,
    fitImagesInViewport: true,
    imageFadeDuration: 600,
    // maxWidth: 800,
    // maxHeight: 600,
    positionFromTop: 50,
    resizeDuration: 700,
    showImageNumberLabel: true,
    wrapAround: false,
    disableScrolling: false,
    /*
    Sanitize Title
    If the caption data is trusted, for example you are hardcoding it in, then leave this to false.
    This will free you to add html tags, such as links, in the caption.

    If the caption data is user submitted or from some other untrusted source, then set this to true
    to prevent xss and other injection attacks.
     */
    sanitizeTitle: false
  };

  Lightbox.prototype.option = function(options) {
    $.extend(this.options, options);
  };

  Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages) {
    return this.options.albumLabel.replace(/%1/g, currentImageNum).replace(/%2/g, totalImages);
  };

  Lightbox.prototype.init = function() {
    var self = this;
    // Both enable and build methods require the body tag to be in the DOM.
    $(document).ready(function() {
      self.enable();
      self.build();
    });
  };

  // Loop through anchors and areamaps looking for either data-lightbox attributes or rel attributes
  // that contain 'lightbox'. When these are clicked, start lightbox.
  Lightbox.prototype.enable = function() {
    var self = this;
    $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function(event) {
      self.start($(event.currentTarget));
      return false;
    });
  };

  // Build html for the lightbox and the overlay.
  // Attach event handlers to the new DOM elements. click click click
  Lightbox.prototype.build = function() {
    var self = this;
    $('

').appendTo($('body'));

    // Cache jQuery objects
    this.$lightbox       = $('#lightbox');
    this.$overlay        = $('#lightboxOverlay');
    this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
    this.$container      = this.$lightbox.find('.lb-container');
    this.$image          = this.$lightbox.find('.lb-image');
    this.$nav            = this.$lightbox.find('.lb-nav');

    // Store css values for future lookup
    this.containerPadding = {
      top: parseInt(this.$container.css('padding-top'), 10),
      right: parseInt(this.$container.css('padding-right'), 10),
      bottom: parseInt(this.$container.css('padding-bottom'), 10),
      left: parseInt(this.$container.css('padding-left'), 10)
    };

    this.imageBorderWidth = {
      top: parseInt(this.$image.css('border-top-width'), 10),
      right: parseInt(this.$image.css('border-right-width'), 10),
      bottom: parseInt(this.$image.css('border-bottom-width'), 10),
      left: parseInt(this.$image.css('border-left-width'), 10)
    };

    // Attach event handlers to the newly minted DOM elements
    this.$overlay.hide().on('click', function() {
      self.end();
      return false;
    });

    this.$lightbox.hide().on('click', function(event) {
      if ($(event.target).attr('id') === 'lightbox') {
        self.end();
      }
      return false;
    });

    this.$outerContainer.on('click', function(event) {
      if ($(event.target).attr('id') === 'lightbox') {
        self.end();
      }
      return false;
    });

    this.$lightbox.find('.lb-prev').on('click', function() {
      if (self.currentImageIndex === 0) {
        self.changeImage(self.album.length - 1);
      } else {
        self.changeImage(self.currentImageIndex - 1);
      }
      return false;
    });

    this.$lightbox.find('.lb-next').on('click', function() {
      if (self.currentImageIndex === self.album.length - 1) {
        self.changeImage(0);
      } else {
        self.changeImage(self.currentImageIndex + 1);
      }
      return false;
    });

    /*
      Show context menu for image on right-click

      There is a div containing the navigation that spans the entire image and lives above of it. If
      you right-click, you are right clicking this div and not the image. This prevents users from
      saving the image or using other context menu actions with the image.

      To fix this, when we detect the right mouse button is pressed down, but not yet clicked, we
      set pointer-events to none on the nav div. This is so that the upcoming right-click event on
      the next mouseup will bubble down to the image. Once the right-click/contextmenu event occurs
      we set the pointer events back to auto for the nav div so it can capture hover and left-click
      events as usual.
     */
    this.$nav.on('mousedown', function(event) {
      if (event.which === 3) {
        self.$nav.css('pointer-events', 'none');

        self.$lightbox.one('contextmenu', function() {
          setTimeout(function() {
              this.$nav.css('pointer-events', 'auto');
          }.bind(self), 0);
        });
      }
    });

    this.$lightbox.find('.lb-loader, .lb-close').on('click', function() {
      self.end();
      return false;
    });
  };

  // Show overlay and lightbox. If the image is part of a set, add siblings to album array.
  Lightbox.prototype.start = function($link) {
    var self    = this;
    var $window = $(window);

    $window.on('resize', $.proxy(this.sizeOverlay, this));

    $('select, object, embed').css({
      visibility: 'hidden'
    });

    this.sizeOverlay();

    this.album = [];
    var imageNumber = 0;

    function addToAlbum($link) {
      self.album.push({
        link: $link.attr('href'),
        title: $link.attr('data-title') || $link.attr('title')
      });
    }

    // Support both data-lightbox attribute and rel attribute implementations
    var dataLightboxValue = $link.attr('data-lightbox');
    var $links;

    if (dataLightboxValue) {
      $links = $($link.prop('tagName') + '[data-lightbox="' + dataLightboxValue + '"]');
      for (var i = 0; i < $links.length; i = ++i) {
        addToAlbum($($links[i]));
        if ($links[i] === $link[0]) {
          imageNumber = i;
        }
      }
    } else {
      if ($link.attr('rel') === 'lightbox') {
        // If image is not part of a set
        addToAlbum($link);
      } else {
        // If image is part of a set
        $links = $($link.prop('tagName') + '[rel="' + $link.attr('rel') + '"]');
        for (var j = 0; j < $links.length; j = ++j) {
          addToAlbum($($links[j]));
          if ($links[j] === $link[0]) {
            imageNumber = j;
          }
        }
      }
    }

    // Position Lightbox
    var top  = $window.scrollTop() + this.options.positionFromTop;
    var left = $window.scrollLeft();
    this.$lightbox.css({
      top: top + 'px',
      left: left + 'px'
    }).fadeIn(this.options.fadeDuration);

    // Disable scrolling of the page while open
    if (this.options.disableScrolling) {
      $('body').addClass('lb-disable-scrolling');
    }

    this.changeImage(imageNumber);
  };

  // Hide most UI elements in preparation for the animated resizing of the lightbox.
  Lightbox.prototype.changeImage = function(imageNumber) {
    var self = this;

    this.disableKeyboardNav();
    var $image = this.$lightbox.find('.lb-image');

    this.$overlay.fadeIn(this.options.fadeDuration);

    $('.lb-loader').fadeIn('slow');
    this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();

    this.$outerContainer.addClass('animating');

    // When image to show is preloaded, we send the width and height to sizeContainer()
    var preloader = new Image();
    preloader.onload = function() {
      var $preloader;
      var imageHeight;
      var imageWidth;
      var maxImageHeight;
      var maxImageWidth;
      var windowHeight;
      var windowWidth;

      $image.attr('src', self.album[imageNumber].link);

      $preloader = $(preloader);

      $image.width(preloader.width);
      $image.height(preloader.height);

      if (self.options.fitImagesInViewport) {
        // Fit image inside the viewport.
        // Take into account the border around the image and an additional 10px gutter on each side.

        windowWidth    = $(window).width();
        windowHeight   = $(window).height();
        maxImageWidth  = windowWidth - self.containerPadding.left - self.containerPadding.right - self.imageBorderWidth.left - self.imageBorderWidth.right - 20;
        maxImageHeight = windowHeight - self.containerPadding.top - self.containerPadding.bottom - self.imageBorderWidth.top - self.imageBorderWidth.bottom - 120;

        // Check if image size is larger then maxWidth|maxHeight in settings
        if (self.options.maxWidth && self.options.maxWidth < maxImageWidth) {
          maxImageWidth = self.options.maxWidth;
        }
        if (self.options.maxHeight && self.options.maxHeight < maxImageWidth) {
          maxImageHeight = self.options.maxHeight;
        }

        // Is there a fitting issue?
        if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
          if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
            imageWidth  = maxImageWidth;
            imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
            $image.width(imageWidth);
            $image.height(imageHeight);
          } else {
            imageHeight = maxImageHeight;
            imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
            $image.width(imageWidth);
            $image.height(imageHeight);
          }
        }
      }
      self.sizeContainer($image.width(), $image.height());
    };

    preloader.src          = this.album[imageNumber].link;
    this.currentImageIndex = imageNumber;
  };

  // Stretch overlay to fit the viewport
  Lightbox.prototype.sizeOverlay = function() {
    this.$overlay
      .width($(document).width())
      .height($(document).height());
  };

  // Animate the size of the lightbox to fit the image we are showing
  Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
    var self = this;

    var oldWidth  = this.$outerContainer.outerWidth();
    var oldHeight = this.$outerContainer.outerHeight();
    var newWidth  = imageWidth + this.containerPadding.left + this.containerPadding.right + this.imageBorderWidth.left + this.imageBorderWidth.right;
    var newHeight = imageHeight + this.containerPadding.top + this.containerPadding.bottom + this.imageBorderWidth.top + this.imageBorderWidth.bottom;

    function postResize() {
      self.$lightbox.find('.lb-dataContainer').width(newWidth);
      self.$lightbox.find('.lb-prevLink').height(newHeight);
      self.$lightbox.find('.lb-nextLink').height(newHeight);
      self.showImage();
    }

    if (oldWidth !== newWidth || oldHeight !== newHeight) {
      this.$outerContainer.animate({
        width: newWidth,
        height: newHeight
      }, this.options.resizeDuration, 'swing', function() {
        postResize();
      });
    } else {
      postResize();
    }
  };

  // Display the image and its details and begin preload neighboring images.
  Lightbox.prototype.showImage = function() {
    this.$lightbox.find('.lb-loader').stop(true).hide();
    this.$lightbox.find('.lb-image').fadeIn(this.options.imageFadeDuration);

    this.updateNav();
    this.updateDetails();
    this.preloadNeighboringImages();
    this.enableKeyboardNav();
  };

  // Display previous and next navigation if appropriate.
  Lightbox.prototype.updateNav = function() {
    // Check to see if the browser supports touch events. If so, we take the conservative approach
    // and assume that mouse hover events are not supported and always show prev/next navigation
    // arrows in image sets.
    var alwaysShowNav = false;
    try {
      document.createEvent('TouchEvent');
      alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false;
    } catch (e) {}

    this.$lightbox.find('.lb-nav').show();

    if (this.album.length > 1) {
      if (this.options.wrapAround) {
        if (alwaysShowNav) {
          this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
        }
        this.$lightbox.find('.lb-prev, .lb-next').show();
      } else {
        if (this.currentImageIndex > 0) {
          this.$lightbox.find('.lb-prev').show();
          if (alwaysShowNav) {
            this.$lightbox.find('.lb-prev').css('opacity', '1');
          }
        }
        if (this.currentImageIndex < this.album.length - 1) {
          this.$lightbox.find('.lb-next').show();
          if (alwaysShowNav) {
            this.$lightbox.find('.lb-next').css('opacity', '1');
          }
        }
      }
    }
  };

  // Display caption, image number, and closing button.
  Lightbox.prototype.updateDetails = function() {
    var self = this;

    // Enable anchor clicks in the injected caption html.
    // Thanks Nate Wright for the fix. @https://github.com/NateWr
    if (typeof this.album[this.currentImageIndex].title !== 'undefined' &&
      this.album[this.currentImageIndex].title !== '') {
      var $caption = this.$lightbox.find('.lb-caption');
      if (this.options.sanitizeTitle) {
        $caption.text(this.album[this.currentImageIndex].title);
      } else {
        $caption.html(this.album[this.currentImageIndex].title);
      }
      $caption.fadeIn('fast')
        .find('a').on('click', function(event) {
          if ($(this).attr('target') !== undefined) {
            window.open($(this).attr('href'), $(this).attr('target'));
          } else {
            location.href = $(this).attr('href');
          }
        });
    }

    if (this.album.length > 1 && this.options.showImageNumberLabel) {
      var labelText = this.imageCountLabel(this.currentImageIndex + 1, this.album.length);
      this.$lightbox.find('.lb-number').text(labelText).fadeIn('fast');
    } else {
      this.$lightbox.find('.lb-number').hide();
    }

    this.$outerContainer.removeClass('animating');

    this.$lightbox.find('.lb-dataContainer').fadeIn(this.options.resizeDuration, function() {
      return self.sizeOverlay();
    });
  };

  // Preload previous and next images in set.
  Lightbox.prototype.preloadNeighboringImages = function() {
    if (this.album.length > this.currentImageIndex + 1) {
      var preloadNext = new Image();
      preloadNext.src = this.album[this.currentImageIndex + 1].link;
    }
    if (this.currentImageIndex > 0) {
      var preloadPrev = new Image();
      preloadPrev.src = this.album[this.currentImageIndex - 1].link;
    }
  };

  Lightbox.prototype.enableKeyboardNav = function() {
    $(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
  };

  Lightbox.prototype.disableKeyboardNav = function() {
    $(document).off('.keyboard');
  };

  Lightbox.prototype.keyboardAction = function(event) {
    var KEYCODE_ESC        = 27;
    var KEYCODE_LEFTARROW  = 37;
    var KEYCODE_RIGHTARROW = 39;

    var keycode = event.keyCode;
    var key     = String.fromCharCode(keycode).toLowerCase();
    if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) {
      this.end();
    } else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
      if (this.currentImageIndex !== 0) {
        this.changeImage(this.currentImageIndex - 1);
      } else if (this.options.wrapAround && this.album.length > 1) {
        this.changeImage(this.album.length - 1);
      }
    } else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
      if (this.currentImageIndex !== this.album.length - 1) {
        this.changeImage(this.currentImageIndex + 1);
      } else if (this.options.wrapAround && this.album.length > 1) {
        this.changeImage(0);
      }
    }
  };

  // Closing time. :-(
  Lightbox.prototype.end = function() {
    this.disableKeyboardNav();
    $(window).off('resize', this.sizeOverlay);
    this.$lightbox.fadeOut(this.options.fadeDuration);
    this.$overlay.fadeOut(this.options.fadeDuration);
    $('select, object, embed').css({
      visibility: 'visible'
    });
    if (this.options.disableScrolling) {
      $('body').removeClass('lb-disable-scrolling');
    }
  };

  return new Lightbox();
}));


text:
{{<govuk_template}}

{{$head}}
  {{>includes/head}}
{{/head}}

{{$propositionHeader}}
  {{>includes/propositional_navigation}}
{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}

  {{>includes/phase_banner}}

			<form action="preparing-food" method="#" class="form">

				Back

				Personal details

							Full name

								For example, 'Mr. John Smith'

							<input type="text" class="form-control" id="full-number">

							<fieldset>
								<legend class="form-label-bold">Date of birth</legend>

For example, 31 04 1970

										Day
										<input type="text" class="form-control" id="dob-day">

										Month
										<input type="text" class="form-control" id="dob-month">

										Year
										<input type="text" class="form-control" id="dob-year">

							</fieldset>

							National Insurance number

								For example, 'VO 12 34 56 D'

							<input type="text" class="form-control" id="ni-number">

					<input type="submit" class="button" value="Continue">

				<button class="button">Save</button>

			</form>

{{/content}}

{{$bodyEnd}}
  {{>includes/elements_scripts}}
{{/bodyEnd}}

{{/govuk_template}}

redpajama_set_name: RedPajamaGithub


text:
package file;

import java.io.Serializable;

/**
 *
 * @author varun
 */
public class AvatarFile implements Serializable {
    private final int icon;
    private final String avatarHeading, avatarSubheading, path, type;

    public AvatarFile(int icon, String avatarHeading, String avatarSubheading, String path, String type) {
        this.icon = icon;
        this.avatarHeading = avatarHeading;
        this.avatarSubheading = avatarSubheading;
        this.path = path;
        this.type = type;
    }

    public String getHeading() {
        return avatarHeading;
    }

    public String getPath() {
        return path;
    }

    public String getSubheading() {
        return avatarSubheading;
    }

    public int getIcon() {
        return icon;
    }

    public String getType() {
        return type;
    }
}


text:
.PHONY: doc all clean clean-all test clean-doc pack

all:
	make -C src
	make -C examples
	make -C tests

rebuild-all: clean-all
	make all

32:
	make -C src        32
	make -C examples   32
	make -C tests      32
64:
	make -C src        64
	make -C examples   64
	make -C tests      64

test:
	make -C src        test
test32:
	make -C src        test32

###untested
#fuzzy:
#	make -C src fuzzy

install:
	make -C src install
uninstall:
	make -C src uninstall
# cleaning etc.
clean:
	make -C src clean
	make -C examples clean
	make -C tests clean

### quick test
#test:
#	make -C src test

# doxygen-generated documentation
doc:
	doxygen doxygen.config

clean-doc:
	rm -rf ./doc/doxygen
	make -C ./doc/latex clean

clean-all: clean clean-doc
	make -C examples clean-all
	make -C ./doc/latex clean-all
	make -C tests clean-all

# create archive with .git
pack: clean-all
	(N=`basename $$(pwd)`; cd ..; \
         tar czvf $$N-git-`date +"%Y%m%d"`.tar.gz $$N ; \
         echo "Done.")

# create distribution archive
dist: clean-all
	touch . # the main directory should have current time stamp
	(N=`basename $$(pwd)`; cd ..; \
         tar czvf $$N-`date +"%Y%m%d"`.tar.gz $$N --exclude=$$N/.git\*; \
         echo "Done.")


text:
var mongoose = require('mongoose'),
    extend = require('mongoose-schema-extend'),
    EntitySchema = require('../entity').schema;

var schema = EntitySchema.extend({
  point: {
    lat: Number,
    lng: Number
  }
});

module.exports = mongoose.model('Place', schema);


text:
package com.spotify.scio.extra

import com.spotify.scio.extra.Collections._
import org.scalacheck._
import org.scalatest._

import scala.collection.compat._ // scalafix:ok

class CollectionsSpec extends PropertySpec {
  val posInts: Gen[Int] = Gen.posNum[Int]
  val intLists: Gen[List[Int]] = Arbitrary.arbitrary[List[Int]]
  val tupleLists: Gen[List[(String, Int)]] = Arbitrary.arbitrary[List[(String, Int)]]

  property("top") {
    forAll(intLists, posInts) { (xs, num) =>
      val maxExpected = xs.sorted.reverse.take(num).sorted
      val minExpected = xs.sorted.take(num).sorted
      def verify(actual: Iterable[Int], expected: List[Int]): Assertion =
        actual.toList.sorted shouldBe expected

      verify(xs.top(num), maxExpected)
      verify(xs.top(num)(Ordering[Int].reverse), minExpected)
      verify(xs.to(Array).top(num), maxExpected)
      verify(xs.to(Iterable).top(num), maxExpected)
    }
  }

  property("topByKey") {
    forAll(tupleLists, posInts) { (xs, num) =>
      val maxExpected =
        xs.groupBy(_._1)
          .iterator
          .map { case (k, v) => k -> v.map(_._2).sorted.reverse.take(num).sorted }
          .toMap
      val minExpected =
        xs.groupBy(_._1)
          .iterator
          .map { case (k, v) => k -> v.map(_._2).sorted.take(num).sorted }
          .toMap
      def verify(actual: Map[String, Iterable[Int]], expected: Map[String, List[Int]]): Assertion =
        actual.iterator.map { case (k, v) => k -> v.toList.sorted }.toMap shouldBe expected
      verify(xs.topByKey(num), maxExpected)
      verify(xs.topByKey(num)(Ordering[Int].reverse), minExpected)
      verify(xs.to(Array).topByKey(num), maxExpected)
      verify(xs.to(Iterable).topByKey(num), maxExpected)
    }
  }
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }

    public function changelog()
    {
        return view('changelog');
    }

    public function todo()
    {
        return view('todo');
    }

    public function kb()
    {
        return view('kb');
    }

}


text:
package sas

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// Asset is a nested struct in sas response
type Asset struct {
	InternetIp    string `json:"InternetIp" xml:"InternetIp"`
	OsName        string `json:"OsName" xml:"OsName"`
	Ip            string `json:"Ip" xml:"Ip"`
	Os            string `json:"Os" xml:"Os"`
	InstanceId    string `json:"InstanceId" xml:"InstanceId"`
	ClientStatus  string `json:"ClientStatus" xml:"ClientStatus"`
	VpcInstanceId string `json:"VpcInstanceId" xml:"VpcInstanceId"`
	IntranetIp    string `json:"IntranetIp" xml:"IntranetIp"`
	AssetType     string `json:"AssetType" xml:"AssetType"`
	RegionId      string `json:"RegionId" xml:"RegionId"`
	Uuid          string `json:"Uuid" xml:"Uuid"`
	Flag          int    `json:"Flag" xml:"Flag"`
	RegionName    string `json:"RegionName" xml:"RegionName"`
	InstanceName  string `json:"InstanceName" xml:"InstanceName"`
	Region        string `json:"Region" xml:"Region"`
}


text:
"""
Documint action factories.

Each public function produces a `dict` suitable for passing to the
`perform_action` session method.
"""

def _action(name, params):
    """
    Convenience function for constructing an action `dict`.
    """
    return {u'action': name,
            u'parameters': params}

def render_html(input, base_uri=None):
    """
    Render an HTML document to a PDF document.

    :param unicode input: URI to the HTML content to render.
    :param base_uri: Optional base URI to use when resolving relative URIs.
    :type base_uri: unicode or None
    """
    def _parse_render(result):
        return result[u'links'][u'result'][0]
    params = {u'input': input}
    if base_uri is not None:
        params[u'base-uri'] = base_uri
    return _action(u'render-html', params), _parse_render

def render_legacy_html(input, base_uri=None):
    """
    Render a legacy HTML document to a PDF document.

    :param unicode input: URI to the HTML content to render.
    :param base_uri: Optional base URI to use when resolving relative URIs.
    :type base_uri: unicode or None
    """
    def _parse_render(result):
        return result[u'links'][u'result'][0]
    params = {u'input': input}
    if base_uri is not None:
        params[u'base-uri'] = base_uri
    return _action(u'render-legacy-html', params), _parse_render

def concatenate(inputs):
    """
    Concatenate several PDF documents together.

    :param inputs: Document URIs.
    :type inputs: list of unicode
    """
    def _parse_concat(result):
        return result[u'links'][u'result'][0]
    return _action(u'concatenate',
                   {u'inputs': inputs}), _parse_concat

def thumbnails(input, dpi):
    """
    Generate JPEG thumbnails for a PDF document.

    :param unicode input: Document URI.
    :param int dpi: Pixel density of the thumbnail.
    """
    def _parse_thumbnails(result):
        return result[u'links'][u'results']
    return _action(u'thumbnails',
                   {u'input': input,
                    u'dpi': dpi}), _parse_thumbnails

def split(input, page_groups):
    """
    Split a PDF document into multiple PDF documents.

    :param unicode input: Document URI.
    :param page-groups: Page number groups, each group of pages represents a
    new document containing only those pages from the original document in the
    order they are specified. For example ``[[1, 3, 2], [4, 2]]`` produces two
    documents: one with pages 1, 3 and 2; the other with pages 4 and 2.
    :type page-groups: list of lists of int
    """
    def _parse_split(result):
        return result[u'links'][u'results']
    return _action(u'split',
                   {u'input': input,
                    u'page-groups': page_groups}), _parse_split

def metadata(input):
    """
    Retrieve metadata from a PDF document.

    :param unicode input: Document URI.
    """
    def _parse_metadata(result):
        return result[u'body']
    return _action(u'metadata',
                   {u'input': input}), _parse_metadata

def sign(inputs, certificate_alias, location, reason):
    """
    Digitally sign one or more PDF documents.

    :param inputs: Document URIs.
    :type inputs: list of unicode
    :param unicode certificate_alias: Certificate alias, in the Documint
    keystore, to use when signing the documents.
    :param unicode location: Signing location.
    :param unicode reason: Signing reason.
    """
    def _parse_sign(result):
        return result[u'links'][u'results']
    return _action(u'sign',
                   {u'inputs': inputs,
                    u'certificate-alias': certificate_alias,
                    u'location': location,
                    u'reason': reason}), _parse_sign

def crush(input, compression_profile):
    """
    Compress a PDF document according to a specific compression profile.

    :param unicode input: Document URI.
    :param unicode compression_profile: Compression profile to use, possible
    choices are: ``text`` (bilevel), ``photo-grey`` (greyscale), ``photo``
    (colour).
    """
    def _parse_crush(result):
        return result[u'links'][u'result'][0]
    return _action(u'crush',
                   {u'input': input,
                    u'compression-profile': compression_profile}), _parse_crush

def stamp(watermark, inputs):
    """
    Stamp documents with a watermark document.

    :param unicode watermark: Watermark document URI.
    :type input: ``List[unicode]``
    :param input: Document URIs.
    """
    def _parse_stamps(result):
        return result[u'links'][u'results']
    return _action(u'stamp',
                   {u'watermark': watermark,
                    u'inputs': inputs}), _parse_stamps


text:
property :username, String, name_property: true
property :password, String
property :auth_username, String, default: 'root'
property :auth_password, String, default: 'root'

action :create do
  unless password
    Chef::Log.fatal('You must provide a password for the :create action on this resource!')
  end

  begin
    unless client.list_cluster_admins.member?(username)
      client.create_cluster_admin(username, password)
      updated_by_last_action true
    end
  rescue InfluxDB::AuthenticationError => e
    # Exception due to missing admin user
    # https://influxdb.com/docs/v0.9/administration/authentication.html
    # https://github.com/chrisduong/chef-influxdb/commit/fe730374b4164e872cbf208c06d2462c8a056a6a
    if e.to_s.include? 'create admin user'
      client.create_cluster_admin(username, password)
      updated_by_last_action true
    end
  end
end

action :update do
  unless password
    Chef::Log.fatal('You must provide a password for the :update action on this resource!')
  end

  client.update_user_password(username, password)
  updated_by_last_action true
end

action :delete do
  if client.list_cluster_admins.member?(username)
    client.delete_user(username)
    updated_by_last_action true
  end
end

def client
  require 'influxdb'
  @client ||=
    InfluxDB::Client.new(
      username: auth_username,
      password: auth_password,
      retry: 10
    )
end


text:
var through = require('through2');
var coffee = require('coffee-script');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var Buffer = require('buffer').Buffer;
var applySourceMap = require('vinyl-sourcemaps-apply');
var path = require('path');
var merge = require('merge');

module.exports = function (opt) {
  function transform(file, enc, cb) {
    if (file.isNull()) return cb(null, file);
    if (file.isStream()) return cb(new PluginError('gulp-coffee', 'Streaming not supported'));

    var data;
    var str = file.contents.toString('utf8');
    var dest = gutil.replaceExtension(file.path, '.js');

    var options = merge({
      bare: false,
      header: false,
      sourceMap: !!file.sourceMap,
      sourceRoot: false,
      literate: /\.(litcoffee|coffee\.md)$/.test(file.path),
      filename: file.path,
      sourceFiles: [file.relative],
      generatedFile: gutil.replaceExtension(file.relative, '.js')
    }, opt);

    try {
      data = coffee.compile(str, options);
    } catch (err) {
      return cb(new PluginError('gulp-coffee', err));
    }

    if (data && data.v3SourceMap && file.sourceMap) {
      applySourceMap(file, data.v3SourceMap);
      file.contents = new Buffer(data.js);
    } else {
      file.contents = new Buffer(data);
    }

    file.path = dest;
    cb(null, file);
  }

  return through.obj(transform);
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<testPlan xmlns="urn:io.apiman.test:2014:02:testPlan">

  <testGroup name="Configure the Gateway" endpoint="api">
    <test name="Publish Api">test-plan-data/policies/failure-processing/001-publish-api.resttest</test>
    <test name="Register Client">test-plan-data/policies/failure-processing/002-register-client.resttest</test>
  </testGroup>

  <testGroup name="Trigger policy failure. Expect processing of failures.">
    <test name="Hit rate limit, then TestPolicy processes failure.">test-plan-data/policies/failure-processing/003-failure.resttest</test>
  </testGroup>

</testPlan>


text:
/* jshint camelcase: false */
/* jshint expr: true */
var chai      = require('chai')
  , Sequelize = require('../../index')
  , Promise   = Sequelize.Promise
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , config    = require(__dirname + "/../config/config")
  , datetime  = require('chai-datetime')
  , promised  =  require("chai-as-promised")
  , _         = require('lodash')
  , async     = require('async')

chai.use(promised);
chai.use(datetime)
chai.config.includeStack = true

describe(Support.getTestDialectTeaser("DAOFactory"), function () {
  beforeEach(function(done) {
    this.User = this.sequelize.define('User', {
      username:     DataTypes.STRING,
      secretValue:  DataTypes.STRING,
      data:         DataTypes.STRING,
      intVal:       DataTypes.INTEGER,
      theDate:      DataTypes.DATE,
      aBool:        DataTypes.BOOLEAN
    })

    this.User.sync({ force: true }).success(function() {
      done()
    })
  })

  describe('find', function() {
    it('supports transactions', function(done) {
      Support.prepareTransactionTest(this.sequelize, function(sequelize) {
        var User = sequelize.define('User', { username: Sequelize.STRING })

        User.sync({ force: true }).success(function() {
          sequelize.transaction().then(function(t) {
            User.create({ username: 'foo' }, { transaction: t }).success(function() {
              User.find({
                where: { username: 'foo' }
              }).success(function(user1) {
                User.find({
                  where: { username: 'foo' },
                }, { transaction: t }).success(function(user2) {
                  expect(user1).to.be.null
                  expect(user2).to.not.be.null

                  t.rollback().success(function() {
                    done()
                  })
                })
              })
            })
          })
        })
      })
    })

    describe('general / basic function', function() {
      beforeEach(function(done) {
        var self = this
        this.User.create({username: 'barfooz'}).success(function(user) {
          self.UserPrimary = self.sequelize.define('UserPrimary', {
            specialkey: {
              type: DataTypes.STRING,
              primaryKey: true
            }
          })

          self.UserPrimary.sync({force: true}).success(function() {
            self.UserPrimary.create({specialkey: 'a string'}).success(function() {
              self.user = user
              done()
            })
          })
        })
      })

      if (Support.dialectIsMySQL()) {
        // Bit fields interpreted as boolean need conversion from buffer / bool.
        // Sqlite returns the inserted value as is, and postgres really should the built in bool type instead

        it('allows bit fields as booleans', function () {
          var self = this,
            bitUser = this.sequelize.define('bituser', {
              bool: 'BIT(1)'
            }, {
              timestamps: false
            });

          // First use a custom data type def to create the bit field
          return bitUser.sync({ force: true }).then(function () {
            // Then change the definition to BOOLEAN
            bitUser = self.sequelize.define('bituser', {
              bool: DataTypes.BOOLEAN
            }, {
              timestamps: false
            });

            return bitUser.bulkCreate([
              { bool: 0 },
              { bool: 1 }
            ]);
          }).then(function () {
            return bitUser.findAll();
          }).then(function (bitUsers) {
            expect(bitUsers[0].bool).not.to.be.ok;
            expect(bitUsers[1].bool).to.be.ok;
          });
        });
      }

      it('does not modify the passed arguments', function (done) {
        var options = { where: ['specialkey = ?', 'awesome']}

        this.UserPrimary.find(options).success(function() {
          expect(options).to.deep.equal({ where: ['specialkey = ?', 'awesome']})
          done()
        })
      })

      it('treats questionmarks in an array', function(done) {
        this.UserPrimary.find({
          where: ['specialkey = ?', 'awesome']
        }).on('sql', function(sql) {
          expect(sql).to.contain("WHERE specialkey = 'awesome'")
          done()
        })
      })

      it('doesn\'t throw an error when entering in a non integer value for a specified primary field', function(done) {
        this.UserPrimary.find('a string').success(function(user) {
          expect(user.specialkey).to.equal('a string')
          done()
        })
      })

      it.skip('doesn\'t throw an error when entering in a non integer value', function(done) {
        this.User.find('a string value').success(function(user) {
          expect(user).to.be.null
          done()
        })
      })

      it('returns a single dao', function(done) {
        var self = this
        this.User.find(this.user.id).success(function(user) {
          expect(Array.isArray(user)).to.not.be.ok
          expect(user.id).to.equal(self.user.id)
          expect(user.id).to.equal(1)
          done()
        })
      })

      it('returns a single dao given a string id', function(done) {
        var self = this
        this.User.find(this.user.id + '').success(function(user) {
          expect(Array.isArray(user)).to.not.be.ok
          expect(user.id).to.equal(self.user.id)
          expect(user.id).to.equal(1)
          done()
        })
      })

      it("should make aliased attributes available", function(done) {
        this.User.find({
          where: { id: 1 },
          attributes: ['id', ['username', 'name']]
        }).success(function(user) {
          expect(user.dataValues.name).to.equal('barfooz')
          done()
        })
      })

      it("should not try to convert boolean values if they are not selected", function(done) {
        var UserWithBoolean = this.sequelize.define('UserBoolean', {
          active: Sequelize.BOOLEAN
        })

        UserWithBoolean.sync({force: true}).success(function () {
          UserWithBoolean.create({ active: true }).success(function(user) {
            UserWithBoolean.find({ where: { id: user.id }, attributes: [ 'id' ] }).success(function(user) {
              expect(user.active).not.to.exist
              done()
            })
          })
        })
      })

      it('finds a specific user via where option', function(done) {
        this.User.find({ where: { username: 'barfooz' } }).success(function(user) {
          expect(user.username).to.equal('barfooz')
          done()
        })
      })

      it("doesn't find a user if conditions are not matching", function(done) {
        this.User.find({ where: { username: 'foo' } }).success(function(user) {
          expect(user).to.be.null
          done()
        })
      })

      it('allows sql logging', function(done) {
        this.User.find({ where: { username: 'foo' } }).on('sql', function(sql) {
          expect(sql).to.exist
          expect(sql.toUpperCase().indexOf("SELECT")).to.be.above(-1)
          done()
        })
      })

      it('ignores passed limit option', function(done) {
        this.User.find({ limit: 10 }).success(function(user) {
          // it returns an object instead of an array
          expect(Array.isArray(user)).to.not.be.ok
          expect(user.dataValues.hasOwnProperty('username')).to.be.ok
          done()
        })
      })

      it('finds entries via primary keys', function(done) {
        var self = this
          , UserPrimary = self.sequelize.define('UserWithPrimaryKey', {
          identifier: {type: Sequelize.STRING, primaryKey: true},
          name: Sequelize.STRING
        })

        UserPrimary.sync({ force: true }).success(function() {
          UserPrimary.create({
            identifier: 'an identifier',
            name: 'John'
          }).success(function(u) {
            expect(u.id).not.to.exist

            UserPrimary.find('an identifier').success(function(u2) {
              expect(u2.identifier).to.equal('an identifier')
              expect(u2.name).to.equal('John')
              done()
            })
          })
        })
      })

      it('finds entries via a string primary key called id', function(done) {
        var self = this
          , UserPrimary = self.sequelize.define('UserWithPrimaryKey', {
          id: {type: Sequelize.STRING, primaryKey: true},
          name: Sequelize.STRING
        })

        UserPrimary.sync({ force: true }).success(function() {
          UserPrimary.create({
            id: 'a string based id',
            name: 'Johnno'
          }).success(function() {
            UserPrimary.find('a string based id').success(function(u2) {
              expect(u2.id).to.equal('a string based id')
              expect(u2.name).to.equal('Johnno')
              done()
            })
          })
        })
      })

      it('always honors ZERO as primary key', function(_done) {
        var self = this
          , permutations = [
            0,
            '0',
            {where: {id: 0}},
            {where: {id: '0'}}
          ]
          , done = _.after(2 * permutations.length, _done)

        this.User.bulkCreate([{username: 'jack'}, {username: 'jack'}]).success(function() {
          permutations.forEach(function(perm) {
            self.User.find(perm).done(function(err, user) {
              expect(err).to.be.null
              expect(user).to.be.null
              done()
            }).on('sql', function(s) {
              expect(s.indexOf(0)).not.to.equal(-1)
              done()
            })
          })
        })
      })

      it('should allow us to find IDs using capital letters', function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          ID: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
          Login: { type: Sequelize.STRING }
        })

        User.sync({ force: true }).success(function() {
          User.create({Login: 'foo'}).success(function() {
            User.find(1).success(function(user) {
              expect(user).to.exist
              expect(user.ID).to.equal(1)
              done()
            })
          })
        })
      })
    })

    describe('eager loading', function() {
      beforeEach(function(done) {
        var self         = this
        self.Task        = self.sequelize.define('Task', { title: Sequelize.STRING })
        self.Worker      = self.sequelize.define('Worker', { name: Sequelize.STRING })

        this.init = function(callback) {
          self.sequelize.sync({ force: true }).success(function() {
            self.Worker.create({ name: 'worker' }).success(function(worker) {
              self.Task.create({ title: 'homework' }).success(function(task) {
                self.worker    = worker
                self.task      = task
                callback()
              })
            })
          })
        }
        done()
      })

      describe('belongsTo', function() {
        describe('generic', function() {
          it('throws an error about unexpected input if include contains a non-object', function(done) {
            var self = this
            self.Worker.find({ include: [ 1 ] }).catch(function(err) {
              expect(err.message).to.equal('Include unexpected. Element has to be either a Model, an Association or an object.');
              done()
            })
          })

          it('throws an error if included DaoFactory is not associated', function(done) {
            var self = this
            self.Worker.find({ include: [ self.Task ] }).catch(function(err) {
              expect(err.message).to.equal('Task is not associated to Worker!');
              done()
            })
          })

          it('returns the associated worker via task.worker', function(done) {
            var self = this
            this.Task.belongsTo(this.Worker)
            this.init(function() {
              self.task.setWorker(self.worker).success(function() {
                self.Task.find({
                  where:   { title: 'homework' },
                  include: [ self.Worker ]
                }).complete(function(err, task) {
                  expect(err).to.be.null
                  expect(task).to.exist
                  expect(task.Worker).to.exist
                  expect(task.Worker.name).to.equal('worker')
                  done()
                })
              })
            })
          })
        })

        it('returns the private and public ip', function(done) {
          var self = Object.create(this)
          self.Domain      = self.sequelize.define('Domain', { ip: Sequelize.STRING })
          self.Environment = self.sequelize.define('Environment', { name: Sequelize.STRING })
          self.Environment.belongsTo(self.Domain, { as: 'PrivateDomain', foreignKey: 'privateDomainId' })
          self.Environment.belongsTo(self.Domain, { as: 'PublicDomain', foreignKey: 'publicDomainId' })

          self.Domain.sync({ force: true }).success(function() {
            self.Environment.sync({ force: true }).success(function() {
              self.Domain.create({ ip: '192.168.0.1' }).success(function(privateIp) {
                self.Domain.create({ ip: '91.65.189.19' }).success(function(publicIp) {
                  self.Environment.create({ name: 'environment' }).success(function(env) {
                    env.setPrivateDomain(privateIp).success(function() {
                      env.setPublicDomain(publicIp).success(function() {
                        self.Environment.find({
                          where:   { name: 'environment' },
                          include: [
                            { daoFactory: self.Domain, as: 'PrivateDomain' },
                            { daoFactory: self.Domain, as: 'PublicDomain' }
                          ]
                        }).complete(function(err, environment) {
                          expect(err).to.be.null
                          expect(environment).to.exist
                          expect(environment.PrivateDomain).to.exist
                          expect(environment.PrivateDomain.ip).to.equal('192.168.0.1')
                          expect(environment.PublicDomain).to.exist
                          expect(environment.PublicDomain.ip).to.equal('91.65.189.19')
                          done()
                        })
                      })
                    })
                  })
                })
              })
            })
          })
        })

        it('eager loads with non-id primary keys', function(done) {
          var self = this
          self.User = self.sequelize.define('UserPKeagerbelong', {
            username: {
              type: Sequelize.STRING,
              primaryKey: true
            }
          })
          self.Group = self.sequelize.define('GroupPKeagerbelong', {
            name: {
              type: Sequelize.STRING,
              primaryKey: true
            }
          })
          self.User.belongsTo(self.Group)

          self.sequelize.sync({ force: true }).success(function() {
            self.Group.create({ name: 'people' }).success(function() {
              self.User.create({ username: 'someone', GroupPKeagerbelongName: 'people' }).success(function() {
                self.User.find({
                  where: {
                    username: 'someone'
                  },
                  include: [self.Group]
                }).complete(function (err, someUser) {
                  expect(err).to.be.null
                  expect(someUser).to.exist
                  expect(someUser.username).to.equal('someone')
                  expect(someUser.GroupPKeagerbelong.name).to.equal('people')
                  done()
                })
              })
            })
          })
        })

        it('getting parent data in many to one relationship', function(done) {
          var User = this.sequelize.define('User', {
            id:  {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
            username:  {type: Sequelize.STRING}
          })

          var Message = this.sequelize.define('Message', {
            id:  {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
            user_id:  {type: Sequelize.INTEGER},
            message:  {type: Sequelize.STRING}
          })

          User.hasMany(Message)
          Message.belongsTo(User, { foreignKey: 'user_id' })

          this.sequelize.sync({ force: true }).success(function() {
            User.create({username: 'test_testerson'}).success(function(user) {
              Message.create({user_id: user.id, message: 'hi there!'}).success(function() {
                Message.create({user_id: user.id, message: 'a second message'}).success(function() {
                  Message.findAll({

                    where: {user_id: user.id},
                    attributes: [
                      'user_id',
                      'message'
                    ],
                    include: [{ model: User, attributes: ['username'] }]

                  }).success(function(messages) {
                    expect(messages.length).to.equal(2);

                    expect(messages[0].message).to.equal('hi there!');
                    expect(messages[0].User.username).to.equal('test_testerson');

                    expect(messages[1].message).to.equal('a second message');
                    expect(messages[1].User.username).to.equal('test_testerson');

                    done()

                  })
                })
              })
            })
          })
        })

        it('allows mulitple assocations of the same model with different alias', function (done) {
          var self = this

          this.Worker.belongsTo(this.Task, { as: 'ToDo' })
          this.Worker.belongsTo(this.Task, { as: 'DoTo' })
          this.init(function () {
            self.Worker.find({
              include: [
                { model: self.Task, as: 'ToDo' },
                { model: self.Task, as: 'DoTo' }
              ]
            }).success(function () {
              // Just being able to include both shows that this test works, so no assertions needed
              done()
            })
          })
        })
      })

      describe('hasOne', function() {
        beforeEach(function(done) {
          var self = this
          this.Worker.hasOne(this.Task)
          this.init(function() {
            self.worker.setTask(self.task).success(function() {
              done()
            })
          })
        })

        it('throws an error if included DaoFactory is not associated', function(done) {
          var self = this
          self.Task.find({ include: [ self.Worker ] }).catch(function(err) {
            expect(err.message).to.equal('Worker is not associated to Task!');
            done()
          })
        })

        it('returns the associated task via worker.task', function(done) {
          this.Worker.find({
            where:   { name: 'worker' },
            include: [ this.Task ]
          }).complete(function(err, worker) {
            expect(err).to.be.null
            expect(worker).to.exist
            expect(worker.Task).to.exist
            expect(worker.Task.title).to.equal('homework')
            done()
          })
        })

        it('eager loads with non-id primary keys', function(done) {
          var self = this
          self.User = self.sequelize.define('UserPKeagerone', {
            username: {
              type: Sequelize.STRING,
              primaryKey: true
            }
          })
          self.Group = self.sequelize.define('GroupPKeagerone', {
            name: {
              type: Sequelize.STRING,
              primaryKey: true
            }
          })
          self.Group.hasOne(self.User)

          self.sequelize.sync({ force: true }).success(function() {
            self.Group.create({ name: 'people' }).success(function() {
              self.User.create({ username: 'someone', GroupPKeageroneName: 'people' }).success(function() {
                self.Group.find({
                  where: {
                    name: 'people'
                  },
                  include: [self.User]
                }).complete(function (err, someGroup) {
                  expect(err).to.be.null
                  expect(someGroup).to.exist
                  expect(someGroup.name).to.equal('people')
                  expect(someGroup.UserPKeagerone.username).to.equal('someone')
                  done()
                })
              })
            })
          })
        })
      })

      describe('hasOne with alias', function() {
        it('throws an error if included DaoFactory is not referenced by alias', function(done) {
          var self = this
          self.Worker.find({ include: [ self.Task ] }).catch(function(err) {
            expect(err.message).to.equal('Task is not associated to Worker!');
            done()
          })
        })

        describe('alias', function() {
          beforeEach(function(done) {
            var self = this
            this.Worker.hasOne(this.Task, { as: 'ToDo' })
            this.init(function() {
              self.worker.setToDo(self.task).success(function() {
                done()
              })
            })
          })

          it('throws an error if alias is not associated', function(done) {
            var self = this
            self.Worker.find({ include: [ { daoFactory: self.Task, as: 'Work' } ] }).catch(function(err) {
              expect(err.message).to.equal('Task (Work) is not associated to Worker!');
              done()
            })
          })

          it('returns the associated task via worker.task', function(done) {
            this.Worker.find({
              where:   { name: 'worker' },
              include: [ { daoFactory: this.Task, as: 'ToDo' } ]
            }).complete(function(err, worker) {
              expect(err).to.be.null
              expect(worker).to.exist
              expect(worker.ToDo).to.exist
              expect(worker.ToDo.title).to.equal('homework')
              done()
            })
          })

          it('returns the associated task via worker.task when daoFactory is aliased with model', function(done) {
            this.Worker.find({
              where:   { name: 'worker' },
              include: [ { model: this.Task, as: 'ToDo' } ]
            }).complete(function(err, worker) {
              expect(worker.ToDo.title).to.equal('homework')
              done()
            })
          })

           it('allows mulitple assocations of the same model with different alias', function (done) {
            var self = this

            this.Worker.hasOne(this.Task, { as: 'DoTo' })
            this.init(function () {
              self.Worker.find({
                include: [
                  { model: self.Task, as: 'ToDo' },
                  { model: self.Task, as: 'DoTo' }
                ]
              }).success(function () {
                // Just being able to include both shows that this test works, so no assertions needed
                done()
              })
            })
          })
        })
      })

      describe('hasMany', function() {
        beforeEach(function(done) {
          var self = this
          this.Worker.hasMany(this.Task)
          this.init(function() {
            self.worker.setTasks([ self.task ]).success(function() {
              done()
            })
          })
        })

        it('throws an error if included DaoFactory is not associated', function(done) {
          var self = this
          self.Task.find({ include: [ self.Worker ] }).catch(function(err) {
            expect(err.message).to.equal('Worker is not associated to Task!');
            done()
          })
        })

        it('returns the associated tasks via worker.tasks', function(done) {
          this.Worker.find({
            where:   { name: 'worker' },
            include: [ this.Task ]
          }).complete(function(err, worker) {
            expect(err).to.be.null
            expect(worker).to.exist
            expect(worker.Tasks).to.exist
            expect(worker.Tasks[0].title).to.equal('homework')
            done()
          })
        })

        it('including two has many relations should not result in duplicate values', function(done) {
          var self = this

          self.Contact = self.sequelize.define('Contact', { name: DataTypes.TEXT })
          self.Photo = self.sequelize.define('Photo', { img: DataTypes.TEXT })
          self.PhoneNumber = self.sequelize.define('PhoneNumber', { phone: DataTypes.TEXT })

          self.Contact.hasMany(self.Photo, { as: 'Photos' })
          self.Contact.hasMany(self.PhoneNumber)

          self.sequelize.sync({ force: true }).success(function() {
            self.Contact.create({ name: 'Boris' }).success(function(someContact) {
              self.Photo.create({ img: 'img.jpg' }).success(function(somePhoto) {
                self.PhoneNumber.create({ phone: '000000' }).success(function(somePhone1) {
                  self.PhoneNumber.create({ phone: '111111' }).success(function(somePhone2) {
                    someContact.setPhotos([somePhoto]).complete(function (err) {
                      expect(err).to.be.null
                      someContact.setPhoneNumbers([somePhone1, somePhone2]).complete(function () {
                        self.Contact.find({
                          where: {
                            name: 'Boris'
                          },
                          include: [self.PhoneNumber, { daoFactory: self.Photo, as: 'Photos' }]
                        }).complete(function (err, fetchedContact) {
                          expect(err).to.be.null
                          expect(fetchedContact).to.exist
                          expect(fetchedContact.Photos.length).to.equal(1)
                          expect(fetchedContact.PhoneNumbers.length).to.equal(2)
                          done()
                        })
                      })
                    })
                  })
                })
              })
            })
          })
        })

        it('eager loads with non-id primary keys', function(done) {
          var self = this
          self.User = self.sequelize.define('UserPKeagerone', {
            username: {
              type: Sequelize.STRING,
              primaryKey: true
            }
          })
          self.Group = self.sequelize.define('GroupPKeagerone', {
            name: {
              type: Sequelize.STRING,
              primaryKey: true
            }
          })
          self.Group.hasMany(self.User)
          self.User.hasMany(self.Group)

          self.sequelize.sync({ force: true }).success(function() {
            self.User.create({ username: 'someone' }).success(function(someUser) {
              self.Group.create({ name: 'people' }).success(function(someGroup) {
                someUser.setGroupPKeagerones([someGroup]).complete(function (err) {
                  expect(err).to.be.null
                  self.User.find({
                    where: {
                      username: 'someone'
                    },
                    include: [self.Group]
                  }).complete(function (err, someUser) {
                    expect(err).to.be.null
                    expect(someUser).to.exist
                    expect(someUser.username).to.equal('someone')
                    expect(someUser.GroupPKeagerones[0].name).to.equal('people')
                    done()
                  })
                })
              })
            })
          })
        })
      })

      describe('hasMany with alias', function() {
        it('throws an error if included DaoFactory is not referenced by alias', function(done) {
          var self = this
          self.Worker.find({ include: [ self.Task ] }).catch(function(err) {
            expect(err.message).to.equal('Task is not associated to Worker!');
            done()
          })
        })

        describe('alias', function() {
          beforeEach(function(done) {
            var self = this
            this.Worker.hasMany(this.Task, { as: 'ToDos' })
            this.init(function() {
              self.worker.setToDos([ self.task ]).success(function() {
                done()
              })
            })
          })

          it('throws an error if alias is not associated', function(done) {
            var self = this
            self.Worker.find({ include: [ { daoFactory: self.Task, as: 'Work' } ] }).catch(function(err) {
              expect(err.message).to.equal('Task (Work) is not associated to Worker!');
              done()
            })
          })

          it('returns the associated task via worker.task', function(done) {
            this.Worker.find({
              where:   { name: 'worker' },
              include: [ { daoFactory: this.Task, as: 'ToDos' } ]
            }).complete(function(err, worker) {
              expect(err).to.be.null
              expect(worker).to.exist
              expect(worker.ToDos).to.exist
              expect(worker.ToDos[0].title).to.equal('homework')
              done()
            })
          })

          it('returns the associated task via worker.task when daoFactory is aliased with model', function(done) {
            this.Worker.find({
              where:   { name: 'worker' },
              include: [ { model: this.Task, as: 'ToDos' } ]
            }).complete(function(err, worker) {
              expect(worker.ToDos[0].title).to.equal('homework')
              done()
            })
          })

          it('allows mulitple assocations of the same model with different alias', function (done) {
            var self = this

            this.Worker.hasMany(this.Task, { as: 'DoTos' })
            this.init(function () {
              self.Worker.find({
                include: [
                  { model: self.Task, as: 'ToDos' },
                  { model: self.Task, as: 'DoTos' }
                ]
              }).success(function () {
                // Just being able to include both shows that this test works, so no assertions needed
                done()
              })
            })
          })
        })
      })

      describe('hasMany (N:M) with alias', function () {
        beforeEach(function () {
          this.Product  = this.sequelize.define('Product', { title: Sequelize.STRING })
          this.Tag      = this.sequelize.define('Tag', { name: Sequelize.STRING })
        })

        it('returns the associated models when using through as string and alias', function (done) {
          var self = this

          this.Product.hasMany(this.Tag, {as: 'tags', through: 'product_tag'})
          this.Tag.hasMany(this.Product, {as: 'products', through: 'product_tag'})

          this.sequelize.sync().done(function () {
            async.auto({
              createProducts: function (callback) {
                self.Product.bulkCreate([
                  {title: 'Chair'},
                  {title: 'Desk'},
                  {title: 'Handbag'},
                  {title: 'Dress'},
                  {title: 'Jan'}
                ]).done(callback)
              },
              // bulkCreate doesn't include id for some reason, not going to fix tis now
              products: ['createProducts', function (callback) {
                self.Product.findAll().done(callback)
              }],
              createTags: function (callback) {
                self.Tag.bulkCreate([
                  {name: 'Furniture'},
                  {name: 'Clothing'},
                  {name: 'People'}
                ]).done(callback)
              },
              tags: ['createTags', function (callback) {
                self.Tag.findAll().done(callback)
              }],
            }, function (err, results) {
              expect(err).not.to.exist

              var products = results.products
                , tags = results.tags

              async.parallel([
                function (callback) {
                  products[0].setTags([tags[0], tags[1]]).done(callback)
                },
                function (callback) {
                  products[1].addTag(tags[0]).done(callback)
                },
                function (callback) {
                  products[2].addTag(tags[1]).done(callback)
                },
                function (callback) {
                  products[3].setTags([tags[1]]).done(callback)
                },
                function (callback) {
                  products[4].setTags([tags[2]]).done(callback)
                }
              ], function (err) {
                expect(err).not.to.exist

                async.parallel([
                  function (callback) {
                    self.Tag.find({
                      where: {
                        id: tags[0].id
                      },
                      include: [
                        {model: self.Product, as: 'products'}
                      ]
                    }).done(function (err, tag) {
                      expect(tag).to.exist
                      expect(tag.products.length).to.equal(2)
                      callback()
                    })
                  },
                  function (callback) {
                    tags[1].getProducts().done(function (err, products) {
                      expect(products.length).to.equal(3)
                      callback()
                    })
                  },
                  function (callback) {
                    self.Product.find({
                      where: {
                        id: products[0].id
                      },
                      include: [
                        {model: self.Tag, as: 'tags'}
                      ]
                    }).done(function (err, product) {
                      expect(product).to.exist
                      expect(product.tags.length).to.equal(2)
                      callback()
                    })
                  },
                  function (callback) {
                    products[1].getTags().done(function (err, tags) {
                      expect(tags.length).to.equal(1)
                      callback()
                    })
                  },
                ], done)
              })
            })
          })
        })

        it('returns the associated models when using through as model and alias', function () {
          // Exactly the same code as the previous test, just with a through model instance, and promisified
          var ProductTag = this.sequelize.define('product_tag');

          this.Product.hasMany(this.Tag, {as: 'tags', through: ProductTag})
          this.Tag.hasMany(this.Product, {as: 'products', through: ProductTag})

          return this.sequelize.sync().bind(this).then(function () {
            return Promise.all([
              this.Product.bulkCreate([
                {title: 'Chair'},
                {title: 'Desk'},
                {title: 'Handbag'},
                {title: 'Dress'},
                {title: 'Jan'}
              ]),
              this.Tag.bulkCreate([
                {name: 'Furniture'},
                {name: 'Clothing'},
                {name: 'People'}
              ])
            ]);
          }).then(function () {
            return Promise.all([
              this.Product.findAll(),
              this.Tag.findAll()
            ])
          }).spread(function (products, tags) {
            this.products = products;
            this.tags = tags;

            return Promise.all([
              products[0].setTags([tags[0], tags[1]]),
              products[1].addTag(tags[0]),
              products[2].addTag(tags[1]),
              products[3].setTags([tags[1]]),
              products[4].setTags([tags[2]])
            ])
          }).then(function () {
            return Promise.all([
              expect(this.Tag.find({
                where: {
                  id: this.tags[0].id
                },
                include: [
                  {model: this.Product, as: 'products'}
                ]
              })).to.eventually.have.property('products').to.have.length(2),
              expect(this.Product.find({
                where: {
                  id: this.products[0].id
                },
                include: [
                  {model: this.Tag, as: 'tags'}
                ]
              })).to.eventually.have.property('tags').to.have.length(2),
              expect(this.tags[1].getProducts()).to.eventually.have.length(3),
              expect(this.products[1].getTags()).to.eventually.have.length(1),
            ]);
          });
        })
      })
    })

    describe('queryOptions', function() {
      beforeEach(function(done) {
        var self = this
        this.User.create({username: 'barfooz'}).success(function(user) {
          self.user = user
          done()
        })
      })

      it("should return a DAO when queryOptions are not set", function(done) {
        var self = this
        this.User.find({ where: { username: 'barfooz'}}).done(function(err, user) {
          expect(user).to.be.instanceOf(self.User.DAO)
          done()
        })
      })

      it("should return a DAO when raw is false", function(done) {
        var self = this
        this.User.find({ where: { username: 'barfooz'}}, { raw: false }).done(function(err, user) {
          expect(user).to.be.instanceOf(self.User.DAO)
          done()
        })
      })

      it("should return raw data when raw is true", function(done) {
        var self = this
        this.User.find({ where: { username: 'barfooz'}}, { raw: true }).done(function(err, user) {
          expect(user).to.not.be.instanceOf(self.User.DAO)
          expect(user).to.be.instanceOf(Object)
          done()
        })
      })
    })
  })
})


text:
(function($){
	var th = null, cf = null, toast = function(m,o){
		// fix option type
		o = $.extend({ duration: 5000, sticky: false, 'type': ''}, o);
		typeof o.duration === 'number' || (o.duration = 5000);
		typeof o.sticky === 'boolean' || (o.sticky = false);
		typeof o.type === 'string' || (o.type = '');
		// create host on first call
		if(!th){
			// get/fix config
			cf = toast.config;
			th = $('

').addClass('toast').appendTo(document.body).hide();
			typeof cf.width === 'number' || (cf.width = 500);
			typeof cf.align === 'string' || (cf.align = 'center');
			typeof cf.closeForStickyOnly === 'boolean' || (cf.closeForStickyOnly = false);
			th.width(cf.width);
			(cf.align === 'left' || cf.align === 'right') && th.css('margin','5px').css(cf.align, '0') || th.css({left: '50%', margin: '5px 0 0 -' + (cf.width / 2) + 'px'});
		}
		// create toast
		var ti = $('

').hide().html(m).appendTo(th), cb = $('<button>×</button>').addClass('close').prependTo(ti), to = null;
		// setup close button
		cb.click(function(){
			clearTimeout(to);
			ti.animate({ height: 0, opacity: 0}, 'fast', function(){
				ti.remove();
				th.children().length || th.removeClass('active').hide();
			});
		});
		cf.closeForStickyOnly && !o.sticky && cb.hide();
		// add type class
		o.type !== '' && ti.addClass(o.type);
		// show host if necessary
		!th.hasClass('active') && th.addClass('active').show();
		// setup timeout unless sticky
		!o.sticky && o.duration > 0 && (to = setTimeout(function(){ cb.click(); }, o.duration));
		// show toast
		ti.fadeIn('normal');
	};
	toast.config = { width: 500, align: 'center', closeForStickyOnly: true };
	$.extend({ toast: toast });
})(jQuery);


text:
class AddStashIdAndStashOauthTokenAndStashOauthTokenSecretToUser < ActiveRecord::Migration
  def change
    add_column :users, :stash_id, :integer
    add_column :users, :stash_oauth_token, :string
    add_column :users, :stash_oauth_token_secret, :string

    add_index  :users, :stash_id, :unique => true
  end
end


text:
package org.apache.camel.component.quartz2;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;

public class QuartzComponentCamelContextSharedSchedulerTest {

    private DefaultCamelContext camel1;
    private DefaultCamelContext camel2;

    @Before
    public void setUp() throws Exception {
        camel1 = new DefaultCamelContext();
        camel1.setName("camel-1");
        camel1.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("quartz2://myGroup/myTimerName?cron=0/2+*+*+*+*+?").to("mock:one");
            }
        });
        camel1.start();

        camel2 = new DefaultCamelContext();
        camel2.setName("camel-2");

        Scheduler camel1Scheduler = camel1.getComponent("quartz2", QuartzComponent.class).getScheduler();
        QuartzComponent camel2QuartzComponent = camel2.getComponent("quartz2", QuartzComponent.class);
        camel2QuartzComponent.setScheduler(camel1Scheduler);

        camel2.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("quartz2://myOtherGroup/myOtherTimerName?cron=0/1+*+*+*+*+?").to("mock:two");
            }
        });

        camel2.start();
    }

    @After
    public void tearDown() throws Exception {
        camel1.stop();
        camel2.stop();
    }

    @Test
    public void testTwoCamelContext() throws Exception {
        MockEndpoint mock1 = camel1.getEndpoint("mock:one", MockEndpoint.class);
        mock1.expectedMinimumMessageCount(2);

        MockEndpoint mock2 = camel2.getEndpoint("mock:two", MockEndpoint.class);
        mock2.expectedMinimumMessageCount(6);
        mock1.assertIsSatisfied();

        JobDetail detail = mock1.getReceivedExchanges().get(0).getIn().getHeader("jobDetail", JobDetail.class);
        Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_CRON_EXPRESSION).equals("0/2 * * * * ?"), CoreMatchers.is(true));

        camel1.stop();

        mock2.assertIsSatisfied();

        detail = mock2.getReceivedExchanges().get(0).getIn().getHeader("jobDetail", JobDetail.class);
        Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_CRON_EXPRESSION).equals("0/1 * * * * ?"), CoreMatchers.is(true));

        camel2.stop();
    }
}


text:
package io.github.vhula.ftracker.core;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Setter;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;

/**
 * @author Vadym Hula <vadym.hula@gmail.com>
 */
@Entity
@Table(name = "ft_glist")
@Setter
@JsonIdentityInfo(property = "id", generator = ObjectIdGenerators.PropertyGenerator.class)
public class GroceryList extends FTrackerEntity {

    private static final long serialVersionUID = -8787406601658797815L;

    @OneToMany(mappedBy = "groceryList", cascade = CascadeType.ALL)
    private List<GroceryListOwners> owners;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "groceryList", orphanRemoval = true, cascade = CascadeType.ALL)
    private List<GroceryItem> groceryItems;

    public List<GroceryListOwners> getOwners() {
        return owners;
    }

    public String getName() {
        return name;
    }

    public List<GroceryItem> getGroceryItems() {
        return groceryItems;
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 2: 174 (1923)

#### Original name
Opegrapha rimosa DC.

### Remarks
null


text:
from flask import Flask, g
from flask_wtf.csrf import CsrfProtect
from flask_login import current_user, LoginManager
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from werkzeug.security import generate_password_hash

from server.database.models import Base, Entry, Feed, User
from .main.views import main

app = Flask(__name__, instance_relative_config=True)
app.config.from_object("config")
app.config.from_pyfile("config.py")
app.register_blueprint(main)
app.config["DATABASE_PATH"] = "sqlite:///{}".format(
    os.path.join(os.path.dirname(__file__), app.config["DATABASE_PATH"]))

csrf = CsrfProtect()
csrf.init_app(app)

login_manager = LoginManager()
login_manager.login_view = "main.login"

@login_manager.user_loader
def load_user(user_id):
    return g.db.query(User).get(int(user_id))

app.login_manager = None

@app.before_first_request
def init_app():
    init_db(create=False)
    g.db.query(User).delete()
    password = generate_password_hash(app.config["PASSWORD"])
    user = User(app.config["USER_NAME"], password)
    g.db.add(user)
    g.db.commit()
    g.user = current_user
    if app.login_manager is None:
        app.login_manager = login_manager
        app.login_manager.init_app(app)

@app.before_request
def init_db(create=False):
    engine = create_engine(app.config["DATABASE_PATH"])
    Session = sessionmaker(bind=engine)
    g.db = Session()
    if create or not engine.dialect.has_table(engine.connect(), "feed"):
        Entry.__table__.drop(engine, checkfirst=True)
        Feed.__table__.drop(engine, checkfirst=True)
    Base.metadata.create_all(engine, checkfirst=True)

@app.teardown_appcontext
def shutdown_session(exception=None):
    db = getattr(g, 'db', None)
    if db is not None:
        g.db.close()


text:
package net.meisen.general.server.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.meisen.general.server.api.IConnectorValidator;
import net.meisen.general.server.api.IListener;
import net.meisen.general.server.exceptions.ServerSettingsException;
import net.meisen.general.server.settings.pojos.Connector;

/**
 * Really, really simple implementation of a IListener and a
 * IConnectorValidator.
 *
 * @author pmeisen
 *
 */
public class DummyListener implements IListener, IConnectorValidator {
	private final static Logger LOG = LoggerFactory
			.getLogger(DummyListener.class);

	/**
	 * The name of this Listener used when defined it, instead of
	 * the class-name
	 */
	public static final String NAME = "DUMMY";

	private Thread dummyThread = null;

	@Override
	public void initialize(final Connector connector) {
		if (!connector.isEnable()) {
			// do nothing
		} else if (LOG.isWarnEnabled()) {
			LOG.warn("Trying to initialize the dummy listener, this listener is just a dummy for the basic implementation of the server.");
		}
	}

	@Override
	public void open() {

		// create a dummy thread
		if (dummyThread == null) {
			dummyThread = new Thread() {
				public void run() {
					try {
						// set the thread into waiting mode
						synchronized (this) {
							dummyThread.wait();
						}
					} catch (final InterruptedException e) {
						interrupt();
					}
				}
			};

			dummyThread.setName("DummyListenerThread");
		}

		dummyThread.start();
	}

	@Override
	public String toString() {
		return "Dummy";
	}

	@Override
	public boolean validate(final Connector connector)
			throws ServerSettingsException {
		return true;
	}

	@Override
	public void close() {

		if (dummyThread != null) {

			// close the thread
			synchronized (dummyThread) {
				dummyThread.notifyAll();
			}

			dummyThread = null;
		}
	}
}


text:
package com.defano.hypertalk.ast.statement.command;

import com.defano.wyldcard.part.model.PartModel;
import com.defano.hypertalk.ast.expression.Expression;
import com.defano.hypertalk.ast.statement.Command;
import com.defano.hypertalk.exception.HtException;
import com.defano.hypertalk.exception.HtSemanticException;
import com.defano.wyldcard.runtime.ExecutionContext;
import org.antlr.v4.runtime.ParserRuleContext;

public class EditScriptCmd extends Command {

    private final Expression partExpression;

    public EditScriptCmd(ParserRuleContext context, Expression partExpression) {
        super(context, "edit");
        this.partExpression = partExpression;
    }

    @Override
    protected void onExecute(ExecutionContext context) throws HtException {
        partExpression.partFactor(context, PartModel.class, new HtSemanticException("No such part.")).editScript(context);
    }
}


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

#region Imports

using System;

#endregion

namespace Hyperstore.Modeling
{
    ///-------------------------------------------------------------------------------------------------
    /// <summary>
    ///  Additional information for session completing events.
    /// </summary>
    /// <seealso cref="T:System.EventArgs"/>
    ///-------------------------------------------------------------------------------------------------
    public class SessionCompletingEventArgs : EventArgs
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="SessionCompletingEventArgs" /> class.
        /// </summary>
        /// <param name="session">The session.</param>
        internal SessionCompletingEventArgs(ISessionInformation session)
        {
            DebugContract.Requires(session);
            Session = session;
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Gets the session.
        /// </summary>
        /// <value>
        ///  The session id.
        /// </value>
        ///-------------------------------------------------------------------------------------------------
        public ISessionInformation Session { get; private set; }
    }
}


text:
<?php

namespace sexlog\Monolog;

use PhpAmqpLib\Connection\AMQPStreamConnection;

abstract class Queue
{
    /**
     * @var AMQPStreamConnection
     */
    protected $connection;

    /**
     * @var string
     */
    protected $channelName;

    /**
     * @param string $channelName
     */
    public function setChannelName($channelName)
    {
        if (empty($channelName)) {
            throw new \InvalidArgumentException('Invalid channel name');
        }

        $this->channelName = $channelName;
    }
}


text:
<?php

class RangeWeightCore extends ObjectModel
{
    public $id_carrier;
    public $delimiter1;
    public $delimiter2;

    /**
     * @see ObjectModel::$definition
     */
    public static $definition = array(
        'table' => 'range_weight',
        'primary' => 'id_range_weight',
        'fields' => array(
            'id_carrier' => array('type' => self::TYPE_INT, 'validate' => 'isInt', 'required' => true),
            'delimiter1' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat', 'required' => true),
            'delimiter2' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat', 'required' => true),
        ),
    );

    protected $webserviceParameters = array(
            'objectNodeName' => 'weight_range',
            'objectsNodeName' => 'weight_ranges',
            'fields' => array(
            'id_carrier' => array('xlink_resource' => 'carriers'))
    );

    /**
     * Override add to create delivery value for all zones
     * @see classes/ObjectModelCore::add()
     *
     * @param bool $null_values
     * @param bool $autodate
     * @return bool Insertion result
     */
    public function add($autodate = true, $null_values = false)
    {
        if (!parent::add($autodate, $null_values) || !Validate::isLoadedObject($this)) {
            return false;
        }
        if (defined('PS_INSTALLATION_IN_PROGRESS')) {
            return true;
        }
        $carrier = new Carrier((int)$this->id_carrier);
        $price_list = array();
        foreach ($carrier->getZones() as $zone) {
            $price_list[] = array(
                'id_range_price' => null,
                'id_range_weight' => (int)$this->id,
                'id_carrier' => (int)$this->id_carrier,
                'id_zone' => (int)$zone['id_zone'],
                'price' => 0,
            );
        }
        $carrier->addDeliveryPrice($price_list);

        return true;
    }

    /**
    * Get all available price ranges
    *
    * @return array Ranges
    */
    public static function getRanges($id_carrier)
    {
        return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
            SELECT *
            FROM `'._DB_PREFIX_.'range_weight`
            WHERE `id_carrier` = '.(int)$id_carrier.'
            ORDER BY `delimiter1` ASC');
    }

    public static function rangeExist($id_carrier, $delimiter1, $delimiter2, $id_reference = null)
    {
        return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
            SELECT count(*)
            FROM `'._DB_PREFIX_.'range_weight` rw'.
            (is_null($id_carrier) && $id_reference ? '
            INNER JOIN `'._DB_PREFIX_.'carrier` c on (rw.`id_carrier` = c.`id_carrier`)' : '').'
            WHERE'.
            ($id_carrier ? ' `id_carrier` = '.(int)$id_carrier : '').
            (is_null($id_carrier) && $id_reference ? ' c.`id_reference` = '.(int)$id_reference : '').'
            AND `delimiter1` = '.(float)$delimiter1.' AND `delimiter2` = '.(float)$delimiter2);
    }

    public static function isOverlapping($id_carrier, $delimiter1, $delimiter2, $id_rang = null)
    {
        return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
            SELECT count(*)
            FROM `'._DB_PREFIX_.'range_weight`
            WHERE `id_carrier` = '.(int)$id_carrier.'
            AND ((`delimiter1` >= '.(float)$delimiter1.' AND `delimiter1` < '.(float)$delimiter2.')
                OR (`delimiter2` > '.(float)$delimiter1.' AND `delimiter2` < '.(float)$delimiter2.')
                OR ('.(float)$delimiter1.' > `delimiter1` AND '.(float)$delimiter1.' < `delimiter2`)
                OR ('.(float)$delimiter2.' < `delimiter1` AND '.(float)$delimiter2.' > `delimiter2`)
            )
            '.(!is_null($id_rang) ? ' AND `id_range_weight` != '.(int)$id_rang : ''));
    }
}


text:
var gamejs = require('gamejs');
qModule('gamejs/audio');
var surfaceEqual = QUnit.surfaceEqual;

var audio = null;
QUnit.testStart(function() {
   audio = new gamejs.audio.Sound(document.getElementById('sound-fixture'));
})

// this should just run through
QUnit.test('basic', 0, function() {
   audio.play();
   audio.stop();
   audio.play();
   audio.pause();
});