text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------

/**
 * ExpressionEngine Image RTE Tool
 *
 * @package		ExpressionEngine
 * @subpackage	RTE
 * @category	RTE
 * @author		EllisLab Dev Team
 * @link		http://ellislab.com
 */
class Image_rte {

	public $info = array(
		'name'			=> 'Image',
		'version'		=> '1.0',
		'description'	=> 'Inserts and manages image alignment in the RTE',
		'cp_only'		=> 'y'
	);

	private $EE;
	private $folders	= array();
	private $filedirs	= array();

	/**
	 * Constructor
	 *
	 * @access	public
	 */
	function __construct()
	{
		// Make a local reference of the ExpressionEngine super object
		$this->EE =& get_instance();
	}

	// --------------------------------------------------------------------

	/**
	 * Globals we need
	 *
	 * @access	public
	 */
	function globals()
	{
		ee()->lang->loadfile('rte');
		return array(
			'rte.image'	=> array(
				'add'			=> lang('img_add'),
				'remove'		=> lang('img_remove'),
				'align_left'	=> lang('img_align_left'),
				'align_center'	=> lang('img_align_center'),
				'align_right'	=> lang('img_align_right'),
				'wrap_left'		=> lang('img_wrap_left'),
				'wrap_none'		=> lang('img_wrap_none'),
				'wrap_right'	=> lang('img_wrap_right'),
				'caption_text'	=> lang('rte_image_caption'),
				'center_error'	=> lang('rte_center_error'),
				'folders'		=> $this->folders,
				'filedirs'		=> $this->filedirs
			)
		);
	}

	/** -------------------------------------
	/**  Libraries we need loaded
	/** -------------------------------------*/
	function libraries()
	{
		return array();

		// @todo The following should already be loaded in the CP...
/*
		return array(
			'plugin'	=> 'ee_filebrowser',
			'ui'		=> 'dialog'
		);
*/
	}

	// --------------------------------------------------------------------

	/**
	 * Styles we need
	 *
	 * @access	public
	 */
	function styles()
	{
		# load the external file
		$styles	= file_get_contents( 'rte.image.css', TRUE );
		$theme	= ee()->session->userdata('cp_theme');
		$theme	= ee()->config->item('theme_folder_url').'cp_themes/'.($theme ? $theme : 'default').'/';
		return str_replace('{theme_folder_url}', $theme, $styles);
	}

	// --------------------------------------------------------------------

	/**
	 * JS Defintion
	 *
	 * @access	public
	 */
	function definition()
	{
		# load the external file
		return file_get_contents( 'rte.image.js', TRUE );
	}

} // END Image_rte

/* End of file rte.image.php */
/* Location: ./system/expressionengine/rte_tools/image/rte.image.php */


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title></title>
	<link rel='stylesheet' type='text/css' href='bower_components/pebble-slate/dist/css/slate.min.css'>
	<link rel='stylesheet' type='text/css' href='css/style.css'>

Watchface
Configuration Page

				Use this configuration page to choose the settings you would like
				applied to this app.

Connection

				Warn on disconnect
				<input type="checkbox" class="item-toggle" id="btWarningToggle" checked>

			When on the clock will vibrate and a text is shown on the screen when Bluetooth connection to the phone is lost.

Colors

				Background Color
				<input id='backgroundColorPicker' type='text' class='item-color item-color-sunny' value='#00AAFF'>

				Clock Face Color
				<input id='clockfaceColorPicker' type='text' class='item-color item-color-sunny' value='#FFFFFF'>

				Stroke Color
				<input id='clockStrokeColorPicker' type='text' class='item-color item-color-sunny' value='#000000'>

			These settings only change on the watch after you click save.

			<input id='submitButton' type='button' class='item-button' value='SUBMIT'>

redpajama_set_name: RedPajamaGithub


text:
require 'test/unit'

require_relative '../../../lib/quizzer/loaders/tests_loader'

class TestsLoaderTest < Test::Unit::TestCase

  @@tests_url = 'test/resources/tests.json';

  def test_load_tests
    assert(File.exist?(@@tests_url), 'Missing tests file')

    begin
      tests = TestsLoader::load_tests(@@tests_url)
      assert(tests.length == 1, 'Unexpected tests array size')
    rescue
      fail('Exception not expected')
    end
  end

end


text:
package org.apache.geronimo.interop.generator;

import java.util.LinkedList;
import java.util.List;

public class GenOptions {
    // -gs  genSrcDir
    // -gc  genClassDir
    // -o   overwrite
    // -v   verbose
    // -s   simpleidl
    // -cp  classpath
    // -g   generate
    // -c   compile
    // -cd  compiledebug
    // -lc  loadclass

    private String genSrcDir = "./src";
    private String genClassDir = "./classes";
    private boolean overwrite = false;
    private boolean verbose = false;
    private boolean simpleIdl = false;
    private String classpath = "";
    private boolean generate = true;
    private boolean compile = false;
    private boolean compileDebug = false;
    private boolean loadclass = false;

    private List interfaces = new LinkedList();

    public GenOptions() {
    }

    public GenOptions(String defaultSrcDir, String args[]) throws GenWarning, GenException {
        genSrcDir = defaultSrcDir;
        parseOptions(args);
    }

    public String getGenSrcDir() {
        return genSrcDir;
    }

    public void setGenSrcDir(String genSrcDir) {
        this.genSrcDir = genSrcDir;
    }

    public String getGenClassDir() {
        return genClassDir;
    }

    public void setGenClassDir(String genClassDir) {
        this.genClassDir = genClassDir;
    }

    public boolean isOverwrite() {
        return overwrite;
    }

    public void setOverwrite(boolean overwrite) {
        this.overwrite = overwrite;
    }

    public boolean isVerbose() {
        return verbose;
    }

    public void setVerbose(boolean verbose) {
        this.verbose = verbose;
    }

    public boolean isSimpleIdl() {
        return simpleIdl;
    }

    public void setSimpleIdl(boolean simpleIdl) {
        this.simpleIdl = simpleIdl;
    }

    public String getClasspath() {
        return classpath;
    }

    public void setClasspath(String classpath) {
        this.classpath = classpath;
    }

    public boolean isGenerate() {
        return generate;
    }

    public void setGenerate(boolean generate) {
        this.generate = generate;
    }

    public boolean isCompile() {
        return compile;
    }

    public void setCompile(boolean compile) {
        this.compile = compile;
    }

    public boolean isCompileDebug() {
        return compileDebug;
    }

    public void setCompileDebug(boolean compileDebug) {
        this.compileDebug = compileDebug;
    }

    public boolean isLoadclass() {
        return loadclass;
    }

    public void setLoadclass(boolean loadclass) {
        this.loadclass = loadclass;
    }

    public List getInterfaces() {
        return interfaces;
    }

    public void setInterfaces(List interfaces) {
        this.interfaces = interfaces;
    }

    public void parseOptions(String args[]) throws GenException, GenWarning {
        GenWarning genWarning = null;

        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-g")) {
                generate = true;
            } else if (args[i].equals("-c")) {
                compile = true;
            } else if (args[i].equals("-cd")) {
                compileDebug = true;
            } else if (args[i].equals("-l")) {
                loadclass = true;
            } else if (args[i].equals("-s")) {
                simpleIdl = true;
            } else if (args[i].equals("-gs")) {
                if ((i + 1) < args.length) {
                    genSrcDir = args[++i];
                } else {
                    throw new GenException("-gs requires an source output diretory.");
                }
            } else if (args[i].equals("-cp")) {
                if ((i + 1) < args.length) {
                    classpath = args[++i];
                } else {
                    throw new GenException("-cp requires a classpath directory.");
                }
            } else if (args[i].equals("-gc")) {
                if ((i + 1) < args.length) {
                    genClassDir = args[++i];
                } else {
                    throw new GenException("-gc requires an class output diretory.");
                }
            } else if (args[i].equals("-v")) {
                verbose = true;
            } else if (args[i].equals("-o")) {
                overwrite = true;
            } else if (args[i].startsWith("-")) {
                String msg = "Ignoring unrecognized options: '" + args[i] + "'";
                if (genWarning != null) {
                    // just a cheap way of chaining the warnings...
                    genWarning = new GenWarning(msg, genWarning);
                } else {
                    genWarning = new GenWarning(msg);
                }
            } else {
                interfaces.add(args[i]);
            }
        }
    }
}


