text:
<?php

abstract class Auth {

	// Auth instances
	protected static $_instance;

	/**
	 * Singleton pattern
	 *
	 * @return Auth
	 */
	public static function instance()
	{
		if ( ! isset(Auth::$_instance))
		{
			// Load the configuration for this type
			$config = F::config('auth');

			if ( ! $type = $config['driver'])
			{
				$type = 'file';
			}

			// Set the session class name
			$class = 'Auth_'.ucfirst($type);

			//载入驱动文件
			$file = F::find_file('driver', 'auth'.DIRECTORY_SEPARATOR.$type);
			include_once $file;

			// Create a new session instance
			Auth::$_instance = new $class($config);
		}

		return Auth::$_instance;
	}

	protected $_session;

	protected $_config;

	/**
	 * Loads Session and configuration options.
	 *
	 * @param   array  $config  Config Options
	 * @return  void
	 */
	public function __construct($config = array())
	{
		// Save the config in the object
		$this->_config = $config;

		$this->_session = Session::instance($this->_config['session_type']);
	}

	abstract protected function _login($username, $password, $remember);

	abstract public function password($username);

	abstract public function check_password($password);

	/**
	 * Gets the currently logged in user from the session.
	 * Returns NULL if no user is currently logged in.
	 *
	 * @param   mixed  $default  Default value to return if the user is currently not logged in.
	 * @return  mixed
	 */
	public function get_user($default = NULL)
	{
		return $this->_session->get($this->_config['session_key'], $default);
	}

	/**
	 * Attempt to log in a user by using an ORM object and plain-text password.
	 *
	 * @param   string   $username  Username to log in
	 * @param   string   $password  Password to check against
	 * @param   boolean  $remember  Enable autologin
	 * @return  boolean
	 */
	public function login($username, $password, $remember = FALSE)
	{
		if (empty($password))
			return FALSE;

		return $this->_login($username, $password, $remember);
	}

	/**
	 * Log out a user by removing the related session variables.
	 *
	 * @param   boolean  $destroy     Completely destroy the session
	 * @param   boolean  $logout_all  Remove all tokens for user
	 * @return  boolean
	 */
	public function logout($destroy = FALSE, $logout_all = FALSE)
	{
		if ($destroy === TRUE)
		{
			// Destroy the session completely
			$this->_session->destroy();
		}
		else
		{
			// Remove the user from the session
			$this->_session->delete($this->_config['session_key']);

			// Regenerate session_id
			$this->_session->regenerate();
		}

		// Double check
		return ! $this->logged_in();
	}

	/**
	 * Check if there is an active session. Optionally allows checking for a
	 * specific role.
	 *
	 * @param   string  $role  role name
	 * @return  mixed
	 */
	public function logged_in($role = NULL)
	{
		return ($this->get_user() !== NULL);
	}

	/**
	 * Creates a hashed hmac password from a plaintext password. This
	 * method is deprecated, [Auth::hash] should be used instead.
	 *
	 * @deprecated
	 * @param  string  $password Plaintext password
	 */
	public function hash_password($password)
	{
		return $this->hash($password);
	}

	/**
	 * Perform a hmac hash, using the configured method.
	 *
	 * @param   string  $str  string to hash
	 * @return  string
	 */
	public function hash($str)
	{
		if ( ! $this->_config['hash_key'])
			throw new Exception('A valid hash key must be set in your auth config.', E_ERROR);

		return hash_hmac($this->_config['hash_method'], $str, $this->_config['hash_key']);
	}

	protected function complete_login($user)
	{
		// Regenerate session_id
		$this->_session->regenerate();

		// Store username in session
		$this->_session->set($this->_config['session_key'], $user);

		return TRUE;
	}

} // End Auth


text:
package abstractfactory;

public class WhiteCat implements ICat {
    @Override
    public void eat() {
        System.out.println("whiteCat is eating");
    }
}

redpajama_set_name: RedPajamaGithub


text:
{-# Language PatternGuards #-}
module Blub
   ( blub
   , foo
   , bar
   ) where
import Control.Monad
import Ugah.Foo ( a
                , b
                )
import Control.Applicative
import Ugah.Blub
f :: Int -> Int
f = (+ 3)

g :: Int -> Int
g =
   where


text:
using System.IO;
using System.Linq;
using SharpCompress.Archive;
using SharpCompress.Archive.Tar;
using SharpCompress.Common;
using SharpCompress.Writer;
using Xunit;

namespace SharpCompress.Test
{
    public class TarArchiveTests : ArchiveTests
    {
        public TarArchiveTests()
        {
            UseExtensionInsteadOfNameToVerify = true;
        }

        [Fact]
        public void TarArchiveStreamRead()
        {
            ArchiveStreamRead("Tar.tar");
        }

        [Fact]
        public void TarArchivePathRead()
        {
            ArchiveFileRead("Tar.tar");
        }

        [Fact]
        public void Tar_NonUstarArchiveWithLongNameDoesNotSkipEntriesAfterTheLongOne()
        {
            string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "very long filename.tar");
            using (var archive = TarArchive.Open(unmodified))
            {
                Assert.Equal(5, archive.Entries.Count);
                Assert.True(archive.Entries.Any(entry => entry.Key == "very long filename/"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "very long filename/very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename very long filename.jpg"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "z_file 1.txt"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "z_file 2.txt"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "z_file 3.txt"));
            }
        }

        [Fact]
        public void Tar_VeryLongFilepathReadback()
        {
            string archive = "Tar_VeryLongFilepathReadback.tar";

            ResetScratch();

            // create a very long filename
            string longFilename = "";
            for (int i = 0; i < 600; i = longFilename.Length)
                longFilename += i.ToString("D10") + "-";
            longFilename += ".txt";

            // Step 1: create a tar file containing a file with a long name
            using (Stream stream = File.OpenWrite(Path.Combine(SCRATCH2_FILES_PATH, archive)))
            using (var writer = WriterFactory.Open(stream, ArchiveType.Tar, CompressionType.None))
            using (Stream inputStream = new MemoryStream())
            {
                StreamWriter sw = new StreamWriter(inputStream);
                sw.Write("dummy filecontent");
                sw.Flush();

                inputStream.Position = 0;
                writer.Write(longFilename, inputStream, null);
            }

            // Step 2: check if the written tar file can be read correctly
            string unmodified = Path.Combine(SCRATCH2_FILES_PATH, archive);
            using (var archive2 = TarArchive.Open(unmodified))
            {
                Assert.Equal(1, archive2.Entries.Count);
                Assert.True(archive2.Entries.Any(entry => entry.Key == longFilename));

                foreach (var entry in archive2.Entries)
                    Assert.Equal("dummy filecontent", new StreamReader(entry.OpenEntryStream()).ReadLine());
            }
        }

        [Fact]
        public void Tar_UstarArchivePathReadLongName()
        {
            string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "ustar with long names.tar");
            using(var archive = TarArchive.Open(unmodified))
            {
                Assert.Equal(6, archive.Entries.Count);
                Assert.True(archive.Entries.Any(entry => entry.Key == "Directory/"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "Directory/Some file with veeeeeeeeeery loooooooooong name"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "Directory/Directory with veeeeeeeeeery loooooooooong name/"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "Directory/Directory with veeeeeeeeeery loooooooooong name/Some file with veeeeeeeeeery loooooooooong name"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "Directory/Directory with veeeeeeeeeery loooooooooong name/Directory with veeeeeeeeeery loooooooooong name/"));
                Assert.True(archive.Entries.Any(entry => entry.Key == "Directory/Directory with veeeeeeeeeery loooooooooong name/Directory with veeeeeeeeeery loooooooooong name/Some file with veeeeeeeeeery loooooooooong name"));
            }
        }

        [Fact]
        public void Tar_Create_New()
        {
            string scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.tar");
            string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar");

            base.ResetScratch();
            using (var archive = TarArchive.Create())
            {
                archive.AddAllFromDirectory(ORIGINAL_FILES_PATH);
                archive.SaveTo(scratchPath, CompressionType.None);
            }
            CompareArchivesByPath(unmodified, scratchPath);
        }
        [Fact]
        public void Tar_Random_Write_Add()
        {
            string jpg = Path.Combine(ORIGINAL_FILES_PATH, "jpg\\test.jpg");
            string scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.mod.tar");
            string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.mod.tar");
            string modified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar");

            base.ResetScratch();
            using (var archive = TarArchive.Open(unmodified))
            {
                archive.AddEntry("jpg\\test.jpg", jpg);
                archive.SaveTo(scratchPath, CompressionType.None);
            }
            CompareArchivesByPath(modified, scratchPath);
        }

        [Fact]
        public void Tar_Random_Write_Remove()
        {
            string scratchPath = Path.Combine(SCRATCH_FILES_PATH, "Tar.mod.tar");
            string modified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.mod.tar");
            string unmodified = Path.Combine(TEST_ARCHIVES_PATH, "Tar.noEmptyDirs.tar");

            base.ResetScratch();
            using (var archive = TarArchive.Open(unmodified))
            {
                var entry = archive.Entries.Where(x => x.Key.EndsWith("jpg")).Single();
                archive.RemoveEntry(entry);
                archive.SaveTo(scratchPath, CompressionType.None);
            }
            CompareArchivesByPath(modified, scratchPath);
        }

        [Fact]
        public void Tar_Containing_Rar_Archive()
        {
            string archiveFullPath = Path.Combine(TEST_ARCHIVES_PATH, "Tar.ContainsRar.tar");
            using (Stream stream = File.OpenRead(archiveFullPath))
            using (IArchive archive = ArchiveFactory.Open(stream))
            {
                Assert.True(archive.Type == ArchiveType.Tar);
            }
        }
    }
}


