text:
<!DOCTYPE html>

      <title>iLocation</title>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="shortcut icon" href="/medias/favicon.ico" type="image/x-icon">
      <link rel="icon" href="/medias/favicon.ico" type="image/x-icon">
      <link href="vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
      <link href="vendors/bootstrap.ui/dist/css/bootstrap-ui.min.css" rel="stylesheet">

      <link href="vendors/AngularJS-Toaster/toaster.min.css" rel="stylesheet">
      <link href="vendors/ng-dialog/css/ngDialog.min.css" rel="stylesheet">
      <link href="vendors/ng-dialog/css/ngDialog-theme-default.min.css" rel="stylesheet">
      <link href="static/style.css" rel="stylesheet">

                  <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
                    Toggle navigation

                  </button>

Navigazione

                        Ruoli

Crea

Gestisci

                        Utenti

Crea

Gestisci

                         {{UserLogged}}

Profilo

Logout

      <toaster-container toaster-options="{'time-out': 2000,'position-class': 'toast-bottom-right','close-button': true}"></toaster-container>


text:
package intermediate;

public interface ICode {

	/**
	* Set and return the root node.
	* @param node the node to set as root.
	* @return the root node.
	*/
	public ICodeNode setRoot(ICodeNode node);

	/**
	* Get the root node.
	* @return the root node.
	*/
	public ICodeNode getRoot();

}

redpajama_set_name: RedPajamaGithub


text:
import browserify from 'browserify';
import gulp from 'gulp';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import uglify from 'gulp-uglify';
import babel from 'gulp-babel';
import sourcemaps from 'gulp-sourcemaps';
import gutil from 'gulp-util';
import rename from 'gulp-rename';
import babelify from 'babelify';
import es3ify from 'gulp-es3ify';
import rimraf from 'rimraf';

const SRC_BROWSER_PATH = 'src/main/browser.js';
const SRC_NODE_PATH = ['src/main/*.js', '!src/main/browser.js', '!src/main/data.js'];
const SRC_BIN_PATH = 'src/bin/*.js';
const DEST_BROWSER_PATH = 'lib/browser/';
const DEST_NODE_PATH = 'lib/node/';
const DEST_BIN_PATH = 'lib/bin/';

gulp.task('default', ['build:browser', 'build:node', 'build:bin']);

gulp.task('build:browser', ['clean:browser'], () =>
  browserify(SRC_BROWSER_PATH, { debug: true })
    .transform(babelify, { presets: ['es2015-ie'], plugins: ['add-module-exports'] })
    .bundle()
    .pipe(source('transliteration.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(es3ify())
      .pipe(gulp.dest(DEST_BROWSER_PATH))
      .pipe(rename('transliteration.min.js'))
      .pipe(uglify())
      .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DEST_BROWSER_PATH))
    .pipe(gutil.noop()),
);

gulp.task('build:node', ['clean:node'], () =>
  gulp.src(SRC_NODE_PATH)
    .pipe(babel())
    .pipe(gulp.dest(DEST_NODE_PATH)),
);

gulp.task('build:bin', ['clean:bin'], () =>
  gulp.src(SRC_BIN_PATH)
    .pipe(babel())
    .pipe(rename({ extname: '' }))
    .pipe(gulp.dest(DEST_BIN_PATH)),
);

gulp.task('clean:browser', cb => rimraf('lib/browser/*', cb));

gulp.task('clean:node', cb => rimraf('lib/node/*', cb));

gulp.task('clean:bin', cb => rimraf('lib/bin/*', cb));


text:
- Office UI Fabric preset
- Presets automation tests
- Headless mode

---

## New in v.3.3.0

- Webpack Dev Server integration
- sp-rest-proxy integration

---

## New in v.3.1.8