text:
SecurID is a library for authenticating with an RSA SecurID ACE
Authentication Server.

RSA SecurID is a two-factor authentication scheme that uses a PIN
and a tokencode to authenticate a user.  The tokencode is generated
by a hardware or software token and changes at regular timed intervals.

## Requirements

Installing the SecurID gem requires installation of the proper ACE
authentication library for your system.  The library may be obtained
from RSA.

## Installation

    $ gem build securid.gemspec
    $ gem install securid-X.X.gem

## Usage

    require 'rubygems'
    require 'securid'

    session = RSA::SecurID::Session.new
    session.authenticate(username, passcode)
    session.authenticated?                     # true on success

The `authenticate` instance method accepts a username and a passcode and
returns true or false to indicate success or failure.

The passcode is simply the concatenation of the user's PIN and their
current tokencode.

### Test Mode

Since it's not always possible to have an RSA ACE server running (local
development for example), the gem supports a test mode that will bypass
any communication with the ACE server and simply return a predetermined
response.

    require 'rubygems'
    require 'securid'

    session = RSA::SecurID::Session.new(test_mode: true)
    session.authenticate(username, passcode)   # never talks to the server
    session.authenticated?                     # test authentication is always successful by default

### Errors

Any unexpected problems during the authentication process will raise an
`RSA::SecurID::SecurIDError`.


text:
class FontChivo < Cask
  # version '1.001'
  version 'latest'
  sha256 :no_check

  url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/chivo',
      :using      => :svn,
      :revision   => '50',
      :trust_cert => true
  homepage 'http://www.google.com/fonts/specimen/Chivo'

  font 'Chivo-Black.ttf'
  font 'Chivo-BlackItalic.ttf'
  font 'Chivo-Italic.ttf'
  font 'Chivo-Regular.ttf'
end


text:
package proctl

import (
	"encoding/binary"
	"fmt"
	"syscall"

	"github.com/derekparker/delve/dwarf/frame"
)

// ThreadContext represents a single thread of execution in the
// traced program.
type ThreadContext struct {
	Id      int
	Process *DebuggedProcess
	Status  *syscall.WaitStatus
}

type Registers interface {
	PC() uint64
	SP() uint64
	SetPC(int, uint64) error
}

// Obtains register values from the debugged process.
func (thread *ThreadContext) Registers() (Registers, error) {
	regs, err := registers(thread.Id)
	if err != nil {
		return nil, fmt.Errorf("could not get registers %s", err)
	}

	return regs, nil
}

// Returns the current PC for this thread id.
func (thread *ThreadContext) CurrentPC() (uint64, error) {
	regs, err := thread.Registers()
	if err != nil {
		return 0, err
	}

	return regs.PC(), nil
}

// PrintInfo prints out the thread status
// including: PC, tid, file, line, and function.
func (thread *ThreadContext) PrintInfo() error {
	pc, err := thread.CurrentPC()
	if err != nil {
		return err
	}
	f, l, fn := thread.Process.GoSymTable.PCToLine(pc)
	if fn != nil {
		fmt.Printf("Thread %d at %#v %s:%d %s\n", thread.Id, pc, f, l, fn.Name)
	} else {
		fmt.Printf("Thread %d at %#v\n", thread.Id, pc)
	}
	return nil
}

// Sets a breakpoint at addr, and stores it in the process wide
// break point table. Setting a break point must be thread specific due to
// ptrace actions needing the thread to be in a signal-delivery-stop.
//
// Depending on hardware support, Delve will choose to either
// set a hardware or software breakpoint. Essentially, if the
// hardware supports it, and there are free debug registers, Delve
// will set a hardware breakpoint. Otherwise we fall back to software
// breakpoints, which are a bit more work for us.
func (thread *ThreadContext) Break(addr uint64) (*BreakPoint, error) {
	return thread.Process.setBreakpoint(thread.Id, addr)
}

// Clears a breakpoint, and removes it from the process level break point table.
func (thread *ThreadContext) Clear(addr uint64) (*BreakPoint, error) {
	return thread.Process.clearBreakpoint(thread.Id, addr)
}

func (thread *ThreadContext) Continue() error {
	// Check whether we are stopped at a breakpoint, and
	// if so, single step over it before continuing.
	regs, err := thread.Registers()
	if err != nil {
		return fmt.Errorf("could not get registers %s", err)
	}

	if _, ok := thread.Process.BreakPoints[regs.PC()-1]; ok {
		err := thread.Step()
		if err != nil {
			return fmt.Errorf("could not step %s", err)
		}
	}

	return syscall.PtraceCont(thread.Id, 0)
}

// Single steps this thread a single instruction, ensuring that
// we correctly handle the likely case that we are at a breakpoint.
func (thread *ThreadContext) Step() (err error) {
	regs, err := thread.Registers()
	if err != nil {
		return err
	}

	bp, ok := thread.Process.BreakPoints[regs.PC()-1]
	if ok {
		// Clear the breakpoint so that we can continue execution.
		_, err = thread.Clear(bp.Addr)
		if err != nil {
			return err
		}

		// Reset program counter to our restored instruction.
		err = regs.SetPC(thread.Id, bp.Addr)
		if err != nil {
			return fmt.Errorf("could not set registers %s", err)
		}

		// Restore breakpoint now that we have passed it.
		defer func() {
			_, err = thread.Break(bp.Addr)
		}()
	}

	err = syscall.PtraceSingleStep(thread.Id)
	if err != nil {
		return fmt.Errorf("step failed: %s", err.Error())
	}

	_, _, err = wait(thread.Id, 0)
	if err != nil {
		return err
	}

	return nil
}

// Step to next source line. Next will step over functions,
// and will follow through to the return address of a function.
// Next is implemented on the thread context, however during the
// course of this function running, it's very likely that the
// goroutine our M is executing will switch to another M, therefore
// this function cannot assume all execution will happen on this thread
// in the traced process.
func (thread *ThreadContext) Next() (err error) {
	pc, err := thread.CurrentPC()
	if err != nil {
		return err
	}

	if bp, ok := thread.Process.BreakPoints[pc-1]; ok {
		pc = bp.Addr
	}

	fde, err := thread.Process.FrameEntries.FDEForPC(pc)
	if err != nil {
		return err
	}

	_, l, _ := thread.Process.GoSymTable.PCToLine(pc)
	ret := thread.ReturnAddressFromOffset(fde.ReturnAddressOffset(pc))
	for {
		if err = thread.Step(); err != nil {
			return err
		}

		if pc, err = thread.CurrentPC(); err != nil {
			return err
		}

		if !fde.Cover(pc) && pc != ret {
			if err := thread.continueToReturnAddress(pc, fde); err != nil {
				if _, ok := err.(InvalidAddressError); !ok {
					return err
				}
			}
			if pc, err = thread.CurrentPC(); err != nil {
				return err
			}
		}

		if _, nl, _ := thread.Process.GoSymTable.PCToLine(pc); nl != l {
			break
		}
	}

	return nil
}