text:
<bill session="110" type="hr" number="1491" updated="2009-01-09T11:01:06-05:00">
	<status><vote date="1222350720" datetime="2008-09-25T10:52:00-04:00" where="h" result="pass" how="by voice vote" roll=""/></status>

	<introduced date="1222228800" datetime="2008-09-24"/>
	<titles>
		<title type="official" as="introduced">Providing for consideration of motions to suspend the rules, and for other purposes.</title>
	</titles>
	<sponsor id="400065"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1222285800" datetime="2008-09-24T16:50:00-04:00"><text>The House Committee on Rules reported an original measure, H. Rept. 110-880, by Mr. Cardoza.</text></action>
		<action date="1222285800" datetime="2008-09-24T16:50:00-04:00"><text>Providing for consideration of motions to suspend the rules, and for other purposes</text></action>
		<calendar date="1222285800" datetime="2008-09-24T16:50:00-04:00" ><text>Placed on the House Calendar, Calendar No. 274.</text></calendar>
		<action date="1222349220" datetime="2008-09-25T10:27:00-04:00"><text>Considered as privileged matter.</text><reference label="consideration" ref="CR H9874-9877"/></action>
		<action date="1222349880" datetime="2008-09-25T10:38:00-04:00"><text>DEBATE - The House proceeded with one hour of debate on H. Res. 1491.</text></action>
		<action date="1222350720" datetime="2008-09-25T10:52:00-04:00"><text>The previous question was ordered without objection.</text><reference label="consideration" ref="CR H9877"/></action>
		<vote date="1222350720" how="by voice vote" datetime="2008-09-25T10:52:00-04:00" where="h" type="vote" result="pass" ><text>On agreeing to the resolution Agreed to by voice vote.</text><reference label="text" ref="CR H9874-9875"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	9/24/2008--Reported to House without amendment. (This measure has not been amended since it was introduced. The summary of that version is repeated here.) Makes it in order at any time on September 25, 2008, the Speaker of the House of Representatives to entertain motions that the House suspend the rules on specified measures.<br/>
	</summary>
</bill>


text:
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.javascript.ast;

import org.mozilla.javascript.Token;

/**
 * With statement.  Node type is {@link Token#WITH}.

 *
 *
WithStatement :
 *      with ( Expression ) Statement ;

 */
public class WithStatement extends AstNode {

    private AstNode expression;
    private AstNode statement;
    private int lp = -1;
    private int rp = -1;

    {
        type = Token.WITH;
    }

    public WithStatement() {
    }

    public WithStatement(int pos) {
        super(pos);
    }

    public WithStatement(int pos, int len) {
        super(pos, len);
    }

    /**
     * Returns object expression
     */
    public AstNode getExpression() {
        return expression;
    }

    /**
     * Sets object expression (and its parent link)
     * @throws IllegalArgumentException} if expression is {@code null}
     */
    public void setExpression(AstNode expression) {
        assertNotNull(expression);
        this.expression = expression;
        expression.setParent(this);
    }

    /**
     * Returns the statement or block
     */
    public AstNode getStatement() {
        return statement;
    }

    /**
     * Sets the statement (and sets its parent link)
     * @throws IllegalArgumentException} if statement is {@code null}
     */
    public void setStatement(AstNode statement) {
        assertNotNull(statement);
        this.statement = statement;
        statement.setParent(this);
    }

    /**
     * Returns left paren offset
     */
    public int getLp() {
      return lp;
    }

    /**
     * Sets left paren offset
     */
    public void setLp(int lp) {
      this.lp = lp;
    }

    /**
     * Returns right paren offset
     */
    public int getRp() {
      return rp;
    }

    /**
     * Sets right paren offset
     */
    public void setRp(int rp) {
      this.rp = rp;
    }

    /**
     * Sets both paren positions
     */
    public void setParens(int lp, int rp) {
        this.lp = lp;
        this.rp = rp;
    }

    @Override
    public String toSource(int depth) {
        StringBuilder sb = new StringBuilder();
        sb.append(makeIndent(depth));
        sb.append("with (");
        sb.append(expression.toSource(0));
        sb.append(") ");
        sb.append(statement.toSource(depth+1));
        if (!(statement instanceof Block)) {
            sb.append(";\n");
        }
        return sb.toString();
    }

    /**
     * Visits this node, then the with-object, then the body statement.
     */
    @Override
    public void visit(NodeVisitor v) {
        if (v.visit(this)) {
            expression.visit(v);
            statement.visit(v);
        }
    }
}


text:
import numpy as np

class Surface(object):
    def __init__(self, image, edge_points3d, edge_points2d):
        """
        Constructor for a surface defined by a texture image and
        4 boundary points. Choose the first point as the origin
        of the surface's coordinate system.

        :param image: image array
        :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction
        :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction
        """
        assert len(edge_points3d) == 4 and len(edge_points2d) == 4

        self.image = image
        self.edge_points3d = edge_points3d
        self.edge_points2d = np.float32(edge_points2d)  # This is required for using cv2's getPerspectiveTransform
        self.normal = self._get_normal_vector()

    def top_left_corner3d(self):
        return self.edge_points3d[0]

    def top_right_corner3d(self):
        return self.edge_points3d[1]

    def bottom_right_corner3d(self):
        return self.edge_points3d[2]

    def bottom_left_corner3d(self):
        return self.edge_points3d[3]

    def distance_to_point(self, point):
        point_to_surface = point - self.top_left_corner3d()
        distance_to_surface = self.normal.dot(point_to_surface)
        return distance_to_surface

    def _get_normal_vector(self):
        """
        :return: the normal vector of the surface. It determined the front side
        of the surface and it's not necessarily a unit vector
        """
        p0 = self.edge_points3d[0]
        p1 = self.edge_points3d[1]
        p3 = self.edge_points3d[3]
        v1 = p3 - p0
        v2 = p1 - p0
        normal = np.cross(v1, v2)
        norm = np.linalg.norm(normal)
        return normal / norm

class Polyhedron(object):
    def __init__(self, surfaces):
        self.surfaces = surfaces

class Space(object):
    def __init__(self, models=None):
        self.models = models or []

    def add_model(self, model):
        assert isinstance(model, Polyhedron)
        self.models.append(model)

class Line2D(object):
    def __init__(self, point1, point2):
        """
        Using the line equation a*x + b*y + c = 0 with b >= 0
        :param point1: starting point
        :param point2: ending point
        :return: a Line object
        """
        assert len(point1) == 2 and len(point2) == 2

        self.a = point2[1] - point1[1]
        self.b = point1[0] - point2[0]
        self.c = point1[1] * point2[0] - point1[0] * point2[1]

        if self.b < 0:
            self.a = -self.a
            self.b = -self.b
            self.c = -self.c

    def is_point_on_left(self, point):
        return self.a * point[0] + self.b * point[1] + self.c > 0

    def is_point_on_right(self, point):
        return self.a * point[0] + self.b * point[1] + self.c < 0

    def is_point_on_line(self, point):
        return self.a * point[0] + self.b * point[1] + self.c == 0

    def get_y_from_x(self, x):
        if self.b == 0:
            return 0.0

        return 1.0 * (-self.c - self.a * x) / self.b

    def get_x_from_y(self, y):
        if self.a == 0:
            return 0.0

        return 1.0 * (-self.c - self.b * y) / self.a


text:
#region copyright
// Copyright 2017 Habart Thierry
//
// 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.
#endregion

using SimpleIdServer.Bus;

namespace SimpleIdentityServer.OpenId.Events
{
    public class ConsentAccepted : Event
    {
        public ConsentAccepted(string id, string processId, string payload, int order)
        {
            Id = id;
            ProcessId = processId;
            Payload = payload;
            Order = order;
        }

        public string Id { get; private set; }
        public string ProcessId { get; private set; }
        public string Payload { get; private set; }
        public int Order { get; private set; }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>foo</groupId>
    <artifactId>foo</artifactId>
    <version>1</version>

        <dependencies>

            <dependency>
                <groupId>a</groupId>
                <artifactId>a</artifactId>
                <version>1</version>
            </dependency>

            <dependency>
                <groupId>b</groupId>
                <artifactId>b</artifactId>
                <version>2</version>
                <optional>true</optional>
            </dependency>

