text:
!!! note
	This article assumes you know how to use Tiled to create a generic tilemap, and therefore does not explain how to make your own. Don't know how? [Click here to go to the official documentation (which actually just leads you to other sources)](http://doc.mapeditor.org/manual/introduction/).

!!! warning
	Be sure to save your tilemaps in Base64 (uncompressed). Undertailor supports only this format and CSV, though Base64 (uncompressed) is faster for it to load.

Creating a tilemap in Tiled is a very simple task, as the tool makes it easy to paint out a new map of your liking. Let's pull out our old chunk of Snowdin again and see how we get it ready for Undertailor.

![Snowdin tilemap](/img/toolscrns/tiled_7.png)

## Defining Collision

Collision is defined by using **Object Layers**. Each Object Layer is read as a different layer of collision, though they will all be treated the same when encountered in-game, that is, objects in the Overworld will still hit them regardless of layer.

![Snowdin collision tilemap](/img/toolscrns/tiled_9.png)

All shapes may be used to define collision, but do note these rules.

* World Objects hit the edges of enclosed shapes. The inside of an enclosed shape is considered to be a body, and cannot be penetrated by another World Object.
* The polygon tool can define any complex shape, but limitations of the game's physics engine disallow polygons to have more than 8 vertices/sides.
* The polygon tool can define any complex shape, but limitations of the game's physics engine disallow polygons to be concave.
* The two limitations above can be bypassed by using the Polyline tool, but note that Polylines are made of edges, cannot be really "enclosed", and therefore have no body. World Objects can technically reside "inside" of a polyline shape.

With these rules in mind, it is recommended that you draw most of your map's boundaries using the Polyline tool. Collisions for objects displayed by the map can be done with the other shapes, if you don't want objects going inside your christmas tree or presents, for example.

!!! tip
	If you place your objects somewhere along the grid, you can use the Polyline tool and hold CTRL to snap to a grid point nearest to your mouse cursor.

## Shape Definitions

It is possible to access shapes from a map within your Lua code. By defining an Object Layer with a name starting with the hash character (`#`), you initialize it as a definition layer in the eyes of Undertailor. These layers will not be registered as collision, but instead purely as map metadata. Metadata shapes can be used to create and add World Objects whose functionality is specific to the current map, not just as collision.

Two types of shape metadata can be created. You can create normal shapes, or `points`, an object with no shape, only a position. Undertailor will notice the difference between these two object types, and will allow them to be retrieved separately as their own types. To create a point, simply create a shape on your map with no width, and no height.

![A point](/img/toolscrns/tiled_10.png)

## Special Properties

Tiled permits us to add specific properties for certain games (like ours) to read, and use the map the way we need to.

![Add a custom property](/img/toolscrns/tiled_8.png)

To add a custom property, select the layer to add it to on the right sidebar containing your layers, then click the plus button on the bottom left of the options sidebar.

### Property: `layer`

This property is required for each **Tile Layer** and **Image Layer**. If not present, the console will log this with an error, and the layer will be ignored during loading. It is an integer.

The property determines the order of rendering for the layers. The lowest layer is rendered in the back, while the highest layer in the front. This can also determine whether or not the layers appear behind or in front of the player character or any world object on the Overworld, as world objects operate on the same notion of layers.

The game will prioritize certain layers over others in rendering.

* A Tile Layer is always rendered first.
* An Image Layer is rendered like a WorldObject, and is rendered second.
* WorldObjects in the Overworld are rendered last.

### Property: `threshold`

This property is optional, and only applicable to **Image Layers**. It is a decimal number between 0.0 and 1.0 (a percentage).

Image Layers are rendered like WorldObjects in the game. That is, like WorldObjects, their position in rendering is determined by their position in the world. Objects and Image Layers with a lower Y value (closer to the bottom of the screen) are rendered in the front, higher Y's in the back. For Image Layers that wish to be able to appropriately shift in front of, or behind World Objects, depending on their position, this may pose an issue when the shape of the image is relatively complex.

![Thresholding-1](/img/toolscrns/prp_threshold_1.png)

Let's start by visiting the problem. In this screenshot, you can immediately tell something isn't right. Our character is standing in front of the shop, but it seems he's being displayed behind it, as if the shop is floating above them.

This is because the game notices that the player character has a higher Y value than the shop image. The shop image's Y value is the position of its bottom-most pixel, which is clearly below our kid's little feet. Naturally, this doesn't work for us, as he is still in front of the shop.

By adding a threshold value, we can tell the game to offset the internal Y position of the shop image by a certain percentage. The threshold value will offset the Y position internally by a percentage. With a value of 0.3, the Y position of an Image Layer holding an image 100 pixels in height will be offset by 30 pixels.

![Thresholding-2](/img/toolscrns/prp_threshold_2.png)

The threshold value was set to 0.3. Now our kid can hide safely between this shop's two houses.


text:
from gimpfu import *
from math import pow, sqrt
from gimpcolor import RGB

def euclidean_distance(point_one, point_two):
    """ Calculate the euclidean distance.

        Args:
            point_one (tuple)
            point_two (tuple)

        Returns:
            float: the distance between the two points
    """
    return sqrt(pow(point_two[0] - point_one[0], 2) + \
        pow(point_two[1] - point_one[1], 2))

def get_maximum_distance(ref_list, dev_list):
    """ Calculate the distance between two list of pixels

        Args:
            ref_list (list)
            dev_list (list)

        Returns:
            float: the distance between the two list
            tuple: the pixel of the dev_list
            tuple: the pixel of the ref_list
    """

    gimp.progress_init("Calculating distance...")

    ref_pixel = (0, 0)
    dev_pixel = (0, 0)
    maximum_distance = float("-inf")
    for index, pixel_ref_list in enumerate(ref_list):
        # Update the progress bar
        gimp.progress_update(float(index) / float(len(ref_list)))

        minimum_distance = float("inf")
        for pixel_dev_list in dev_list:
            distance = euclidean_distance(pixel_ref_list, pixel_dev_list)

            # Update the minimum distance
            if distance < minimum_distance:
                minimum_distance = distance
                dev_pixel = pixel_dev_list

        # Update the maximum distance
        if minimum_distance > maximum_distance:
            maximum_distance = minimum_distance
            ref_pixel = pixel_ref_list

    return maximum_distance, dev_pixel, ref_pixel

def search_pixel(layer, color, pixel, outline_pixels):
    """ Search the outline pixels with a DFS

        Args:
            layer (gimp.Drawable): the layer over do the search
            color (gimpcolor.RGB): the outline pixel's color
            pixel (tuple): the pixel to control and from start a new search
            outline_pixels (list): the list of the outline pixels

        Returns:
            list: the list of the outline pixels
    """

    # I use a `try except` to avoid exceptions that can araise
    # if the method goes through an illegal position in the
    # image (e.g. a pixel that does not exists)
    try:
        # Goes on in the search if the color that it has met is the target color
        if RGB(*layer.get_pixel(pixel)) == color:
            outline_pixels.append(pixel)
            target_pixels = [
                (pixel[0], pixel[1] + 1), # Up
                (pixel[0] + 1, pixel[1]), # Right
                (pixel[0], pixel[1] - 1), # Down
                (pixel[0] + 1, pixel[1])  # Left
            ]

            # Searching
            for target_pixel in target_pixels:
                if target_pixel not in outline_pixels:
                    outline_pixels = search_pixel(layer, color, target_pixel, \
                        outline_pixels)
    except Exception as e:
        gimp.message("Raised exception while saving the outline pixels: " + \
            str(e.message))
    finally:
        return outline_pixels

def get_outline_pixels_positions(image, layer, color, fill_color):
    """ Create the outline and search the pixels of the outline.

        Args:
            image (gimp.Image): the image over we make the transformation
            layer (gimp.Drawable): the layer we transformate
            color (gimpcolor.RGB): the outline's color
            fill_color (gimpcolor.tuple): the other color

        Returns:
            list: the list of the outline pixels
    """

    gimp.progress_init("Searching the outline pixels for the layer...")

    # Clear an eventually selection
    pdb.gimp_selection_clear(image)

    # Initially i search the first pixel colored with the target color
    target_pixel = (0, 0)
    found_pixel = False
    for x in range(layer.width):
        gimp.progress_update(float(x) / float(layer.width))
        for y in range(layer.height):
            if RGB(*layer.get_pixel(x, y)) == color:
                target_pixel = (x, y)
                found_pixel = True

        # If the target color is found, then stop the search
        if found_pixel:
            break

    # Selecting the target area
    pdb.gimp_image_select_contiguous_color(image, 0, layer, \
        target_pixel[0], target_pixel[1])

    # Shrink the selection
    pdb.gimp_selection_shrink(image, 1)

    # Set the target color in the palette
    pdb.gimp_context_set_foreground(RGB(
        fill_color.r if fill_color.r < 1.0 else fill_color.r / 255.0,
        fill_color.g if fill_color.g < 1.0 else fill_color.g / 255.0,
        fill_color.b if fill_color.b < 1.0 else fill_color.b / 255.0,
        fill_color.a if fill_color.a < 1.0 else fill_color.a / 255.0
    ))

    # Fill the selection with the target color
    pdb.gimp_edit_bucket_fill(layer, 0, 0, 100, 0, False, 0, 0)

    gimp.progress_init("Saving the outline pixels...")
    return search_pixel(layer, color, target_pixel, [])

def hausdorff_distance(image, color, fill_color):
    """ Calculate the hausdorff distance.

        Args:
            image (Image): the image to analyse
            color (RGB):

    """

    # Indicates the start of the process
    gimp.progress_init("Initializing Hausdorff distance...")

    try:
        # Outline the first layer
        ref_layer = image.layers[0]
        ref_layer_outline_pixels_positions_list = \
            get_outline_pixels_positions(image, ref_layer, color, fill_color)

        # Outline the second layer
        dev_layer = image.layers[1]
        dev_layer_outline_pixels_positions_list = \
            get_outline_pixels_positions(image, dev_layer, color, fill_color)

        # Retrieve the maxmin distance of first layer, with the two points...
        ref_layer_distance, ref_pixel_one, ref_pixel_two = \
            get_maximum_distance(ref_layer_outline_pixels_positions_list, \
                dev_layer_outline_pixels_positions_list)

        # ...and the maxmin distance and the points of the second layer.
        dev_layer_distance, dev_pixel_one, dev_pixel_two = \
            get_maximum_distance(dev_layer_outline_pixels_positions_list, \
                ref_layer_outline_pixels_positions_list)

        # Now i make the lines to point out the two distances (obviously, the
        # maximum distance will have a wider line)
        red = (255.0, 0.0, 0.0, 255.0)

        distance = max(ref_layer_distance, dev_layer_distance)
        gimp.message("The distance is: " + str(distance))
        return distance
    except Exception as e:
        gimp.message("Unexpected error: " + str(e.message))

    gimp.message("It was not possible to calculate the distance.")
    return float("-inf")

register(
    "python-fu-hausdorff-distance",
    "AISP Hausdorff distance",
    "Calculate the Hausdorff distance between two layers.",
    "Valerio Belli",
    "Valerio Belli",
    "2017",
    "Hausdorff distance",
    "",
    [
        (PF_IMAGE, "image", """The image on which we calculates Hausdorff
            distance.""", None),
        (PF_COLOR, "color", "The outline's color.", (255.0, 255.0, 255.0, 255.0)),
        (PF_COLOR, "fill_color", "The filling color", (0.0, 0.0, 0.0, 255.0))
    ],
    [
        (PF_FLOAT, "distance", "The calculated distance."),
    ],
    hausdorff_distance,
    menu="<Image>/Filters/",
)

if "__main__" == __name__:
    main()

redpajama_set_name: RedPajamaGithub