func (thread *ThreadContext) continueToReturnAddress(pc uint64, fde *frame.FrameDescriptionEntry) error {
	for !fde.Cover(pc) {
		// Our offset here is be 0 because we
		// have stepped into the first instruction
		// of this function. Therefore the function
		// has not had a chance to modify its' stack
		// and change our offset.
		addr := thread.ReturnAddressFromOffset(0)
		bp, err := thread.Break(addr)
		if err != nil {
			if _, ok := err.(BreakPointExistsError); !ok {
				return err
			}
		}
		bp.temp = true
		// Ensure we cleanup after ourselves no matter what.
		defer thread.clearTempBreakpoint(bp.Addr)

		for {
			err = thread.Continue()
			if err != nil {
				return err
			}
			// We wait on -1 here because once we continue this
			// thread, it's very possible the scheduler could of
			// change the goroutine context on us, we there is
			// no guarantee that waiting on this tid will ever
			// return.
			wpid, _, err := trapWait(thread.Process, -1)
			if err != nil {
				return err
			}
			if wpid != thread.Id {
				thread = thread.Process.Threads[wpid]
			}
			pc, _ = thread.CurrentPC()
			if (pc-1) == bp.Addr || pc == bp.Addr {
				break
			}
		}
	}

	return nil
}

// Takes an offset from RSP and returns the address of the
// instruction the currect function is going to return to.
func (thread *ThreadContext) ReturnAddressFromOffset(offset int64) uint64 {
	regs, err := thread.Registers()
	if err != nil {
		panic("Could not obtain register values")
	}

	retaddr := int64(regs.SP()) + offset
	data := make([]byte, 8)
	readMemory(thread.Id, uintptr(retaddr), data)
	return binary.LittleEndian.Uint64(data)
}

func (thread *ThreadContext) clearTempBreakpoint(pc uint64) error {
	var software bool
	if _, ok := thread.Process.BreakPoints[pc]; ok {
		software = true
	}
	if _, err := thread.Clear(pc); err != nil {
		return err
	}
	if software {
		// Reset program counter to our restored instruction.
		regs, err := thread.Registers()
		if err != nil {
			return err
		}

		return regs.SetPC(thread.Id, pc)
	}

	return nil
}


text:
using System;
using System.Data;
using System.Collections.Generic;

namespace MonoDevelop.Database.Sql
{
	public class FromSelectClause : FromClause
	{
		protected SelectStatement source;

		public FromSelectClause (SelectStatement source)
		{
			Source = source;
		}

		public SelectStatement Source {
			get { return source; }
			set {
				if (value == null)
					throw new ArgumentNullException ("source");
				source = value;
			}
		}
	}
}


text:
package net.boreeas.frozenircd.connection;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
import net.boreeas.frozenircd.config.ConfigData;
import net.boreeas.frozenircd.config.ConfigKey;
import net.boreeas.frozenircd.connection.client.Client;

/**
 *
 * @author Boreeas
 */
public class IdentDaemon extends Thread {

    private Client client;
    private Socket socket;

    public IdentDaemon(Client client, Socket socket) {

        super("IdentHostname[" + client + "]");

        setDaemon(true);

        this.client = client;
        this.socket = socket;
    }

    @Override
    public void run() {

        client.sendNotice(ConfigData.getFirstConfigOption(ConfigKey.HOST), "AUTH", "*** Checking Ident");

        try {
            Socket identdSocket = new Socket(socket.getInetAddress(), 113);
            identdSocket.setSoTimeout(10000);

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(identdSocket.getOutputStream()));
            writer.write(String.format("%s, %s", socket.getPort(), socket.getLocalPort()));

            String id = parseIdentResponse(
                    new BufferedReader(
                    new InputStreamReader(
                    identdSocket.getInputStream())).readLine());

            if (id == null || id.length() == 0) {
                throw new IOException();    // No ident reponse
            }

            client.setIdentResponseReceived(true);
            client.setUsername(id);

        }
        catch (SocketTimeoutException ex) {
            client.sendNotice(ConfigData.getFirstConfigOption(ConfigKey.HOST), "AUTH", "*** Ident reponse timed out");
        }
        catch (IOException ex) {
            client.sendNotice(ConfigData.getFirstConfigOption(ConfigKey.HOST), "AUTH", "*** No Ident reponse");
        }
    }

    public String parseIdentResponse(String response) {

        String[] fields = response.split(" ?: ?");
        if (fields.length < 4) {
            return null;
        }

        if (!fields[1].equalsIgnoreCase("USERID")) {
            return null;
        }

        return response.trim();
    }
}


text:
package org.openmuc.framework.driver.csv.exceptions;

public class NoValueReceivedYetException extends CsvException {

    private static final long serialVersionUID = 8609753792624311525L;

    public NoValueReceivedYetException(String message) {
        super(message);
    }

    @Override
    public String getMessage() {
        return message;
    }
}


text:
package consulo.csharp.lang.psi.impl;

/**
 * @author VISTALL
 * @since 27.11.14
 */
public interface DotNetTypes2
{
	interface System
	{
		interface Runtime
		{
			interface CompilerServices
			{
				String InternalsVisibleToAttribute = "System.Runtime.CompilerServices.InternalsVisibleToAttribute";
				String AsyncStateMachineAttribute = "System.Runtime.CompilerServices.AsyncStateMachineAttribute";

			}

			interface InteropServices
			{
				String InAttribute = "System.Runtime.InteropServices.InAttribute";
				String OutAttribute = "System.Runtime.InteropServices.OutAttribute";
			}
		}

		interface Linq
		{
			String IGrouping$2 = "System.Linq.IGrouping`2";
			String Enumerable = "System.Linq.Enumerable";
		}

		interface Threading
		{
			interface Tasks
			{

				String Task = "System.Threading.Tasks.Task";
				String Task$1 = "System.Threading.Tasks.Task`1";
			}
		}

		interface Collections
		{
			interface Generic
			{
				String IEnumerable$1 = "System.Collections.Generic.IEnumerable`1";
				String IEnumerator$1 = "System.Collections.Generic.IEnumerator`1";
				String IList$1 = "System.Collections.Generic.IList`1";
			}

			String IEnumerable = "System.Collections.IEnumerable";
			String IEnumerator = "System.Collections.IEnumerator";
		}

		interface Diagnostics
		{
			String DebuggerDisplayAttribute = "System.Diagnostics.DebuggerDisplayAttribute";
		}

		String RuntimeArgumentHandle = "System.RuntimeArgumentHandle";
		String FlagsAttribute  = "System.FlagsAttribute";
		String FormattableString  = "System.FormattableString";
		String NullReferenceException  = "System.NullReferenceException";
	}
}


text:
threads(5, 5)
tag("MIQ: Web Server Worker")


text:
cask :v1 => 'dash' do
  version :latest
  sha256 :no_check

  url 'https://newyork.kapeli.com/downloads/v3/Dash.zip'
  appcast 'https://kapeli.com/Dash3.xml'
  name 'Dash'
  homepage 'https://kapeli.com/dash'
  license :commercial

  app 'Dash.app'

  postflight do
    suppress_move_to_applications
  end

  zap :delete => [
                  '~/Library/Application Support/Dash',
                  '~/Library/Preferences/com.kapeli.dash.plist',
                 ]
end


text:
tic ~/.yadr/iTerm2/xterm-256color.terminfo

# Specify the preferences directory
defaults write com.googlecode.iterm2.plist PrefsCustomFolder -string "~/.yadr/iTerm2"
# Tell iTerm2 to use the custom preferences in the directory
defaults write com.googlecode.iterm2.plist LoadPrefsFromCustomFolder -bool true

# Add shortcut to Dock
defaults write com.apple.dock persistent-apps -array-add "<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>/Applications/iTerm.app</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>"

# reset the preferences cache
killall cfprefsd


text:
<?php

/**
 * Class AutoloaderTest
 */
class HandlebarsTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        \Handlebars\Autoloader::register();
    }

    /**
     * Test handlebars autoloader
     *
     * @return void
     */
    public function testAutoLoad()
    {
        Handlebars\Autoloader::register(realpath(__DIR__ . '/../fixture/'));

        $this->assertTrue(class_exists('Handlebars\\Test'));
        $this->assertTrue(class_exists('\\Handlebars\\Test'));
        $this->assertTrue(class_exists('Handlebars\\Example\\Test'));
        $this->assertTrue(class_exists('\\Handlebars\\Example\\Test'));
        $this->assertFalse(class_exists('\\Another\\Example\\Test'));
    }

    /**
     * Test basic tags
     *
     * @param string $src    handlebars source
     * @param array  $data   data
     * @param string $result expected data
     *
     * @dataProvider simpleTagdataProvider
     *
     * @return void
     */
    public function testBasicTags($src, $data, $result)
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));
        $this->assertEquals($result, $engine->render($src, $data));
    }

    /**
     * Simple tag provider
     *
     * @return array
     */
    public function simpleTagdataProvider()
    {
        return array(
            array(
                '{{! This is comment}}',
                array(),
                ''
            ),
            array(
                '{{data}}',
                array('data' => 'result'),
                'result'
            ),
            array(
                '{{data.key}}',
                array('data' => array('key' => 'result')),
                'result'
            ),
            array(
                '{{data.length}}',
                array("data" => array(1, 2, 3, 4)),
                '4'
            ),
            array(
                '{{data.length}}',
                array("data" => (object)array(1, 2, 3, 4)),
                ''
            ),
            array(
                '{{data.length}}',
                array("data" => array("length" => "15 inches", "test", "test", "test")),
                "15 inches"
            ),
            array(
                '{{data.0}}',
                array("data" => array(1, 2, 3, 4)),
                '1'
            ),
            array(
                '{{data.property.3}}',
                array("data" => array("property" => array(1, 2, 3, 4))),
                '4'
            ),
            array(
                '{{data.unsafe}}',
                array('data' => array('unsafe' => 'Test')),
                '<strong>Test</strong>'
            ),
            array(
                '{{{data.safe}}}',
                array('data' => array('safe' => 'Test')),
                'Test'
            ),
            array(
                "\{{data}}", // is equal to \\{{data}}
                array('data' => 'foo'),
                '{{data}}',
            ),
            array(
                '\\\\{{data}}',
                array('data' => 'foo'),
                '\\\\foo'
            ),
            array(
                '\\\{{data}}', // is equal to \\\\{{data}} in php
                array('data' => 'foo'),
                '\\\\foo'
            ),
            array(
                '\{{{data}}}',
                array('data' => 'foo'),
                '{{{data}}}'
            ),
            array(
                '\pi',
                array(),
                '\pi'
            ),
            array(
                '\\\\\\\\qux',
                array(),
                '\\\\\\\\qux'
            ),
            array(
                "var jsVar = 'It\'s a phrase in apos';",
                array(),
                "var jsVar = 'It\'s a phrase in apos';"
            ),
            array(
                'var jsVar = "A \"quoted\" text";',
                array(),
                'var jsVar = "A \"quoted\" text";',
            ),
            array(
                '{{#if first}}The first{{else}}{{#if second}}The second{{/if}}{{/if}}',
                array('first' => false, 'second' => true),
                'The second'
            )
        );
    }

    /**
     * Test helpers (internal helpers)
     *
     * @param string $src    handlebars source
     * @param array  $data   data
     * @param string $result expected data
     *
     * @dataProvider internalHelpersdataProvider
     *
     * @return void
     */
    public function testSimpleHelpers($src, $data, $result)
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $helpers = new \Handlebars\Helpers();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader, 'helpers' => $helpers));

        $this->assertEquals($result, $engine->render($src, $data));
    }

    /**
     * Simple helpers provider
     *
     * @return array
     */
    public function internalHelpersdataProvider()
    {
        return array(
            array(
                '{{#if data}}Yes{{/if}}',
                array('data' => true),
                'Yes'
            ),
            # see the issue #76
            array(
                '{{#if data}}0{{/if}}',
                array('data' => true),
                '0'
            ),
            array(
                '{{#if data}}Yes{{/if}}',
                array('data' => false),
                ''
            ),
            array(
                '{{#with data}}{{key}}{{/with}}',
                array('data' => array('key' => 'result')),
                'result'
            ),
            array(
                '{{#each data}}{{this}}{{/each}}',
                array('data' => array(1, 2, 3, 4)),
                '1234'
            ),
            array(
                '{{#each data}}{{@key}}{{/each}}',
                array('data' => array('the_only_key' => 1)),
                'the_only_key'
            ),
            array(
                '{{#each data}}{{@key}}=>{{this}}{{/each}}',
                array('data' => array('key1' => 1, 'key2' => 2,)),
                'key1=>1key2=>2'
            ),
            array(
                '{{#each data}}{{@key}}=>{{this}}{{/each}}',
                array('data' => new \ArrayIterator(array('key1' => 1, 'key2' => 2))),
                'key1=>1key2=>2'
            ),
            array(
                '{{#each data}}{{@index}}=>{{this}},{{/each}}',
                array('data' => array('key1' => 1, 'key2' => 2,)),
                '0=>1,1=>2,'
            ),
            array(
                '{{#each data}}{{#if @first}}the first is {{this}}{{/if}}{{/each}}',
                array('data' => array('one', 'two', 'three')),
                'the first is one'
            ),
            array(
                '{{#each data}}{{#if @last}}the last is {{this}}{{/if}}{{/each}}',
                array('data' => array('one', 'two', 'three')),
                'the last is three'
            ),
            array(
                '{{#each data}}{{this}}{{else}}fail{{/each}}',
                array('data' => array(1, 2, 3, 4)),
                '1234'
            ),
            array(
                '{{#each data}}fail{{else}}ok{{/each}}',
                array('data' => false),
                'ok'
            ),
            array(
                '{{#unless data}}ok{{/unless}}',
                array('data' => true),
                ''
            ),
            array(
                '{{#unless data}}ok{{/unless}}',
                array('data' => false),
                'ok'
            ),
            array(
                '{{#unless data}}ok{{else}}fail{{/unless}}',
                array('data' => false),
                'ok'
            ),
            array(
                '{{#unless data}}fail{{else}}ok{{/unless}}',
                array('data' => true),
                'ok'
            ),
            array(
                '{{#bindAttr data}}',
                array(),
                'data'
            ),
            array(
                '{{#if 1}}ok{{else}}fail{{/if}}',
                array(),
                'ok'
            ),
            array(
                '{{#if 0}}ok{{else}}fail{{/if}}',
                array(),
                'fail'
            ),
            array(
                '  {{~#if 1}}OK   {{~else~}} NO {{~/if~}}  END',
                array(),
                'OKEND'
            ),
            array(
                'XX {{~#bindAttr data}} XX',
                array(),
                'XXdata XX'
            ),
            array(
                '{{#each data}}{{#if @last}}the last is
                {{~this}}{{/if}}{{/each}}',
                array('data' => array('one', 'two', 'three')),
                'the last isthree'
            ),
            array(
                '{{#with data}}

                {{~key~}}

                {{/with}}',
                array('data' => array('key' => 'result')),
                'result'
            ),
            array(
                '{{= (( )) =}}((#if 1))OK((else))NO((/if))',
                array(),
                'OK'
            ),
            array(
                '{{#each data~}}    {{this}}    {{~/each}}',
                array('data' => array(1, 2, 3, 4)),
                '1234'
            ),
            array(
                '{{#each data}}{{this}}    {{~/each}}',
                array('data' => array(1, 2, 3, 4)),
                '1234'
            ),
            array(
                '{{#each data~}}    {{this}}{{/each}}',
                array('data' => array(1, 2, 3, 4)),
                '1234'
            ),
            array( '{{#if first}}The first{{else}}{{#if second}}The second{{/if}}{{/if}}',
                array('first' => false, 'second' => true),
                'The second'
            )
        );
    }

    /**
     * Management helpers
     */
    public function testHelpersManagement()
    {
        $helpers = new \Handlebars\Helpers(array('test' => function () {
            }), false);
        $engine = new \Handlebars\Handlebars(array('helpers' => $helpers));
        $this->assertTrue(is_callable($engine->getHelper('test')));
        $this->assertTrue($engine->hasHelper('test'));
        $engine->removeHelper('test');
        $this->assertFalse($engine->hasHelper('test'));
    }

    /**
     * Custom helper test
     */
    public function testCustomHelper()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));
        $engine->addHelper('test', function () {
            return 'Test helper is called';
        });
        $this->assertEquals('Test helper is called', $engine->render('{{#test}}', array()));
        $this->assertEquals('Test helper is called', $engine->render('{{test}}', array()));

        $engine->addHelper('test2', function ($template, $context, $arg) {
            return 'Test helper is called with ' . $arg;
        });
        $this->assertEquals('Test helper is called with a b c', $engine->render('{{#test2 a b c}}', array()));
        $this->assertEquals('Test helper is called with a b c', $engine->render('{{test2 a b c}}', array()));

        $engine->addHelper('renderme', function () {
            return new \Handlebars\String("{{test}}");
        });
        $this->assertEquals('Test helper is called', $engine->render('{{#renderme}}', array()));

        $engine->addHelper('dontrenderme', function () {
            return "{{test}}";
        });
        $this->assertEquals('{{test}}', $engine->render('{{#dontrenderme}}', array()));

        $engine->addHelper('markupHelper', function () {
            return 'Test';
        });
        $this->assertEquals('Test', $engine->render('{{{markupHelper}}}', array()));
        $this->assertEquals('<strong>Test</strong>', $engine->render('{{markupHelper}}', array()));

        $engine->addHelper('safeStringTest', function () {
            return new \Handlebars\SafeString('Test');
        });
        $this->assertEquals('Test', $engine->render('{{safeStringTest}}', array()));

        $engine->addHelper('argsTest', function ($template, $context, $arg) {
            $parsedArgs = $template->parseArguments($arg);

            return implode(' ', $parsedArgs);
        });
        $this->assertEquals("a \"b\" c", $engine->render('{{{argsTest "a" "\"b\"" \'c\'}}}', array()));

        // This is just a fun thing to do :)
        $that = $this;
        $engine->addHelper('stopToken',
            function ($template, $context, $arg) use ($that) {
                /** @var $template \Handlebars\Template */
                $parsedArgs = $template->parseArguments($arg);
                $first = array_shift($parsedArgs);
                $last = array_shift($parsedArgs);
                if ($last == 'yes') {
                    $template->setStopToken($first);
                    $that->assertEquals($first, $template->getStopToken());
                    $buffer = $template->render($context);
                    $template->setStopToken(false);
                    $template->discard($context);
                } else {
                    $template->setStopToken($first);
                    $that->assertEquals($first, $template->getStopToken());
                    $template->discard($context);
                    $template->setStopToken(false);
                    $buffer = $template->render($context);
                }

                return $buffer;
            });

        $this->assertEquals("Used", $engine->render('{{# stopToken fun no}}Not used{{ fun }}Used{{/stopToken }}', array()));
        $this->assertEquals("Not used", $engine->render('{{# stopToken any yes}}Not used{{ any }}Used{{/stopToken }}', array()));

        $this->setExpectedException('InvalidArgumentException');
        $engine->getHelpers()->call('invalid', $engine->loadTemplate(''), new \Handlebars\Context(), '', '');
    }

    public function testInvalidHelperMustacheStyle()
    {
        $this->setExpectedException('RuntimeException');
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));
        $engine->render('{{#NOTVALID}}XXX{{/NOTVALID}}', array());
    }

    public function testInvalidHelper()
    {
        $this->setExpectedException('RuntimeException');
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));
        $engine->render('{{#NOTVALID argument}}XXX{{/NOTVALID}}', array());
    }

    /**
     * Test mustache style loop and if
     */
    public function testMustacheStyle()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));
        $this->assertEquals('yes', $engine->render('{{#x}}yes{{/x}}', array('x' => true)));
        $this->assertEquals('', $engine->render('{{#x}}yes{{/x}}', array('x' => false)));
        $this->assertEquals('yes', $engine->render('{{^x}}yes{{/x}}', array('x' => false)));
        $this->assertEquals('', $engine->render('{{^x}}yes{{/x}}', array('x' => true)));
        $this->assertEquals('1234', $engine->render('{{#x}}{{this}}{{/x}}', array('x' => array(1, 2, 3, 4))));
        $this->assertEquals('012', $engine->render('{{#x}}{{@index}}{{/x}}', array('x' => array('a', 'b', 'c'))));
        $this->assertEquals('abc', $engine->render('{{#x}}{{@key}}{{/x}}', array('x' => array('a' => 1, 'b' => 2, 'c' => 3))));
        $this->assertEquals('the_only_key', $engine->render('{{#x}}{{@key}}{{/x}}', array('x' => array('the_only_key' => 1))));
        $std = new stdClass();
        $std->value = 1;
        $this->assertEquals('1', $engine->render('{{#x}}{{value}}{{/x}}', array('x' => $std)));
        $this->assertEquals('1', $engine->render('{{{x}}}', array('x' => 1)));
    }

    /**
     * @expectedException \LogicException
     */
    public function testParserException()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));
        $engine->render('{{#test}}{{#test2}}{{/test}}{{/test2}}', array());
    }

    /**
     * Test add/get/has/clear functions on helper class
     */
    public function testHelpersClass()
    {
        $helpers = new \Handlebars\Helpers();
        $helpers->add('test', function () {
        });
        $this->assertTrue($helpers->has('test'));
        $this->assertTrue(isset($helpers->test));
        $this->assertFalse($helpers->isEmpty());
        $helpers->test2 = function () {
        };
        $this->assertTrue($helpers->has('test2'));
        $this->assertTrue(isset($helpers->test2));
        $this->assertFalse($helpers->isEmpty());
        unset($helpers->test2);
        $this->assertFalse($helpers->has('test2'));
        $this->assertFalse(isset($helpers->test2));
        $helpers->clear();
        $this->assertFalse($helpers->has('test'));
        $this->assertFalse(isset($helpers->test));
        $this->assertTrue($helpers->isEmpty());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testHelperWrongConstructor()
    {
        $helper = new \Handlebars\Helpers("helper");
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testHelperWrongCallable()
    {
        $helper = new \Handlebars\Helpers();
        $helper->add('test', 1);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testHelperWrongGet()
    {
        $helper = new \Handlebars\Helpers();
        $x = $helper->test;
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testHelperWrongUnset()
    {
        $helper = new \Handlebars\Helpers();
        unset($helper->test);
    }

    /**
     * test String class
     */
    public function testStringClass()
    {
        $string = new \Handlebars\String('test');
        $this->assertEquals('test', $string->getString());
        $string->setString('new');
        $this->assertEquals('new', $string->getString());
    }

    /**
     * @param $dir
     *
     * @return bool
     */
    private function delTree($dir)
    {
        $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            (is_dir("$dir/$file")) ? $this->delTree("$dir/$file") : unlink("$dir/$file");
        }

        return rmdir($dir);
    }

    /**
     * Its not a good test :) but ok
     */
    public function testCacheSystem()
    {
        $path = sys_get_temp_dir() . '/__cache__handlebars';

        @$this->delTree($path);

        $dummy = new \Handlebars\Cache\Disk($path);
        $engine = new \Handlebars\Handlebars(array('cache' => $dummy));
        $this->assertEquals(0, count(glob($path . '/*')));
        $engine->render('test', array());
        $this->assertEquals(1, count(glob($path . '/*')));
    }

    public function testArrayLoader()
    {
        $loader = new \Handlebars\Loader\ArrayLoader(array('test' => 'HELLO'));
        $loader->addTemplate('another', 'GOODBYE');
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));
        $this->assertEquals($engine->render('test', array()), 'HELLO');
        $this->assertEquals($engine->render('another', array()), 'GOODBYE');

        $this->setExpectedException('RuntimeException');
        $engine->render('invalid-template', array());
    }

    /**
     * Test file system loader
     */
    public function testFileSystemLoader()
    {
        $loader = new \Handlebars\Loader\FilesystemLoader(realpath(__DIR__ . '/../fixture/data'));
        $engine = new \Handlebars\Handlebars();
        $engine->setLoader($loader);
        $this->assertEquals('test', $engine->render('loader', array()));
    }

    /**
     * Test file system loader
     */
    public function testFileSystemLoaderMultipleFolder()
    {
        $paths = array(
            realpath(__DIR__ . '/../fixture/data'),
            realpath(__DIR__ . '/../fixture/another')
        );

        $options = array(
            'prefix' => '__',
            'extension' => 'hb'
        );
        $loader = new \Handlebars\Loader\FilesystemLoader($paths, $options);
        $engine = new \Handlebars\Handlebars();
        $engine->setLoader($loader);
        $this->assertEquals('test_extra', $engine->render('loader', array()));
        $this->assertEquals('another_extra', $engine->render('another', array()));
    }

    /**
     * Test file system loader
     *
     * @expectedException \InvalidArgumentException
     */
    public function testFileSystemLoaderNotFound()
    {
        $loader = new \Handlebars\Loader\FilesystemLoader(realpath(__DIR__ . '/../fixture/data'));
        $engine = new \Handlebars\Handlebars();
        $engine->setLoader($loader);
        $engine->render('invalid_file', array());
    }

    /**
     * Test file system loader
     *
     * @expectedException \RuntimeException
     */
    public function testFileSystemLoaderInvalidFolder()
    {
        new \Handlebars\Loader\FilesystemLoader(realpath(__DIR__ . '/../fixture/') . 'invalid/path');
    }

    /**
     * Test partial loader
     */
    public function testPartialLoader()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $partialLoader = new \Handlebars\Loader\FilesystemLoader(realpath(__DIR__ . '/../fixture/data'));
        $engine = new \Handlebars\Handlebars();
        $engine->setLoader($loader);
        $engine->setPartialsLoader($partialLoader);

        $this->assertEquals('test', $engine->render('{{>loader}}', array()));
    }

    public function testPartial()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $partialLoader = new \Handlebars\Loader\ArrayLoader(array('test' => '{{key}}', 'bar' => 'its foo'));
        $partialAliasses = array('foo' => 'bar');
        $engine = new \Handlebars\Handlebars(
            array(
                'loader' => $loader,
                'partials_loader' => $partialLoader,
                'partials_alias' => $partialAliasses
            )
        );

        $this->assertEquals('HELLO', $engine->render('{{>test parameter}}', array('parameter' => array('key' => 'HELLO'))));
        $this->assertEquals('its foo', $engine->render('{{>foo}}', array()));
        $engine->registerPartial('foo-again', 'bar');
        $this->assertEquals('its foo', $engine->render('{{>foo-again}}', array()));
        $engine->unRegisterPartial('foo-again');

        $this->setExpectedException('RuntimeException');
        $engine->render('{{>foo-again}}', array());
    }

    /**
     * test variable access
     */
    public function testVariableAccess()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = \Handlebars\Handlebars::factory();
        $engine->setLoader($loader);

        $var = new \StdClass();
        $var->x = 'var-x';
        $var->y = array(
            'z' => 'var-y-z'
        );
        $this->assertEquals('test', $engine->render('{{var}}', array('var' => 'test')));
        $this->assertEquals('var-x', $engine->render('{{var.x}}', array('var' => $var)));
        $this->assertEquals('var-y-z', $engine->render('{{var.y.z}}', array('var' => $var)));
        // Access parent context in with helper
        $this->assertEquals('var-x', $engine->render('{{#with var.y}}{{../var.x}}{{/with}}', array('var' => $var)));

        $obj = new DateTime();
        $time = $obj->getTimestamp();
        $this->assertEquals($time, $engine->render('{{time.getTimestamp}}', array('time' => $obj)));
    }

    public function testContext()
    {
        $test = new stdClass();
        $test->value = 'value';
        $test->array = array(
            'a' => '1',
            'b' => '2',
            '!"#%&\'()*+,./;<=>@[\\^`{|}~ ' => '3',
        );
        $context = new \Handlebars\Context($test);
        $this->assertEquals('value', $context->get('value'));
        $this->assertEquals('value', $context->get('value', true));
        $this->assertEquals('value', $context->get('[value]', true));
        $this->assertEquals('1', $context->get('array.a', true));
        $this->assertEquals('2', $context->get('array.b', true));
        $this->assertEquals('3', $context->get('array.[!"#%&\'()*+,./;<=>@[\\^`{|}~ ]', true));
        $new = array('value' => 'new value');
        $context->push($new);
        $this->assertEquals('new value', $context->get('value'));
        $this->assertEquals('new value', $context->get('value', true));
        $this->assertEquals('value', $context->get('../value'));
        $this->assertEquals('value', $context->get('../value', true));
        $this->assertEquals($new, $context->last());
        $this->assertEquals($new, $context->get('.'));
        $this->assertEquals($new, $context->get('this'));
        $this->assertEquals($new, $context->get('this.'));
        $this->assertEquals($test, $context->get('../.'));
        $context->pop();
        $this->assertEquals('value', $context->get('value'));
        $this->assertEquals('value', $context->get('value', true));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getInvalidData
     */
    public function testInvalidAccessContext($invalid)
    {
        $context = new \Handlebars\Context(array());
        $this->assertEmpty($context->get($invalid));
        $context->get($invalid, true);
    }

    public function getInvalidData()
    {
        return array(
            array('../../data'),
            array('data'),
            array(''),
            array('data.key.key'),
        );
    }

    /**
     * Test for proper handling of the length property
     **/
    public function testArrayLengthEmulation()
    {

        $data = array("numbers" => array(1, 2, 3, 4),
            "object" => (object)array("prop1" => "val1", "prop2" => "val2"),
            "object_with_length_property" => (object)array("length" => "15cm")
        );
        $context = new \Handlebars\Context($data);
        // make sure we are getting the array length when given an array
        $this->assertEquals($context->get("numbers.length"), 4);
        // make sure we are not getting a length when given an object
        $this->assertEmpty($context->get("object.length"));
        // make sure we can still get the length property when given an object
        $this->assertEquals($context->get("object_with_length_property.length"), "15cm");
    }

    public function argumentParserProvider()
    {
        return array(
            array('arg1 arg2', array("arg1", "arg2")),
            array('"arg1 arg2"', array("arg1 arg2")),
            array('arg1 arg2 "arg number 3"', array("arg1", "arg2", "arg number 3")),
            array('arg1 "arg\"2" "\"arg3\""', array("arg1", 'arg"2', '"arg3"')),
            array("'arg1 arg2'", array("arg1 arg2")),
            array("arg1 arg2 'arg number 3'", array("arg1", "arg2", "arg number 3")),
            array('arg1 "arg\"2" "\\\'arg3\\\'"', array("arg1", 'arg"2', "'arg3'")),
            array('arg1 arg2.[value\'s "segment"].val', array("arg1", 'arg2.[value\'s "segment"].val')),
            array('"arg1.[value 1]" arg2', array("arg1.[value 1]", 'arg2')),
        );
    }

    /**
     * Test Argument Parser
     *
     * @param string $arg_string argument text
     * @param        $expected_array
     *
     * @dataProvider argumentParserProvider
     *
     * @return void
     */
    public function testArgumentParser($arg_string, $expected_array)
    {
        $engine = new \Handlebars\Handlebars();
        $template = new \Handlebars\Template($engine, null, null);
        // get the string version of the arguments array
        $args = $template->parseArguments($arg_string);
        $args = array_map(function ($a) {
            return (string)$a;
        }, $args);
        $this->assertEquals($args, $expected_array);
    }

    public function namedArgumentParserProvider()
    {
        return array(
            array('arg1="value" arg2="value 2"', array('arg1' => 'value', 'arg2' => 'value 2')),
            array('arg1=var1', array('arg1' => 'var1')),
            array('[arg "1"]="arg number 1"', array('arg "1"' => "arg number 1")),
            array('arg1 =   "value"', array('arg1' => "value")),
        );
    }

    /**
     * Test Named Argument Parser
     *
     * @param string $arg_string argument text
     * @param        $expected_array
     *
     * @dataProvider namedArgumentParserProvider
     *
     * @return void
     */
    public function testNamedArgumentsParser($arg_string, $expected_array)
    {
        $engine = new \Handlebars\Handlebars();
        $template = new \Handlebars\Template($engine, null, null);
        // get the string version of the arguments array
        $args = $template->parseNamedArguments($arg_string);
        $args = array_map(function ($a) {
            return (string)$a;
        }, $args);
        $this->assertEquals($args, $expected_array);
    }

    /**
     * Test Combined Arguments Parser
     *
     * @param string $arg_string argument text
     * @param        $positional_args
     * @param        $named_args
     *
     * @dataProvider combinedArgumentsParserProvider
     *
     * @return void
     */
    public function testCombinedArgumentsParser($arg_string, $positional_args, $named_args)
    {
        $args = new \Handlebars\Arguments($arg_string);

        // Get the string version of the arguments array
        $stringify = function ($a) {
            return (string)$a;
        };

        if ($positional_args !== false) {
            $this->assertEquals(
                array_map($stringify, $args->getPositionalArguments()),
                $positional_args
            );
        }
        if ($named_args !== false) {
            $this->assertEquals(
                array_map($stringify, $args->getNamedArguments()),
                $named_args
            );
        }
    }

    public function combinedArgumentsParserProvider()
    {
        $result = array();

        // Use data provider for positional arguments parser
        foreach ($this->argumentParserProvider() as $dataSet) {
            $result[] = array(
                $dataSet[0],
                $dataSet[1],
                false,
            );
        }

        // Use data provider for named arguments parser
        foreach ($this->namedArgumentParserProvider() as $dataSet) {
            $result[] = array(
                $dataSet[0],
                false,
                $dataSet[1],
            );
        }

        // Add test cases with combined arguments
        return array_merge(
            $result,
            array(
                array(
                    'arg1 arg2 arg3=value1 arg4="value2"',
                    array('arg1', 'arg2'),
                    array('arg3' => 'value1', 'arg4' => 'value2')
                ),
                array(
                    '@first arg=@last',
                    array('@first'),
                    array('arg' => '@last')
                ),
                array(
                    '[seg arg1] [seg arg2] = [seg value "1"]',
                    array('[seg arg1]'),
                    array('seg arg2' => '[seg value "1"]')
                )
            )
        );
    }

    public function stringLiteralInCustomHelperProvider()
    {
        return array(
            array('{{#test2 arg1 "Argument 2"}}', array("arg1" => "Argument 1"), "Argument 1:Argument 2"),
            array('{{#test2 "Argument 1" "Argument 2"}}', array("arg1" => "Argument 1"), "Argument 1:Argument 2"),
            array('{{#test2 "Argument 1" arg2}}', array("arg2" => "Argument 2"), "Argument 1:Argument 2")
        );
    }

    /**
     * Test String literals in the context of a helper
     *
     * @param string $template template text
     * @param array  $data     context data
     * @param string $results  The Expected Results
     *
     * @dataProvider stringLiteralInCustomHelperProvider
     *
     * @return void
     */
    public function testStringLiteralInCustomHelper($template, $data, $results)
    {
        $engine = new \Handlebars\Handlebars();
        $engine->addHelper('test2', function ($template, $context, $args) {
            $args = $template->parseArguments($args);

            $args = array_map(function ($a) use ($context) {
                return $context->get($a);
            }, $args);

            return implode(':', $args);
        });
        $res = $engine->render($template, $data);
        $this->assertEquals($res, $results);
    }

    public function testString()
    {
        $string = new \Handlebars\String("Hello World");
        $this->assertEquals((string)$string, "Hello World");
    }

    public function testInvalidNames()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(
            array(
                'loader' => $loader,
            )
        );
        $all = \Handlebars\Context::NOT_VALID_NAME_CHARS;

        for ($i = 0; $i < strlen($all); $i++) {
            // Dot in string is valid, its an exception here
            if ($all{$i} === '.') {
                continue;
            }
            try {
                $name = 'var' . $all{$i} . 'var';
                $engine->render('{{' . $name . '}}', array($name => 'VALUE'));
                throw new Exception("Accept the $name :/");
            } catch (Exception $e) {
                $this->assertInstanceOf("InvalidArgumentException", $e);
            }
        }
    }

    /**
     * Helper subexpressions test
     */
    public function testHelperSubexpressions()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));
        $engine->addHelper('test', function ($template, $context, $arg) {
            return $arg . 'Test.';
        });

        // assert that nested syntax is accepted and sub-helper is run
        $this->assertEquals('Test.Test.', $engine->render('{{test (test)}}', array()));

        $engine->addHelper('add', function ($template, $context, $arg) {
            $values = explode(" ", $arg);

            return $values[0] + $values[1];
        });

        // assert that subexpression result is inserted correctly as argument to top level helper
        $this->assertEquals('42', $engine->render('{{add 21 (add 10 (add 5 6))}}', array()));

        // assert that bracketed expressions within string literals are treated correctly
        $this->assertEquals("'(test)'Test.", $engine->render("{{test '(test)'}}", array()));
        $this->assertEquals("')'Test.Test.", $engine->render("{{test (test ')')}}", array()));

        $engine->addHelper('concat', function(\Handlebars\Template $template,\Handlebars\Context $context, $args) {
            $result = '';

            foreach($template->parseArguments($args) as $arg) {
                if (($trnaslated = $context->get($arg)) !== null ) {
                    $result .= $trnaslated;
                } else {
                    $result .= $arg;
                }
            }

            return $result;
        });

        $this->assertEquals('ACB', $engine->render('{{concat a (concat c b)}}', array('a' => 'A', 'b' => 'B', 'c' => 'C')));
        $this->assertEquals('ACB', $engine->render('{{concat (concat a c) b}}', array('a' => 'A', 'b' => 'B', 'c' => 'C')));
        $this->assertEquals('A-B', $engine->render('{{concat (concat a "-") b}}', array('a' => 'A', 'b' => 'B')));
        $this->assertEquals('!B', $engine->render('{{concat (concat a "-") b}}', array('a' => 'A', 'b' => 'B', 'A-' => '!')));
    }

    /**
     * Test if and unless adding an extra layer when accessing parent
     */
    public function testIfUnlessExtraLayer()
    {
        $loader = new \Handlebars\Loader\StringLoader();
        $engine = new \Handlebars\Handlebars(array('loader' => $loader));

        $this->assertEquals('good', $engine->render('{{#with b}}{{#if this}}{{../../a}}{{/if}}{{/with}}', array('a' => 'good', 'b' => 'stump')));
        $this->assertEquals('good', $engine->render('{{#with b}}{{#unless false}}{{../../a}}{{/unless}}{{/with}}', array('a' => 'good', 'b' => 'stump')));
    }

    /**
     * Test of Arguments to string conversion.
     */
    public function testArgumentsString()
    {
        $argsString = 'foo bar [foo bar] baz="value"';
        $args = new \Handlebars\Arguments($argsString);
        $this->assertEquals($argsString, (string)$args);
    }
}