        </dependencies>

</project>


text:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <getopt.h>
#include <string.h>

#define CODE_VARIABLE        0
#define CODE_UNIQUE         (1 << 7)

#define MSG_BYTES            32
#define COMM_BYTES           12
#define BYTE_ALIGN           4

#define INVALID -1
#define VALID 0

#define packed_struct __attribute__ ((packed))

int param = 0;

struct sched_message {
	short prev_pid;
	unsigned char prev_prio;
	unsigned char prev_state;
	char prev_comm[COMM_BYTES];
	short next_pid;
	unsigned char next_prio;
	char pad;
	char next_comm[COMM_BYTES];
};

union trace_message {
	char message[MSG_BYTES];	// 24B, message(192b)
	struct sched_message sched_msg;
};

struct trace_packet {			// total 40 byte(message), 16byte(uid)
	int tv_sec;
	int tv_nsec;
	short pid;					// 2B, int16_t(16b)
	char event_type;			// 1B, char(8b)
	unsigned char codelen;		// 1B, code(1b) + variable length(7b) or uid(7b)
	int pad;
	union trace_message msg;
};

static int print_uid_packet(struct trace_packet *packet)
{
	unsigned char uid = packet->codelen & (unsigned char)(~CODE_UNIQUE);
	printf("[%06d:%06d] %03u: %c|%u\r\n", packet->tv_sec, packet->tv_nsec / 1000, (unsigned int)packet->pid, (unsigned int)packet->event_type, uid);
	return sizeof(struct trace_packet) - MSG_BYTES;
}

static int print_message_packet(struct trace_packet *packet)
{
	printf("[%06d:%06d] %03u: %c|%s\r\n", packet->tv_sec, packet->tv_nsec / 1000, (unsigned int)packet->pid, packet->event_type, packet->msg.message);
	return sizeof(struct trace_packet);
}

static int print_sched_packet(struct trace_packet *packet)
{
	printf("[%06d:%06d] %03u: %c|prev_comm=%s prev_pid=%u prev_prio=%u prev_state=%u ==> next_comm=%s next_pid=%u next_prio=%u\r\n", packet->tv_sec, packet->tv_nsec / 1000, (unsigned int)packet->pid, packet->event_type, packet->msg.sched_msg.prev_comm, (unsigned int)packet->msg.sched_msg.prev_pid, (unsigned int)packet->msg.sched_msg.prev_prio, (unsigned int)packet->msg.sched_msg.prev_state, packet->msg.sched_msg.next_comm, (unsigned int)packet->msg.sched_msg.next_pid, (unsigned int)packet->msg.sched_msg.next_prio);
	return sizeof(struct trace_packet);
}

static int print_packet(struct trace_packet *packet)
{
	int isSched = (packet->event_type == 's') ? 1 : 0;
	int isUnique = (packet->codelen & CODE_UNIQUE);

	if (isSched) {
		return print_sched_packet(packet);
	} else if (isUnique) {
		return print_uid_packet(packet);
	} else {
		return print_message_packet(packet);
	}
}

static void show_help()
{
	printf("usage: parse_dump [dumpfile]\r\n");
	printf("example: ./parse_dump ramdump\r\n");
}

static int check_args_validation(int argc, char **args)
{
	int i = 0;
	if (argc != 2) {
		show_help();
		return INVALID;
	}

	return VALID;
}

static int get_dumpsize(FILE *file)
{
	int size = 0;
	fseek(file, 0, SEEK_END);
	size = ftell(file);
	fseek(file, 0, SEEK_SET);
	return size;
}

static FILE *open_dump(char *path)
{
	FILE *file = fopen(path, "r+");
	if (file == NULL) {
		printf("Failed to open : %s\r\n", path);
	}
	return file;
}

static char *alloc_tracebuffer(int size)
{
	char *bp = (char *)malloc(size * sizeof(char));
	if (bp == NULL) {
		printf("Failed to zalloc buffer in ttrace\r\n");
	}
	return bp;
}

static void close_dump(FILE *file)
{
	if (file == NULL) {
		printf("file pointer doesn't opened\r\n");
		return;
	}
	fclose(file);
	return;
}

static void free_tracebuffer(char *buffer)
{
	if (buffer == NULL) {
		printf("tracebuffer dosen't allocated\r\n");
		return;
	}
	free(buffer);
	return;
}

static int read_tracebuffer(FILE *file, int bufsize)
{
	char *buffer = NULL;
	int read_len = 0, offset = 0;

	buffer = alloc_tracebuffer(bufsize);
	if (buffer == NULL) {
		return INVALID;
	}

	read_len = fread(buffer, sizeof(char), bufsize, file);
	if (read_len < 0) {
		return INVALID;
	}

	while (offset < read_len) {
		offset += print_packet((struct trace_packet *)(buffer + offset));
	}

	free_tracebuffer(buffer);
	return VALID;
}

int main(int argc, char **args)
{
	FILE *file;
	int filesize, ret;

	if (INVALID == check_args_validation(argc, args)) {
		return INVALID;
	}

	file = open_dump(args[1]);
	if (file == NULL) {
		return INVALID;
	}

	filesize = get_dumpsize(file);
	if (filesize <= 0) {
		return INVALID;
	}

	ret = read_tracebuffer(file, filesize);

	close_dump(file);
	return ret;
}


text:
@interface UIViewController(BackButton)

- (void)navCustomeBackBtn:(SEL)action;

@end


text:
byte_reader_t* string_byte_reader_alloc();
byte_reader_t* stdio_byte_reader_alloc();
byte_reader_t* mmap_byte_reader_alloc();

void string_byte_reader_free(byte_reader_t* pbr);
void stdio_byte_reader_free(byte_reader_t* pbr);
void mmap_byte_reader_free(byte_reader_t* pbr);

#endif // BYTE_READERS_H


text:
///////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009, Michael A. Jackson. BlueQuartz Software
//  All rights reserved.
//  BSD License: http://www.opensource.org/licenses/bsd-license.html
//
//
///////////////////////////////////////////////////////////////////////////////
#ifndef WINDOWSFILEWRITER_H_
#define WINDOWSFILEWRITER_H_

#include "MXA/MXA.h"

#if defined (_MSC_VER)
#include <MXA/Common/Win32Defines.h>
#endif
//

// Conditional Includes/Defines for Large File Support on Windows
#if defined (WINDOWS_LARGE_FILE_SUPPORT)
#include <io.h>
#include <fcntl.h>
#include <stdlib.h>
#include <windows.h>
#define WRITER64_OUTPUT_STREAM HANDLE
#else  // Non Windows Platform
#include <fstream>
#define WRITER64_OUTPUT_STREAM std::ofstream
#endif

// Hard set our stream buffer to 4096 bytes
#define BUFF_SIZE 4096

// C++ Includes
#include <string>
#include <iostream>
#include <vector>
#include <stdexcept>

/**
 * @class MXAFileWriter64 MXAFileWriter64.h MXA/Common/IO/MXAFileWriter64.h
 * @brief This class is a wrapper around platform specific native streams to make
 * sure that we can write files larger than 2GB
 * @author Mike Jackson @ BlueQuartz Software.us
 * @date August 2007
 * @version $Revision: 1.2 $
 */
class MXA_EXPORT  MXAFILEWRITER_CLASS_NAME
{

public:
  explicit MXAFILEWRITER_CLASS_NAME(const std::string &filename);

  virtual ~MXAFILEWRITER_CLASS_NAME();

  /**
   * @brief Initializes our stream object and opens the file
   * @return True on success. False on any failure
   */
  bool initWriter();

  /**
 * @brief Reads a number of bytes from the underlying stream
 * @param data The char pointer to read the data into
 * @param numBytes The number of bytes to read
 */
  bool write(char* data, int64_t numBytes)
  {
  DWORD nBytesToWrite = static_cast<DWORD>(numBytes);
  DWORD nBytesWritten = 0;
  int error = WriteFile(_outStream,  // Which is really an HANDLE hFile on Windows
                   data,
                   nBytesToWrite,
                   &nBytesWritten,
                   NULL) ;
    if (nBytesToWrite != nBytesWritten)
    {
      //throw std::runtime_error ( "Error: Number of bytes written did not match number of bytes asked." );
      return false;
    }
    return true;
  }

  /**
   * @brief Writes a single value to a file with no byte swapping performed
   * @param value The value to write to the file
   */
  template<typename T>
  bool writeValue(T* value)
  {
    DWORD nBytesToWrite = static_cast<DWORD>(sizeof(T));
    DWORD nBytesWritten = 0;
    int error = WriteFile(_outStream,  // Which is really an HANDLE hFile on Windows
                          (char*)(value),
                          nBytesToWrite,
                          &nBytesWritten,
                          NULL) ;
    if (nBytesToWrite != nBytesWritten)
    {
     // throw std::runtime_error ( "Error: Number of bytes written did not match number of bytes asked." );
      return false;
    }
    return true;
  }

  /**
   * @brief Writes a "C" array into the file
   * @param front pointer to the location in the array to start writing
   * @param numElements number of elements of the array to write
   */
  template<typename T>
  bool writeArray(T* front, int64_t numElements)
  {
    DWORD nBytesToWrite = static_cast<DWORD>(sizeof(T) * numElements);
    DWORD nBytesWritten = 0;
    int error = WriteFile(_outStream,  // Which is really an HANDLE hFile on Windows
                          (char*)(front),
                          nBytesToWrite,
                          &nBytesWritten,
                          NULL) ;
    if (nBytesToWrite != nBytesWritten)
    {
     // throw std::runtime_error ( "Error: Number of bytes written did not match number of bytes asked." );
      return false;
    }
    return true;
  }