- Package manager selection (`npm`, `yarn`, `pnpm`), added `pnpm` support ([@olegrumiancev](https://github.com/olegrumiancev)) [PR](https://github.com/koltyakov/generator-sppp/pull/19)

---

## New in v.3.1.*

- Webpack externals config
- Custom actions provisionging options
- Excluding polyfills from bundles
- React basic projects preset

---

## New in v.3.0.*

- Update to `sp-build-tasks` ver. 3.0.*
- Dependencies srink and optimization
- Strong typed custom Gulp JavaScript tasks
- dotenv for redefining configs paths

---

## New in v.2.2.*

- React project compatibility improvements
- Update to Webpack 4

---

## New in v.2.1.*

- JSON schema is added to `./config/app.json` file.

---

## New in v.2.0.*

- Code base has been migrated to TypeScript
- Custom Gulp tasks support has been added
- Generator has been migrated to a new version of Yeoman framework
- Yarn is integrated as a default package manager
- SharePoint build tasks has been migrated to `sp-build-tasks`
- Auth wizard system has been migrated to `node-sp-auth-config`

---

## New in v.1.5.*

- Live reload functionality is integrated
- Dynamic configuration helpers

---


text:
// Author: jmarantz@google.com (Joshua Marantz)

#include "pagespeed/kernel/base/writer.h"

namespace net_instaweb {

Writer::~Writer() {
}

}  // namespace net_instaweb


text:
LRCAPS ;DALISC/FHS - REPLACEMENT RTN OF WKLD REP GENERATOR-MAIN ;10/15/92 11:15
 ;;5.2;LAB SERVICE;;Sep 27, 1994
 ; This routine is obsolete with V5.2. The replacement routine is
 ; LRCAPR1
EN ;
 G ^LRCAPR1
 Q


text:
<?php

namespace Drupal\Tests\jsonapi\Functional;

use Behat\Mink\Driver\BrowserKitDriver;
use Drupal\Core\Url;
use GuzzleHttp\RequestOptions;

/**
 * Boilerplate for JSON:API Functional tests' HTTP requests.
 *
 * @internal
 */
trait JsonApiRequestTestTrait {

  /**
   * Performs a HTTP request. Wraps the Guzzle HTTP client.
   *
   * Why wrap the Guzzle HTTP client? Because we want to keep the actual test
   * code as simple as possible, and hence not require them to specify the
   * 'http_errors = FALSE' request option, nor do we want them to have to
   * convert Drupal Url objects to strings.
   *
   * We also don't want to follow redirects automatically, to ensure these tests
   * are able to detect when redirects are added or removed.
   *
   * @param string $method
   *   HTTP method.
   * @param \Drupal\Core\Url $url
   *   URL to request.
   * @param array $request_options
   *   Request options to apply.
   *
   * @return \Psr\Http\Message\ResponseInterface
   *   The response.
   *
   * @see \GuzzleHttp\ClientInterface::request()
   */
  protected function request($method, Url $url, array $request_options) {
    $this->refreshVariables();
    $request_options[RequestOptions::HTTP_ERRORS] = FALSE;
    $request_options[RequestOptions::ALLOW_REDIRECTS] = FALSE;
    $request_options = $this->decorateWithXdebugCookie($request_options);
    $client = $this->getSession()->getDriver()->getClient()->getClient();
    return $client->request($method, $url->setAbsolute(TRUE)->toString(), $request_options);
  }

  /**
   * Adds the Xdebug cookie to the request options.
   *
   * @param array $request_options
   *   The request options.
   *
   * @return array
   *   Request options updated with the Xdebug cookie if present.
   */
  protected function decorateWithXdebugCookie(array $request_options) {
    $session = $this->getSession();
    $driver = $session->getDriver();
    if ($driver instanceof BrowserKitDriver) {
      $client = $driver->getClient();
      foreach ($client->getCookieJar()->all() as $cookie) {
        if (isset($request_options[RequestOptions::HEADERS]['Cookie'])) {
          $request_options[RequestOptions::HEADERS]['Cookie'] .= '; ' . $cookie->getName() . '=' . $cookie->getValue();
        }
        else {
          $request_options[RequestOptions::HEADERS]['Cookie'] = $cookie->getName() . '=' . $cookie->getValue();
        }
      }
    }
    return $request_options;
  }

}


text:
export function curry (func) {
    return function(...a) {
        return function(...b) {
            return func(...a, ...b);
        }
    }
}

export function curryr (func) {
    return function(...a) {
        return function(...b) {
            return func(...b, ...a);
        }
    }
}

export const isFalse = obj => !obj;
export const isTrue = obj => !isFalse(obj)

export function isIn(list, value) {
    if (isFalse(list)) return false;
    let result = false;
    each(list, a => { if (a == value) result = true; });
    return result;
}

export const isArray = a => a.hasOwnProperty("length");

export const each = (list, func) => {
    if (isFalse(list)) return;
    if (isArray(list)) {
        for (let i=0; i < list.length; i++) {
            func(list[i]);
        }
    } else {
        for (let key in list) func(list[key]);
    }
}

export function isSameList(left, right) {
    const length = left.length;
    if (length != right.length) return false;
    for (let i = 0; i < length; i++) {
        if (left[i] != right[i])
            return false;
    }
    return true;
}

export function hasKey(obj, key) {
    if (isFalse(obj)) return false;
    return isIn(getKeys(obj), key);
}

export function getKeys(obj) {
    if (isFalse(obj)) return [];

    let keys = []
    for (let key in obj) {
        keys.push(key);
    }
    return keys;
}

type stringOrNumber = string | number;

export function get(obj: any, key: number | string | stringOrNumber [] , defaultValue = undefined): any {
    if (isFalse(obj)) return defaultValue;

    let keys: stringOrNumber[] = [];
    if (typeof key === "string") {
        keys = key.split(".")
            .map(k => parseInt(k) >= 0 ? parseInt(k) : k.trim())
            .filter(k => typeof k === "number" || (typeof k === "string" && k.length > 0));
    } else if (typeof key === "number") {
        keys.push(key);
    } else {
        keys = key;
    }

    if (keys.length === 0) {
        return obj;
    }

    const travelingNode = isArray(obj) ?
        (typeof keys[0] === "number" && obj.length > keys[0] ? obj[keys[0]] : defaultValue) :
        obj[keys[0]] || defaultValue;

    return keys.length === 1 ? travelingNode :
        get(travelingNode, keys.slice(1), defaultValue);
}

export function map(list, func?) {
    if (arguments.length == 1) return curryr(map)(list); // curryr 내장

	if (isFalse(list)) return [];
    let result = [];
    each(list, a => result.push(func(a)));
    return result;
}

export function reduce(list, func, base?) {
	if (arguments.length == 2) return curryr(reduce)(list, func); // curryr 내장

    if (isFalse(list)) return base;
    let start = 0;
    let result = base;

    if (isFalse(base)) {
        start = 1;
        result = get(list,0);
    }

    for (let i = start; i < list.length; i++) {
        result = func(result, get(list,i));
    }

    return result;
}

export function pipe(...args: any[]) {
    const func_list =
        arguments.length == 1 && get(arguments,0).hasOwnProperty("length") ?
            arguments[0] :
            arguments;
    return function(arg) {
        return reduce(func_list, (acc, fn) => fn(acc), arg);
    }
}

export function filter(list, pred?) {
	if (arguments.length == 1) return curryr(filter)(list); // curryr 내장

    if (isFalse(list)) return [];

    let result = [];
    each(list, a => { if (pred(a)) result.push(a) });
    return result;
}

export function reject(list, pred?) {
	if (arguments.length == 1) return curryr(reject)(list); // curryr 내장

    if (isFalse(list)) return [];

    pred = arguments.length == 1 ? list : pred;
    pred = pipe(pred, isFalse);

    return filter(list, pred);
}

export function slice(list, start, end?) {
    if (isFalse(list)) return [];
    const length = list.length;
    if (isFalse(length)) return [];
    let result = [];
    if (isFalse(end)) end = length;
    if (isFalse(start)) start = 0;
    for (let i = 0; i < end; i++) {
        if (start <= i && i < end) {
            result.push(list[i]);
        }
    }
    return result;
}

export function go(...args: any[]) {
    if (arguments.length < 2) return undefined;
    const data = get(arguments, 0);
    const funcs = slice(arguments, 1);
    return pipe(funcs)(data);
}

export function random() {
    return Math.random();
}

export function randomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(random() * (max - min + 1)) + min;
}

export function sample(list) {
    if (isFalse(list) || !isArray(list)) return undefined;
    const length = list.length;
    const index = randomInt(0, length);
    return get(list, index);
}

export async function goAsync(data: any, ...args: any[]): Promise<any> {
    let acc: any = data;
    for (let i = 0; i < args.length; i++)
        acc = await args[i](acc);
    return acc;
}

export function isInteger(s) {
    const n = Number(s);
    return n === +n && n === (n|0);
}

export function toBoolean(value: string | boolean | number): boolean {
    return value === true || value === "true" || value > 0 ? true : false;
}

export function isNullOrEmpty(word) {
    return word === undefined || word === null || word === '' ? true : false;
}

export function nvl(value, defaultValue = null, func = null) {
    return isNullOrEmpty(value) ? defaultValue : func ? func(value) : value;
}

export function distinct(list: any[]) : any[] {
    const result = [];
    list.forEach(one => {
        if (result.every(e => !deepEqual(e, one))) {
            result.push(one);
        }
    });

    return result;
}

export function all(list: any, pred?) {
	if (arguments.length == 1) return curryr(all)(list); // curryr 내장

    return isArray(list) ? list.every(pred) : false;
}

export function any(list: any, pred?) {
	if (arguments.length == 1) return curryr(any)(list); // curryr 내장

	return isArray(list) ? list.some(pred) : false;
}

export function deepEqual(a: any, b: any) {
    const type = typeof a;

    if (type != typeof b)
        return false;

    if (type != "object")
        return a === b;

    const keysOfA = getKeys(a);
    const keysOfB = getKeys(b);

    if (keysOfA.length != keysOfB.length)
        return false;

    if (keysOfA.some(key => keysOfB.indexOf(key) < 0))
        return false;

    return keysOfA.every(key => deepEqual(a[key],b[key]));
}

export function subObj(obj: any, keys?: string[]) {
	if (arguments.length == 1) return curryr(subObj)(obj); // curryr 내장

	const data = {};
	keys.forEach(key => { data[key] = obj[key]; });
	return data;
}

export function minusObjByKeys(obj: any, keys?: string[]) {
	if (arguments.length == 1) return curryr(minusObjByKeys)(obj); // curryr 내장

	let data = Object.assign({}, obj);
	keys.forEach(key => { delete data[key]; });
	return data;
}

export function getSubProprtties(group: any, list?: any, label: string = "values") {
	if (arguments.length == 2) return curryr(getSubProprtties)(group, list); // curryr 내장

    const keys = getKeys(group);
	group[label]= go(list,
        filter(row => all(keys, key => group[key] == row[key])),
        map(minusObjByKeys(keys)));
	return group;
}

export function groupBy(list: any[], keys?: string[] | string, label: string = "values") {
    if (arguments.length == 2) return curryr(groupBy)(list, keys);// curryr 내장

    return go(list,
        map(subObj(keys)),
        distinct,
        map(getSubProprtties(list, label)));
}

export function head(list: any[]) {
    if (isArray(list))
        return list.length > 0 ? list[0] : undefined;
    return list;
}

export function hasSameKeys(left: any, right: any, keys: any[]) {
    if (!left) return false;
    if (!right) return false;
    for (const key of keys)
        if (!deepEqual(left[key], right[key]))
            return false;
    return true;
}

export function leftJoin(lefts: any[], rights: any[], keys: any[]) {
    const compFunc1 = curryr(hasSameKeys)(keys);
    return lefts.map(left => {
        const compFunc2 = curry(compFunc1)(left);
        const right = head(rights.filter(right => compFunc2(right)));
        return Object.assign(left, right);
    });
}


text:
package taskmaster

// RecoverableFunc is a wrapper for recoverable goruntine
func RecoverableFunc(routine func(), recoverCallback func(interface{})) func() {
	return func() {
		defer func() {
			if r := recover(); r != nil {
				recoverCallback(r)
			}
		}()
		routine()
	}
}


text:
module Jasonette
  class Style < Jasonette::Base
    def set_style name, *args, &block
      raise [name, args, block_given?].inspect
      @attributes[name.to_s] = value
    end
  end
end


text:
<?php
namespace Testify\Parser;

class TUse
{
    /**
     * @var string Full class definition
     */
    protected $class;

    /**
     * @var string The name for this class as referred to in code 'Xyz as Abc'
     */
    protected $alias;

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

    /**
     * @param string $class
     */
    public function setClass($class)
    {
        $this->class = $class;
    }

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

    /**
     * @param string $alias
     */
    public function setAlias($alias)
    {
        $this->alias = $alias;
    }

    public function toArray()
    {
        return get_object_vars($this);
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Auth ( Assertion (..)
            , VerifierResponse (..)
            , AuthToken (..)
            , checkAssertion
            , checkAuthToken
            , parseAuthToken
            , encryptAndSerialise
            ) where

import Control.Applicative ((<$>), (<*>))
import Data.Aeson
import Text.ParserCombinators.Parsec
import Network.HTTP.Conduit
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack)
import Data.ByteString.Lazy (fromChunks)
import Data.Text.Lazy (Text, unpack)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Web.ClientSession (Key, encryptIO, decrypt)
import Control.Error (hush)

-- | Identity assertion recieved from a user
data Assertion = Assertion String deriving (Show)
instance FromJSON Assertion where
  parseJSON (Object v) = Assertion <$> v .: "assertion"
  parseJSON _          = error "Invalid JSON"

-- | The validity of an assertion, as determined by the Persona verifer
data VerifierResponse = VerifierResponse { verifierStatus :: String
                                         , verifierEmail :: String
                                         } deriving (Show)
instance FromJSON VerifierResponse where
  parseJSON (Object v) = VerifierResponse <$> v .: "status" <*> v .: "email"
  parseJSON _          = error "Invalid JSON"

-- | The authentication token of a user already logged in
data AuthToken = AuthToken { tokenEmail :: String
                           , tokenSession :: String
                           } deriving (Show)
instance FromJSON AuthToken where
  parseJSON (Object v) = AuthToken <$> v .: "email" <*> v .: "session"
  parseJSON _          = error "Invalid JSON"

-- | check the validity of an assertion using the Persona verfier. Thread-blocking.
checkAssertion :: ByteString -> Assertion -> IO VerifierResponse
checkAssertion hostUrl (Assertion a) = do
  url <- parseUrl "https://verifier.login.persona.org/verify"
  let req = urlEncodedBody [("audience", hostUrl), ("assertion", pack a)] url
  response <- withManager . httpLbs $ req
  -- TODO: check certificate - at present we're open to a MitM
  return . fromJust . decode . responseBody $ response

-- | Check that an auth token was issued by the server, and that the user is who he thinks he is.
checkAuthToken :: Key -> AuthToken -> Maybe String
checkAuthToken key (AuthToken email session) =
  case decrypt key $ pack session of
    Nothing -> Nothing
    Just str -> if str == pack email then Just email
                                     else Nothing

encryptAndSerialise :: Key -> String -> IO Text
encryptAndSerialise key msg = do
  encMsg <- encryptIO key . pack $ msg
  return $ decodeUtf8 $ fromChunks [encMsg]

-- | Parse the text of a "Cookie" header, extracting an auth token if the appropriate fields are set
parseAuthToken :: Text -> Maybe AuthToken
parseAuthToken str = case parseCookie $ unpack str of
                       Nothing -> Nothing
                       Just c  -> AuthToken <$> lookup "email" c <*> lookup "session" c

-- | Parse the text of a "Cookie" header.
parseCookie :: String -> Maybe [(String, String)]
parseCookie = hush . parse cookieFields "(Unknown)"

cookieFields :: GenParser Char st [(String, String)]
cookieFields = do
  first <- cookieField
  next <- (string "; " >> cookieFields) <|> return []
  return $ first:next

cookieField :: GenParser Char st (String, String)
cookieField = do
  name <- many (noneOf "=")
  char '='
  value <- many (noneOf ";\n")
  return (name, value)


text:
using ProtoBuf;

namespace Qwack.Transport.TransportObjects.MarketData.Curves
{
    [ProtoContract]
    public class TO_PriceCurve
    {
        [ProtoMember(1)]
        public TO_BasicPriceCurve BasicPriceCurve { get; set; }
        [ProtoMember(2)]
        public TO_ContangoPriceCurve ContangoPriceCurve { get; set; }
        [ProtoMember(3)]
        public TO_BasisPriceCurve BasisPriceCurve { get; set; }
        [ProtoMember(4)]
        public TO_ConstantPriceCurve ConstantPriceCurve { get; set; }
        [ProtoMember(5)]
        public TO_EquityPriceCurve EquityPriceCurve { get; set; }
    }
}


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ToDo = new Schema({
    description : { type: String, index: true, required: true },
    priority :    { type: String, enum : ['0', '1', '2'], default: '0' },
    scheduled :   Date,
    modified :    { type: Date, default : new Date() },
    done :        { type: Boolean, default: false }
});

var User = new Schema({
    name : { type: String, index: true, required: true }
});

mongoose.model('ToDo', ToDo);
mongoose.model('User', User);

exports.ToDo = function(db) {
    return db.model('ToDo');
};

exports.User = function(db) {
    return db.model('User');
};


text:
<?php
namespace TYPO3\CMS\Fluid\ViewHelpers;

/*                                                                        *
 * This script is part of the TYPO3 project - inspiring people to share!  *
 *                                                                        *
 * TYPO3 is free software; you can redistribute it and/or modify it under *
 * the terms of the GNU General Public License version 2 as published by  *
 * the Free Software Foundation.                                          *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General      *
 * Public License for more details.                                       *
 *                                                                        */
/**
 * This ViewHelper renders CObjects from the global TypoScript configuration.
 *
 * = Examples =
 *
 *
 * <f:cObject typoscriptObjectPath="lib.someLibObject" />
 *
 * <output>
 * rendered lib.someLibObject
 * </output>
 *
 *
 * <f:cObject typoscriptObjectPath="lib.customHeader" data="{article}" currentValueKey="title" />
 *
 * <output>
 * rendered lib.customHeader. data and current value will be available in TypoScript
 * </output>
 *
 *
 * {article -> f:cObject(typoscriptObjectPath: 'lib.customHeader')}
 *
 * <output>
 * rendered lib.customHeader. data will be available in TypoScript
 * </output>
 */
class CObjectViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper
{
    /**
     * Disable the escaping interceptor because otherwise the child nodes would be escaped before this view helper
     * can decode the text's entities.
     *
     * @var bool
     */
    protected $escapingInterceptorEnabled = false;

    /**
     * @var array
     */
    protected $typoScriptSetup;

    /**
     * @var \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController contains a backup of the current $GLOBALS['TSFE'] if used in BE mode
     */
    protected $tsfeBackup;

    /**
     * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
     */
    protected $configurationManager;

    /**
     * @param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
     * @return void
     */
    public function injectConfigurationManager(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager)
    {
        $this->configurationManager = $configurationManager;
        $this->typoScriptSetup = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);
    }

    /**
     * Renders the TypoScript object in the given TypoScript setup path.
     *
     * @param string $typoscriptObjectPath the TypoScript setup path of the TypoScript object to render
     * @param mixed $data the data to be used for rendering the cObject. Can be an object, array or string. If this argument is not set, child nodes will be used
     * @param string $currentValueKey
     * @param string $table
     * @throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
     * @return string the content of the rendered TypoScript object
     */
    public function render($typoscriptObjectPath, $data = null, $currentValueKey = null, $table = '')
    {
        if (TYPO3_MODE === 'BE') {
            $this->simulateFrontendEnvironment();
        }
        if ($data === null) {
            $data = $this->renderChildren();
        }
        $currentValue = null;
        if (is_object($data)) {
            $data = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getGettableProperties($data);
        } elseif (is_string($data) || is_numeric($data)) {
            $currentValue = (string)$data;
            $data = [$data];
        }
        /** @var \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $contentObject */
        $contentObject = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
        $contentObject->start($data, $table);
        if ($currentValue !== null) {
            $contentObject->setCurrentVal($currentValue);
        } elseif ($currentValueKey !== null && isset($data[$currentValueKey])) {
            $contentObject->setCurrentVal($data[$currentValueKey]);
        }
        $pathSegments = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('.', $typoscriptObjectPath);
        $lastSegment = array_pop($pathSegments);
        $setup = $this->typoScriptSetup;
        foreach ($pathSegments as $segment) {
            if (!array_key_exists(($segment . '.'), $setup)) {
                throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('TypoScript object path "' . htmlspecialchars($typoscriptObjectPath) . '" does not exist', 1253191023);
            }
            $setup = $setup[$segment . '.'];
        }
        $content = $contentObject->cObjGetSingle($setup[$lastSegment], $setup[$lastSegment . '.']);
        if (TYPO3_MODE === 'BE') {
            $this->resetFrontendEnvironment();
        }
        return $content;
    }

    /**
     * Sets the $TSFE->cObjectDepthCounter in Backend mode
     * This somewhat hacky work around is currently needed because the cObjGetSingle() function of \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer relies on this setting
     *
     * @return void
     */
    protected function simulateFrontendEnvironment()
    {
        $this->tsfeBackup = isset($GLOBALS['TSFE']) ? $GLOBALS['TSFE'] : null;
        $GLOBALS['TSFE'] = new \stdClass();
        $GLOBALS['TSFE']->cObjectDepthCounter = 100;
    }

    /**
     * Resets $GLOBALS['TSFE'] if it was previously changed by simulateFrontendEnvironment()
     *
     * @return void
     * @see simulateFrontendEnvironment()
     */
    protected function resetFrontendEnvironment()
    {
        $GLOBALS['TSFE'] = $this->tsfeBackup;
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title>Yet Another React Starter Kit</title>
    {% if (o.htmlWebpackPlugin.options.production) { %}
    <link rel="stylesheet" href="app.{%=o.webpack.hash%}.css" media="all">
    {% } %}

    {% for (var chunk in o.htmlWebpackPlugin.files.chunks) { %}

    {% } %}


text:
@interface ContactTableViewCell ()
@property (weak, nonatomic) IBOutlet UIImageView *photoView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *companyLabel;
@property (weak, nonatomic) IBOutlet UILabel *phonesLabel;
@property (weak, nonatomic) IBOutlet UILabel *emailsLabel;
@end

@implementation ContactTableViewCell

#pragma mark - life cycle

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return self;
}

#pragma mark - table view model transfer implementation

- (void)updateWithModel:(id)model
{
    APContact *contact = model;
    self.nameLabel.text = [self contactName:contact];
    self.companyLabel.text = contact.job.company ?: @"(No company)";
    self.phonesLabel.text = [self contactPhones:contact];
    self.emailsLabel.text = [self contactEmails:contact];
    self.photoView.image = contact.thumbnail ?: [UIImage imageNamed:@"no_photo"];
}

#pragma mark - private

- (NSString *)contactName:(APContact *)contact
{
    if (contact.name.compositeName)
    {
        return contact.name.compositeName;
    }
    else if (contact.name.firstName && contact.name.lastName)
    {
        return [NSString stringWithFormat:@"%@ %@", contact.name.firstName, contact.name.lastName];
    }
    else if (contact.name.firstName || contact.name.lastName)
    {
        return contact.name.firstName ?: contact.name.lastName;
    }
    else
    {
        return @"Untitled contact";
    }
}

- (NSString *)contactPhones:(APContact *)contact
{
    if (contact.phones.count > 0)
    {
        NSMutableString *result = [[NSMutableString alloc] init];
        for (APPhone *phone in contact.phones)
        {
            NSString *string = phone.localizedLabel.length == 0 ? phone.number :
                               [NSString stringWithFormat:@"%@ (%@)", phone.number,
                                                          phone.localizedLabel];
            [result appendFormat:@"%@, ", string];
        }
        return result;
    }
    else
    {
        return @"(No phones)";
    }
}

- (NSString *)contactEmails:(APContact *)contact
{
    if (contact.emails.count > 1)
    {
        NSMutableString *result = [[NSMutableString alloc] init];
        for (APEmail *email in contact.emails)
        {
            [result appendFormat:@"%@, ", email.address];
        }
        return result;
    }
    else
    {
        return contact.emails.count == 1 ? contact.emails[0].address : @"(No emails)";
    }
}

@end


text:
@class MRItem;
@interface MRContentView : UIView
@property (nonatomic, assign) BOOL horiticalCenter;
- (void) layoutMRItem:(MRItem*)item;

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Finl. Basidsvamp. 46(11): 4 (1904)

#### Original name
Daedaleopsis incana P. Karst., 1904

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/base_titlebar"
        layout="@layout/common_navigationbar" />

    <FrameLayout
        android:id="@+id/contentView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="@dimen/x41"
                android:background="@color/WGViewBackgroundColor"
                android:text="@string/Setting_UserInfo"
                android:textColor="@color/WGAppBaseTitleAColor"
                android:gravity="center"
                android:textSize="@dimen/ft12"/>

            <include
                android:id="@+id/postCodeView"
                layout="@layout/common_cell_type4"
                style="WGCellStyle4View.WGCellStyleTextAndDetailText"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="@dimen/x41"
                android:background="@color/WGViewBackgroundColor"
                android:text="@string/Setting_SystemMessage"
                android:textColor="@color/WGAppBaseTitleAColor"
                android:gravity="center"
                android:textSize="@dimen/ft12"/>

            <include
                android:id="@+id/languageView"
                layout="@layout/common_cell_type4"
                style="WGCellStyle4View.WGCellStyleTextAndDetailAndArr"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:background="@color/navigaiotnBar_separate_color"></View>

            <include
                android:id="@+id/versionView"
                layout="@layout/common_cell_type4"
                style="WGCellStyle4View.WGCellStyleTextAndDetailAndArr"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:background="@color/navigaiotnBar_separate_color"></View>

            <include
                android:id="@+id/cleanCacheView"
                layout="@layout/common_cell_type4"
                style="WGCellStyle4View.WGCellStyleOnlyText"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:background="@color/navigaiotnBar_separate_color"></View>

            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/x41"></View>

            <Button
                android:id="@+id/loginBtn"
                android:layout_width="match_parent"
                android:layout_height="@dimen/x34"
                android:textColor="#ffffff"
                android:textSize="@dimen/ft12"
                android:layout_marginLeft="@dimen/x13"
                android:layout_marginRight="@dimen/x13"
                android:background="@drawable/login_btn_bg"
                android:text="@string/Setting_Logout"/>

            <View
                android:layout_width="wrap_content"
                android:layout_height="@dimen/x30"></View>

        </LinearLayout>

    </FrameLayout>

</LinearLayout>


text:
package org.springframework.metrics.benchmark;

import com.netflix.spectator.api.Counter;
import org.openjdk.jmh.annotations.*;

import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class CounterBenchmark extends AbstractCollectorBenchmark {

    private Counter spectatorCounter;
    private com.codahale.metrics.Counter dropwizardCounter;

    @Setup
    public void setup() {
        spectatorCounter = spectatorRegistry.counter("count");
        dropwizardCounter = dropwizardRegistry.counter("count");
    }

    @Benchmark
    public void spectatorCounter() {
        spectatorCounter.increment();
    }

    @Benchmark
    public void bootCounter() {
        bootCounterService.increment("count");
    }

    @Benchmark
    public void prometheusCounter() {
        prometheusCounter.inc();
    }

    @Benchmark
    public void datadogStatsdCounter() {
        statsd.incrementCounter("count");
    }

    @Benchmark
    public void dropwizardCounter() {
        dropwizardCounter.inc();
    }
}


text:
'use strict'

var routes = {}
var config = require('../../config/config')
var Loo = require('../../models/loo')

routes.home = {
  handler: function * () {
    var maxDistance = this.query.radius || config.query_defaults.maxDistance
    var limit = this.query.limit || config.query_defaults.limit
    var lon = config.ui.map.center[1]
    var lat = config.ui.map.center[0]
    var loos = yield Loo.findNear(lon, lat, maxDistance, limit).exec()
    switch (this.accepts('html', 'json')) {
      case 'html':
        yield this.renderDefaults('home', {
          loo: loos,
          macromap: {
            locate: true
          }
        })
        break
      case 'json':
        break
    }
  },
  path: '/',
  method: 'get'
}

module.exports = routes


text:
package org.apache.log4j.component.plugins;

import junit.framework.TestCase;
import org.apache.log4j.*;
import org.apache.log4j.LoggerRepositoryExImpl;
import org.apache.log4j.util.Compare;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

public class PluginTestCase extends TestCase {

    static String FILE = "plugins.PluginTestCase";
    static String WITNESS = "witness/plugins.PluginTestCase";
    private static boolean verbosePluginOutput = true;
    private static HashMap repositoryMap = new HashMap();

    PluginRegistry pluginRegistry;
    public PluginTestCase(String name) {
        super(name);
    }

    public void setUp() {
        pluginRegistry = new LoggerRepositoryExImpl(
                LogManager.getLoggerRepository()).getPluginRegistry();

        // delete the output file if they happen to exist
        new File(getOutputFile("test1")).delete();
    }

    private String getOutputFile(String caseName) {

        return FILE + "." + caseName + ".txt";
    }

    private String getWitnessFile(String caseName) {

        return WITNESS + "." + caseName + ".txt";
    }

    private void setupAppender(String caseName) throws IOException {

        Logger root = Logger.getRootLogger();
        root.removeAllAppenders();

        // set up appender
        FileAppender appender = new FileAppender(new SimpleLayout(),
                getOutputFile(caseName), false);

        //FileAppender appender = new FileAppender(new PatternLayout("%c{1}: %m%n"),
        //  getOutputFile(caseName), false);
        root.addAppender(appender);
        root.setLevel(Level.DEBUG);
    }

    // basic test of plugin in standalone mode
    public void test1() throws Exception {

        String testName = "test1";
        Logger logger = Logger.getLogger(testName);

        setupAppender(testName);

        PluginTester plugin1 = new PluginTester1("plugin1", 1);
        PluginTester plugin2 = new PluginTester1("plugin1", 2);
        PluginTester plugin3 = new PluginTester2("plugin1", 3);
        PluginTester plugin4 = new PluginTester2("plugin2", 4);
        PluginTester retPlugin;

        repositoryMap.clear();
        repositoryMap.put(LogManager.getLoggerRepository(),
            "default repository");

        // test basic starting/stopping
        logger.info("test 1.1 - basic starting/stopping");
        logger.info("starting " + plugin1.getIdentifier());
        pluginRegistry.addPlugin(plugin1);
        logger.info("stopping " + plugin1.getIdentifier() +
            " using plugin object");
        pluginRegistry.stopPlugin(plugin1.getName());

        // test restarting and starting when already started
        logger.info("test 1.2 - restarting and starting when already started");
        logger.info("restarting " + plugin1.getIdentifier());
        pluginRegistry.addPlugin(plugin1);
        logger.info("restarting " + plugin1.getIdentifier() + " again");
        pluginRegistry.addPlugin(plugin1);

        // test stopping and stopping when already stopped
        logger.info("test 1.3- stopping and stopping when already stopped");
        logger.info("stopping " + plugin1.getIdentifier());
        pluginRegistry.stopPlugin(plugin1.getName());
        logger.info("stopping " + plugin1.getIdentifier() + " again");
        pluginRegistry.stopPlugin(plugin1.getName());

        logger.info("test 1.4 - restarting then stopping by plugin name");
        logger.info("starting " + plugin1.getIdentifier());
        pluginRegistry.addPlugin(plugin1);
        logger.info("stopping " + plugin1.getIdentifier() +
            " using plugin name");
        pluginRegistry.stopPlugin(plugin1.getName());

//        // test starting of an "equal" plugin
//        logger.info("test 1.5 - starting of an \"equal\" plugin");
//        logger.info("starting " + plugin1.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin1);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
//        logger.info("starting " + plugin2.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin2);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
//        logger.info("stopping " + retPlugin.getIdentifier());
//        pluginRegistry.stopPlugin(retPlugin.getName());
//
//        // test starting an "equal" plugin after original stopped
//        logger.info(
//            "test 1.6 - starting an \"equal\" plugin after original stopped");
//        logger.info("starting " + plugin2.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin2);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
//        logger.info("stopping " + retPlugin.getIdentifier());
//        pluginRegistry.stopPlugin(retPlugin.getName());
//
//        // test starting of an "unequal" plugin with same name
//        logger.info(
//            "test 1.7 - starting of an \"unequal\" plugin with same name");
//        logger.info("starting " + plugin1.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin1);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
//        logger.info("starting " + plugin3.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin3);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
//        logger.info("stopping " + retPlugin.getIdentifier());
//        pluginRegistry.stopPlugin(retPlugin.getName());
//
//        // test starting of multiple plugins and stopAll
//        logger.info("test 1.8 - starting of multiple plugins and stopAll");
//        logger.info("starting " + plugin1.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin1);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
//        logger.info("starting " + plugin4.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin4);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
//        verbosePluginOutput = false;
//        logger.info("stopping all plugins");
//        pluginRegistry.stopAllPlugins();
//        verbosePluginOutput = true;
//        logger.info(plugin1.getIdentifier() + " is " +
//            (plugin1.isActive() ? "active" : "inactive"));
//        logger.info(plugin4.getIdentifier() + " is " +
//            (plugin4.isActive() ? "active" : "inactive"));
//        logger.info("stopping all plugins again");
//        pluginRegistry.stopAllPlugins();
//
//        // test starting of multiple plugins and stopAll
//        logger.info(
//            "test 1.9 - starting of multiple plugins, stopping, and stopAll");
//        logger.info("starting " + plugin1.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin1);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
//        logger.info("starting " + plugin4.getIdentifier());
//        retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin4);
//        logger.info("returned plugin is " + retPlugin.getIdentifier());
        logger.info("stopping " + plugin1.getIdentifier() +
            " using plugin object");
        pluginRegistry.stopPlugin(plugin1.getName());
        verbosePluginOutput = false;
        logger.info("stopping all plugins");
        pluginRegistry.stopAllPlugins();
        verbosePluginOutput = true;
        logger.info(plugin1.getIdentifier() + " is " +
            (plugin1.isActive() ? "active" : "inactive"));
        logger.info(plugin4.getIdentifier() + " is " +
            (plugin4.isActive() ? "active" : "inactive"));
        logger.info("stopping all plugins again");
        //
        //  Warning about removing non-registered LoggerRepositoryEventListener
        //     goes to console on log4j 1.2 instead of log file with log4j 1.3.
        //
        pluginRegistry.stopAllPlugins();

        assertTrue(Compare.compare(PluginTestCase.class,
                getOutputFile(testName),
                getWitnessFile(testName)));
    }

    // basic test of plugin with repositories
    public void test2() throws Exception {
//
//        String testName = "test2";
//        Logger logger = Logger.getLogger(testName);
//
//        setupAppender(testName);
//
//        PluginTester plugin1 = new PluginTester1("plugin1", 1);
//        PluginTester plugin2 = new PluginTester1("plugin2", 2);
//        PluginTester retPlugin;
//        LoggerRepository repo1 = new Hierarchy(new RootLogger(Level.DEBUG));
//        LoggerRepository repo2 = new Hierarchy(new RootLogger(Level.DEBUG));
//
//        PluginRegistry pr1 = repo1.getPluginRegistry();
//        PluginRegistry pr2 = repo2.getPluginRegistry();
//
//        repositoryMap.clear();
//        repositoryMap.put(repo1, "repository1");
//        repositoryMap.put(repo2, "repository2");
//
//        logger.info("test 2.1 - starting plugins in multiple repositories");
//        logger.info("starting " + plugin1.getIdentifier() + " in " +
//            repositoryMap.get(repo1));
//        retPlugin = (PluginTester) pr1.startPlugin(plugin1);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//        logger.info("starting " + plugin2.getIdentifier() + " in " +
//            repositoryMap.get(repo2));
//        retPlugin = (PluginTester) pr2.startPlugin(plugin2);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//
//        logger.info("test 2.2 - stopping plugins in multiple repositories");
//        logger.info("stopping " + plugin1.getIdentifier() + " in " +
//            repositoryMap.get(plugin1.getLoggerRepository()));
//        retPlugin = (PluginTester) pr1.stopPlugin(plugin1.getName());
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//        logger.info("stopping " + plugin2.getIdentifier() + " in " +
//            repositoryMap.get(plugin2.getLoggerRepository()));
//        retPlugin = (PluginTester) pr2.stopPlugin(plugin2.getName());
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//
//        logger.info("test 2.3 - restarting plugins in different repositories");
//        logger.info("starting " + plugin1.getIdentifier() + " in " +
//            repositoryMap.get(repo2));
//        retPlugin = (PluginTester) pr2.startPlugin(plugin1);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//        logger.info("starting " + plugin2.getIdentifier() + " in " +
//            repositoryMap.get(repo1));
//        retPlugin = (PluginTester) pr1.startPlugin(plugin2);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//
//        logger.info("test 2.4 - stopping plugins using stopAll");
//        logger.info("stopping all plugins in " + repositoryMap.get(repo1));
//        pr1.stopAllPlugins();
//        logger.info("stopping all plugins in " + repositoryMap.get(repo2));
//        pr2.stopAllPlugins();
//
//        logger.info(
//            "test 2.5 - starting a plugin already active in another repository");
//        logger.info("starting " + plugin1.getIdentifier() + " in " +
//            repositoryMap.get(repo1));
//        retPlugin = (PluginTester) pr1.startPlugin(plugin1);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//        logger.info("starting " + plugin2.getIdentifier() + " in " +
//            repositoryMap.get(repo2));
//        retPlugin = (PluginTester) pr2.startPlugin(plugin2);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//        logger.info("restarting " + plugin1.getIdentifier() + " in " +
//            repositoryMap.get(repo2));
//        retPlugin = (PluginTester) pr2.startPlugin(plugin1);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//        logger.info("restarting " + plugin2.getIdentifier() + " in " +
//            repositoryMap.get(repo1));
//        retPlugin = (PluginTester) pr1.startPlugin(plugin2);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//
//        logger.info("test 2.6 - handle repository reset");
//        logger.info("resetting " + repositoryMap.get(repo1));
//        repo1.resetConfiguration();
//        logger.info("resetting " + repositoryMap.get(repo2));
//        repo2.resetConfiguration();
//
//        logger.info("test 2.7 - handle repository shutdown");
//        logger.info("starting " + plugin1.getIdentifier() + " in " +
//            repositoryMap.get(repo1));
//        retPlugin = (PluginTester) pr1.startPlugin(plugin1);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//        logger.info("starting " + plugin2.getIdentifier() + " in " +
//            repositoryMap.get(repo2));
//        retPlugin = (PluginTester) pr2.startPlugin(plugin2);
//        logger.info(
//            "returned plugin is " + retPlugin.getIdentifier() + " in " +
//            repositoryMap.get(retPlugin.getLoggerRepository()));
//        logger.info("shutting down " + repositoryMap.get(repo1));
//        repo1.shutdown();
//        logger.info("shutting down " + repositoryMap.get(repo2));
//        repo2.shutdown();
//
//        assertTrue(Compare.compare(getOutputFile(testName),
//                getWitnessFile(testName)));
    }

    public void testPluginListeners() {

        Plugin p = new PluginTester1("MyNewPlugin", 1);
        PluginListenerLatch l = new PluginListenerLatch();
        pluginRegistry.stopAllPlugins();
        pluginRegistry.addPluginListener(l);
        pluginRegistry.addPlugin(p);

        PluginEvent e = l.LastEvent;

        assertTrue("PluginListener should have been notified of start",
            l.StartLatch);
        assertTrue("PluginListener stop latch should not be activated",
            !l.StopLatch);
        assertTrue("PluginListener should be given reference to Plugin",
            e.getPlugin() == p);

        l.reset();
        pluginRegistry.stopAllPlugins();
        assertTrue("PluginListener should have been notified of stop",
            l.StopLatch);
        assertTrue("PluginListener should not have been notified of start",
            !l.StartLatch);
        assertTrue("PluginListener should be given reference to Plugin",
            l.LastEvent.getPlugin() == p);
        assertTrue(
            "PluginListener should have received a distinct event object",
            l.LastEvent != e);
    }

    public void testPropertyChangeListeners() {

        Plugin plugin = new PluginTester1("PluginTest1", 1);

        final PropertyChangeListenerLatch l = new PropertyChangeListenerLatch();
        plugin.addPropertyChangeListener(l);

        /**
         * Test the basic properties and ensure they get latched by notification
         */
        plugin.setName("NewName");
        assertTrue("PropertyChange latch should have been detected",
            l.isLatched());
        assertTrue("Old value unexpected: '" + l.getLastEvent().getOldValue() +
            "'", l.getLastEvent().getOldValue().equals("PluginTest1"));
        assertTrue("New value unexpected: '" + l.getLastEvent().getNewValue() +
            "'", l.getLastEvent().getNewValue().equals("NewName"));

        l.reset();

        plugin.removePropertyChangeListener(l);
        plugin.setName("SecondNewName");

        assertTrue("Should not have been notified/latched", !l.isLatched());

        l.reset();

        /**
         * Test when only listening for specific property
         */
        plugin.addPropertyChangeListener("name", l);

        plugin.setName("NewName2");
        assertTrue("PropertyChange latch should have been detected",
            l.isLatched());
        assertTrue("Old value unexpected: '" + l.getLastEvent().getOldValue() +
            "'", l.getLastEvent().getOldValue().equals("SecondNewName"));
        assertTrue("New value unexpected: '" + l.getLastEvent().getNewValue() +
            "'", l.getLastEvent().getNewValue().equals("NewName2"));

        plugin.removePropertyChangeListener("name", l);

        l.reset();

        /**
         * setup some assertions before continuing testing to make sure the test code isn't broken
         */
        assertTrue("Plugin should not be active just yet", !plugin.isActive());
        assertTrue("Latch should not be latched", !l.isLatched());

        plugin.addPropertyChangeListener("active", l);

        pluginRegistry.addPlugin(plugin);
/*
        assertTrue(
            "Should have been notified of activation when pluginRegistry.start(plugin)",
            l.isLatched());
        assertTrue("Active old value should have been false",
            l.getLastEvent().getOldValue().equals(Boolean.FALSE));
        assertTrue("Active New value should have been true",
            l.getLastEvent().getNewValue().equals(Boolean.TRUE));

        pluginRegistry.stopAllPlugins();
        l.reset();
        assertTrue("Latch should have been reset", !l.isLatched());
*/

        /**
         * start afresh
         */
/*
        plugin = new PluginTester1("LoggerRepositoryProperty", 2);

        LoggerRepository oldValue = plugin.getLoggerRepository();
        plugin.addPropertyChangeListener("loggerRepository", l);

        LoggerRepository rep = new Hierarchy(new RootLogger(Level.DEBUG));
        plugin.setLoggerRepository(rep);

        assertTrue("Should be notified of LoggerRepository property change",
            l.isLatched());
        assertTrue("LoggerRepository Old value mismatch",
            l.getLastEvent().getOldValue() == oldValue);
        assertTrue("LoggerRepository New vale mismatch",
            l.getLastEvent().getNewValue() == rep);
*/
    }

    private static class PluginListenerLatch implements PluginListener {

        private boolean StartLatch;
        private boolean StopLatch;
        private PluginEvent LastEvent;

        /* (non-Javadoc)
         * @see org.apache.log4j.plugins.PluginListener#pluginStarted(org.apache.log4j.plugins.PluginEvent)
         */
        public void pluginStarted(PluginEvent e) {
            StartLatch = true;
            LastEvent = e;
        }

        /* (non-Javadoc)
         * @see org.apache.log4j.plugins.PluginListener#pluginStopped(org.apache.log4j.plugins.PluginEvent)
         */
        public void pluginStopped(PluginEvent e) {
            StopLatch = true;
            LastEvent = e;
        }

        void reset() {
            StartLatch = false;
            StopLatch = false;
            LastEvent = null;
        }
    }

    private static class PropertyChangeListenerLatch
        implements PropertyChangeListener {

        boolean latch = false;
        PropertyChangeEvent lastEvent = null;

        /* (non-Javadoc)
         * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
         */
        public void propertyChange(PropertyChangeEvent evt) {
            latch = true;
            lastEvent = evt;
        }

        boolean isLatched() {

            return latch;
        }

        void reset() {
            latch = false;
            lastEvent = null;
        }

        PropertyChangeEvent getLastEvent() {

            return lastEvent;
        }
    }

    /**
      Class to test the Plugin and PluginRegistry functionality. */
    private static class PluginTester extends PluginSkeleton {

        protected Logger logger;
        private boolean active = false;
        public int id;

        public synchronized boolean isActive() {
            logger.debug(this.getIdentifier() + " is " +
                (active ? "active" : "inactive"));

            return active;
        }

        private synchronized boolean setActive(boolean _active) {

            boolean oldValue = active;

            if (active != _active) {
                active = _active;
                firePropertyChange("active", oldValue, active);

                return true;
            } else {

                return false;
            }
        }

        public String getIdentifier() {

            if (verbosePluginOutput) {

                return this.getName() + "-id" + id;
            } else {

                return "plugin in " +
                repositoryMap.get(this.getLoggerRepository());
            }
        }

        public void activateOptions() {

            if (setActive(true)) {
                logger.debug(this.getIdentifier() + " activated");
            } else {
                logger.debug(this.getIdentifier() + " already activated");
            }
        }

        public void shutdown() {

            if (setActive(false)) {
                logger.debug(this.getIdentifier() + " shutdown");
            } else {
                logger.debug(this.getIdentifier() + " already shutdown");
            }
        }

        /* (non-Javadoc)
         * @see org.apache.log4j.plugins.Plugin#isEquivalent(org.apache.log4j.plugins.Plugin)
         */
        public boolean isEquivalent(Plugin testPlugin) {

            boolean equiv = super.isEquivalent(testPlugin);

            if (equiv) {
                logger.debug("plugin equal");
            } else if (!(testPlugin.getClass() == this.getClass())) {
                logger.debug(
                    "plugin not equal, different class: " +
                    this.getClass().getName() + " != " +
                    testPlugin.getClass().getName());

            } else if (!this.getName().equals(testPlugin.getName())) {
                logger.debug(
                    "plugin not equal, different name: " + this.getName() +
                    " != " + testPlugin.getName());

            } else if (!this.getLoggerRepository().equals(
                        testPlugin.getLoggerRepository())) {
                logger.debug(
                    "plugin not equal, different repository: " +
                    repositoryMap.get(this.getLoggerRepository()) + " != " +
                    repositoryMap.get(testPlugin.getLoggerRepository()));
            }

            return equiv;
        }
    }

    /**
      Class to test the Plugin and PluginRegistry functionality. */
    private static class PluginTester1 extends PluginTester {
        public PluginTester1(String _name, int _id) {
            logger = Logger.getLogger(this.getClass());
            setName(_name);
            id = _id;
        }
    }

    /**
      Class to test the Plugin and PluginRegistry functionality. */
    private static class PluginTester2 extends PluginTester {
        public PluginTester2(String _name, int _id) {
            logger = Logger.getLogger(this.getClass());
            setName(_name);
            id = _id;
        }
    }
}


text:
layout: picture-post
title: "April #day21"
excerpt: "April 2018 Photography"
categories: photo-challenge
tags: [April, 2018, Photography]
comments: true
share: true
---
Day 21 - Make it bright


text: package umich.ms.fileio;


text:
"""
This script can be used to check if TM1py can connect to your TM1 instance
"""

import getpass
from distutils.util import strtobool

from TM1py.Services import TM1Service

# Parameters for connection
user = input("TM1 User (leave empty if SSO): ")
password = getpass.getpass("Password (leave empty if SSO): ")
namespace = input("CAM Namespace (leave empty if no CAM Security): ")
address = input("Address (leave empty if localhost): ") or "localhost"
gateway = input("ClientCAMURI (leave empty if no SSO): ")
port = input("HTTP Port (Default 5000): ") or "5000"
ssl = strtobool(input("SSL (Default T or F): ") or "T")

if len(namespace.strip()) == 0:
    namespace = None

if len(gateway.strip()) == 0:
    gateway = None

try:
    with TM1Service(
            address=address,
            port=port,
            user=user,
            password=password,
            namespace=namespace,
            gateway=gateway,
            ssl=ssl) as tm1:
        server_name = tm1.server.get_server_name()
        print("Connection to TM1 established!! your Servername is: {}".format(server_name))
except Exception as e:
    print("\nERROR:")
    print("\t" + str(e))


text:
<?php

namespace AppBundle\Controller\Form;

use AppBundle\Controller\DefaultController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use YnloFramework\YnloFormBundle\Form\Type\TagsType;

class TagsController extends DefaultController
{
    const TITLE = 'Tags';
    const ICON = 'tags';

    /**
     * @Route(path="/form/widgets/tags", name="form_widget_tags")
     */
    public function defaultAction(Request $request)
    {
        $form = $this->get('form.factory')->create();
        $form->add('tags', TagsType::class);

        $form->add(
            'tags_predefined', TagsType::class,
            [
                'label' => 'Tags (Predefined tags)',
                'choices' => [
                    'php' => 'php',
                    'html' => 'html',
                    'javascript' => 'javascript',
                    'css' => 'css',
                ]
            ]
        );
        return $this->renderExample(['form' => $form->createView()]);
    }
}


text:
Ingresa tus datos

		<form data-ng-submit="signin()" class="signin form-horizontal" autocomplete="off">
			<fieldset>

					Nombre de usuario
					<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Nombre de usuario">

					Contraseña
					<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Contraseña">

					<button type="submit" class="btn btn-primary">Ingresar</button>  o
					Registrarse

			</fieldset>
		</form>


text:
package edu.umd.cs.findbugs.detect;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ASTORE;
import org.apache.bcel.generic.InstructionHandle;

import edu.umd.cs.findbugs.BugAccumulator;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.StatelessDetector;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.Hierarchy2;
import edu.umd.cs.findbugs.ba.LiveLocalStoreDataflow;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.MethodUnprofitableException;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import edu.umd.cs.findbugs.ba.XClass;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.MissingClassException;
import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
import edu.umd.cs.findbugs.util.ClassName;

;

/**
 * RuntimeExceptionCapture
 *
 * @author Brian Goetz
 * @author Bill Pugh
 * @author David Hovemeyer
 */
public class RuntimeExceptionCapture extends OpcodeStackDetector implements StatelessDetector {
    private static final boolean DEBUG = SystemProperties.getBoolean("rec.debug");

    private BugReporter bugReporter;

    private List<ExceptionCaught> catchList = new ArrayList<ExceptionCaught>();

    private List<ExceptionThrown> throwList = new ArrayList<ExceptionThrown>();

    private BugAccumulator accumulator;

    private static class ExceptionCaught {
        public String exceptionClass;

        public int startOffset, endOffset, sourcePC;

        public boolean seen = false;

        public boolean dead = false;

        public ExceptionCaught(String exceptionClass, int startOffset, int endOffset, int sourcePC) {
            this.exceptionClass = exceptionClass;
            this.startOffset = startOffset;
            this.endOffset = endOffset;
            this.sourcePC = sourcePC;
        }
    }

    private static class ExceptionThrown {
        public @DottedClassName
        String exceptionClass;

        public int offset;

        public ExceptionThrown(@DottedClassName String exceptionClass, int offset) {
            this.exceptionClass = exceptionClass;
            this.offset = offset;
        }
    }

    public RuntimeExceptionCapture(BugReporter bugReporter) {
        this.bugReporter = bugReporter;
        accumulator = new BugAccumulator(bugReporter);
    }

    @Override
    public void visitJavaClass(JavaClass c) {
        super.visitJavaClass(c);
        accumulator.reportAccumulatedBugs();
    }

   @Override
   public void visitAfter(Code obj) {
        for (ExceptionCaught caughtException : catchList) {
            Set<String> thrownSet = new HashSet<String>();
            for (ExceptionThrown thrownException : throwList) {
                if (thrownException.offset >= caughtException.startOffset && thrownException.offset < caughtException.endOffset) {
                    thrownSet.add(thrownException.exceptionClass);
                    if (thrownException.exceptionClass.equals(caughtException.exceptionClass))
                        caughtException.seen = true;
                }
            }
            int catchClauses = 0;
            if (caughtException.exceptionClass.equals("java.lang.Exception") && !caughtException.seen) {
                // Now we have a case where Exception is caught, but not thrown
                boolean rteCaught = false;
                for (ExceptionCaught otherException : catchList) {
                    if (otherException.startOffset == caughtException.startOffset
                            && otherException.endOffset == caughtException.endOffset) {
                        catchClauses++;
                        if (otherException.exceptionClass.equals("java.lang.RuntimeException"))
                            rteCaught = true;
                    }
                }
                int range = caughtException.endOffset - caughtException.startOffset;
                if (!rteCaught) {
                    int priority = LOW_PRIORITY + 1;
                    if (range > 300)
                        priority--;
                    else if (range < 30)
                        priority++;
                    if (catchClauses > 1)
                        priority++;
                    if (thrownSet.size() > 1)
                        priority--;
                    if (caughtException.dead)
                        priority--;
                    accumulator.accumulateBug(new BugInstance(this, "REC_CATCH_EXCEPTION", priority).addClassAndMethod(this),
                            SourceLineAnnotation.fromVisitedInstruction(getClassContext(), this, caughtException.sourcePC));
                }
            }
        }
        catchList.clear();
        throwList.clear();
    }

    @Override
    public void visit(CodeException obj) {
        try {
            super.visit(obj);
            int type = obj.getCatchType();
            if (type == 0)
                return;
            String name = getConstantPool().constantToString(getConstantPool().getConstant(type));

            ExceptionCaught caughtException = new ExceptionCaught(name, obj.getStartPC(), obj.getEndPC(), obj.getHandlerPC());
            catchList.add(caughtException);

            // See if the store that saves the exception object
            // is alive or dead. We rely on the fact that javac
            // always (?) emits an ASTORE instruction to save
            // the caught exception.
            LiveLocalStoreDataflow dataflow = getClassContext().getLiveLocalStoreDataflow(getMethod());
            CFG cfg = getClassContext().getCFG(getMethod());
            Collection<BasicBlock> blockList = cfg.getBlocksContainingInstructionWithOffset(obj.getHandlerPC());
            for (BasicBlock block : blockList) {
                InstructionHandle first = block.getFirstInstruction();
                if (first != null && first.getPosition() == obj.getHandlerPC() && first.getInstruction() instanceof ASTORE) {
                    ASTORE astore = (ASTORE) first.getInstruction();
                    BitSet liveStoreSet = dataflow.getFactAtLocation(new Location(first, block));
                    if (!liveStoreSet.get(astore.getIndex())) {
                        // The ASTORE storing the exception object is dead
                        if (DEBUG) {
                            System.out.println("Dead exception store at " + first);
                        }
                        caughtException.dead = true;
                        break;
                    }
                }
            }
        } catch (MethodUnprofitableException e) {
            Method m = getMethod();
            bugReporter.reportSkippedAnalysis(DescriptorFactory.instance().getMethodDescriptor(getClassName(), getMethodName(),
                    getMethodSig(), m.isStatic()));
        } catch (DataflowAnalysisException e) {
            bugReporter.logError("Error checking for dead exception store", e);
        } catch (CFGBuilderException e) {
            bugReporter.logError("Error checking for dead exception store", e);
        }
    }

    @Override
    public void sawOpcode(int seen) {
        switch (seen) {
        case ATHROW:
            if (stack.getStackDepth() > 0) {
                OpcodeStack.Item item = stack.getStackItem(0);
                String signature = item.getSignature();
                if (signature != null && signature.length() > 0) {
                    if (signature.startsWith("L"))
                        signature = SignatureConverter.convert(signature);
                    else
                        signature = signature.replace('/', '.');
                    throwList.add(new ExceptionThrown(signature, getPC()));
                }
            }
            break;

        case INVOKEVIRTUAL:
        case INVOKESPECIAL:
        case INVOKESTATIC:
            String className = getClassConstantOperand();
            if (!className.startsWith("["))
                try {
                    XClass c = Global.getAnalysisCache().getClassAnalysis(XClass.class,
                            DescriptorFactory.createClassDescriptor(className));
                    XMethod m = Hierarchy2.findInvocationLeastUpperBound(c, getNameConstantOperand(), getSigConstantOperand(),
                            seen == INVOKESTATIC, seen == INVOKEINTERFACE);
                    if (m == null)
                        break;
                    String[] exceptions = m.getThrownExceptions();
                    if (exceptions != null)
                        for (String name : exceptions)
                            throwList.add(new ExceptionThrown(ClassName.toDottedClassName(name), getPC()));
                } catch (MissingClassException e) {
                    bugReporter.reportMissingClass(e.getClassDescriptor());
                } catch (CheckedAnalysisException e) {
                    bugReporter.logError("Error looking up " + className, e);
                }
            break;
        default:
            break;
        }

    }

}

// vim:ts=4


text:
package org.springframework.security.oauth2.provider.authentication;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.Assert;

/**
 * A pre-authentication filter for OAuth2 protected resources. Extracts an OAuth2 token from the incoming request and
 * uses it to populate the Spring Security context with an {@link OAuth2Authentication} (if used in conjunction with an
 * {@link OAuth2AuthenticationManager}).
 *
 * @author Dave Syer
 *
 */
public class OAuth2AuthenticationProcessingFilter implements Filter, InitializingBean {

	private final static Log logger = LogFactory.getLog(OAuth2AuthenticationProcessingFilter.class);

	private AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();

	private AuthenticationManager authenticationManager;

	private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new OAuth2AuthenticationDetailsSource();

	private TokenExtractor tokenExtractor = new BearerTokenExtractor();

	private AuthenticationEventPublisher eventPublisher = new NullEventPublisher();

	private boolean stateless = true;

	/**
	 * Flag to say that this filter guards stateless resources (default true). Set this to true if the only way the
	 * resource can be accessed is with a token. If false then an incoming cookie can populate the security context and
	 * allow access to a caller that isn't an OAuth2 client.
	 *
	 * @param stateless the flag to set (default true)
	 */
	public void setStateless(boolean stateless) {
		this.stateless = stateless;
	}

	/**
	 * @param authenticationEntryPoint the authentication entry point to set
	 */
	public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
		this.authenticationEntryPoint = authenticationEntryPoint;
	}

	/**
	 * @param authenticationManager the authentication manager to set (mandatory with no default)
	 */
	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	/**
	 * @param tokenExtractor the tokenExtractor to set
	 */
	public void setTokenExtractor(TokenExtractor tokenExtractor) {
		this.tokenExtractor = tokenExtractor;
	}

	/**
	 * @param eventPublisher the event publisher to set
	 */
	public void setAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher) {
		this.eventPublisher = eventPublisher;
	}

	/**
	 * @param authenticationDetailsSource The AuthenticationDetailsSource to use
	 */
	public void setAuthenticationDetailsSource(
			AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
		Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
		this.authenticationDetailsSource = authenticationDetailsSource;
	}

	public void afterPropertiesSet() {
		Assert.state(authenticationManager != null, "AuthenticationManager is required");
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
			ServletException {

		final boolean debug = logger.isDebugEnabled();
		final HttpServletRequest request = (HttpServletRequest) req;
		final HttpServletResponse response = (HttpServletResponse) res;

		try {

			Authentication authentication = tokenExtractor.extract(request);

			if (authentication == null) {
				if (stateless && isAuthenticated()) {
					if (debug) {
						logger.debug("Clearing security context.");
					}
					SecurityContextHolder.clearContext();
				}
				if (debug) {
					logger.debug("No token in request, will continue chain.");
				}
			}
			else {
				request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
				if (authentication instanceof AbstractAuthenticationToken) {
					AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
					needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
				}
				Authentication authResult = authenticationManager.authenticate(authentication);

				if (debug) {
					logger.debug("Authentication success: " + authResult);
				}

				eventPublisher.publishAuthenticationSuccess(authResult);
				SecurityContextHolder.getContext().setAuthentication(authResult);

			}
		}
		catch (OAuth2Exception failed) {
			SecurityContextHolder.clearContext();

			if (debug) {
				logger.debug("Authentication request failed: " + failed);
			}
			eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
					new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

			authenticationEntryPoint.commence(request, response,
					new InsufficientAuthenticationException(failed.getMessage(), failed));

			return;
		}

		chain.doFilter(request, response);
	}

	private boolean isAuthenticated() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
			return false;
		}
		return true;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void destroy() {
	}

	private static final class NullEventPublisher implements AuthenticationEventPublisher {
		public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) {
		}

		public void publishAuthenticationSuccess(Authentication authentication) {
		}
	}

}


