text:
declare -a autojump_paths
autojump_paths=(
  $HOME/.autojump/etc/profile.d/autojump.zsh         # manual installation
  $HOME/.autojump/share/autojump/autojump.zsh        # manual installation
  $HOME/.nix-profile/etc/profile.d/autojump.sh       # NixOS installation
  /run/current-system/sw/share/autojump/autojump.zsh # NixOS installation
  /usr/share/autojump/autojump.zsh                   # Debian and Ubuntu package
  /etc/profile.d/autojump.zsh                        # manual installation
  /etc/profile.d/autojump.sh                         # Gentoo installation
  /usr/local/share/autojump/autojump.zsh             # FreeBSD installation
  /opt/local/etc/profile.d/autojump.sh               # macOS with MacPorts
  /usr/local/etc/profile.d/autojump.sh               # macOS with Homebrew (default)
)

for file in $autojump_paths; do
  if [[ -f "$file" ]]; then
    source "$file"
    found=1
    break
  fi
done

# if no path found, try Homebrew
if (( ! found && $+commands[brew] )); then
  file=$(brew --prefix)/etc/profile.d/autojump.sh
  if [[ -f "$file" ]]; then
    source "$file"
    found=1
  fi
fi

(( ! found )) && echo 'autojump script not found'

unset autojump_paths file found


text:
package com.redhat.consulting.fusequickstarts.karaf.osgi_ds.api;

public interface IHelloService {
    public String sayMessage();
    public String sayHello(String pName);
}

redpajama_set_name: RedPajamaGithub


text:
<?php

use Twig\Node\Node;

class_exists('Twig\Node\Node');

@trigger_error('Using the "Twig_Node" class is deprecated since Twig version 2.7, use "Twig\Node\Node" instead.', \E_USER_DEPRECATED);

if (false) {
    /** @deprecated since Twig 2.7, use "Twig\Node\Node" instead */
    class Twig_Node extends Node
    {
    }
}


text:
function [fTardinessFine_dollar, tAgentTardiness_hour] = resalloc_calc_tardi_fine(stSystemMasterConfig, stAgentJobInfo, tAgentJobDuration_hour)

tAgentRequiredDuration_sec = etime(stAgentJobInfo.atClockAgentJobDue.aClockYearMonthDateHourMinSec, ...
                                stAgentJobInfo.atClockAgentJobStart.aClockYearMonthDateHourMinSec);

tAgentTardiness_hour = tAgentJobDuration_hour - tAgentRequiredDuration_sec/3600;
if tAgentTardiness_hour < 0
    tAgentTardiness_hour = 0;
end

fTardinessFine_dollar = stAgentJobInfo.fLatePenalty_DollarPerFrame/stSystemMasterConfig.fTimeFrameUnitInHour * tAgentTardiness_hour;


text:
package org.apache.bookkeeper.stream.cli;

/**
 * Utils for commands.
 */
public final class Commands {

    private Commands() {}

    public static final String OP_INIT = "init";
    public static final String OP_CREATE = "create";
    public static final String OP_DELETE = "delete";
    public static final String OP_LIST = "list";
    public static final String OP_GET = "get";
    public static final String OP_DEL = "del";
    public static final String OP_PUT = "put";
    public static final String OP_INC = "inc";

}


text:
#!/usr/bin/php
<?php
/**
 * TYPO3ObsoleteMethods Class
 * By Bastian Bringenberg <mail@bastian-bringenberg.de>
 *
 * #########
 * # USAGE #
 * #########
 *
 * See Readme File
 *
 * ###########
 * # Licence #
 * ###########
 *
 * See License File
 *
 * ##############
 * # Repository #
 * ##############
 *
 * Fork me on GitHub
 * https://github.com/bbnetz/TYPO3ObsoleteMethods
 *
 *
 */

/**
 * Class TYPO3ObsoleteMethods
 * @author Bastian Bringenberg <mail@bastian-bringenberg.de>
 * @link https://github.com/bbnetz/TYPO3ObsoleteMethods
 *
 */
class TYPO3ObsoleteMethods {

	/**
	 * @var string $obsoleteList Location in the Wiki where all deprecated methods are located
	 */
	protected $obsoleteList = 'http://wiki.typo3.org/TYPO3_6.0_Extension_Migration_Tips';

	/**
	 * @var string $html the html from the wiki
	 */
	protected $html = null;

	/**
	 * @var array contains all obsolete static methods from the core in form ( per array entry ): array('class', 'methodName', 'informationText')
	 */
	protected $obsoleteStaticMethods = array();

	/**
	 * @var array contains all obsolete non static methods from the core in form ( per array entry ): array('class', 'methodName', 'informationText')
	 */
	protected $obsoleteNonStaticMethods = array();

	/**
	 * @var array $ignoredFiles list of files to ignore
	 */
	protected $ignoredFiles = array('README', 'readme', 'Changelog', 'ChangeLog','changelog');

	/**
	 * @var array $checkableExtensions containing all pathes to possible Extensions
	 */
	protected $checkableExtensions = array();

	/**
	 * @var boolean $searchNonStatic if set will also check for non static methods. Warning: not yet stable could show wrong informations
	 */
	protected $searchNonStatic = false;

	/**
	 * function __construct
	 * Constructor for TYPO3ObsoleteMethods
	 *
	 * @return void
	 */
	public function __construct() {
		$ops = getopt('',
			array(
				'',
				'instancesPath::',
				'extensionPath::',
				'ignoredFiles::',
				'searchNonStatic::',
			)
		);

		if(isset($ops['instancesPath']))
			$this->checkableExtensions = array_merge($this->checkableExtensions, $this->getExtensionPathesByInstance($ops['instancesPath']));

		if(isset($ops['extensionPath']))
			$this->checkableExtensions = array_merge($this->checkableExtensions, $this->getExtensionPathesFromExtensionList($ops['extensionPath']));

		if(isset($ops['ignoredFiles']))
			$this->ignoredFiles = array_merge($this->ignoredFiles, $this->getIgnoredFiles($ops['ignoredFiles']));

		if(isset($ops['searchNonStatic']))
			$this->searchNonStatic = true;

		if(count($this->checkableExtensions) == 0)
			die('No Extension to Check.');
	}

	/**
	 * function start
	 * Doing all the work
	 *
	 * @return void
	 */
	public function start() {
		$this->html = $this->getCurrentHTML($this->obsoleteList);
		$this->obsoleteStaticMethods = $this->fetchStaticMethodFromHTML($this->html);
		$this->obsoleteNonStaticMethods = $this->fetchNonStaticMethodFromHTML($this->html);
		$this->checkExtensions($this->checkableExtensions);
		$output = '';
		foreach($this->obsoleteStaticMethods as $ext ) {
			if($ext['used'])
				$output .= 'Static Method: '.$ext['class'].'::'.$ext['methodname'].' - '.$ext['note'].PHP_EOL;
		}
		foreach($this->obsoleteNonStaticMethods as $ext ) {
			if($ext['used'])
				$output .= 'NonStatic Method: '.$ext['class'].'::'.$ext['methodname'].' - '.$ext['note'].PHP_EOL;
		}
		if($output != '')
			echo PHP_EOL.PHP_EOL.PHP_EOL.'Helping hands for your obsolete methods:'.PHP_EOL.'========================================'.PHP_EOL;
		echo $output;
	}

	/**
	 * function getCurrentHTML
	 * Gets $url and creates HTMLString from it
	 *
	 * @param string $url to fetch the HTML from
	 * @return string the HTML from $url
	 */
	protected function getCurrentHTML($url) {
		return file_get_contents($url);
	}