  /**
 * @brief Sets the filepointer of the underlying stream
 * @param position The position to set the file pointer to
 */
  void setFilePointer64( int64_t position )
  {
    LARGE_INTEGER posOut;
    LARGE_INTEGER offset;
    offset.QuadPart = position;
    SetFilePointerEx(_outStream, offset, &posOut , FILE_BEGIN); //Seek from the beginning of file

  }

/**
 * @brief Returns the current position of the file pointer
 * @return the Current position of the file pointer
 */
  int64_t getFilePointer64()
  {
    LARGE_INTEGER posOut;
    LARGE_INTEGER offset;
    offset.QuadPart = 0;
    SetFilePointerEx(_outStream, offset, &posOut , FILE_CURRENT); //From where we are now
    return posOut.QuadPart;
  }

private:
  std::string _filename;
  WRITER64_OUTPUT_STREAM _outStream;
  std::vector<char> _buffer;

};

#endif /* WINDOWSFILEWRITER_H_ */


text:
class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end

class User < ActiveRecord::Base

  has_many :questions
  has_many :answers
  has_many :comments
  has_many :votes

  validates :name, presence: true
  validates :email, presence: true, uniqueness: true, email: true
  validates :password_hash, presence: true

  def password
    @password ||= BCrypt::Password.new(password_hash)
  end

  def password=(new_password_plaintext)
    @password = BCrypt::Password.create(new_password_plaintext)
    self.password_hash = @password.to_s
  end

  def authenticate(password_plaintext)
    return self.password == password_plaintext
  end
end


text:
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

namespace Microsoft.HBase.Client.Filters
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using Microsoft.HBase.Client.Internal;

    /// <summary>
    /// This filter is used to filter cells based on value.
    /// </summary>
    public class SingleColumnValueFilter : Filter
    {
        private readonly byte[] _family;
        private readonly byte[] _qualifier;

        /// <summary>
        /// Initializes a new instance of the <see cref="SingleColumnValueFilter" /> class.
        /// </summary>
        /// <param name="family">The name of the column family.</param>
        /// <param name="qualifier">The name of the column qualifier.</param>
        /// <param name="compareOp">The operator.</param>
        /// <param name="value">The value to compare column values against.</param>
        /// <param name="filterIfMissing">
        /// When <c>true</c>, the entire row will be skipped if the column is not found;
        /// when <c>false</c>, the row will pass if the column is not found.
        /// </param>
        /// <param name="latestVersion">
        /// When <c>true</c>, the row will be returned if only the latest version of the column value matches;
        /// when <c>false</c>, the row will be returned if any version of the column value matches.
        /// </param>
        /// <remarks>
        /// Constructor for binary compare of the value of a single column.
        /// </remarks>
        public SingleColumnValueFilter(
            byte[] family,
            byte[] qualifier,
            CompareFilter.CompareOp compareOp,
            byte[] value,
            bool filterIfMissing = false,
            bool latestVersion = true) : this(family, qualifier, compareOp, new BinaryComparator(value), filterIfMissing, latestVersion)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SingleColumnValueFilter"/> class.
        /// </summary>
        /// <param name="family">The name of the column family.</param>
        /// <param name="qualifier">The name of the column qualifier.</param>
        /// <param name="compareOp">The operator.</param>
        /// <param name="comparator">The comparator to use.</param>
        /// <param name="filterIfMissing">
        /// When <c>true</c>, the entire row will be skipped if the column is not found;
        /// when <c>false</c>, the row will pass if the column is not found.
        /// </param>
        /// <param name="latestVersion">
        /// When <c>true</c>, the row will be returned if only the latest version of the column value matches;
        /// when <c>false</c>, the row will be returned if any version of the column value matches.
        /// </param>
        /// <remarks>
        /// Constructor for binary compare of the value of a single column.
        /// </remarks>
        public SingleColumnValueFilter(
            byte[] family,
            byte[] qualifier,
            CompareFilter.CompareOp compareOp,
            ByteArrayComparable comparator,
            bool filterIfMissing = false,
            bool latestVersion = true)
        {
            family.ArgumentNotNull("family");
            qualifier.ArgumentNotNull("qualifier");

            if (!Enum.IsDefined(typeof(CompareFilter.CompareOp), compareOp))
            {
                throw new InvalidEnumArgumentException("compareOp", (int)compareOp, typeof(CompareFilter.CompareOp));
            }

            comparator.ArgumentNotNull("comparator");

            _family = (byte[])family.Clone();
            _qualifier = (byte[])qualifier.Clone();
            CompareOperation = compareOp;
            Comparator = comparator;

            FilterIfMissing = filterIfMissing;
            LatestVersion = latestVersion;
        }

        /// <summary>
        /// Gets the comparator.
        /// </summary>
        /// <value>
        /// The comparator.
        /// </value>
        public ByteArrayComparable Comparator { get; private set; }

        /// <summary>
        /// Gets the compare operation.
        /// </summary>
        /// <value>
        /// The compare operation.
        /// </value>
        public CompareFilter.CompareOp CompareOperation { get; private set; }

        /// <summary>
        /// Gets the name of the column family.
        /// </summary>
        /// <value>
        /// The name of the column family.
        /// </value>
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public byte[] Family
        {
            get { return (byte[])_family.Clone(); }
        }

        /// <summary>
        /// Gets a value indicating whether the entire row should be filtered if column is not found.
        /// </summary>
        /// <value>
        ///   <c>true</c> if the entire row should be filtered if column is not found; otherwise, <c>false</c>.
        /// </value>
        public bool FilterIfMissing { get; private set; }

        /// <summary>
        /// Gets a value indicating whether or not only the latest version will be tested.
        /// </summary>
        /// <value>
        /// When <c>true</c>, the row will be returned if only the latest version of the column value matches;
        /// when <c>false</c>, the row will be returned if any version of the column value matches.
        /// </value>
        public bool LatestVersion { get; private set; }

        /// <summary>
        /// Gets the name of the column qualifier.
        /// </summary>
        /// <value>
        /// The name of the column qualifier.
        /// </value>
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public byte[] Qualifier
        {
            get { return (byte[])_qualifier.Clone(); }
        }

        /// <inheritdoc/>
        [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
        public override string ToEncodedString()
        {
            const string filterPattern =
                @"{{""type"":""SingleColumnValueFilter"",""op"":""{0}"",""family"":""{1}"",""qualifier"":""{2}"",""ifMissing"":{3},""latestVersion"":{4},""comparator"":{{{5}}}}}";

            return string.Format(
                CultureInfo.InvariantCulture,
                filterPattern,
                CompareOperation.ToCodeName(),
                Convert.ToBase64String(Family),
                Convert.ToBase64String(Qualifier),
                FilterIfMissing.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(),
                LatestVersion.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(),
                Comparator.ToEncodedString());
        }
    }
}


text:
import { version } from '../../package.json'
import BIDS from './obj'
import reset from './reset'
import quickTest from './quickTest'
import quickTestError from './quickTestError'
import fullTest from './fullTest'
import utils from '../../utils'
import { schemaRegex } from '../../validators/schemaTypes'
import { schemaSetup } from '../../utils/type'

/**
 * Start
 *
 * Takes either a filelist array or
 * a path to a BIDS directory and an
 * options object and starts
 * the validation process and
 * returns the errors and warnings as
 * arguments to the callback.
 */
const start = (dir, options, callback) => {
  if (!options.json) {
    // eslint-disable-next-line
    console.log(`bids-validator@${version}`)
  }

  utils.options.parse(dir, options, async function (issues, options) {
    if (issues && issues.length > 0) {
      // option parsing issues
      callback({ config: issues })
    } else {
      BIDS.options = options
      reset(BIDS)
      // Load the bids-spec schema ahead of any validation
      let schema
      if (options.schema) {
        schema = await schemaRegex(options.schema)
        schemaSetup(schema)
      }
      const files = await utils.files.readDir(dir, options)
      if (quickTest(files)) {
        // Is the dir using git-annex?
        const annexed = utils.files.remoteFiles.isGitAnnex(dir)
        fullTest(files, BIDS.options, annexed, dir, schema, callback)
      } else {
        // Return an error immediately if quickTest fails
        const issue = quickTestError(dir)
        BIDS.summary.totalFiles = Object.keys(files).length
        callback(utils.issues.format([issue], BIDS.summary, options))
      }
    }
  })
}

export default start


text:
Gem to validation IE from factories in Brazil

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'validator_ie'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install validator_ie

## Usage
```ruby
result = ValidatorIE::valid?('XXXXXXXXXXXX','AC') # Only numbers
unless result
  puts ValidatorIE::errors.full_messages
end
```
## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/rmomogi/validator_ie. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
package fireboard

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"testing"

	"github.com/influxdata/telegraf/testutil"
	"github.com/stretchr/testify/require"
)

func TestFireboard(t *testing.T) {
	// Create a test server with the const response JSON
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		fmt.Fprintln(w, response)
	}))
	defer ts.Close()

	// Parse the URL of the test server, used to verify the expected host
	u, err := url.Parse(ts.URL)
	require.NoError(t, err)

	// Create a new fb instance with our given test server
	fireboard := NewFireboard()
	fireboard.AuthToken = "b4bb6e6a7b6231acb9f71b304edb2274693d8849"
	fireboard.URL = u.String()

	// Create a test accumulator
	acc := &testutil.Accumulator{}

	// Gather data from the test server
	err = fireboard.Gather(acc)
	require.NoError(t, err)

	// Expect the correct values for all known keys
	expectFields := map[string]interface{}{
		"temperature": float64(79.9),
	}
	// Expect the correct values for all tags
	expectTags := map[string]string{
		"title":   "telegraf-FireBoard",
		"uuid":    "b55e766c-b308-49b5-93a4-df89fe31efd0",
		"channel": strconv.FormatInt(1, 10),
		"scale":   "Fahrenheit",
	}

	acc.AssertContainsTaggedFields(t, "fireboard", expectFields, expectTags)
}