text:
package org.apache.tinkerpop.gremlin.process.computer;

import org.apache.tinkerpop.gremlin.structure.Graph;

/**
 * The result of the {@link GraphComputer}'s computation. This is returned in a {@link java.util.concurrent.Future} by {@link GraphComputer#submit}.
 * A GraphComputer computation yields two things: an updated view of the computed on {@link Graph} and any computational sideEffects called {@link Memory}.
 *
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public interface ComputerResult extends AutoCloseable {

    /**
     * Get the {@link Graph} computed as determined by {@link GraphComputer.Persist} and {@link GraphComputer.ResultGraph}.
     *
     * @return The computed graph
     */
    public Graph graph();

    /**
     * Get the GraphComputer's computational sideEffects known as {@link Memory}.
     *
     * @return the computed memory
     */
    public Memory memory();

    /**
     * Close the computed {@link GraphComputer} result. The semantics of "close" differ depending on the underlying implementation.
     * In general, when a {@link ComputerResult} is closed, the computed values are no longer available to the user.
     *
     * @throws Exception
     */
    @Override
    public void close() throws Exception;

}


text:
module Substation
  module Processor

    # Supports building new {Processor} instances
    class Builder

      include Concord.new(:name, :klass, :executor)

      # Build processor
      #
      # @param [#call] handler
      # @param [Chain] failure_chain
      #
      # @return [Processor]
      #
      # @api private
      def call(handler, failure_chain, observers)
        klass.new(name, handler, Config.new(executor, failure_chain, observers))
      end

    end # class Builder

  end # module Processor
end # module Substation


text:
using namespace std;
using namespace GiNaC;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " <graph-series-filename>\n";
        return 1;
    }

    // Reading in graph series:
    string graph_series_filename(argv[1]);
    ifstream graph_series_file(graph_series_filename);
    parser coefficient_reader;
    KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });
    KontsevichGraphSeries<ex> inverse = graph_series.inverse();

    for (size_t n = 0; n <= inverse.precision(); ++n)
    {
        cout << "h^" << n << ":\n";
        for (auto& term : inverse[n])
        {
            cout << term.second.encoding() << "    " << term.first << "\n";
        }
    }
}


text:
<!DOCTYPE html>

	<meta name="description" content="Lesson 3, JavaScript Basics, JavaScript Loops, Arrays, Strings, Task 17, Extract Element Content" />
	<meta name="keywords" content="lesson, exercise, JavaScript Basics, JavaScript Loops, Arrays, Strings, Extract Element Content" />
	<meta name="author" content="Removed for reasons of anonymity" />
	<meta charset="UTF-8" />
	<title>Extract Element Content | JavaScript Loops, Arrays, Strings</title>
	<link rel="stylesheet" type="text/css" href="../styles/normalize.css" />
	<link rel="stylesheet" type="text/css" href="../styles/styles.css" />

Extract Element Content

Home

Number Checker

Min and Max Number

Properties

Create Array

Compare Chars

Maximal Sequence

Maximal Increasing Sequence

Sort Array

Most Frequent Number

Reverse String

Check the Brackets

Substring Count

Replace the White-Spaces

Palindromes

Most Frequent Word

Cards Frequencies

Extract Element Content

Replace <a> Tag

Text Modifier

Task 17*: Extract Element Content

Write a JavaScript function extractContent(value) that extracts the text content from given HTML fragment (given as string). The function should return anything that is in a tag, without the tags. Write JS program contentExtracter.js that invokes your function with the sample input data below and prints the output at the console. Examples:

Hint: Create an element and use its innerHTML and innerText properties.

Some html for the purpose:

Hello
W3C

            	<button name="calc" type="button" onclick="extractContentHTML()">Extract this</button>

Or copy and paste to extract the bottom line.

<p>Hello</p><a href='http://w3c.org'>W3C</a>

                Enter text:
                <input type="text" id="data" value="
Hello
W3C" />

                <button name="calc" type="button" onclick="extractContentByInput()">Extract</button>

Copyright ©2014 by "Removed for reasons of anonymity"

Contact with me:


text:
const express = require('express');
const config = require('./config');
const models = require('./models');
const middlewares = require('./middlewares');
const auth = require('./auth');
const routes = require('./routes');

const app = express();
app.set('trust proxy', true);
app.set('x-powered-by', false);

Object.assign(app, {
  db: models
});

auth(app, config);
middlewares(app, config);
routes(app);

app.use((req, res, next) => {
  next({
    status: 404,
    code: 'not_found',
    message: 'Not Found'
  });
});

app.use((err, req, res, next) => {
  if (err.name === 'SequelizeValidationError') {
    res.status(400);
    res.json({
      code: 'not_valid',
      message: err.message,
      params: err.errors.reduce((params, {path, message, type}) => {
        params[path] = {type, message};
        return params;
      }, {})
    });
  } else {
    res.status(err.status || 500);
    res.json({
      code: err.code,
      message: err.message,
      params: err.params || {}
    });
  }
});

const server = app.listen(config.listen, () => {
  const {address, port} = server.address();
  console.log('[%s] server started http://%s:%d', app.get('env'), address, port);
});


text:
<?php

# override the default TCPDF config file
if(!defined('K_TCPDF_EXTERNAL_CONFIG')) {
	define('K_TCPDF_EXTERNAL_CONFIG', TRUE);
}

# include TCPDF
require(APPPATH.'config/tcpdf'.EXT);
require_once($tcpdf['base_directory'].'tcpdf.php');

/************************************************************
 * TCPDF - CodeIgniter Integration
 * Library file
 * ----------------------------------------------------------
 * @author Jonathon Hill http://jonathonhill.net
 * @version 1.0
 * @package tcpdf_ci
 ***********************************************************/
class pdf extends TCPDF {

	/**
	 * TCPDF system constants that map to settings in our config file
	 *
	 * @var array
	 * @access private
	 */
	private $cfg_constant_map = array(
		'K_PATH_MAIN'	=> 'base_directory',
		'K_PATH_URL'	=> 'base_url',
		'K_PATH_FONTS'	=> 'fonts_directory',
		'K_PATH_CACHE'	=> 'cache_directory',
		'K_PATH_IMAGES'	=> 'image_directory',
		'K_BLANK_IMAGE' => 'blank_image',
		'K_SMALL_RATIO'	=> 'small_font_ratio',
	);

	/**
	 * Settings from our APPPATH/config/tcpdf.php file
	 *
	 * @var array
	 * @access private
	 */
	private $_config = array();

	/**
	 * Initialize and configure TCPDF with the settings in our config file
	 *
	 */
	function __construct() {

		# load the config file
		require(APPPATH.'config/tcpdf'.EXT);
		$this->_config = $tcpdf;
		unset($tcpdf);

		# set the TCPDF system constants
		foreach($this->cfg_constant_map as $const => $cfgkey) {
			if(!defined($const)) {
				define($const, $this->_config[$cfgkey]);
				#echo sprintf("Defining: %s = %s\n<br />", $const, $this->_config[$cfgkey]);
			}
		}

		# initialize TCPDF
		parent::__construct(
			$this->_config['page_orientation'],
			$this->_config['page_unit'],
			$this->_config['page_format'],
			$this->_config['unicode'],
			$this->_config['encoding'],
			$this->_config['enable_disk_cache']
		);

		# language settings
		if(is_file($this->_config['language_file'])) {
			include($this->_config['language_file']);
			$this->setLanguageArray($l);
			unset($l);
		}

		# margin settings
		$this->SetMargins($this->_config['margin_left'], $this->_config['margin_top'], $this->_config['margin_right']);

		# header settings
		$this->print_header = $this->_config['header_on'];
		#$this->print_header = FALSE;
		$this->setHeaderFont(array($this->_config['header_font'], '', $this->_config['header_font_size']));
		$this->setHeaderMargin($this->_config['header_margin']);
		$this->SetHeaderData(
			$this->_config['header_logo'],
			$this->_config['header_logo_width'],
			$this->_config['header_title'],
			$this->_config['header_string']
		);

		# footer settings
		$this->print_footer = $this->_config['footer_on'];
		$this->setFooterFont(array($this->_config['footer_font'], '', $this->_config['footer_font_size']));
		$this->setFooterMargin($this->_config['footer_margin']);

		# page break
		$this->SetAutoPageBreak($this->_config['page_break_auto'], $this->_config['footer_margin']);

		# cell settings
		$this->cMargin = $this->_config['cell_padding'];
		$this->setCellHeightRatio($this->_config['cell_height_ratio']);

		# document properties
		$this->author = $this->_config['author'];
		$this->creator = $this->_config['creator'];

		# font settings
		#$this->SetFont($this->_config['page_font'], '', $this->_config['page_font_size']);

		# image settings
		$this->imgscale = $this->_config['image_scale'];

	}

}


text:
<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://github.com/sboo
 * @since      1.0.0
 *
 * @package    Bithek
 * @subpackage Bithek/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Bithek
 * @subpackage Bithek/public
 * @author     Ramon Ackermann <ramon.ackermann@sboo.eu>
 */
class Bithek_Public
{

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $plugin_name The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $version The current version of this plugin.
     */
    private $version;

