text:
<?php
namespace Sonic\UnitTest;

/**
 * Runner
 *
 * Singleton class for running all the unit tests
 *
 * @category Sonic
 * @package UnitTest
 * @author Craig Campbell
 */
class Runner
{
    /**
     * @var Runner
     */
    protected static $_instance;

    /**
     * path to the directory containing the tests we are running
     *
     * @var string
     */
    protected $_directory;

    /**
     * single file we are going to process
     *
     * @var SplFileInfo
     */
    protected $_file;

    /**
     * path to directory to store the coverage report in
     *
     * @var string
     */
    protected $_coverage_directory;

    /**
     * stores the current TestCase object and method
     *
     * @var array
     */
    protected $_current;

    /**
     * args that were passed in via command line
     *
     * @var array
     */
    protected $_args = array();

    /**
     * used to store the coverage per file before we create Coverage objects
     *
     * @todo move this out into some sort of Coverage Tracker object
     * @var array
     */
    protected $_coverage = array();

    /**
     * name of bootstrap file
     *
     * @var string
     */
    const BOOTSTRAP = '_bootstrap.php';

    /**
     * name of shutdown file
     *
     * @var string
     */
    const SHUTDOWN = '_shutdown.php';

    /**
     * constructor
     *
     * @return void
     */
    private function __construct()
    {
        $this->_loadFramework();
    }

    /**
     * gets instance of Runner
     *
     * @return Runner
     */
    public static function getInstance()
    {
        if (!self::$_instance instanceof Runner) {
            self::$_instance = new Runner();
        }
        return self::$_instance;
    }

    /**
     * loads the unit test framework
     *
     * @return void
     */
    protected function _loadFramework()
    {
        include 'Exception.php';
        include 'Coverage.php';
        include 'Result.php';
        include 'Result/Error.php';
        include 'Result/Failure.php';
        include 'Result/Success.php';
        include 'TestCase.php';
        include 'Tracker.php';
    }

    /**
     * starts running the unit tests
     *
     * @param array $args argumnts passed in via command line
     * @return void
     */
    public static function start($args = array())
    {
        $runner = self::getInstance();

        // store the args locally and process them
        $runner->_args = $args;
        $runner->_processArgs($args);

        // set up an error handler so warnings and errors can be caught
        set_error_handler(array($runner, 'handleError'));

        if ($runner->showCoverage()) {
            xdebug_start_code_coverage(XDEBUG_CC_UNUSED);
        }

        if ($runner->hasFile(self::BOOTSTRAP)) {
            $runner->includeFile(self::BOOTSTRAP);
        }

        $runner->runTests($runner->_file);

        $runner->showResults();

        if ($runner->hasFile(self::SHUTDOWN)) {
            $runner->includeFile(self::SHUTDOWN);
        }
    }

    /**
     * processes the command line arguments
     *
     * @param array $args
     * @return void
     */
    protected function _processArgs($args = array())
    {
        if (count($args) == 1) {
            throw new Exception('no test directory specified');
        }

        $dir = array_pop($args);

        if (!is_dir($dir) && !file_exists($dir)) {
            throw new Exception('invalid test directory specified: ' . $dir);
        }

        // single file
        if (!is_dir($dir) && file_exists($dir)) {
            $path = $this->_convertDirectoryToPath($dir);
            $this->_file = new \SplFileInfo($path);
            $this->directory($this->_file->getPath());
        }

        if (is_dir($dir)) {
            $directory = $this->_convertDirectoryToPath($dir);
            $this->directory($directory);
        }

        $coverage_directory = $this->_getArgValue('--coverage-html', $args);
        if (!$coverage_directory) {
            return;
        }

        if (!file_exists($coverage_directory)) {
            mkdir($coverage_directory);
        }
        $path = $this->_convertDirectoryToPath($coverage_directory);
        $this->coverageDirectory($path);
    }

    /**
     * handles runtime errors that occur while the tests are running
     *
     * @param int $type
     * @param string $message
     * @param string $file
     * @param int $line
     * @return void
     */
    public function handleError($type, $message, $file, $line)
    {
        $current = $this->current();
        $method = get_class($current[0]) . '->' . $current[1] . '()';
        $error = new Result\Error($method, $file, $line);
        $error->setMessage($message);
        switch ($type) {
            case E_NOTICE:
                return;
                break;
            default:
                if ($current[0] instanceof TestCase) {
                    $current[0]->logError($error, $current[1]);
                }
                break;
        }
    }

    /**
     * determines if we should show coverage on this run
     *
     * @return bool
     */
    public function showCoverage()
    {
        if (!extension_loaded('xdebug')) {
            return false;
        }

        $valid = array('--coverage', '--coverage-html');
        foreach ($valid as $arg) {
            if (in_array($arg, $this->_args)) {
                return true;
            }
        }
        return false;
    }

    /**
     * determines if this file exists in the tests directory
     *
     * @param string $filename
     * @return bool
     */
    public function hasFile($filename)
    {
        return file_exists($this->directory() . '/' . $filename);
    }

    /**
     * includes a file
     *
     * @param string $filename
     * @return void
     */
    public function includeFile($filename)
    {
        include_once $this->directory() . '/' . $filename;
    }

    /**
     * gets an argument value based on argument name
     *
     * @param string $var
     * @return mixed
     */
    protected function _getArgValue($var)
    {
        $args = $this->_args;

        if (!in_array($var, $args)) {
            return;
        }

        $key = array_search($var, $args);
        if ($key === false) {
            return null;
        }

        if (isset($args[$key + 1])) {
            return $args[$key + 1];
        }

        return null;
    }

    /**
     * converts a relative path passed in via command line to an absolute path
     *
     * @param string $directory
     * @return string
     */
    protected function _convertDirectoryToPath($directory)
    {
        $info = pathinfo($directory);
        $full_path = realpath($info['dirname'] . '/' . $info['basename']);
        return $full_path;
    }

    /**
     * sets or gets coverage directory for html output of code coverage
     *
     * @param string $dir
     * @return string
     */
    public function coverageDirectory($dir = null)
    {
        if ($dir) {
            $this->_coverage_directory = $dir;
        }
        return $this->_coverage_directory;
    }

    /**
     * sets or gets the directory we are currently running tests in
     *
     * @param string $dir
     * @return string
     */
    public function directory($dir = null)
    {
        if ($dir) {
            $this->_directory = $dir;
        }
        return $this->_directory;
    }