var response = `
[{
	"id": 99999,
	"title": "telegraf-FireBoard",
	"created": "2019-03-23T16:48:32.152010Z",
	"uuid": "b55e766c-b308-49b5-93a4-df89fe31efd0",
	"hardware_id": "XXXXXXXXX",
	"latest_temps": [
	  {
		"temp": 79.9,
		"channel": 1,
		"degreetype": 2,
		"created": "2019-06-25T06:07:10Z"
	  }
	],
	"last_templog": "2019-06-25T06:06:40Z",
	"model": "FBX11E",
	"channel_count": 6,
	"degreetype": 2
  }]
`


text:
package com.ibm.jaggr.core.cache;

/**
 * OSGi service listener interface that is called by the cache manager when it has been
 * initialized.  Aggregator extension may register service listeners for this interface
 * to know when it is safe to call cache manager methods for adding named caches,
 * etc.  To receive listener events, register the implementing class as an OSGi service,
 * specifying the servlet name in the name service property.
 */
public interface ICacheManagerListener {
	/**
	 * Called when the cache manager has been initialized.
	 *
	 * @param cacheManager the cache manager instance.
	 */
	void initialized(ICacheManager cacheManager);
}


text:
using System.Data.Entity.ModelConfiguration;
using NewsAggregator.Domain.Entites;

namespace NewsAggregator.Data.Context.Mappings
{
    public class WebSiteMap : EntityTypeConfiguration<WebSite>
    {
        public WebSiteMap()
        {
            // Key
            HasKey(p => p.WebSiteID);

            // Properties
            Property(p => p.Title).IsRequired().HasMaxLength(255);
            Property(p => p.Description).IsRequired();
            Property(p => p.Link).IsRequired().HasMaxLength(2048);
        }
    }
}


text:
package kizitorashiro.mp3meta.id3v22;

import java.util.HashMap;

import kizitorashiro.mp3meta.ID3v2Exception;
import kizitorashiro.mp3meta.ID3v2InvalidFormatException;

public class TLA extends TXX{
	public TLA(){
		super();
	}

	@Override
	public byte[] create(HashMap<String, String> args) throws ID3v2Exception{
		String value = args.get("value");
		if(value == null || value.length() != 3){
			throw new ID3v2InvalidFormatException("TLA MUST be three characters");
		}
		return super.create(args);
	}

}


text:
package mk.ukim.finki.wp.repository.db;

import mk.ukim.finki.wp.model.db.EventMethodOfEntering;
import mk.ukim.finki.wp.repository.JpaSpecificationRepository;

public interface EventMethodOfEnteringRepository extends JpaSpecificationRepository<EventMethodOfEntering> {

}


text:
export var RelativePositionStrategy = (function () {
    function RelativePositionStrategy(_relativeTo) {
        this._relativeTo = _relativeTo;
    }
    RelativePositionStrategy.prototype.apply = function (element) {
        // Not yet implemented.
        return null;
    };
    RelativePositionStrategy.prototype.dispose = function () {
        // Not yet implemented.
    };
    return RelativePositionStrategy;
}());

//# sourceMappingURL=relative-position-strategy.js.map


text:
package org.hawkular.agent.monitor.api;

import java.util.Collection;

import org.hawkular.agent.monitor.extension.MonitorServiceConfiguration.EndpointConfiguration;
import org.hawkular.agent.monitor.inventory.AvailType;
import org.hawkular.agent.monitor.inventory.MeasurementInstance;
import org.hawkular.agent.monitor.inventory.MetricType;
import org.hawkular.agent.monitor.inventory.MonitoredEndpoint;
import org.hawkular.agent.monitor.inventory.NodeLocation;
import org.hawkular.agent.monitor.storage.AvailDataPoint;
import org.hawkular.agent.monitor.storage.MetricDataPoint;
import org.hawkular.agent.monitor.util.Consumer;

/**
 * A service that can be used to sample metrics and avails for the given {@link MonitoredEndpoint}.
 *
 * @author Peter Palaga
 *
 * @param <L> the type of the protocol specific location, typically a subclass of {@link NodeLocation}
 */
public interface SamplingService<L> {

    /**
     * @return the endpoint this service is able to sample
     */
    MonitoredEndpoint<EndpointConfiguration> getMonitoredEndpoint();

    /**
     * Checks the availabilities defined by {@code instances} and reports them back to the given {@code consumer}.
     *
     * @param instances the availabilities to check
     * @param consumer the consumer to send the results to
     */
    void measureAvails(Collection<MeasurementInstance<L, AvailType<L>>> instances, Consumer<AvailDataPoint> consumer);

    /**
     * Collects the metrics defined by {@code instances} and reports them back to the given {@code consumer}.
     *
     * @param instances the metrics to check
     * @param consumer the consumer to send the results to
     */
    void measureMetrics(Collection<MeasurementInstance<L, MetricType<L>>> instances,
            Consumer<MetricDataPoint> consumer);

}


text:
import path from 'path';
import assert from 'assert';

let script = require(__filename.replace(/_test\.js$/, '_solution.js'));

describe('examples', () => {

  it('example 1', () => {
    assert.equal(script.run('To continue, please consult the code grid in the manual.  Enter the code at row 4, column 3.'), 21345942);
  });

});


text:
/*
 * GET home page.
 */

exports.index = function(req, res){
	res.locals.session = req.session;
  res.render('index', { title: 'Express with dust'});
};


text:
package bndtools.wizards.workspace;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import aQute.bnd.build.Project;
import bndtools.Plugin;

public class WorkspaceSetupWizardPage extends WizardPage {

	public static final String			PROP_LOCATION		= "location";
	public static final String			PROP_CLEAN_BUILD	= "cleanBuild";

	private final PropertyChangeSupport	propSupport			= new PropertyChangeSupport(this);
	private final WorkspaceLocationPart	locationPart		= new WorkspaceLocationPart();

	private LocationSelection			location			= LocationSelection.WORKSPACE;
	private boolean						cleanBuild			= true;

	private Image						bannerImg;

	public WorkspaceSetupWizardPage() {
		super("Workspace Setup");
	}

	@Override
	public void createControl(Composite parent) {
		setTitle("Setup Bnd Workspace");
		setDescription("Create a workspace folder with initial configuration");
		setImageDescriptor(Plugin.imageDescriptorFromPlugin("icons/bndtools-wizban.png")); //$NON-NLS-1$

		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout(1, false);
		layout.verticalSpacing = 20;
		composite.setLayout(layout);
		setControl(composite);

		bannerImg = AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "banner.png")
			.createImage(parent.getDisplay());
		Label lblBanner = new Label(composite, SWT.NONE);
		lblBanner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		lblBanner.setImage(bannerImg);

		Control locationControl = locationPart.createControl(composite);
		locationControl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

		locationPart.addPropertyChangeListener(WorkspaceLocationPart.PROP_LOCATION, evt -> {
			LocationSelection oldLocation = location;
			location = locationPart.getLocation();
			propSupport.firePropertyChange(PROP_LOCATION, oldLocation, location);
			updateUI();
		});

		Group buildGroup = new Group(composite, SWT.NONE);
		buildGroup.setText("Build");
		buildGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		buildGroup.setLayout(new GridLayout(1, false));

		final Button btnCleanBuild = new Button(buildGroup, SWT.CHECK);
		btnCleanBuild.setText("Clean workspace after import (Recommended)");
		btnCleanBuild.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
		btnCleanBuild.setSelection(cleanBuild);

		btnCleanBuild.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				cleanBuild = btnCleanBuild.getSelection();
				updateUI();
			}
		});

		updateUI();
	}

	private void updateUI() {
		String warning = cleanBuild ? null : "Existing Bnd projects may not build until the workspace is cleaned.";

		// Check for existing workspace/cnf
		IProject cnfProject = ResourcesPlugin.getWorkspace()
			.getRoot()
			.getProject(Project.BNDCNF);
		if (cnfProject != null && cnfProject.exists()) {
			File cnfDir = cnfProject.getLocation()
				.toFile();
			warning = String.format(
				"This Eclipse workspace is already configured as a Bnd workspace: %s. You will not be able to create or import a Bnd workspace from elsewhere.",
				cnfDir);
		}
		setMessage(warning, WARNING);

		String locationError = location.validate();
		setErrorMessage(locationError);
		setPageComplete(locationError == null);
	}

	@Override
	public void dispose() {
		super.dispose();
		bannerImg.dispose();
	}

	public void setLocation(LocationSelection location) {
		this.location = location;
		locationPart.setLocation(location);
	}

	public LocationSelection getLocation() {
		return location;
	}

	public void setCleanBuild(boolean cleanBuild) {
		this.cleanBuild = cleanBuild;
	}

	public boolean isCleanBuild() {
		return cleanBuild;
	}

	public void addPropertyChangeListener(PropertyChangeListener listener) {
		propSupport.addPropertyChangeListener(listener);
	}

	public void removePropertyChangeListener(PropertyChangeListener listener) {
		propSupport.removePropertyChangeListener(listener);
	}

	public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
		propSupport.addPropertyChangeListener(propertyName, listener);
	}

	public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
		propSupport.removePropertyChangeListener(propertyName, listener);
	}

}


