text:
This folder contains files to run JerryScript on
[STM32F4-Discovery board](http://www.st.com/content/st_com/en/products/evaluation-tools/product-evaluation-tools/mcu-eval-tools/stm32-mcu-eval-tools/stm32-mcu-discovery-kits/stm32f4discovery.html) with [NuttX](http://nuttx.org/)

### How to build

#### 1. Setting up the build environment for STM32F4-Discovery board

Clone JerryScript and NuttX into jerry-nuttx directory

```
mkdir jerry-nuttx
cd jerry-nuttx
git clone https://github.com/jerryscript-project/jerryscript.git
git clone https://bitbucket.org/nuttx/nuttx.git
git clone https://bitbucket.org/nuttx/apps.git
git clone https://github.com/texane/stlink.git
```

The following directory structure is created after these commands

```
jerry-nuttx
  + apps
  + jerryscript
  |  + targets
  |      + nuttx-stm32f4
  + nuttx
  + stlink
```

#### 2. Adding JerryScript as an interpreter for NuttX

```
cd apps/interpreters
mkdir jerryscript
cp ../../jerryscript/targets/nuttx-stm32f4/* ./jerryscript/
```

#### 3. Configure NuttX

```
# assuming you are in jerry-nuttx folder
cd nuttx/tools

# configure NuttX USB console shell
./configure.sh stm32f4discovery/usbnsh

cd ..
# might require to run "make menuconfig" twice
make menuconfig
```

We must set the following options:

* Change `Build Setup -> Build Host Platform` from _Windows_ to _Linux_
* Enable `System Type -> FPU support`
* Enable `Application Configuration -> Interpreters -> JerryScript`

If you get `kconfig-mconf: not found` error when you run `make menuconfig` you may have to install kconfig-frontends:

```
# assume you are in jerry-nuttx folder
sudo apt-get install gperf flex bison libncurses-dev
git clone https://github.com/jameswalmsley/kconfig-frontends.git
cd kconfig-frontends
./bootstrap
./configure --enable-mconf
make
sudo make install
sudo ldconfig
```

#### 4. Build JerryScript for NuttX

```
# assuming you are in jerry-nuttx folder
cd nuttx/
make
```

#### 5. Flashing

Connect Mini-USB for power supply and connect Micro-USB for `NSH` console.

To configure `stlink` utility for flashing, follow the instructions in the official [Stlink repository](https://github.com/texane/stlink).

To flash,
```
# assuming you are in nuttx folder
sudo ../stlink/build/Release/st-flash write nuttx.bin 0x8000000
```

### Running JerryScript

You can use `minicom` for terminal program, or any other you may like, but set
baud rate to `115200`.

```
sudo minicom --device=/dev/ttyACM0 --baud=115200
```

You may have to press `RESET` on the board and press `Enter` keys on the console
several times to make `nsh` prompt to appear.

If the prompt shows like this,
```
NuttShell (NSH)
               nsh>
                    nsh>
                         nsh>
```
please set `Add Carriage Ret` option by `CTRL-A` > `Z` > `U` at the console,
if you're using `minicom`.

Run `jerry` with javascript file(s)

```
NuttShell (NSH)
nsh> jerry full_path/any.js
```

Without argument it prints:
```
nsh> jerry
No input files, running a hello world demo:
Hello world 5 times from JerryScript
```


text:
require "digest"
require "erb"

module Homebrew
  class FormulaCreator
    attr_reader :url, :sha256, :desc, :homepage
    attr_accessor :name, :version, :tap, :path, :mode

    def url=(url)
      @url = url
      path = Pathname.new(url)
      if @name.nil?
        case url
        when %r{github\.com/(\S+)/(\S+)\.git}
          @user = Regexp.last_match(1)
          @name = Regexp.last_match(2)
          @head = true
          @github = true
        when %r{github\.com/(\S+)/(\S+)/(archive|releases)/}
          @user = Regexp.last_match(1)
          @name = Regexp.last_match(2)
          @github = true
        else
          @name = path.basename.to_s[/(.*?)[-_.]?#{Regexp.escape(path.version.to_s)}/, 1]
        end
      end
      update_path
      if @version
        @version = Version.create(@version)
      else
        @version = Version.detect(url, {})
      end
    end

    def update_path
      return if @name.nil? || @tap.nil?
      @path = Formulary.path "#{@tap}/#{@name}"
    end

    def fetch?
      !Homebrew.args.no_fetch?
    end

    def head?
      @head || Homebrew.args.HEAD?
    end

    def generate!
      raise "#{path} already exists" if path.exist?

      if version.nil? || version.null?
        opoo "Version cannot be determined from URL."
        puts "You'll need to add an explicit 'version' to the formula."
      elsif fetch?
        unless head?
          r = Resource.new
          r.url(url)
          r.version(version)
          r.owner = self
          @sha256 = r.fetch.sha256 if r.download_strategy == CurlDownloadStrategy
        end

        if @user && @name
          begin
            metadata = GitHub.repository(@user, @name)
            @desc = metadata["description"]
            @homepage = metadata["homepage"]
          rescue GitHub::HTTPNotFoundError
            # If there was no repository found assume the network connection is at
            # fault rather than the input URL.
            nil
          end
        end
      end

      path.write ERB.new(template, nil, ">").result(binding)
    end

    def template
      <<~EOS
        # Documentation: https://docs.brew.sh/Formula-Cookbook
        #                http://www.rubydoc.info/github/Homebrew/brew/master/Formula
        # PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
        class #{Formulary.class_s(name)} < Formula
          desc "#{desc}"
          homepage "#{homepage}"
        <% if head? %>
          head "#{url}"
        <% else %>
          url "#{url}"
        <% unless version.nil? or version.detected_from_url? %>
          version "#{version}"
        <% end %>
          sha256 "#{sha256}"
        <% end %>
        <% if mode == :cmake %>
          depends_on "cmake" => :build
        <% elsif mode == :meson %>
          depends_on "meson-internal" => :build
          depends_on "ninja" => :build
          depends_on "python" => :build
        <% elsif mode.nil? %>
          # depends_on "cmake" => :build
        <% end %>

          def install
            # ENV.deparallelize  # if your formula fails when building in parallel
        <% if mode == :cmake %>
            system "cmake", ".", *std_cmake_args
        <% elsif mode == :autotools %>
            # Remove unrecognized options if warned by configure
            system "./configure", "--disable-debug",
                                  "--disable-dependency-tracking",
                                  "--disable-silent-rules",
                                  "--prefix=\#{prefix}"
        <% elsif mode == :meson %>
            ENV.refurbish_args

            mkdir "build" do
              system "meson", "--prefix=\#{prefix}", ".."
              system "ninja"
              system "ninja", "install"
            end
        <% else %>
            # Remove unrecognized options if warned by configure
            system "./configure", "--disable-debug",
                                  "--disable-dependency-tracking",
                                  "--disable-silent-rules",
                                  "--prefix=\#{prefix}"
            # system "cmake", ".", *std_cmake_args
        <% end %>
        <% if mode != :meson %>
            system "make", "install" # if this fails, try separate make/make install steps
        <% end %>
          end

          test do
            # `test do` will create, run in and delete a temporary directory.
            #
            # This test will fail and we won't accept that! For Homebrew/homebrew-core
            # this will need to be a test that verifies the functionality of the
            # software. Run the test with `brew test #{name}`. Options passed
            # to `brew install` such as `--HEAD` also need to be provided to `brew test`.
            #
            # The installed folder is not in the path, so use the entire path to any
            # executables being tested: `system "\#{bin}/program", "do", "something"`.
            system "false"
          end
        end
      EOS
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
window.addEventListener("load", function() {
  chrome.devtools.inspectedWindow.eval(
    "window.webkitIntent",
     function(result, isException) {
       if (isException || !!result == false) {
         console.log("The page does not have any intent data");
         var nodataEl = document.getElementById("nodata");
         nodataEl.style.display = "block";
       }
       else {
         var intentEl = document.getElementById("intent");
         intentEl.style.display = "block";
         console.log("The page has been invoked with the " + result + " intent");
         var action = document.getElementById("action");
         var type = document.getElementById("type");
         var data = document.getElementById("data");
         var majorType = data.className = result.type.substr(0, result.type.indexOf("/"));
         var typeEl = document.getElementById("majorType");
         action.textContent = result.action;
         type.textContent = result.type;
         data.textContent = result.data;

         if(majorType == "image") {
           majorType.src = data;
         }
         else if (majorType == "video") {
           majorType.src = data;
         }
         else if(majorType == "audio") {
           majorType.src = data;
         }
       }
     }
    );
}, false);


text:
'use strict';

var isTypedArray = require( './../lib' );

var arr = new Int8Array( 10 );
console.log( isTypedArray( arr ) );
// returns true

arr = new Uint8Array( 10 );
console.log( isTypedArray( arr ) );
// returns true

arr = new Uint8ClampedArray( 10 );
console.log( isTypedArray( arr ) );
// returns true

arr = new Int16Array( 10 );
console.log( isTypedArray( arr ) );
// returns true

arr = new Uint16Array( 10 );
console.log( isTypedArray( arr ) );
// returns true

arr = new Int32Array( 10 );
console.log( isTypedArray( arr ) );
// returns true

arr = new Uint32Array( 10 );
console.log( isTypedArray( arr ) );
// returns true

arr = new Float32Array( 10 );
console.log( isTypedArray( arr ) );
// returns true

arr = new Float64Array( 10 );
console.log( isTypedArray( arr ) );
// returns true

console.log( isTypedArray( [] ) );
// returns false

console.log( isTypedArray( {} ) );
// returns false

console.log( isTypedArray( null ) );
// returns false

console.log( isTypedArray( new Buffer( 10 ) ) );
// returns false


text:
#import "NPPButton.h"

#pragma mark -
#pragma mark Constants
#pragma mark -
//**********************************************************************************************************
//
//	Constants
//
//**********************************************************************************************************

#define NPP_BT_STATE_UP			@"up"
#define NPP_BT_STATE_DOWN		@"down"

#define NPP_BT_BASE				@"npp_bt.png"
#define NPP_BT_KEY				@"npp_bt_key.png"
#define NPP_BT_KEY_SEG			@"npp_bt_key_seg.png"

#define NPP_BT_DEFAULT_BASE		@"base"
#define NPP_BT_DEFAULT_KEY		@"keyboard"
#define NPP_BT_DEFAULT_KEY_SEG	@"keyboard_segment"
#define NPP_BT_DEFAULT_LIGHT	@"light"
#define NPP_BT_DEFAULT_DARK		@"dark"
#define NPP_BT_DEFAULT_ALERT	@"alert"
#define NPP_BT_DEFAULT_CONFIRM	@"confirm"

#pragma mark -
#pragma mark Private Interface
#pragma mark -
//**********************************************************************************************************
//
//	Private Interface
//
//**********************************************************************************************************

#pragma mark -
#pragma mark Private Definitions
//**************************************************
//	Private Definitions
//**************************************************

#pragma mark -
#pragma mark Private Functions
//**************************************************
//	Private Functions
//**************************************************

NPP_STATIC_READONLY(NSMutableDictionary, nppButtonDefaults);

static UIColor *nppUIColorConstrasting(NPPStyleColor style)
{
	UIColor *color = nil;

	switch (style)
	{
		case NPPStyleColorAlert:
			color = [UIColor whiteColor];
			break;
		case NPPStyleColorConfirm:
			color = [UIColor whiteColor];
			break;
		case NPPStyleColorDark:
			color = [UIColor whiteColor];
			break;
		case NPPStyleColorLight:
		default:
			color = [UIColor blackColor];
			break;
	}

	return color;
}

static UIImage *nppUIImageFor(NPPButtonType type, NPPStyleColor style, BOOL isUp)
{
	NSString *path = nil;
	NSString *named = nil;
	NSString *pureName = nil;
	NSString *extension = nil;
	NSString *stateName = (isUp) ? NPP_BT_STATE_UP : NPP_BT_STATE_DOWN;
	NSMutableDictionary *defaults = nppButtonDefaults();
	NSString *keyStyle = nil;

	switch (style)
	{
		case NPPStyleColorAlert:
			keyStyle = NPP_BT_DEFAULT_ALERT;
			break;
		case NPPStyleColorConfirm:
			keyStyle = NPP_BT_DEFAULT_CONFIRM;
			break;
		case NPPStyleColorDark:
			keyStyle = NPP_BT_DEFAULT_DARK;
			break;
		case NPPStyleColorLight:
		default:
			keyStyle = NPP_BT_DEFAULT_LIGHT;
			break;
	}

	switch (type)
	{
		case NPPButtonTypeKeyLeft:
		case NPPButtonTypeKeyRight:
		case NPPButtonTypeKeyMiddle:
			named = [[defaults objectForKey:NPP_BT_DEFAULT_KEY_SEG] objectForKey:keyStyle];
			break;
		case NPPButtonTypeKey:
			named = [[defaults objectForKey:NPP_BT_DEFAULT_KEY] objectForKey:keyStyle];
			break;
		case NPPButtonTypeBase:
		default:
			named = [[defaults objectForKey:NPP_BT_DEFAULT_BASE] objectForKey:keyStyle];
			break;
	}

	extension = nppGetFileExtension(named);
	pureName = nppGetFileName(named);

	// Tries the state name match only.
	path = [NSString stringWithFormat:@"%@_%@.%@", pureName, stateName, extension];
	if (!nppFileExists(path))
	{
		path = named;
	}

	return nppImageFromFile(path);
}

#pragma mark -
#pragma mark Private Category
//**************************************************
//	Private Category
//**************************************************

@interface NPPButton()

// Initializes a new instance.
- (void) initializingButton;

- (void) handleCallback:(id)sender;

@end

#pragma mark -
#pragma mark Public Interface
#pragma mark -
//**********************************************************************************************************
//
//	Public Interface
//
//**********************************************************************************************************

@implementation NPPButton

#pragma mark -
#pragma mark Properties
//**************************************************
//	Properties
//**************************************************

@synthesize type = _type, styleColor = _styleColor;

#pragma mark -
#pragma mark Constructors
//**************************************************
//	Constructors
//**************************************************

- (id) init
{
	if ((self = [super initWithFrame:CGRectZero]))
	{
		[self initializingButton];
	}

	return self;
}

- (id) initWithCoder:(NSCoder *)aDecoder
{
	if ((self = [super initWithCoder:aDecoder]))
	{
		[self initializingButton];

		// Loading original image.
		UIImage *up = [self backgroundImageForState:UIControlStateNormal];
		UIImage *down = [self backgroundImageForState:UIControlStateHighlighted];
		UIImage *selected = [self backgroundImageForState:UIControlStateSelected];

		// Gets the 9-slice image area.
		selected = (selected != up) ? [selected imageNineSliced] : nil;
		down = (down != up) ? [down imageNineSliced] : nil;
		up = [up imageNineSliced];

		// Make localizable text.
		BOOL hasAtt = [self respondsToSelector:@selector(attributedTitleForState:)];
		NSAttributedString *att = (hasAtt) ? [self attributedTitleForState:UIControlStateNormal] : nil;

		if (att != nil)
		{
			NSRange range = NSMakeRange(0, att.string.length);
			UIFont *font = [self.titleLabel.font nppFont];

			NSMutableAttributedString *finalString = [att mutableCopy];
			[finalString addAttribute:NSFontAttributeName value:font range:range];
			[finalString replaceCharactersInRange:range withString:nppS(self.titleLabel.text)];
			[self setAttributedTitle:finalString forState:UIControlStateNormal];
			nppRelease(finalString);
		}
		else
		{
			[self setTitle:nppS(self.titleLabel.text) forState:UIControlStateNormal];
		}

		[self setBackgroundImage:up forState:UIControlStateNormal];
		[self setBackgroundImage:down forState:UIControlStateHighlighted];
		[self setBackgroundImage:selected forState:UIControlStateSelected];
	}

	return self;
}

- (id) initWithFrame:(CGRect)frame
{
	if ((self = [super initWithFrame:frame]))
	{
		[self initializingButton];
	}

	return self;
}

- (id) initWithTitle:(NSString *)title
			   image:(NSString *)named
				type:(NPPButtonType)type
			   style:(NPPStyleColor)style;
{
	if ((self = [super initWithFrame:CGRectZero]))
	{
		[self initializingButton];
		[self setType:type andStyle:style];

		UIImage *image = nppImageFromFile(named);
		self.titleLabel.font = [UIFont nppFontBoldWithSize:16.0f];
		[self setTitle:title forState:UIControlStateNormal];
		[self setImage:image forState:UIControlStateNormal];
		[self sizeToFit];
	}

	return self;
}

+ (id) buttonWithTitle:(NSString *)title
				  image:(NSString *)named
				  type:(NPPButtonType)type
				 style:(NPPStyleColor)style
{
	NPPButton *button = [[self alloc] initWithTitle:title image:named type:type style:style];
	return nppAutorelease(button);
}

#pragma mark -
#pragma mark Private Methods
//**************************************************
//	Private Methods
//**************************************************

- (void) initializingButton
{
	// Custom button.
	UILabel *label = self.titleLabel;
	label.font = [label.font nppFont];
	_type = NPPButtonTypeBase;
	_styleColor = NPPStyleColorLight;
}

- (void) handleCallback:(id)sender
{
	nppBlock(_block);
}

#pragma mark -
#pragma mark Self Public Methods
//**************************************************
//	Self Public Methods
//**************************************************

- (void) setTarget:(id)aTarget action:(SEL)aSelector
{
	[self removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];
	[self addTarget:aTarget action:aSelector forControlEvents:UIControlEventTouchUpInside];
}

- (void) setBlock:(NPPBlockVoid)block
{
	nppRelease(_block);
	_block = [block copy];

	[self setTarget:self action:@selector(handleCallback:)];
}

- (void) setType:(NPPButtonType)type andStyle:(NPPStyleColor)style
{
	_type = type;
	_styleColor = style;

	// Loading original image.
	UIImage *up = nppUIImageFor(_type, _styleColor, YES);
	UIImage *down = nppUIImageFor(_type, _styleColor, NO);
	CGRect crop = CGRectZero;

	switch (_type)
	{
		case NPPButtonTypeKeyLeft:
			crop = CGRectMake(0, 0, up.size.width * 0.5f, up.size.height);
			up = [up imageCroppedInRect:crop];
			down = [down imageCroppedInRect:crop];
			self.contentMode = UIViewContentModeTopLeft;
			break;
		case NPPButtonTypeKeyRight:
			crop = CGRectMake(up.size.width * 0.5f, 0, up.size.width * 0.5f, up.size.height);
			up = [up imageCroppedInRect:crop];
			down = [down imageCroppedInRect:crop];
			self.contentMode = UIViewContentModeTopRight;
			break;
		case NPPButtonTypeKeyMiddle:
			self.contentMode = UIViewContentModeCenter;
			break;
		case NPPButtonTypeBase:
			self.contentMode = UIViewContentModeTopRight;
			break;
		case NPPButtonTypeKey:
		default:
			self.contentMode = UIViewContentModeCenter;
			break;
	}

	// Gets the 9-slice image area.
	up = [up imageNineSliced];
	down = [down imageNineSliced];

	// Creates the required button.
	[self setBackgroundImage:down forState:UIControlStateHighlighted];
	[self setBackgroundImage:down forState:UIControlStateSelected];
	[self setBackgroundImage:up forState:UIControlStateNormal];
	[self setTitleColor:nppUIColorConstrasting(_styleColor) forState:UIControlStateNormal];
}

+ (void) defineBackground:(NSString *)imageNamed type:(NPPButtonType)type style:(NPPStyleColor)style
{
	NSMutableDictionary *defaults = nppButtonDefaults();
	NSMutableDictionary *item = nil;
	NSString *keyStyle = nil;
	NSString *keyType = nil;

	switch (style)
	{
		case NPPStyleColorAlert:
			keyStyle = NPP_BT_DEFAULT_ALERT;
			break;
		case NPPStyleColorConfirm:
			keyStyle = NPP_BT_DEFAULT_CONFIRM;
			break;
		case NPPStyleColorDark:
			keyStyle = NPP_BT_DEFAULT_DARK;
			break;
		case NPPStyleColorLight:
		default:
			keyStyle = NPP_BT_DEFAULT_LIGHT;
			break;
	}

	switch (type)
	{
		case NPPButtonTypeKeyLeft:
		case NPPButtonTypeKeyRight:
		case NPPButtonTypeKeyMiddle:
			keyType = NPP_BT_DEFAULT_KEY_SEG;
			break;
		case NPPButtonTypeKey:
			keyType = NPP_BT_DEFAULT_KEY;
			break;
		case NPPButtonTypeBase:
		default:
			keyType = NPP_BT_DEFAULT_BASE;
			break;
	}

	if (imageNamed != nil)
	{
		item = [defaults objectForKey:keyType];

		if (item == nil)
		{
			item = [NSMutableDictionary dictionary];
			[defaults setObject:item forKey:keyType];
		}

		[item setObject:imageNamed forKey:keyStyle];
	}
	else
	{
		item = [defaults objectForKey:keyType];
		[item removeObjectForKey:keyStyle];
	}
}

#pragma mark -
#pragma mark Override Public Methods
//**************************************************
//	Override Public Methods
//**************************************************

- (void) dealloc
{
	nppRelease(_block);

#ifndef NPP_ARC
	[super dealloc];
#endif
}

+ (BOOL) accessInstanceVariablesDirectly
{
	return NO;
}

+ (void) initialize
{
	if (self == [NPPButton class])
	{
		NSString *extension = nil;
		NSString *named = nil;
		NSString *path = nil;

		// Base Button.
		extension = nppGetFileExtension(NPP_BT_BASE);
		named = nppGetFileName(NPP_BT_BASE);
		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_LIGHT, extension];
		[self defineBackground:path type:NPPButtonTypeBase style:NPPStyleColorLight];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_DARK, extension];
		[self defineBackground:path type:NPPButtonTypeBase style:NPPStyleColorDark];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_CONFIRM, extension];
		[self defineBackground:path type:NPPButtonTypeBase style:NPPStyleColorConfirm];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_ALERT, extension];
		[self defineBackground:path type:NPPButtonTypeBase style:NPPStyleColorAlert];

		// Keyboard Button.
		extension = nppGetFileExtension(NPP_BT_KEY);
		named = nppGetFileName(NPP_BT_KEY);
		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_LIGHT, extension];
		[self defineBackground:path type:NPPButtonTypeKey style:NPPStyleColorLight];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_DARK, extension];
		[self defineBackground:path type:NPPButtonTypeKey style:NPPStyleColorDark];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_CONFIRM, extension];
		[self defineBackground:path type:NPPButtonTypeKey style:NPPStyleColorConfirm];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_ALERT, extension];
		[self defineBackground:path type:NPPButtonTypeKey style:NPPStyleColorAlert];

		// Keyboard Segment Button.
		extension = nppGetFileExtension(NPP_BT_KEY_SEG);
		named = nppGetFileName(NPP_BT_KEY_SEG);
		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_LIGHT, extension];
		[self defineBackground:path type:NPPButtonTypeKeyMiddle style:NPPStyleColorLight];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_DARK, extension];
		[self defineBackground:path type:NPPButtonTypeKeyMiddle style:NPPStyleColorDark];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_CONFIRM, extension];
		[self defineBackground:path type:NPPButtonTypeKeyMiddle style:NPPStyleColorConfirm];

		path = [NSString stringWithFormat:@"%@_%@.%@", named, NPP_BT_DEFAULT_ALERT, extension];
		[self defineBackground:path type:NPPButtonTypeKeyMiddle style:NPPStyleColorAlert];
	}
}