text:
import { Component, Input, OnInit, OnDestroy, OnChanges,
    ComponentFactoryResolver, ViewContainerRef, ViewChild, ViewEncapsulation} from '@angular/core';

/**
 * Component to dynamicly load other component
 */
@Component({
    selector: 'app-component-loader',
    encapsulation: ViewEncapsulation.None,
    template: '<ng-container #destination ></ng-container>'
})
export class ComponentLoaderComponent implements OnInit, OnDestroy, OnChanges {

    /**
     * class of the component to load
     */
    @Input() class_component: any = null;

    /**
     * data to pass to component
     */
    @Input() data: any = null;

    /**
     * component reference in dom
     */
    @ViewChild('destination', { read: ViewContainerRef, static: false }) viewContainerRef: ViewContainerRef;
    /**
     * component reference
     */
    private componentRef: any = null;

    /**
     * Component initialisation
     */
    constructor(
        private _factoryResolver: ComponentFactoryResolver
    ) { }

    /**
     * Lifecycle hook OnInit
     */
    ngOnInit() {
        // Build the child component
        const factory = this._factoryResolver.resolveComponentFactory(this.class_component);
        this.componentRef = this.viewContainerRef.createComponent(factory);

        // then give some data
        this.setComponentData(this.data);
    }

    /**
     * Lifecycle hook OnChanges, on modification of data send it to the child
     */
    ngOnChanges(changes) {
        this.setComponentData(changes);
    }