text:
namespace etl {

template <typename Expr>
struct optimizable;

template <typename Expr>
struct optimizer;

template <typename Expr>
struct transformer;

struct identity_op;

struct transform_op;

template <typename Sub>
struct stateful_op;

template <typename T, typename Expr, typename UnaryOp>
struct unary_expr;

template <typename T, typename LeftExpr, typename BinaryOp, typename RightExpr>
struct binary_expr;

template <typename Generator>
class generator_expr;

template <typename Expr>
struct optimized_expr;

template <typename Expr>
struct serial_expr;

template <typename Selector, Selector V, typename Expr>
struct selected_expr;

template <typename Expr>
struct parallel_expr;

template <typename Expr, typename R = etl::nanoseconds>
struct timed_expr;

template <typename D, typename T, typename A, typename B, typename R>
struct temporary_expr_bin;

template <typename T, size_t D>
struct dim_view;

template <typename T, bool Aligned, typename Enable = void>
struct sub_view;

template <typename T, bool Aligned, typename Enable = void>
struct sub_matrix_2d;

template <typename T, bool Aligned, typename Enable = void>
struct sub_matrix_3d;

template <typename T, bool Aligned, typename Enable = void>
struct sub_matrix_4d;

template <typename T, typename Enable = void>
struct slice_view;

template <typename T, bool Aligned>
struct memory_slice_view;

template <typename T, bool DMA, size_t... Dims>
struct fast_matrix_view;

template <typename T, size_t D, typename Enable = void>
struct dyn_matrix_view;

template <typename A>
struct transpose_expr;

template <typename A>
struct transpose_front_expr;

template <typename D, bool Fast>
struct base_temporary_expr;

template <typename T>
struct scalar;

} //end of namespace etl


text:
package pl.edu.uwm.wmii.visearch.analyzer;

/**
 * Creation at: Apr 10, 2013
 *
 */

import java.awt.List;
import org.opencv.core.*;

import org.opencv.highgui.Highgui;
import org.opencv.imgproc.*;
import org.opencv.features2d.*;

/**
 * @author ksopyla
 *
 */
public class KeyPointExtractor {

	/**
	 * @param imageName
	 * @param method
	 * @param kp - output parameter
	 * @param des - output parameter
	 */
	public void Extract(String imageName, ExtractionMethod method,
			MatOfKeyPoint kp, Mat des) {
		// TODO Auto-generated method stub

		Mat imSrc = Highgui.imread(imageName);

		FeatureDetector fd= GetFeatureDetector(method);

		fd.detect(imSrc, kp);

		DescriptorExtractor desExt = GetDescriptor(method);
		desExt.compute(imSrc, kp,des);

	}

	/**
	 * @param method
	 * @return
	 */
	private DescriptorExtractor GetDescriptor(ExtractionMethod method) {
		// TODO Auto-generated method stub

		switch (method) {
		case SIFT:
			return DescriptorExtractor.create(DescriptorExtractor.SIFT);
		case SURF:
			return DescriptorExtractor.create(DescriptorExtractor.SURF);
		}
		return null;
	}

	/**
	 * @param method
	 * @return
	 */
	private FeatureDetector GetFeatureDetector(ExtractionMethod method) {
		// TODO Auto-generated method stub
		switch (method) {
		case SIFT:
			return FeatureDetector.create(FeatureDetector.SIFT);
		case SURF:
			return FeatureDetector.create(FeatureDetector.SURF);
		}
		return null;
	}

}


text:
function [data, fileList] = load_matfiles_fast(dpath)
% load_matfiles_fast    Load data from Mat files in `dpath` directory using `matfile`.
%
% This file is a part of BrainDecoderToolbox2.
%
% Inputs:
%
% - dpath   : Path to directory containing Mat files.
%
% Outputs:
%
% - data     : Cell array of mat-file objects (loaded by matfile).
% - fileList : Cell array of loaded files.
%

files = dir(dpath);

fileList = {};
data = {};

for i = 1:length(files)
    if isequal(files(i).name, '.') || isequal(files(i).name, '..')
        continue;
    end

    fpath = fullfile(dpath, files(i).name);
    [pathstr, name, ext] = fileparts(fpath);

    if ~isequal(ext, '.mat');
        continue;
    end

    data{end + 1, 1} = matfile(fpath);
    fileList{end + 1, 1} = files(i).name;
end


text:
'''
BPL, Branch on Result Plus Test

This is a test for the branch instruction BPL of
the 6502. This instruction performs the branch
if N == 0.

'''

import unittest
from pynes.compiler import lexical, syntax, semantic

class BplTest(unittest.TestCase):

    '''This is an relative instruction, so it works quite different
    from others. The instruction uses an offset witch can range from
    -128 to +127. The offset is added to the program counter.'''

    def test_bpl_rel(self):
        tokens = list(lexical('BPL $10'))
        self.assertEquals(2, len(tokens))
        self.assertEquals('T_INSTRUCTION', tokens[0]['type'])
        self.assertEquals('T_ADDRESS', tokens[1]['type'])
        ast = syntax(tokens)
        self.assertEquals(1, len(ast))
        self.assertEquals('S_RELATIVE', ast[0]['type'])
        code = semantic(ast)
        self.assertEquals(code, [0x10, 0x0e])


text:
NSString const *jk_UIBarButtonItem_badgeKey = @"jk_UIBarButtonItem_badgeKey";

NSString const *jk_UIBarButtonItem_badgeBGColorKey = @"jk_UIBarButtonItem_badgeBGColorKey";
NSString const *jk_UIBarButtonItem_badgeTextColorKey = @"jk_UIBarButtonItem_badgeTextColorKey";
NSString const *jk_UIBarButtonItem_badgeFontKey = @"jk_UIBarButtonItem_badgeFontKey";
NSString const *jk_UIBarButtonItem_badgePaddingKey = @"jk_UIBarButtonItem_badgePaddingKey";
NSString const *jk_UIBarButtonItem_badgeMinSizeKey = @"jk_UIBarButtonItem_badgeMinSizeKey";
NSString const *jk_UIBarButtonItem_badgeOriginXKey = @"jk_UIBarButtonItem_badgeOriginXKey";
NSString const *jk_UIBarButtonItem_badgeOriginYKey = @"jk_UIBarButtonItem_badgeOriginYKey";
NSString const *jk_UIBarButtonItem_shouldHideBadgeAtZeroKey = @"jk_UIBarButtonItem_shouldHideBadgeAtZeroKey";
NSString const *jk_UIBarButtonItem_shouldAnimateBadgeKey = @"jk_UIBarButtonItem_shouldAnimateBadgeKey";
NSString const *jk_UIBarButtonItem_badgeValueKey = @"jk_UIBarButtonItem_badgeValueKey";

@implementation UIBarButtonItem (JKBadge)

@dynamic jk_badgeValue, jk_badgeBGColor, jk_badgeTextColor, jk_badgeFont;
@dynamic jk_badgePadding, jk_badgeMinSize, jk_badgeOriginX, jk_badgeOriginY;
@dynamic jk_shouldHideBadgeAtZero, jk_shouldAnimateBadge;

- (void)jk_badgeInit
{
    UIView *superview = nil;
    CGFloat defaultOriginX = 0;
    if (self.customView) {
        superview = self.customView;
        defaultOriginX = superview.frame.size.width - self.jk_badge.frame.size.width/2;
        // Avoids badge to be clipped when animating its scale
        superview.clipsToBounds = NO;
    } else if ([self respondsToSelector:@selector(view)] && [(id)self view]) {
        superview = [(id)self view];
        defaultOriginX = superview.frame.size.width - self.jk_badge.frame.size.width;
    }
    [superview addSubview:self.jk_badge];

    // Default design initialization
    self.jk_badgeBGColor   = [UIColor redColor];
    self.jk_badgeTextColor = [UIColor whiteColor];
    self.jk_badgeFont      = [UIFont systemFontOfSize:12.0];
    self.jk_badgePadding   = 6;
    self.jk_badgeMinSize   = 8;
    self.jk_badgeOriginX   = defaultOriginX;
    self.jk_badgeOriginY   = -4;
    self.jk_shouldHideBadgeAtZero = YES;
    self.jk_shouldAnimateBadge = YES;
}

#pragma mark - Utility methods

// Handle badge display when its properties have been changed (color, font, ...)
- (void)jk_refreshBadge
{
    // Change new attributes
    self.jk_badge.textColor        = self.jk_badgeTextColor;
    self.jk_badge.backgroundColor  = self.jk_badgeBGColor;
    self.jk_badge.font             = self.jk_badgeFont;

    if (!self.jk_badgeValue || [self.jk_badgeValue isEqualToString:@""] || ([self.jk_badgeValue isEqualToString:@"0"] && self.jk_shouldHideBadgeAtZero)) {
        self.jk_badge.hidden = YES;
    } else {
        self.jk_badge.hidden = NO;
        [self jk_updateBadgeValueAnimated:YES];
    }

}

