text:
<?php
namespace Myspace\BookmarkBundle\Controller;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Myspace\BookmarkBundle\Entity\Bookmark;
use Myspace\BookmarkBundle\Entity\Category;
use Myspace\BookmarkBundle\Entity\ImportFile;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    public function angularjsAction()
    {
        return $this->render('MyspaceBookmarkBundle:Default:angular.html.twig', array());
    }

    public function iconAction()
    {
        return $this->render('MyspaceBookmarkBundle:Default:icon.html.twig', array());
    }

    /**
     * @Route("/tag/{tagid}", name="tag_detail")
     */
    public function tagAction($tagid)
    {
        $tag = $this->getDoctrine()
            ->getRepository('MyspaceBookmarkBundle:Tag')
            ->findOneById($tagid);
        return $this->render('MyspaceBookmarkBundle:Default:tag.html.twig', array('tag' => $tag));
    }

    /**
     * @Route("/bookmark/{bookmarkid}", name="bookmark_detail")
     */
    public function bookmarkAction($bookmarkid)
    {
        $bookmark = $this->getDoctrine()
            ->getRepository('MyspaceBookmarkBundle:Bookmark')
            ->findOneById($bookmarkid);
        return $this->render('MyspaceBookmarkBundle:Default:bookmark.html.twig', array('bookmark' => $bookmark));
    }

    /**
     * @Route("/category/{catid}", name="category_detail")
     */
    public function categoryAction($catid)
    {
        $bookmarks = $this->getDoctrine()
            ->getRepository('MyspaceBookmarkBundle:Bookmark')
            ->findByCategory($catid);
        return $this->render('MyspaceBookmarkBundle:Default:bookmarksbbycategory.html.twig', array('bookmarks' => $bookmarks));
    }

    /**
     * @Route("/", name="index")
     */
    public function indexAction()
    {
        $cats = $this->getDoctrine()
            ->getRepository('MyspaceBookmarkBundle:Category')
            ->findAll();
        $tags = $this->getDoctrine()
            ->getRepository('MyspaceBookmarkBundle:Tag')
            ->findAll();
        $array = array($cats, $tags);

        return $this->render('MyspaceBookmarkBundle:Default:index.html.twig', array('array' => $array));
    }

    /**
     * @Route("/import", name="import_data")
     */
    public function importAction(Request $request)
    {
        set_time_limit(0);
        $importFile = new ImportFile();

        $form = $this->createFormBuilder($importFile)
            ->add('file', 'file')
            ->add('save', 'submit', array('label' => 'Import'))
            ->getForm();
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            // perform some action, such as saving the task to the database
            $filePath = $importFile->getFile();

            //truncat all table:
            /** @var EntityManager $entityManager */
            $entityManager = $this->getDoctrine()->getManager();
            /** @var Connection $connection */
            $connection = $entityManager->getConnection();
            $schemaManager = $connection->getSchemaManager();
            $tables = $schemaManager->listTables();
            $query = '';
            $connection->query('SET FOREIGN_KEY_CHECKS=0');
            foreach ($tables as $table) {
                $name = $table->getName();
                $query .= 'TRUNCATE ' . $name . ';';
            }
            $connection->executeQuery($query, array(), array());
            $connection->query('SET FOREIGN_KEY_CHECKS=1');

            $fileContent = file_get_contents($filePath);
            $array = explode("\n", $fileContent);
            $newarr = array();
            foreach ($array as $line) {
                if (strpos($line, "<H3 ADD_DATE") !== false || strpos($line, "
([^<]+)</";
            $addDate = "/ADD_DATE=\"(\\d+)\"/";
            $lastModify = "/LAST_MODIFIED=\"(\\d+)\"/";
            $herf = "/HREF=\"([^\"]+)\"/";
            $icon = "/ICON=\"([^\"]+)\"/";
            $flushItemCount = 0;
            foreach ($newarr as $line) {
                $flushItemCount++;
                if (strpos($line, "setName($texts[1]);
                    $category->setCreated($this->getDateTimeFromTimestamp($addDates[1]));
                    $category->setLastModified($this->getDateTimeFromTimestamp($lastModifies[1]));
                    $em->persist($category);

                    $currentCategory = $category;
                } else if (strpos($line, "
setUrl($hrefs[1]);
                    if (count($texts) > 0) {
                        $bookmark->setTitle($texts[1]);
                    }

                    if (count($icons) > 0) {
                        $bookmark->setIcon($icons[1]);
                    }

                    if(count($addDates) > 0) {
                        $date = $this->getDateTimeFromTimestamp($addDates[1]);
                        $bookmark->setCreated($date);
                    }
                    $bookmark->setCategory($currentCategory);
                    $em->persist($bookmark);
                }

                if($flushItemCount % 100 == 0)
                {
                    $em->flush();
                }
            }

            $em->flush();

            return $this->redirect($this->generateUrl('index'));
        } else {
            return $this->render("MyspaceBookmarkBundle:Default:import.html.twig", array("form" => $form->createView(),));
        }

    }

    /**
     * @param $ts
     * @return \DateTime
     */
    private function getDateTimeFromTimestamp($ts)
    {
        $date = new \DateTime("@$ts");
        return $date;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Whoops - php errors for cool kids
 * @author Filipe Dobreira <http://github.com/filp>
 */

namespace Whoops\Handler;

use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\VarDumper\Cloner\AbstractCloner;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use UnexpectedValueException;
use Whoops\Exception\Formatter;
use Whoops\Util\Misc;
use Whoops\Util\TemplateHelper;

class PrettyPageHandler extends Handler
{
    const EDITOR_SUBLIME = "sublime";
    const EDITOR_TEXTMATE = "textmate";
    const EDITOR_EMACS = "emacs";
    const EDITOR_MACVIM = "macvim";
    const EDITOR_PHPSTORM = "phpstorm";
    const EDITOR_IDEA = "idea";
    const EDITOR_VSCODE = "vscode";
    const EDITOR_ATOM = "atom";
    const EDITOR_ESPRESSO = "espresso";
    const EDITOR_XDEBUG = "xdebug";

    /**
     * Search paths to be scanned for resources, in the reverse
     * order they're declared.
     *
     * @var array
     */
    private $searchPaths = [];

    /**
     * Fast lookup cache for known resource locations.
     *
     * @var array
     */
    private $resourceCache = [];

    /**
     * The name of the custom css file.
     *
     * @var string
     */
    private $customCss = null;

    /**
     * @var array[]
     */
    private $extraTables = [];

    /**
     * @var bool
     */
    private $handleUnconditionally = false;

    /**
     * @var string
     */
    private $pageTitle = "Whoops! There was an error.";

    /**
     * @var array[]
     */
    private $applicationPaths;

    /**
     * @var array[]
     */
    private $blacklist = [
        '_GET' => [],
        '_POST' => [],
        '_FILES' => [],
        '_COOKIE' => [],
        '_SESSION' => [],
        '_SERVER' => [],
        '_ENV' => [],
    ];

    /**
     * A string identifier for a known IDE/text editor, or a closure
     * that resolves a string that can be used to open a given file
     * in an editor. If the string contains the special substrings
     * %file or %line, they will be replaced with the correct data.
     *
     * @example
     *  "txmt://open?url=%file&line=%line"
     * @var mixed $editor
     */
    protected $editor;

    /**
     * A list of known editor strings
     * @var array
     */
    protected $editors = [
        "sublime"  => "subl://open?url=file://%file&line=%line",
        "textmate" => "txmt://open?url=file://%file&line=%line",
        "emacs"    => "emacs://open?url=file://%file&line=%line",
        "macvim"   => "mvim://open/?url=file://%file&line=%line",
        "phpstorm" => "phpstorm://open?file=%file&line=%line",
        "idea"     => "idea://open?file=%file&line=%line",
        "vscode"   => "vscode://file/%file:%line",
        "atom"     => "atom://core/open/file?filename=%file&line=%line",
        "espresso" => "x-espresso://open?filepath=%file&lines=%line",
    ];

    /**
     * @var TemplateHelper
     */
    private $templateHelper;

    /**
     * Constructor.
     */
    public function __construct()
    {
        if (ini_get('xdebug.file_link_format') || extension_loaded('xdebug')) {
            // Register editor using xdebug's file_link_format option.
            $this->editors['xdebug'] = function ($file, $line) {
                return str_replace(['%f', '%l'], [$file, $line], ini_get('xdebug.file_link_format'));
            };

            // If xdebug is available, use it as default editor.
            $this->setEditor('xdebug');
        }

        // Add the default, local resource search path:
        $this->searchPaths[] = __DIR__ . "/../Resources";

        // blacklist php provided auth based values
        $this->blacklist('_SERVER', 'PHP_AUTH_PW');

        $this->templateHelper = new TemplateHelper();

        if (class_exists('Symfony\Component\VarDumper\Cloner\VarCloner')) {
            $cloner = new VarCloner();
            // Only dump object internals if a custom caster exists.
            $cloner->addCasters(['*' => function ($obj, $a, $stub, $isNested, $filter = 0) {
                $class = $stub->class;
                $classes = [$class => $class] + class_parents($class) + class_implements($class);

                foreach ($classes as $class) {
                    if (isset(AbstractCloner::$defaultCasters[$class])) {
                        return $a;
                    }
                }

                // Remove all internals
                return [];
            }]);
            $this->templateHelper->setCloner($cloner);
        }
    }

    /**
     * @return int|null
     */
    public function handle()
    {
        if (!$this->handleUnconditionally()) {
            // Check conditions for outputting HTML:
            // @todo: Make this more robust
            if (PHP_SAPI === 'cli') {
                // Help users who have been relying on an internal test value
                // fix their code to the proper method
                if (isset($_ENV['whoops-test'])) {
                    throw new \Exception(
                        'Use handleUnconditionally instead of whoops-test'
                        .' environment variable'
                    );
                }

                return Handler::DONE;
            }
        }

        $templateFile = $this->getResource("views/layout.html.php");
        $cssFile      = $this->getResource("css/whoops.base.css");
        $zeptoFile    = $this->getResource("js/zepto.min.js");
        $prettifyFile = $this->getResource("js/prettify.min.js");
        $clipboard    = $this->getResource("js/clipboard.min.js");
        $jsFile       = $this->getResource("js/whoops.base.js");

        if ($this->customCss) {
            $customCssFile = $this->getResource($this->customCss);
        }

        $inspector = $this->getInspector();
        $frames = $this->getExceptionFrames();
        $code = $this->getExceptionCode();

        // List of variables that will be passed to the layout template.
        $vars = [
            "page_title" => $this->getPageTitle(),

            // @todo: Asset compiler
            "stylesheet" => file_get_contents($cssFile),
            "zepto"      => file_get_contents($zeptoFile),
            "prettify"   => file_get_contents($prettifyFile),
            "clipboard"  => file_get_contents($clipboard),
            "javascript" => file_get_contents($jsFile),

            // Template paths:
            "header"                     => $this->getResource("views/header.html.php"),
            "header_outer"               => $this->getResource("views/header_outer.html.php"),
            "frame_list"                 => $this->getResource("views/frame_list.html.php"),
            "frames_description"         => $this->getResource("views/frames_description.html.php"),
            "frames_container"           => $this->getResource("views/frames_container.html.php"),
            "panel_details"              => $this->getResource("views/panel_details.html.php"),
            "panel_details_outer"        => $this->getResource("views/panel_details_outer.html.php"),
            "panel_left"                 => $this->getResource("views/panel_left.html.php"),
            "panel_left_outer"           => $this->getResource("views/panel_left_outer.html.php"),
            "frame_code"                 => $this->getResource("views/frame_code.html.php"),
            "env_details"                => $this->getResource("views/env_details.html.php"),

            "title"            => $this->getPageTitle(),
            "name"             => explode("\\", $inspector->getExceptionName()),
            "message"          => $inspector->getExceptionMessage(),
            "previousMessages" => $inspector->getPreviousExceptionMessages(),
            "docref_url"       => $inspector->getExceptionDocrefUrl(),
            "code"             => $code,
            "previousCodes"    => $inspector->getPreviousExceptionCodes(),
            "plain_exception"  => Formatter::formatExceptionPlain($inspector),
            "frames"           => $frames,
            "has_frames"       => !!count($frames),
            "handler"          => $this,
            "handlers"         => $this->getRun()->getHandlers(),

            "active_frames_tab" => count($frames) && $frames->offsetGet(0)->isApplication() ?  'application' : 'all',
            "has_frames_tabs"   => $this->getApplicationPaths(),

            "tables"      => [
                "GET Data"              => $this->masked($_GET, '_GET'),
                "POST Data"             => $this->masked($_POST, '_POST'),
                "Files"                 => isset($_FILES) ? $this->masked($_FILES, '_FILES') : [],
                "Cookies"               => $this->masked($_COOKIE, '_COOKIE'),
                "Session"               => isset($_SESSION) ? $this->masked($_SESSION, '_SESSION') :  [],
                "Server/Request Data"   => $this->masked($_SERVER, '_SERVER'),
                "Environment Variables" => $this->masked($_ENV, '_ENV'),
            ],
        ];

        if (isset($customCssFile)) {
            $vars["stylesheet"] .= file_get_contents($customCssFile);
        }

        // Add extra entries list of data tables:
        // @todo: Consolidate addDataTable and addDataTableCallback
        $extraTables = array_map(function ($table) use ($inspector) {
            return $table instanceof \Closure ? $table($inspector) : $table;
        }, $this->getDataTables());
        $vars["tables"] = array_merge($extraTables, $vars["tables"]);

        $plainTextHandler = new PlainTextHandler();
        $plainTextHandler->setException($this->getException());
        $plainTextHandler->setInspector($this->getInspector());
        $vars["preface"] = "<!--\n\n\n" .  $this->templateHelper->escape($plainTextHandler->generateResponse()) . "\n\n\n\n\n\n\n\n\n\n\n-->";

        $this->templateHelper->setVariables($vars);
        $this->templateHelper->render($templateFile);

        return Handler::QUIT;
    }

    /**
     * Get the stack trace frames of the exception that is currently being handled.
     *
     * @return \Whoops\Exception\FrameCollection;
     */
    protected function getExceptionFrames()
    {
        $frames = $this->getInspector()->getFrames();

        if ($this->getApplicationPaths()) {
            foreach ($frames as $frame) {
                foreach ($this->getApplicationPaths() as $path) {
                    if (strpos($frame->getFile(), $path) === 0) {
                        $frame->setApplication(true);
                        break;
                    }
                }
            }
        }

        return $frames;
    }

    /**
     * Get the code of the exception that is currently being handled.
     *
     * @return string
     */
    protected function getExceptionCode()
    {
        $exception = $this->getException();

        $code = $exception->getCode();
        if ($exception instanceof \ErrorException) {
            // ErrorExceptions wrap the php-error types within the 'severity' property
            $code = Misc::translateErrorCode($exception->getSeverity());
        }

        return (string) $code;
    }

    /**
     * @return string
     */
    public function contentType()
    {
        return 'text/html';
    }

    /**
     * Adds an entry to the list of tables displayed in the template.
     * The expected data is a simple associative array. Any nested arrays
     * will be flattened with print_r
     * @param string $label
     * @param array  $data
     */
    public function addDataTable($label, array $data)
    {
        $this->extraTables[$label] = $data;
    }

    /**
     * Lazily adds an entry to the list of tables displayed in the table.
     * The supplied callback argument will be called when the error is rendered,
     * it should produce a simple associative array. Any nested arrays will
     * be flattened with print_r.
     *
     * @throws InvalidArgumentException If $callback is not callable
     * @param  string                   $label
     * @param  callable                 $callback Callable returning an associative array
     */
    public function addDataTableCallback($label, /* callable */ $callback)
    {
        if (!is_callable($callback)) {
            throw new InvalidArgumentException('Expecting callback argument to be callable');
        }

        $this->extraTables[$label] = function (\Whoops\Exception\Inspector $inspector = null) use ($callback) {
            try {
                $result = call_user_func($callback, $inspector);

                // Only return the result if it can be iterated over by foreach().
                return is_array($result) || $result instanceof \Traversable ? $result : [];
            } catch (\Exception $e) {
                // Don't allow failure to break the rendering of the original exception.
                return [];
            }
        };
    }

    /**
     * Returns all the extra data tables registered with this handler.
     * Optionally accepts a 'label' parameter, to only return the data
     * table under that label.
     * @param  string|null      $label
     * @return array[]|callable
     */
    public function getDataTables($label = null)
    {
        if ($label !== null) {
            return isset($this->extraTables[$label]) ?
                   $this->extraTables[$label] : [];
        }

        return $this->extraTables;
    }

    /**
     * Allows to disable all attempts to dynamically decide whether to
     * handle or return prematurely.
     * Set this to ensure that the handler will perform no matter what.
     * @param  bool|null $value
     * @return bool|null
     */
    public function handleUnconditionally($value = null)
    {
        if (func_num_args() == 0) {
            return $this->handleUnconditionally;
        }

        $this->handleUnconditionally = (bool) $value;
    }

    /**
     * Adds an editor resolver, identified by a string
     * name, and that may be a string path, or a callable
     * resolver. If the callable returns a string, it will
     * be set as the file reference's href attribute.
     *
     * @example
     *  $run->addEditor('macvim', "mvim://open?url=file://%file&line=%line")
     * @example
     *   $run->addEditor('remove-it', function($file, $line) {
     *       unlink($file);
     *       return "http://stackoverflow.com";
     *   });
     * @param string $identifier
     * @param string|callable $resolver
     */
    public function addEditor($identifier, $resolver)
    {
        $this->editors[$identifier] = $resolver;
    }

    /**
     * Set the editor to use to open referenced files, by a string
     * identifier, or a callable that will be executed for every
     * file reference, with a $file and $line argument, and should
     * return a string.
     *
     * @example
     *   $run->setEditor(function($file, $line) { return "file:///{$file}"; });
     * @example
     *   $run->setEditor('sublime');
     *
     * @throws InvalidArgumentException If invalid argument identifier provided
     * @param  string|callable          $editor
     */
    public function setEditor($editor)
    {
        if (!is_callable($editor) && !isset($this->editors[$editor])) {
            throw new InvalidArgumentException(
                "Unknown editor identifier: $editor. Known editors:" .
                implode(",", array_keys($this->editors))
            );
        }

        $this->editor = $editor;
    }

    /**
     * Given a string file path, and an integer file line,
     * executes the editor resolver and returns, if available,
     * a string that may be used as the href property for that
     * file reference.
     *
     * @throws InvalidArgumentException If editor resolver does not return a string
     * @param  string                   $filePath
     * @param  int                      $line
     * @return string|bool
     */
    public function getEditorHref($filePath, $line)
    {
        $editor = $this->getEditor($filePath, $line);

        if (empty($editor)) {
            return false;
        }

        // Check that the editor is a string, and replace the
        // %line and %file placeholders:
        if (!isset($editor['url']) || !is_string($editor['url'])) {
            throw new UnexpectedValueException(
                __METHOD__ . " should always resolve to a string or a valid editor array; got something else instead."
            );
        }

        $editor['url'] = str_replace("%line", rawurlencode($line), $editor['url']);
        $editor['url'] = str_replace("%file", rawurlencode($filePath), $editor['url']);

        return $editor['url'];
    }

    /**
     * Given a boolean if the editor link should
     * act as an Ajax request. The editor must be a
     * valid callable function/closure
     *
     * @throws UnexpectedValueException  If editor resolver does not return a boolean
     * @param  string                   $filePath
     * @param  int                      $line
     * @return bool
     */
    public function getEditorAjax($filePath, $line)
    {
        $editor = $this->getEditor($filePath, $line);

        // Check that the ajax is a bool
        if (!isset($editor['ajax']) || !is_bool($editor['ajax'])) {
            throw new UnexpectedValueException(
                __METHOD__ . " should always resolve to a bool; got something else instead."
            );
        }
        return $editor['ajax'];
    }

    /**
     * Given a boolean if the editor link should
     * act as an Ajax request. The editor must be a
     * valid callable function/closure
     *
     * @param  string $filePath
     * @param  int    $line
     * @return array
     */
    protected function getEditor($filePath, $line)
    {
        if (!$this->editor || (!is_string($this->editor) && !is_callable($this->editor))) {
            return [];
        }

        if (is_string($this->editor) && isset($this->editors[$this->editor]) && !is_callable($this->editors[$this->editor])) {
            return [
                'ajax' => false,
                'url' => $this->editors[$this->editor],
            ];
        }

        if (is_callable($this->editor) || (isset($this->editors[$this->editor]) && is_callable($this->editors[$this->editor]))) {
            if (is_callable($this->editor)) {
                $callback = call_user_func($this->editor, $filePath, $line);
            } else {
                $callback = call_user_func($this->editors[$this->editor], $filePath, $line);
            }

            if (empty($callback)) {
                return [];
            }

            if (is_string($callback)) {
                return [
                    'ajax' => false,
                    'url' => $callback,
                ];
            }

            return [
                'ajax' => isset($callback['ajax']) ? $callback['ajax'] : false,
                'url' => isset($callback['url']) ? $callback['url'] : $callback,
            ];
        }

        return [];
    }

    /**
     * @param  string $title
     * @return void
     */
    public function setPageTitle($title)
    {
        $this->pageTitle = (string) $title;
    }

    /**
     * @return string
     */
    public function getPageTitle()
    {
        return $this->pageTitle;
    }

    /**
     * Adds a path to the list of paths to be searched for
     * resources.
     *
     * @throws InvalidArgumentException If $path is not a valid directory
     *
     * @param  string $path
     * @return void
     */
    public function addResourcePath($path)
    {
        if (!is_dir($path)) {
            throw new InvalidArgumentException(
                "'$path' is not a valid directory"
            );
        }

        array_unshift($this->searchPaths, $path);
    }

    /**
     * Adds a custom css file to be loaded.
     *
     * @param  string $name
     * @return void
     */
    public function addCustomCss($name)
    {
        $this->customCss = $name;
    }

    /**
     * @return array
     */
    public function getResourcePaths()
    {
        return $this->searchPaths;
    }

    /**
     * Finds a resource, by its relative path, in all available search paths.
     * The search is performed starting at the last search path, and all the
     * way back to the first, enabling a cascading-type system of overrides
     * for all resources.
     *
     * @throws RuntimeException If resource cannot be found in any of the available paths
     *
     * @param  string $resource
     * @return string
     */
    protected function getResource($resource)
    {
        // If the resource was found before, we can speed things up
        // by caching its absolute, resolved path:
        if (isset($this->resourceCache[$resource])) {
            return $this->resourceCache[$resource];
        }

        // Search through available search paths, until we find the
        // resource we're after:
        foreach ($this->searchPaths as $path) {
            $fullPath = $path . "/$resource";

            if (is_file($fullPath)) {
                // Cache the result:
                $this->resourceCache[$resource] = $fullPath;
                return $fullPath;
            }
        }

        // If we got this far, nothing was found.
        throw new RuntimeException(
            "Could not find resource '$resource' in any resource paths."
            . "(searched: " . join(", ", $this->searchPaths). ")"
        );
    }

    /**
     * @deprecated
     *
     * @return string
     */
    public function getResourcesPath()
    {
        $allPaths = $this->getResourcePaths();

        // Compat: return only the first path added
        return end($allPaths) ?: null;
    }

    /**
     * @deprecated
     *
     * @param  string $resourcesPath
     * @return void
     */
    public function setResourcesPath($resourcesPath)
    {
        $this->addResourcePath($resourcesPath);
    }

    /**
     * Return the application paths.
     *
     * @return array
     */
    public function getApplicationPaths()
    {
        return $this->applicationPaths;
    }

    /**
     * Set the application paths.
     *
     * @param array $applicationPaths
     */
    public function setApplicationPaths($applicationPaths)
    {
        $this->applicationPaths = $applicationPaths;
    }

    /**
     * Set the application root path.
     *
     * @param string $applicationRootPath
     */
    public function setApplicationRootPath($applicationRootPath)
    {
        $this->templateHelper->setApplicationRootPath($applicationRootPath);
    }

    /**
     * blacklist a sensitive value within one of the superglobal arrays.
     *
     * @param $superGlobalName string the name of the superglobal array, e.g. '_GET'
     * @param $key string the key within the superglobal
     */
    public function blacklist($superGlobalName, $key)
    {
        $this->blacklist[$superGlobalName][] = $key;
    }

    /**
     * Checks all values within the given superGlobal array.
     * Blacklisted values will be replaced by a equal length string cointaining only '*' characters.
     *
     * We intentionally dont rely on $GLOBALS as it depends on 'auto_globals_jit' php.ini setting.
     *
     * @param $superGlobal array One of the superglobal arrays
     * @param $superGlobalName string the name of the superglobal array, e.g. '_GET'
     * @return array $values without sensitive data
     */
    private function masked(array $superGlobal, $superGlobalName)
    {
        $blacklisted = $this->blacklist[$superGlobalName];

        $values = $superGlobal;
        foreach ($blacklisted as $key) {
            if (isset($superGlobal[$key]) && is_string($superGlobal[$key])) {
                $values[$key] = str_repeat('*', strlen($superGlobal[$key]));
            }
        }
        return $values;
    }
}


text:
'use strict';

/* jasmine specs for directives go here */

describe('directives', function () {
  beforeEach(module('photoChallenges.directives'));

  describe('app-version', function () {
    it('should print current version', function () {
      module(function ($provide) {
        $provide.value('version', 'TEST_VER');
      });
      inject(function ($compile, $rootScope) {
        var element = $compile('<span app-version></span>')($rootScope);
        expect(element.text()).toEqual('TEST_VER');
      });
    });
  });

  describe('challenge-header', function () {
        beforeEach(module('partials/challenge-header.html'));
        var scope, $compile, element;

        function sharedBehaviorForChallengeHeader(context) {
          beforeEach(inject(function ($rootScope, _$compile_) {

            scope = $rootScope;
            $compile = _$compile_;

            element = angular.element('<challenge-header challenge="challenge"></challenge-header>');

            scope.challenge = context.challenge;

            // Compile the element
            $compile(element)(scope);
            scope.$digest();
          }));

          it('should print the id', function () {
            expect(element.find('h1').text()).toBe('Challenge #1')
          });

          it('should print the submitter', function () {
            element = element.find('a.submitter');
            expect(element.text()).toBe('ccb621');
            expect(element.attr('href')).toBe('#/users/1');
          });

          it('should print the description', function () {
            expect(element.find('.description').text()).toBe("Photograph an interesting cloud.");
          });
        }

        var _challenge = {"id": 1, "created_at": "2014-04-19T00:03:47.631Z", "description": "Photograph an interesting cloud.", "daily_challenge_date": "2014-04-18T04:00:00.000Z", "user": {"id": 1, "display_name": "ccb621"},
          "photos": {"count": 0, "links": []}};

        sharedBehaviorForChallengeHeader({challenge: _challenge});

        describe('without challenge date', function () {
          var challenge = jQuery.extend({}, _challenge);
          challenge.daily_challenge_date = null;
          var context = {
            challenge: challenge
          };

          sharedBehaviorForChallengeHeader(context);

          it('does not display a daily challenge date', function () {
            expect(element.find('.daily-challenge-date').length).toBe(0);
          });
        });

        describe('with challenge date', function () {
          var challenge = jQuery.extend({}, _challenge);
          challenge.daily_challenge_date = "2014-04-18T04:00:00.000Z";
          var context = {
            challenge: challenge
          };

          sharedBehaviorForChallengeHeader(context);

          it('displays a daily challenge date', function () {
            expect(element.find('.daily-challenge-date').text()).toBe('2014 Apr 18');
          });
        });

        describe('with 1 photo', function () {
          var challenge = jQuery.extend({}, _challenge);
          challenge.photos = {"count": 1, "links": [
            {"id": 4, "url": "http://lorempixel.com/640/480/?3860", "user": {"id": 10, "display_name": "litzy.hegmann"}}
          ]};
          var context = {
            challenge: challenge
          };

          sharedBehaviorForChallengeHeader(context);

          it('the number of photos should be singular', function () {
            expect(element.find('.photo-count').text()).toBe('1 photo');
          });
        });

        describe('with multiple photos', function () {
          var challenge = jQuery.extend({}, _challenge);
          challenge.photos = {"count": 2, "links": [
            {"id": 4, "url": "http://lorempixel.com/640/480/?3860", "user": {"id": 10, "display_name": "litzy.hegmann"}},
            {"id": 5, "url": "http://lorempixel.com/640/480/?7719", "user": {"id": 13, "display_name": "carey"}}
          ]};
          var context = {
            challenge: challenge
          };

          sharedBehaviorForChallengeHeader(context);

          it('the number of photos should be plural', function () {
            expect(element.find('.photo-count').text()).toBe('2 photos');
          });
        });
      }
  )
  ;
  describe('photo-grid', function () {

    beforeEach(module('partials/photo-grid.html'));

    function createGrid(photos) {
      var scope, $compile, element;

      inject(function ($rootScope, _$compile_) {
        scope = $rootScope;
        $compile = _$compile_;

        element = angular.element('<photo-grid photos="photos"></photo-grid>');

        scope.photos = photos;
      });

      $compile(element)(scope);
      scope.$digest();

      return element;
    }

    describe('with photos', function () {
      var photos = [
        {"id": 27, "url": "http://lorempixel.com/640/480/?9391", "user": {"id": 8, "display_name": "justus"}},
        {"id": 394, "url": "http://lorempixel.com/640/480/?5305", "user": {"id": 16, "display_name": "maryjane"}}
      ];

      it('displays links and photos', function () {
        var element = createGrid(photos);
        var thumbnails = element.find('.thumbnail');
        expect(thumbnails.length).toEqual(2);
        expect(thumbnails.eq(0).attr('href')).toEqual('#/photos/27');
        expect(thumbnails.eq(0).find('img').attr('src')).toEqual('http://lorempixel.com/640/480/?9391');

        expect(thumbnails.eq(1).attr('href')).toEqual('#/photos/394');
        expect(thumbnails.eq(1).find('img').attr('src')).toEqual('http://lorempixel.com/640/480/?5305');
      });
    });

    describe('without photos', function () {
      it('displays an empty alert', function () {
        var element = createGrid([]).find('.alert-info');
        expect(element.text().trim()).toEqual('No photos have been posted.');
      });
    });
  });
});


text:
package com.sun.jdmk;

import javax.management.MBeanServerDelegate;
import javax.management.*;
import java.io.ObjectInputStream;
import java.util.Set;

import com.sun.jdmk.interceptor.DefaultMBeanServerInterceptor;
import com.sun.jdmk.interceptor.MBeanServerInterceptor;

/**
 * Extends the MBeanInterceptor interface to provide methods for
 * getting and setting the DefaultMBeanInterceptor used for request
 * treatment, getters for the MetaData and MBeanInstantiator objects
 * associated to the MBeanServer and a getter for the class loader of
 * an MBean given its ObjectName.
 *
 * @since Java DMK 5.0
 * @deprecated Use {@link com.sun.jdmk.JdmkMBeanServer} instead.
 */

public interface MBeanServerInt extends MBeanServerInterceptor  {

    /**
     * Return the MBeanInterceptor to which all requests from the
     * MBeanServer interface are forwarded.
     * @deprecated use {@link com.sun.jdmk.JdmkMBeanServer#getMBeanServerInterceptor()}
     */
    public MBeanInterceptor getDefaultMBeanInterceptor();

    /**
     *
Change the MBeanInterceptor object to which all requests
     * from the MBeanServer interface are forwarded.  The old
     * object is lost unless it was accessible by other means.

     *
     * @param interceptor   the new object.
     * @exception IllegalArgumentException if interceptor is null.
     * @deprecated use {@link com.sun.jdmk.JdmkMBeanServer#setMBeanServerInterceptor(com.sun.jdmk.interceptor.MBeanServerInterceptor)}
     */
    public  void setDefaultMBeanInterceptor(MBeanInterceptor interceptor)
	throws IllegalArgumentException;

    /**
     * Return the MBeanInstantiator associated to this MBeanServer.
     */
    public MBeanInstantiator getMBeanInstantiator();

    /**
     * Return the MetaData associated to this MBeanServer.
     */
    public MetaData getMetaData();

    /**
     * Return the MBeanServerDelegate representing the MBeanServer
     */
    public javax.management.MBeanServerDelegate getMBeanServerDelegate();

}


text:
package com.github.dozermapper.core.util;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.github.dozermapper.core.MappingException;
import com.github.dozermapper.core.cache.Cache;
import com.github.dozermapper.core.classmap.ClassMap;
import com.github.dozermapper.core.classmap.Configuration;
import com.github.dozermapper.core.classmap.CopyByReferenceContainer;
import com.github.dozermapper.core.classmap.DozerClass;
import com.github.dozermapper.core.config.BeanContainer;
import com.github.dozermapper.core.converters.CustomConverterContainer;
import com.github.dozermapper.core.fieldmap.DozerField;
import com.github.dozermapper.core.fieldmap.FieldMap;

import org.apache.commons.lang3.StringUtils;

import static com.github.dozermapper.core.util.DozerConstants.BASE_CLASS;

/**
 * Internal class that provides various mapping utilities used throughout the code base. Only intended for internal use.
 */
public final class MappingUtils {

    private MappingUtils() {
    }

    public static String getClassNameWithoutPackage(Class<?> clazz) { // TODO Replace with Apache implementation
        Package pckage = clazz.getPackage();
        int pckageIndex = 0;
        if (pckage != null) {
            pckageIndex = pckage.getName().length() + 1;
        }
        return clazz.getName().substring(pckageIndex);
    }

    public static boolean isSupportedCollection(Class<?> aClass) {
        return CollectionUtils.isCollection(aClass) || CollectionUtils.isArray(aClass);
    }

    public static boolean isSupportedMap(Class<?> aClass) {
        return Map.class.isAssignableFrom(aClass);
    }

    public static void throwMappingException(Throwable e) throws MappingException {
        if (e instanceof MappingException) {
            // in this case we do not want to re-wrap an existing mapping exception
            throw (MappingException)e;
        } else if (e instanceof RuntimeException) {
            // feature request 1561837. Dont wrap any runtime exceptions in a MappingException
            throw (RuntimeException)e;
        } else {
            throw new MappingException(e);
        }
    }

    public static void throwMappingException(String msg) throws MappingException {
        throw new MappingException(msg);
    }

    public static void throwMappingException(String msg, Throwable cause) throws MappingException {
        throw new MappingException(msg, cause);
    }

    public static boolean isBlankOrNull(String value) {
        return value == null || value.trim().length() < 1;
    }

    public static Throwable getRootCause(Throwable ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        return rootCause;
    }

    public static String getMappedParentFieldKey(Object destObj, FieldMap destFieldMap) {
        StringBuilder buf = new StringBuilder(100); // TODO Use IdentityHashMap instead of String concatenation
        buf.append(System.identityHashCode(destObj));
        buf.append(destFieldMap.getDestFieldName());
        if (destFieldMap.getDestFieldKey() != null) {
            buf.append("[").append(destFieldMap.getDestFieldKey()).append("]");
        }
        return buf.toString();
    }

    public static Class<?> findCustomConverter(Cache converterByDestTypeCache, CustomConverterContainer customConverterContainer,
                                               Class<?> srcClass, Class<?> destClass) {
        if (customConverterContainer == null) {
            return null;
        }

        return customConverterContainer.getCustomConverter(srcClass, destClass, converterByDestTypeCache);
    }

    public static Class<?> determineCustomConverter(FieldMap fieldMap, Cache converterByDestTypeCache,
                                                    CustomConverterContainer customConverterContainer, Class<?> srcClass, Class<?> destClass) {
        if (customConverterContainer == null) {
            return null;
        }

        // This method is messy. Just trying to isolate the junk into this one method instead of spread across the mapping
        // processor until a better solution can be put into place
        // For indexed mapping, need to use the actual class at index to determine the custom converter.
        if (fieldMap != null && fieldMap.isDestFieldIndexed()) {
            if (destClass.isArray()) {
                destClass = destClass.getComponentType();
            } else if (destClass.isAssignableFrom(Collection.class) && fieldMap.getDestHintContainer() != null
                       && !fieldMap.getDestHintContainer().hasMoreThanOneHint()) {
                // use hint when trying to find a custom converter
                destClass = fieldMap.getDestHintContainer().getHint();
            }
        }

        return findCustomConverter(converterByDestTypeCache, customConverterContainer, srcClass, destClass);
    }

    public static void reverseFields(FieldMap source, FieldMap reversed) {
        DozerField destField = source.getSrcFieldCopy();
        DozerField sourceField = source.getDestFieldCopy();

        reversed.setDestField(destField);
        reversed.setSrcField(sourceField);

        reversed.setCustomConverter(source.getCustomConverter());
        reversed.setCustomConverterId(source.getCustomConverterId());
        reversed.setMapId(source.getMapId());
        reversed.setRelationshipType(source.getRelationshipType());
        reversed.setRemoveOrphans(source.isRemoveOrphans());
        reversed.setSrcHintContainer(source.getDestHintContainer());
        reversed.setDestHintContainer(source.getSrcHintContainer());
        reversed.setSrcDeepIndexHintContainer(source.getDestDeepIndexHintContainer());
        reversed.setDestDeepIndexHintContainer(source.getSrcDeepIndexHintContainer());
    }

    public static void reverseFields(ClassMap source, ClassMap destination, BeanContainer beanContainer) {
        // reverse the fields
        destination.setSrcClass(new DozerClass(source.getDestClassName(), source.getDestClassToMap(), source.getDestClassBeanFactory(),
                                               source.getDestClassBeanFactoryId(), source.getDestClassMapGetMethod(), source.getDestClassMapSetMethod(),
                                               source.getDestClass().getCreateMethod(),
                                               source.isDestMapNull(), source.isDestMapEmptyString(), source.getDestClass().isAccessible(),
                                               source.getDestClass().isSkipConstructor(), beanContainer));
        destination.setDestClass(new DozerClass(source.getSrcClassName(), source.getSrcClassToMap(), source.getSrcClassBeanFactory(),
                                                source.getSrcClassBeanFactoryId(), source.getSrcClassMapGetMethod(), source.getSrcClassMapSetMethod(),
                                                source.getSrcClass().getCreateMethod(),
                                                source.isSrcMapNull(), source.isSrcMapEmptyString(), source.getSrcClass().isAccessible(), source.getSrcClass().isSkipConstructor(),
                                                beanContainer));
        destination.setType(source.getType());
        destination.setWildcard(source.isWildcard());
        destination.setWildcardCaseInsensitive(source.isWildcardCaseInsensitive());
        destination.setTrimStrings(source.isTrimStrings());
        destination.setDateFormat(source.getDateFormat());
        destination.setRelationshipType(source.getRelationshipType());
        destination.setStopOnErrors(source.isStopOnErrors());
        destination.setAllowedExceptions(source.getAllowedExceptions());
        destination.setSrcClassCreateMethod(source.getDestClassCreateMethod());
        destination.setDestClassCreateMethod(source.getSrcClassCreateMethod());
        if (StringUtils.isNotEmpty(source.getMapId())) {
            destination.setMapId(source.getMapId());
        }
    }

    public static Object getIndexedValue(Object collection, int index) {
        Object result = null;
        if (collection instanceof Object[]) {
            Object[] x = (Object[])collection;
            if (index < x.length) {
                return x[index];
            }
        } else if (collection instanceof Collection) {
            Collection<?> x = (Collection<?>)collection;
            if (index < x.size()) {
                Iterator<?> iter = x.iterator();
                for (int i = 0; i < index; i++) {
                    iter.next();
                }
                result = iter.next();
            }
        }
        return result;
    }

    public static void applyGlobalCopyByReference(Configuration globalConfig, FieldMap fieldMap, ClassMap classMap) {
        CopyByReferenceContainer copyByReferenceContainer = globalConfig.getCopyByReferences();
        String destFieldTypeName = null;
        Class<?> clazz = fieldMap.getDestFieldType(classMap.getDestClassToMap());
        if (clazz != null) {
            destFieldTypeName = clazz.getName();
        }
        if (copyByReferenceContainer.contains(destFieldTypeName) && !fieldMap.isCopyByReferenceOveridden()) {
            fieldMap.setCopyByReference(true);
        }
    }

    public static Class<?> loadClass(String name, BeanContainer beanContainer) {
        DozerClassLoader loader = beanContainer.getClassLoader();
        return loader.loadClass(name);
    }

    public static Class<?> getRealClass(Class<?> clazz, BeanContainer beanContainer) {
        DozerProxyResolver proxyResolver = beanContainer.getProxyResolver();
        return proxyResolver.getRealClass(clazz);
    }

    public static <T> T deProxy(T object, BeanContainer beanContainer) {
        DozerProxyResolver proxyResolver = beanContainer.getProxyResolver();
        return proxyResolver.unenhanceObject(object);
    }

    public static boolean isProxy(Class<?> clazz, BeanContainer beanContainer) {
        DozerProxyResolver proxyResolver = beanContainer.getProxyResolver();
        return proxyResolver.isProxy(clazz);
    }

    public static Object prepareIndexedCollection(Class<?> collectionType, Object existingCollection, Object collectionEntry,
                                                  int index) {
        Object result = null;
        if (collectionType.isArray()) {
            result = prepareIndexedArray(collectionType, existingCollection, collectionEntry, index);
        } else if (Collection.class.isAssignableFrom(collectionType)) {
            result = prepareIndexedCollectionType(collectionType, existingCollection, collectionEntry, index);
        } else {
            throwMappingException("Only types java.lang.Object[] and java.util.Collection are supported for indexed properties.");
        }

        return result;
    }

    public static boolean isDeepMapping(String mapping) {
        return mapping != null && mapping.contains(DozerConstants.DEEP_FIELD_DELIMITER);
    }

    @SuppressWarnings("unchecked")
    private static <T> T[] prepareIndexedArray(Class<T> collectionType, Object existingCollection, Object collectionEntry, int index) {
        T[] result;

        if (existingCollection == null) {
            result = (T[])Array.newInstance(collectionType.getComponentType(), index + 1);
        } else {
            int originalLenth = ((Object[])existingCollection).length;
            result = (T[])Array.newInstance(collectionType.getComponentType(), Math.max(index + 1, originalLenth));
            System.arraycopy(existingCollection, 0, result, 0, originalLenth);
        }
        result[index] = (T)collectionEntry;
        return result;
    }

    @SuppressWarnings("unchecked")
    private static Collection<?> prepareIndexedCollectionType(Class<?> collectionType, Object existingCollection,
                                                              Object collectionEntry, int index) {
        Collection result = null;
        //Instantiation of the new Collection: can be interface or implementation class
        if (collectionType.isInterface()) {
            if (collectionType.equals(Set.class)) {
                result = new HashSet();
            } else if (collectionType.equals(List.class)) {
                result = new ArrayList();
            } else {
                throwMappingException("Only interface types java.util.Set and java.util.List are supported for java.util.Collection type indexed properties.");
            }
        } else {
            //It is an implementation class of Collection
            try {
                result = (Collection)collectionType.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

        //Fill in old values in new Collection
        if (existingCollection != null) {
            result.addAll((Collection)existingCollection);
        }

        //Add the new value:
        //For an ordered Collection
        if (result instanceof List) {
            while (result.size() < index + 1) {
                result.add(null);
            }
            ((List)result).set(index, collectionEntry);
        } else {
            //for an unordered Collection (index has no use here)
            result.add(collectionEntry);
        }
        return result;
    }

    /**
     * Used to test if {@code srcFieldClass} is enum.
     *
     * @param srcFieldClass the source field to be tested.
     * @return {@code true} if and only if current running JRE is 1.5 or above, and
     * {@code srcFieldClass} is enum; otherwise return {@code false}.
     */
    public static boolean isEnumType(Class<?> srcFieldClass) {
        if (srcFieldClass.isAnonymousClass()) {
            //If srcFieldClass is anonymous class, replace srcFieldClass with its enclosing class.
            //This is used to ensure Dozer can get correct Enum type.
            srcFieldClass = srcFieldClass.getEnclosingClass();
        }
        return srcFieldClass.isEnum();
    }

    /**
     * Used to test if both {@code srcFieldClass} and {@code destFieldType} are enum.
     *
     * @param srcFieldClass the source field to be tested.
     * @param destFieldType the destination field to be tested.
     * @return {@code true} if and only if current running JRE is 1.5 or above, and both
     * {@code srcFieldClass} and {@code destFieldType} are enum; otherwise return {@code false}.
     */
    public static boolean isEnumType(Class<?> srcFieldClass, Class<?> destFieldType) {
        return isEnumType(srcFieldClass) && isEnumType(destFieldType);
    }

    public static List<Class<?>> getSuperClassesAndInterfaces(Class<?> srcClass, BeanContainer beanContainer) {
        List<Class<?>> superClasses = new ArrayList<>();
        Class<?> realClass = getRealClass(srcClass, beanContainer);

        // Add all super classes first
        Class<?> superClass = getRealClass(realClass, beanContainer).getSuperclass();
        while (!isBaseClass(superClass)) {
            superClasses.add(superClass);
            superClass = superClass.getSuperclass();
        }

        // Now add all interfaces of the passed in class and all it's super classes

        // Linked hash set so duplicated are not added but insertion order is kept
        LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<>();

        interfaces.addAll(getInterfaceHierarchy(realClass, beanContainer));
        for (Class<?> clazz : superClasses) {
            interfaces.addAll(getInterfaceHierarchy(clazz, beanContainer));
        }

        superClasses.addAll(interfaces);
        return superClasses;
    }

    @SuppressWarnings("unchecked")
    public static List<Class<?>> getInterfaceHierarchy(Class<?> srcClass, BeanContainer beanContainer) {
        final List<Class<?>> result = new LinkedList<>();
        Class<?> realClass = getRealClass(srcClass, beanContainer);

        final LinkedList<Class> interfacesToProcess = new LinkedList<>();

        Class[] interfaces = realClass.getInterfaces();

        interfacesToProcess.addAll(Arrays.asList(interfaces));

        while (!interfacesToProcess.isEmpty()) {
            Class<?> iface = interfacesToProcess.remove();
            if (!result.contains(iface)) {
                result.add(iface);
                for (Class subiface : iface.getInterfaces()) {
                    // if we haven't processed this interface yet then add it to be processed
                    if (!result.contains(subiface)) {
                        interfacesToProcess.add(subiface);
                    }
                }
            }
        }

        return result;

    }

    private static boolean isBaseClass(Class<?> clazz) {
        return clazz == null || BASE_CLASS.equals(clazz.getName());
    }

}


text:
/**
 * Segments definitions.
 */
package com.jeometry.twod.segment;


text:
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0

To use the Neal Family Quiz skill, try saying...

* *Alexa launch Neal Family Quiz*

* *Repeat*

* *Help*

Think you can answer
"Who was born in 1966"
"Which is the best movie"
Take this quiz and find out!

***

### Skill Details

* **Invocation Name:** neal family quiz
* **Category:** null
* **ID:** amzn1.ask.skill.89dcf885-ad7a-4a17-8884-9617ad4a9055
* **ASIN:** B01N0KSGUM
* **Author:** Steal Enterprise
* **Release Date:** November 30, 2016 @ 06:05:00
* **In-App Purchasing:** No


text:
% rtcUpdateGeometryBuffer(3) | Embree Ray Tracing Kernels 3

#### NAME

    rtcUpdateGeometryBuffer - marks a buffer view bound to the geometry
      as modified

#### SYNOPSIS

    #include <embree3/rtcore.h>

    void rtcUpdateGeometryBuffer(
      RTCGeometry geometry,
      enum RTCBufferType type,
      unsigned int slot
    );

#### DESCRIPTION

The `rtcUpdateGeometryBuffer` function marks the buffer view bound to
the specified buffer type and slot (`type` and `slot` argument) of a
geometry (`geometry` argument) as modified.

If a data buffer is changed by the application, the
`rtcUpdateGeometryBuffer` call must be invoked for that buffer. Each
buffer view assigned to a buffer slot is initially marked as modified,
thus this function needs to be called only when doing buffer
modifications after the first `rtcCommitScene`.

#### EXIT STATUS

On failure an error code is set that can be queried using
`rtcGetDeviceError`.

#### SEE ALSO

[rtcNewGeometry], [rtcCommitScene]


text:
package me.simple.util;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

import me.simple.domain.Pageable;

public class SQLUtil {
    private static final Logger logger = LoggerFactory.getLogger(SQLUtil.class);

//    public static String generateInsertSql(String tableName, List<String> insertColumns) {
//        StringBuffer buffer = new StringBuffer("INSERT INTO ");
//        buffer.append(tableName).append(" (");
//        buffer.append(Joiner.on(",").join(insertColumns));
//        buffer.append(") VALUES (:");
//        buffer.append(Joiner.on(",:").join(insertColumns));
//        buffer.append(") ");
//        return buffer.toString();
//    }

    public static String generateRemoveSql(String tableName, String primaryKey) {
        StringBuffer buffer = new StringBuffer("UPDATE ");
        buffer.append(tableName).append(" SET ");
        buffer.append("deleted=1,mduser=:mduser,mdtime=:mdtime ");
        buffer.append("WHERE deleted=0 AND ").append(primaryKey).append("=:").append(primaryKey);
        return buffer.toString();
    }

    public static String generateRemoveSql(String tableName, List<String> uniqueKeys) {
        StringBuffer buffer = new StringBuffer("UPDATE ");
        buffer.append(tableName).append(" SET ");
        buffer.append("deleted=1,mduser=:mduser,mdtime=:mdtime ");
        buffer.append("WHERE deleted=0 AND ");
        for (String key: uniqueKeys
             ) {
            buffer.append(key).append("=:").append(key).append(" AND ");
        }
        buffer.delete(buffer.length() - 4, buffer.length());
        return buffer.toString();
    }

//    public static String generateDisableToggleSql(String tableName, String primaryKey) {
//        StringBuffer buffer = new StringBuffer("UPDATE ");
//        buffer.append(tableName).append(" SET ");
//        buffer.append("disabled=:disabled,mduser=:mduser,mdtime=:mdtime ");
//        buffer.append("WHERE deleted=0 AND ").append(primaryKey).append("=:").append(primaryKey);
//        return buffer.toString();
//    }

    public static String generateUpdateSql(String tableName, List<String> updateColumns, String primaryKey) {
        StringBuffer buffer = new StringBuffer("UPDATE ");
        buffer.append(tableName).append(" SET ");
        for (String col : updateColumns) {
            buffer.append(col).append("=:").append(col).append(",");
        }
        buffer.deleteCharAt(buffer.length() - 1).append(" ");
        buffer.append("WHERE deleted=0 AND ").append(primaryKey).append("=:").append(primaryKey);
        return buffer.toString();
    }

//    public static String generateDeleteSql(String tableName, String primaryKey) {
//        StringBuffer buffer = new StringBuffer("DELETE FROM ");
//        buffer.append(tableName).append(" ");
//        buffer.append("WHERE ").append(primaryKey).append("=:").append(primaryKey);
//        return buffer.toString();
//    }

    public static String generateGetSql(String tableName, String primaryKey) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM ");
        buffer.append(tableName).append(" ");
        buffer.append("WHERE deleted=0 AND ").append(primaryKey).append("=:").append(primaryKey);
        return buffer.toString();
    }

    public static String generateGetAllSql(String tableName, String primaryKey) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM ");
        buffer.append(tableName).append(" WHERE ");
        buffer.append(primaryKey).append("=:").append(primaryKey);
        return buffer.toString();
    }

    public static String generateGetSql(String tableName, String primaryKey,boolean filterDeleted) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM ");
        buffer.append(tableName).append(" ");
        if (filterDeleted) {
            buffer.append("WHERE deleted=0 ");
        }else {
            buffer.append("WHERE 1 = 1 ");
        }
        buffer.append(" AND ").append(primaryKey).append("=:").append(primaryKey);
        return buffer.toString();
    }

    public static String generateCountSQL(String querySql) {
        StringBuffer buffer = new StringBuffer(querySql);
        int index = querySql.toLowerCase().indexOf(" from ");
        buffer.delete(0, index);
        buffer.insert(0, "select count(1)");
        return buffer.toString();
    }

    public static String sortingAndPaging(final StringBuffer buffer, final Pageable pageable) {
        String sort = pageable.getSort();
        String order = pageable.getOrder();
        boolean pable = pageable.isPable();
        boolean sable = pageable.isSable();

        if (StringUtils.hasText(sort) && sable) {
            buffer.append("ORDER BY ").append(HtmlUtils.htmlEscape(sort)).append(" ");
            if (StringUtils.hasText(order) && ("asc".equalsIgnoreCase(order) || "desc".equalsIgnoreCase(order))) {
                buffer.append(HtmlUtils.htmlEscape(order)).append(" ");
            }
        }
        if (pable) {
            buffer.append("LIMIT ");
            buffer.append((pageable.getPage() - 1) * pageable.getRows());
            buffer.append(",");
            buffer.append(pageable.getRows());
        }
        return buffer.toString();
    }

    public static String like(String value) {
        StringBuffer fieldValue = new StringBuffer(StringUtils.trimWhitespace(value));
        fieldValue.insert(0, "%");
        fieldValue.insert(fieldValue.length(), "%");
        return fieldValue.toString();
    }

//    public static String notIn(String columname, String values, final List<Object> args) {
//        List<String> valueList = Splitter.on(",").splitToList(values);
//        int size = valueList.size();
//        int iMax = size - 1;
//        StringBuffer buffer = new StringBuffer();
//        for (int i = 0; i < size; i++) {
//            buffer.append(columname).append(" <> ? ");
//            args.add(valueList.get(i));
//            if (i < iMax) {
//                buffer.append("AND ");
//            }
//        }
//        return buffer.toString();
//    }

//    public static String in(String columname, String values, final List<Object> args) {
//        List<String> valueList = Splitter.on(",").splitToList(values);
//        int size = valueList.size();
//        int iMax = size - 1;
//        StringBuffer buffer = new StringBuffer();
//        for (int i = 0; i < size; i++) {
//            buffer.append(columname).append(" = ? ");
//            args.add(valueList.get(i));
//            if (i < iMax) {
//                buffer.append("OR ");
//            }
//        }
//        return buffer.toString();
//    }

}