@end


text:
using System.ComponentModel.DataAnnotations;

namespace Singl.Models
{
    public enum TipoCurso
    {
        Bacharelado,
        Licenciatura,
        Mestrado,
        Doutorado,
        [Display(Name="Especialização")]
        Especializacao

    }
}


text:
<?php namespace Wright\View;

use Wright\Extensions\Twig;

$container->bind(ViewInterface::class, TwigView::class, [
    'twig' => $container->get('twig')
]);

$container->bind('twig', \Twig_Environment::class, [
        'loader' => $container->definition(\Twig_Loader_Filesystem::class, [
            'paths' => getcwd() . '/templates'
        ]),
        'options' => [
            'cache' => getcwd() . '/cache/twig',
            'auto_reload' => true
        ]
    ])
    ->after(function ($twig) {

        $twig->addExtension(new Twig\StandardExtension);
    });


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

<!--L
  Copyright 5AM Solutions, Inc.

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/prot-express/LICENSE.txt for details.
L-->

<ExperimentArchive xmlns="http://cpas.fhcrc.org/exp/xml" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://cpas.fhcrc.org/exp/xml http://cpas.fhcrc.org/download/XarSchema/V1.2/expTypes.xsd">
	<Experiment rdf:about="${FolderLSIDBase}:IPAS14" xmlrdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
		<Name>IPAS14 Experiment</Name>
		<Comments>Mouse Pancreatic Cancer Research</Comments>
		<Hypothesis>Cancer can kill a mouse too.</Hypothesis>
		<ExperimentDescriptionURL>http://testUrl1:8080/index.html</ExperimentDescriptionURL>
		<Contact>
			<ContactId>Jim's Laboratory</ContactId>
			<FirstName>Jim</FirstName>
			<LastName>Smith</LastName>
			<Email>jim@smiths.net</Email>
		</Contact>
	</Experiment>
	<ProtocolDefinitions>
		<Protocol rdf:about="${FolderLSIDBase}:Process.IPAS14">
			<Name>IPAS14 Process</Name>
			<ProtocolDescription>Prepare and run LCMS, including fractionation of the input sample.  Produces one mzXML file per fraction in a single directory.</ProtocolDescription>
			<ApplicationType>ExperimentRun</ApplicationType>
			<MaxInputMaterialPerInstance xsi:nil="true"/>
			<MaxInputDataPerInstance xsi:nil="true"/>
			<OutputMaterialPerInstance xsi:nil="true"/>
			<OutputDataPerInstance xsi:nil="true"/>
			<OutputMaterialType>Material</OutputMaterialType>
			<OutputDataType>Data</OutputDataType>
			<Instrument>This is the instrument.</Instrument>
			<Software>this is the software....</Software>
			<ParameterDeclarations>
				<SimpleVal Name="ApplicationLSIDTemplate" OntologyEntryURI="terms.fhcrc.org#XarTemplate.ApplicationLSID" ValueType="String">${RunLSIDBase}:IPAS14</SimpleVal>
				<SimpleVal Name="ApplicationNameTemplate" OntologyEntryURI="terms.fhcrc.org#XarTemplate.ApplicationName" ValueType="String">Do IPAS 14 protocol</SimpleVal>
			</ParameterDeclarations>
			<Properties>
				<SimpleVal Name="TreatAsFractions" OntologyEntryURI="terms.fhcrc.org#RunProtocolTypes.TreatAsFractions" ValueType="String">true</SimpleVal>
				<SimpleVal Name="Category" OntologyEntryURI="terms.fhcrc.org#RunProtocolTypes.Category" ValueType="String">mass_spec</SimpleVal>
			</Properties>
			<Contact>
				<ContactId>Dr. Tabb's Research Center' for Protocols</ContactId>
				<FirstName>John</FirstName>
				<LastName>Tabb</LastName>
				<Email>tabb@research-center.com</Email>
			</Contact>
		</Protocol>
	</ProtocolDefinitions>
	<ProtocolActionDefinitions/>
	<StartingInputDefinitions/>
	<ExperimentRuns>
		<ExperimentRun rdf:about="${FolderLSIDBase}.${XarFileId}:IPAS14.IP0014_AX02">
			<Name>IP0014_AX02 (Mouse Pancreatic Cancer Study)</Name>
			<ProtocolLSID>${FolderLSIDBase}:Process.IPAS14</ProtocolLSID>
			<ExperimentLSID>${FolderLSIDBase}:IPAS14</ExperimentLSID>
			<Comments>Profiling of Proteins in Lung Adenocarcinoma Cell Surface</Comments>
			<ProtocolApplications>
				<ProtocolApplication rdf:about="${RunLSIDBase}:IPAS14">
					<Name>Do IPAS 14 protocol</Name>
					<CpasType>ExperimentRun</CpasType>
					<ProtocolLSID>${FolderLSIDBase}:Process.IPAS14</ProtocolLSID>
					<ActionSequence>1</ActionSequence>
					<ActivityDate>2006-08-31-07:00</ActivityDate>
					<InputRefs>
						<MaterialLSID>${FolderLSIDBase}-Xar${XarFileId}-1:UnspecifiedCancer</MaterialLSID>
						<MaterialLSID>${FolderLSIDBase}-Xar${XarFileId}-2:UnspecifiedCase</MaterialLSID>
						<DataLSID>${FolderLSIDBase}-Xar${XarFileId}-1:tandem.xml</DataLSID>
						<DataLSID>${FolderLSIDBase}-Xar${XarFileId}-2:IPI_Mouse.fasta</DataLSID>
					</InputRefs>
					<ProtocolApplicationParameters>
						<SimpleVal Name="ApplicationLSIDTemplate" OntologyEntryURI="terms.fhcrc.org#XarTemplate.ApplicationLSID" ValueType="String">${RunLSIDBase}:IPAS14</SimpleVal>
						<SimpleVal Name="ApplicationNameTemplate" OntologyEntryURI="terms.fhcrc.org#XarTemplate.ApplicationName" ValueType="String">Do IPAS 14 protocol</SimpleVal>
					</ProtocolApplicationParameters>
					<OutputMaterials/>
					<OutputDataObjects/>
				</ProtocolApplication>
			</ProtocolApplications>
		</ExperimentRun>
	</ExperimentRuns>