- (CGSize)jk_badgeExpectedSize
{
    // When the value changes the badge could need to get bigger
    // Calculate expected size to fit new value
    // Use an intermediate label to get expected size thanks to sizeToFit
    // We don't call sizeToFit on the true label to avoid bad display
    UILabel *frameLabel = [self jk_duplicateLabel:self.jk_badge];
    [frameLabel sizeToFit];

    CGSize expectedLabelSize = frameLabel.frame.size;
    return expectedLabelSize;
}

- (void)jk_updateBadgeFrame
{

    CGSize expectedLabelSize = [self jk_badgeExpectedSize];

    // Make sure that for small value, the badge will be big enough
    CGFloat minHeight = expectedLabelSize.height;

    // Using a const we make sure the badge respect the minimum size
    minHeight = (minHeight < self.jk_badgeMinSize) ? self.jk_badgeMinSize : expectedLabelSize.height;
    CGFloat minWidth = expectedLabelSize.width;
    CGFloat padding = self.jk_badgePadding;

    // Using const we make sure the badge doesn't get too smal
    minWidth = (minWidth < minHeight) ? minHeight : expectedLabelSize.width;
    self.jk_badge.layer.masksToBounds = YES;
    self.jk_badge.frame = CGRectMake(self.jk_badgeOriginX, self.jk_badgeOriginY, minWidth + padding, minHeight + padding);
    self.jk_badge.layer.cornerRadius = (minHeight + padding) / 2;
}

// Handle the badge changing value
- (void)jk_updateBadgeValueAnimated:(BOOL)animated
{
    // Bounce animation on badge if value changed and if animation authorized
    if (animated && self.jk_shouldAnimateBadge && ![self.jk_badge.text isEqualToString:self.jk_badgeValue]) {
        CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        [animation setFromValue:[NSNumber numberWithFloat:1.5]];
        [animation setToValue:[NSNumber numberWithFloat:1]];
        [animation setDuration:0.2];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithControlPoints:.4f :1.3f :1.f :1.f]];
        [self.jk_badge.layer addAnimation:animation forKey:@"bounceAnimation"];
    }

    // Set the new value
    self.jk_badge.text = self.jk_badgeValue;

    // Animate the size modification if needed
    if (animated && self.jk_shouldAnimateBadge) {
        [UIView animateWithDuration:0.2 animations:^{
            [self jk_updateBadgeFrame];
        }];
    } else {
        [self jk_updateBadgeFrame];
    }
}

- (UILabel *)jk_duplicateLabel:(UILabel *)labelToCopy
{
    UILabel *duplicateLabel = [[UILabel alloc] initWithFrame:labelToCopy.frame];
    duplicateLabel.text = labelToCopy.text;
    duplicateLabel.font = labelToCopy.font;

    return duplicateLabel;
}

- (void)jk_removeBadge
{
    // Animate badge removal
    [UIView animateWithDuration:0.2 animations:^{
        self.jk_badge.transform = CGAffineTransformMakeScale(0, 0);
    } completion:^(BOOL finished) {
        [self.jk_badge removeFromSuperview];
        self.jk_badge = nil;
    }];
}

#pragma mark - getters/setters
-(UILabel*)jk_badge {
    UILabel* lbl = objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgeKey);
    if(lbl==nil) {
        lbl = [[UILabel alloc] initWithFrame:CGRectMake(self.jk_badgeOriginX, self.jk_badgeOriginY, 20, 20)];
        [self setJk_badge:lbl];
        [self jk_badgeInit];
        [self.customView addSubview:lbl];
        lbl.textAlignment = NSTextAlignmentCenter;
    }
    return lbl;
}
-(void)setJk_badge:(UILabel *)badgeLabel
{
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgeKey, badgeLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

// Badge value to be display
-(NSString *)jk_badgeValue {
    return objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgeValueKey);
}
-(void)setJk_vadgeValue:(NSString *)badgeValue
{
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgeValueKey, badgeValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    // When changing the badge value check if we need to remove the badge
    [self jk_updateBadgeValueAnimated:YES];
    [self jk_refreshBadge];
}

// Badge background color
-(UIColor *)badgeBGColor {
    return objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgeBGColorKey);
}
-(void)setBadgeBGColor:(UIColor *)badgeBGColor
{
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgeBGColorKey, badgeBGColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (self.jk_badge) {
        [self jk_refreshBadge];
    }
}

// Badge text color
-(UIColor *)badgeTextColor {
    return objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgeTextColorKey);
}
-(void)setBadgeTextColor:(UIColor *)badgeTextColor
{
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgeTextColorKey, badgeTextColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (self.jk_badge) {
        [self jk_refreshBadge];
    }
}

// Badge font
-(UIFont *)badgeFont {
    return objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgeFontKey);
}
-(void)setBadgeFont:(UIFont *)badgeFont
{
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgeFontKey, badgeFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (self.jk_badge) {
        [self jk_refreshBadge];
    }
}

// Padding value for the badge
-(CGFloat) badgePadding {
    NSNumber *number = objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgePaddingKey);
    return number.floatValue;
}
-(void) setBadgePadding:(CGFloat)badgePadding
{
    NSNumber *number = [NSNumber numberWithDouble:badgePadding];
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgePaddingKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (self.jk_badge) {
        [self jk_updateBadgeFrame];
    }
}

// Minimum size badge to small
-(CGFloat)jk_badgeMinSize {
    NSNumber *number = objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgeMinSizeKey);
    return number.floatValue;
}
-(void) setJk_badgeMinSize:(CGFloat)badgeMinSize
{
    NSNumber *number = [NSNumber numberWithDouble:badgeMinSize];
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgeMinSizeKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (self.jk_badge) {
        [self jk_updateBadgeFrame];
    }
}

// Values for offseting the badge over the BarButtonItem you picked
-(CGFloat)jk_badgeOriginX {
    NSNumber *number = objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgeOriginXKey);
    return number.floatValue;
}
-(void) setJk_badgeOriginX:(CGFloat)badgeOriginX
{
    NSNumber *number = [NSNumber numberWithDouble:badgeOriginX];
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgeOriginXKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (self.jk_badge) {
        [self jk_updateBadgeFrame];
    }
}

-(CGFloat)jk_badgeOriginY {
    NSNumber *number = objc_getAssociatedObject(self, &jk_UIBarButtonItem_badgeOriginYKey);
    return number.floatValue;
}
-(void) setJk_badgeOriginY:(CGFloat)badgeOriginY
{
    NSNumber *number = [NSNumber numberWithDouble:badgeOriginY];
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_badgeOriginYKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (self.jk_badge) {
        [self jk_updateBadgeFrame];
    }
}

// In case of numbers, remove the badge when reaching zero
-(BOOL) shouldHideBadgeAtZero {
    NSNumber *number = objc_getAssociatedObject(self, &jk_UIBarButtonItem_shouldHideBadgeAtZeroKey);
    return number.boolValue;
}
- (void)setShouldHideBadgeAtZero:(BOOL)shouldHideBadgeAtZero
{
    NSNumber *number = [NSNumber numberWithBool:shouldHideBadgeAtZero];
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_shouldHideBadgeAtZeroKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if(self.jk_badge) {
        [self jk_refreshBadge];
    }
}