    private $db_directory;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string $plugin_name The name of the plugin.
     * @param      string $version The version of this plugin.
     */
    public function __construct($plugin_name, $version)
    {

        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->db_directory = dirname(plugin_dir_path(__FILE__)) . '/db';

    }

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_styles()
    {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Bithek_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Bithek_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/bithek-public.css', array(),
            $this->version, 'all');

    }

    /**
     * Register the JavaScript for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts()
    {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Bithek_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Bithek_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/bithek-public.js', array('jquery'),
            $this->version, false);

    }

    private function get_medienart_name($key = null)
    {
        $medienartOptions = array(
            '' => 'Alle',
            'Belletristik' => 'Belletristik',
            'Comic' => 'Comic',
            'DVD-Video' => 'DVD-Video',
            'Hörbuch' => 'Hörbuch',
            'Kass.' => 'Kassette',
            'Sachliteratur' => 'Sachliteratur',
            'Zeitschrift' => 'Zeitschrift',
        );
        if (!is_null($key) && isset($medienartOptions[$key])) {
            return $medienartOptions[$key];
        }
        return $medienartOptions;
    }

    /**
     * @param $shortcode_attributes
     * @return string
     */
    public function shortcode_bithek($shortcode_attributes)
    {
        // For empty Shortcodes like [table] or [table /], an empty string is passed, see WP Core #26927.
        $shortcode_attributes = (array)$shortcode_attributes;
        $action = isset($shortcode_attributes['action']) ? $shortcode_attributes['action'] : null;

        switch ($action) {
            case 'search':
                return $this->searchform() . $this->searchresult();
                break;
            default:
                break;
        }
    }

    /**
     * @return string
     */
    private function searchform()
    {
        $titel = isset($_POST['titel']) ? trim($_POST['titel']) : '';
        $verfasser_i = isset($_POST['verfasser_i']) ? trim($_POST['verfasser_i']) : '';
        $thema = isset($_POST['thema']) ? trim($_POST['thema']) : '';
        $medienart = isset($_POST['medienart']) ? trim($_POST['medienart']) : '';

        $medienartOptions = $this->get_medienart_name();

        $formHTML = '<form method="POST">

Titel:	<input type="text" name="titel" value="' . $titel . '"/>

Verfasser:	<input type="text" name="verfasser_i" value="' . $verfasser_i . '"/>

Thema:	<input type="text" name="thema" value="' . $thema . '"/>

Medienart:	<select name="medienart">';
        foreach ($medienartOptions as $medienartOptionKey => $medienartOptionValue) {
            $formHTML .= '<option value="' . $medienartOptionKey . '" ' . ($medienart == $medienartOptionKey ? 'selected="selected"' : '') . '>' . $medienartOptionValue . '</option>';
        }
        $formHTML .= '
            </select>

	<input type="submit" value="Suche">

        </form>';

        return $formHTML;
    }

    private function searchresult()
    {
        $titel = isset($_POST['titel']) ? trim($_POST['titel']) : '';
        $verfasser_i = isset($_POST['verfasser_i']) ? trim($_POST['verfasser_i']) : '';
        $thema = isset($_POST['thema']) ? trim($_POST['thema']) : '';
        $medienart = isset($_POST['medienart']) ? trim($_POST['medienart']) : '';

        $limit = 50;
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;

        $resultHTML = '';
        if (
            !empty($titel)
            || !empty($verfasser_i)
            || !empty($thema)
            /*|| !empty($medienart)*/
        ) {
            $dbh = new PDO('sqlite:' . $this->db_directory . '/books.db3');
            if (!$dbh) {
                echo "\nnew PDO::errorInfo():\n";
                print_r($dbh->errorInfo());
            }
            $where = [];
            $params = [];
            if (!empty($titel)) {
                $titel = preg_replace('/[^\d\s\p{L}\p{Nd}]/ui',' ', $titel);
                $arrTitle = explode(' ', $titel);
                $arrTitle = array_filter($arrTitle);
                foreach($arrTitle as $word) {
                    $where[] = 'titel LIKE ?';
                    $params[] = '%' . $word . '%';
                }
            }

            if (!empty($verfasser_i)) {
                $verfasser_i = preg_replace('/[^\d\s\p{L}\p{Nd}]/ui',' ', $verfasser_i);
                $arrVervasser_i = explode(' ', $verfasser_i);
                $arrVervasser_i = array_filter($arrVervasser_i);
                foreach($arrVervasser_i as $word) {
                    $where[] = 'verfasser_i LIKE ?';
                    $params[] = '%' . $word . '%';
                }
            }

            if (!empty($thema)) {
                $thema = preg_replace('/[^\d\s\p{L}\p{Nd}]/ui',' ', $thema);
                $arrThema = explode(' ', $thema);
                $arrThema = array_filter($arrThema);
                foreach($arrThema as $word) {
                    $where[] = '(schlagwort LIKE ? OR sk_i LIKE ? OR sk_ii LIKE ?)';
                    $params[] = '%' . $word . '%';
                    $params[] = '%' . $word . '%';
                    $params[] = '%' . $word . '%';
                }
            }

            if (!empty($medienart)) {
                $where[] = 'medienart = ?';
                $params[] = $medienart;
            }

            $query = 'SELECT recordid, isbn, titel, verfasser_i, medienart, ausgeliehen, schlagwort, sk_i, sk_ii FROM books';
            if (count($where)) {
                $query .= ' WHERE ' . implode(' AND ', $where);
            }

            $query .= ' LIMIT ' . (($page - 1) * $limit) . ', ' . $limit;

            $stmt = $dbh->prepare($query);
            if ($stmt === false) {
                echo "\nprepare PDO::errorInfo():\n";
                print_r($dbh->errorInfo());
            }

            $stmt->execute($params);

            $resultHTML .= '
Suchresultat

';
            while ($results = $stmt->fetch()) {

                $thema = array( $results['schlagwort'], $results['sk_i'], $results['sk_ii']);
                $thema = array_filter($thema);
                $resultHTML .= '
';

                $resultHTML .= '
' . $results['verfasser_i'] . '
';
                $resultHTML .= '
' . $results['titel'] . '
';
                $resultHTML .= '
' . $this->get_medienart_name($results['medienart']) . (count($thema) ? ' - ' . implode(', ', $thema) : '') .  '
';
                $resultHTML .= '	';
                $resultHTML .= '
' . $results['ausgeliehen'] . '
';
                $resultHTML .= '	';
                $resultHTML .= '
';
            }
            $resultHTML .= '
';
        }

        return $resultHTML;
    }
}


text:
#ifndef VOCAB_TREE_H_
#define VOCAB_TREE_H_

#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <opencv2/core/core_c.h>
#include <opencv2/flann/flann.hpp>

#include <CentersChooser.h>
#include <DirectIndex.hpp>
#include <DynamicMat.hpp>
#include <FileUtils.hpp>
#include <FunctionUtils.hpp>
#include <InvertedIndex.hpp>
#include <KMajority.h>
#include <VocabBase.hpp>

#include <fstream>

namespace vlr {

struct VocabTreeParams: public cvflann::IndexParams {
	VocabTreeParams(int branching = 10, int depth = 6, int maxIterations = 10,
			cvflann::flann_centers_init_t centersInitMethod =
					cvflann::FLANN_CENTERS_RANDOM) {
		(*this)["depth"] = depth;
		(*this)["branch.factor"] = branching;
		(*this)["max.iterations"] = maxIterations;
		(*this)["centers.init.method"] = centersInitMethod;
	}
};

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

class VocabTreeBase: public VocabBase {
public:

	/**
	 * Virtual destroyer to enable destruction from a subclass.
	 */
	virtual ~VocabTreeBase() {
	}

	virtual void build() = 0;

	virtual void quantize(const cv::Mat& feature, int diLevel, int& wordId,
			int& nodeAtL) const = 0;

	virtual void save(const std::string& filename) const = 0;

	virtual void load(const std::string& filename) = 0;

	virtual size_t size() const = 0;

	virtual size_t getNumWords() const = 0;

	virtual int getDepth() const = 0;

	virtual size_t getVeclen() const = 0;

};

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

/**
 * Structure representing a node in the hierarchical k-means tree.
 */
template<typename TDescriptor>
struct VocabTreeNode {
	// The node id
	int node_id;
	// The cluster center
	TDescriptor* center;
	// Children nodes (only for non-terminal nodes)
	// Note: no need to store how many children does it has because
	// this is a k-ary tree, where 'k' is the branch factor, i.e. it has k children or none
	VocabTreeNode** children;
	// Word id (only for terminal nodes)
	int word_id;
	VocabTreeNode() :
			node_id(-1), center(NULL), children(NULL), word_id(-1) {
	}
};

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

template<class TDescriptor, class Distance>
class VocabTree: public VocabTreeBase {

private:

	typedef typename Distance::ResultType DistanceType;
	typedef VocabTreeNode<TDescriptor>* VocabTreeNodePtr;

protected:

	/** Attributes useful for building the tree **/
	// The function used for choosing the cluster centers
	cvflann::flann_centers_init_t m_centers_init;
	// Maximum number of iterations to use when performing k-means clustering
	int m_iterations;
	// The data set used by this index
	vlr::Mat& m_dataset;

	/** Attributes of the tree **/
	// Branching factor (number of partitions in which
	// data is divided at each level of the tree)
	int m_branching;
	// Number of levels of the tree
	int m_depth;
	// Length of each feature vector
	size_t m_veclen;
	// Number of nodes in the tree
	size_t m_size;
	// The root node of the tree
	VocabTreeNodePtr m_root;
	// Words of the vocabulary
	std::vector<VocabTreeNodePtr> m_words;

	/** Other attributes **/
	// The distance measure used to evaluate similarity between features
	Distance m_distance;

public:

	/**
	 * Class constructor.
	 *
	 * @param inputData - Reference to the matrix with the data to be clustered
	 * @param params - Parameters to the hierarchical k-means algorithm
	 */
	VocabTree(vlr::Mat& inputData = vlr::DEFAULT_INPUTDATA,
			const cvflann::IndexParams& params = VocabTreeParams());

	/**
	 * Class destroyer, releases the memory used by the tree.
	 */
	virtual ~VocabTree();

	/**
	 * Builds the tree.
	 *
	 * @note After this method is executed m_root holds a pointer to the tree,
	 *		 while m_words holds pointers to the leaf nodes.
	 * @note Interior nodes have only 'center' and 'children' information,
	 * 		 while leaf nodes have only 'center' and 'word_id', all weights for
	 * 		 interior nodes are 0 while weights for leaf nodes are 1.
	 */
	void build();

	void quantize(const cv::Mat& feature, int diLevel, int& wordId,
			int& nodeAtL) const;

	/**
	 * Saves the tree to a file stream.
	 *
	 * @param filename - The name of the file stream where to save the tree
	 */
	void save(const std::string& filename) const;

	/**
	 * Loads the tree from a file stream.
	 *
	 * @param filename - The name of the file stream from where to load the tree
	 */
	void load(const std::string& filename);

	size_t size() const {
		return getNumWords();
	}

	size_t getNumNodes() const {
		return m_size;
	}

	size_t getNumWords() const {
		return m_words.size();
	}

	bool operator==(const VocabTree<TDescriptor, Distance> &other) const;

	bool operator!=(const VocabTree<TDescriptor, Distance> &other) const;

	/**** Getters ****/
	VocabTreeNodePtr getRoot() const {
		return m_root;
	}

	int getBranching() const {
		return m_branching;
	}

	int getDepth() const {
		return m_depth;
	}

	size_t getVeclen() const {
		return m_veclen;
	}

private:

	/**
	 * Recursively releases the memory allocated to store the tree node centers.
	 *
	 * @param node - A pointer to a node in the tree where to start the releasing
	 */
	void free_centers(VocabTreeNodePtr node);

	/**
	 * The method responsible with actually doing the recursive hierarchical clustering.
	 *
	 * @param node - The node to cluster
	 * @param indices - Indices of the points belonging to the current node
	 * @param indices_length
	 */
	void computeClustering(VocabTreeNodePtr node, int* indices,
			int indices_length, int level, bool fitted);

	/**
	 * Saves the vocabulary tree starting at a given node to a stream.
	 *
	 * @param fs - A reference to the file storage pointing to the file where to save the tree
	 * @param node - The node indicating the root of the tree to save
	 */
	void save_tree(cv::FileStorage& fs, VocabTreeNodePtr node) const;

	/**
	 * Loads the vocabulary tree from a stream and stores into into a given node pointer.
	 *
	 * @param filename - A reference to the file storage where to read node parameters
	 * @param node - The node where to store the loaded tree
	 */
	void load_tree(boost::iostreams::filtering_istream& is,
			VocabTreeNodePtr& node);

	/**
	 * Returns whether the tree is empty.
	 *
	 * @return true if and only if the tree is empty
	 */
	bool empty() const;

	/**
	 *
	 * @param a
	 * @param b
	 * @return
	 */
	bool compareEqual(const VocabTreeNodePtr a, const VocabTreeNodePtr b) const;