</ExperimentArchive>


text:
package com.orendainx.trucking.nifi.processors

import java.io.OutputStream
import java.nio.charset.StandardCharsets

import com.orendainx.trucking.simulator.simulators.ManualTickAndFetchSimulator
import org.apache.nifi.annotation.behavior._
import org.apache.nifi.annotation.documentation.{CapabilityDescription, Tags}
import org.apache.nifi.annotation.lifecycle.{OnRemoved, OnShutdown}
import org.apache.nifi.components.PropertyDescriptor
import org.apache.nifi.logging.ComponentLog
import org.apache.nifi.processor._
import org.apache.nifi.processor.io.OutputStreamCallback

import scala.collection.JavaConverters._

/**
  * @author Edgar Orendain <edgar@orendainx.com>
  */
@Tags(Array("trucking", "data", "event", "generator", "simulator", "iot"))
@CapabilityDescription("Generates simulated truck sensor data. Find the master project and its code, documentation and corresponding tutorials at: https://github.com/orendain/trucking-iot")
@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
@TriggerSerially
@WritesAttributes(Array(
  new WritesAttribute(attribute = "dataType", description = "The class name of the of the TruckingData this flowfile carries (e.g. \"TruckData\" or \"TrafficData\").")
))
class GetTruckingData extends AbstractProcessor {

  private var log: ComponentLog = _
  private val RelSuccess = new Relationship.Builder().name("success").description("All generated data is routed to this relationship.").build
  private lazy val simulator = new ManualTickAndFetchSimulator()

  /** Perform necessary initialization */
  override def init(context: ProcessorInitializationContext): Unit = {
    log = context.getLogger // Save reference to NiFi's logger
    simulator.tick() // On initialization, tick the simulator forward
  }

  /** Called when processor is scheduled to run and when work exists for it */
  override def onTrigger(context: ProcessContext, session: ProcessSession): Unit = {

    // Fetch results that have been generated by the simulator since last onTrigger
    val truckingData = simulator.fetch()
    log.debug(s"Received data: $truckingData")

    // Process each bit of data generated, creating flow file and tagging with attributes as appropriate
    truckingData.foreach { data =>
      log.debug(s"Processing data: $data")

      var flowFile = session.create()
      flowFile = session.putAttribute(flowFile, "dataType", data.getClass.getSimpleName)
      flowFile = session.write(flowFile, new OutputStreamCallback {
        override def process(outputStream: OutputStream) =
          outputStream.write(data.toCSV.getBytes(StandardCharsets.UTF_8))
      })

      // TODO: document what this does
      // TODO: session.getProvenanceReporter.receive(flowFile, "ThisDoesWhat?")
      session.getProvenanceReporter.route(flowFile, RelSuccess)
      session.transfer(flowFile, RelSuccess)
      session.commit()
    }

    // Tick the simulator forward so results are ready to be fetched by onTrigger's next invocation
    simulator.tick()
  }

  // Define properties and relationships
  override def getSupportedPropertyDescriptors: java.util.List[PropertyDescriptor] = List.empty[PropertyDescriptor].asJava

  override def getRelationships: java.util.Set[Relationship] = Set(RelSuccess).asJava

  @OnRemoved
  @OnShutdown
  /** Clean up and exit gracefully */
  def cleanup(): Unit = simulator.stop()
}


text:
/**
 * Created by blairanderson on 8/1/14.
 */

exports.settings = function settings(params, callback){

}


text:
"""Implementation of the graph module for a [Java package] dependency graph."""

import class_dependency
import graph
import group_json_consts
import java_group

class JavaPackage(java_group.JavaGroup):
    """A representation of a Java package."""