    /**
     * Send data to the inner component
     */
    private setComponentData(changes) {
        if (this.componentRef) {
        // send data to component
        Object.assign(this.componentRef.instance, changes);
        // trigger component ngOnChange
        this.componentRef.instance.ngOnChanges( changes );
        }
    }

    /**
     * Lifecycle hook OnDestroy
     */
    ngOnDestroy() {
        if (this.componentRef) {
        this.componentRef.destroy();
        }
    }
}


text:
require "enerscore/version"
require "enerscore/api"
require "enerscore/cache"
require "enerscore/result"
require "enerscore/response_parser"

module Enerscore
  # Your code goes here...
end


text:
using System.IO;
using System.Drawing;

using Aspose.Cells;

namespace Aspose.Cells.Examples.CSharp.Articles.CopyShapesBetweenWorksheets
{
    public class CopyingPicture
    {
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Create a workbook object
            // Open the template file
            Workbook workbook = new Workbook(dataDir+ "aspose-sample.xlsx");

            // Get the Picture from the "Picture" worksheet.
            Aspose.Cells.Drawing.Picture source = workbook.Worksheets["Sheet1"].Pictures[0];

            // Save Picture to Memory Stream
            MemoryStream ms = new MemoryStream(source.Data);

            // Copy the picture to the Result Worksheet
            workbook.Worksheets["Sheet2"].Pictures.Add(source.UpperLeftRow, source.UpperLeftColumn, ms, source.WidthScale, source.HeightScale);