	/**
	 * function fetchStaticMethodFromHTML
	 * Itterates trough the Tables of $this->obsoleteList and collects informations from the first Table
	 *
	 * @param string $html the html to check in
	 * @return array see $this->obsoleteStaticMethods for more informations
	 */
	protected function fetchStaticMethodFromHTML($html) {
		$array = array();
		preg_match_all('/
(.*?)<\/table>/sm', $html, $tables);
		preg_match_all('/
(.*?)<\/tr>/s', $tables[0][0], $rows);
		foreach($rows[1] as $number => $row) {
			if($number == 0 ) continue;
			$array[] = $this->buildSingleMethodEntryFromTableRow($row);
		}
		return $array;
	}

	/**
	 * function fetchNonStaticMethodFromHTML
	 * Itterates trough the Tables of $this->obsoleteList and collects informations from the second Table
	 *
	 * @param string $html the html to check in
	 * @return array see $this->obsoleteNonStaticMethods for more informations
	 */
	protected function fetchNonStaticMethodFromHTML($html) {
		$array = array();
		preg_match_all('/
(.*?)<\/table>/sm', $html, $tables);
		preg_match_all('/
(.*?)<\/tr>/s', $tables[0][1], $rows);
		foreach($rows[1] as $number => $row) {
			if($number == 0 ) continue;
			$array[] = $this->buildSingleMethodEntryFromTableRow($row);
		}
		return $array;
	}

	/**
	 * function buildSingleMethodEntryFromTableRow
	 * Gets a TD Row and returns as method struct
	 *
	 * @param string $row the table data row
	 * @return array $method a struct for the methods
	 */
	protected function buildSingleMethodEntryFromTableRow($row) {
		$method = array(
			'class' => '',
			'methodname' => '',
			'note' => '',
			'used' => false
			);
		$row = str_replace(array('>', '<'), array('>', '<'), $row);
		$tbs = explode('	', $row);
		$tbs[0] = str_replace(array('', '	'), array('', ''), $tbs[0]);
		$tbs[1] = str_replace(array('', '	'), array('', ''), $tbs[1]);
		$splitted_field = explode('::', $tbs[0]);
		$method['class'] = trim($splitted_field[0]);
		if(isset($splitted_field[1]))
			$method['methodname'] = trim($splitted_field[1]);
		$method['note'] = trim($tbs[1]);
		return $method;
	}

	/**
	 * function checkExtensions
	 * itterates trough $extensionList
	 *
	 * @param array $extensionList containing all pathes
	 * @return void
	 */
	protected function checkExtensions($extensionList) {
		foreach($extensionList as $extensionPath )
			$this->checkExtension($extensionPath);
	}

	/**
	 * function checkExtension
	 * checks the extension for obsolete static and non-static methods
	 * Echos on Error
	 *
	 * @param string $extensionPath The path to the extension
	 * @return void
	 */
	protected function checkExtension($extensionPath) {
		for($i = 0; $i < count($this->obsoleteStaticMethods) -1; $i++) {
			$filename = $this->php_grep($this->obsoleteStaticMethods[$i]['class'].'::'.$this->obsoleteStaticMethods[$i]['methodname'], $extensionPath);
			if($filename) {
				$filenames = explode(PHP_EOL, $filename);
					foreach($filenames as $filename) {
						if($filename !== '')
							echo 'StaticMethod: '.$this->obsoleteStaticMethods[$i]['class'].'::'.$this->obsoleteStaticMethods[$i]['methodname'].' in '.$filename.PHP_EOL;
					}
				$this->obsoleteStaticMethods[$i]['used'] = true;
			}
		}

		if($this->searchNonStatic)
			for($i = 0; $i < count($this->obsoleteStaticMethods) -1; $i++) {
				$error = $this->php_grep($this->obsoleteNonStaticMethods[$i]['class'], $extensionPath);
				if($filename = $this->php_grep($this->obsoleteNonStaticMethods[$i]['class'], $extensionPath)) {
					$filenames = explode(PHP_EOL, $filename);
					foreach($filenames as $filename)
						if(trim($filename) !== '')
							if(strpos(file_get_contents($filename), $this->obsoleteStaticMethods[$i]['methodname']) !== FALSE) {
								echo 'NonStaticMethod: '.$this->obsoleteStaticMethods[$i]['class'].'::'.$this->obsoleteStaticMethods[$i]['methodname'].' in '.$filename.PHP_EOL;
								$this->obsoleteNonStaticMethods[$i]['used'] = true;
							}
				}
			}
	}

	/**
	 * function php_grep
	 * works like grep -R
	 *
	 * @see http://www.cafewebmaster.com/search-text-files-recursively-php-grep
	 * @param string $q the search string
	 * @param string $path the path to check
	 * @return string the method and the path to the error
	 */
	protected function php_grep($q, $path){
		$fp = opendir($path);
		$ret = '';
		while($f = readdir($fp)){
			if($this->ignoreFile($f)) continue;
			if( preg_match('#^\.+$#', $f) ) continue; // ignore symbolic links
			$file_full_path = $path.DIRECTORY_SEPARATOR.$f;
			if(is_dir($file_full_path)) {
				$ret .= $this->php_grep($q, $file_full_path);
			} else if( stristr(file_get_contents($file_full_path), $q) ) {
				$ret .= $file_full_path.PHP_EOL;
			}
		}
		return $ret;
	}

	/**
	 * function ignoreFile
	 * Checks if $file is ignored
	 *
	 * @param string $file the file name to check
	 * @return boolean true if $file is ignored
	 */
	protected function ignoreFile($file) {
		return in_array($file, $this->ignoredFiles);
	}

	/**
	 * function getIgnoredFiles
	 * Separates the comma list and trims each entry
	 *
	 * @param string $ignoredFiles comma separated list of files
	 * @return array of trimmed files
	 */
	public function getIgnoredFiles($ignoredFiles) {
		$ignoredFiles = explode(',', $ignoredFiles);
		$files = array();
		foreach($ignoredFiles as $file) {
			$files[] = trim($file);
		}
		return $files;
	}

	/**
	 * function getExtensionPathesFromExtensionList
	 * Separates the comma list and trims each entry
	 *
	 * @param string $pathesList comma separated list of directories
	 * @return array of trimmed extensionPathes
	 */
	public function getExtensionPathesFromExtensionList($pathesList) {
		$pathesList = explode(',', $pathesList);
		$files = array();
		foreach($pathesList as $file) {
			$files[] = realpath(trim($file));
		}
		return $files;
	}

	/**
	 * function getExtensionPathesByInstance
	 * Gets all Extensions from $instancesList
	 *
	 * @param string $instancesList comma separated list of instances
	 * @return array of Extensions
	 */
	public function getExtensionPathesByInstance($instancesList) {
		$instancesList = explode(',', $instancesList);
		$files = array();
		foreach($instancesList as $file) {
			$files = array_merge($files, $this->getExtensionsFromSingleInstance(realpath(trim($file))));
		}
		return $files;
	}

	/**
	 * function getExtensionsFromSingleInstance
	 * Checks TYPO3 Instances to get all Extensions from it
	 *
	 * @param string $file a path to the TYPO3 instance
	 * @return array of Extensions
	 */
	public function getExtensionsFromSingleInstance($file) {
		if($file{strlen($file)-1} != DIRECTORY_SEPARATOR ) $file .= DIRECTORY_SEPARATOR;
		return glob($file.'typo3conf'.DIRECTORY_SEPARATOR.'ext'.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
	}

}

$typo3obsoletemethods = new TYPO3ObsoleteMethods();
$typo3obsoletemethods -> start();


text:
<accordion close-others="oneAtATime">

    <accordion-group
            ng-repeat="record in records | sortRecords"
            is-open="expanded"
            ng-controller="RecordCtrl"
            ng-click="setLocationHash()">
        <accordion-heading>

{{getTitle(record)}}

        </accordion-heading>

{{'configuration' | translate}}

{{'configurationDescription' | translate}}

{{getTitle(detail)}}

 0 && pages[page].inputTitle">{{pages[page].inputTitle | translate}}

                *
                {{getTitle(input)}}

 0 && pages[page].outputTitle">{{pages[page].outputTitle | translate}}

{{getTitle(output)}}

    </accordion-group>
</accordion>


text:
"""Sample plugin module for Igor"""
import requests
import os
import dhcpleases
import time

class DHCPPlugin:
    def __init__(self, igor, pluginName, pluginData):
        self.igor = igor
        self.pluginName = pluginName
        self.pluginData = pluginData

    def index(self, *args, **kwargs):
        return self.igor.app.raiseHTTPError("404 No index method for this plugin")

    def pull(self, token=None, callerToken=None):
        leaseFile = self.pluginData.get('leaseFile', '/var/lib/dhcp/dhcpd.leases')
        useArp = self.pluginData.get('useArp', True)
        usePing = self.pluginData.get('usePing', True)
        fields = self.pluginData.get('fields', 'client-hostname,hardware,ip-address,alive,arp,ping').split(',')

        with open(leaseFile) as fp:
            leases = dhcpleases.parse_leases_file(fp)
        activeLeases = dhcpleases.select_active_leases(leases, dhcpleases.timestamp_now())
        if usePing:
            activeLeases = dhcpleases.test_pingable(activeLeases)
        if useArp:
            activeLeases = dhcpleases.test_arp(activeLeases)
        if fields:
            activeLeases = dhcpleases.filter_keys(activeLeases, fields)

        data = dict(lease=activeLeases, lastActivity=time.time())
        path = 'sensors/%s' % self.pluginName
        rv = self.igor.databaseAccessor.put_key(path, 'application/x-python-object', None, data, 'application/x-python-object', token, replace=True)
        return 'ok\n'

def igorPlugin(igor, pluginName, pluginData):
    return DHCPPlugin(igor, pluginName, pluginData)


text:
function Polpetta(request, response) {

  var url = request.url;

  // immutable properties
  defineKnownProperty(this, "request", request);
  defineKnownProperty(this, "response", response);

  if (!invokedHtaccess.call(
    this,
    0,
    "onrequest",
    url
  )) {
    polpetta_redirect.call(this, url, true);
    pathname = this.url.pathname;
    defineNotConfigurableProperty(
      this, "path",
      pathname == WEB_SEP ?
        root :
        polpetta_resolve(
          decodeURIComponent(
            pathname
          )
        )
    );

    /* check url and resulting path
    console.log(url);
    console.log(pathname);
    console.log(this.path);
    //*/

    if (HIDDEN_FILE.test(pathname)) {
      return forbidden.call(this, stats);
    }

    // request.method switch helper
    ResponseSwitch.call(this);
  }

}

Polpetta.factory = function (request, response) {
  return new Polpetta(request, response);
};

// exports it in case someone would like to use it
freeze(this.Polpetta = Polpetta);


text:
import sys, os.path
from pdfdevice import PDFDevice, PDFTextDevice
from pdffont import PDFUnicodeNotDefined
from pdftypes import LITERALS_DCT_DECODE
from pdfcolor import LITERAL_DEVICE_GRAY, LITERAL_DEVICE_RGB
from layout import LTContainer, LTPage, LTText, LTLine, LTRect, LTCurve
from layout import LTFigure, LTImage, LTChar, LTTextLine
from layout import LTTextBox, LTTextBoxVertical, LTTextGroup
from utils import apply_matrix_pt, mult_matrix
from utils import enc, bbox2str, create_bmp

##  PDFLayoutAnalyzer
##
class PDFLayoutAnalyzer(PDFTextDevice):

    def __init__(self, rsrcmgr, pageno=1, laparams=None):
        PDFTextDevice.__init__(self, rsrcmgr)
        self.pageno = pageno
        self.laparams = laparams
        self._stack = []
        return

    def begin_page(self, page, ctm):
        (x0,y0,x1,y1) = page.mediabox
        (x0,y0) = apply_matrix_pt(ctm, (x0,y0))
        (x1,y1) = apply_matrix_pt(ctm, (x1,y1))
        mediabox = (0, 0, abs(x0-x1), abs(y0-y1))
        self.cur_item = LTPage(self.pageno, mediabox)
        return

    def end_page(self, page):
        assert not self._stack
        assert isinstance(self.cur_item, LTPage)
        if self.laparams is not None:
            self.cur_item.analyze(self.laparams)
        self.pageno += 1
        self.receive_layout(self.cur_item)
        return

    def begin_figure(self, name, bbox, matrix):
        self._stack.append(self.cur_item)
        self.cur_item = LTFigure(name, bbox, mult_matrix(matrix, self.ctm))
        return

    def end_figure(self, _):
        fig = self.cur_item
        assert isinstance(self.cur_item, LTFigure)
        if self.laparams is not None:
            self.cur_item.analyze(self.laparams)
        self.cur_item = self._stack.pop()
        self.cur_item.add(fig)
        return

    def render_image(self, name, stream):
        assert isinstance(self.cur_item, LTFigure)
        item = LTImage(name, stream,
                       (self.cur_item.x0, self.cur_item.y0,
                        self.cur_item.x1, self.cur_item.y1))
        self.cur_item.add(item)
        return

    def paint_path(self, gstate, stroke, fill, evenodd, path):
        shape = ''.join(x[0] for x in path)
        if shape == 'ml':
            # horizontal/vertical line
            (_,x0,y0) = path[0]
            (_,x1,y1) = path[1]
            (x0,y0) = apply_matrix_pt(self.ctm, (x0,y0))
            (x1,y1) = apply_matrix_pt(self.ctm, (x1,y1))
            if x0 == x1 or y0 == y1:
                self.cur_item.add(LTLine(gstate.linewidth, (x0,y0), (x1,y1)))
                return
        if shape == 'mlllh':
            # rectangle
            (_,x0,y0) = path[0]
            (_,x1,y1) = path[1]
            (_,x2,y2) = path[2]
            (_,x3,y3) = path[3]
            (x0,y0) = apply_matrix_pt(self.ctm, (x0,y0))
            (x1,y1) = apply_matrix_pt(self.ctm, (x1,y1))
            (x2,y2) = apply_matrix_pt(self.ctm, (x2,y2))
            (x3,y3) = apply_matrix_pt(self.ctm, (x3,y3))
            if ((x0 == x1 and y1 == y2 and x2 == x3 and y3 == y0) or
                (y0 == y1 and x1 == x2 and y2 == y3 and x3 == x0)):
                self.cur_item.add(LTRect(gstate.linewidth, (x0,y0,x2,y2)))
                return
        # other shapes
        pts = []
        for p in path:
            for i in xrange(1, len(p), 2):
                pts.append(apply_matrix_pt(self.ctm, (p[i], p[i+1])))
        self.cur_item.add(LTCurve(gstate.linewidth, pts))
        return

    def render_char(self, matrix, font, fontsize, scaling, rise, cid):
        try:
            text = font.to_unichr(cid)
            assert isinstance(text, unicode), text
        except PDFUnicodeNotDefined:
            text = self.handle_undefined_char(font, cid)
        textwidth = font.char_width(cid)
        textdisp = font.char_disp(cid)
        item = LTChar(matrix, font, fontsize, scaling, rise, text, textwidth, textdisp)
        self.cur_item.add(item)
        return item.adv

    def handle_undefined_char(self, font, cid):
        if self.debug:
            print >>sys.stderr, 'undefined: %r, %r' % (font, cid)
        return '(cid:%d)' % cid

    def receive_layout(self, ltpage):
        return

##  PDFPageAggregator
##
class PDFPageAggregator(PDFLayoutAnalyzer):

    def __init__(self, rsrcmgr, pageno=1, laparams=None):
        PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams)
        self.result = None
        return

    def receive_layout(self, ltpage):
        self.result = ltpage
        return

    def get_result(self):
        return self.result

##  PDFConverter
##
class PDFConverter(PDFLayoutAnalyzer):

    def __init__(self, rsrcmgr, outfp, codec='utf-8', pageno=1, laparams=None):
        PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams)
        self.outfp = outfp
        self.codec = codec
        return

    def write_image(self, image):
        stream = image.stream
        filters = stream.get_filters()
        if len(filters) == 1 and filters[0] in LITERALS_DCT_DECODE:
            ext = '.jpg'
            data = stream.get_rawdata()
        elif stream.colorspace is LITERAL_DEVICE_RGB:
            ext = '.bmp'
            data = create_bmp(stream.get_data(), stream.bits*3, image.width, image.height)
        elif stream.colorspace is LITERAL_DEVICE_GRAY:
            ext = '.bmp'
            data = create_bmp(stream.get_data(), stream.bits, image.width, image.height)
        else:
            ext = '.img'
            data = stream.get_data()
        name = image.name+ext
        path = os.path.join(self.outdir, name)
        fp = file(path, 'wb')
        fp.write(data)
        fp.close()
        return name

##  TextConverter
##
class TextConverter(PDFConverter):

    def __init__(self, rsrcmgr, outfp, codec='utf-8', pageno=1, laparams=None,
                 showpageno=False):
        PDFConverter.__init__(self, rsrcmgr, outfp, codec=codec, pageno=pageno, laparams=laparams)
        self.showpageno = showpageno
        return

    def write_text(self, text):
        self.outfp.write(text.encode(self.codec, 'ignore'))
        #self.outfp = (text.encode(self.codec,'ignore'))
        return

    def receive_layout(self, ltpage):
        def render(item):
            if isinstance(item, LTContainer):
                for child in item:
                    render(child)
            elif isinstance(item, LTText):
                self.write_text(item.text)
            if isinstance(item, LTTextBox):
                self.write_text('\n')
        if self.showpageno:
            self.write_text('Page %s\n' % ltpage.pageid)
        render(ltpage)
        self.write_text('\f')
        return

    # Some dummy functions to save memory/CPU when all that is wanted is text.
    # This stops all the image and drawing ouput from being recorded and taking
    # up RAM.
    def render_image(self, name, stream):
        pass
    def paint_path(self, gstate, stroke, fill, evenodd, path):
        pass

##  HTMLConverter
##
class HTMLConverter(PDFConverter):

    RECT_COLORS = {
        #'char': 'green',
        'figure': 'yellow',
        'textline': 'magenta',
        'textbox': 'cyan',
        'textgroup': 'red',
        'curve': 'black',
        'page': 'gray',
        }

    TEXT_COLORS = {
        'textbox': 'blue',
        'char': 'black',
        }

    def __init__(self, rsrcmgr, outfp, codec='utf-8', pageno=1, laparams=None,
                 scale=1, fontscale=0.7, layoutmode='normal', showpageno=True,
                 pagemargin=50, outdir=None,
                 rect_colors={'curve':'black', 'page':'gray'},
                 text_colors={'char':'black'}):
        PDFConverter.__init__(self, rsrcmgr, outfp, codec=codec, pageno=pageno, laparams=laparams)
        self.scale = scale
        self.fontscale = fontscale
        self.layoutmode = layoutmode
        self.showpageno = showpageno
        self.pagemargin = pagemargin
        self.outdir = outdir
        self.rect_colors = rect_colors
        self.text_colors = text_colors
        if self.debug:
            self.rect_colors.update(self.RECT_COLORS)
            self.text_colors.update(self.TEXT_COLORS)
        self._yoffset = self.pagemargin
        self._font = None
        self._fontstack = []
        self.write_header()
        return

    def write(self, text):
        self.outfp.write(text)
        return

    def write_header(self):
        self.write('\n')
        self.write('<meta http-equiv="Content-Type" content="text/html; charset=%s">\n' % self.codec)
        self.write('\n')
        return

    def write_footer(self):
        self.write('
Page: %s
\n' %
                   ', '.join('%s' % (i,i) for i in xrange(1,self.pageno)))
        self.write('\n')
        return

    def write_text(self, text):
        self.write(enc(text, self.codec))
        return

    def place_rect(self, color, borderwidth, x, y, w, h):
        color = self.rect_colors.get(color)
        if color is not None:
            self.write('\n' %
                       (color, borderwidth,
                        x*self.scale, (self._yoffset-y)*self.scale,
                        w*self.scale, h*self.scale))
        return

    def place_border(self, color, borderwidth, item):
        self.place_rect(color, borderwidth, item.x0, item.y1, item.width, item.height)
        return

    def place_image(self, item, borderwidth, x, y, w, h):
        if self.outdir is not None:
            name = self.write_image(item)
            self.write('\n' %
                       (enc(name), borderwidth,
                        x*self.scale, (self._yoffset-y)*self.scale,
                        w*self.scale, h*self.scale))
        return

    def place_text(self, color, text, x, y, size):
        color = self.text_colors.get(color)
        if color is not None:
            self.write('' %
                       (color, x*self.scale, (self._yoffset-y)*self.scale, size*self.scale*self.fontscale))
            self.write_text(text)
            self.write('\n')
        return

    def begin_textbox(self, color, borderwidth, x, y, w, h, writing_mode):
        self._fontstack.append(self._font)
        self._font = None
        self.write('
' %
                   (color, borderwidth, writing_mode,
                    x*self.scale, (self._yoffset-y)*self.scale,
                    w*self.scale, h*self.scale))
        return

    def put_text(self, text, fontname, fontsize):
        font = (fontname, fontsize)
        if font != self._font:
            if self._font is not None:
                self.write('')
            self.write('' %
                       (fontname, fontsize * self.scale * self.fontscale))
            self._font = font
        self.write_text(text)
        return

    def put_newline(self):
        self.write('
')
        return

    def end_textbox(self, color):
        if self._font is not None:
            self.write('')
        self._font = self._fontstack.pop()
        self.write('
')
        return

    def receive_layout(self, ltpage):
        def show_layout(item):
            if isinstance(item, LTTextGroup):
                self.place_border('textgroup', 1, item)
                for child in item:
                    show_layout(child)
            return
        def render(item):
            if isinstance(item, LTPage):
                self._yoffset += item.y1
                self.place_border('page', 1, item)
                if self.showpageno:
                    self.write('
' %
                               ((self._yoffset-item.y1)*self.scale))
                    self.write('Page %s
\n' % (item.pageid, item.pageid))
                for child in item:
                    render(child)
                if item.layout:
                    show_layout(item.layout)
            elif isinstance(item, LTCurve):
                self.place_border('curve', 1, item)
            elif isinstance(item, LTFigure):
                self.place_border('figure', 1, item)
                for child in item:
                    render(child)
            elif isinstance(item, LTImage):
                self.place_image(item, 1, item.x0, item.y1, item.width, item.height)
            else:
                if self.layoutmode == 'exact':
                    if isinstance(item, LTTextLine):
                        self.place_border('textline', 1, item)
                        for child in item:
                            render(child)
                    elif isinstance(item, LTTextBox):
                        self.place_border('textbox', 1, item)
                        self.place_text('textbox', str(item.index+1), item.x0, item.y1, 20)
                        for child in item:
                            render(child)
                    elif isinstance(item, LTChar):
                        self.place_border('char', 1, item)
                        self.place_text('char', item.text, item.x0, item.y1, item.size)
                else:
                    if isinstance(item, LTTextLine):
                        for child in item:
                            render(child)
                        if self.layoutmode != 'loose':
                            self.put_newline()
                    elif isinstance(item, LTTextBox):
                        self.begin_textbox('textbox', 1, item.x0, item.y1, item.width, item.height,
                                           item.get_writing_mode())
                        for child in item:
                            render(child)
                        self.end_textbox('textbox')
                    elif isinstance(item, LTChar):
                        self.put_text(item.text, item.fontname, item.size)
                    elif isinstance(item, LTText):
                        self.write_text(item.text)
            return
        render(ltpage)
        self._yoffset += self.pagemargin
        return

    def close(self):
        self.write_footer()
        return

##  XMLConverter
##
class XMLConverter(PDFConverter):

    def __init__(self, rsrcmgr, outfp, codec='utf-8', pageno=1, laparams=None, outdir=None):
        PDFConverter.__init__(self, rsrcmgr, outfp, codec=codec, pageno=pageno, laparams=laparams)
        self.outdir = outdir
        self.write_header()
        return

    def write_header(self):
        self.outfp.write('<?xml version="1.0" encoding="%s" ?>\n' % self.codec)
        self.outfp.write('<pages>\n')
        return

    def write_footer(self):
        self.outfp.write('</pages>\n')
        return

    def write_text(self, text):
        self.outfp.write(enc(text, self.codec))
        return

    def receive_layout(self, ltpage):
        def show_layout(item):
            if isinstance(item, LTTextBox):
                self.outfp.write('<textbox id="%d" bbox="%s" />\n' %
                                 (item.index, bbox2str(item.bbox)))
            elif isinstance(item, LTTextGroup):
                self.outfp.write('<textgroup bbox="%s">\n' % bbox2str(item.bbox))
                for child in item:
                    show_layout(child)
                self.outfp.write('</textgroup>\n')
            return
        def render(item):
            if isinstance(item, LTPage):
                self.outfp.write('<page id="%s" bbox="%s" rotate="%d">\n' %
                                 (item.pageid, bbox2str(item.bbox), item.rotate))
                for child in item:
                    render(child)
                if item.layout:
                    self.outfp.write('<layout>\n')
                    show_layout(item.layout)
                    self.outfp.write('</layout>\n')
                self.outfp.write('</page>\n')
            elif isinstance(item, LTLine):
                self.outfp.write('<line linewidth="%d" bbox="%s" />\n' %
                                 (item.linewidth, bbox2str(item.bbox)))
            elif isinstance(item, LTRect):
                self.outfp.write('<rect linewidth="%d" bbox="%s" />\n' %
                                 (item.linewidth, bbox2str(item.bbox)))
            elif isinstance(item, LTCurve):
                self.outfp.write('<curve linewidth="%d" bbox="%s" pts="%s"/>\n' %
                                 (item.linewidth, bbox2str(item.bbox), item.get_pts()))
            elif isinstance(item, LTFigure):
                self.outfp.write('
\n' %
                                 (item.name, bbox2str(item.bbox)))
                for child in item:
                    render(child)
                self.outfp.write('
\n')
            elif isinstance(item, LTTextLine):
                self.outfp.write('<textline bbox="%s">\n' % bbox2str(item.bbox))
                for child in item:
                    render(child)
                self.outfp.write('</textline>\n')
            elif isinstance(item, LTTextBox):
                wmode = ''
                if isinstance(item, LTTextBoxVertical):
                    wmode = ' wmode="vertical"'
                self.outfp.write('<textbox id="%d" bbox="%s"%s>\n' %
                                 (item.index, bbox2str(item.bbox), wmode))
                for child in item:
                    render(child)
                self.outfp.write('</textbox>\n')
            elif isinstance(item, LTChar):
                self.outfp.write('<text font="%s" bbox="%s" size="%.3f">' %
                                 (enc(item.fontname), bbox2str(item.bbox), item.size))
                self.write_text(item.text)
                self.outfp.write('</text>\n')
            elif isinstance(item, LTText):
                self.outfp.write('<text>%s</text>\n' % item.text)
            elif isinstance(item, LTImage):
                if self.outdir:
                    name = self.write_image(item)
                    self.outfp.write('<image src="%s" width="%d" height="%d" />\n' %
                                     (enc(name), item.width, item.height))
                else:
                    self.outfp.write('<image width="%d" height="%d" />\n' %
                                     (item.width, item.height))
            else:
                assert 0, item
            return
        render(ltpage)
        return

    def close(self):
        self.write_footer()
        return


text:
// File: CommonLoggingLogCreationExtension.cs
// Project Name: ILogInject.Unity
// Project Home: https://github.com/trondr/ILogInject/blob/master/README.md
// License: New BSD License (BSD) https://github.com/trondr/ILogInject/blob/master/License.md
// Credits: http://blog.baltrinic.com/software-development/dotnet/log4net-integration-with-unity-ioc-container
// Copyright © <github.com/trondr> 2013
// All rights reserved.

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.ObjectBuilder;

namespace ILogInject.Unity
{
   public class CommonLoggingLogCreationExtension: UnityContainerExtension
   {
      protected override void Initialize()
      {
         Context.Strategies.AddNew<CommonLoggingLogCreationStrategy>(UnityBuildStage.PreCreation);
      }
   }
}


text:
/* globals console*/
"use strict";

function PointIntCircle(params) {
    var xCoordinate = +params[0];
    var yCoordinate = +params[1];
    var xCenter = 0;
    var yCenter = 0;
    var radius = 2;

    var distance = Math.sqrt(Math.pow(xCoordinate - xCenter, 2) + Math.pow(yCoordinate - yCenter, 2)).toFixed(2);

    if (distance <= radius) {
        console.log("yes " + distance);
    }
    else {
        console.log("no " + distance);
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model.item;

/**
 *
 * @author Dr.Chase
 */
public class ItemAvailability {
    public enum TypeOfTime {
        ÓRA,
        NAP,
        HÓNAP
    }

    public int difficulty;     // how hard it is to get the stuff
    public int minTimeToGetIt; // How many hours does it take to get it
    TypeOfTime typeOfTime;
}


text:
IRISPOINTEREXTENSION_API bool IR_Initialize()
{
	IrisDev::RegistClass("Pointer", new IrisPointer());

	return true;
}

IRISPOINTEREXTENSION_API bool IR_Release()
{
	return true;
}


text:
package org.neo4j.kernel.ha.cluster;

import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.protocol.election.ElectionCredentials;
import org.neo4j.cluster.protocol.election.ElectionCredentialsProvider;
import org.neo4j.cluster.protocol.election.NotElectableElectionCredentials;
import org.neo4j.kernel.ha.HighAvailabilityMemberInfoProvider;
import org.neo4j.kernel.impl.core.LastTxIdGetter;

/**
 * ElectionCredentialsProvider that provides the server id, latest txId and current role status as credentials for
 * elections.
 */
public class DefaultElectionCredentialsProvider
    implements ElectionCredentialsProvider
{
    private final InstanceId serverId;
    private final LastTxIdGetter lastTxIdGetter;
    private final HighAvailabilityMemberInfoProvider masterInfo;

    public DefaultElectionCredentialsProvider( InstanceId serverId, LastTxIdGetter lastTxIdGetter,
                                               HighAvailabilityMemberInfoProvider masterInfo )
    {
        this.serverId = serverId;
        this.lastTxIdGetter = lastTxIdGetter;
        this.masterInfo = masterInfo;
    }

    @Override
    public ElectionCredentials getCredentials( String role )
    {
        if ( masterInfo.getHighAvailabilityMemberState().isEligibleForElection() )
        {
            return new DefaultElectionCredentials(
                    serverId.toIntegerIndex(),
                    lastTxIdGetter.getLastTxId(),
                    isMasterOrToMaster() );
        }
        return new NotElectableElectionCredentials();
    }

    private boolean isMasterOrToMaster()
    {
        return masterInfo.getHighAvailabilityMemberState() == HighAvailabilityMemberState.MASTER ||
                masterInfo.getHighAvailabilityMemberState() == HighAvailabilityMemberState.TO_MASTER;
    }
}


text:
#
# Makefile for the security policy.
#
# Targets:
#
# install       - compile and install the policy configuration, and context files.
# load          - compile, install, and load the policy configuration.
# reload        - compile, install, and load/reload the policy configuration.
# relabel       - relabel filesystems based on the file contexts configuration.
# checklabels   - check filesystems against the file context configuration
# restorelabels - check filesystems against the file context configuration
#                 and restore the label of files with incorrect labels
# policy        - compile the policy configuration locally for testing/development.
#
# The default target is 'policy'.
#
#
# Please see build.conf for policy build options.
#

########################################
#
# NO OPTIONS BELOW HERE
#

# Include the local build.conf if it exists, otherwise
# include the configuration of the root directory.
include build.conf

ifdef LOCAL_ROOT
	-include $(LOCAL_ROOT)/build.conf
endif

# refpolicy version
version = $(shell cat VERSION)

ifdef LOCAL_ROOT
builddir := $(LOCAL_ROOT)/
tmpdir := $(LOCAL_ROOT)/tmp
tags := $(LOCAL_ROOT)/tags
else
tmpdir := tmp
tags := tags
endif

# executable paths
BINDIR ?= /usr/bin
SBINDIR ?= /usr/sbin
ifdef TEST_TOOLCHAIN
tc_usrbindir := env LD_LIBRARY_PATH="$(TEST_TOOLCHAIN)/lib:$(TEST_TOOLCHAIN)/usr/lib" $(TEST_TOOLCHAIN)$(BINDIR)
tc_usrsbindir := env LD_LIBRARY_PATH="$(TEST_TOOLCHAIN)/lib:$(TEST_TOOLCHAIN)/usr/lib" $(TEST_TOOLCHAIN)$(SBINDIR)
tc_sbindir := env LD_LIBRARY_PATH="$(TEST_TOOLCHAIN)/lib:$(TEST_TOOLCHAIN)/usr/lib" $(TEST_TOOLCHAIN)/sbin
else
tc_usrbindir := $(BINDIR)
tc_usrsbindir := $(SBINDIR)
tc_sbindir := /sbin
endif
CHECKPOLICY ?= $(tc_usrbindir)/checkpolicy
CHECKMODULE ?= $(tc_usrbindir)/checkmodule
SEMODULE ?= $(tc_usrsbindir)/semodule
SEMOD_PKG ?= $(tc_usrbindir)/semodule_package
SEMOD_LNK ?= $(tc_usrbindir)/semodule_link
SEMOD_EXP ?= $(tc_usrbindir)/semodule_expand
LOADPOLICY ?= $(tc_usrsbindir)/load_policy
SETFILES ?= $(tc_sbindir)/setfiles
XMLLINT ?= $(BINDIR)/xmllint
SECHECK ?= $(BINDIR)/sechecker

# interpreters and aux tools
AWK ?= gawk
GREP ?= egrep
INSTALL ?= install
M4 ?= m4
PYTHON ?= python
SED ?= sed
SORT ?= LC_ALL=C sort
UMASK ?= umask

CFLAGS += -Wall

# policy source layout
poldir := policy
moddir := $(poldir)/modules
flaskdir := $(poldir)/flask
secclass := $(flaskdir)/security_classes
isids := $(flaskdir)/initial_sids
avs := $(flaskdir)/access_vectors

# local source layout
ifdef LOCAL_ROOT
local_poldir := $(LOCAL_ROOT)/policy
local_moddir := $(local_poldir)/modules
endif

# policy building support tools
support := support
genxml := $(PYTHON) -E $(support)/segenxml.py
gendoc := $(PYTHON) -E $(support)/sedoctool.py
genperm := $(PYTHON) -E $(support)/genclassperms.py
policyvers := $(PYTHON) -E $(support)/policyvers.py
fcsort := $(tmpdir)/fc_sort
setbools := $(AWK) -f $(support)/set_bools_tuns.awk
get_type_attr_decl := $(SED) -r -f $(support)/get_type_attr_decl.sed
comment_move_decl := $(SED) -r -f $(support)/comment_move_decl.sed
gennetfilter := $(PYTHON) -E $(support)/gennetfilter.py
m4iferror := $(support)/iferror.m4
m4divert := $(support)/divert.m4
m4undivert := $(support)/undivert.m4
# use our own genhomedircon to make sure we have a known usable one,
# so policycoreutils updates are not required (RHEL4)
genhomedircon := $(PYTHON) -E $(support)/genhomedircon

# documentation paths
docs := doc
xmldtd = $(docs)/policy.dtd
metaxml = metadata.xml
doctemplate = $(docs)/templates
docfiles = $(docs)/Makefile.example $(addprefix $(docs)/,example.te example.if example.fc)

ifndef LOCAL_ROOT
polxml = $(docs)/policy.xml
tunxml = $(docs)/global_tunables.xml
boolxml = $(docs)/global_booleans.xml
htmldir = $(docs)/html
else
polxml = $(LOCAL_ROOT)/doc/policy.xml
tunxml = $(LOCAL_ROOT)/doc/global_tunables.xml
boolxml = $(LOCAL_ROOT)/doc/global_booleans.xml
htmldir = $(LOCAL_ROOT)/doc/html
endif

# config file paths
globaltun = $(poldir)/global_tunables
globalbool = $(poldir)/global_booleans
user_files := $(poldir)/users
policycaps := $(poldir)/policy_capabilities
ctx_defaults := $(poldir)/context_defaults

# local config file paths
ifndef LOCAL_ROOT
mod_conf = $(poldir)/modules.conf
booleans = $(poldir)/booleans.conf
tunables = $(poldir)/tunables.conf
else
mod_conf = $(local_poldir)/modules.conf
booleans = $(local_poldir)/booleans.conf
tunables = $(local_poldir)/tunables.conf
endif

# install paths
PKGNAME ?= refpolicy-$(version)
prefix = $(DESTDIR)/usr
topdir = $(DESTDIR)/etc/selinux
installdir = $(topdir)/$(strip $(NAME))
srcpath = $(installdir)/src
userpath = $(installdir)/users
policypath = $(installdir)/policy
contextpath = $(installdir)/contexts
homedirpath = $(contextpath)/files/homedir_template
fcpath = $(contextpath)/files/file_contexts
fcsubspath = $(contextpath)/files/file_contexts.subs_dist
ncpath = $(contextpath)/netfilter_contexts
sharedir = $(prefix)/share/selinux
modpkgdir = $(sharedir)/$(strip $(NAME))
headerdir = $(modpkgdir)/include
docsdir = $(prefix)/share/doc/$(PKGNAME)

# enable MLS if requested.
ifeq "$(TYPE)" "mls"
	M4PARAM += -D enable_mls
	CHECKPOLICY += -M
	CHECKMODULE += -M
	gennetfilter += -m
endif

# enable MLS if MCS requested.
ifeq "$(TYPE)" "mcs"
	M4PARAM += -D enable_mcs
	CHECKPOLICY += -M
	CHECKMODULE += -M
	gennetfilter += -c
endif

# enable distribution-specific policy
ifneq ($(DISTRO),)
	M4PARAM += -D distro_$(DISTRO)
endif

ifeq "$(DISTRO)" "ubuntu"
	M4PARAM += -D distro_debian
endif

ifneq ($(OUTPUT_POLICY),)
	CHECKPOLICY += -c $(OUTPUT_POLICY)
endif

ifneq "$(CUSTOM_BUILDOPT)" ""
	M4PARAM += $(foreach opt,$(CUSTOM_BUILDOPT),-D $(opt))
endif

# if not set, use the type as the name.
NAME ?= $(TYPE)

# default unknown permissions setting
UNK_PERMS ?= deny

ifeq ($(DIRECT_INITRC),y)
	M4PARAM += -D direct_sysadm_daemon
endif

ifeq "$(UBAC)" "y"
	M4PARAM += -D enable_ubac
endif

ifeq "$(INIT_SYSTEMD)" "y"
	M4PARAM += -D init_systemd
endif

# default MLS/MCS sensitivity and category settings.
MLS_SENS ?= 16
MLS_CATS ?= 1024
MCS_CATS ?= 1024

ifeq ($(QUIET),y)
	verbose = @
endif

M4PARAM += -D mls_num_sens=$(MLS_SENS) -D mls_num_cats=$(MLS_CATS) -D mcs_num_cats=$(MCS_CATS) -D hide_broken_symptoms

# we need exuberant ctags; unfortunately it is named
# differently on different distros
ifeq ($(DISTRO),debian)
	CTAGS := ctags-exuberant
endif

ifeq ($(DISTRO),gentoo)
	CTAGS := exuberant-ctags
endif

CTAGS ?= ctags

m4support := $(m4divert) $(wildcard $(poldir)/support/*.spt)
ifdef LOCAL_ROOT
m4support += $(wildcard $(local_poldir)/support/*.spt)
endif
m4support += $(m4undivert)

appconf := config/appconfig-$(TYPE)
seusers := $(appconf)/seusers
appdir := $(contextpath)
user_default_contexts := $(wildcard config/appconfig-$(TYPE)/*_default_contexts)
user_default_contexts_names := $(addprefix $(contextpath)/users/,$(subst _default_contexts,,$(notdir $(user_default_contexts))))
appfiles := $(addprefix $(appdir)/,default_contexts default_type initrc_context failsafe_context userhelper_context removable_context dbus_contexts sepgsql_contexts x_contexts customizable_types securetty_types virtual_domain_context virtual_image_context) $(contextpath)/files/media $(fcsubspath) $(user_default_contexts_names)
net_contexts := $(builddir)net_contexts

all_layers := $(shell find $(wildcard $(moddir)/*) -maxdepth 0 -type d)
ifdef LOCAL_ROOT
all_layers += $(shell find $(wildcard $(local_moddir)/*) -maxdepth 0 -type d)
endif

generated_te := $(basename $(foreach dir,$(all_layers),$(wildcard $(dir)/*.te.in)))
generated_if := $(basename $(foreach dir,$(all_layers),$(wildcard $(dir)/*.if.in)))
generated_fc := $(basename $(foreach dir,$(all_layers),$(wildcard $(dir)/*.fc.in)))

# sort here since it removes duplicates, which can happen
# when a generated file is already generated
detected_mods := $(sort $(foreach dir,$(all_layers),$(wildcard $(dir)/*.te)) $(generated_te))

modxml := $(addprefix $(tmpdir)/, $(detected_mods:.te=.xml))
layerxml := $(sort $(addprefix $(tmpdir)/, $(notdir $(addsuffix .xml,$(all_layers)))))
layer_names := $(sort $(notdir $(all_layers)))
all_metaxml = $(call detect-metaxml, $(layer_names))

# modules.conf setting for base module
configbase := base

# modules.conf setting for loadable module
configmod := module

# modules.conf setting for unused module
configoff := off

# test for module overrides from command line
mod_test = $(filter $(APPS_OFF), $(APPS_BASE) $(APPS_MODS))
mod_test += $(filter $(APPS_MODS), $(APPS_BASE))
ifneq "$(strip $(mod_test))" ""
        $(error Applications must be base, module, or off, and not in more than one list! $(strip $(mod_test)) found in multiple lists!)
endif

# add on suffix to modules specified on command line
cmdline_base := $(addsuffix .te,$(APPS_BASE))
cmdline_mods := $(addsuffix .te,$(APPS_MODS))
cmdline_off := $(addsuffix .te,$(APPS_OFF))

# extract settings from modules.conf
mod_conf_base := $(addsuffix .te,$(sort $(shell awk '/^[[:blank:]]*[[:alpha:]]/{ if ($$3 == "$(configbase)") print $$1 }' $(mod_conf) 2> /dev/null)))
mod_conf_mods := $(addsuffix .te,$(sort $(shell awk '/^[[:blank:]]*[[:alpha:]]/{ if ($$3 == "$(configmod)") print $$1 }' $(mod_conf) 2> /dev/null)))
mod_conf_off := $(addsuffix .te,$(sort $(shell awk '/^[[:blank:]]*[[:alpha:]]/{ if ($$3 == "$(configoff)") print $$1 }' $(mod_conf) 2> /dev/null)))

base_mods := $(cmdline_base)
mod_mods := $(cmdline_mods)
off_mods := $(cmdline_off)

base_mods += $(filter-out $(cmdline_off) $(cmdline_base) $(cmdline_mods), $(mod_conf_base))
mod_mods += $(filter-out $(cmdline_off) $(cmdline_base) $(cmdline_mods), $(mod_conf_mods))
off_mods += $(filter-out $(cmdline_off) $(cmdline_base) $(cmdline_mods), $(mod_conf_off))

# add modules not in modules.conf to the off list
off_mods += $(filter-out $(base_mods) $(mod_mods) $(off_mods),$(notdir $(detected_mods)))

# filesystems to be used in labeling targets
filesystems = $(shell mount | grep -v "context=" | egrep -v '\((|.*,)bind(,.*|)\)' | awk '/(ext[234]|btrfs| xfs| jfs).*rw/{print $$3}';)
fs_names := "btrfs ext2 ext3 ext4 xfs jfs"

########################################
#
# Functions
#

# detect-metaxml layer_names
ifdef LOCAL_ROOT
define detect-metaxml
	$(shell for i in $1; do \
		if [ -d $(moddir)/$$i -a -d $(local_moddir)/$$i ]; then \
			if [ -f $(local_moddir)/$$i/$(metaxml) ]; then \
				echo $(local_moddir)/$$i/$(metaxml) ;\
			else \
				echo $(moddir)/$$i/$(metaxml) ;\
			fi \
		elif [ -d $(local_moddir)/$$i ]; then
			echo $(local_moddir)/$$i/$(metaxml) ;\
		else \
			echo $(moddir)/$$i/$(metaxml) ;\
		fi \
	done )
endef
else
define detect-metaxml
	$(shell for i in $1; do echo $(moddir)/$$i/$(metaxml); done)
endef
endif

########################################
#
# Load appropriate rules
#

ifeq ($(MONOLITHIC),y)
	include Rules.monolithic
else
	include Rules.modular
endif

########################################
#
# Generated files
#
# NOTE: There is no "local" version of these files.
#
generate: $(generated_te) $(generated_if) $(generated_fc)

$(moddir)/kernel/corenetwork.if: $(moddir)/kernel/corenetwork.te.in $(moddir)/kernel/corenetwork.if.m4 $(moddir)/kernel/corenetwork.if.in
	@echo "#" > $@
	@echo "# This is a generated file!  Instead of modifying this file, the" >> $@
	@echo "# $(notdir $@).in or $(notdir $@).m4 file should be modified." >> $@
	@echo "#" >> $@
	$(verbose) cat $@.in >> $@
	$(verbose) $(GREP) "^[[:blank:]]*network_(interface|node|port|packet)(_controlled)?\(.*\)" $< \
		| $(M4) -D self_contained_policy $(M4PARAM) $(m4divert) $@.m4 $(m4undivert) - \
		| $(SED) -e 's/dollarsone/\$$1/g' -e 's/dollarszero/\$$0/g' >> $@

$(moddir)/kernel/corenetwork.te: $(m4divert) $(moddir)/kernel/corenetwork.te.m4 $(m4undivert) $(moddir)/kernel/corenetwork.te.in
	@echo "#" > $@
	@echo "# This is a generated file!  Instead of modifying this file, the" >> $@
	@echo "# $(notdir $@).in or $(notdir $@).m4 file should be modified." >> $@
	@echo "#" >> $@
	$(verbose) $(M4) -D self_contained_policy $(M4PARAM) $^ \
		| $(SED) -e 's/dollarsone/\$$1/g' -e 's/dollarszero/\$$0/g' >> $@

########################################
#
# Network packet labeling
#
$(net_contexts): $(moddir)/kernel/corenetwork.te.in
	@echo "Creating netfilter network labeling rules"
	$(verbose) $(gennetfilter) $^ > $@

########################################
#
# Create config files
#
conf: $(mod_conf) $(booleans) $(generated_te) $(generated_if) $(generated_fc)

$(mod_conf) $(booleans): $(polxml)
	@echo "Updating $(mod_conf) and $(booleans)"
	$(verbose) $(gendoc) -b $(booleans) -m $(mod_conf) -x $(polxml)

########################################
#
# Generate the fc_sort program
#
$(fcsort) : $(support)/fc_sort.c
	$(verbose) $(CC) $(CFLAGS) $^ -o $@

########################################
#
# Documentation generation
#
$(layerxml): %.xml: $(all_metaxml) $(filter $(addprefix $(moddir)/, $(notdir $*))%, $(detected_mods)) $(subst .te,.if, $(filter $(addprefix $(moddir)/, $(notdir $*))%, $(detected_mods)))
	@test -d $(tmpdir) || mkdir -p $(tmpdir)
	$(verbose) cat $(filter %$(notdir $*)/$(metaxml), $(all_metaxml)) > $@
	$(verbose) for i in $(basename $(filter $(addprefix $(moddir)/, $(notdir $*))%, $(detected_mods))); do $(genxml) -w -m $$i >> $@; done
ifdef LOCAL_ROOT
	$(verbose) for i in $(basename $(filter $(addprefix $(local_moddir)/, $(notdir $*))%, $(detected_mods))); do $(genxml) -w -m $$i >> $@; done
endif

$(tunxml): $(globaltun)
	$(verbose) $(genxml) -w -t $< > $@

$(boolxml): $(globalbool)
	$(verbose) $(genxml) -w -b $< > $@

$(polxml): $(layerxml) $(tunxml) $(boolxml)
	@echo "Creating $(@F)"
	@test -d $(dir $(polxml)) || mkdir -p $(dir $(polxml))
	@test -d $(tmpdir) || mkdir -p $(tmpdir)
	$(verbose) echo '<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>' > $@
	$(verbose) echo '<!DOCTYPE policy SYSTEM "$(notdir $(xmldtd))">' >> $@
	$(verbose) echo '<policy>' >> $@
	$(verbose) for i in $(basename $(notdir $(layerxml))); do echo "<layer name=\"$$i\">" >> $@; cat $(tmpdir)/$$i.xml >> $@; echo "</layer>" >> $@; done
	$(verbose) cat $(tunxml) $(boolxml) >> $@
	$(verbose) echo '</policy>' >> $@
	$(verbose) if test -x $(XMLLINT) && test -f $(xmldtd); then \
		$(XMLLINT) --noout --path $(dir $(xmldtd)) --dtdvalid $(xmldtd) $@ ;\
	fi

xml: $(polxml)

html $(tmpdir)/html: $(polxml)
	@echo "Building html interface reference documentation in $(htmldir)"
	@test -d $(htmldir) || mkdir -p $(htmldir)
	@test -d $(tmpdir) || mkdir -p $(tmpdir)
	$(verbose) $(gendoc) -d $(htmldir) -T $(doctemplate) -x $(polxml)
	$(verbose) cp $(doctemplate)/*.css $(htmldir)
	@touch $(tmpdir)/html

########################################
#
# Runtime binary policy patching of users
#
$(userpath)/system.users: $(m4support) $(tmpdir)/generated_definitions.conf $(user_files)
	@mkdir -p $(tmpdir)
	@echo "Installing system.users"
	@echo "# " > $(tmpdir)/system.users
	@echo "# Do not edit this file. " >> $(tmpdir)/system.users
	@echo "# This file is replaced on reinstalls of this policy." >> $(tmpdir)/system.users
	@echo "# Please edit local.users to make local changes." >> $(tmpdir)/system.users
	@echo "#" >> $(tmpdir)/system.users
	$(verbose) $(M4) -D self_contained_policy $(M4PARAM) $^ | $(SED) -r -e 's/^[[:blank:]]+//' \
		-e '/^[[:blank:]]*($$|#)/d' >> $(tmpdir)/system.users
	@$(INSTALL) -d -m 0755 $(@D)
	$(verbose) $(INSTALL) -m 0644 $(tmpdir)/system.users $@

$(userpath)/local.users: config/local.users
	@echo "Installing local.users"
	@$(INSTALL) -d -m 0755 $(@D)
	$(verbose) $(INSTALL) -b -m 0644 $< $@

########################################
#
# Build Appconfig files
#
$(tmpdir)/initrc_context: $(appconf)/initrc_context
	@mkdir -p $(tmpdir)
	$(verbose) $(M4) $(M4PARAM) $(m4support) $^ | $(GREP) '^[a-z]' > $@

########################################
#
# Install Appconfig files
#
install-appconfig: $(appfiles)

$(installdir)/booleans: $(booleans)
	@mkdir -p $(tmpdir)
	$(verbose) $(SED) -r -e 's/false/0/g' -e 's/true/1/g' \
		-e '/^[[:blank:]]*($$|#)/d' $(booleans) | $(SORT) > $(tmpdir)/booleans
	@$(INSTALL) -d -m 0755 $(@D)
	$(verbose) $(INSTALL) -m 0644 $(tmpdir)/booleans $@

$(contextpath)/files/media: $(appconf)/media
	@$(INSTALL) -d -m 0755 $(@D)
	$(verbose) $(INSTALL) -m 0644 $< $@

$(fcsubspath): config/file_contexts.subs_dist
	@$(INSTALL) -d -m 0755 $(@D)
	$(verbose) $(INSTALL) -m 0644 $< $@

$(contextpath)/users/%: $(appconf)/%_default_contexts
	@$(INSTALL) -d -m 0755 $(@D)
	$(verbose) $(INSTALL) -m 0644 $^ $@

$(appdir)/%: $(appconf)/%
	$(verbose) $(M4) $(M4PARAM) $(m4support) $< > $(tmpdir)/$(@F)
	@$(INSTALL) -d -m 0755 $(@D)
	$(verbose) $(INSTALL) -m 0644 $(tmpdir)/$(@F) $@

########################################
#
# Install policy headers
#
install-headers: $(layerxml) $(tunxml) $(boolxml)
	@mkdir -p $(headerdir)
	@echo "Installing $(NAME) policy headers."
	$(verbose) $(INSTALL) -m 644 $^ $(headerdir)
	$(verbose) mkdir -p $(headerdir)/support
	$(verbose) $(INSTALL) -m 644 $(m4support) $(word $(words $(genxml)),$(genxml)) $(xmldtd) $(headerdir)/support
	$(verbose) $(genperm) $(avs) $(secclass) > $(headerdir)/support/all_perms.spt
	$(verbose) for i in $(notdir $(all_layers)); do \
		mkdir -p $(headerdir)/$$i ;\
		$(INSTALL) -m 644 $(moddir)/$$i/*.if $(headerdir)/$$i ;\
	done
	$(verbose) echo "TYPE ?= $(TYPE)" > $(headerdir)/build.conf
	$(verbose) echo "NAME ?= $(NAME)" >> $(headerdir)/build.conf
ifneq "$(DISTRO)" ""
	$(verbose) echo "DISTRO ?= $(DISTRO)" >> $(headerdir)/build.conf
endif
	$(verbose) echo "MONOLITHIC ?= n" >> $(headerdir)/build.conf
	$(verbose) echo "DIRECT_INITRC ?= $(DIRECT_INITRC)" >> $(headerdir)/build.conf
	$(verbose) echo "override UBAC := $(UBAC)" >> $(headerdir)/build.conf
	$(verbose) echo "override MLS_SENS := $(MLS_SENS)" >> $(headerdir)/build.conf
	$(verbose) echo "override MLS_CATS := $(MLS_CATS)" >> $(headerdir)/build.conf
	$(verbose) echo "override MCS_CATS := $(MCS_CATS)" >> $(headerdir)/build.conf
	$(verbose) $(INSTALL) -m 644 $(support)/Makefile.devel $(headerdir)/Makefile

########################################
#
# Install policy documentation
#
install-docs: $(tmpdir)/html
	@mkdir -p $(docsdir)/html
	@echo "Installing policy documentation"
	$(verbose) $(INSTALL) -m 644 $(docfiles) $(docsdir)
	$(verbose) $(INSTALL) -m 644 $(wildcard $(htmldir)/*) $(docsdir)/html

########################################
#
# Install policy sources
#
install-src:
	rm -rf $(srcpath)/policy.old
	-mv $(srcpath)/policy $(srcpath)/policy.old
	mkdir -p $(srcpath)/policy
	cp -R . $(srcpath)/policy

########################################
#
# Generate tags file
#
tags: $(tags)
$(tags):
	@($(CTAGS) --version | grep -q Exuberant) || (echo ERROR: Need exuberant-ctags to function!; exit 1)
	@LC_ALL=C $(CTAGS) -f $(tags) --langdef=te --langmap=te:..te.if.spt \
	 --regex-te='/^type[ \t]+(\w+)(,|;)/\1/t,type/' \
	 --regex-te='/^typealias[ \t]+\w+[ \t+]+alias[ \t]+(\w+);/\1/t,type/' \
	 --regex-te='/^attribute[ \t]+(\w+);/\1/a,attribute/' \
	 --regex-te='/^[ \t]*define\(`(\w+)/\1/d,define/' \
	 --regex-te='/^[ \t]*interface\(`(\w+)/\1/i,interface/' \
	 --regex-te='/^[ \t]*template\(`(\w+)/\1/i,template/' \
	 --regex-te='/^[ \t]*bool[ \t]+(\w+)/\1/b,bool/' policy/modules/*/*.{if,te} policy/support/*.spt

########################################
#
# Filesystem labeling
#
checklabels:
	@echo "Checking labels on filesystem types: $(fs_names)"
	@if test -z "$(filesystems)"; then \
		echo "No filesystems with extended attributes found!" ;\
		false ;\
	fi
	$(verbose) $(SETFILES) -v -n $(fcpath) $(filesystems)

restorelabels:
	@echo "Restoring labels on filesystem types: $(fs_names)"
	@if test -z "$(filesystems)"; then \
		echo "No filesystems with extended attributes found!" ;\
		false ;\
	fi
	$(verbose) $(SETFILES) -v $(fcpath) $(filesystems)

relabel:
	@echo "Relabeling filesystem types: $(fs_names)"
	@if test -z "$(filesystems)"; then \
		echo "No filesystems with extended attributes found!" ;\
		false ;\
	fi
	$(verbose) $(SETFILES) $(fcpath) $(filesystems)

resetlabels:
	@echo "Resetting labels on filesystem types: $(fs_names)"
	@if test -z "$(filesystems)"; then \
		echo "No filesystems with extended attributes found!" ;\
		false ;\
	fi
	$(verbose) $(SETFILES) -F $(fcpath) $(filesystems)

########################################
#
# Clean everything
#
bare: clean
	$(verbose) rm -f $(polxml)
	$(verbose) rm -f $(layerxml)
	$(verbose) rm -f $(modxml)
	$(verbose) rm -f $(tunxml)
	$(verbose) rm -f $(boolxml)
	$(verbose) rm -f $(mod_conf)
	$(verbose) rm -f $(booleans)
	$(verbose) rm -fR $(htmldir)
	$(verbose) rm -f $(tags)
# don't remove these files if we're given a local root
ifndef LOCAL_ROOT
	$(verbose) rm -f $(fcsort)
	$(verbose) rm -f $(support)/*.pyc
ifneq ($(generated_te),)
	$(verbose) rm -f $(generated_te)
endif
ifneq ($(generated_if),)
	$(verbose) rm -f $(generated_if)
endif
ifneq ($(generated_fc),)
	$(verbose) rm -f $(generated_fc)
endif
endif

.PHONY: install-src install-appconfig install-headers generate xml conf html bare tags
.SUFFIXES:
.SUFFIXES: .c


text:
# Coding style

## Naming conventions

C code in `vesper-libs` should use `snake_case` names for variables and
functions.
C++ code should use upper-case `CamelCase` names for classes and
structs and lower-case `camelCase` for variables and functions.
C and C++ code should use upper-case `SNAKE_CASE` for constants and macros.

## Filenames

C code files should have a `snake_case` filename with `*.h` or `*.c` extension.
C++ code files should have an upper-case `CamelCase` filename with `*.hpp` or
`*.cpp` extension.

## Indent style

Code in `vesper-libs` should use [One True Brace Style (1TBS)][1TBS_link].

[1TBS_link]:
http://en.wikipedia.org/wiki/Indent_style#Variant:_1TBS

## Miscellaneous

Code in `vesper-libs` should furthermore conform to the following rules:

* Lines should not be longer than 80 characters.
* Pointer variables have the asterisk `*` symbol attached to their name.
* Keywords like `if`, `for`, `while`, `switch` are followed by a space.
* Binary operators excluding `>>` and `<<` are framed by spaces.
* Unary operators and increment or decrement operators are not framed by spaces.
* Inner elements in round brackets are not framed by spaces.
* Nested preprocessor commands (starting with hash `#` sign) use current code
  indentation and are indented by 2 spaces per level.
* Code inside preprocessor commands is indented by 4 spaces.
* `#endif` lines should include matching `#if` condition as a comment.
* Curly brackets closing a namespace should include namespace as a comment.
* Namespace do not affect indentation at all.
* `switch` statements: `case` is indented by 4 spaces, the code is indented by 8
  spaces, `break` is indented by 6 spaces.
* Keywords like `public`, `protected`, `private` are indented by 2 spaces.
* All code should use `/* C-style */` comments.
* Multi-line comments begin and end with an empty line and are prefixed by `*`.
* Header files should be guarded by `HEADER_H_INCLUDED` or `HEADER_HPP_INCLUDED`
  preprocessor commands, which do not affect indentation at all.

## Example

### C code

`output_string.c`:

```C

    #if defined _WIN32
      #include <windows.h>
    #endif /* defined _WIN32 */

    /**
     * Output information about input number.
     * Returns 0 if input number is even, else 1.
     */
    int output_string(int *interesting_number)
    {
        if (*interesting_number > 100) {
            puts("Big number.");
        } else {
            puts("Small number.");
        }

        int x = *interesting_number % 2;
        switch (x) {
            case 0:
                puts("Even number.");
              break;

            case 1:
                puts("Odd number.");
              break;
        }

        #if defined PRINT_GREETING
            puts("Hello, world.");
        #endif /* defined PRINT_GREETING */

        return x;
    }

```

### C++ code

`NumberOperator.hpp`:

```C++

    #if !defined NUMBEROPERATOR_HPP_INCLUDED
    #define NUMBEROPERATOR_HPP_INCLUDED

    #include <iostream>

    namespace NumberWorks {

    class NumberOperator {
      private:
        int anyNumber;

      public:
        NumberOperator(int anyNumber) : anyNumber(anyNumber)
        {
            /* do nothing */
        }

        /**
         * Print the number and return.
         */
        void printInformation()
        {
            std::cout<<"Number: "<<anyNumber<<std::endl;
        }

    };

    } /* namespace NumberWorks */

    #endif /* !defined NUMBEROPERATOR_HPP_INCLUDED */

```


text:
#pragma once

#include "../math/Color4.h"
#include "../dxgi/Enums.h"

#include "../DataBox.h"
#include "../ComObject.h"

#include "DeviceChild11.h"
#include "Enums11.h"

using System::Runtime::InteropServices::OutAttribute;

namespace SlimDX
{
	namespace Direct3D11
	{
		ref class Asynchronous;
		ref class Device;
		ref class CommandList;
		ref class Resource;
		ref class DepthStencilView;
		ref class RenderTargetView;
		ref class ShaderResourceView;
		ref class UnorderedAccessView;
		ref class Buffer;
		ref class Predicate;
		ref class Texture1D;
		ref class Texture2D;
		ref class Texture3D;
		value class ResourceRegion;

		ref class GeometryShaderWrapper;
		ref class InputAssemblerWrapper;
		ref class OutputMergerWrapper;
		ref class RasterizerWrapper;
		ref class PixelShaderWrapper;
		ref class StreamOutputWrapper;
		ref class VertexShaderWrapper;
		ref class DomainShaderWrapper;
		ref class HullShaderWrapper;
		ref class ComputeShaderWrapper;

		/// <summary>Represents a device context which generates rendering commands.</summary>
		/// <unmanaged>ID3D11DeviceContext</unmanaged>
		public ref class DeviceContext : DeviceChild
		{
			COMOBJECT_CUSTOM(ID3D11DeviceContext, DeviceContext);

		private:
			InputAssemblerWrapper^ inputAssembler;
			OutputMergerWrapper^ outputMerger;
			StreamOutputWrapper^ streamOutput;
			RasterizerWrapper^ rasterizer;
			VertexShaderWrapper^ vertexShader;
			PixelShaderWrapper^ pixelShader;
			GeometryShaderWrapper^ geometryShader;
			DomainShaderWrapper^ domainShader;
			HullShaderWrapper^ hullShader;
			ComputeShaderWrapper^ computeShader;

			void InitializeSubclasses();

		public:
			/// <summary>
			/// Initializes a new instance of the <see cref="DeviceContext"/> class. This instance will be a deferred rendering context.
			/// </summary>
			/// <param name="device">The device used to create the context.</param>
			DeviceContext( SlimDX::Direct3D11::Device^ device );

			/// <summary>
			/// Marks the beginning of a series of asynchronous commands.
			/// </summary>
			/// <param name="data">An asynchronous data provider.</param>
			void Begin( Asynchronous^ data );

			/// <summary>
			/// Clears the specified depth-stencil resource.
			/// </summary>
			/// <param name="view">The view of the resource to clear.</param>
			/// <param name="flags">Flags indicating which parts of the resource to clear.</param>
			/// <param name="depth">The depth value to clear to, if applicable.</param>
			/// <param name="stencil">The stencil value to clear to, if applicable.</param>
			void ClearDepthStencilView( DepthStencilView^ view, DepthStencilClearFlags flags, float depth, System::Byte stencil );

			/// <summary>
			/// Clears the specified render target resource.
			/// </summary>
			/// <param name="view">The view of the resource to clear.</param>
			/// <param name="color">The color to clear to.</param>
			void ClearRenderTargetView( RenderTargetView^ view, Color4 color );

			/// <summary>
			/// Restores all device state to defaults.
			/// </summary>
			void ClearState();

			/// <summary>
			/// Clears an unordered access resource with the given values.
			/// </summary>
			/// <param name="unorderedAccessView">The view of the resource to clear.</param>
			/// <param name="values">Values that will be copied to corresponding channels on the resource.</param>
			void ClearUnorderedAccessView( UnorderedAccessView^ unorderedAccessView, array<int>^ values );

			/// <summary>
			/// Clears an unordered access resource with the given values.
			/// </summary>
			/// <param name="unorderedAccessView">The view of the resource to clear.</param>
			/// <param name="values">Values that will be copied to corresponding channels on the resource.</param>
			void ClearUnorderedAccessView( UnorderedAccessView^ unorderedAccessView, array<float>^ values );

			/// <summary>
			/// Copies resource data using the GPU.
			/// </summary>
			/// <param name="source">The source resource.</param>
			/// <param name="destination">The destination resource.</param>
			void CopyResource( Resource^ source, Resource^ destination );

			/// <summary>
			/// Copies data from a buffer holding variable length data.
			/// </summary>
			/// <param name="unorderedAccessView">The view of the source resource.</param>
			/// <param name="destinationBuffer">The destination buffer.</param>
			/// <param name="destinationOffset">Aligned byte offset from the start of the destination buffer to which data will be copied.</param>
			void CopyStructureCount( UnorderedAccessView^ unorderedAccessView, Buffer^ destinationBuffer, int destinationOffset );

			/// <summary>
			/// Copies a portion of a resource's data using the GPU.
			/// </summary>
			/// <param name="source">The source resource.</param>
			/// <param name="sourceSubresource">The source subresource.</param>
			/// <param name="region">The source region.</param>
			/// <param name="destination">The destination resource.</param>
			/// <param name="destinationSubresource">The destination subresource.</param>
			/// <param name="x">The X offset between the source region origin and the destination location.</param>
			/// <param name="y">The Y offset between the source region origin and the destination location.</param>
			/// <param name="z">The Z offset between the source region origin and the destination location.</param>
			void CopySubresourceRegion( Resource^ source, int sourceSubresource, ResourceRegion region, Resource^ destination, int destinationSubresource, int x, int y, int z );

			/// <summary>
			/// Copies an entire region of a resource's subresource data using the GPU.
			/// </summary>
			/// <param name="source">The source resource.</param>
			/// <param name="sourceSubresource">The source subresource.</param>
			/// <param name="destination">The destination resource.</param>
			/// <param name="destinationSubresource">The destination subresource.</param>
			/// <param name="x">The X offset between the source region origin and the destination location.</param>
			/// <param name="y">The Y offset between the source region origin and the destination location.</param>
			/// <param name="z">The Z offset between the source region origin and the destination location.</param>
			void CopySubresourceRegion( Resource^ source, int sourceSubresource, Resource^ destination, int destinationSubresource, int x, int y, int z );

			/// <summary>
			/// Copies a multisampled resource into a non-multisampled resource.
			/// </summary>
			/// <param name="source">The source resource.</param>
			/// <param name="sourceSubresource">The source subresource.</param>
			/// <param name="destination">The destination resource.</param>
			/// <param name="destinationSubresource">The destination subresource.</param>
			/// <param name="format">The format that indicates how the multisampled resource will be resolved.</param>
			void ResolveSubresource( Resource^ source, int sourceSubresource, Resource^ destination, int destinationSubresource, DXGI::Format format );

			/// <summary>
			/// Copies data from the CPU to to a non-mappable subresource region.
			/// </summary>
			/// <param name="source">The source data.</param>
			/// <param name="resource">The destination resource.</param>
			/// <param name="subresource">The destination subresource.</param>
			void UpdateSubresource( DataBox^ source, Resource^ resource, int subresource );

			/// <summary>
			/// Copies data from the CPU to to a non-mappable subresource region.
			/// </summary>
			/// <param name="source">The source data.</param>
			/// <param name="resource">The destination resource.</param>
			/// <param name="subresource">The destination subresource.</param>
			/// <param name="region">The destination region within the resource.</param>
			void UpdateSubresource( DataBox^ source, Resource^ resource, int subresource, ResourceRegion region );

			/// <summary>
			/// Executes a command list from a thread group.
			/// </summary>
			/// <param name="threadGroupCountX">The number of groups dispatched in the x direction.</param>
			/// <param name="threadGroupCountY">The number of groups dispatched in the y direction.</param>
			/// <param name="threadGroupCountZ">The number of groups dispatched in the z direction.</param>
			void Dispatch( int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ );

			/// <summary>
			/// Execute a command list to draw GPU-generated primitives over one of more thread groups.
			/// </summary>
			/// <param name="arguments">A buffer containing arguments for the thread groups.</param>
			/// <param name="alignedOffset">A byte-aligned offset between the start of the buffer and the arguments.</param>
			void DispatchIndirect( Buffer^ arguments, int alignedOffset );

			/// <summary>
			/// Renders non-indexed, non-instanced primitive data.
			/// </summary>
			/// <param name="vertexCount">The number of vertices to use.</param>
			/// <param name="startVertexLocation">The index of the first vertex.</param>
			void Draw( int vertexCount, int startVertexLocation );

			/// <summary>
			/// Renders non-indexed, instanced primitive data.
			/// </summary>
			/// <param name="vertexCountPerInstance">The number of vertices to use per instance.</param>
			/// <param name="instanceCount">The number of instances to render.</param>
			/// <param name="startVertexLocation">The index of the first vertex.</param>
			/// <param name="startInstanceLocation">The index of the first instance.</param>
			void DrawInstanced( int vertexCountPerInstance, int instanceCount, int startVertexLocation, int startInstanceLocation );

			/// <summary>
			/// Renders non-indexed, instanced, GPU-generated primitive data.
			/// </summary>
			/// <param name="arguments">A buffer containing arguments for the draw call.</param>
			/// <param name="alignedOffset">A byte-aligned offset between the start of the buffer and the arguments.</param>
			void DrawInstancedIndirect( Buffer^ arguments, int alignedOffset );

			/// <summary>
			/// Renders indexed, non-instanced primitive data.
			/// </summary>
			/// <param name="indexCount">The number of indices to use.</param>
			/// <param name="startIndexLocation">The index of the first index.</param>
			/// <param name="baseVertexLocation">The index of the first vertex.</param>
			void DrawIndexed( int indexCount, int startIndexLocation, int baseVertexLocation );

			/// <summary>
			/// Renders indexed, instanced primitive data.
			/// </summary>
			/// <param name="indexCountPerInstance">The number of indices to use per instance.</param>
			/// <param name="instanceCount">The number of instances to render.</param>
			/// <param name="startIndexLocation">The index of the first index.</param>
			/// <param name="baseVertexLocation">The index of the first vertex.</param>
			/// <param name="startInstanceLocation">The index of the first instance.</param>
			void DrawIndexedInstanced( int indexCountPerInstance, int instanceCount, int startIndexLocation, int baseVertexLocation, int startInstanceLocation );

			/// <summary>
			/// Renders indexed, instanced, GPU-generated primitive data.
			/// </summary>
			/// <param name="arguments">A buffer containing arguments for the draw call.</param>
			/// <param name="alignedOffset">A byte-aligned offset between the start of the buffer and the arguments.</param>
			void DrawIndexedInstancedIndirect( Buffer^ arguments, int alignedOffset );

			/// <summary>
			/// Renders primitive data of an unknown size that was created by a geometry shader.
			/// </summary>
			void DrawAuto();

			/// <summary>
			/// Marks the end of a series of asynchronous commands.
			/// </summary>
			/// <param name="data">An asynchronous data provider.</param>
			void End( Asynchronous^ data );

			/// <summary>
			/// Queues commands from a command list onto a device.
			/// </summary>
			/// <param name="commands">The list of commands to execute.</param>
			/// <param name="restoreState">A flag indicating whether the immediate context state is saved (prior) and restored (after) the execution of a command list.</param>
			void ExecuteCommandList( CommandList^ commands, bool restoreState );

			/// <summary>
			/// Create a command list and record graphics commands into it.
			/// </summary>
			/// <param name="restoreState">A flag indicating whether the immediate context state is saved (prior) and restored (after) the execution of a command list.</param>
			/// <returns>The created command list containing the queued rendering commands.</returns>
			CommandList^ FinishCommandList( bool restoreState );

			/// <summary>
			/// Sends queued commands in the command buffer to the GPU.
			/// </summary>
			void Flush();

			/// <summary>
			/// Generates mipmaps for the specified shader resource.
			/// </summary>
			/// <param name="view">A view of the resource for which to generate mipmaps.</param>
			void GenerateMips( ShaderResourceView^ view );

			/// <summary>
			/// Gets the minimum level-of-detail for a resource.
			/// </summary>
			/// <param name="resource">The resource for which level-of-detail information is to be retrieved.</param>
			/// <returns>The minimum level-of-detail for the specified resource.</returns>
			float GetMinimumLod( Resource^ resource );

			/// <summary>
			/// Sets the minimum level-of-detail for a resource.
			/// </summary>
			/// <param name="resource">The resource for which level-of-detail information is to be set.</param>
			/// <param name="minimumLod">The level-of-detail for the resource.</param>
			void SetMinimumLod( Resource^ resource, float minimumLod );

			/// <summary>
			/// Determines if data is available for an asynchronous object.
			/// </summary>
			/// <param name="data">The asynchronous data provider.</param>
			/// <returns><c>true</c> if query data is available for retrieval; otherwise, <c>false</c>.</returns>
			bool IsDataAvailable( Asynchronous^ data );

			/// <summary>
			/// Determines if data is available for an asynchronous object.
			/// </summary>
			/// <param name="data">The asynchronous data provider.</param>
			/// <param name="flags">Flags specifying how the command should operate.</param>
			/// <returns><c>true</c> if query data is available for retrieval; otherwise, <c>false</c>.</returns>
			bool IsDataAvailable( Asynchronous^ data, AsynchronousFlags flags );

			/// <summary>
			/// Gets data from the GPU asynchronously.
			/// </summary>
			/// <param name="data">The asynchronous data provider.</param>
			/// <returns>The data retrieved from the GPU.</returns>
			DataStream^ GetData( Asynchronous^ data );

			/// <summary>
			/// Gets data from the GPU asynchronously.
			/// </summary>
			/// <param name="data">The asynchronous data provider.</param>
			/// <param name="flags">Flags specifying how the command should operate.</param>
			/// <returns>The data retrieved from the GPU.</returns>
			DataStream^ GetData( Asynchronous^ data, AsynchronousFlags flags );

			/// <summary>
			/// Gets data from the GPU asynchronously.
			/// </summary>
			/// <param name="data">The asynchronous data provider.</param>
			/// <returns>The data retrieved from the GPU.</returns>
			generic<typename T> where T : value class
			T GetData( Asynchronous^ data );

			/// <summary>
			/// Gets data from the GPU asynchronously.
			/// </summary>
			/// <param name="data">The asynchronous data provider.</param>
			/// <param name="flags">Flags specifying how the command should operate.</param>
			/// <returns>The data retrieved from the GPU.</returns>
			generic<typename T> where T : value class
			T GetData( Asynchronous^ data, AsynchronousFlags flags );

			/// <summary>
			/// Gets the rendering predicate state.
			/// </summary>
			/// <param name="predicate">When the method completes, contains the predicate interface currently in use.</param>
			/// <param name="predicateValue">When the method completes, contains the predicate comparison value.</param>
			void GetPredication( [Out] Predicate^ %predicate, [Out] bool %predicateValue );

			/// <summary>
			/// Maps a GPU resource into CPU-accessible memory.
			/// </summary>
			/// <param name="resource">The resource to map.</param>
			/// <param name="mipSlice">A zero-based index into an array of subtextures; 0 indicates the first, most detailed subtexture (or mipmap level).</param>
			/// <param name="arraySlice">The zero-based index of the first texture to use (in an array of textures).</param>
			/// <param name="mode">Specifies the CPU's read and write permissions for the resource. </param>
			/// <param name="flags">Flags that specify what the CPU should do when the GPU is busy.</param>
			/// <returns>The mapped resource data.</returns>
			DataBox^ MapSubresource( Texture1D^ resource, int mipSlice, int arraySlice, MapMode mode, MapFlags flags );

			/// <summary>
			/// Maps a GPU resource into CPU-accessible memory.
			/// </summary>
			/// <param name="resource">The resource to map.</param>
			/// <param name="mipSlice">A zero-based index into an array of subtextures; 0 indicates the first, most detailed subtexture (or mipmap level).</param>
			/// <param name="arraySlice">The zero-based index of the first texture to use (in an array of textures).</param>
			/// <param name="mode">Specifies the CPU's read and write permissions for the resource. </param>
			/// <param name="flags">Flags that specify what the CPU should do when the GPU is busy.</param>
			/// <returns>The mapped resource data.</returns>
			DataBox^ MapSubresource( Texture2D^ resource, int mipSlice, int arraySlice, MapMode mode, MapFlags flags );

			/// <summary>
			/// Maps a GPU resource into CPU-accessible memory.
			/// </summary>
			/// <param name="resource">The resource to map.</param>
			/// <param name="mipSlice">A zero-based index into an array of subtextures; 0 indicates the first, most detailed subtexture (or mipmap level).</param>
			/// <param name="arraySlice">The zero-based index of the first texture to use (in an array of textures).</param>
			/// <param name="mode">Specifies the CPU's read and write permissions for the resource. </param>
			/// <param name="flags">Flags that specify what the CPU should do when the GPU is busy.</param>
			/// <returns>The mapped resource data.</returns>
			DataBox^ MapSubresource( Texture3D^ resource, int mipSlice, int arraySlice, MapMode mode, MapFlags flags );

			/// <summary>
			/// Maps a GPU resource into CPU-accessible memory.
			/// </summary>
			/// <param name="resource">The resource to map.</param>
			/// <param name="mode">Specifies the CPU's read and write permissions for the resource. </param>
			/// <param name="flags">Flags that specify what the CPU should do when the GPU is busy.</param>
			/// <returns>The mapped resource data.</returns>
			DataBox^ MapSubresource( Buffer^ resource, MapMode mode, MapFlags flags );

			/// <summary>
			/// Maps a GPU resource into CPU-accessible memory.
			/// </summary>
			/// <param name="resource">The resource to map.</param>
			/// <param name="subresource">Index of the subresource level to lock.</param>
			/// <param name="mode">Specifies the CPU's read and write permissions for the resource. </param>
			/// <param name="flags">Flags that specify what the CPU should do when the GPU is busy.</param>
			/// <returns>The mapped resource data.</returns>
			DataBox^ MapSubresource( Resource^ resource, int subresource, MapMode mode, MapFlags flags );

			/// <summary>
			/// Releases a previously mapped resource.
			/// </summary>
			/// <param name="resource">The resource to unmap.</param>
			/// <param name="subresource">Index of the subresource to unmap.</param>
			void UnmapSubresource( Resource^ resource, int subresource );

			/// <summary>
			/// Sets a rendering predicate.
			/// </summary>
			/// <param name="predicate">The predicate to set.</param>
			/// <param name="predicateValue">If true, rendering will be affected when the predicate's conditions are met. Otherwise,
			/// rendering will be affected when the predicate's conditions are not met.</param>
			void SetPredication( Predicate^ predicate, bool predicateValue );

			/// <summary>
			/// Gets the type of the device context.
			/// </summary>
			property DeviceContextType Type
			{
				DeviceContextType get();
			}

			/// <summary>
			/// Gets the device's input assembler interface.
			/// </summary>
			property InputAssemblerWrapper^ InputAssembler
			{
				InputAssemblerWrapper^ get();
			}

			/// <summary>
			/// Gets the device's output merger interface.
			/// </summary>
			property OutputMergerWrapper^ OutputMerger
			{
				OutputMergerWrapper^ get();
			}

			/// <summary>
			/// Gets the device's stream output interface.
			/// </summary>
			property StreamOutputWrapper^ StreamOutput
			{
				StreamOutputWrapper^ get();
			}

			/// <summary>
			/// Gets the device's rasterizer interface.
			/// </summary>
			property RasterizerWrapper^ Rasterizer
			{
				RasterizerWrapper^ get();
			}

			/// <summary>
			/// Gets the device's vertex shader interface.
			/// </summary>
			property VertexShaderWrapper^ VertexShader
			{
				VertexShaderWrapper^ get();
			}

			/// <summary>
			/// Gets the device's pixel shader interface.
			/// </summary>
			property PixelShaderWrapper^ PixelShader
			{
				PixelShaderWrapper^ get();
			}

			/// <summary>
			/// Gets the device's geometry shader interface.
			/// </summary>
			property GeometryShaderWrapper^ GeometryShader
			{
				GeometryShaderWrapper^ get();
			}

			/// <summary>
			/// Gets the device's domain shader interface.
			/// </summary>
			property DomainShaderWrapper^ DomainShader
			{
				DomainShaderWrapper^ get();
			}

			/// <summary>
			/// Gets the device's hull shader interface.
			/// </summary>
			property HullShaderWrapper^ HullShader
			{
				HullShaderWrapper^ get();
			}

			/// <summary>
			/// Gets the device's compute shader interface.
			/// </summary>
			property ComputeShaderWrapper^ ComputeShader
			{
				ComputeShaderWrapper^ get();
			}
		};
	}
}


text:
class Thumbnail;

namespace cc {
class Layer;
}

namespace android {

// A layer to render a thumbnail.
class ThumbnailLayer : public Layer {
 public:
  // Creates a ThumbnailLayer.
  static scoped_refptr<ThumbnailLayer> Create();
  // Sets thumbnail that will be shown. |thumbnail| should not be nullptr.
  void SetThumbnail(Thumbnail* thumbnail);
  // Clip the thumbnail to the given |clipping|.
  void Clip(const gfx::Rect& clipping);
  void ClearClip();
  // Add self to |parent| or replace self at |index| if there already is an
  // instance with the same ID at |index|.
  void AddSelfToParentOrReplaceAt(scoped_refptr<cc::Layer> parent,
                                  size_t index);

  // Implements Layer.
  scoped_refptr<cc::Layer> layer() override;

 protected:
  ThumbnailLayer();
  ~ThumbnailLayer() override;

 private:
  void UpdateSizes(const gfx::SizeF& content_size,
                   const gfx::SizeF& resource_size);

  scoped_refptr<cc::UIResourceLayer> layer_;
  gfx::SizeF content_size_;
  gfx::Rect last_clipping_;
  bool clipped_ = false;
  gfx::SizeF resource_size_;

  DISALLOW_COPY_AND_ASSIGN(ThumbnailLayer);
};

}  // namespace android

#endif  // CHROME_BROWSER_ANDROID_COMPOSITOR_LAYER_THUMBNAIL_LAYER_H_