class JavaPackageDependencyGraph(graph.Graph[JavaPackage]):
    """A graph representation of the dependencies between Java packages.

    A directed edge A -> B indicates that A depends on B.
    """
    def __init__(self, class_graph: class_dependency.JavaClassDependencyGraph):
        """Initializes a new package-level dependency graph
        by "collapsing" a class-level dependency graph into its packages.

        Args:
            class_graph: A class-level graph to collapse to a package-level one.
        """
        super().__init__()

        # Create list of all packages using class nodes
        # so we don't miss packages with no dependencies (edges).
        for class_node in class_graph.nodes:
            self.add_node_if_new(class_node.package)

        for begin_class, end_class in class_graph.edges:
            begin_package = begin_class.package
            end_package = end_class.package
            self.add_edge_if_new(begin_package, end_package)

            begin_package_node = self.get_node_by_key(begin_package)
            end_package_node = self.get_node_by_key(end_package)
            assert begin_package_node is not None
            assert end_package_node is not None
            begin_package_node.add_class(begin_class)
            end_package_node.add_class(end_class)
            begin_package_node.add_class_dependency_edge(
                end_package_node, begin_class, end_class)

    def create_node_from_key(self, key: str):
        """Create a JavaPackage node from the given key (package name)."""
        return JavaPackage(key)

    def get_edge_metadata(self, begin_node, end_node):
        """Generates JSON metadata for the current edge.

        The list of edges is sorted in order to help with testing.
        Structure:
        {
            'class_edges': [
                [begin_key, end_key], ...
            ],
        }
        """
        return {
            group_json_consts.CLASS_EDGES:
            sorted(
                [begin.name, end.name] for begin, end in
                begin_node.get_class_dependencies_in_outbound_edge(end_node)),
        }