            // Save the Worksheet
            workbook.Save(dataDir+ "Shapes.out.xlsx");
            // ExEnd:1

        }
    }
}


text:
package org.batfish.representation.cisco;

import java.io.Serializable;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.datamodel.acl.AclLineMatchExpr;

@ParametersAreNonnullByDefault
public interface ServiceObjectGroupLine extends Serializable {
  @Nonnull
  AclLineMatchExpr toAclLineMatchExpr(
      Map<String, ServiceObject> serviceObjects,
      Map<String, ServiceObjectGroup> serviceObjectGroups);
}


text:
module AccessorExtender
  # Extends the module object with class/module and instance accessors for
  # class/module attributes, just like the native attr* accessors for instance
  # attributes.
  class ::Module

    # Defines a class attribute and creates a class and instance reader methods.
    # The underlying the class variable is set to +nil+, if it is not previously
    # defined.
    def mattr_reader(*syms)
      syms.each do |sym|
        raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
        class_eval(<<-EOS, __FILE__, __LINE__ + 1)
          @@#{sym} = nil unless defined? @@#{sym}
          def self.#{sym}
            @@#{sym}
          end
        EOS

        class_variable_set("@@#{sym}", yield) if block_given?
      end
    end
    alias :cattr_reader :mattr_reader

    # Defines a class attribute and creates a class and instance writer methods to
    # allow assignment to the attribute.
    def mattr_writer(*syms)
      syms.each do |sym|
        raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
        class_eval(<<-EOS, __FILE__, __LINE__ + 1)
          @@#{sym} = nil unless defined? @@#{sym}
          def self.#{sym}=(obj)
            @@#{sym} = obj
          end
        EOS

        send("#{sym}=", yield) if block_given?
      end
    end
    alias :cattr_writer :mattr_writer

    # Defines both class and instance accessors for class attributes.
    def mattr_accessor(*syms, &blk)
      mattr_reader(*syms, &blk)
      mattr_writer(*syms, &blk)
    end
    alias :cattr_accessor :mattr_accessor

  end