    /**
     * runs the tests
     *
     * @return void
     */
    public function runTests(\SplFileInfo $file = null)
    {
        $tracker = Tracker::getInstance();

        $sonic = " ____    ___   _   _  ___  ____\n/ ___|  / _ \ | \ | ||_ _|/ ___|\n\___ \ | | | ||  \| | | || |\n ___) || |_| || |\  | | || |___\n|____/  \___/ |_| \_||___|\____|";

        $tracker->output($sonic, 'yellow');
        $tracker->output(" Unit Test Framework\n\n", 'yellow');

        if ($file) {
            return $this->processFile($file);
        }

        $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory()));
        foreach ($it as $file) {
            $this->processFile($file);
        }
    }

    /**
     * processes a file in the tests directory and if it is a valid test file
     * then run it
     *
     * @param SplFileInfo $file
     * @return void
     */
    public function processFile(\SplFileInfo $file)
    {
        $name = $file->getFilename();

        // ignore underscore files
        if ($name[0] == '_') {
            return;
        }

        // ignore dot files
        if ($name[0] == '.') {
            return;
        }

        // ignore non test files
        if (strpos($name, 'Test.php') === false) {
            return;
        }

        $this->includeFile($name);
        $class_name = str_replace('Test.php', 'Test', $name);

        $test_case = new $class_name;
        $methods = $test_case->getTestMethods();
        foreach ($methods as $method) {
            $this->_runMethod($test_case, $method);
        }
    }

    /**
     * runs a specific test in a file
     *
     * @param TestCase $test
     * @param string $method
     * @return void
     */
    protected function _runMethod(TestCase $test, $method)
    {
        // if the method is not a test method then we should ignore it
        if (preg_match('/test[A-Z0-9_]{1}/', $method) == 0) {
            return;
        }

        $this->current(array($test, $method));

        $tracker = Tracker::getInstance();
        $tracker->incrementTestCount();

        try {
            $test->$method();
        } catch (\Exception $e) {
            $test->caughtException($e);
        }

        $test->hasFinished();

        // log the test result to command line
        if ($test->hadFailure($method)) {
            return $tracker->output('F', 'red');
        }

        if ($test->hadError($method)) {
            return $tracker->output('E', 'yellow');
        }

        return $tracker->output('.', 'green');
    }

    /**
     * gets or sets the current running test
     *
     * @param array $info
     * @return array
     */
    public function current($info = null)
    {
        if ($info !== null) {
            $this->_current = $info;
        }
        return $this->_current;
    }

    /**
     * shows the results for the tests that were run
     *
     * @return void
     */
    public function showResults()
    {
        $tracker = Tracker::getInstance();

        $tracker->outputStats();
        if (count($tracker->getFailures())) {
            $tracker->output("\nFAILURES\n", null, null, true);
            $tracker->outputFailures();
        }

        if (count($tracker->getErrors())) {
            $tracker->output("\nERRORS\n");
            $tracker->outputErrors();
        }

        $tracker->output("\n");

        if (count($tracker->getFailures())) {
            return;
        }

        if ($this->coverageDirectory()) {
            $tracker->output('Generating coverage report as html...' . "\n");
            $this->_generateCoverageHtml();
            return $tracker->output('Done' . "\n");
        }

        if ($this->showCoverage()) {
            $this->_generateCoverageCommandLine();
            return;
        }
    }

    /**
     * generates coverage report for this run as html
     *
     * @todo make this prettier with external view template
     * @return void
     */
    protected function _generateCoverageHtml()
    {
        $coverage = xdebug_get_code_coverage();
        ksort($coverage);

        foreach ($coverage as $file => $lines) {
            $this->_addToCoverageList($file, $lines);
        }

        foreach ($this->_coverage as $file => $lines) {
            $this->_writeCoverageReport($file, $lines);
        }

        $summary = '';
        $summary .= '';
        $summary .= '' . "\n";
        $summary .= '
' . "\n";
        $tracker = Tracker::getInstance();

        $summary .= '

File

All Files

Lines

' . $tracker->getTotalLines() . '

Covered Lines

' . $tracker->getCoveredLines() . '

Percent

' . $tracker->getTotalCoverage() . '%

' . "\n";

        foreach ($tracker->getCoverages() as $coverage) {
            $summary .= '

File

getPath() . '">' . $coverage->getFile() . '

Lines

' . $coverage->getLineCount() . '

Covered Lines

' . $coverage->getCoveredLineCount() . '

Percent

' . $coverage->getPercentCovered() . '%

' . "\n";
        }
        $summary .= '
';
        file_put_contents($this->coverageDirectory() . '/index.html', $summary);
    }

    /**
     * generates coverage report for command line
     *
     * @return void
     */
    protected function _generateCoverageCommandLine()
    {
        $coverage = xdebug_get_code_coverage();
        ksort($coverage);

        foreach ($coverage as $file => $lines) {
            $this->_addToCoverageList($file, $lines);
        }

        foreach ($this->_coverage as $file => $lines) {
            $coverage = $this->_addToCoverage($file, $lines);
            $sizes[] = strlen($file);
        }

        $tracker = Tracker::getInstance();

        $file_pad = max($sizes) + 4;
        $pad = 10;

        $header = str_pad('FILE', $file_pad) . str_pad('LINES', $pad) . str_pad('COVERED', $pad) . str_pad('PERCENT', $pad). "\n";
        $tracker->output($header, 'white', 'black', true);

        $tracker->output(str_pad('All', $file_pad));
        $tracker->output(str_pad($tracker->getTotalLines(), $pad));
        $tracker->output(str_pad($tracker->getCoveredLines(), $pad));
        $total_coverage = $tracker->getTotalCoverage();
        $tracker->output(str_pad($total_coverage, $pad), $this->_getColorForCoverage($total_coverage));
        $tracker->output("\n");

        foreach ($tracker->getCoverages() as $coverage) {
            $tracker->output(str_pad($coverage->getFile(), $file_pad));
            $tracker->output(str_pad($coverage->getLineCount(), $pad));
            $tracker->output(str_pad($coverage->getCoveredLineCount(), $pad));
            $total_coverage = $coverage->getPercentCovered();
            $tracker->output(str_pad($total_coverage, $pad), $this->_getColorForCoverage($total_coverage));
            $tracker->output("\n");
        }
        $tracker->output("\n");
    }

    /**
     * determines which color to show the coverage in
     *
     * @param int $coverage
     * @return string
     */
    protected function _getColorForCoverage($coverage) {
        if ($coverage > 75) {
            return 'green';
        }

        if ($coverage > 25) {
            return 'yellow';
        }

        return 'red';
    }

    /**
     * adds a file to the coverage list
     *
     * @param string $file path to file
     * @param array $lines array from from xdebug_get_code_coverage(XDEBUG_CC_UNUSED)
     * @return void
     */
    protected function _addToCoverageList($file, $lines)
    {
        $tracker = Tracker::getInstance();

        // ignore any files in the tests directory
        if (strpos($file, $this->_directory) !== false) {
            return;
        }

        // don't track coverage on the unit test framework itself
        if (strpos($file, '/UnitTest/') !== false) {
            return;
        }

        // if there are only two lines touched that means the file was included
        // but wasn't used so let's leave it out of the coverage list
        $covered_lines = 0;
        foreach ($lines as $line => $covered) {
            if ($covered == 1) {
                ++$covered_lines;
                continue;
            }
        }

        if ($covered_lines == 2) {
            return;
        }

        // store the coverage temporarily
        $this->_coverage[$file] = $lines;
    }

    /**
     * creates a Coverage object and tracks it
     *
     * @param string $file path to file
     * @param array $lines lines from xdebug_get_code_coverage(XDEBUG_CC_UNUSED)
     * @return Coverage
     */
    protected function _addToCoverage($file, $lines)
    {
        $coverage = new Coverage($file, $lines);
        Tracker::getInstance()->addCoverage($coverage);
        return $coverage;
    }

    /**
     * writes a coverage report as html
     *
     * @param string $file path to file
     * @param array $lines lines from xdebug_get_code_coverage(XDEBUG_CC_UNUSED)
     */
    protected function _writeCoverageReport($file, $lines)
    {
        $coverage = $this->_addToCoverage($file, $lines);
        $coverage->generateReport();
        $coverage->writeToDisk($this->coverageDirectory());
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/rdf/base/idl/nsIRDFContainerUtils.idl
 */

#ifndef __gen_nsIRDFContainerUtils_h__
#define __gen_nsIRDFContainerUtils_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

#ifndef __gen_nsIRDFContainer_h__
#include "nsIRDFContainer.h"
#endif

#ifndef __gen_nsIRDFResource_h__
#include "nsIRDFResource.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsIRDFContainerUtils */
#define NS_IRDFCONTAINERUTILS_IID_STR "d4214e91-fb94-11d2-bdd8-00104bde6048"

#define NS_IRDFCONTAINERUTILS_IID \
  {0xd4214e91, 0xfb94, 0x11d2, \
    { 0xbd, 0xd8, 0x00, 0x10, 0x4b, 0xde, 0x60, 0x48 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIRDFContainerUtils : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IRDFCONTAINERUTILS_IID)

  /* boolean IsOrdinalProperty (in nsIRDFResource aProperty); */
  NS_SCRIPTABLE NS_IMETHOD IsOrdinalProperty(nsIRDFResource *aProperty, bool *_retval NS_OUTPARAM) = 0;

  /* nsIRDFResource IndexToOrdinalResource (in long aIndex); */
  NS_SCRIPTABLE NS_IMETHOD IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource * *_retval NS_OUTPARAM) = 0;

  /* long OrdinalResourceToIndex (in nsIRDFResource aOrdinal); */
  NS_SCRIPTABLE NS_IMETHOD OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM) = 0;

  /* boolean IsContainer (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
  NS_SCRIPTABLE NS_IMETHOD IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) = 0;

  /* boolean IsEmpty (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
  NS_SCRIPTABLE NS_IMETHOD IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) = 0;

  /* boolean IsBag (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
  NS_SCRIPTABLE NS_IMETHOD IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) = 0;

  /* boolean IsSeq (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
  NS_SCRIPTABLE NS_IMETHOD IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) = 0;

  /* boolean IsAlt (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
  NS_SCRIPTABLE NS_IMETHOD IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) = 0;

  /* nsIRDFContainer MakeBag (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
  NS_SCRIPTABLE NS_IMETHOD MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) = 0;

  /* nsIRDFContainer MakeSeq (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
  NS_SCRIPTABLE NS_IMETHOD MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) = 0;

  /* nsIRDFContainer MakeAlt (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
  NS_SCRIPTABLE NS_IMETHOD MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) = 0;

  /* long indexOf (in nsIRDFDataSource aDataSource, in nsIRDFResource aContainer, in nsIRDFNode aElement); */
  NS_SCRIPTABLE NS_IMETHOD IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIRDFContainerUtils, NS_IRDFCONTAINERUTILS_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIRDFCONTAINERUTILS \
  NS_SCRIPTABLE NS_IMETHOD IsOrdinalProperty(nsIRDFResource *aProperty, bool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource * *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIRDFCONTAINERUTILS(_to) \
  NS_SCRIPTABLE NS_IMETHOD IsOrdinalProperty(nsIRDFResource *aProperty, bool *_retval NS_OUTPARAM) { return _to IsOrdinalProperty(aProperty, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource * *_retval NS_OUTPARAM) { return _to IndexToOrdinalResource(aIndex, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM) { return _to OrdinalResourceToIndex(aOrdinal, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return _to IsContainer(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return _to IsEmpty(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return _to IsBag(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return _to IsSeq(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return _to IsAlt(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) { return _to MakeBag(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) { return _to MakeSeq(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) { return _to MakeAlt(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM) { return _to IndexOf(aDataSource, aContainer, aElement, _retval); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIRDFCONTAINERUTILS(_to) \
  NS_SCRIPTABLE NS_IMETHOD IsOrdinalProperty(nsIRDFResource *aProperty, bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsOrdinalProperty(aProperty, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IndexToOrdinalResource(aIndex, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->OrdinalResourceToIndex(aOrdinal, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsContainer(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsEmpty(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsBag(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsSeq(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsAlt(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->MakeBag(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->MakeSeq(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->MakeAlt(aDataSource, aResource, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IndexOf(aDataSource, aContainer, aElement, _retval); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsRDFContainerUtils : public nsIRDFContainerUtils
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIRDFCONTAINERUTILS

  nsRDFContainerUtils();

private:
  ~nsRDFContainerUtils();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsRDFContainerUtils, nsIRDFContainerUtils)

nsRDFContainerUtils::nsRDFContainerUtils()
{
  /* member initializers and constructor code */
}

nsRDFContainerUtils::~nsRDFContainerUtils()
{
  /* destructor code */
}

/* boolean IsOrdinalProperty (in nsIRDFResource aProperty); */
NS_IMETHODIMP nsRDFContainerUtils::IsOrdinalProperty(nsIRDFResource *aProperty, bool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIRDFResource IndexToOrdinalResource (in long aIndex); */
NS_IMETHODIMP nsRDFContainerUtils::IndexToOrdinalResource(PRInt32 aIndex, nsIRDFResource * *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* long OrdinalResourceToIndex (in nsIRDFResource aOrdinal); */
NS_IMETHODIMP nsRDFContainerUtils::OrdinalResourceToIndex(nsIRDFResource *aOrdinal, PRInt32 *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean IsContainer (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsContainer(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean IsEmpty (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsEmpty(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean IsBag (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean IsSeq (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean IsAlt (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::IsAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, bool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIRDFContainer MakeBag (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::MakeBag(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIRDFContainer MakeSeq (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::MakeSeq(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIRDFContainer MakeAlt (in nsIRDFDataSource aDataSource, in nsIRDFResource aResource); */
NS_IMETHODIMP nsRDFContainerUtils::MakeAlt(nsIRDFDataSource *aDataSource, nsIRDFResource *aResource, nsIRDFContainer * *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* long indexOf (in nsIRDFDataSource aDataSource, in nsIRDFResource aContainer, in nsIRDFNode aElement); */
NS_IMETHODIMP nsRDFContainerUtils::IndexOf(nsIRDFDataSource *aDataSource, nsIRDFResource *aContainer, nsIRDFNode *aElement, PRInt32 *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

extern nsresult
NS_NewRDFContainerUtils(nsIRDFContainerUtils** aResult);

#endif /* __gen_nsIRDFContainerUtils_h__ */

redpajama_set_name: RedPajamaGithub


text:
/**
 *  To test the final parameter problem of inner class
 */

package com.ciaoshen.thinkinjava.chapter11;
import java.util.*;

public interface AnonymousInner {

    public void checkOuterFields();
    public void checkAnonymousInnerParam();
    public void checkAnonymousInnerFields();

}


text:
package com.fruedacode.microservices.catalogoservice;

import java.math.BigDecimal;
import java.util.Objects;

/**
 *
 * @author ciberado
 */
public class FichaProducto {

    private String referencia;
    private String modelo;
    private String sexo;
    private String color;
    private String imagen;
    private BigDecimal precio;

    public FichaProducto(String referencia, String modelo, String sexo, String color, String imagen, BigDecimal precio) {
        this.referencia = referencia;
        this.modelo = modelo;
        this.sexo = sexo;
        this.color = color;
        this.imagen = imagen;
        this.precio = precio;
    }

    public String getReferencia() {
        return referencia;
    }

    public void setReferencia(String referencia) {
        this.referencia = referencia;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public String getSexo() {
        return sexo;
    }

    public void setSexo(String sexo) {
        this.sexo = sexo;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getImagen() {
        return imagen;
    }

    public void setImagen(String imagen) {
        this.imagen = imagen;
    }

    public void setPrecio(BigDecimal precio) {
        this.precio = precio;
    }

    public BigDecimal getPrecio() {
        return precio;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 71 * hash + Objects.hashCode(this.referencia);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final FichaProducto other = (FichaProducto) obj;
        if (!Objects.equals(this.referencia, other.referencia)) {
            return false;
        }
        return true;
    }

}


text:
(function() {
  'use strict';

  function comparePasswords(password, comparate, invalidmsg) {
    if (password.value !== comparate.value) {
      password.setCustomValidity(invalidmsg);
    } else {
      password.setCustomValidity('');
    }
  }

  var inputs = document.querySelectorAll('input[compareTo], input[data-compareTo]');

  for (var i = 0, input; input = inputs[i]; i++) {
    var form = input.form;
    var comparateName = input.getAttribute('compareTo')       ||
                        input.getAttribute('data-compareTo')  ||
                        input.getAttribute('compare-to')      ||
                        input.getAttribute('data-compare-to');
    var comparates = form.querySelectorAll('[name="' + comparateName + '"]');

    if (comparates.length === 0) {
      console.error('CompareTo could not find an element with the name "' + comparateName + '". Please ensure that one element with that name exists.');
      continue;
    }

    if (comparates.length > 1) {
      console.error('CompareTo found more than one (' + comparates.length  + ') elements with the name "' + comparateName + '". Please ensure that only one element with that name exists.')
      continue;
    }

    var comparate = comparates[0];
    var error = input.getAttribute('compareToError')        ||
                input.getAttribute('data-compareToError')   ||
                input.getAttribute('compare-to-error')      ||
                input.getAttribute('data-compare-to-error') ||
                'These passwords don\'t match.';

    var callback = (function(input, comparate, invalidmsg) {
      return function() {
        comparePasswords(input, comparate, invalidmsg);
      }
    })(input, comparate, error);

    input.addEventListener('change', callback);
    comparate.addEventListener('change', callback);
  }
}());


text:
{#
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
#}

{% extends "airflow/dag.html" %}
{% from 'appbuilder/custom_icons.html' import icon %}

{% block content %}
  {{ super() }}

    <form method="get" id="daform" action="#">
      <input type="hidden" name="dag_id" value="{{ dag.dag_id }}">
      <input type="hidden" value="{{ task_id }}" name="task_id">

        Task Instance: {{ task_id }}
        at {{ form.execution_date(class_="form-control") }}

    </form>

        details
      Task Instance Details

        code
      Rendered Template

    {% if k8s_or_k8scelery_executor %}

        {{ icon('kubernetes') }}
        K8s Pod Spec

    {% endif %}

        reorder
      Log

        sync_alt
      XCom

{% endblock %}
{% block tail %}
  {{ super() }}

{% endblock %}


text:
title: docker/dtr images
description: List all the images necessary to install DTR
keywords: dtr, cli, images
---

List all the images necessary to install DTR

## Usage

```bash
docker run -it --rm docker/dtr \
    images [command options]
```

## Description

This command lists all the images necessary to install DTR.


text:
**Eigen is a C++ template library for linear algebra: matrices, vectors, numerical solvers, and related algorithms.**

For more information go to http://eigen.tuxfamily.org/.

For ***pull request***, ***bug reports***, and ***feature requests***, go to https://gitlab.com/libeigen/eigen.


text:
<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Validator;

use Input;
use Form;

class BackupDownloadController extends Controller {

	var $apiKey = "---------------";

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	public function isNotAdmin($currentUserJSON)
	{
		$currentUserDecoded = json_decode($currentUserJSON);
		foreach($currentUserDecoded->roles as $value)
			if(strpos($value,"admin") !== false)
				return false;
		return true;
	}

	/**
	 * Display the specified resource.
	 *
	 * @return Response
	 */
	public function show()
	{
		header('Content-Type: application/json');

		$rules = array(
			'tableName'			=> 'required',
			'apiKey' 			=> 'required'
		);
		$validatorFail = Validator::make(\Input::all(), $rules)->fails() ? true : false;
		if ($validatorFail)
		{
			$returnObject = array('error' => 'ERROR: something went wrong.');
			return json_encode($returnObject);
		}

		//session_start();
		$apiKey = \Input::get('apiKey');

		if(!isset($apiKey) || $apiKey != $this->apiKey)
		{
			$returnObject = array('error' => 'ERROR: Only admins can use this functionality!');
			return json_encode($returnObject);
		}

		$tableName = \Input::get('tableName');
		$table = \DB::table($tableName)->get();
		return json_encode($table);
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function store()
	{
		header('Content-Type: application/json');

		$rules = array(
		'tableName'      	 => 'required',
		'modality'			=> 'required',
		'data'			=> 'required'
		);
		$validatorFail = Validator::make(\Input::all(), $rules)->fails() ? true : false;
		if ($validatorFail)
		{
			$returnObject = array('error' => 'ERROR: something went wrong.');
			return json_encode($returnObject);
		}

		$returnObject;
		$apiKey = \Input::get('apiKey');

		if(!isset($apiKey) || $apiKey != $this->apiKey)
		{
			$returnObject = array('error' => 'ERROR: Only admins can use this functionality!');
			return json_encode($returnObject);
		}

		$modality = \Input::get('modality');
		$tableName = \Input::get('tableName');
		$data = \Input::get('data');

		if($modality =="insert")
		{
			\DB::table($tableName)->truncate();
			\DB::table($tableName)->insert(json_decode($data,true));
			$returnObject = array('error' => 'OK');
		}
		else if($modality == "update")
		{
			\DB::table($tableName)->insert(json_decode($data,true));
			$returnObject = array('error' => 'OK');
		}
		return json_encode($returnObject);
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

}


text:
$(document).ready(function () {

    function vuDebug(config) {

        this.config = {
            root: $('base').attr('href')
        };
        $.extend(this.config, config);
        this.toggle = function () {
            $('#vu-debug-bar').toggleClass('open');
            if ($('#vu-debug-bar').is('.open')) {
                this.open();
            } else {
                this.close();
            }
            return false;
        };
        this.open = function () {
            $('#vu-debug-bar').addClass('open');
            $('.vu-debug-tab:first-child').addClass('open');
            $('#vu-debug-tabs li:first-child a').addClass('open');
            $('#vu-debug-close').show();
            return false;
        };
        this.close = function () {
            $('#vu-debug-bar').removeClass('open');
            $('.vu-debug-tab').removeClass('open');
            $('#vu-debug-tabs li a').removeClass('open');
            $('#vu-debug-close').hide();
            return false;
        };
        this.openTab = function (element) {
            if (!$('#vu-debug-bar').is('.open')) {
                this.toggle(element);
            }
            $('.vu-debug-tab').scrollTop(0);
            var target = element.attr('href');
            $('#vu-debug-tabs li a').removeClass('open');
            element.addClass('open');
            $('.vu-debug-tab').removeClass('open');
            $(target).addClass('open');
            return false;
        };
        this.toggleCode = function (element) {
            var content;
            if (!element.find('pre').length) {
                content = element.find('.vu-debug-toggle-pre').html();
                element.find('.vu-debug-toggle-pre').html('
' + content + '
');
            } else {
                content = element.find('.vu-debug-toggle-pre pre').html();
                element.find('.vu-debug-toggle-pre').html(content);
            }
            return false;
        };
        this.countAllMessages = function (element) {
            $(element).each(function () {
                $(this).html($($(this).parent().attr('href') + ' table tr').length);
            });
        };
        this.countMessages = function (target) {
            return $(target).length;
        };
        this.highlightJSON = function (element) {
            $(element).each(function () {
                try {
                    json = JSON.stringify(JSON.parse($(this).html()), null, 2);
                } catch (e) {
                    return;
                }
                json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                $(this).html(json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                    var cls = 'number';
                    if (/^"/.test(match)) {
                        if (/:$/.test(match)) {
                            cls = 'key';
                        } else {
                            cls = 'string';
                        }
                    } else if (/true|false/.test(match)) {
                        cls = 'boolean';
                    } else if (/null/.test(match)) {
                        cls = 'null';
                    }
                    return '' + match + '';
                }));
            });
        };
//        this.console = function (element) {
//            element = $(element);
//            //alert(element.html());
//            object = JSON.stringify(JSON.parse(element.html()), null, 2);
//            var html = '
';
//            $.each(object, function (i, val) {
//                html += '
';
//                html += '
' + val.data + '' + val.type + '
';
//                html += '	' + val.file + ' ' + val.line + '';
//                html += '
';
//            });
//            html += '
';
//            element.html(html);
//        };
    }

    var vuDebug = new vuDebug();
//    vuDebug.countAllMessages('.vu-debug-count');
//    vuDebug.console('#vu-debug-tab-Console pre');
    vuDebug.highlightJSON('.vu-debug-tab pre');
    $('#vu-debug-header:not(#vu-debug-tabs ul)').on('click', function () {
        return vuDebug.toggle();
    });
    $('#vu-debug-close').on('click', function () {
        return vuDebug.close();
    });
    $('#vu-debug-tabs li a').on('click', function () {
        return vuDebug.openTab($(this));
    });
    $('.vu-debug-tab table tr:has(.vu-debug-toggle-pre)').on('click', function () {
        return vuDebug.toggleCode($(this));
    });
    if (vuDebug.countMessages('#vu-debug-tab-console table tr')) {
        vuDebug.open();
    }

});


text:
Third-party private monitor plugins
===================================

This directory can be used to hold monitor plugins developed by third parties who have forked the scalyr-agent-2
repository and do not wish to contrib the plugins to the main Scalyr repository.

Any monitors placed in this directory will be included in the local monitors directory the scaly-agent-2 package
(RPM, Debian, tarball) built by the `build_package.py` tool in the root of this repository.


text:
@interface ViewController ()
@property (nonatomic) CMMotionManager *motionManager;
@property (nonatomic) UIView *containerView, *fluidView, *iceCube1, *iceCube2;
@property (nonatomic) UIGravityBehavior *fluidGravityBehavior, *iceCubeGravityBehavior;
@property (nonatomic) UIAttachmentBehavior *attachmentBehavior;
@property (nonatomic) UIDynamicItemBehavior *fluidItemBehavior;
@property (nonatomic) UICollisionBehavior *iceCubeCollisionBehavior;
@property (nonatomic) UIDynamicAnimator *animator;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
    self.containerView.center = self.view.center;
    self.containerView.backgroundColor = [UIColor clearColor];
    self.containerView.layer.borderColor = [UIColor blackColor].CGColor;
    self.containerView.layer.borderWidth = 2.0f;
    self.containerView.clipsToBounds = YES;
    [self.view addSubview:self.containerView];

    self.fluidView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 300.0f)];
    self.fluidView.backgroundColor = [UIColor colorWithRed:212.0f/255.0f green:151.0f/255.0f blue:76.0f/255.0f alpha:1.0f];
    self.fluidView.center = CGPointMake(50.0f, 200.0f);
    [self.containerView addSubview:self.fluidView];

    self.iceCube1 = [[UIView alloc] initWithFrame:CGRectMake(12.0f, 74.0f, 25.0f, 25.0f)];
    self.iceCube1.backgroundColor = [UIColor clearColor];
    self.iceCube1.layer.cornerRadius = 6.0f;
    self.iceCube1.layer.borderColor = [UIColor blackColor].CGColor;
    self.iceCube1.layer.borderWidth = 2.0f;
    [self.containerView addSubview:self.iceCube1];

    CGRect iceCubeFrame = self.iceCube1.frame;
    iceCubeFrame.origin.y -= CGRectGetHeight(self.iceCube1.bounds);
    iceCubeFrame.origin.x += 12.0f;
    self.iceCube2 =  [[UIView alloc] initWithFrame:iceCubeFrame];
    self.iceCube2.backgroundColor = [UIColor clearColor];
    self.iceCube2.layer.cornerRadius = 6.0f;
    self.iceCube2.layer.borderColor = [UIColor blackColor].CGColor;
    self.iceCube2.layer.borderWidth = 2.0f;
    [self.containerView addSubview:self.iceCube2];

    self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.containerView];

    self.fluidGravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.fluidView]];

    self.iceCubeGravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.iceCube1, self.iceCube2]];

    self.attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:self.fluidView offsetFromCenter:UIOffsetMake(0.0f, -1.0f * CGRectGetHeight(self.fluidView.frame) / 2.0f) attachedToAnchor:CGPointMake(CGRectGetWidth(self.containerView.frame) / 2.0f, (CGRectGetHeight(self.containerView.frame) / 2.0f) - 10.0f)];
    self.attachmentBehavior.length = 10.0f;
    self.attachmentBehavior.damping = 0.0f;

    self.fluidItemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self.fluidView]];
    self.fluidItemBehavior.angularResistance = 10.0f;

    self.iceCubeCollisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.iceCube1, self.iceCube2]];
    [self.iceCubeCollisionBehavior addBoundaryWithIdentifier:@"container" forPath:[UIBezierPath bezierPathWithRect:self.containerView.bounds]];
    [self.animator addBehavior:self.iceCubeCollisionBehavior];

    [self.animator addBehavior:self.attachmentBehavior];

    self.motionManager = [[CMMotionManager alloc] init];
    if (self.motionManager.accelerometerAvailable) {
        __weak typeof(self) weakSelf = self;
        [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
            typeof(self) strongSelf = weakSelf;
//            NSLog(@"%f, %f", accelerometerData.acceleration.x, accelerometerData.acceleration.y);

            //                        x: 0.0f, y: -1.0f
            //     x: -1.0f, y: 0.0f                     x: 1.0f, y: 0.0f
            //                        x: 0.0f, y: 1.0f

            // Factor of 10 is to pull down on liquid much more strongly than horizontal forces
            strongSelf.fluidGravityBehavior.gravityDirection = CGVectorMake(accelerometerData.acceleration.x, 10 * fabsf(accelerometerData.acceleration.y));
            strongSelf.iceCubeGravityBehavior.gravityDirection = CGVectorMake(accelerometerData.acceleration.x, fabsf(accelerometerData.acceleration.y));
        }];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    self.fluidGravityBehavior.gravityDirection = CGVectorMake(0.0f, 1.0f);
    self.iceCubeGravityBehavior.gravityDirection = CGVectorMake(0.0f, 1.0f);
    [self.animator addBehavior:self.fluidGravityBehavior];
    [self.animator addBehavior:self.iceCubeGravityBehavior];
}

@end


text:
/**
 * Main JS file for Casper behaviours
 */

/*globals jQuery, document */
(function ($) {
    "use strict";

    $(document).ready(function(){

        $(".post-content").fitVids();

        // Calculates Reading Time
        $('.post-content').readingTime({
            readingTimeTarget: '.post-reading-time',
            wordCountTarget: '.post-word-count',
            lang: 'cn'
        });

        // Creates Captions from Alt tags
        $(".post-content img").each(function() {
            // Let's put a caption if there is one
            if($(this).attr("alt"))
              $(this).wrap('

')
              .after('
'+$(this).attr("alt")+'
');
        });

    });

}(jQuery));


text:
package net.exacode.spring.social.connect.mongo;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import net.exacode.spring.social.connect.SocialConnectionDao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import com.mongodb.WriteConcern;

/**
 * A MongoDB data access object for spring social connections
 *
 * @author mendlik
 */
@Service
public class MongoConnectionDao implements SocialConnectionDao {

	private final MongoTemplate mongoTemplate;
	private final MongoConnectionConverter converter;

	@Autowired
	public MongoConnectionDao(MongoTemplate mongoTemplate,
			MongoConnectionConverter converter) {
		this.mongoTemplate = mongoTemplate;
		this.converter = converter;
	}

	/**
	 * Returns the max connection rank for the user and the provider.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#getMaxRank(String,
	 *      String)
	 */
	@Override
	public int getMaxRank(String userId, String providerId) {
		// select coalesce(max(rank) + 1, 1) as rank from UserConnection where
		// userId = ? and providerId = ?
		Query q = query(where("userId").is(userId).and("providerId")
				.is(providerId));

		q.with(new Sort(Direction.DESC, "rank"));
		MongoConnection cnn = mongoTemplate.findOne(q, MongoConnection.class);

		if (cnn == null)
			return 1;

		return cnn.getRank() + 1;
	}

	/**
	 * Create a new connection for the user.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#create(String,
	 *      Connection, int)
	 */
	@Override
	public void create(String userId, Connection<?> userConn, int rank) {
		MongoConnection mongoCnn = converter.convert(userConn);
		mongoCnn.setUserId(userId);
		mongoCnn.setRank(rank);
		mongoTemplate.insert(mongoCnn);
	}

	/**
	 * Update a connection.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#update(String,
	 *      Connection)
	 */
	@Override
	public void update(String userId, Connection<?> userConn) {
		MongoConnection mongoCnn = converter.convert(userConn);
		mongoCnn.setUserId(userId);
		try {
			mongoTemplate.setWriteConcern(WriteConcern.SAFE);
			mongoTemplate.save(mongoCnn);
		} catch (DuplicateKeyException e) {
			Query q = query(where("userId").is(userId).and("providerId")
					.is(mongoCnn.getProviderId()).and("providerUserId")
					.is(mongoCnn.getProviderUserId()));

			Update update = Update
					.update("expireTime", mongoCnn.getExpireTime())
					.set("accessToken", mongoCnn.getAccessToken())
					.set("profileUrl", mongoCnn.getProfileUrl())
					.set("imageUrl", mongoCnn.getImageUrl())
					.set("displayName", mongoCnn.getDisplayName());

			mongoTemplate.findAndModify(q, update, MongoConnection.class);
		}
	}

	/**
	 * Remove a connection.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#remove(String,
	 *      ConnectionKey)
	 */
	@Override
	public void remove(String userId, ConnectionKey connectionKey) {
		// delete where userId = ? and providerId = ? and providerUserId = ?
		Query q = query(where("userId").is(userId).and("providerId")
				.is(connectionKey.getProviderId()).and("providerUserId")
				.is(connectionKey.getProviderUserId()));
		mongoTemplate.remove(q, MongoConnection.class);
	}

	/**
	 * Remove all the connections for a user on a provider.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#remove(String,
	 *      String)
	 */
	@Override
	public void remove(String userId, String providerId) {
		// delete where userId = ? and providerId = ?
		Query q = query(where("userId").is(userId).and("providerId")
				.is(providerId));

		mongoTemplate.remove(q, MongoConnection.class);
	}

	/**
	 * Return the primary connection.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#getPrimaryConnection(String,
	 *      String)
	 */
	@Override
	public Connection<?> getPrimaryConnection(String userId, String providerId) {
		// where userId = ? and providerId = ? and rank = 1
		Query q = query(where("userId").is(userId).and("providerId")
				.is(providerId).and("rank").is(1));

		MongoConnection mc = mongoTemplate.findOne(q, MongoConnection.class);
		return converter.convert(mc);
	}

	/**
	 * Get the connection for user, provider and provider user id.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#getConnection(String,
	 *      String, String)
	 */
	@Override
	public Connection<?> getConnection(String userId, String providerId,
			String providerUserId) {
		// where userId = ? and providerId = ? and providerUserId = ?
		Query q = query(where("userId").is(userId).and("providerId")
				.is(providerId).and("providerUserId").is(providerUserId));

		MongoConnection mc = mongoTemplate.findOne(q, MongoConnection.class);
		return converter.convert(mc);
	}

	/**
	 * Get all the connections for an user id.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#getConnections(String)
	 */
	@Override
	public List<Connection<?>> getConnections(String userId) {
		// select where userId = ? order by providerId, rank
		Query q = query(where("userId").is(userId));
		q.with(new Sort(Direction.ASC, "providerId"));
		q.with(new Sort(Direction.ASC, "rank"));
		return runQuery(q);
	}

	/**
	 * Get all the connections for an user id on a provider.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#getConnections(String,
	 *      String)
	 */
	@Override
	public List<Connection<?>> getConnections(String userId, String providerId) {
		// where userId = ? and providerId = ? order by rank
		Query q = new Query(where("userId").is(userId).and("providerId")
				.is(providerId));
		q.with(new Sort(Direction.ASC, "rank"));

		return runQuery(q);
	}

	/**
	 * Get all the connections for an user.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#getConnections(String,
	 *      MultiValueMap)
	 */
	@Override
	public List<Connection<?>> getConnections(String userId,
			MultiValueMap<String, String> providerUsers) {
		// userId? and providerId = ? and providerUserId in (?, ?, ...) order by
		// providerId, rank

		if (providerUsers == null || providerUsers.isEmpty()) {
			throw new IllegalArgumentException(
					"Unable to execute find: no providerUsers provided");
		}

		List<Criteria> lc = new ArrayList<Criteria>();
		for (Entry<String, List<String>> entry : providerUsers.entrySet()) {
			String providerId = entry.getKey();

			lc.add(where("providerId").is(providerId).and("providerUserId")
					.in(entry.getValue()));
		}

		Criteria criteria = where("userId").is(userId);
		criteria.orOperator(lc.toArray(new Criteria[lc.size()]));

		Query q = new Query(criteria);
		q.with(new Sort(Direction.ASC, "providerId"));
		q.with(new Sort(Direction.ASC, "rank"));

		return runQuery(q);
	}

	/**
	 * Get the user ids on the provider.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#getUserIds(String,
	 *      Set)
	 */
	@Override
	public Set<String> getUserIds(String providerId, Set<String> providerUserIds) {
		// select userId from " + tablePrefix + "UserConnection where providerId
		// = :providerId and providerUserId in (:providerUserIds)
		Query q = query(where("providerId").is(providerId)
				.and("providerUserId")
				.in(new ArrayList<String>(providerUserIds)));
		q.fields().include("userId");

		List<MongoConnection> results = mongoTemplate.find(q,
				MongoConnection.class);
		Set<String> userIds = new HashSet<String>();
		for (MongoConnection mc : results) {
			userIds.add(mc.getUserId());
		}

		return userIds;
	}

	/**
	 * Get the user ids on the provider with a given provider user id.
	 *
	 * @see net.exacode.spring.social.connect.SocialConnectionDao#getUserIds(String,
	 *      String)
	 */
	@Override
	public List<String> getUserIds(String providerId, String providerUserId) {
		// select userId where providerId = ? and providerUserId = ?",
		Query q = query(where("providerId").is(providerId)
				.and("providerUserId").is(providerUserId));
		q.fields().include("userId");

		List<MongoConnection> results = mongoTemplate.find(q,
				MongoConnection.class);
		List<String> userIds = new ArrayList<String>();
		for (MongoConnection mc : results) {
			userIds.add(mc.getUserId());
		}

		return userIds;
	}

	private List<Connection<?>> runQuery(Query query) {
		List<MongoConnection> results = mongoTemplate.find(query,
				MongoConnection.class);
		List<Connection<?>> l = new ArrayList<Connection<?>>();
		for (MongoConnection mc : results) {
			l.add(converter.convert(mc));
		}

		return l;
	}

}


text:
"""
Transfer

https://docs.python.org/3/library/copy.html

"""
import sys
import os
import copy

sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), '../../')))

from django.conf import settings
from ozpcenter import models

from ozpcenter.bookmark_helper import BookmarkFolder
from ozpcenter.api.bookmark.model_access import copy_tree_recursive, get_bookmark_tree
import ozpcenter.api.bookmark.serializers as serializers

def _parse_legacy_bookmark_query(application_library_entry_query, current_bookmarks_paths=None):
    """
    parse library endpoint bookmarks

    Args:
        application_library_entry_query: ApplicationLibraryEntry Query
        previous_path_data: ['/',
                            '/heros/',
                            '/heros/Iron Man'...]
    Returns:
        {'bookmark_folder': None,
         'bookmark_listing': None,
         'folders': [],
         'listings': [{'bookmark_listing': (killer_whale-['bigbrother'])},
                      {'bookmark_listing': (lion_finder-['bigbrother'])},
                      {'bookmark_listing': (monkey_finder-['bigbrother'])},
                      {'bookmark_listing': (parrotlet-['jones'])},
                      {'bookmark_listing': (white_horse-['bigbrother'])},
                      {'bookmark_listing': (wolf_finder-['bigbrother'])}]}
    """
    current_bookmarks_paths = current_bookmarks_paths if current_bookmarks_paths else []
    output = {
        'bookmark_folder_name': None,
        'bookmark_listing': None,
        'path': '/',
        'folders': [],
        'listings': []
    }
    output_template = copy.deepcopy(output)

    folder_mapping = {}

    for application_library_entry in application_library_entry_query:
        folder_name = application_library_entry.folder
        listing = application_library_entry.listing

        if folder_name:
            folder_listing_path = '/{}/{}'.format(folder_name, listing.title)
            folder_path = '/{}/'.format(folder_name)

            if folder_path in current_bookmarks_paths:
                print('skip folder bookmark: {}'.format(folder_path))
                continue

            if folder_listing_path in current_bookmarks_paths:
                print('skip listing bookmark: {}'.format(folder_listing_path))
                continue

            if folder_name in folder_mapping:
                folder_mapping[folder_name]['listings'].append({
                    'bookmark_listing': listing,
                    'path': folder_listing_path})
            else:
                folder_mapping[folder_name] = copy.deepcopy(output_template)
                folder_mapping[folder_name]['bookmark_folder_name'] = folder_name
                folder_mapping[folder_name]['path'] = folder_path

                folder_mapping[folder_name]['listings'].append({
                    'bookmark_listing': listing,
                    'path': folder_listing_path})
                output['folders'].append(folder_mapping[folder_name])
        else:
            folder_listing_path = '/{}'.format(listing.title)

            if folder_listing_path in current_bookmarks_paths:
                print('skip listing bookmark: {}'.format(folder_listing_path))
                continue

            output['listings'].append({
                'bookmark_listing': listing,
                'path': folder_listing_path})

    return output

class MockRequest(object):
    def __init__(self, current_profile):
        self.user = current_profile.user
        self.build_absolute_uri = lambda url: url
        self.GET = []

def run():
    """
    Convert ApplicationLibraryEntry (2.0) to BookmarkEntry (3.0)
    """
    DELETE_BOOKMARKS = False

    for current_profile in models.Profile.objects.iterator():
        print('--Processing Username: {}'.format(current_profile.user.username))
        mocked_request = MockRequest(current_profile)

        if DELETE_BOOKMARKS:
            print('Deleting BookmarkEntry records for user, WARNING: it might also delete shared folders')
            print(models.BookmarkEntry.objects.filter(creator_profile=current_profile).delete())

        current_profile_library_query = models.ApplicationLibraryEntry.objects.filter(owner=current_profile)

        # Getting Current Bookmarks
        current_bookmarks = get_bookmark_tree(current_profile, request=mocked_request, serializer_class=serializers.BookmarkSerializer)
        current_bookmarks_paths = BookmarkFolder.parse_endpoint(current_bookmarks).filesystem_structure_list()

        # Creating Copy Tree
        copy_tree = _parse_legacy_bookmark_query(current_profile_library_query, current_bookmarks_paths)
        # import pprint; pprint.pprint(copy_tree)
        copy_tree_objects = copy_tree_recursive(current_profile, copy_tree, None)
        # import pprint; pprint.pprint(copy_tree_objects)

        print('--Bookmarks for Username: {}'.format(current_profile.user.username))
        data = get_bookmark_tree(current_profile, request=mocked_request, serializer_class=serializers.BookmarkSerializer)
        data = BookmarkFolder.parse_endpoint(data).filesystem_structure_list()

        import pprint
        pprint.pprint(data)
        print('-' * 15)


text:
module ZAWS
  class External
    class AWSCLI
      class Generators
        class Result
          class EC2
            class Instances
              def initialize
                @res= {}
                @res["Reservations"]= []
                @res["Reservations"] << { "Instances" => [] }
                self
              end

              def instance_id(instance_number, id)
                resize_instances_array(instance_number)
                @res["Reservations"][0]["Instances"][instance_number]["InstanceId"]=id
                self
              end

              def security_groups(instance_number,groups)
                @res["Reservations"][0]["Instances"][instance_number]["SecurityGroups"]=groups.get_security_groups_array
                self
              end

              def network_interfaces(instance_number,interfaces)
                 @res["Reservations"][0]["Instances"][instance_number]["NetworkInterfaces"]=interfaces.get_network_interfaces_array
                 self
              end

              def tags(instance_number,tags)
                 @res["Reservations"][0]["Instances"][instance_number]["Tags"]=tags.get_tags_array
                 self
              end

              def resize_instances_array(index)
                while index > @res["Reservations"][0]["Instances"].length-1
                 @res["Reservations"][0]["Instances"].push({})
                end
              end

              def get_json
                @res.to_json
              end

              def get_instances_array
                @res["Reservations"][0]["Instances"]
              end

            end
          end
        end
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
URIUtil (Jetty Server Project 6.1.26 API)
</TITLE>

<META NAME="date" CONTENT="2010-11-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../javadoc.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.mortbay.util

Class URIUtil

java.lang.Object
  org.mortbay.util.URIUtil

All Implemented Interfaces:
java.lang.Cloneable

public class URIUtil
extends java.lang.Object
implements java.lang.Cloneable

URI Holder.
 This class assists with the decoding and encoding or HTTP URI's.
 It differs from the java.net.URL class as it does not provide
 communications ability, but it does assist with query string
 formatting.

UTF-8 encoding is used by default for % encoded characters. This
 may be overridden with the org.mortbay.util.URI.charset system property.

Author:

Greg Wilkins (gregw)

See Also:
UrlEncoded

Field Summary

static java.lang.String
__CHARSET

static java.lang.String
HTTP

static java.lang.String
HTTP_COLON

static java.lang.String
HTTPS

static java.lang.String
HTTPS_COLON

static java.lang.String
SLASH

Method Summary

static java.lang.String
addPaths(java.lang.String p1,
         java.lang.String p2)

          Add two URI path segments.

static java.lang.String
canonicalPath(java.lang.String path)

          Convert a path to a cananonical form.

static java.lang.String
compactPath(java.lang.String path)

          Convert a path to a compact form.

static java.lang.String
decodePath(byte[] buf,
           int offset,
           int length)

static java.lang.String
decodePath(java.lang.String path)

static java.lang.String
encodePath(java.lang.String path)

          Encode a URI path.

static java.lang.StringBuffer
encodePath(java.lang.StringBuffer buf,
           java.lang.String path)

          Encode a URI path.

static java.lang.StringBuffer
encodeString(java.lang.StringBuffer buf,
             java.lang.String path,
             java.lang.String encode)

          Encode a URI path.

static boolean
hasScheme(java.lang.String uri)

static java.lang.String
parentPath(java.lang.String p)

          Return the parent Path.

static java.lang.String
stripPath(java.lang.String path)

          Strip parameters from a path.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

SLASH

public static final java.lang.String SLASH

See Also:
Constant Field Values

HTTP

public static final java.lang.String HTTP

See Also:
Constant Field Values

HTTP_COLON

public static final java.lang.String HTTP_COLON

See Also:
Constant Field Values

HTTPS

public static final java.lang.String HTTPS

See Also:
Constant Field Values

HTTPS_COLON

public static final java.lang.String HTTPS_COLON

See Also:
Constant Field Values

__CHARSET

public static final java.lang.String __CHARSET

Method Detail

encodePath

public static java.lang.String encodePath(java.lang.String path)

Encode a URI path.
 This is the same encoding offered by URLEncoder, except that
 the '/' character is not encoded.

Parameters:
path - The path the encode

Returns:
The encoded path

encodePath

public static java.lang.StringBuffer encodePath(java.lang.StringBuffer buf,
                                                java.lang.String path)

Encode a URI path.

Parameters:
path - The path the encode
buf - StringBuffer to encode path into (or null)

Returns:
The StringBuffer or null if no substitutions required.

encodeString

public static java.lang.StringBuffer encodeString(java.lang.StringBuffer buf,
                                                  java.lang.String path,
                                                  java.lang.String encode)

Encode a URI path.

Parameters:
path - The path the encode
buf - StringBuffer to encode path into (or null)
encode - String of characters to encode. % is always encoded.

Returns:
The StringBuffer or null if no substitutions required.

decodePath

public static java.lang.String decodePath(java.lang.String path)

decodePath

public static java.lang.String decodePath(byte[] buf,
                                          int offset,
                                          int length)

addPaths

public static java.lang.String addPaths(java.lang.String p1,
                                        java.lang.String p2)

Add two URI path segments.
 Handles null and empty paths, path and query params (eg ?a=b or
 ;JSESSIONID=xxx) and avoids duplicate '/'

Parameters:
p1 - URI path segment (should be encoded)
p2 - URI path segment (should be encoded)

Returns:
Legally combined path segments.

parentPath

public static java.lang.String parentPath(java.lang.String p)

Return the parent Path.
 Treat a URI like a directory path and return the parent directory.

stripPath

public static java.lang.String stripPath(java.lang.String path)

Strip parameters from a path.
 Return path upto any semicolon parameters.

canonicalPath

public static java.lang.String canonicalPath(java.lang.String path)

Convert a path to a cananonical form.
 All instances of "." and ".." are factored out.  Null is returned
 if the path tries to .. above its root.

Parameters:
path -

Returns:
path or null.

compactPath

public static java.lang.String compactPath(java.lang.String path)

Convert a path to a compact form.
 All instances of "//" and "///" etc. are factored out to single "/"

Parameters:
path -

Returns:
path

hasScheme

public static boolean hasScheme(java.lang.String uri)

Parameters:
uri - URI

Returns:
True if the uri has a scheme

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 1995-2010 Mort Bay Consulting. All Rights Reserved.


text:
//
//  MMAttachedTabBarButton.m
//  MMTabBarView
//
//  Created by Michael Monscheuer on 9/5/12.
//
//

#import "MMAttachedTabBarButton.h"

#import "MMAttachedTabBarButtonCell.h"
#import "MMTabDragAssistant.h"
#import "MMTabStyle.h"
#import "NSView+MMTabBarViewExtensions.h"

#import "PlaylistTabBarItem.h"
#import "MartinAppDelegate.h"
#import "Playlist.h"

@interface MMAttachedTabBarButton (/*Private*/) <NSTextFieldDelegate>

- (MMAttachedTabBarButton *)_selectedAttachedTabBarButton;
- (NSRect)_draggingRect;

@end

@implementation MMAttachedTabBarButton {
  BOOL renamingTitle;
}

@synthesize tabViewItem = _tabViewItem;
@dynamic slidingFrame;
@synthesize isInAnimatedSlide = _isInAnimatedSlide;
@synthesize isInDraggedSlide = _isInDraggedSlide;
@dynamic isSliding;
@dynamic isOverflowButton;

+ (void)initialize {
  [super initialize];
}

+ (Class)cellClass {
  return [MMAttachedTabBarButtonCell class];
}

- (id)initWithFrame:(NSRect)frame tabViewItem:(NSTabViewItem *)anItem {

  self = [super initWithFrame:frame];
  if (self) {
    _tabViewItem = [anItem retain];
    _isInAnimatedSlide = NO;
    _isInDraggedSlide = NO;
  }

  return self;
}

- (id)initWithFrame:(NSRect)frame {

  NSAssert(FALSE,@"please use designated initializer -initWithFrame:tabViewItem:");

  [self release];
  return nil;
}

- (void)dealloc
{
  [_tabViewItem release], _tabViewItem = nil;
  [super dealloc];
}

- (void)drawRect:(NSRect)dirtyRect {
  [super drawRect:dirtyRect];
}

- (MMAttachedTabBarButtonCell *)cell {
  return (MMAttachedTabBarButtonCell *)[super cell];
}

- (void)setCell:(MMAttachedTabBarButtonCell *)aCell {
  [super setCell:aCell];
}

-(void)viewWillDraw {

  NSView *superview = [self superview];
  [superview setNeedsDisplayInRect:[superview bounds]];

  [super viewWillDraw];
}

#pragma mark -
#pragma mark Accessors

- (NSRect)slidingFrame {
  @synchronized(self) {
    return [self frame];
  }
}

- (void)setSlidingFrame:(NSRect)aRect {
  @synchronized(self) {
    aRect.origin.y = [self frame].origin.y;
    [self setFrame:aRect];
  }
}

- (BOOL)isSliding {
  return _isInDraggedSlide || _isInAnimatedSlide;
}

- (void)setTitle:(NSString *)aString {
  [super setTitle:aString];

  // additionally synchronize label of tab view item if appropriate
  if (_tabViewItem && [_tabViewItem respondsToSelector:@selector(label)]) {
    if (![[_tabViewItem label] isEqualToString:aString]) {
      [_tabViewItem setLabel:aString];
    }
  }
}

#pragma mark -
#pragma mark Dividers

- (BOOL)shouldDisplayLeftDivider {

  if ([self isSliding] || ([self tabState] & MMTab_PlaceholderOnLeft))
    return YES;

  return [super shouldDisplayLeftDivider];
}

- (BOOL)shouldDisplayRightDivider {

  if ([self isOverflowButton])
    return NO;

  return YES;
}

#pragma mark -
#pragma mark Interfacing Cell

- (BOOL)isOverflowButton {
  return [[self cell] isOverflowButton];
}

- (void)setIsOverflowButton:(BOOL)value {
  [[self cell] setIsOverflowButton:value];
}

#pragma mark -
#pragma mark Event Handling

- (void)mouseDown:(NSEvent *)theEvent {
  MMAttachedTabBarButton *previousSelectedButton = [self _selectedAttachedTabBarButton];

  MMTabBarView *tabBarView = [self tabBarView];

  // select immediately
  if ([tabBarView selectsTabsOnMouseDown]) {
    if (self != previousSelectedButton) {
      [previousSelectedButton setState:NSOffState];
      [self setState:NSOnState];
      [self sendAction:[self action] to:[self target]];
    }
  }

  // eventually begin dragging of button
  if ([tabBarView shouldStartDraggingAttachedTabBarButton:self withMouseDownEvent:theEvent]) {
    [tabBarView startDraggingAttachedTabBarButton:self withMouseDownEvent:theEvent];
  }
}

- (void)mouseUp:(NSEvent *)theEvent {
  MMTabBarView *tabBarView = [self tabBarView];

  NSPoint mouseUpPoint = [theEvent locationInWindow];
  NSPoint mousePt = [self convertPoint:mouseUpPoint fromView:nil];

  if (NSMouseInRect(mousePt, [self bounds], [self isFlipped])) {
    if (![tabBarView selectsTabsOnMouseDown]) {
      MMAttachedTabBarButton *previousSelectedButton = [self _selectedAttachedTabBarButton];
      [previousSelectedButton setState:NSOffState];
      [self setState:NSOnState];
      [self sendAction:[self action] to:[self target]];
    }

    if (theEvent.clickCount > 1) {
      [self beginRenaming];
    }
  }
}

#pragma mark - Martin renaming support

static const int kRenameFieldTag = 601;

- (void)beginRenaming {
  PlaylistTabBarItem *item = self.tabViewItem.identifier;

  if ([self viewWithTag:kRenameFieldTag] != nil || item.playlist.isQueue == YES) {
    return;
  }

  renamingTitle = YES;

  NSTextField *renameField = [[NSTextField alloc] initWithFrame:NSOffsetRect(NSInsetRect(self.bounds, 20, 0), 0, 3)];
  renameField.tag = kRenameFieldTag;
  renameField.delegate = self;
  renameField.focusRingType = NSFocusRingTypeNone;

  NSTextFieldCell *cell = renameField.cell;
  cell.editable = YES;
  cell.bezeled = NO;
  cell.bordered = NO;
  cell.drawsBackground = NO;
  cell.usesSingleLineMode = YES;
  cell.alignment = NSCenterTextAlignment;
  cell.wraps = YES;
  cell.lineBreakMode = NSLineBreakByTruncatingTail;
  cell.font = self.cell.font;

  cell.stringValue = item.title;

  // this hides tab's title but leaves it's size intact
  self.attributedTitle = [[NSAttributedString alloc] initWithString:@""];

  [self addSubview:renameField];

  [[MartinAppDelegate get].window makeFirstResponder:renameField];
}

- (void)endRenaming {
  if (renamingTitle == NO) {
    return;
  }

  renamingTitle = NO;
  NSTextField *renameField = [self viewWithTag:kRenameFieldTag];
  [renameField removeFromSuperview];
}

- (void)cancelRenaming {
  if (renamingTitle == NO) {
    return;
  }

  PlaylistTabBarItem *item = self.tabViewItem.identifier;
  self.title = item.title;
  [self endRenaming];
}

- (void)cancelOperation:(id)sender {
  [self cancelRenaming];
}

- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor {
  if (renamingTitle == NO) {
    return YES;
  }

  PlaylistTabBarItem *item = self.tabViewItem.identifier;
  item.title = fieldEditor.string;
  [self endRenaming];
  return YES;
}

#pragma mark - Martin delete with middle click support

- (void)otherMouseUp:(NSEvent *)theEvent {
  [self.tabBarView _didClickCloseButton:_closeButton];
}

#pragma mark - Martin now playing support

- (void)updateNowPlayingIndicator {
  PlaylistTabBarItem *item = self.tabViewItem.identifier;
  Playlist *playlist = item.playlist;
  BOOL nowPlaying = [[MartinAppDelegate get].playerController nowPlayingItemFromPlaylist:playlist];

  CGFloat fontSize = self.cell.font.pointSize;
  NSFont *font = nowPlaying? [NSFont boldSystemFontOfSize:fontSize]: [NSFont systemFontOfSize:fontSize];
  self.cell.font = font;
}

#pragma mark -
#pragma mark Drag Support

- (NSRect)draggingRect {
  return [self _draggingRect];
}

- (NSImage *)dragImage {

  // assure that we will draw the tab bar contents correctly
  [self setFrame:[self stackingFrame]];

  MMTabBarView *tabBarView = [self tabBarView];

  NSRect draggingRect = [self draggingRect];

	[tabBarView lockFocus];
  [tabBarView display];  // forces update to ensure that we get current state
	NSBitmapImageRep *rep = [[[NSBitmapImageRep alloc] initWithFocusedViewRect:draggingRect] autorelease];
	[tabBarView unlockFocus];
	NSImage *image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
	[image addRepresentation:rep];
	NSImage *returnImage = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
	[returnImage lockFocus];
  [image drawAtPoint:NSMakePoint(0.0, 0.0) fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
	[returnImage unlockFocus];
	if (![[self indicator] isHidden]) {
		NSImage *pi = [[NSImage alloc] initByReferencingFile:[[MMTabBarView bundle] pathForImageResource:@"pi"]];
		[returnImage lockFocus];
		NSPoint indicatorPoint = NSMakePoint([self frame].size.width - MARGIN_X - kMMTabBarIndicatorWidth, MARGIN_Y);
    [pi drawAtPoint:indicatorPoint fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
		[returnImage unlockFocus];
		[pi release];
	}
	return returnImage;
}

#pragma mark -
#pragma mark Animation Support

- (void)slideAnimationWillStart {
  _isInAnimatedSlide = YES;
}

- (void)slideAnimationDidEnd {
  _isInAnimatedSlide = NO;
}

#pragma mark -
#pragma mark Private Methods

- (MMAttachedTabBarButton *)_selectedAttachedTabBarButton {

  MMTabBarView *tabBarView = [self enclosingTabBarView];
  return [tabBarView selectedAttachedButton];
}

- (NSRect)_draggingRect {
  return [self frame];
}

@end


text:
<root>
  <page>
    <script when="docapi.BEFORE" language="js">
	  var util = require('util');
	  var modules = require('__init__').modules.core;
	  var lines = [];
	  Object.keys(modules).forEach(function (name) {
	    var label = util.format( '%s (%s)', name, modules[name] );
	    var module = require(name);
	    lines.push(label, "~".repeat( label.length ), util.inspect(module), '');
	  });
	  console.log(lines.join('\n'));
    </script>
  </page>
</root>


text:
package untouchedwagons.minecraft.mindcrackermobs.item;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import untouchedwagons.minecraft.mindcrackermobs.MindcrackerMobsMod;

import java.util.List;

public class ItemBeefBoots extends ItemArmor {
    public ItemBeefBoots() {
        super(ArmorMaterial.DIAMOND, 3, 3); // The first '3' means diamond, the second '3' means boots

        this.setUnlocalizedName("beefBoots");
        this.setTextureName("diamond_boots");
    }

    @SideOnly(Side.CLIENT)
    public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4)
    {
        String s = EnumChatFormatting.YELLOW + par2EntityPlayer.getDisplayName() + " did a Vintage Beef" + EnumChatFormatting.RESET;

        //noinspection unchecked
        par3List.add(s);
    }

    @Override
    public void getSubItems(Item p_150895_1_, CreativeTabs p_150895_2_, List p_150895_3_) {
        //noinspection unchecked
        p_150895_3_.add(createBoots());
    }

    public static ItemStack createBoots() {
        ItemStack boot_stack = new ItemStack(MindcrackerMobsMod.beef_boots);

        boot_stack.addEnchantment(Enchantment.featherFalling, 5);

        return boot_stack;
    }
}


text:
import json

from nose.tools import eq_

from lib.sellers.constants import (ACCESS_PURCHASE, ACCESS_SIMULATE,
                                   EXTERNAL_PRODUCT_ID_IS_NOT_UNIQUE)
from lib.sellers.models import Seller, SellerProduct, SellerPaypal
from solitude.base import APITest

uuid = 'sample:uid'

class TestSeller(APITest):

    def setUp(self):
        self.api_name = 'generic'
        self.list_url = self.get_list_url('seller')

    def test_add(self):
        res = self.client.post(self.list_url, data={'uuid': uuid})
        eq_(res.status_code, 201)
        eq_(Seller.objects.filter(uuid=uuid).count(), 1)

    def test_add_multiple(self):
        self.client.post(self.list_url, data={'uuid': uuid})
        res = self.client.post(self.list_url, data={'uuid': uuid})
        eq_(res.status_code, 400)
        eq_(self.get_errors(res.content, 'uuid'),
            ['Seller with this Uuid already exists.'])

    def test_add_empty(self):
        res = self.client.post(self.list_url, data={'uuid': ''})
        eq_(res.status_code, 400)
        eq_(self.get_errors(res.content, 'uuid'), ['This field is required.'])

    def test_add_missing(self):
        res = self.client.post(self.list_url, data={})
        eq_(res.status_code, 400)
        eq_(self.get_errors(res.content, 'uuid'), ['This field is required.'])

    def test_list_allowed(self):
        self.allowed_verbs(self.list_url, ['post', 'get'])

    def create(self):
        return Seller.objects.create(uuid=uuid)

    def test_get(self):
        obj = self.create()
        res = self.client.get(self.get_detail_url('seller', obj))
        eq_(res.status_code, 200)
        content = json.loads(res.content)
        eq_(content['uuid'], uuid)
        eq_(content['resource_pk'], obj.pk)

class TestSellerPaypal(APITest):

    def setUp(self):
        self.api_name = 'paypal'
        self.seller = Seller.objects.create(uuid=uuid)
        self.list_url = self.get_list_url('seller')

    def data(self):
        return {'seller': '/generic/seller/%s/' % self.seller.pk,
                'paypal_id': 'foo@bar.com',
                'address_one': '123 main st.',
                'country': 'canada'}

    def test_post(self):
        res = self.client.post(self.list_url, data=self.data())
        eq_(res.status_code, 201)
        objs = SellerPaypal.objects.all()
        eq_(objs.count(), 1)
        eq_(objs[0].paypal_id, 'foo@bar.com')
        eq_(objs[0].address_one, '123 main st.')

    def test_get(self):
        obj = self.create()
        url = self.get_detail_url('seller', obj)
        res = self.client.get(url)
        eq_(res.status_code, 200)
        eq_(json.loads(res.content)['token'], False)
        eq_(json.loads(res.content)['secret'], False)

    def test_get_generic(self):
        self.create()
        url = self.get_detail_url('seller', self.seller, api_name='generic')
        res = self.client.get(url)
        eq_(res.status_code, 200)
        content = json.loads(res.content)
        eq_(content['paypal']['token'], False)
        eq_(content['paypal']['secret'], False)

    def create(self):
        return SellerPaypal.objects.create(seller=self.seller,
                                           address_one='123 main st.')

    def test_booleans(self):
        obj = self.create()
        url = self.get_detail_url('seller', obj)

        res = self.client.get(url, data={'uuid': uuid})
        content = json.loads(res.content)
        eq_(content['secret'], False)
        eq_(content['token'], False)

        obj.token = obj.secret = 'abc'
        obj.save()

        res = self.client.get(url, data={'uuid': uuid})
        content = json.loads(res.content)
        eq_(content['secret'], True)
        eq_(content['token'], True)

    def test_set_paypal_id(self):
        obj = self.create()
        url = self.get_detail_url('seller', obj)
        id_ = 'foo@bar.com'
        res = self.client.put(url, data={'paypal_id': id_})
        eq_(res.status_code, 202)
        eq_(json.loads(res.content)['paypal_id'], id_)

    def test_patch(self):
        obj = self.create()
        url = self.get_detail_url('seller', obj)
        id_ = 'foo@bar.com'
        secret = 'some-secret'
        obj.secret = secret
        obj.save()

        res = self.client.patch(url, data={'paypal_id': id_})
        eq_(res.status_code, 202, res.content)
        res = SellerPaypal.objects.get(pk=obj.pk)
        eq_(res.secret, secret)
        eq_(res.paypal_id, id_)
        eq_(res.address_one, '123 main st.')

    def test_list_allowed(self):
        obj = self.create()
        url = self.get_detail_url('seller', obj)

        self.allowed_verbs(self.list_url, ['post', 'get'])
        self.allowed_verbs(url, ['get', 'delete', 'put', 'patch'])

class TestSellerProduct(APITest):

    def setUp(self):
        self.api_name = 'generic'
        self.seller = Seller.objects.create(uuid=uuid)
        self.seller_url = self.get_detail_url('seller', self.seller.pk)
        self.list_url = self.get_list_url('product')

    def create(self, **kw):
        params = {'seller': self.seller, 'external_id': 'xyz',
                  'public_id': uuid}
        params.update(kw)
        return SellerProduct.objects.create(**params)

    def create_url(self):
        obj = self.create(public_id='%s-url' % uuid)
        url = self.get_detail_url('product', obj)
        return obj, url

    def data(self, **kw):
        params = {'seller': self.seller_uri(),
                  'external_id': 'pre-generated-product-id',
                  'secret': 'hush',
                  'access': ACCESS_PURCHASE,
                  'public_id': 'public-id'}
        params.update(**kw)
        return params

    def seller_uri(self):
        return self.get_detail_url('seller', self.seller.pk)

    def test_get_miss(self):
        # A test that filtering on the wrong uuid returns zero.
        self.create()
        res = self.client.get(self.list_url, data={'seller__uuid': 'foo'})
        eq_(json.loads(res.content)['meta']['total_count'], 0)

    def test_get_all(self):
        # No filters at all still returns everything.
        self.create()
        res = self.client.get(self.list_url)
        eq_(json.loads(res.content)['meta']['total_count'], 1)

    def test_get_one(self):
        # Getting just one object just works.
        self.create()
        res = self.client.get(self.list_url, data={'seller__uuid': uuid})
        eq_(json.loads(res.content)['meta']['total_count'], 1)

    def test_not_active(self):
        obj = self.create()
        obj.seller.active = False
        obj.seller.save()
        res = self.client.get(self.list_url, data={'seller__uuid': uuid,
                                                   'seller__active': True})
        eq_(json.loads(res.content)['meta']['total_count'], 0)

    def test_post(self):
        res = self.client.post(self.list_url, data=self.data())
        eq_(res.status_code, 201)
        objs = SellerProduct.objects.all()
        eq_(objs.count(), 1)

    def test_get_by_external_id(self):
        prod = self.create(external_id='my-id')
        res = self.client.get(self.list_url, data={'seller': self.seller.pk,
                                                   'external_id': 'my-id'})
        eq_(res.status_code, 200)
        data = json.loads(res.content)
        eq_(data['meta']['total_count'], 1)
        eq_(data['objects'][0]['resource_pk'], prod.pk)

    def test_get_by_public_id(self):
        self.create(public_id='one', external_id='one')
        self.create(public_id='two', external_id='two')
        res = self.client.get(self.list_url, data={'seller': self.seller.pk,
                                                   'public_id': 'one'})
        eq_(res.status_code, 200, res)
        data = json.loads(res.content)
        eq_(data['meta']['total_count'], 1)
        eq_(data['objects'][0]['public_id'], 'one')

    def test_id_unique_for_seller_error(self):
        res = self.client.post(self.list_url,
                               data=self.data(external_id='unique-id'))
        eq_(res.status_code, 201, res.content)
        # Submit the same ID for the same seller.
        res = self.client.post(self.list_url,
                               data=self.data(external_id='unique-id'))
        eq_(res.status_code, 400)
        eq_(self.get_errors(res.content, '__all__'),
            [EXTERNAL_PRODUCT_ID_IS_NOT_UNIQUE], res.content)

    def test_id_unique_for_seller_ok(self):
        res = self.client.post(self.list_url,
                               data=self.data(external_id='unique-id'))
        eq_(res.status_code, 201)

        new_seller = Seller.objects.create(uuid='some-other-seller')

        data = self.data(seller=self.get_detail_url('seller', new_seller.pk),
                         external_id='unique-id', public_id='blah')
        res = self.client.post(self.list_url, data=data)
        eq_(res.status_code, 201)

    def test_list_allowed(self):
        obj, url = self.create_url()

        self.allowed_verbs(self.list_url, ['post', 'get'])
        self.allowed_verbs(url, ['get', 'put', 'patch'])

    def test_patch_get_secret(self):
        obj, url = self.create_url()
        res = self.client.patch(url, json.dumps({'seller': self.seller_url,
                                                 'external_id': 'xyz',
                                                 'secret': 'hush'}))
        eq_(res.status_code, 202, res.content)
        res = self.client.get(url)
        data = json.loads(res.content)
        eq_(data['secret'], 'hush')

    def test_patch_get_access(self):
        obj, url = self.create_url()
        res = self.client.patch(url, json.dumps({'access': ACCESS_SIMULATE}))
        eq_(res.status_code, 202, res.content)
        res = self.client.get(url)
        data = json.loads(res.content)
        eq_(data['access'], ACCESS_SIMULATE)

    def test_patch_get_ext_id(self):
        obj, url = self.create_url()
        res = self.client.patch(url, json.dumps({'seller': self.seller_url,
                                                 'external_id': 'some-id'}))
        eq_(res.status_code, 202)
        data = obj.reget()
        eq_(data.external_id, 'some-id')

    def test_put_get(self):
        obj, url = self.create_url()
        res = self.client.put(url, json.dumps({'seller': self.seller_url,
                                               'secret': 'hush',
                                               'access': ACCESS_PURCHASE,
                                               'external_id': 'abc',
                                               'public_id': 'blah'}))
        eq_(res.status_code, 202)
        data = obj.reget()
        eq_(data.secret, 'hush')
        eq_(data.external_id, 'abc')

    def test_patch_non_unique_ext_id(self):
        self.create(external_id='some-id')
        obj, url = self.create_url()
        res = self.client.patch(url, json.dumps({'external_id': 'some-id'}))
        eq_(res.status_code, 400)
        eq_(self.get_errors(res.content, '__all__'),
            [EXTERNAL_PRODUCT_ID_IS_NOT_UNIQUE], res.content)

    def test_put_non_unique_ext_id(self):
        self.create(external_id='some-id')
        obj, url = self.create_url()
        res = self.client.put(url, json.dumps({'seller': self.seller_url,
                                               'secret': 'hush',
                                               'external_id': 'some-id',
                                               'public_id': 'blah'}))
        eq_(res.status_code, 400)
        eq_(self.get_errors(res.content, '__all__'),
            [EXTERNAL_PRODUCT_ID_IS_NOT_UNIQUE], res.content)


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['addafter'] = 'Añadir un nuevo Capítulo';
$string['book:addinstance'] = 'Añadir un nuevo libro';
$string['book:edit'] = 'Editar capítulos de libro';
$string['book:read'] = 'Leer libro';
$string['book:viewhiddenchapters'] = 'Ver capítulos de libro oculto';
$string['chapters'] = 'Capítulos';
$string['chaptertitle'] = 'Título del Capítulo';
$string['confchapterdelete'] = '¿Realmente quiere eliminar este Capítulo?';
$string['confchapterdeleteall'] = '¿Está seguro que quiere eliminar este capítulo y todos sus subcapítulos?';
$string['content'] = 'Contenido';
$string['customtitles'] = 'Títulos personalizados';
$string['customtitles_help'] = 'Los títulos de los capítulos se muestran automáticamente sólo en la tabla de contenido y como una cabecera encima del contenido.

Si se marca la opción "Títulos personalizados", el título del capítulo no se muestra como una cabecera encima del contenido. Se puede introducir un título diferente (puede que incluso más largo que el del capítulo) como parte del contenido.';
$string['editingchapter'] = 'Edición de capítulo';
$string['errorchapter'] = 'Error al leer el capítulo del libro.';
$string['modulename'] = 'Libro';
$string['modulename_help'] = 'El módulo libro permite crear material de estudio de múltiples páginas en formato libro, con capítulos y subcapítulos. El libro puede incluir contenido multimedia así como texto y es útil para mostrar grandes volúmenes de información repartido en secciones.

Un libro puede usarse

* Para mostrar material de lectura de los módulos individuales de estudio
* Como un manual para el personal del departamento
* Como un portafolio de trabajos de los estudiantes';
$string['modulenameplural'] = 'Libros';
$string['navexit'] = 'Salir del libro';
$string['navnext'] = 'Siguiente';
$string['navprev'] = 'Anterior';
$string['nocontent'] = 'Aún no se ha añadido contenido a este libro.';
$string['numbering'] = 'Numeración del capítulo';
$string['numbering0'] = 'Nada';
$string['numbering1'] = 'Númerica';
$string['numbering2'] = 'Viñetas';
$string['numbering3'] = 'Sangrado';
$string['numbering_help'] = '* Ninguno - los títulos de capítulos y subcapítulos no tienen formato
* Números - los capítulos y subcapítulos son numerados (1, 1.1, 1.2, 2, ...)
* Viñetas - los subcapítulos son indentados y son mostrados con viñetas
* Sangría - los subcapítulos son indentados';
$string['numberingoptions'] = 'Opciones de formato de capítulos disponibles';
$string['numberingoptions_desc'] = 'Seleccionar opciones de numeración que estaran disponibles al crear nuevos libros.';
$string['page-mod-book-x'] = 'Cualquier página del módulo Libro';
$string['pluginadministration'] = 'Administración del Libro';
$string['pluginname'] = 'Libro';
$string['subchapter'] = 'Subcapítulo';
$string['subchapternotice'] = '(Disponible una vez que el primer capítulo se haya creado)';
$string['subplugintype_booktool'] = 'Herramienta Libro';
$string['subplugintype_booktool_plural'] = 'Herramientas Libro';
$string['toc'] = 'Tabla de contenidos';
$string['top'] = 'arriba';