// Badge has a bounce animation when value changes
-(BOOL) jk_shouldAnimateBadge {
    NSNumber *number = objc_getAssociatedObject(self, &jk_UIBarButtonItem_shouldAnimateBadgeKey);
    return number.boolValue;
}
- (void)setJk_shouldAnimateBadge:(BOOL)shouldAnimateBadge
{
    NSNumber *number = [NSNumber numberWithBool:shouldAnimateBadge];
    objc_setAssociatedObject(self, &jk_UIBarButtonItem_shouldAnimateBadgeKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if(self.jk_badge) {
        [self jk_refreshBadge];
    }
}

@end


text:
Something other than numbers and characters has been used for a range.

Erroneous code example:

```compile_fail,E0029
let string = "salutations !";

// The ordering relation for strings cannot be evaluated at compile time,
// so this doesn't work:
match string {
    "hello" ..= "world" => {}
    _ => {}
}

// This is a more general version, using a guard:
match string {
    s if s >= "hello" && s <= "world" => {}
    _ => {}
}
```

In a match expression, only numbers and characters can be matched against a
range. This is because the compiler checks that the range is non-empty at
compile-time, and is unable to evaluate arbitrary comparison functions. If you
want to capture values of an orderable type between two end-points, you can use
a guard.


text:
// Package json is a JSON parser following the specifications at http://json.org/.
package json

import (
	"errors"
	"io"
	"strconv"

	"github.com/tdewolff/buffer"
)

// ErrBadComma is returned when an unexpected comma is encountered.
var ErrBadComma = errors.New("unexpected comma character outside an array or object")

// ErrNoComma is returned when no comma is present between two values.
var ErrNoComma = errors.New("expected comma character or an array or object ending")

// ErrBadObjectKey is returned when the object key is not a quoted string.
var ErrBadObjectKey = errors.New("expected object key to be a quoted string")

// ErrBadObjectDeclaration is returned when the object key is not followed by a colon character.
var ErrBadObjectDeclaration = errors.New("expected colon character after object key")

// ErrBadObjectEnding is returned when an unexpected right brace is encountered.
var ErrBadObjectEnding = errors.New("unexpected right brace character")

// ErrBadArrayEnding is returned when an unexpected right bracket is encountered.
var ErrBadArrayEnding = errors.New("unexpected right bracket character")

////////////////////////////////////////////////////////////////

// GrammarType determines the type of grammar
type GrammarType uint32

// GrammarType values.
const (
	ErrorGrammar GrammarType = iota // extra grammar when errors occur
	WhitespaceGrammar
	LiteralGrammar
	NumberGrammar
	StringGrammar
	StartObjectGrammar // {
	EndObjectGrammar   // }
	StartArrayGrammar  // [
	EndArrayGrammar    // ]
)

// String returns the string representation of a GrammarType.
func (gt GrammarType) String() string {
	switch gt {
	case ErrorGrammar:
		return "Error"
	case WhitespaceGrammar:
		return "Whitespace"
	case LiteralGrammar:
		return "Literal"
	case NumberGrammar:
		return "Number"
	case StringGrammar:
		return "String"
	case StartObjectGrammar:
		return "StartObject"
	case EndObjectGrammar:
		return "EndObject"
	case StartArrayGrammar:
		return "StartArray"
	case EndArrayGrammar:
		return "EndArray"
	}
	return "Invalid(" + strconv.Itoa(int(gt)) + ")"
}

////////////////////////////////////////////////////////////////

// State determines the current state the parser is in.
type State uint32

// State values.
const (
	ValueState State = iota // extra token when errors occur
	ObjectKeyState
	ObjectValueState
	ArrayState
)

// String returns the string representation of a State.
func (state State) String() string {
	switch state {
	case ValueState:
		return "Value"
	case ObjectKeyState:
		return "ObjectKey"
	case ObjectValueState:
		return "ObjectValue"
	case ArrayState:
		return "Array"
	}
	return "Invalid(" + strconv.Itoa(int(state)) + ")"
}

////////////////////////////////////////////////////////////////

// Parser is the state for the lexer.
type Parser struct {
	r     *buffer.Lexer
	state []State
	err   error

	needComma bool
}

// NewParser returns a new Parser for a given io.Reader.
func NewParser(r io.Reader) *Parser {
	return &Parser{
		r:     buffer.NewLexer(r),
		state: []State{ValueState},
	}
}

// Err returns the error encountered during tokenization, this is often io.EOF but also other errors can be returned.
func (p Parser) Err() error {
	if p.err != nil {
		return p.err
	}
	return p.r.Err()
}

// Next returns the next Grammar. It returns ErrorGrammar when an error was encountered. Using Err() one can retrieve the error message.
func (p *Parser) Next() (GrammarType, []byte) {
	p.r.Free(p.r.ShiftLen())

	p.moveWhitespace()
	c := p.r.Peek(0)
	state := p.state[len(p.state)-1]
	if c == ',' {
		if state != ArrayState && state != ObjectKeyState {
			p.err = ErrBadComma
			return ErrorGrammar, nil
		}
		p.r.Move(1)
		p.moveWhitespace()
		p.needComma = false
		c = p.r.Peek(0)
	}
	p.r.Skip()

	if p.needComma && c != '}' && c != ']' && c != 0 {
		p.err = ErrNoComma
		return ErrorGrammar, nil
	} else if c == '{' {
		p.state = append(p.state, ObjectKeyState)
		p.r.Move(1)
		return StartObjectGrammar, p.r.Shift()
	} else if c == '}' {
		if state != ObjectKeyState {
			p.err = ErrBadObjectEnding
			return ErrorGrammar, nil
		}
		p.needComma = true
		p.state = p.state[:len(p.state)-1]
		if p.state[len(p.state)-1] == ObjectValueState {
			p.state[len(p.state)-1] = ObjectKeyState
		}
		p.r.Move(1)
		return EndObjectGrammar, p.r.Shift()
	} else if c == '[' {
		p.state = append(p.state, ArrayState)
		p.r.Move(1)
		return StartArrayGrammar, p.r.Shift()
	} else if c == ']' {
		p.needComma = true
		if state != ArrayState {
			p.err = ErrBadArrayEnding
			return ErrorGrammar, nil
		}
		p.state = p.state[:len(p.state)-1]
		if p.state[len(p.state)-1] == ObjectValueState {
			p.state[len(p.state)-1] = ObjectKeyState
		}
		p.r.Move(1)
		return EndArrayGrammar, p.r.Shift()
	} else if state == ObjectKeyState {
		if c != '"' || !p.consumeStringToken() {
			p.err = ErrBadObjectKey
			return ErrorGrammar, nil
		}
		n := p.r.Pos()
		p.moveWhitespace()
		if c := p.r.Peek(0); c != ':' {
			p.err = ErrBadObjectDeclaration
			return ErrorGrammar, nil
		}
		p.r.Move(1)
		p.state[len(p.state)-1] = ObjectValueState
		return StringGrammar, p.r.Shift()[:n]
	} else {
		p.needComma = true
		if state == ObjectValueState {
			p.state[len(p.state)-1] = ObjectKeyState
		}
		if c == '"' && p.consumeStringToken() {
			return StringGrammar, p.r.Shift()
		} else if p.consumeNumberToken() {
			return NumberGrammar, p.r.Shift()
		} else if p.consumeLiteralToken() {
			return LiteralGrammar, p.r.Shift()
		}
	}
	return ErrorGrammar, nil
}

// State returns the state the parser is currently in (ie. which token is expected).
func (p *Parser) State() State {
	return p.state[len(p.state)-1]
}

////////////////////////////////////////////////////////////////

/*
The following functions follow the specifications at http://json.org/
*/

func (p *Parser) moveWhitespace() {
	for {
		if c := p.r.Peek(0); c != ' ' && c != '\t' && c != '\r' && c != '\n' {
			break
		}
		p.r.Move(1)
	}
}

func (p *Parser) consumeLiteralToken() bool {
	c := p.r.Peek(0)
	if c == 't' && p.r.Peek(1) == 'r' && p.r.Peek(2) == 'u' && p.r.Peek(3) == 'e' {
		p.r.Move(4)
		return true
	} else if c == 'f' && p.r.Peek(1) == 'a' && p.r.Peek(2) == 'l' && p.r.Peek(3) == 's' && p.r.Peek(4) == 'e' {
		p.r.Move(5)
		return true
	} else if c == 'n' && p.r.Peek(1) == 'u' && p.r.Peek(2) == 'l' && p.r.Peek(3) == 'l' {
		p.r.Move(4)
		return true
	}
	return false
}

func (p *Parser) consumeNumberToken() bool {
	mark := p.r.Pos()
	if p.r.Peek(0) == '-' {
		p.r.Move(1)
	}
	c := p.r.Peek(0)
	if c >= '1' && c <= '9' {
		p.r.Move(1)
		for {
			if c := p.r.Peek(0); c < '0' || c > '9' {
				break
			}
			p.r.Move(1)
		}
	} else if c != '0' {
		p.r.Rewind(mark)
		return false
	} else {
		p.r.Move(1) // 0
	}
	if c := p.r.Peek(0); c == '.' {
		p.r.Move(1)
		if c := p.r.Peek(0); c < '0' || c > '9' {
			p.r.Move(-1)
			return true
		}
		for {
			if c := p.r.Peek(0); c < '0' || c > '9' {
				break
			}
			p.r.Move(1)
		}
	}
	mark = p.r.Pos()
	if c := p.r.Peek(0); c == 'e' || c == 'E' {
		p.r.Move(1)
		if c := p.r.Peek(0); c == '+' || c == '-' {
			p.r.Move(1)
		}
		if c := p.r.Peek(0); c < '0' || c > '9' {
			p.r.Rewind(mark)
			return true
		}
		for {
			if c := p.r.Peek(0); c < '0' || c > '9' {
				break
			}
			p.r.Move(1)
		}
	}
	return true
}

func (p *Parser) consumeStringToken() bool {
	// assume to be on "
	p.r.Move(1)
	for {
		c := p.r.Peek(0)
		if c == '"' {
			p.r.Move(1)
			break
		} else if c == '\\' && (p.r.Peek(1) != 0 || p.r.Err() == nil) {
			p.r.Move(1)
		} else if c == 0 {
			return false
		}
		p.r.Move(1)
	}
	return true
}


text:
(function() {
  var target_dir = '/extensions/platform_apps/url_handlers/common/';
  var link = document.getElementById('link');
  var mismatching_link = document.getElementById('mismatching_link');

  if (link || mismatching_link) {
    var clickEvent = document.createEvent('MouseEvents');
    clickEvent.initMouseEvent('click', true, true, window,
                              0, 0, 0, 0, 0, false, false,
                              false, false, 0, null);
    if (link) {
      console.log("Clicking a matching link");
      link.href = target_dir + 'target.html';
      // This click should open the handler app (pre-installed in the browser by
      // the CPP test before launching this) with link.href.
      link.dispatchEvent(clickEvent);
    }

    if (mismatching_link) {
      console.log("Clicking a mismatching link");
      mismatching_link.href = target_dir + 'mismatching_target.html';
      // This click should NOT open the handler app, because the URL does not
      // match the url_handlers of the app. It should open the link in a new
      // tab instead.
      mismatching_link.dispatchEvent(clickEvent);
    }
  } else {
    console.log("Calling window.open()");
    window.open(target_dir + 'target.html');
  }
})();