end


text:
package org.artificer.common.query.xpath.ast;

import org.artificer.common.query.xpath.visitors.XPathVisitor;

/**
 * An X-Path expression.
 *
 * <pre>
 *   Expr ::= AndExpr
 * </pre>
 *
 * @author eric.wittmann@redhat.com
 */
public class Expr extends AbstractXPathNode {

	private AndExpr andExpr;

	/**
	 * Default constructor.
	 */
	public Expr() {
	}

	/**
	 * @return the andExpr
	 */
	public AndExpr getAndExpr() {
		return andExpr;
	}

	/**
	 * @param andExpr the andExpr to set
	 */
	public void setAndExpr(AndExpr andExpr) {
		this.andExpr = andExpr;
	}

	/**
	 * @see AbstractXPathNode#accept(org.artificer.common.query.xpath.visitors.XPathVisitor)
	 */
	@Override
	public void accept(XPathVisitor visitor) {
		visitor.visit(this);
	}

}


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.7.6.1">
  <compounddef id="structboost_1_1geometry_1_1traits_1_1closure" kind="struct" prot="public">
    <compoundname>boost::geometry::traits::closure</compoundname>
    <includes local="no">closure.hpp</includes>
    <templateparamlist>
      <param>
        <type>typename G</type>
      </param>
    </templateparamlist>
      <sectiondef kind="public-static-attrib">
      <memberdef kind="variable" id="structboost_1_1geometry_1_1traits_1_1closure_1a31b7458c9557c07ac35bedd7ab65a300" prot="public" static="yes" mutable="no">
        <type>const <ref refid="group__enum_1ga7d33eca9a5389952bdf719972eb802b6" kindref="member">closure_selector</ref></type>
        <definition>const closure_selector boost::geometry::traits::closure< G >::value</definition>
        <argsstring></argsstring>
        <name>value</name>
        <initializer> <ref refid="group__enum_1gga7d33eca9a5389952bdf719972eb802b6a17768d8af3fcc199a847d70965cbf9c5" kindref="member">closed</ref></initializer>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/travis/build/boostorg/boost/boost/geometry/core/closure.hpp" line="77" bodyfile="/home/travis/build/boostorg/boost/boost/geometry/core/closure.hpp" bodystart="77" bodyend="-1"/>
      </memberdef>
      </sectiondef>
    <briefdescription>
<para>Traits class indicating if points within a ring or (multi)polygon are closed (last point == first point), open or not known. </para>    </briefdescription>
    <detaileddescription>
<para><simplesect kind="par"><title>Geometries:</title><para><itemizedlist>
<listitem><para>ring </para></listitem></itemizedlist>
</para></simplesect>
<parameterlist kind="templateparam"><parameteritem>
<parameternamelist>
<parametername>G</parametername>
</parameternamelist>
<parameterdescription>
<para>geometry </para></parameterdescription>
</parameteritem>
</parameterlist>
</para>    </detaileddescription>
    <location file="/home/travis/build/boostorg/boost/boost/geometry/core/closure.hpp" line="76" bodyfile="/home/travis/build/boostorg/boost/boost/geometry/core/closure.hpp" bodystart="75" bodyend="78"/>
    <listofallmembers>
      <member refid="structboost_1_1geometry_1_1traits_1_1closure_1a31b7458c9557c07ac35bedd7ab65a300" prot="public" virt="non-virtual"><scope>boost::geometry::traits::closure</scope><name>value</name></member>
    </listofallmembers>
  </compounddef>
</doxygen>