text:
![alt tag](https://raw.githubusercontent.com/jxcore/jxcore-ios-sample/master/img/simulator_ss.png)

 - Test on iPhone 4S, 5, 5S, 6
 - Uses JXcore native interface. See [here](https://github.com/jxcore/jxcore/blob/master/doc/native/Embedding_API_Details.md) for API details.


text:
require 'rails_helper'

describe GeoTools do
  describe 'Get coordinates' do
    it 'should do something' do
      expect(GeoTools.get_coordinates('blah')).to eq('blah')
    end
  end
end


text:
module Gish::Exceptions
  class UnknownCallbackTypeError < NotImplementedError
    def initialize(callback)
      super "gish: Unknown callback (#{callback})"
    end
  end
end


text:
name: cljs.spec/instrument-ns
see also:
---

## Summary

## Details

## Examples


text:
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using ICSharpCode.NRefactory.Editor;
using PapillonEditor.Document;

namespace PapillonEditor.Snippets
{
	/// <summary>
	/// Represents an active element that allows the snippet to stay interactive after insertion.
	/// </summary>
	public interface IActiveElement
	{
		/// <summary>
		/// Called when the all snippet elements have been inserted.
		/// </summary>
		void OnInsertionCompleted();

		/// <summary>
		/// Called when the interactive mode is deactivated.
		/// </summary>
		void Deactivate(SnippetEventArgs e);

		/// <summary>
		/// Gets whether this element is editable (the user will be able to select it with Tab).
		/// </summary>
		bool IsEditable { get; }

		/// <summary>
		/// Gets the segment associated with this element. May be null.
		/// </summary>
		ISegment Segment { get; }
	}
}


text:
package darks.orm.core.executor;

import java.sql.SQLException;

import darks.orm.app.SqlSession;
import darks.orm.core.aspect.AspectUpdateContext;
import darks.orm.core.data.xml.DMLUpdateData;
import darks.orm.core.data.xml.QueryAspectWrapper;
import darks.orm.core.data.xml.SimpleAspectWrapper;

public class SqlMapUpdateExecutor extends SqlMapExecutorAdapter
{

    private DMLUpdateData updateData;

    private SimpleAspectWrapper simpleWrapper;

    private AspectUpdateContext aspectUpdateContext;

    private SqlSession session;

    public SqlMapUpdateExecutor()
    {

    }

    public SqlMapUpdateExecutor(SqlSession session, DMLUpdateData updateData, SimpleAspectWrapper simpleWrapper)
    {
        this.updateData = updateData;
        this.simpleWrapper = simpleWrapper;
        this.session = session;
    }

    @Override
    public boolean initialize()
    {
        aspectUpdateContext = new AspectUpdateContext(updateData.getAspectData());
        return true;
    }

    @Override
    public Object bodyInvoke()
        throws SQLException
    {
        session.executeUpdate(simpleWrapper.getSql(), simpleWrapper.getParams());
        return null;
    }

    @Override
    public boolean afterInvoke()
    {
        return aspectUpdateContext.afterInvoke(session, updateData.getAspectData(), simpleWrapper, null);
    }

    @Override
    public boolean beforeInvoke()
    {
        return aspectUpdateContext.beforeInvoke(session, updateData.getAspectData(), simpleWrapper, null);
    }

    public DMLUpdateData getUpdateData()
    {
        return updateData;
    }

    public void setUpdateData(DMLUpdateData updateData)
    {
        this.updateData = updateData;
    }

    public SimpleAspectWrapper getSqlMapAspectData()
    {
        return simpleWrapper;
    }

    public void setSqlMapAspectData(QueryAspectWrapper simpleWrapper)
    {
        this.simpleWrapper = simpleWrapper;
    }

    public AspectUpdateContext getAspectUpdateContext()
    {
        return aspectUpdateContext;
    }

    public void setAspectUpdateContext(AspectUpdateContext aspectUpdateContext)
    {
        this.aspectUpdateContext = aspectUpdateContext;
    }

}


text:
package android.location;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Represents a geographical boundary, also known as a geofence.
 *
 * <p>Currently only circular geofences are supported and they do not support altitude changes.
 *
 * @hide
 */
public final class Geofence implements Parcelable {
    /** @hide */
    public static final int TYPE_HORIZONTAL_CIRCLE = 1;

    private final int mType;
    private final double mLatitude;
    private final double mLongitude;
    private final float mRadius;

    /**
     * Create a circular geofence (on a flat, horizontal plane).
     *
     * @param latitude latitude in degrees, between -90 and +90 inclusive
     * @param longitude longitude in degrees, between -180 and +180 inclusive
     * @param radius radius in meters
     * @return a new geofence
     * @throws IllegalArgumentException if any parameters are out of range
     */
    public static Geofence createCircle(double latitude, double longitude, float radius) {
        return new Geofence(latitude, longitude, radius);
    }

    private Geofence(double latitude, double longitude, float radius) {
        checkRadius(radius);
        checkLatLong(latitude, longitude);
        mType = TYPE_HORIZONTAL_CIRCLE;
        mLatitude = latitude;
        mLongitude = longitude;
        mRadius = radius;
    }

    /** @hide */
    public int getType() {
        return mType;
    }

    /** @hide */
    public double getLatitude() {
        return mLatitude;
    }

    /** @hide */
    public double getLongitude() {
        return mLongitude;
    }

    /** @hide */
    public float getRadius() {
        return mRadius;
    }

    private static void checkRadius(float radius) {
        if (radius <= 0) {
            throw new IllegalArgumentException("invalid radius: " + radius);
        }
    }

    private static void checkLatLong(double latitude, double longitude) {
        if (latitude > 90.0 || latitude < -90.0) {
            throw new IllegalArgumentException("invalid latitude: " + latitude);
        }
        if (longitude > 180.0 || longitude < -180.0) {
            throw new IllegalArgumentException("invalid longitude: " + longitude);
        }
    }

    private static void checkType(int type) {
        if (type != TYPE_HORIZONTAL_CIRCLE) {
            throw new IllegalArgumentException("invalid type: " + type);
        }
    }

    public static final Parcelable.Creator<Geofence> CREATOR = new Parcelable.Creator<Geofence>() {
        @Override
        public Geofence createFromParcel(Parcel in) {
            int type = in.readInt();
            double latitude = in.readDouble();
            double longitude = in.readDouble();
            float radius = in.readFloat();
            checkType(type);
            return Geofence.createCircle(latitude, longitude, radius);
        }
        @Override
        public Geofence[] newArray(int size) {
            return new Geofence[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeInt(mType);
        parcel.writeDouble(mLatitude);
        parcel.writeDouble(mLongitude);
        parcel.writeFloat(mRadius);
    }

    private static String typeToString(int type) {
        switch (type) {
            case TYPE_HORIZONTAL_CIRCLE:
                return "CIRCLE";
            default:
                checkType(type);
                return null;
        }
    }

    @Override
    public String toString() {
        return String.format("Geofence[%s %.6f, %.6f %.0fm]",
                typeToString(mType), mLatitude, mLongitude, mRadius);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        long temp;
        temp = Double.doubleToLongBits(mLatitude);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(mLongitude);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + Float.floatToIntBits(mRadius);
        result = prime * result + mType;
        return result;
    }

    /**
     * Two geofences are equal if they have identical properties.
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Geofence))
            return false;
        Geofence other = (Geofence) obj;
        if (mRadius != other.mRadius)
            return false;
        if (mLatitude != other.mLatitude)
            return false;
        if (mLongitude != other.mLongitude)
            return false;
        if (mType != other.mType)
            return false;
        return true;
    }
}


text:
@interface AppDelegate ()

@property (nonatomic, strong) UIApplicationShortcutItem *launchedShortcutItem;
@property (nonatomic, strong) MainViewController *mainViewCtrl;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    CGRect rect = [[UIScreen mainScreen] bounds];
    self.window = [[UIWindow alloc] initWithFrame:rect];

    MainViewController *mainVC = [[MainViewController alloc] init];
    self.mainViewCtrl = mainVC;
    self.window.rootViewController = mainVC;

    [self.window makeKeyAndVisible];

    [application setMinimumBackgroundFetchInterval:3 * 60 * 60];

    BOOL shouldPerformAdditionalDelegateHandling = YES;

    // If a shortcut was launched, display its information and take the appropriate action
    UIApplicationShortcutItem *shortcutItem = launchOptions[UIApplicationLaunchOptionsShortcutItemKey];
    if (shortcutItem) {
        self.launchedShortcutItem = shortcutItem;
        // This will block "performActionForShortcutItem:completionHandler" from being called.
        shouldPerformAdditionalDelegateHandling = NO;
    }

//    return YES;
    return shouldPerformAdditionalDelegateHandling;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    if ([CXWebsiteManager websitesIsDifferent]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:CXWebsiteListDidChangedNotification object:nil];
    }
    if (self.launchedShortcutItem) {
        [self handleShortcutItem:self.launchedShortcutItem];
        self.launchedShortcutItem = nil;
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - handle shortcut

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
    BOOL handledShortCutItem = [self handleShortcutItem:shortcutItem];
    completionHandler(handledShortCutItem);
}

- (BOOL)handleShortcutItem:(UIApplicationShortcutItem *)shortcutItem
{
    NSString *shortcutType = [[shortcutItem.type componentsSeparatedByString:@"."] lastObject];
    NSInteger type = [shortcutType integerValue];
    self.mainViewCtrl.selectedIndex = type;

    return YES;
}

#pragma mark - Background Fetch
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    [self.mainViewCtrl performFetchWithCompletionHandler:completionHandler];
}

@end


text:
// Copyright (c) 2014 Marc René Arns. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

/*
Package wrapcontrib provides middleware (wraps) and helpers for http://github.com/go-on/wrap.

The middleware documentation is located at: https://godoc.org/github.com/go-on/wrap-contrib/wraps.

The helper documentation is located at: https://godoc.org/github.com/go-on/wrap-contrib/helper.

*/
package wrapcontrib


text:
<?php
/**
 * GithubController class definition
 *
 * PHP version 5.6.25+
 *
 * @package    GitDeploy
 * @link       https://github.com/froger-me/Git-deploy
 */

namespace GitDeploy;

if (!defined('ENTRY_POINT')) {
    exit('nope'); // Don't access this script directly
}

/**
 * GitHub repositoryClass
 *
 * Validates the GitHub request and calls the deployment service
 *
 * @package GitDeploy
 * @see     GitDeploy\SettingsModel           The settings of the application
 * @see     GitDeploy\DeployService           The service used to execute the deployment commands
 * @see     GitDeploy\RepositoryController    The parent class
 */
class GithubController extends RepositoryController
{
    /**
     * Set the $payload property from the request
     *
     * Depending on the chosen method, either:
     * - reads the request's body as a JSON string
     * - extracts the payload from the POST parameters
     *
     * @return void
     */
    protected function setPayload()
    {
        $payload = '';

        switch ($this->method) {
            case 'POST':
                $payload = isset($_POST['payload']) ? $_POST['payload'] : '';
                break;
            case 'JSONStream':
                $payload = file_get_contents('php://input');
                break;
            default:
                $payload = '';
                break;
        }

        $this->payload = ($payload) ? $payload : '';
    }

    /**
     * Does nothing - not applicable for this implementation
     * @return void
     */
    protected function setToken()
    {
        // Not applicable
    }

    /**
     * Does nothing - not applicable for this implementation
     * @return void
     */
    protected function setHash()
    {
        // Not applicable
    }

    /**
     * Set the $method property
     *
     * Determines the value 'POST' or 'JSONStream' depending on the Content-type request header
     *
     * @return void
     */
    protected function setMethod()
    {

        if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'application/x-www-form-urlencoded') {
            $this->method = 'POST';
        } else {
            $this->method = 'JSONStream';
        }
    }

    /**
     * Validate the $payload property
     *
     * Checks for X-Hub-Signature header, securely compares it with a new signature generated from the $payload property and a secret authentication string, and validates the JSON string.
     * The secret authentication string is possibly stored in server environement variables.
     *
     * @uses GitDeploy\SettingsModel::getCurrentWorkingCopyKey() to get the current working copy settings key
     * @uses GitDeploy\SettingsModel::getWorkingCopySettings() to get the authToken and authTokenVarName settings
     * @uses GitDeploy\RepositoryController::validatePayload() to perform JSON string validation
     *
     * @return boolean|false true if the $payload property is valid, false otherwise
     */
    protected function validatePayload()
    {
        $valid = false;

        if (isset($_SERVER['HTTP_X_HUB_SIGNATURE'])) {
            $authToken          = $this->settingsModel->getWorkingCopySettings($this->settingsModel->getCurrentWorkingCopyKey())->authToken;
            $authTokenVarName   = $this->settingsModel->getWorkingCopySettings($this->settingsModel->getCurrentWorkingCopyKey())->authTokenVarName;

            $authToken = ($authToken === 'ENV') ? 'ENV' : $authToken;

            if ($authToken === 'ENV') {
                $authToken = getenv($authTokenVarName);
            }

            $signature = 'sha1=' . hash_hmac('sha1', $this->payload, $authToken);

            if (hash_equals($signature, $_SERVER['HTTP_X_HUB_SIGNATURE'])) {
                $this->payload = json_decode($this->payload);
                $valid = parent::validatePayload();
            }
        }

        return $valid;
    }

    /**
     * Does nothing - not applicable for this implementation
     * @return void
     */
    protected function validateToken()
    {
        // Not applicable
        return true;
    }
}


text:
namespace System.ComponentModel.Composition
{
    public static class AdaptationConstants
    {
        private const string CompositionNamespace = "System.ComponentModel.Composition";
        public const string AdapterContractName = CompositionNamespace + ".AdapterContract";
        public const string AdapterFromContractMetadataName = "FromContract";
        public const string AdapterToContractMetadataName = "ToContract";
    }
}


text:
require_relative 'boot'

require 'rails/all'
# require "rails"
# # Pick the frameworks you want:
# require "active_model/railtie"
# require "active_job/railtie"
# require "active_record/railtie"
# require "action_controller/railtie"
# require "action_mailer/railtie"
# require "action_view/railtie"
# require "action_cable/engine"
# # require "sprockets/railtie"
# require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Pluginseo
  class Application < Rails::Application
    config.action_dispatch.default_headers['P3P'] = 'CP="Not used"'
    config.action_dispatch.default_headers.delete('X-Frame-Options')
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.autoload_paths += %W(#{config.root}/app/services)
    # config.autoload_paths += %W(#{config.root}/app/serializers)
    # config.api_only = true
  end
end


text:
class Week < ActiveRecord::Base
  has_many :submissions

  validates :name, presence: true
  validates :max_points, presence: true

end


text: Fixed dependencies vulnerability


text:
/**
 * 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.
 */
package org.apache.aurora.scheduler.async;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.twitter.common.quantity.Amount;
import com.twitter.common.quantity.Time;
import com.twitter.common.stats.StatsProvider;
import com.twitter.common.testing.easymock.EasyMockTest;
import com.twitter.common.util.testing.FakeClock;

import org.apache.aurora.gen.AssignedTask;
import org.apache.aurora.gen.ScheduleStatus;
import org.apache.aurora.gen.ScheduledTask;
import org.apache.aurora.gen.TaskConfig;
import org.apache.aurora.gen.TaskEvent;
import org.apache.aurora.scheduler.events.PubsubEvent.TaskStateChange;
import org.apache.aurora.scheduler.state.StateManager;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

import static org.apache.aurora.gen.ScheduleStatus.ASSIGNED;
import static org.apache.aurora.gen.ScheduleStatus.FINISHED;
import static org.apache.aurora.gen.ScheduleStatus.INIT;
import static org.apache.aurora.gen.ScheduleStatus.KILLED;
import static org.apache.aurora.gen.ScheduleStatus.KILLING;
import static org.apache.aurora.gen.ScheduleStatus.LOST;
import static org.apache.aurora.gen.ScheduleStatus.PENDING;
import static org.apache.aurora.gen.ScheduleStatus.PREEMPTING;
import static org.apache.aurora.gen.ScheduleStatus.RUNNING;
import static org.apache.aurora.gen.ScheduleStatus.STARTING;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.junit.Assert.assertEquals;

public class TaskTimeoutTest extends EasyMockTest {

  private static final String TASK_ID = "task_id";
  private static final long TIMEOUT_MS = Amount.of(1L, Time.MINUTES).as(Time.MILLISECONDS);

  private AtomicLong timedOutTaskCounter;
  private ScheduledExecutorService executor;
  private ScheduledFuture<?> future;
  private StateManager stateManager;
  private FakeClock clock;
  private TaskTimeout timeout;
  private StatsProvider statsProvider;

  @Before
  public void setUp() {
    executor = createMock(ScheduledExecutorService.class);
    future = createMock(new Clazz<ScheduledFuture<?>>() { });
    stateManager = createMock(StateManager.class);
    clock = new FakeClock();
    statsProvider = createMock(StatsProvider.class);
    timedOutTaskCounter = new AtomicLong();
    expect(statsProvider.makeCounter(TaskTimeout.TIMED_OUT_TASKS_COUNTER))
        .andReturn(timedOutTaskCounter);
  }

  private void replayAndCreate() {
    control.replay();
    timeout = new TaskTimeout(
        executor,
        stateManager,
        Amount.of(TIMEOUT_MS, Time.MILLISECONDS),
        statsProvider);
  }

  private Capture<Runnable> expectTaskWatch(long expireMs) {
    Capture<Runnable> capture = createCapture();
    executor.schedule(
        EasyMock.capture(capture),
        eq(expireMs),
        eq(TimeUnit.MILLISECONDS));
    expectLastCall().andReturn(future);
    return capture;
  }

  private Capture<Runnable> expectTaskWatch() {
    return expectTaskWatch(TIMEOUT_MS);
  }

  private void changeState(String taskId, ScheduleStatus from, ScheduleStatus to) {
    IScheduledTask task = IScheduledTask.build(new ScheduledTask()
        .setStatus(to)
        .setAssignedTask(new AssignedTask().setTaskId(taskId)));
    timeout.recordStateChange(TaskStateChange.transition(task, from));
  }

  private void changeState(ScheduleStatus from, ScheduleStatus to) {
    changeState(TASK_ID, from, to);
  }

  @Test
  public void testNormalTransitions() {
    expectTaskWatch();
    expectTaskWatch();

    replayAndCreate();

    changeState(INIT, PENDING);
    changeState(PENDING, ASSIGNED);
    changeState(ASSIGNED, STARTING);
    changeState(STARTING, RUNNING);
    changeState(RUNNING, KILLING);
    changeState(KILLING, KILLED);
  }

  @Test
  public void testTransientToTransient() {
    expectTaskWatch();
    Capture<Runnable> killingTimeout = expectTaskWatch();
    expect(stateManager.changeState(
        TASK_ID,
        Optional.of(KILLING),
        LOST,
        TaskTimeout.TIMEOUT_MESSAGE))
        .andReturn(true);

    replayAndCreate();

    changeState(PENDING, ASSIGNED);
    changeState(ASSIGNED, KILLING);
    killingTimeout.getValue().run();
  }

  @Test
  public void testTimeout() throws Exception {
    Capture<Runnable> assignedTimeout = expectTaskWatch();
    expect(stateManager.changeState(
        TASK_ID,
        Optional.of(ASSIGNED),
        LOST,
        TaskTimeout.TIMEOUT_MESSAGE))
        .andReturn(true);

    replayAndCreate();

    changeState(INIT, PENDING);
    changeState(PENDING, ASSIGNED);
    assignedTimeout.getValue().run();
    assertEquals(timedOutTaskCounter.intValue(), 1);
  }

  @Test
  public void testTaskDeleted() throws Exception {
    Capture<Runnable> assignedTimeout = expectTaskWatch();
    expect(stateManager.changeState(
        TASK_ID,
        Optional.of(KILLING),
        LOST,
        TaskTimeout.TIMEOUT_MESSAGE))
        .andReturn(false);

    replayAndCreate();

    changeState(INIT, PENDING);
    changeState(PENDING, KILLING);
    assignedTimeout.getValue().run();
    assertEquals(timedOutTaskCounter.intValue(), 0);
  }

  private static IScheduledTask makeTask(
      String taskId,
      ScheduleStatus status,
      long stateEnteredMs) {

    return IScheduledTask.build(new ScheduledTask()
        .setStatus(status)
        .setTaskEvents(ImmutableList.of(new TaskEvent(stateEnteredMs, status)))
        .setAssignedTask(new AssignedTask()
            .setTaskId(taskId)
            .setTask(new TaskConfig())));
  }

  @Test
  public void testStorageStart() {
    expectTaskWatch(TIMEOUT_MS);
    expectTaskWatch(TIMEOUT_MS);
    expectTaskWatch(TIMEOUT_MS);

    replayAndCreate();

    clock.setNowMillis(TIMEOUT_MS * 2);
    for (IScheduledTask task : ImmutableList.of(
        makeTask("a", ASSIGNED, 0),
        makeTask("b", KILLING, TIMEOUT_MS),
        makeTask("c", PREEMPTING, clock.nowMillis() + TIMEOUT_MS))) {

      timeout.recordStateChange(TaskStateChange.initialized(task));
    }

    changeState("a", ASSIGNED, RUNNING);
    changeState("b", KILLING, KILLED);
    changeState("c", PREEMPTING, FINISHED);
  }
}


text:
class Document
  attr_reader :gif_file_name, :gif

  def initialize(file_path,size="100",interval=200)
    @pdf = MiniMagick::Image.open(file_path)
    @interval = interval
    @size = "#{size}%"
    @gif = Tempfile.new(["animated",".gif"], "./tmp")
    @gif_file_name = File.basename(@gif.path)
  end

  def to_gif
    begin
      convert_pdf
    ensure
      @gif.close
    end
  end

  private

    def convert_pdf
      MiniMagick::Tool::Convert.new(false) do |convert|
        convert.delay(@interval)
        convert << @pdf.path
        convert.alpha("remove")
        convert << "-loop" << "0"
        convert.resize(@size)
        convert << @gif.path
      end
    end

end


text:
/**
 * Filled angular gauge module for Highcharts
 * License: www.highcharts.com/license
 * Author: Torstein Honsi
 * Version: 0.0.1
 * http://jsfiddle.net/highcharts/5FnPZ/
 */

/*global Highcharts*/
(function (H) {
    "use strict";

    var defaultPlotOptions = H.getOptions().plotOptions,
        pInt = H.pInt,
        pick = H.pick;

    // The default options
    defaultPlotOptions.filledgauge = H.merge(defaultPlotOptions.gauge, {
        colorByPoint: true
    });

    // The series prototype
    H.seriesTypes.filledgauge = H.extendClass(H.seriesTypes.gauge, {
        type: 'filledgauge',

        /**
         * Draw the points where each point is one needle
         */
        drawPoints: function () {
            var series = this,
                yAxis = series.yAxis,
                center = yAxis.center,
                options = series.options,
                renderer = series.chart.renderer;

            H.each(series.points, function (point) {
                var graphic = point.graphic,
                    rotation = yAxis.startAngleRad + yAxis.translate(point.y, null, null, null, true),
                    radius = (pInt(pick(options.radius, 100)) * center[2]) / 200,
                    innerRadius = (pInt(pick(options.innerRadius, 60)) * center[2]) / 200,
                    shapeArgs,
                    d;

                // Handle the wrap option
                if (options.wrap === false) {
                    rotation = Math.max(yAxis.startAngleRad, Math.min(yAxis.endAngleRad, rotation));
                }
                rotation = rotation * 180 / Math.PI;

                shapeArgs = {
                    x: center[0],
                    y: center[1],
                    r: radius,
                    innerR: innerRadius,
                    start: yAxis.startAngleRad,
                    end: rotation / (180 / Math.PI)
                };

                if (graphic) {
                    d = shapeArgs.d;
                    graphic.animate(shapeArgs);
                    shapeArgs.d = d; // animate alters it
                } else {
                    point.graphic = renderer.arc(shapeArgs)
                        .attr({
                            stroke: options.borderColor || 'none',
                            'stroke-width': options.borderWidth || 0,
                            fill: point.color
                        })
                        .add(series.group);
                }
            });
        },
        animate: null
    });

}(Highcharts));


text:
using System;

namespace pwiz.Common.DataBinding.Attributes
{
    /// <summary>
    /// Specifies that the property is "advanced" and should only be displayed
    /// in column choosers if the user has chosen to "show advanced".
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class AdvancedAttribute : Attribute
    {
        public AdvancedAttribute() : this(true)
        {
        }
        public AdvancedAttribute(bool advanced)
        {
            Advanced = advanced;
        }
        public bool Advanced { get; private set; }
    }
}


text:
class ThirdController < UIViewController
  def initWithNibName(nib_name, bundle: bundle)
    self.tabBarItem = UITabBarItem.alloc.initWithTitle("Third", image: nil, tag: 0)

    super
  end
  def viewDidLoad
    self.view.backgroundColor = UIColor.whiteColor

    label               = UILabel.alloc.initWithFrame(self.view.bounds)
    label.text          = "3"
    label.font          = UIFont.systemFontOfSize(300)
    label.textAlignment = NSTextAlignmentCenter

    self.view.addSubview label

    super
  end
end


text:
void KVPairWriterTest::SetUp() {
  bufferFactory = NULL;
  parentWorker = NULL;
  writer = NULL;
  memoryAllocator = NULL;

  memoryAllocator = new SimpleMemoryAllocator();

  NamedObjectCollection dependencies;
  Params params;
  params.add<uint64_t>("DEFAULT_BUFFER_SIZE", 1000);
  parentWorker = dynamic_cast<KVPairWriterParentWorker*>(
    KVPairWriterParentWorker::newInstance(
      "dummy_phase_name", "dummy_stage_name", 0, params, *memoryAllocator,
      dependencies));

  EXPECT_TRUE(parentWorker != NULL);

  createNewKVPairWriter(1, NULL, NULL);
}

void KVPairWriterTest::TearDown() {
  if (bufferFactory != NULL) {
    delete bufferFactory;
    bufferFactory = NULL;
  }

  if (parentWorker != NULL) {
    delete parentWorker;
    parentWorker = NULL;
  }

  if (writer != NULL) {
    delete writer;
    writer = NULL;
  }

  if (memoryAllocator != NULL) {
    delete memoryAllocator;
    memoryAllocator = NULL;
  }
}

void KVPairWriterTest::createNewKVPairWriter(
  uint64_t numBuffers, PartitionFunctionInterface* partitionFunction,
  KVPairWriteStrategyInterface* writeStrategy) {

  if (writer != NULL) {
    delete writer;
    writer = NULL;
  }

  if (partitionFunction == NULL) {
    partitionFunction = new SinglePartitionMergingPartitionFunction();
  }

  writer = new KVPairWriter(
    numBuffers, *partitionFunction, writeStrategy,
    100, NULL,
    boost::bind(
      &KVPairWriterParentWorker::emitBufferFromWriter, parentWorker, _1, _2),
    boost::bind(
      &KVPairWriterParentWorker::getBufferForWriter, parentWorker, _1),
    boost::bind(
      &KVPairWriterParentWorker::putBufferFromWriter, parentWorker, _1),
    boost::bind(
      &KVPairWriterParentWorker::logSample, parentWorker, _1),
    boost::bind(
      &KVPairWriterParentWorker::logWriteStats, parentWorker, _1, _1, _2, _2),
    true);
}

void KVPairWriterTest::createNewFastKVPairWriter(
  PartitionFunctionInterface* partitionFunction) {

  if (writer != NULL) {
    delete writer;
    writer = NULL;
  }

  if (partitionFunction == NULL) {
    partitionFunction = new SinglePartitionMergingPartitionFunction();
  }

  writer = new FastKVPairWriter(
    partitionFunction, 100,
    boost::bind(
      &KVPairWriterParentWorker::emitBufferFromWriter, parentWorker, _1, _2),
    boost::bind(
      &KVPairWriterParentWorker::getBufferForWriter, parentWorker, _1),
    boost::bind(
      &KVPairWriterParentWorker::putBufferFromWriter, parentWorker, _1),
    boost::bind(
      &KVPairWriterParentWorker::logSample, parentWorker, _1),
    boost::bind(
      &KVPairWriterParentWorker::logWriteStats, parentWorker, _1, _1, _2, _2),
    true, false);
}

void KVPairWriterTest::createNewTuple(uint8_t** key, uint64_t keyLength,
                                      uint8_t** value, uint64_t valueLength) {
  *key = new uint8_t[keyLength];
  *value = new uint8_t[valueLength];

  for (uint32_t i = 0; i < keyLength; i++) {
    (*key)[i] = i;
  }

  for (uint32_t i = 0; i < valueLength; i++) {
    (*value)[i] = i;
  }
}

TEST_F(KVPairWriterTest, testStandardWrite) {
  createNewKVPairWriter(1, NULL, NULL);

  uint32_t keyLength = 20;
  uint32_t valueLength = 80;
  uint8_t* key;
  uint8_t* value;

  createNewTuple(&key, keyLength, &value, valueLength);

  KeyValuePair kvPair;
  kvPair.setKey(key, keyLength);
  kvPair.setValue(value, valueLength);

  // Test write with regular writer
  writer->write(kvPair);
  writer->flushBuffers();

  validateStandardWrite(key, keyLength, value, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  // Test write with fast writer
  createNewFastKVPairWriter(NULL);

  writer->write(kvPair);
  writer->flushBuffers();

  validateStandardWrite(key, keyLength, value, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  delete[] key;
  key = NULL;
  delete[] value;
  value = NULL;
}

TEST_F(KVPairWriterTest, testLargeTuple) {
  createNewKVPairWriter(1, NULL, NULL);

  uint32_t keyLength = 500;
  uint32_t valueLength = 300;
  uint8_t* key;
  uint8_t* value;

  createNewTuple(&key, keyLength, &value, valueLength);

  KeyValuePair kvPair;
  kvPair.setKey(key, keyLength);
  kvPair.setValue(value, valueLength);

  // Test large tuple with regular writer
  writer->write(kvPair);
  writer->write(kvPair);
  writer->flushBuffers();

  validateLargeWrite(key, keyLength, value, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  // Test large tuple with fast writer
  createNewFastKVPairWriter(NULL);

  writer->write(kvPair);
  writer->write(kvPair);
  writer->flushBuffers();

  validateLargeWrite(key, keyLength, value, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  delete[] key;
  key = NULL;
  delete[] value;
  value = NULL;
}

TEST_F(KVPairWriterTest, testHugeTuple) {
  createNewKVPairWriter(1, NULL, NULL);

  uint32_t keyLength = 900;
  uint32_t valueLength = 400;
  uint8_t* key;
  uint8_t* value;

  createNewTuple(&key, keyLength, &value, valueLength);

  KeyValuePair kvPair;
  kvPair.setKey(key, keyLength);
  kvPair.setValue(value, valueLength);

  // Test huge tuple with regular writer
  writer->write(kvPair);
  writer->flushBuffers();

  const std::list<KVPairBuffer*>& emittedBuffers =
    parentWorker->getEmittedBuffers();

  EXPECT_EQ(static_cast<size_t>(1), emittedBuffers.size());

  KVPairBuffer* buffer = *emittedBuffers.begin();

  EXPECT_EQ(static_cast<uint64_t>(KeyValuePair::tupleSize(900, 400)),
            buffer->getCurrentSize());
  EXPECT_EQ(static_cast<uint64_t>(2000), buffer->getCapacity());
  EXPECT_EQ(static_cast<uint64_t>(1), buffer->getNumTuples());

  KeyValuePair emittedKVPair;
  EXPECT_EQ(true, buffer->getNextKVPair(emittedKVPair));
  checkTuple(emittedKVPair, key, keyLength, value, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  // Test huge tuple with fast writer
  createNewFastKVPairWriter(NULL);

  writer->write(kvPair);
  writer->flushBuffers();

  EXPECT_EQ(static_cast<size_t>(1), emittedBuffers.size());

  buffer = *emittedBuffers.begin();

  EXPECT_EQ(static_cast<uint64_t>(KeyValuePair::tupleSize(900, 400)),
            buffer->getCurrentSize());
  EXPECT_EQ(static_cast<uint64_t>(2000), buffer->getCapacity());
  EXPECT_EQ(static_cast<uint64_t>(1), buffer->getNumTuples());

  EXPECT_EQ(true, buffer->getNextKVPair(emittedKVPair));
  checkTuple(emittedKVPair, key, keyLength, value, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  delete[] key;
  key = NULL;
  delete[] value;
  value = NULL;
}

void KVPairWriterTest::appendTuple(uint8_t* key, uint32_t keyLength,
                                   uint32_t valueLength) {
  for (uint32_t i = 0; i < keyLength; i++) {
    key[i] = i;
  }

  uint8_t* value = writer->setupWrite(key, keyLength, valueLength);

  for (uint32_t i = 0; i < valueLength; i++) {
    value[i] = i;
  }

  writer->commitWrite(valueLength);
}

TEST_F(KVPairWriterTest, testSetupAndCommitTupleWrite) {
  createNewKVPairWriter(1, NULL, NULL);

  uint32_t keyLength = 20;
  uint32_t valueLength = 80;
  uint8_t* key = new uint8_t[keyLength];
  uint8_t* expectedValue = new uint8_t[valueLength];

  for (uint32_t i = 0; i < valueLength; i++) {
    expectedValue[i] = i;
  }

  // Test setup/commit with regular writer
  appendTuple(key, keyLength, valueLength);
  writer->flushBuffers();

  validateStandardWrite(key, keyLength, expectedValue, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  // Test setup/commit with fast writer
  createNewFastKVPairWriter(NULL);

  appendTuple(key, keyLength, valueLength);
  writer->flushBuffers();

  validateStandardWrite(key, keyLength, expectedValue, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  delete[] key;
  delete[] expectedValue;
}

TEST_F(KVPairWriterTest, testSetupAndCommitLargeTuple) {
  createNewKVPairWriter(1, NULL, NULL);

  uint32_t keyLength = 500;
  uint32_t valueLength = 300;
  uint8_t* key = new uint8_t[keyLength];
  uint8_t* expectedValue = new uint8_t[valueLength];

  for (uint32_t i = 0; i < valueLength; i++) {
    expectedValue[i] = i;
  }

  // Test setup/commit for large tuple with regular writer
  appendTuple(key, keyLength, valueLength);
  appendTuple(key, keyLength, valueLength);
  writer->flushBuffers();

  validateLargeWrite(key, keyLength, expectedValue, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  // Test setup/commit for large tuple with fast writer
  createNewFastKVPairWriter(NULL);

  appendTuple(key, keyLength, valueLength);
  appendTuple(key, keyLength, valueLength);
  writer->flushBuffers();

  validateLargeWrite(key, keyLength, expectedValue, valueLength);

  parentWorker->returnEmittedBuffersToPool();

  delete[] key;
  delete[] expectedValue;
}

void KVPairWriterTest::checkTuple(KeyValuePair& kvPair, uint8_t* referenceKey,
                                  uint32_t keyLength, uint8_t* referenceValue,
                                  uint32_t valueLength) {
  EXPECT_EQ(keyLength, kvPair.getKeyLength());

  if (referenceKey != NULL) {
    EXPECT_EQ(0, memcmp(referenceKey, kvPair.getKey(), keyLength));
  }

  EXPECT_EQ(valueLength, kvPair.getValueLength());

  if (referenceValue != NULL) {
    EXPECT_EQ(0, memcmp(referenceValue, kvPair.getValue(), valueLength));
  }
}

void KVPairWriterTest::validateStandardWrite(
  uint8_t* key, uint32_t keyLength, uint8_t* value, uint32_t valueLength) {
  const std::list<KVPairBuffer*>& emittedBuffers =
    parentWorker->getEmittedBuffers();

  EXPECT_EQ(static_cast<size_t>(1), emittedBuffers.size());

  KVPairBuffer* buffer = emittedBuffers.front();
  EXPECT_EQ(
    static_cast<uint64_t>(KeyValuePair::tupleSize(keyLength, valueLength)),
    buffer->getCurrentSize());
  EXPECT_EQ(static_cast<uint64_t>(1), buffer->getNumTuples());

  KeyValuePair emittedKVPair;
  EXPECT_EQ(true, buffer->getNextKVPair(emittedKVPair));
  checkTuple(emittedKVPair, key, keyLength, value, valueLength);
}

void KVPairWriterTest::validateLargeWrite(
  uint8_t* key, uint32_t keyLength, uint8_t* value, uint32_t valueLength) {
  const std::list<KVPairBuffer*>& emittedBuffers =
    parentWorker->getEmittedBuffers();

  EXPECT_EQ(static_cast<size_t>(2), emittedBuffers.size());

  for (std::list<KVPairBuffer*>::const_iterator iter = emittedBuffers.begin();
       iter != emittedBuffers.end(); iter++) {
    KVPairBuffer* buffer = *iter;

    EXPECT_EQ(
      static_cast<uint64_t>(KeyValuePair::tupleSize(keyLength, valueLength)),
      buffer->getCurrentSize());
    EXPECT_EQ(static_cast<uint64_t>(1), buffer->getNumTuples());

    KeyValuePair emittedKVPair;

    EXPECT_EQ(true, buffer->getNextKVPair(emittedKVPair));

    checkTuple(emittedKVPair, key, keyLength, value, valueLength);
  }
}

TEST_F(KVPairWriterTest, testPhaseZeroStrategy) {
  PhaseZeroKVPairWriteStrategy* phaseZeroStrategy =
    new PhaseZeroKVPairWriteStrategy();

  createNewKVPairWriter(1, NULL, phaseZeroStrategy);

  uint32_t maxKeyLength = 50;
  uint8_t* key = new uint8_t[maxKeyLength];

  appendTuple(key, 20, 80);
  appendTuple(key, 30, 60);
  appendTuple(key, 50, 70);
  appendTuple(key, 22, 37);

  writer->flushBuffers();

  const std::list<KVPairBuffer*>& emittedBuffers =
    parentWorker->getEmittedBuffers();

  EXPECT_EQ(static_cast<size_t>(1), emittedBuffers.size());

  KVPairBuffer* buffer = emittedBuffers.front();

  // Header + Key + uint64_t tuple size for each tuple
  uint64_t totalSize =
    KeyValuePair::tupleSize(20, sizeof(uint64_t)) +
    KeyValuePair::tupleSize(30, sizeof(uint64_t)) +
    KeyValuePair::tupleSize(50, sizeof(uint64_t)) +
    KeyValuePair::tupleSize(22, sizeof(uint64_t));

  EXPECT_EQ(totalSize, buffer->getCurrentSize());

  KeyValuePair emittedKVPair;
  EXPECT_EQ(true, buffer->getNextKVPair(emittedKVPair));
  uint64_t value = KeyValuePair::tupleSize(20, 80);
  uint8_t* valuePointer = reinterpret_cast<uint8_t*>(&value);
  checkTuple(emittedKVPair, key, 20, valuePointer, sizeof(valuePointer));

  EXPECT_EQ(true, buffer->getNextKVPair(emittedKVPair));
  value = KeyValuePair::tupleSize(30, 60);
  checkTuple(emittedKVPair, key, 30, valuePointer, sizeof(valuePointer));

  EXPECT_EQ(true, buffer->getNextKVPair(emittedKVPair));
  value = KeyValuePair::tupleSize(50, 70);
  checkTuple(emittedKVPair, key, 50, valuePointer, sizeof(valuePointer));

  EXPECT_EQ(true, buffer->getNextKVPair(emittedKVPair));
  value = KeyValuePair::tupleSize(22, 37);
  checkTuple(emittedKVPair, key, 22, valuePointer, sizeof(valuePointer));

  EXPECT_TRUE(!buffer->getNextKVPair(emittedKVPair));

  parentWorker->returnEmittedBuffersToPool();

  delete[] key;
  key = NULL;
}


text:
require File.dirname(__FILE__) + '/../test_helper'

class PeriodTest < ActiveSupport::TestCase
  fixtures :periods

  # This tests the options method to make sure it returns the correct
  # datastructure with the correct number of elements.
  # This does not check the validity of the contents.
  def test_period_options
    options = Period.options

    assert_equal 13, options.length, "There are 13 period options"

    for option in options
      assert_equal 2, option.length, "Option is an array with two values"
    end

  end

  def test_to_s
    period = Period.find(:first)
    assert_equal period.name, period.to_s, "Converting a period to a string gives the name of the period."
  end

end


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { autoinject, customElement, bindable, bindingMode, children, inlineView, containerless, Container, ViewCompiler, ViewSlot } from 'aurelia-framework';
import { UIEvent } from "../../utils/ui-event";
import * as _ from "lodash";
let UIDgCell = class UIDgCell {
    constructor(element, container, compiler) {
        this.element = element;
        this.container = container;
        this.compiler = compiler;
    }
    attached() {
        if (this.element.innerHTML)
            return;
        let template = '';
        if (this.type == 'subview') {
            if (isFunction(this.parent.subview))
                template = this.parent.subview({ record: this.record });
            else
                template = this.parent.subview;
        }
        else if (this.col.type == 'normal')
            template = `<span class="\${col.class}" innerhtml.bind='col.getValue(record[col.dataId],record)'></span>`;
        else if (this.col.type == 'glyph')
            template = `

        <ui-glyph class="\${col.class} \${col.getGlyph(record[col.dataId],record)}" glyph.bind="col.getGlyph(record[col.dataId],record)"></ui-glyph>

`;
        else if (this.col.type == 'link')
            template = `
          <ui-glyph glyph.bind="col.getGlyph(record[col.dataId],record)" if.bind="col.glyph"></ui-glyph>

        `;
        else if (this.col.type == 'button') {
            template = `<ui-button click.trigger="col.fireClick($event,record[col.dataId],record)" show.bind="col.isVisible(record[col.dataId],record)" theme.bind="col.getTheme(record[col.dataId],record)" small square glyph.bind="col.getGlyph(record[col.dataId],record)" disabled.bind="col.isDisabled(record[col.dataId],record)" dropdown.bind="col.dropdown" menuopen.trigger="col.fireMenuOpen($event, record)">

        </ui-button>`;
            this.element.classList.add('btn-fix');
        }
        let viewFactory = this.compiler.compile(`<template>${template}</template>`);
        let view = viewFactory.create(this.container);
        view.bind(this);
        this.slot = new ViewSlot(this.element, true);
        this.slot.add(view);
        this.slot.attached();
    }
    bind() {
        if (this.slot)
            this.slot.attached();
    }
    detached() {
        if (this.slot)
            this.slot.detached();
    }
};
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgCell.prototype, "col", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgCell.prototype, "type", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgCell.prototype, "record", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgCell.prototype, "parent", void 0);
UIDgCell = __decorate([
    autoinject(),
    inlineView(`<template></template>`),
    customElement('ui-dg-cell'),
    __metadata("design:paramtypes", [Element, Container, ViewCompiler])
], UIDgCell);
export { UIDgCell };
let UIDgRow = class UIDgRow {
    constructor(element) {
        this.element = element;
        this.level = 0;
        this.last = false;
    }
    bind(bindingContext, overrideContext) {
        if (this.level > 0 && !overrideContext.$first && overrideContext.$last)
            this.last = true;
    }
    indexChanged() {
        UIEvent.queueTask(() => {
            if (this.rowExpand && this.parent.expandWidth < this.rowExpand.offsetWidth)
                this.parent.expandWidth = this.rowExpand.offsetWidth;
            if (this.rowCounter && this.parent.counterWidth < this.rowCounter.offsetWidth)
                this.parent.counterWidth = this.rowCounter.offsetWidth;
        });
    }
    attached() {
        if (this.rowExpand && this.parent.expandWidth < this.rowExpand.offsetWidth)
            this.parent.expandWidth = this.rowExpand.offsetWidth;
        if (this.rowCounter && this.parent.counterWidth < this.rowCounter.offsetWidth)
            this.parent.counterWidth = this.rowCounter.offsetWidth;
    }
};
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgRow.prototype, "level", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgRow.prototype, "index", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgRow.prototype, "record", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgRow.prototype, "parent", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDgRow.prototype, "odd", void 0);
UIDgRow = __decorate([
    autoinject(),
    inlineView(`<template>

        <ui-glyph glyph="glyph" repeat.for="i of level"></ui-glyph>
        <ui-glyph glyph="\${record.isOpen?'glyph-icon-minus':'glyph-icon-plus'}"></ui-glyph>

\${index}

      <ui-dg-cell class="ui-dg-cell \${col.align}" repeat.for="col of parent.colLocked" css.bind="{width:col.getWidth(col.width)+'px'}" col.bind="col" parent.bind="parent" record.bind="record">
      </ui-dg-cell>

    <ui-dg-cell class="ui-dg-cell \${col.align}" repeat.for="col of parent.cols" css.bind="{width:col.getWidth(col.width)+'px'}" col.bind="col" parent.bind="parent" record.bind="record">
    </ui-dg-cell>

  <ui-dg-row containerless if.bind="!parent.subview&&record.subdata&&record.isOpen" level.bind="level+1" parent.bind="parent" record.bind="rec" index.bind="$index" odd.bind="$odd" repeat.for="rec of record.subdata"></ui-dg-row>

    <ui-dg-cell class="ui-dg-subview" parent.bind="parent" record.bind="record" type="subview"></ui-dg-cell>

</template>`),
    customElement('ui-dg-row'),
    __metadata("design:paramtypes", [Element])
], UIDgRow);
export { UIDgRow };
let UIDatagrid = class UIDatagrid {
    constructor(element) {
        this.element = element;
        this.data = [];
        this.summaryRow = false;
        this.sortColumn = '';
        this.sortOrder = '';
        this.perPage = 50;
        this.cols = [];
        this.colHead = [];
        this.colLocked = [];
        this.virtual = false;
        this.rowCounter = false;
        this.rowExpander = false;
        this.expandWidth = 0;
        this.counterWidth = 0;
        this.loaded = false;
        this.isBusy = false;
        this.paged = [];
        this.filtered = [];
        this.isRtl = false;
        this.resizing = false;
        this.virtual = element.hasAttribute('virtual');
        this.rowCounter = element.hasAttribute('row-counter');
        this.rowExpander = element.hasAttribute('row-expander');
        if (!element.hasAttribute('scroll'))
            this.element.classList.add('ui-auto-size');
    }
    bind(bindingContext, overrideContext) {
        if (this.pager) {
            if (!(this.pager instanceof UIPager))
                throw new Error('Pager must be instance of UIPager');
            this.obPageChange = UIEvent.observe(this.pager, 'page', () => this.makePage());
        }
    }
    attached() {
        UIEvent.queueTask(() => {
            this.columnsChanged(this.columns);
            this.dataChanged(this.data);
        });
    }
    detached() {
        if (this.obPageChange)
            this.obPageChange.dispose();
    }
    columnsChanged(c) {
        this.colHead = _.sortBy(this.columns, 'locked');
        let cols = _.sortBy(_.flatMap(this.columns, c => c.columns || [c]), 'locked');
        this.colLocked = _.filter(cols, (c) => c.locked == 0);
        this.cols = _.filter(cols, (c) => c.locked == 1);
    }
    dataChanged(newValue) {
        UIEvent.queueTask(() => {
            if (this.pager) {
                this.pager.page = 0;
                this.pager.totalPages = Math.ceil(this.data.length / this.perPage);
            }
            this.filter();
        });
    }
    filter() {
        this.filtered = this.data;
        this.makePage();
    }
    makePage() {
        this.isBusy = true;
        UIEvent.queueTask(() => {
            let data = _.orderBy(this.filtered, [this.sortColumn, 'ID', 'id'], [this.sortOrder, this.sortOrder, this.sortOrder]);
            if (this.pager) {
                let pp = parseInt(this.perPage + '');
                data = _.slice(data, this.pager.page * pp, (this.pager.page * pp) + pp);
            }
            this.paged = data;
            this.loaded = true;
            UIEvent.queueTask(() => this.isBusy = false);
        });
    }
    doSort(col) {
        if (!col.sortable || this.resizing)
            return;
        if (this.sortColumn != col.dataId)
            this.sortOrder = 'asc';
        if (this.sortColumn == col.dataId)
            this.sortOrder = this.sortOrder == 'asc' ? 'desc' : 'asc';
        this.sortColumn = col.dataId;
        UIEvent.queueTask(() => this.makePage());
    }
    fireSelect(record) {
        UIEvent.fireEvent('rowselect', this.element, ({ record }));
    }
    resizeColumn(evt, col) {
        if (evt.button != 0)
            return true;
        this.isRtl = window.isRtl(this.element);
        this.diff = 0;
        this.colResize = col;
        this.resizing = true;
        this.startX = (evt.x || evt.clientX);
        this.ghost.style[this.isRtl ? 'left' : 'right'] = "none";
        this.ghost.style[this.isRtl ? 'right' : 'left'] = (getParentByClass(evt.target, 'ui-dg-cell').offsetLeft + parseInt(col.width)) + 'px';
        document.addEventListener('mouseup', this.stop = evt => this.resizeEnd(evt));
        document.addEventListener('mousemove', this.move = evt => this.resize(evt));
    }
    resize(evt) {
        var x = (evt.x || evt.clientX) - this.startX;
        x = (this.isRtl ? -1 : 1) * x;
        if (x < 0 && (parseInt(this.colResize.width) + x) <= (this.colResize.minWidth || 80))
            return;
        if (x > 0 && (parseInt(this.colResize.width) + x) >= (500))
            return;
        this.startX = (evt.x || evt.clientX);
        this.diff += x;
        this.colResize.width = (parseInt(this.colResize.width) + x);
        this.ghost.style[this.isRtl ? 'right' : 'left'] = (parseInt(this.ghost.style[this.isRtl ? 'right' : 'left']) + x) + 'px';
    }
    resizeEnd(evt) {
        this.resizing = false;
        document.removeEventListener('mousemove', this.move);
        document.removeEventListener('mouseup', this.stop);
        evt.stopPropagation();
        return false;
    }
};
__decorate([
    children('ui-dg-column-group,ui-dg-column,ui-dg-button,ui-dg-link,ui-dg-glyph'),
    __metadata("design:type", Object)
], UIDatagrid.prototype, "columns", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDatagrid.prototype, "data", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDatagrid.prototype, "subview", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDatagrid.prototype, "summaryRow", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDatagrid.prototype, "sortColumn", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDatagrid.prototype, "sortOrder", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDatagrid.prototype, "pager", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIDatagrid.prototype, "perPage", void 0);
UIDatagrid = __decorate([
    autoinject(),
    inlineView(`<template class="ui-datagrid">
<slot></slot>

    <template repeat.for="col of colHead">

    <ui-glyph glyph="glyph-funnel"></ui-glyph>

    <ui-glyph glyph="glyph-funnel"></ui-glyph>

    </template>

<slot name="dg-empty"></slot>

  <ui-dg-row containerless parent.bind="$parent" record.bind="record" index.bind="$index" odd.bind="$odd" repeat.for="record of paged"></ui-dg-row>

  <ui-dg-row parent.bind="$parent" record.bind="record" index.bind="$index" odd.bind="$odd" virtual-repeat.for="record of paged"></ui-dg-row>

    <ui-glyph class="ui-anim-loader" glyph="glyph-loader"></ui-glyph>

<template>`),
    customElement('ui-datagrid'),
    __metadata("design:paramtypes", [Element])
], UIDatagrid);
export { UIDatagrid };
let UIDGEmpty = class UIDGEmpty {
};
UIDGEmpty = __decorate([
    containerless(),
    customElement('ui-dg-empty'),
    inlineView(`<template><div slot="dg-empty"><slot></slot></div></template>`)
], UIDGEmpty);
export { UIDGEmpty };
let UIPager = class UIPager {
    constructor(element) {
        this.element = element;
        this.page = 0;
        this.style = "chevron";
        this.totalPages = 1;
    }
    bind(bindingContext, overrideContext) {
        if (this.store)
            this.totalPages = this.store.totalPages;
    }
    attached() {
        if (this.store && !this.store.isLoaded)
            UIEvent.queueTask(() => this.store.loadPage(this.page));
    }
    fireChange() {
        if (this.store)
            this.store.loadPage(this.page);
        UIEvent.fireEvent('change', this.element, this.page);
    }
};
__decorate([
    bindable({ defaultBindingMode: bindingMode.twoWay }),
    __metadata("design:type", Object)
], UIPager.prototype, "page", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIPager.prototype, "style", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIPager.prototype, "store", void 0);
__decorate([
    bindable(),
    __metadata("design:type", Object)
], UIPager.prototype, "totalPages", void 0);
UIPager = __decorate([
    autoinject(),
    inlineView(`<template class="ui-pager">
  <ui-glyph glyph="glyph-\${style}-double-left"></ui-glyph>
  <ui-glyph glyph="glyph-\${style}-left"></ui-glyph>
  \${page+1} of \${totalPages}
  =totalPages?'disabled':''}" click.trigger="fireChange(page=page+1)"><ui-glyph glyph="glyph-\${style}-right"></ui-glyph>
  =totalPages?'disabled':''}" click.trigger="fireChange(page=totalPages-1)"><ui-glyph glyph="glyph-\${style}-double-right"></ui-glyph>
</template>`),
    customElement('ui-pager'),
    __metadata("design:paramtypes", [Element])
], UIPager);
export { UIPager };
let UIDGFilter = class UIDGFilter {
    constructor(element) {
        this.element = element;
    }
};
UIDGFilter = __decorate([
    autoinject(),
    inlineView(`<template class="ui-filter"></template>`),
    customElement('ui-dg-filter'),
    __metadata("design:paramtypes", [Element])
], UIDGFilter);
export { UIDGFilter };


text:
namespace Merchello.Core.Trees
{
    using System.Collections.Generic;
    using System.Linq;

    using Merchello.Core.Models.Interfaces;

    /// <summary>
    /// A base class for visiting nodes in a tree.
    /// </summary>
    /// <typeparam name="TNode">
    /// The type of the node value
    /// </typeparam>
    internal abstract class TreeNodeVistorBase<TNode> : ITreeNodeVisitor<TNode>
    {
        /// <summary>
        /// A queue to store found nodes.
        /// </summary>
        private readonly Queue<TreeNode<TNode>> _nodes;

        /// <summary>
        /// Initializes a new instance of the <see cref="TreeNodeVistorBase{TNode}"/> class.
        /// </summary>
        protected TreeNodeVistorBase()
        {
            _nodes = new Queue<TreeNode<TNode>>();
        }

        /// <summary>
        /// Gets the list of nodes.
        /// </summary>
        /// <remarks>
        /// Used to store matched nodes from the tree traversal
        /// </remarks>
        public IEnumerable<TreeNode<TNode>> Nodes
        {
            get
            {
                return _nodes.ToArray();
            }
        }

        /// <summary>
        /// Gets the values of the matched nodes
        /// </summary>
        public IEnumerable<TNode> Values
        {
            get
            {
                return _nodes.ToArray().Select(x => x.Value);
            }
        }

        /// <inheritdoc/>
        public bool Completed { get; set; }

        /// <inheritdoc/>
        public abstract void Visit(TreeNode<TNode> item);

        /// <summary>
        /// Removes a node from the top of the queue.
        /// </summary>
        /// <returns>
        /// The <see cref="TreeNode{TNode}"/>.
        /// </returns>
        protected TreeNode<TNode> Dequeue()
        {
            return _nodes.Dequeue();
        }

        /// <summary>
        /// Adds a node the the queue.
        /// </summary>
        /// <param name="node">
        /// The node.
        /// </param>
        protected void Enqueue(TreeNode<TNode> node)
        {
            _nodes.Enqueue(node);
        }
    }
}