text:
package org.apache.activemq.management;

import javax.jms.Destination;

import org.apache.activemq.util.IndentPrinter;

/**
 * Statistics for a JMS consumer
 *
 *
 */
public class JMSConsumerStatsImpl extends JMSEndpointStatsImpl {
    private String origin;

    public JMSConsumerStatsImpl(JMSSessionStatsImpl sessionStats, Destination destination) {
        super(sessionStats);
        if (destination != null) {
            this.origin = destination.toString();
        }
    }

    public JMSConsumerStatsImpl(CountStatisticImpl messageCount, CountStatisticImpl pendingMessageCount, CountStatisticImpl expiredMessageCount, TimeStatisticImpl messageWaitTime,
                                TimeStatisticImpl messageRateTime, String origin) {
        super(messageCount, pendingMessageCount, expiredMessageCount, messageWaitTime, messageRateTime);
        this.origin = origin;
    }

    public String getOrigin() {
        return origin;
    }

    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("consumer ");
        buffer.append(origin);
        buffer.append(" { ");
        buffer.append(super.toString());
        buffer.append(" }");
        return buffer.toString();
    }

    public void dump(IndentPrinter out) {
        out.printIndent();
        out.print("consumer ");
        out.print(origin);
        out.println(" {");
        out.incrementIndent();

        super.dump(out);

        out.decrementIndent();
        out.printIndent();
        out.println("}");
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
  <OS_AUTH_DOMAINS IDENTIFIER="1" DOMAIN_NAME="default"/>
  <CATISSUE_USER IDENTIFIER="1" FIRST_NAME="ADMIN" LAST_NAME="ADMIN" LOGIN_NAME="admin@admin.com" ACTIVITY_STATUS="Active"
    DOMAIN_NAME="default"/>
  <CATISSUE_ADDRESS IDENTIFIER="1" STREET="Street1" CITY="New york" STATE="NY" COUNTRY="US" ZIPCODE="12341"
    PHONE_NUMBER="1231231234" />

  <CATISSUE_SITE IDENTIFIER="1" NAME="SITE1" TYPE="LIB RACK ARRAY" USER_ID="1" ADDRESS_ID="1" ACTIVITY_STATUS="Active" />

  <OS_STORAGE_CONTAINERS IDENTIFIER="1" NAME="FREEZER-100" BARCODE="BARCODE-100" TEMPERATURE="20.0" DIMENSION_ONE_CAPACITY="2"
    DIMENSION_TWO_CAPACITY="2" DIMENSION_ONE_LABELING_SCHEME="Alphabets Lower Case" DIMENSION_TWO_LABELING_SCHEME="Alphabets Lower Case"
    SITE_ID="1" CREATED_BY="1" ACTIVITY_STATUS="Active" COMMENTS="DEFAULT-COMMENTS" />

  <OS_STORAGE_CONTAINERS IDENTIFIER="2" NAME="child-1" BARCODE="default-barcode" TEMPERATURE="20.0" DIMENSION_ONE_CAPACITY="2"
   DIMENSION_TWO_CAPACITY="2" DIMENSION_ONE_LABELING_SCHEME="Alphabets Lower Case" DIMENSION_TWO_LABELING_SCHEME="Alphabets Lower Case"
   SITE_ID="1" CREATED_BY="1" ACTIVITY_STATUS="Active" COMMENTS="default-comments" />

  <OS_STORAGE_CONTAINERS IDENTIFIER="3" NAME="child-2" BARCODE="default-barcode" TEMPERATURE="20.0" DIMENSION_ONE_CAPACITY="2"
   DIMENSION_TWO_CAPACITY="2" DIMENSION_ONE_LABELING_SCHEME="Alphabets Lower Case" DIMENSION_TWO_LABELING_SCHEME="Alphabets Lower Case"
   SITE_ID="1" CREATED_BY="1" ACTIVITY_STATUS="Active" COMMENTS="default-comments" />

  <OS_STORAGE_CONTAINERS IDENTIFIER="4" NAME="child-3" BARCODE="default-barcode" TEMPERATURE="20.0" DIMENSION_ONE_CAPACITY="2"
   DIMENSION_TWO_CAPACITY="2" DIMENSION_ONE_LABELING_SCHEME="Alphabets Lower Case" DIMENSION_TWO_LABELING_SCHEME="Alphabets Lower Case"
   SITE_ID="1" CREATED_BY="1" ACTIVITY_STATUS="Active" COMMENTS="default-comments" />

  <OS_STORAGE_CONTAINERS IDENTIFIER="5" NAME="child-4" BARCODE="default-barcode" TEMPERATURE="20.0" DIMENSION_ONE_CAPACITY="2"
   DIMENSION_TWO_CAPACITY="2" DIMENSION_ONE_LABELING_SCHEME="Alphabets Lower Case" DIMENSION_TWO_LABELING_SCHEME="Alphabets Lower Case"
   SITE_ID="1" CREATED_BY="1" ACTIVITY_STATUS="Active" COMMENTS="default-comments" />

  <OS_CONTAINER_POSITIONS IDENTIFIER="1" POS_ONE="1" POS_TWO="1" POS_ONE_STR="a" POS_TWO_STR="a" STORAGE_CONTAINER_ID="1"
   OCCUPYING_CONTAINER_ID="2"/>

  <OS_CONTAINER_POSITIONS IDENTIFIER="2" POS_ONE="1" POS_TWO="2" POS_ONE_STR="a" POS_TWO_STR="b" STORAGE_CONTAINER_ID="1"
   OCCUPYING_CONTAINER_ID="3"/>

  <OS_CONTAINER_POSITIONS IDENTIFIER="3" POS_ONE="2" POS_TWO="1" POS_ONE_STR="b" POS_TWO_STR="a" STORAGE_CONTAINER_ID="1"
   OCCUPYING_CONTAINER_ID="4"/>

  <OS_CONTAINER_POSITIONS IDENTIFIER="4" POS_ONE="2" POS_TWO="2" POS_ONE_STR="b" POS_TWO_STR="b" STORAGE_CONTAINER_ID="1"
   OCCUPYING_CONTAINER_ID="5"/>

  <CATISSUE_COLLECTION_PROTOCOL IDENTIFIER="1" TITLE="duplicate-title-1" PRINCIPAL_INVESTIGATOR_ID="1" SHORT_TITLE="short-title-1"
    START_DATE="2000-01-31"
    CONSENTS_WAIVED="1" IRB_IDENTIFIER="ASDF-0000" LABEL_FORMAT="specimen-label-format" DESCRIPTION_URL="www.example.com"
    DERIV_LABEL_FORMAT="derivative-format" ALIQUOT_LABEL_FORMAT="aliquot-format" ALIQUOT_IN_SAME_CONTAINER="1"
    ACTIVITY_STATUS="Active"/>

  <CATISSUE_COLLECTION_PROTOCOL IDENTIFIER="2" TITLE="duplicate-title-2" PRINCIPAL_INVESTIGATOR_ID="1" SHORT_TITLE="short-title-2"
    START_DATE="2000-01-31"
    CONSENTS_WAIVED="1" IRB_IDENTIFIER="ASDF-0000" LABEL_FORMAT="specimen-label-format" DESCRIPTION_URL="www.example.com"
    DERIV_LABEL_FORMAT="derivative-format" ALIQUOT_LABEL_FORMAT="aliquot-format" ALIQUOT_IN_SAME_CONTAINER="1"
    ACTIVITY_STATUS="Active"/>

  <CATISSUE_COLLECTION_PROTOCOL IDENTIFIER="3" TITLE="duplicate-title-3" PRINCIPAL_INVESTIGATOR_ID="1" SHORT_TITLE="short-title-3"
    START_DATE="2000-01-31"
    CONSENTS_WAIVED="1" IRB_IDENTIFIER="ASDF-0000" LABEL_FORMAT="specimen-label-format" DESCRIPTION_URL="www.example.com"
    DERIV_LABEL_FORMAT="derivative-format" ALIQUOT_LABEL_FORMAT="aliquot-format" ALIQUOT_IN_SAME_CONTAINER="1"
    ACTIVITY_STATUS="Active"/>

  <OS_STOR_CONT_SPEC_CLASSES STORAGE_CONTAINER_ID="1" SPECIMEN_CLASS="Cell" />
  <OS_STOR_CONT_SPEC_CLASSES STORAGE_CONTAINER_ID="1" SPECIMEN_CLASS="Fluid" />
  <OS_STOR_CONT_SPEC_CLASSES STORAGE_CONTAINER_ID="1" SPECIMEN_CLASS="Molecular" />

  <OS_STOR_CONT_SPEC_TYPES STORAGE_CONTAINER_ID="1" SPECIMEN_TYPE="Bile" />
  <OS_STOR_CONT_SPEC_TYPES STORAGE_CONTAINER_ID="1" SPECIMEN_TYPE="DNA" />
  <OS_STOR_CONT_SPEC_TYPES STORAGE_CONTAINER_ID="1" SPECIMEN_TYPE="Bone Marrow Plasma"/>

  <OS_STOR_CONTAINER_CPS STORAGE_CONTAINER_ID="1" CP_ID="1" />
  <OS_STOR_CONTAINER_CPS STORAGE_CONTAINER_ID="1" CP_ID="2" />
  <OS_STOR_CONTAINER_CPS STORAGE_CONTAINER_ID="1" CP_ID="3" />

</dataset>


text:
NumberProgressBar [Demo](http://kalasoo.github.io/NumberProgressBar/)
=====================================================================

> A lovely progressbar. Inspired by [daimajia](https://github.com/daimajia/NumberProgressBar).

![demo](http://imageshack.com/a/img838/9281/urq.gif)

### To-do List

- [ ] Support multiple number styles
  - [x] percentage
  - [x] numerator / denominator
  - [x] reverse
  - [ ] negative number
  - [ ] customizable
- [ ] Fix bug of multiple reach operations
- [ ] Add color option

### Installation

```
bower install NumberProgressBar [--save]
```

### Usage

##### HTML

```HTML
<div class="number-pb">
  <div class="number-pb-shown"></div>
  <div class="number-pb-num">0%</div>
</div>
```

##### CSS
You can refer to the file `number-pb.css` and make your own modifications.

```CSS
.number-pb {
  position: relative;
  height: 3px;
  background-color: #ddd;
}

.number-pb .number-pb-shown {
  position: absolute;
  background-color: #176785;
  background-image: linear-gradient(to right, #176785, #499989);
  top: -1px;
  left: 0;
  height: 5px;
  -moz-box-shadow:    0 0 3px 0 #499989;
  -webkit-box-shadow: 0 0 3px 0 #499989;
  box-shadow:         0 0 3px 0 #499989;
}

.number-pb .number-pb-num {
  position: absolute;
  background-color: #fff;
  left: 0;
  top: -0.45em;
  padding: 0 5px;
}
```

##### javaScript

```javascript
var basicBar = $basic.find('.number-pb').NumberProgressBar({
  style: 'basic',
  min: A_MIN_NUMBER,
  max: A_MAX_NUMBER
})
var percentageBar = $('.number-pb').NumberProgressBar({
  style: 'percentage'
})
var stepBar = $('.number-pb').NumberProgressBar({
  style: 'step',
  max: maxStep
})
/* For stepBar:
   min is set to 0 automatically,
   max is supposed to be > 0 */
bars.reach(dest, reachOptions);  //dest is the progress # at which you want to reach
```

### Options

#### barOptions

These are the options you can configure when initializing a progressbar.

| Option        | Default              | Usage                                     |
| ------------- | -------------------- | ----------------------------------------- |
| style         | `basic`              | [`basic`, `percentage`, `step`]           |
| duration      | `10000`              | The duration (in ms) needed from 0 to 100 |
| min           | `0`                  | The min # of the progress                 |
| max           | `100`                | The max # of the progress                 |
| reverse       | `false`              | If `true`, count down progress            |
| current       | `0`                  | The initial # of the progress             |
| shownQuery    | `'.number-pb-shown'` | Your query string for the shown bar       |
| numQuery      | `'.number-pb-num'`   | Your query string for the number          |

#### reachOptions

These are the options for each reach operation: `bar.reach(dest, reachOptions)`.

| Option        | Default              | Usage                                       |
| ------------- | -------------------- | ------------------------------------------- |
| duration      | `null`               | The duration for a reach operation.         |
| complete      | `null`               | The callback when a reach operation is done.|


text:
Last.fm Scrobbler for Chrome was created for people who listen to music online through their browser, and would like to keep an updated playback history using [last.fm][1]'s scrobbling service.

## Usage

You can obtain the scrobbler either from Chrome Web Store directly or by installing as an "[unpacked extension][2]".

### Chrome Web Store

You can get it directly from Chrome Web Store:

https://chrome.google.com/webstore/detail/lastfm-scrobbler/hhinaapppaileiechjoiifaancjggfjm

### Unpacked extension

1. Grab a copy of the source code either by cloning the repository or by downloading and extracting the zipped source.

2. Next, enable "Developer mode" within on your Chrome based browser.

3. Finally select "Load unpacked extension" and select the location you have saved the source.

## Development

Check the [wiki pages](../../wiki) to understand development of connectors.

### Gitter

You can join us at Gitter room [david-sabata/web-scrobbler](https://gitter.im/david-sabata/web-scrobbler)

There's also IRC channel #web-scrobbler on irc.freenode.net, but Gitter is preferred now :wink:

## Privacy Policy

See https://github.com/david-sabata/web-scrobbler/wiki/Privacy-policy

## License

See [LICENSE.txt](LICENSE.txt)

[0]: https://kiwiirc.com/client/irc.freenode.net/web-scrobbler
[1]: http://www.last.fm
[2]: https://developer.chrome.com/extensions/getstarted#unpacked


text:
package nu.xom;

import java.util.HashMap;
import java.util.Map;

import org.jaxen.NamespaceContext;

/**
 *
 *

 *  Provides namespace prefix bindings for use in an XPath expression.
 *

 *
 * @author Elliotte Rusty Harold
 * @version 1.2b1
 *
 */
public final class XPathContext {

    private Map namespaces = new HashMap();

    /**
     *

     * Creates a new XPath context that binds the specified prefix to
     * the specified URI. The xml
     * prefix is also bound to the URI
     * http://www.w3.org/XML/1998/namespace.
     *

     *
     * @param prefix the prefix to bind
     * @param uri the namespace URI the prefix is bound to
     */
    public XPathContext(String prefix, String uri) {
        this();
        addNamespace(prefix, uri);
    }

    /**
     *

     * Creates a new XPath context that binds the xml
     * prefix to the URI
     * http://www.w3.org/XML/1998/namespace.
     *

     */
    public XPathContext() {
        addNamespace("xml", Namespace.XML_NAMESPACE);
    }

    /**
     *

     * Binds the specified prefix to the specified namespace URI.
     * If the prefix is already bound in this context, the new URI
     * replaces the old URI. Binding a prefix to null removes the
     * declaration. The binding of the xml prefix
     * may not be changed.
     *

     *
     * @param prefix the prefix to bind
     * @param uri the namespace URI the prefix is bound to
     *
     * @throws NamespaceConflictException if the prefix is
     *     xml and the URI is not
     *     http://www.w3.org/XML/1998/namespace or the
     *     prefix is the empty string
     * @throws NullPointerException if the prefix is null
     *
     */
    public void addNamespace(String prefix, String uri) {

        if ("xml".equals(prefix)
          && !Namespace.XML_NAMESPACE.equals(uri)) {
            throw new NamespaceConflictException(
              "Wrong namespace URI for xml prefix: " + uri);
        }
        if ("".equals(uri)) uri = null;
        if (prefix == null) {
            throw new NullPointerException("Prefixes used in XPath expressions cannot be null");
        }
        else if ("".equals(prefix)){
            throw new NamespaceConflictException(
              "XPath expressions do not use the default namespace");
        }

        // should there be a separate remove method????
        if (uri == null) {
            namespaces.remove(prefix);
        }
        else {
            namespaces.put(prefix, uri);
        }

    }

    // should this be a Node rather than an Element????
    /**
     *

     * Creates a new XPath context that contains all the namespace
     * bindings in scope on the element. Changing
     * the prefixes in scope on the element after the context
     * is returned does not change the context.
     *

     *
     * @param element the element whose namespace bindings are copied
     *
     * @return all the namespace prefix mappings
     *     in scope on the element
     */
    public static XPathContext makeNamespaceContext(Element element) {

        XPathContext context = new XPathContext();
        context.namespaces = element.getNamespacePrefixesInScope();
        return context;

    }

    NamespaceContext getJaxenContext() {
        return new JaxenNamespaceContext();
    }

    private class JaxenNamespaceContext implements NamespaceContext {

        public String translateNamespacePrefixToUri(String prefix) {
            return lookup(prefix);
        }

    }

    public String lookup(String prefix) {
        return (String) namespaces.get(prefix);
    }

}


text:
package org.keycloak.events;

/**
 * @author Stian Thorgersen
 */
public interface Details {
    String CUSTOM_REQUIRED_ACTION="custom_required_action";
    String EMAIL = "email";
    String PREVIOUS_EMAIL = "previous_email";
    String UPDATED_EMAIL = "updated_email";
    String ACTION = "action";
    String CODE_ID = "code_id";
    String REDIRECT_URI = "redirect_uri";
    String RESPONSE_TYPE = "response_type";
    String RESPONSE_MODE = "response_mode";
    String GRANT_TYPE = "grant_type";
    String AUTH_TYPE = "auth_type";
    String AUTH_METHOD = "auth_method";
    String IDENTITY_PROVIDER = "identity_provider";
    String IDENTITY_PROVIDER_USERNAME = "identity_provider_identity";
    String REGISTER_METHOD = "register_method";
    String USERNAME = "username";
    String REMEMBER_ME = "remember_me";
    String TOKEN_ID = "token_id";
    String REFRESH_TOKEN_ID = "refresh_token_id";
    String REFRESH_TOKEN_TYPE = "refresh_token_type";
    String VALIDATE_ACCESS_TOKEN = "validate_access_token";
    String UPDATED_REFRESH_TOKEN_ID = "updated_refresh_token_id";
    String NODE_HOST = "node_host";
    String REASON = "reason";
    String REVOKED_CLIENT = "revoked_client";
    String CLIENT_SESSION_STATE = "client_session_state";
    String CLIENT_SESSION_HOST = "client_session_host";
    String RESTART_AFTER_TIMEOUT = "restart_after_timeout";

    String CONSENT = "consent";
    String CONSENT_VALUE_NO_CONSENT_REQUIRED = "no_consent_required"; // No consent is required by client
    String CONSENT_VALUE_CONSENT_GRANTED = "consent_granted";         // Consent granted by user
    String CONSENT_VALUE_PERSISTED_CONSENT = "persistent_consent";    // Persistent consent used (was already granted by user before)
    String IMPERSONATOR_REALM = "impersonator_realm";
    String IMPERSONATOR = "impersonator";

    String CLIENT_AUTH_METHOD = "client_auth_method";

    String SIGNATURE_REQUIRED = "signature_required";
    String SIGNATURE_ALGORITHM = "signature_algorithm";

    String CLIENT_REGISTRATION_POLICY = "client_registration_policy";

    String EXISTING_USER = "previous_user";

}


text:
package org.ee.expression.parser;

public class MultiplyToken extends BinaryToken {
	public MultiplyToken() {
		super(Precedence.MULT_DIVIDE, "*");
	}

	@Override
	protected int apply(int lhs, int rhs) {
		return lhs * rhs;
	}
}