	/**
	 * Copy constructor and the assignment operator are private
	 * to prevent obtaining copies of the instance.
	 */
	VocabTree(VocabTree const&); // Don't Implement
	void operator=(VocabTree const&); // Don't implement

};

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

typedef VocabTree<float, cv::L2<float> > VocabTreeReal;
typedef VocabTree<uchar, cv::Hamming> VocabTreeBin;

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

template<class TDescriptor, class Distance>
VocabTree<TDescriptor, Distance>::VocabTree(vlr::Mat& inputData,
		const cvflann::IndexParams& params) :
		m_dataset(inputData), m_veclen(0), m_size(0), m_root(NULL), m_distance(
				Distance()) {

	// Attributes initialization
	m_veclen = m_dataset.cols;
	m_branching = cvflann::get_param<int>(params, "branch.factor");
	m_iterations = cvflann::get_param<int>(params, "max.iterations");
	m_depth = cvflann::get_param<int>(params, "depth");
	m_centers_init = cvflann::get_param<cvflann::flann_centers_init_t>(params,
			"centers.init.method");

	if (m_iterations < 0) {
		m_iterations = std::numeric_limits<int>::max();
	}

}

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

template<class TDescriptor, class Distance>
VocabTree<TDescriptor, Distance>::~VocabTree() {
	if (m_root != NULL) {
		free_centers(m_root);
	}
}

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

template<class TDescriptor, class Distance>
void VocabTree<TDescriptor, Distance>::free_centers(VocabTreeNodePtr node) {
	delete[] node->center;
	if (node->children != NULL) {
		for (int k = 0; k < m_branching; ++k) {
			free_centers(node->children[k]);
		}
		delete[] node->children;
	}
	delete node;
}

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

template<class TDescriptor, class Distance>
void VocabTree<TDescriptor, Distance>::build() {

	if (m_branching < 2) {
		throw std::runtime_error("[VocabTree::build] Error, branching factor"
				" must be at least 2");
	}

	if (m_depth < 1) {
		throw std::runtime_error("[VocabTree::build] Error, depth"
				" must be at least 1");
	}

	if (m_dataset.empty() == true) {
		throw std::runtime_error("[VocabTree::build] Error, data set is empty"
				" cannot proceed with clustering");
	}

	// Number of features in the data set
	int size = m_dataset.rows;

	//  Array of descriptors indices
	int* indices = new int[size];
	for (int i = 0; i < size; ++i) {
		indices[i] = i;
	}

	m_root = new VocabTreeNode<TDescriptor>();
	m_root->center = new TDescriptor[m_veclen];
	std::fill(m_root->center, m_root->center + m_veclen, 0);

#if VTREEVERBOSE
	printf("[VocabTree::build] Started clustering\n");
#endif

	computeClustering(m_root, indices, size, 0, false);

#if VTREEVERBOSE
	printf("[VocabTree::build] Finished clustering\n");
#endif

	delete[] indices;
}

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

template<class TDescriptor, class Distance>
void VocabTree<TDescriptor, Distance>::quantize(const cv::Mat& feature,
		int diLevel, int& wordId, int& nodeAtL) const {

	CV_Assert(0 <= diLevel && diLevel < m_depth);

	VocabTreeNodePtr best_node = m_root;

	int level = 0;

	while (best_node->children != NULL) {

		VocabTreeNodePtr node = best_node;

		// Arbitrarily assign to first child
		best_node = node->children[0];
		DistanceType best_distance = m_distance((TDescriptor*) feature.data,
				best_node->center, m_veclen);

		// Looking for a better child
		for (int j = 1; j < m_branching; ++j) {
			DistanceType d = m_distance((TDescriptor*) feature.data,
					node->children[j]->center, m_veclen);
			if (d < best_distance) {
				best_distance = d;
				best_node = node->children[j];
				if (level == diLevel) {
					nodeAtL = j;
				}
			}
		}

		++level;
	}

	wordId = best_node->word_id;
}

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

template<class TDescriptor, class Distance>
void VocabTree<TDescriptor, Distance>::save(const std::string& filename) const {

	if (empty()) {
		throw std::runtime_error("[VocabTree::save] Tree is empty");
	}

	cv::FileStorage fs(filename.c_str(), cv::FileStorage::WRITE);

	if (fs.isOpened() == false) {
		throw std::runtime_error(
				"[VocabTree::save] Error opening file " + filename
						+ " for writing");
	}

	std::string vocabType =
			typeid(TDescriptor) == typeid(float) ? "HKM" :
			typeid(TDescriptor) == typeid(uchar) ? "HKMAJ" : "UNKNOWN";

	fs << "type" << vocabType;
	fs << "iterations" << m_iterations;
	fs << "branching" << m_branching;
	fs << "depth" << m_depth;
	fs << "vectorLength" << (int) m_veclen;
	fs << "size" << (int) m_size;

	fs << "nodes" << "[";

	save_tree(fs, m_root);

	fs << "]";

	fs.release();
}

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

template<class TDescriptor, class Distance>
void VocabTree<TDescriptor, Distance>::save_tree(cv::FileStorage& fs,
		VocabTreeNodePtr node) const {

	// Save node
	fs << "{";
	fs << "center"
			<< cv::Mat(1, m_veclen, cv::DataType<TDescriptor>::type,
					(uchar*) node->center);
	fs << "nodeId" << node->node_id;
	fs << "wordId" << node->word_id;
	fs << "}";

	// Save children, if any
	if (node->children != NULL) {
		for (int i = 0; i < m_branching; ++i) {
			save_tree(fs, node->children[i]);
		}
	}

}

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

template<class TDescriptor, class Distance>
void VocabTree<TDescriptor, Distance>::load(const std::string& filename) {

	std::ifstream inputZippedFileStream;
	boost::iostreams::filtering_istream inputFileStream;

	std::string line, field;
	std::stringstream ss;

	enum treeFields {
		iterations, branching, depth, vectorLength, size, nodes
	};
	std::string treeFieldsNames[] = { "iterations:", "branching:", "depth:",
			"vectorLength:", "size:", "nodes:" };

	// Open file
	inputZippedFileStream.open(filename.c_str(),
			std::fstream::in | std::fstream::binary);

	// Check file
	if (inputZippedFileStream.good() == false) {
		throw std::runtime_error("[VocabTree::load] "
				"Unable to open file [" + filename + "] for reading");
	}

	try {
		inputFileStream.push(boost::iostreams::gzip_decompressor());
		inputFileStream.push(inputZippedFileStream);

		while (getline(inputFileStream, line)) {
			ss.clear();
			ss.str(line);
			ss >> field;
			if (field.compare(treeFieldsNames[iterations]) == 0) {
				ss >> m_iterations;
			} else if (field.compare(treeFieldsNames[branching]) == 0) {
				ss >> m_branching;
			} else if (field.compare(treeFieldsNames[depth]) == 0) {
				ss >> m_depth;
			} else if (field.compare(treeFieldsNames[vectorLength]) == 0) {
				ss >> m_veclen;
			} else if (field.compare(treeFieldsNames[size]) == 0) {
				ss >> m_size;
			} else if (field.compare(treeFieldsNames[nodes]) == 0) {
				break;
			}
		}

		m_root = new VocabTreeNode<TDescriptor>();
		load_tree(inputFileStream, m_root);

	} catch (const boost::iostreams::gzip_error& e) {
		throw std::runtime_error("[VocabTree::load] "
				"Got error while parsing file [" + std::string(e.what()) + "]");
	}

	// Close file
	inputZippedFileStream.close();

}

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

template<class TDescriptor, class Distance>
void VocabTree<TDescriptor, Distance>::load_tree(
		boost::iostreams::filtering_istream& inputFileStream,
		VocabTreeNodePtr& node) {

	enum nodeFields {
		start, center, rows, cols, dt, data, nodeId, wordId
	};
	std::string nodeFieldsNames[] = { "-", "center:", "rows:", "cols:", "dt:",
			"data:", "nodeId:", "wordId:" };

	std::string line, field;
	std::stringstream ss;

	cv::Mat _center;

	int _rows = -1;
	int _cols = -1;
	std::string _type;
	int colIdx = -1;
	float elem;

	while (getline(inputFileStream, line)) {
		ss.clear();
		ss.str(line);
		ss >> field;
		if (field.compare(nodeFieldsNames[start]) == 0) {
			continue;
		} else if (field.compare(nodeFieldsNames[center]) == 0) {
			continue;
		} else if (field.compare(nodeFieldsNames[rows]) == 0) {
			ss >> _rows;
		} else if (field.compare(nodeFieldsNames[cols]) == 0) {
			ss >> _cols;
		} else if (field.compare(nodeFieldsNames[dt]) == 0) {
			ss >> _type;
		} else if (field.compare(nodeFieldsNames[nodeId]) == 0) {
			ss >> node->node_id;
		} else if (field.compare(nodeFieldsNames[wordId]) == 0) {
			ss >> node->word_id;
			break;
		} else {
			if (field.compare(nodeFieldsNames[data]) == 0) {
				_center = cv::Mat::zeros(_rows, _cols,
						_type.compare("f") == 0 ? CV_32F : CV_8U);
				line.replace(line.find(nodeFieldsNames[data]), 5, " ");
			}

			bool isLastLine = line.find("]") != std::string::npos;

			std::replace(line.begin(), line.end(), '[', ' ');
			std::replace(line.begin(), line.end(), ',', ' ');
			std::replace(line.begin(), line.end(), ']', ' ');

			ss.clear();
			ss.str(line);

			while ((ss >> elem).fail() == false) {
				_center.at<TDescriptor>(0, ++colIdx) = elem;
			}

			if (isLastLine) {
				// Check dimensions correctness
				CV_Assert(_center.rows == 1);
				CV_Assert(_center.cols == int(m_veclen));

				// Deep copy
				node->center = new TDescriptor[m_veclen];
				for (size_t k = 0; k < m_veclen; ++k) {
					node->center[k] = _center.at<TDescriptor>(0, k);
				}

				// Release memory and dereference header
				_center.release();
				_center = cv::Mat();
			}
		}
	}

	bool hasChildren = node->word_id == -1;

	if (hasChildren == false) {
		// Node has no children then it's a leaf node
		node->children = NULL;
		m_words.push_back(node);
	} else {
		// Node has children then it's an interior node
		node->children = new VocabTreeNodePtr[m_branching];
		for (int c = 0; c < m_branching; ++c) {
			node->children[c] = new VocabTreeNode<TDescriptor>();
			load_tree(inputFileStream, node->children[c]);
		}
	}

}

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

template<class TDescriptor, class Distance>
void VocabTree<TDescriptor, Distance>::computeClustering(VocabTreeNodePtr node,
		int* indices, int indices_length, int level, bool fitted) {

	node->node_id = m_size;
	++m_size;

	// Sort descriptors, caching leverages this fact
	// Note: it doesn't affect the clustering process since all descriptors referenced by indices belong to the same cluster
	if (level > 1) {
		std::sort(indices, indices + indices_length);
	}

	// Recursion base case: done when the last level is reached
	// or when there is less data than clusters
	if (level == m_depth || indices_length < m_branching) {
		node->children = NULL;
		node->word_id = m_words.size();
		m_words.push_back(node);
#if VTREEVERBOSE
		if (level == m_depth) {
			printf(
					"[VocabTree::computeClustering] (level %d): last level was reached (%d features)\n",
					level, indices_length);
		} else {
			printf(
					"[VocabTree::computeClustering] (level %d): there was less data than clusters (%d features)\n",
					level, indices_length);
		}
#endif
		return;
	}

#if VTREEVERBOSE
	printf(
			"[VocabTree::computeClustering] (level %d): Running k-means (%d features)\n",
			level, indices_length);
	fflush(stdout);
#endif

	std::vector<int> centers_idx(m_branching);
	int centers_length = 0;

#if DEBUG
#if VTREEVERBOSE
	printf("randomCenters - Start\n");
#endif
#endif

	CentersChooser<TDescriptor, Distance>::create(m_centers_init)->chooseCenters(
			m_branching, indices, indices_length, centers_idx, centers_length,
			m_dataset);

#if DEBUG
#if VTREEVERBOSE
	printf("randomCenters - End\n");
#endif
#endif

	// Recursion base case: done as well if by case got
	// less cluster indices than clusters
	if (centers_length < m_branching) {
		node->children = NULL;
		node->word_id = m_words.size();
		m_words.push_back(node);
#if VTREEVERBOSE
		printf(
				"[VocabTree::computeClustering] (level %d): got less cluster indices than clusters (%d features)\n",
				level, indices_length);
#endif
		return;
	}

#if DEBUG
#if VTREEVERBOSE
	printf("initCentroids - Start\n");
#endif
#endif

	cv::Mat dcenters(m_branching, m_veclen, m_dataset.type());
	for (int i = 0; i < centers_length; ++i) {
		m_dataset.row(centers_idx[i]).copyTo(
				dcenters(cv::Range(i, i + 1), cv::Range(0, m_veclen)));
	}

#if DEBUG
#if VTREEVERBOSE
	printf("initCentroids - End\n");
#endif
#endif

	std::vector<int> count(m_branching);
	for (int i = 0; i < m_branching; ++i) {
		count[i] = 0;
	}

#if DEBUG
#if VTREEVERBOSE
	printf("quantize - Start\n");
#endif
#endif

	std::vector<int> belongs_to(indices_length);
	std::vector<DistanceType> distance_to(indices_length);
	for (int i = 0; i < indices_length; ++i) {
		distance_to[i] = m_distance(
				(TDescriptor*) m_dataset.row(indices[i]).data,
				(TDescriptor*) dcenters.row(0).data, m_veclen);
		belongs_to[i] = 0;
		for (int j = 1; j < m_branching; ++j) {
			DistanceType new_sq_dist = m_distance(
					(TDescriptor*) m_dataset.row(indices[i]).data,
					(TDescriptor*) dcenters.row(j).data, m_veclen);
			if (distance_to[i] > new_sq_dist) {
				belongs_to[i] = j;
				distance_to[i] = new_sq_dist;
			}
		}
		++count[belongs_to[i]];
	}

#if DEBUG
#if VTREEVERBOSE
	printf("quantize - End\n");
#endif
#endif

	bool converged = false;
	int iteration = 0;
	while (converged == false && iteration < m_iterations) {
#if DEBUG
#if VTREEVERBOSE
		printf("iteration=[%d]\n", iteration);
#endif
#endif

		converged = true;
		++iteration;

#if DEBUG
#if VTREEVERBOSE
		printf("computeCentroids - Start\n");
#endif
#endif

		// Zeroing all the centroids dimensions
		dcenters = cv::Scalar::all(0);

		if (m_dataset.type() == CV_8U) {
			// Warning: using matrix of integers, there might be
			// an overflow when summing too much descriptors
			cv::Mat bitwiseCount(m_branching, m_veclen * 8,
					cv::DataType<int>::type);
			// Zeroing matrix of cumulative bits
			bitwiseCount = cv::Scalar::all(0);
			// Bitwise summing the data into each centroid
			for (int i = 0; i < indices_length; ++i) {
				int j = belongs_to[i];
				cv::Mat b = bitwiseCount.row(j);
				KMajority::cumBitSum(m_dataset.row(indices[i]), b);
			}
			// Bitwise majority voting
			for (int j = 0; j < m_branching; ++j) {
				cv::Mat centroid = dcenters.row(j);
				KMajority::majorityVoting(bitwiseCount.row(j), centroid,
						count[j]);
			}
		} else {
			// Accumulate data into its corresponding cluster accumulator
			for (int i = 0; i < indices_length; ++i) {
				for (unsigned int k = 0; k < m_veclen; ++k) {
					dcenters.at<TDescriptor>(belongs_to[i], k) += m_dataset.row(
							indices[i]).at<TDescriptor>(0, k);
				}
			}
			// Divide accumulated data by the number transaction assigned to the cluster
			for (int i = 0; i < m_branching; ++i) {
				if (count[i] != 0) {
					for (unsigned int k = 0; k < m_veclen; ++k) {
						dcenters.at<TDescriptor>(i, k) /= count[i];
					}
				}
			}
		}
#if DEBUG
#if VTREEVERBOSE
		printf("computeCentroids - End\n");
#endif
#endif

#if DEBUG
#if VTREEVERBOSE
		printf("quantize - Start\n");
#endif
#endif

		for (int i = 0; i < indices_length; ++i) {
			DistanceType sq_dist = m_distance(
					(TDescriptor*) m_dataset.row(indices[i]).data,
					(TDescriptor*) dcenters.row(0).data, m_veclen);
			int new_centroid = 0;
			for (int j = 1; j < m_branching; ++j) {
				DistanceType new_sq_dist = m_distance(
						(TDescriptor*) m_dataset.row(indices[i]).data,
						(TDescriptor*) dcenters.row(j).data, m_veclen);
				if (sq_dist > new_sq_dist) {
					new_centroid = j;
					sq_dist = new_sq_dist;
				}
			}
			if (new_centroid != belongs_to[i]) {
				--count[belongs_to[i]];
				++count[new_centroid];
				belongs_to[i] = new_centroid;
				distance_to[i] = sq_dist;

				converged = false;
			}
		}

#if DEBUG
#if VTREEVERBOSE
		printf("quantize - End\n");
#endif
#endif

#if DEBUG
#if VTREEVERBOSE
		printf("handleEmptyClusters - Start\n");
#endif
#endif

		// If some cluster appears to be empty then:
		// 1. Find the biggest cluster.
		// 2. Find farthest point in the biggest cluster
		// 3. Exclude the farthest point from the biggest cluster and form a new 1-point cluster.

		for (int k = 0; k < m_branching; ++k) {
			if (count[k] != 0) {
				continue;
			}

			// 1. Find the biggest cluster
			int max_k = 0;
			for (int k1 = 1; k1 < m_branching; ++k1) {
				if (count[max_k] < count[k1])
					max_k = k1;
			}

			// 2. Find farthest point in the biggest cluster
			DistanceType maxDist(-1);
			int idxFarthestPt = -1;
			for (int i = 0; i < indices_length; ++i) {
				if (belongs_to[i] == max_k) {
					if (maxDist < distance_to[i]) {
						maxDist = distance_to[i];
						idxFarthestPt = i;
					}
				}
			}

			// 3. Exclude the farthest point from the biggest cluster and form a new 1-point cluster
			--count[max_k];
			++count[k];
			belongs_to[idxFarthestPt] = k;
		}

#if DEBUG
#if VTREEVERBOSE
		printf("handleEmptyClusters - End\n");
#endif
#endif

	}

	TDescriptor** centers = new TDescriptor*[m_branching];

	for (int i = 0; i < m_branching; ++i) {
		centers[i] = new TDescriptor[m_veclen];
		for (size_t k = 0; k < m_veclen; ++k) {
			centers[i][k] = dcenters.at<TDescriptor>(i, k);
		}
	}

	// Compute k-means clustering for each of the resulting clusters
	node->children = new VocabTreeNodePtr[m_branching];
	int start = 0;
	int end = start;
	for (int c = 0; c < m_branching; ++c) {

#if VTREEVERBOSE
		printf(
				"[VocabTree::computeClustering] Clustering over resulting clusters, level=[%d] branch=[%d]\n",
				level, c);
#endif

		// Re-order indices by chunks in clustering order
		for (int i = 0; i < indices_length; ++i) {
			if (belongs_to[i] == c) {
				std::swap(indices[i], indices[end]);
				std::swap(belongs_to[i], belongs_to[end]);
				++end;
			}
		}

		node->children[c] = new VocabTreeNode<TDescriptor>();
		node->children[c]->center = centers[c];
		computeClustering(node->children[c], indices + start, end - start,
				level + 1, fitted);
		start = end;
	}

	dcenters.release();
	delete[] centers;
}

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

template<class TDescriptor, class Distance>
bool VocabTree<TDescriptor, Distance>::empty() const {
	return m_size == 0;
}

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

template<class TDescriptor, class Distance>
bool VocabTree<TDescriptor, Distance>::compareEqual(const VocabTreeNodePtr a,
		const VocabTreeNodePtr b) const {

#if DEBUG
#if VTREEVERBOSE
	printf("[VocabTree::compareEqual] Comparing tree roots\n");
#endif
#endif

	// Assert both nodes are interior or leaf nodes
	if ((a->children != NULL && b->children == NULL)
			|| (a->children == NULL && b->children != NULL)) {
		return false;
	}

	// At this point both nodes have none or some children,
	// hence valid nodes so we proceed to check the centers
	for (size_t k = 0; k < m_veclen; ++k) {
		// Might be necessary to check as well the type of pointer
		// i.e. both should be pointers to the same type
		if (a->center[k] != b->center[k]) {
			return false;
		}
	}

	if (a->children == NULL) {
		// Base case: both are leaf nodes since have no children
		return true;
	} else {
		// Recursion case: both are interior nodes
		for (size_t i = 0; (int) i < m_branching; ++i) {
			if (compareEqual(a->children[i], b->children[i]) == false) {
				return false;
			}
		}
	}

	return true;
}

template<class TDescriptor, class Distance>
bool VocabTree<TDescriptor, Distance>::operator==(
		const VocabTree<TDescriptor, Distance> &other) const {

	if (getVeclen() != other.getVeclen()
			|| getBranching() != other.getBranching()
			|| getDepth() != other.getDepth()) {
#if DEBUG
#if VTREEVERBOSE
		printf("[VocabTree::operator==] Vector length, branch factor or depth are not equal\n");
#endif
#endif
		return false;
	}

	if (compareEqual(getRoot(), other.getRoot()) == false) {
#if DEBUG
#if VTREEVERBOSE
		printf("[VocabTree::operator==] Tree is not equal\n");
#endif
#endif
		return false;
	}

	return true;
}

template<class TDescriptor, class Distance>
bool VocabTree<TDescriptor, Distance>::operator!=(
		const VocabTree<TDescriptor, Distance> &other) const {
	return !(*this == other);
}

} /* namespace vlr */

#endif /* VOCAB_TREE_H_ */


text:
/*!
 * Audio5js: HTML5 Audio Compatibility Layer
 * https://github.com/zohararad/audio5js
 * License MIT (c) Zohar Arad 2013
 */
(function ($win, ns, factory) {
  "use strict";
  /*global define */
  /*global swfobject */

  if (typeof (module) !== 'undefined' && module.exports) { // CommonJS
    module.exports = factory(ns, $win);
  } else if (typeof (define) === 'function' && define.amd) { // AMD
    define(function () {
      return factory(ns, $win);
    });
  } else { //


text:
"use strict";

// Friendly names of known service principals.
// TODO(davidben): Cross-realm?
// TODO(davidben): Move this to a config.js.
var SERVICES = { };
SERVICES["krbtgt/" + krb.realm + "@" + krb.realm] = {
  dangerous: true,
  desc: "Full access to your Athena account"
};
SERVICES["moira/moira7.mit.edu" + "@" + krb.realm] = {
  dangerous: true,
  desc: "View and modify your mailing lists and groups"
};
SERVICES["afs/athena.mit.edu" + "@" + krb.realm] = {
  dangerous: true,
  desc: "Full access to all your files on Athena"
};
SERVICES["zephyr/zephyr" + "@" + krb.realm] = {
  desc: "Send and receive zephyr notices as you"
};

function makeServiceNode(service) {
  var serviceStr = service.toString();

  var li = document.createElement("li");
  var abbr = document.createElement("abbr");
  li.appendChild(abbr);
  abbr.title = serviceStr;
  if (serviceStr in SERVICES) {
    var info = SERVICES[serviceStr];
    if (info.dangerous)
      li.className = "dangerous";
    $(abbr).text(info.desc);
  } else {
    // Label it "Access BLAH on your behalf".
    // (Okay, fine, dealing with the DOM directly can be annoying.)
    var target = document.createElement("code");
    var detail = null;
    target.className = "identifier";
    if (service.principalName.nameString.length === 2 &&
        service.principalName.nameString[0] === "host") {
      $(target).text(service.principalName.nameString[1]);
    } else if (service.principalName.nameString.length === 2 &&
               service.principalName.nameString[0] === "HTTP") {
      detail = document.createTextNode("web services on ");
      $(target).text(service.principalName.nameString[1]);
    } else {
      $(target).text(serviceStr);
    }
    abbr.appendChild(document.createTextNode("Access "));
    if (detail)
      abbr.appendChild(detail);
    abbr.appendChild(target);
    abbr.appendChild(document.createTextNode(" on your behalf"));
  }
  return li;
}

function registerTicketAPI() {
  WinChan.onOpen(function (origin, args, cb) {
    // NOTE: origin is a trusted value we get from the browser. args
    // is untrusted data from some other origin. It is absolutely
    // critical that we do not eval anything in there, including as
    // HTML. If attaching it to DOM, only use textContent and
    // equivalent APIs.

    // FIXME: ui.js should probably provide some sane API. Maybe a
    // logged in callback? I dunno. Really the UI flow should probably
    // be controlled by the page with ui.js or something similar just
    // providing the functions to actually create these things? I
    // dunno. This currently has silliness where, if onOpen gets
    // called after the UI is shown, placeholder values are visible.

    // Makes a principal, but is picky about types.
    function makePrincipal(principal, realm) {
      if (typeof realm !== "string")
        throw new TypeError();
      if (!(principal instanceof Array))
        throw new TypeError();
      principal.forEach(function(component) {
        if (typeof component !== "string")
          throw new TypeError();
      });
      return new krb.Principal({
        nameType: krb.KRB_NT_UNKNOWN,
        nameString: principal
      }, realm);
    }

    var services = [];
    var returnList = true;
    try {
      if (args.services) {
        if (!(args.services instanceof Array))
          throw TypeError();
        services = args.services.map(function(service) {
          return makePrincipal(service.principal, service.realm);
        });
        if (services.length == 0)
          throw Error();
      } else {
        services = [makePrincipal(args.principal, args.realm)];
        returnList = false;
      }
    } catch (e) {
      cb({
        status: "ERROR",
        code: "BAD_REQUEST",
        message: "Bad services argument."
      });
      throw e;
    }

    var user = null;
    if (args.user) {
      try {
        user = makePrincipal(args.user.principal, args.user.realm);
      } catch (e) {
        cb({
          status: "ERROR",
          code: "BAD_REQUEST",
          message: "Bad user argument."
        });
        throw e;
      }
    }

    function deny(code, message) {
      code = code || "NOT_ALLOWED";
      message = message || "The user did not approve the permission grant.";
      cb({
        status: "DENIED",
        code: code,
        message: message
      });
    }

    // Require everyone to use SSL. (Is there no better way to do this
    // check.) We'll want to allow things like chrome-extension:// in
    // future probably, though chrome-extension://aslkdfjsdlkfjdslkfs
    // is not a useful string. Also allow things running over
    // localhost. Overwise testing is a nightmare.
    if (!origin.startsWith("https:") &&
        !origin.startsWith("http://localhost:") &&
        !origin.startsWith("http://127.0.0.1:")) {
        deny("BAD_ORIGIN", "Site must be under SSL or hosted on localhost.");
        return;
    }

    getTGTSession().then(function(r) {
        var tgtSession = r[0], prompted = r[1];

        if (user) {
          // If the caller requested a particular user, don't give
          // them back a mismatching principal.
          //
          // TODO(davidben): Be less confusing and use this to inform
          // the UI somehow. Multiple sign-on?
          if (tgtSession.client.realm != user.realm ||
              !krb.principalNamesEqual(tgtSession.client.principalName,
                                       user.principalName)) {
            cb({
              status: "DENIED",
              code: "WRONG_USER"
            });
            return;
          }
        }

        var authed = $('#request-ticket-template').children().clone();
        authed.appendTo(document.body);
        if (prompted)
            authed.fadeIn();

        authed.find('.client-principal').text(tgtSession.client.toString());
        authed.find('.foreign-origin').text(origin);
        var permissionList = authed.find('.permission-list');
        services.forEach(function(service) {
          permissionList.append(makeServiceNode(service));
        });
        authed.find('.service-principal').text(
          services.map(function(service) {
            return service.toString(); }).join(', '));

        authed.find('.request-ticket-deny').click(function() { deny() });
        authed.find('.request-ticket-allow').click(function(e) {
            // None of these errors should really happen. Ideally this
            // file would be in control of the UI and this event
            // listener would only be hooked up when we've got a valid
            // tgtSession.
            if (!localStorage.getItem("tgtSession")) {
                log('No ticket');
                deny();
                return;
            }

            if (tgtSession.isExpired()) {
                // I guess this is actually possible if the ticket
                // expires while this user is deliberating.
                log('Ticket expired');
                deny();
                return;
            }

            // User gave us permission and we have a legit TGT. Let's go!
            Q.all(services.map(function(service) {
              return KDC.getServiceSession(tgtSession, service);
            })).then(function(sessions) {
              // TODO: Do we want to store this in the ccache
              // too, so a service which doesn't cache its own
              // tickets needn't get new ones all the time?
              // Also, the ccache needs some fancy abstraction
              // or something.
              if (returnList) {
                cb({
                  status: 'OK',
                  sessions: sessions.map(function(session) {
                    return session.toDict();
                  })
                });
              } else {
                cb({
                  status: 'OK',
                  session: sessions[0].toDict()
                });
              }
            }, function (error) {
              // TODO(davidben): This is an internal error. We
              // shouldn't close just yet.
              log(error);
              deny();
            }).done();
        });
    }).done();
  });
}


text:
package ru.job4j.list;

/**
 * @author Vitaly Zubov (mailto:Zubov.VP@yandex.ru).
 * @version $Id$
 * @since 0.1
 */
public interface List<E> {
    int size();
    boolean add(E e);
    E get(int index) throws NoSuchFieldException;
}


text:
static jmp_buf buf;

int main(int argc, const char *argv[])
{
	int ret = setjmp(buf);
	if (ret)
		printf("returned from setjmp: %d\n", ret);
	else
	{
		printf("Going to call longjmp\n");
		longjmp(buf, 17);
	}

	return 0;
}

// CHECK: Going to call longjmp
// CHECK: returned from setjmp: 17


text:
package com.tvd12.ezyfox.database.mapservice;

public interface EzyCheckContainService<K, V> {

    boolean containsKey(K key);

    boolean containsValue(V value);
}


text:
<?php namespace Anomaly\PostsModule\Post;

use Anomaly\PostsModule\Post\Contract\PostInterface;
use Anomaly\Streams\Platform\View\ViewTemplate;

/**
 * Class PostLoader
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\PostsModule\Post
 */
class PostLoader
{

    /**
     * The template data.
     *
     * @var ViewTemplate
     */
    protected $template;

    /**
     * Create a new PostLoader instance.
     *
     * @param ViewTemplate $template
     */
    public function __construct(ViewTemplate $template)
    {
        $this->template = $template;
    }

    /**
     * Load post data to the template.
     *
     * @param PostInterface $post
     */
    public function load(PostInterface $post)
    {
        $this->template->set('title', $post->getTitle());
        $this->template->set('meta_title', $post->metaTitle());
        $this->template->set('meta_keywords', $post->metaKeywords());
        $this->template->set('meta_description', $post->metaDescription());
    }
}


text:
package org.semanticweb.elk.reasoner.saturation.rules.backwardlinks;

import org.semanticweb.elk.reasoner.saturation.conclusions.model.BackwardLink;
import org.semanticweb.elk.reasoner.saturation.context.ContextPremises;
import org.semanticweb.elk.reasoner.saturation.rules.ClassInferenceProducer;

/**
 * A visitor pattern for {@link LinkedBackwardLinkRule}s
 *
 * @author "Yevgeny Kazakov"
 *
 * @param <O>
 *            the type of output parameter with which this visitor works
 */
public interface LinkedBackwardLinkRuleVisitor<O> {

	O visit(ContradictionOverBackwardLinkRule rule, BackwardLink premise,
			ContextPremises premises, ClassInferenceProducer producer);

	O visit(BackwardLinkChainFromBackwardLinkRule rule, BackwardLink premise,
			ContextPremises premises, ClassInferenceProducer producer);

}


text:
import unittest

from mongokit.schema_document import *
from mongokit import Document, Connection

class TypesTestCase(unittest.TestCase):

    def setUp(self):
        self.connection = Connection()
        self.col = self.connection['test']['mongokit']

    def tearDown(self):
        self.connection.drop_database('test')

    def test_authorized_type(self):
       for auth_type in SchemaDocument.authorized_types:
            if auth_type is dict:
                auth_type = {}
            class MyDoc(SchemaDocument):
                structure = { "foo":auth_type }
            if type(auth_type) is dict:
                assert MyDoc() == {"foo":{}}, MyDoc()
            elif auth_type is list:
                assert MyDoc() == {"foo":[]}
            else:
                assert MyDoc() == {"foo":None}, auth_type

    def test_not_authorized_type(self):
        for unauth_type in [set]:
            failed = False
            try:
                class MyDoc(SchemaDocument):
                    structure = { "foo":[unauth_type] }
            except StructureError, e:
                self.assertEqual(str(e), "MyDoc: %s is not an authorized type" % unauth_type)
                failed = True
            self.assertEqual(failed, True)
            failed = False
            try:
                class MyDoc(SchemaDocument):
                    structure = { "foo":(unauth_type) }
            except StructureError, e:
                self.assertEqual(str(e), "MyDoc: %s is not an authorized type" % unauth_type)
                failed = True
            self.assertEqual(failed, True)
            failed = False
            try:
                class MyDoc2(SchemaDocument):
                    structure = { 'foo':[{int:unauth_type }]}
            except StructureError, e:
                self.assertEqual(str(e), "MyDoc2: %s is not an authorized type" % unauth_type)
                failed = True
            self.assertEqual(failed, True)
            failed = False
            try:
                class MyDoc3(SchemaDocument):
                    structure = { 'foo':[{unauth_type:int }]}
            except AuthorizedTypeError, e:
                self.assertEqual(str(e), "MyDoc3: %s is not an authorized type" % unauth_type)
                failed = True
            self.assertEqual(failed, True)

        failed = False
        try:
            class MyDoc4(SchemaDocument):
                structure = {1:unicode}
        except StructureError, e:
            self.assertEqual(str(e), "MyDoc4: 1 must be a basestring or a type")
            failed = True
        self.assertEqual(failed, True)

    def test_type_from_functions(self):
        from datetime import datetime
        class MyDoc(SchemaDocument):
            structure = {
                "foo":datetime,
            }
        assert MyDoc() == {"foo":None}, MyDoc()
        mydoc = MyDoc()
        mydoc['foo'] = datetime.now()
        mydoc.validate()

    def test_non_typed_list(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":[]
            }
        mydoc = MyDoc()
        mydoc.validate()
        assert mydoc['foo'] == []
        mydoc['foo'] = [u"bla", 23]
        mydoc.validate()
        mydoc['foo'] = [set([1,2]), "bla"]
        self.assertRaises(AuthorizedTypeError, mydoc.validate)
        mydoc['foo'] = u"bla"
        self.assertRaises(SchemaTypeError, mydoc.validate)

#        class MyDoc(SchemaDocument):
#            structure = {
#                "foo":list
#            }
#        mydoc = MyDoc()
#        mydoc.validate()
#        assert mydoc['foo'] == []
#        mydoc['foo'] = [u"bla", 23]
#        mydoc.validate()
#        mydoc['foo'] = [set([1,2]), "bla"]
#        self.assertRaises(AuthorizedTypeError, mydoc.validate)

    def test_typed_list(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":[int]
            }
        mydoc = MyDoc()
        mydoc.validate()
        assert mydoc['foo'] == []
        mydoc['foo'] = [1,2,3]
        mydoc.validate()
        mydoc['foo'] = [u"bla"]
        self.assertRaises(SchemaTypeError, mydoc.validate)

    def test_typed_list_with_dict(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":[{unicode:int}]
            }
        mydoc = MyDoc()
        mydoc['foo'] = [{u"bla":1},{u"ble":2}]
        mydoc.validate()
        mydoc['foo'] = [{u"bla":u"bar"}]
        self.assertRaises(SchemaTypeError, mydoc.validate)

    def test_typed_list_with_list(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":[[unicode]]
            }
        mydoc = MyDoc()
        mydoc['foo'] = [[u"bla",u"blu"],[u"ble",u"bli"]]
        mydoc.validate()
        mydoc['foo'] = [[u"bla",1]]
        self.assertRaises(SchemaTypeError, mydoc.validate)

    def test_typed_tuple(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":(int, unicode, float)
            }
        mydoc = MyDoc()
        mydoc.validate()
        assert mydoc['foo'] == [None, None, None]
        mydoc['foo'] = [u"bla", 1, 4.0]
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = [1, u"bla"]
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = u"bla"
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = [1,u'bar',3.2]
        mydoc.validate()
        mydoc['foo'] = [None, u"bla", 3.1]
        mydoc.validate()
        mydoc['foo'][0] = 50
        mydoc.validate()

    def test_nested_typed_tuple(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":{'bar':(int, unicode, float)}
            }
        mydoc = MyDoc()
        mydoc.validate()
        assert mydoc['foo']['bar'] == [None, None, None]
        mydoc['foo']['bar'] = [u"bla", 1, 4.0]
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo']['bar'] = [1, u"bla"]
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo']['bar'] = [1,u'bar',3.2]
        mydoc.validate()
        mydoc['foo']['bar'] = [None, u"bla", 3.1]
        mydoc.validate()
        mydoc['foo']['bar'][0] = 50
        mydoc.validate()

    def test_saving_tuple(self):
        class MyDoc(Document):
            structure = { 'foo': (int, unicode, float) }
        self.connection.register([MyDoc])

        mydoc = self.col.MyDoc()
        assert mydoc == {'foo': [None, None, None]}, mydoc
        mydoc['foo'] = (1, u'a', 1.1) # note that this will be converted to list
        assert mydoc == {'foo': (1, u'a', 1.1000000000000001)}, mydoc
        mydoc.save()
        mydoc = self.col.find_one()

        class MyDoc(Document):
            structure = {'foo':[unicode]}
        self.connection.register([])
        self.connection.register([MyDoc])
        mydoc = self.col.MyDoc()
        mydoc['foo'] = (u'bla', u'bli', u'blu', u'bly')
        mydoc.save()
        mydoc = self.col.get_from_id(mydoc['_id'])

    def test_nested_typed_tuple_in_list(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":{'bar':[(int, unicode, float)]}
            }
        mydoc = MyDoc()
        mydoc.validate()
        assert mydoc == {'foo': {'bar': []}}
        mydoc['foo']['bar'].append([u"bla", 1, 4.0])
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo']['bar'] = []
        mydoc['foo']['bar'].append([1, u"bla"])
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo']['bar'] = []
        mydoc['foo']['bar'].append([1,u'bar',3.2])
        mydoc.validate()
        mydoc['foo']['bar'].append([None, u"bla", 3.1])
        mydoc.validate()
        mydoc['foo']['bar'][1][0] = 50
        mydoc.validate()

    def test_dict_unicode_typed_list(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":{unicode:[int]}
            }
        mydoc = MyDoc()
        mydoc['foo'] = {u"bar":[1,2,3]}
        mydoc.validate()
        mydoc['foo'] = {u"bar":[u"bla"]}
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = {3:[1,2,3]}
        self.assertRaises(SchemaTypeError, mydoc.validate)

    def test_with_custom_object(self):
        class MyDict(dict):
            pass
        class MyDoc(SchemaDocument):
            structure = {
                "foo":{unicode:int}
            }
        mydoc = MyDoc()
        mydict = MyDict()
        mydict[u"foo"] = 3
        mydoc["foo"] = mydict
        mydoc.validate()

    def test_custom_object_as_type(self):
        class MyDict(dict):
            pass
        class MyDoc(SchemaDocument):
            structure = {
                "foo":MyDict({unicode:int})
            }
        mydoc = MyDoc()
        mydict = MyDict()
        mydict[u"foo"] = 3
        mydoc["foo"] = mydict
        mydoc.validate()
        mydoc['foo'] = {u"foo":"7"}
        self.assertRaises(SchemaTypeError, mydoc.validate)

        class MyInt(int):
            pass
        class MyDoc(SchemaDocument):
            structure = {
                "foo":MyInt,
            }
        mydoc = MyDoc()
        mydoc["foo"] = MyInt(3)
        mydoc.validate()
        mydoc['foo'] = 3
        self.assertRaises(SchemaTypeError, mydoc.validate)

    def test_list_instead_of_dict(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":{unicode:[unicode]}
            }
        mydoc = MyDoc()
        mydoc['foo'] = [u'bla']
        self.assertRaises(SchemaTypeError, mydoc.validate)

    def _test_big_nested_example(self):
        # XXX TODO
        class MyDoc(SchemaDocument):
            structure = {
                "foo":{unicode:[int], u"bar":{"spam":{int:[unicode]}}},
                "bla":{"blo":{"bli":[{"arf":unicode}]}},
            }
        mydoc = MyDoc()
        mydoc['foo'].update({u"bir":[1,2,3]})
        mydoc['foo'][u'bar'][u'spam'] = {1:[u'bla', u'ble'], 3:[u'foo', u'bar']}
        mydoc.validate()
        mydoc['bla']['blo']['bli'] = [{u"bar":[u"bla"]}]
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['bla']['blo']['bli'] = [{u"arf":[1]}]
        self.assertRaises(SchemaTypeError, mydoc.validate)

    def test_adding_custom_type(self):
        class MyDoc(SchemaDocument):
            structure = {
                "foo":str,
            }
            authorized_types = SchemaDocument.authorized_types + [str]
        mydoc = MyDoc()

    def test_schema_operator(self):
        from mongokit.operators import SchemaOperator
        class OP(SchemaOperator):
            repr = "op"
        op = OP()
        self.assertRaises(NotImplementedError, op.validate, "bla")

    def test_or_operator(self):
        from mongokit import OR
        assert repr(OR(unicode, str)) == "<unicode or str>"

        failed = False
        try:
            class BadMyDoc(SchemaDocument):
                structure = {"bla":OR(unicode,str)}
        except StructureError, e:
            self.assertEqual(str(e), "BadMyDoc: <type 'str'> in <unicode or str> is not an authorized type (type found)")
            failed = True
        self.assertEqual(failed, True)

        from datetime import datetime
        class MyDoc(SchemaDocument):
            structure = {
                "foo":OR(unicode,int),
                "bar":OR(unicode, datetime),
                "foobar": OR(basestring, int),
            }

        mydoc = MyDoc()
        assert str(mydoc.structure['foo']) == '<unicode or int>'
        assert str(mydoc.structure['bar']) == '<unicode or datetime>'
        assert str(mydoc.structure['foobar']) == '<basestring or int>'
        assert mydoc == {'foo': None, 'bar': None, 'foobar': None}
        mydoc['foo'] = 3.0
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = u"foo"
        mydoc.validate()
        mydoc['foo'] = 3
        mydoc.validate()
        mydoc['foo'] = 'bar'
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = datetime.now()
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = u"foo"
        mydoc['bar'] = datetime.now()
        mydoc.validate()
        mydoc['bar'] = u"today"
        mydoc.validate()
        mydoc['bar'] = 25
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['bar'] = u"bar"
        mydoc["foo"] = u"foo"
        mydoc["foobar"] = "foobar"
        mydoc.validate()
        mydoc["foobar"] = datetime.now()
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc["foobar"] = 3
        mydoc.validate()

    def test_not_operator(self):
        from mongokit import NOT
        failed = False
        try:
            class BadMyDoc(SchemaDocument):
                structure = {"bla":NOT(unicode,str)}
        except StructureError, e:
            self.assertEqual(str(e), "BadMyDoc: <type 'str'> in <not unicode, not str> is not an authorized type (type found)")
            failed = True
        self.assertEqual(failed, True)

        from datetime import datetime
        class MyDoc(SchemaDocument):
            structure = {
                "foo":NOT(unicode,int),
                "bar":NOT(datetime),
                "foobar": NOT(basestring)
            }

        mydoc = MyDoc()
        assert str(mydoc.structure['foo']) == '<not unicode, not int>', str(mydoc.structure['foo'])
        assert str(mydoc.structure['bar']) == '<not datetime>'
        assert str(mydoc.structure['foobar']) == '<not basestring>'
        assert mydoc == {'foo': None, 'bar': None, 'foobar': None}
        assert mydoc['foo'] is None
        assert mydoc['bar'] is None
        assert mydoc['foobar'] is None
        mydoc['foo'] = 3
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = u"foo"
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = 3.0
        mydoc.validate()
        mydoc['foo'] = datetime.now()
        mydoc.validate()

        mydoc['bar'] = datetime.now()
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['bar'] = u"today"
        mydoc.validate()
        mydoc['bar'] = 25
        mydoc.validate()
        mydoc['foobar'] = 'abc'
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foobar'] = 1
        mydoc.validate()

    def test_is_operator(self):
        from mongokit import IS
        failed = False
        try:
            class BadMyDoc(SchemaDocument):
                structure = {"bla":IS('bla',3)}
        except StructureError, e:
            self.assertEqual(str(e), "BadMyDoc: bla in <is 'bla' or is 3> is not an authorized type (str found)")
            failed = True
        self.assertEqual(failed, True)

        from datetime import datetime
        class MyDoc(SchemaDocument):
            structure = {
                "foo":IS(u'spam',u'eggs'),
                "bar":IS(u'3', 3)
            }

        mydoc = MyDoc()
        assert str(mydoc.structure['foo']) == "<is u'spam' or is u'eggs'>"
        assert str(mydoc.structure['bar']) == "<is u'3' or is 3>"
        assert mydoc == {'foo': None, 'bar': None}
        assert mydoc['foo'] is None
        assert mydoc['bar'] is None
        mydoc['foo'] = 3
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = u"bla"
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = datetime.now()
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = u"spam"
        mydoc.validate()
        mydoc['foo'] = u"eggs"
        mydoc.validate()

        mydoc['bar'] = datetime.now()
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['bar'] = u"today"
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['bar'] = 'foo'
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['bar'] = 3
        mydoc.validate()
        mydoc['bar'] = u"3"
        mydoc.validate()

    def test_subclassed_type(self):
        """
        accept all subclass of supported type
        """
        class CustomFloat(float):
            def __init__(self, float):
                self = float + 2
        class MyDoc(SchemaDocument):
            structure = {
                "foo":float,
            }
        mydoc = MyDoc()
        mydoc['foo'] = CustomFloat(4)
        mydoc.validate()

    def test_set_type(self):
        from mongokit import Set
        class MyDoc(Document):
            structure = {
                "tags":Set(int),
            }

        self.connection.register([MyDoc])
        mydoc = self.col.MyDoc()
        mydoc['tags'] = set(["1","1","2","3","4"])
        self.assertRaises(ValueError, mydoc.validate)
        mydoc['tags'] = set([1,1,2,3,4])
        mydoc.save()

        doc = self.col.MyDoc.find_one()
        assert doc['tags'] == set([1,2,3,4]), doc['tags']

    def test_set_type2(self):
        class MyDoc(Document):
                structure = {
                        'title':unicode,
                        'category':Set(unicode)
                }
                required_fields=['title']
        self.connection.register([MyDoc])
        doc = self.col.MyDoc()
        print doc # {'category': set([]), 'title': None}
        assert isinstance(doc['category'], set)
        try:
                doc.validate()
        except RequireFieldError as e:
                print e # title is required

        print doc # {'category': [], 'title': None}
        assert isinstance(doc['category'], set)
        doc['title']=u'hello'
        doc.validate()

    def test_int_type(self):
        @self.connection.register
        class MyDoc(Document):
            structure = {
                "foo":int,
            }

        mydoc = self.col.MyDoc()
        mydoc['foo'] = ''
        self.assertRaises(SchemaTypeError, mydoc.validate)
        mydoc['foo'] = 10
        mydoc.save()

    def test_uuid_type(self):
        import uuid
        @self.connection.register
        class MyDoc(Document):
            structure = {
                'uuid': uuid.UUID,
            }
        uid = uuid.uuid4()
        obj = self.col.MyDoc()
        obj['uuid'] = uid
        obj.save()

        assert isinstance(self.col.MyDoc.find_one()['uuid'], uuid.UUID)

    def test_binary_with_str_type(self):
        import bson
        @self.connection.register
        class MyDoc(Document):
            structure = {
                'my_binary': basestring,
            }
        obj = self.col.MyDoc()
        # non-utf8 string
        non_utf8 = "\xFF\xFE\xFF";
        obj['my_binary'] = non_utf8

        self.assertRaises(bson.errors.InvalidStringData, obj.validate)

    def test_binary_with_unicode_type(self):
        import bson
        @self.connection.register
        class MyDoc(Document):
            structure = {
                'my_binary': unicode,
            }
        obj = self.col.MyDoc()
        # non-utf8 string
        non_utf8 = "\xFF\xFE\xFF";
        obj['my_binary'] = non_utf8

        self.assertRaises(bson.errors.InvalidStringData, obj.validate)

    def test_binary_with_binary_type(self):
        import bson
        @self.connection.register
        class MyDoc(Document):
            structure = {
                'my_binary': bson.binary.Binary,
            }
        obj = self.col.MyDoc()
        # non-utf8 string
        non_utf8 = "\xFF\xFE\xFF";
        bin_obj = bson.binary.Binary(non_utf8)
        obj['my_binary'] = bin_obj
        obj.save()

        self.assertEquals(self.col.MyDoc.find_one()['my_binary'], bin_obj)


text:
from openerp import SUPERUSER_ID
from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.addons.website.models.website import unslug

class WebsitePartnerPage(http.Controller):

    # Do not use semantic controller due to SUPERUSER_ID
    @http.route(['/partners/<partner_id>'], type='http', auth="public", website=True)
    def partners_detail(self, partner_id, **post):
        _, partner_id = unslug(partner_id)
        if partner_id:
            partner = request.registry['res.partner'].browse(request.cr, SUPERUSER_ID, partner_id, context=request.context)
            is_website_publisher = request.registry['res.users'].has_group(request.cr, request.uid, 'base.group_website_publisher')
            if partner.exists() and (partner.website_published or is_website_publisher):
                values = {
                    'main_object': partner,
                    'partner': partner,
                    'edit_page': False
                }
                return request.website.render("website_partner.partner_page", values)
        return request.not_found()


text:
<?php

namespace Hcode;

class Model {

	private $values = [];

	public function __call($name, $args)
	{

		$method = substr($name, 0, 3);
		$fieldName = substr($name, 3, strlen($name));

		switch ($method)
		{

			case "get":
				return (isset($this->values[$fieldName])) ? $this->values[$fieldName] : NULL;
			break;

			case "set":
				$this->values[$fieldName] = $args[0];
			break;

		}

	}

	public function setData($data = array())
	{

		foreach ($data as $key => $value) {

			$this->{"set".$key}($value);

		}

	}

	public function getValues()
	{

		return $this->values;

	}

}

 ?>


text:
from uuid import uuid4
from traceback import format_exc
from sys import stdout
import logging

class TransactionManager:

    def __init__(self):
        self.transactions = []

    def __begin_transaction(self, cursor):
        cursor.execute('BEGIN;')
        return (cursor, uuid4())

    def __prepare_transaction(self, transaction):
        cursor, transaction_id = transaction
        cursor.execute('PREPARE TRANSACTION \'%s\';'%transaction_id)
        logging.info('Prepared transaction %s'%transaction_id)
        self.transactions.append(transaction)

    def __add_queries(self, cursor, queries):
        transaction = self.__begin_transaction(cursor)
        for q in queries:
            cursor.execute(q)
        self.__prepare_transaction(transaction)

    def add_transaction(self, cursor, queries):
        try:
            self.__add_queries(cursor, queries)
        except Exception as e:
            cursor.execute("rollback;")
            logging.warning(format_exc())
            self.rollback_transactions()
            raise e

    def commit_transactions(self):
        for cursor, transaction_id in self.transactions:
            logging.info('Commiting %s'%transaction_id)
            cursor.execute('COMMIT PREPARED \'%s\';'%transaction_id)

    def rollback_transactions(self):
        for cursor, transaction_id in self.transactions:
            logging.info('Rolling back %s'%transaction_id)
            cursor.execute('ROLLBACK PREPARED \'%s\';'%transaction_id)
        self.transactions = []


text:
const fs = require('fs-extra');
const ng = require('../helpers/ng');
const existsSync = require('exists-sync');
const expect = require('chai').expect;
const forEach = require('lodash/forEach');
const walkSync = require('walk-sync');
const Blueprint = require('angular-cli/ember-cli/lib/models/blueprint');
const path = require('path');
const tmp = require('../helpers/tmp');
const root = process.cwd();
const util = require('util');
const EOL = require('os').EOL;
const SilentError = require('silent-error');

describe('Acceptance: ng new', function () {
  beforeEach(function () {
    return tmp.setup('./tmp').then(function () {
      process.chdir('./tmp');
    });
  });

  afterEach(function () {
    this.timeout(10000);

    return tmp.teardown('./tmp');
  });

  function confirmBlueprintedForDir(dir) {
    return function () {
      let blueprintPath = path.join(root, dir, 'files');
      let expected = walkSync(blueprintPath);
      let actual = walkSync('.').sort();
      let directory = path.basename(process.cwd());

      forEach(Blueprint.renamedFiles, function (destFile, srcFile) {
        expected[expected.indexOf(srcFile)] = destFile;
      });

      expected.forEach(function (file, index) {
        expected[index] = file.replace(/__name__/g, 'angular-cli');
      });

      expected.sort();

      expect(directory).to.equal('foo');
      expect(expected).to.deep.equal(
        actual,
        EOL + ' expected: ' + util.inspect(expected) + EOL + ' but got: ' + util.inspect(actual));

    };
  }

  function confirmBlueprinted() {
    return confirmBlueprintedForDir('blueprints/ng2');
  }

  it('requires a valid name (!)', () => {
    return ng(['new', '!', '--skip-npm', '--skip-git', '--inline-template'])
      .then(() => { throw new Error(); }, () => {});
  });
  it('requires a valid name (abc-.)', () => {
    return ng(['new', 'abc-.', '--skip-npm', '--skip-git', '--inline-template'])
      .then(() => { throw new Error(); }, () => {});
  });
  it('requires a valid name (abc-)', () => {
    return ng(['new', 'abc-', '--skip-npm', '--skip-git', '--inline-template'])
      .then(() => { throw new Error(); }, () => {});
  });
  it('requires a valid name (abc-def-)', () => {
    return ng(['new', 'abc-def-', '--skip-npm', '--skip-git', '--inline-template'])
      .then(() => { throw new Error(); }, () => {});
  });
  it('requires a valid name (abc-123)', () => {
    return ng(['new', 'abc-123', '--skip-npm', '--skip-git', '--inline-template'])
      .then(() => { throw new Error(); }, () => {});
  });
  it('requires a valid name (abc)', () => {
    return ng(['new', 'abc', '--skip-npm', '--skip-git', '--inline-template']);
  });
  it('requires a valid name (abc-def)', () => {
    return ng(['new', 'abc-def', '--skip-npm', '--skip-git', '--inline-template']);
  });

  it('ng new foo, where foo does not yet exist, works', function () {
    return ng(['new', 'foo', '--skip-npm']).then(confirmBlueprinted);
  });

  it('ng new with empty app does throw exception', function () {
    expect(ng(['new', ''])).to.throw;
  });

  it('ng new without app name does throw exception', function () {
    expect(ng(['new', ''])).to.throw;
  });

  it('ng new with app name creates new directory and has a dasherized package name', function () {
    return ng(['new', 'FooApp', '--skip-npm', '--skip-git']).then(function () {
      expect(!existsSync('FooApp'));

      const pkgJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));
      expect(pkgJson.name).to.equal('foo-app');
    });
  });

  it('ng new has a .editorconfig file', function () {
    return ng(['new', 'FooApp', '--skip-npm', '--skip-git']).then(function () {
      expect(!existsSync('FooApp'));

      const editorConfig = fs.readFileSync('.editorconfig', 'utf8');
      expect(editorConfig).to.exist;
    });
  });

  it('Cannot run ng new, inside of angular-cli project', function () {
    return ng(['new', 'foo', '--skip-npm', '--skip-git'])
      .then(function () {
        return ng(['new', 'foo', '--skip-npm', '--skip-git']).then(() => {
          throw new SilentError('Cannot run ng new, inside of angular-cli project should fail.');
        }, () => {
          expect(!existsSync('foo'));
        });
      })
      .then(confirmBlueprinted);
  });

  it('ng new without skip-git flag creates .git dir', function () {
    return ng(['new', 'foo', '--skip-npm']).then(function () {
      expect(existsSync('.git'));
    });
  });

  it('ng new with --dry-run does not create new directory', function () {
    return ng(['new', 'foo', '--dry-run']).then(function () {
      const cwd = process.cwd();
      expect(cwd).to.not.match(/foo/, 'does not change cwd to foo in a dry run');
      expect(!existsSync(path.join(cwd, 'foo')), 'does not create new directory');
      expect(!existsSync(path.join(cwd, '.git')), 'does not create git in current directory');
    });
  });

  it('ng new with --directory uses given directory name and has correct package name', function () {
    return ng(['new', 'foo', '--skip-npm', '--skip-git', '--directory=bar'])
      .then(function () {
        const cwd = process.cwd();
        expect(cwd).to.not.match(/foo/, 'does not use app name for directory name');
        expect(!existsSync(path.join(cwd, 'foo')), 'does not create new directory with app name');

        expect(cwd).to.match(/bar/, 'uses given directory name');
        expect(existsSync(path.join(cwd, 'bar')), 'creates new directory with specified name');

        const pkgJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));
        expect(pkgJson.name).to.equal('foo', 'uses app name for package name');
      });
  });

  it('ng new --inline-template does not generate a template file', () => {
    return ng(['new', 'foo', '--skip-npm', '--skip-git', '--inline-template'])
      .then(() => {
        const templateFile = path.join('src', 'app', 'app.component.html');
        expect(existsSync(templateFile)).to.equal(false);
      });
  });

  it('ng new --inline-style does not gener a style file', () => {
    return ng(['new', 'foo', '--skip-npm', '--skip-git', '--inline-style'])
      .then(() => {
        const styleFile = path.join('src', 'app', 'app.component.css');
        expect(existsSync(styleFile)).to.equal(false);
      });
  });

  it('should skip spec files when passed --skip-tests', () => {
    return ng(['new', 'foo', '--skip-npm', '--skip-git', '--skip-tests'])
      .then(() => {
        const specFile = path.join('src', 'app', 'app.component.spec.ts');
        expect(existsSync(specFile)).to.equal(false);
      });
  });

});


text:
<?php
/**
 * Adapter to get the embed code from cadenaser.com
 */
namespace Embed\Adapters;

class Cadenaser extends Webpage implements AdapterInterface
{
    /**
     * {@inheritDoc}
     */
    public function getCode()
    {
        $dom = $this->request->getHtmlContent();

        foreach ($dom->getElementsByTagName('div') as $div) {
            if ($div->hasAttribute('class') && ($div->getAttribute('class') === 'llevatelo')) {
                $input = $div->getElementsByTagName('input');

                if ($input->length && $input->item(0)->hasAttribute('value')) {
                    return $input->item(0)->getAttribute('value');
                }
            }
        }
    }
}