text:
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import reducers from './reducer';

const store = createStore(reducers, compose(
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
  applyMiddleware(thunk)
));

if (module.hot) {
  module.hot.accept('./reducer', () => {
    return store.replaceReducer(require('./reducer').default);
  });
}

export default store;


text:
jFirecrow
=========

Firecrow - browser simulator for feature identification, automatic scenario generation, and feature reuse

redpajama_set_name: RedPajamaGithub


text:
namespace _04.Character_Multiplier
{
    using System;

    public class CharacterMultiplier
    {
        public static void Main()
        {
            string[] input = Console.ReadLine().Split(' ');
            string firstStr = input[0];
            string secondStr = input[1];

            Console.WriteLine(CharMultiplier(firstStr, secondStr));
        }

        private static int CharMultiplier(string firstStr, string secondStr)
        {
            int longestLength = Math.Max(firstStr.Length, secondStr.Length);
            int sum = 0;

            for (int i = 0; i < longestLength; i++)
            {
                if (firstStr.Length == secondStr.Length)
                {
                    sum += (int)(firstStr[i]) * (int)(secondStr[i]);
                }
                else
                {
                    if (firstStr.Length > secondStr.Length)
                    {
                        if (secondStr.Length <= i)
                        {
                            sum += (int)(firstStr[i]);
                        }
                        else
                        {
                            sum += (int)(firstStr[i]) * (int)(secondStr[i]);
                        }
                    }
                    else
                    {
                        if (firstStr.Length <= i)
                        {
                            sum += (int)(secondStr[i]);
                        }
                        else
                        {
                            sum += (int)(firstStr[i]) * (int)(secondStr[i]);
                        }
                    }
                }
            }

            return sum;
        }
    }
}


text:
import os
import sys
from PyQt4.QtCore import (QFile, QString, QVariant, Qt)
from PyQt4.QtCore import pyqtSignal as Signal
from PyQt4.QtGui import (QApplication, QDialog, QDialogButtonBox, QMenu,
        QMessageBox, QTableView, QVBoxLayout)
from PyQt4.QtSql import (QSqlDatabase, QSqlQuery, QSqlTableModel, QSqlRelation)
from PyQt4 import QtSql

ID, CITY, DEPARTMENT, FIRSTNAME, LASTNAME, SEX, ADDRESS, PID, TITLE, SOLARY, SHIFT, HOURS = range(12)

class StaffDataDlg(QDialog):

    def __init__(self, parent=None):
        super(StaffDataDlg, self).__init__(parent)
        self.create_widgets()
        self.layout_widgets()
        self.create_connections()
        self.setMinimumWidth(850)
        self.setWindowTitle(u'Список сотрудников компании')

    def create_widgets(self):
        # self.model = QSqlTableModel(self)
        self.model = QtSql.QSqlRelationalTableModel(self)
        self.model.setTable("employee")
        self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
        self.model.setRelation(CITY, QtSql.QSqlRelation('cities', 'city_id', 'name'))
        self.model.setRelation(DEPARTMENT, QtSql.QSqlRelation('deps', 'dep_id', 'name'))

        self.model.setSort(ID, Qt.AscendingOrder)
        self.model.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))

        self.model.setHeaderData(CITY, Qt.Horizontal,
                QVariant("City"))
        self.model.setHeaderData(DEPARTMENT, Qt.Horizontal,
                QVariant("Department"))
        self.model.setHeaderData(FIRSTNAME, Qt.Horizontal,
                QVariant("First Name"))
        self.model.setHeaderData(LASTNAME, Qt.Horizontal,
                QVariant("Last Name"))
        self.model.setHeaderData(SEX, Qt.Horizontal,
                QVariant("sex"))
        self.model.setHeaderData(ADDRESS, Qt.Horizontal,
                QVariant("Address"))
        self.model.setHeaderData(PID, Qt.Horizontal,
                QVariant("PID"))

        self.model.setHeaderData(TITLE, Qt.Horizontal,
                QVariant("Title"))

        self.model.setHeaderData(SOLARY, Qt.Horizontal,
                QVariant("SOLARY"))
        self.model.setHeaderData(SHIFT, Qt.Horizontal,
                QVariant("SHIFT"))
        self.model.setHeaderData(HOURS, Qt.Horizontal,
                QVariant("HOURS"))

        self.model.select()

        self.view = QTableView()
        self.view.setModel(self.model)
        # self.view.setSelectionMode(QTableView.SingleSelection)
        self.view.setItemDelegate(QtSql.QSqlRelationalDelegate(self))
        # self.view.setSelectionBehavior(QTableView.SelectRows)
        self.view.setColumnHidden(ID, True)
        self.view.resizeColumnsToContents()

        self.buttonBox = QDialogButtonBox()
        self.addButton = self.buttonBox.addButton(u"&Добавить",
                QDialogButtonBox.ActionRole)
        self.deleteButton = self.buttonBox.addButton(u"&Удалить",
                QDialogButtonBox.ActionRole)
        self.sortButton = self.buttonBox.addButton(u"&Сортировать",
                QDialogButtonBox.ActionRole)

        menu = QMenu(self)
        self.sortByTitleAction = menu.addAction(u"Сортировка по &Title")
        self.sortBySolaryAction = menu.addAction(
                u"Сортировка по &SOLARY")
        self.sortByIDAction = menu.addAction(u"Сортировка по &ID")
        self.sortButton.setMenu(menu)
        self.closeButton = self.buttonBox.addButton(QDialogButtonBox.Close)

    def layout_widgets(self):
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def create_connections(self):
        self.addButton.clicked.connect(self.addRecord)
        self.deleteButton.clicked.connect(self.deleteRecord)
        self.sortByTitleAction.triggered.connect(
                lambda: self.sort(TITLE))
        self.sortBySolaryAction.triggered.connect(
                lambda: self.sort(SOLARY))
        self.sortByIDAction.triggered.connect(lambda: self.sort(ID))
        self.closeButton.clicked.connect(self.accept)

    def addRecord(self):
        row = self.model.rowCount()
        self.model.insertRow(row)
        index = self.model.index(row, TITLE)
        self.view.setCurrentIndex(index)
        self.view.edit(index)

    def deleteRecord(self):
        index = self.view.currentIndex()
        if not index.isValid():
            return
        record = self.model.record(index.row())
        title = record.value(TITLE).toString()
        desc = record.value(SOLARY).toString()
        if (QMessageBox.question(self, "Reference Data",
                QString("Delete %1 from title %2?")
                .arg(desc).arg(title),
                QMessageBox.Yes|QMessageBox.No) ==
                QMessageBox.No):
            return
        self.model.removeRow(index.row())
        self.model.submitAll()

    def sort(self, column):
        self.model.setSort(column, Qt.AscendingOrder)
        self.model.select()

def main():
    app = QApplication(sys.argv)

    filename = os.path.join(os.path.dirname(__file__), "staff.db")
    create = not QFile.exists(filename)

    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(filename)
    if not db.open():
        QMessageBox.warning(None, "Reference Data",
            QString("Database Error: %1").arg(db.lastError().text()))
        sys.exit(1)

    form = StaffDataDlg()
    form.show()

    sys.exit(app.exec_())

main()


text:
<?php
/**
 * Plugin Spip-Bonux
 * Le plugin qui lave plus SPIP que SPIP
 * (c) 2008 Mathieu Marcillaud, Cedric Morin, Romy Tetue
 * Licence GPL
 *
 */

if (!defined("_ECRIRE_INC_VERSION")) return;

include_spip('inc/core21_filtres');

/**
 * une fonction pour générer des menus avec liens
 * ou un span lorsque l'item est sélectionné
 *
 * @param string $url
 * @param string $libelle
 * @param bool $on
 * @param string $class
 * @param string $title
 * @return string
 */
function aoustrong($url,$libelle,$on=false,$class="",$title="",$rel=""){
	return lien_ou_expose($url,$libelle,$on,$class,$title,$rel);
}

/**
 * une fonction pour générer une balise img à partir d'un nom de fichier
 *
 * @param string $img
 * @param string $alt
 * @param string $class
 * @return string
 */
function tag_img($img,$alt="",$class=""){
	$balise_img = chercher_filtre('balise_img');
	return $balise_img($img,$alt,$class);
}

/**
 * Afficher un message "un truc"/"N trucs"
 *
 * @param int $nb
 * @return string
 */
function affiche_un_ou_plusieurs($nb,$chaine_un,$chaine_plusieurs,$var='nb'){
	return singulier_ou_pluriel($nb,$chaine_un,$chaine_plusieurs,$var);
}

/**
 * Ajouter un timestamp à une url de fichier
 *
 * @param unknown_type $fichier
 * @return unknown
 */
function timestamp($fichier){
	if (!$fichier) return $fichier;
	$m = filemtime($fichier);
	return "$fichier?$m";
}

/**
 * Transformer un tableau d'entrées array("rubrique|9","article|8",...)
 * en un tableau contenant uniquement les identifiants d'un type donné.
 * Accepte aussi que les valeurs d'entrées soient une chaîne brute
 * "rubrique|9,article|8,..."
 *
 * @param array/string $selected liste des entrées : tableau ou chaîne séparée par des virgules
 * @param string $type type de valeur à récuperer ('rubrique', 'article')
 *
 * @return array liste des identifiants trouvés.
**/
function picker_selected($selected, $type){
	$select = array();
	$type = preg_replace(',\W,','',$type);

	if ($selected and !is_array($selected))
		$selected = explode(',', $selected);

	if (is_array($selected))
		foreach($selected as $value)
			if (preg_match(",".$type."[|]([0-9]+),",$value,$match)
			  AND strlen($v=intval($match[1])))
			  $select[] = $v;
	return $select;
}

function picker_identifie_id_rapide($ref,$rubriques=0,$articles=0){
	include_spip("inc/json");
	include_spip("inc/lien");
	if (!($match = typer_raccourci($ref)))
		return json_export(false);
	@list($type,,$id,,,,) = $match;
	if (!in_array($type,array($rubriques?'rubrique':'x',$articles?'article':'x')))
		return json_export(false);
	$table_sql = table_objet_sql($type);
	$id_table_objet = id_table_objet($type);
	if (!$titre = sql_getfetsel('titre',$table_sql,"$id_table_objet=".intval($id)))
		return json_export(false);
	$titre = attribut_html(extraire_multi($titre));
	return json_export(array('type'=>$type,'id'=>"$type|$id",'titre'=>$titre));
}

/**
 * Donner n'importe quelle information sur un objet de manière générique.
 *
 * La fonction va gérer en interne deux cas particuliers les plus utilisés :
 * l'URL et le titre (qui n'est pas forcemment la champ SQL "titre").
 *
 * On peut ensuite personnaliser les autres infos en créant une fonction
 * generer_<nom_info>_entite($id_objet, $type_objet, $ligne).
 * $ligne correspond à la ligne SQL de tous les champs de l'objet, les fonctions
 * de personnalisation n'ont donc pas à refaire de requête.
 *
 * @param int $id_objet
 * @param string $type_objet
 * @param string $info
 * @return string
 */
function generer_info_entite($id_objet, $type_objet, $info, $etoile=''){
	// On vérifie qu'on a tout ce qu'il faut
	$id_objet = intval($id_objet);
	if (!($id_objet and $type_objet and $info))
		return '';

	// Si on demande l'url, on retourne direct la fonction
	if ($info == 'url')
		return generer_url_entite($id_objet, $type_objet);

	// Si on demande le titre, on le gère en interne
	if ($demande_titre = ($info == 'titre')){
		global $table_titre;
		$champ_titre = $table_titre[table_objet($type_objet)];
		if (!$champ_titre) $champ_titre = 'titre';
		$champ_titre = ", $champ_titre";
	}

	// Sinon on va tout chercher dans la table et on garde en mémoire
	static $objets;

	// On ne fait la requête que si on n'a pas déjà l'objet ou si on demande le titre mais qu'on ne l'a pas encore
	if (!$objets[$type_objet][$id_objet] or ($demande_titre and !$objets[$type_objet][$id_objet]['titre'])){
		include_spip('base/abstract_sql');
		include_spip('base/connect_sql');
		$objets[$type_objet][$id_objet] = sql_fetsel(
			'*'.$champ_titre,
			table_objet_sql($type_objet),
			id_table_objet($type_objet).' = '.intval($id_objet)
		);
	}
	$ligne = $objets[$type_objet][$id_objet];

	if ($demande_titre)
		$info_generee = $objets[$type_objet][$id_objet]['titre'];
	// Si la fonction generer_TRUC_entite existe, on l'utilise
	else if ($generer = charger_fonction("generer_${info}_entite", '', true))
		$info_generee = $generer($id_objet, $type_objet, $ligne);
	// Sinon on prend le champ SQL
	else
		$info_generee = $ligne[$info];

	// On va ensuite chercher les traitements automatiques à faire
	global $table_des_traitements;
	$maj = strtoupper($info);
	$traitement = $table_des_traitements[$maj];
	$table_objet = table_objet($type_objet);

	if (!$etoile and is_array($traitement)){
		$traitement = $traitement[isset($traitement[$table_objet]) ? $table_objet : 0];
		$traitement = str_replace('%s', '"'.str_replace('"', '\\"', $info_generee).'"', $traitement);
		eval("\$info_generee = $traitement;");
	}

	return $info_generee;
}

/**
 * Protéger les champs passés dans l'url et utilisés dans {tri ...}
 * préserver l'espace pour interpréter ensuite num xxx et multi xxx
 * @param string $t
 * @return string
 */
function tri_protege_champ($t){
	return preg_replace(',[^\s\w.+],','',$t);
}

/**
 * Interpréter les multi xxx et num xxx utilisés comme tri
 * pour la clause order
 * 'multi xxx' devient simplement 'multi' qui est calculé dans le select
 * 'hasard' est calculé dans le select
 * @param string $t
 * @return string
 */
function tri_champ_order($t,$table=NULL,$field=NULL){
	if (strncmp($t,'num ',4)==0){
		$t = substr($t,4);
		$t = preg_replace(',\s,','',$t);
		// Lever une ambiguïté possible si le champ fait partie de la table (pour compatibilité de la balise tri avec compteur, somme, etc.)
		if (!is_null($table) && !is_null($field) && in_array($t,unserialize($field)))
			$t = "0+$table.$t";
		else
			$t = "0+$t";
		return $t;
	}
	elseif(strncmp($t,'multi ',6)==0){
		return "multi";
	}
	else {
		$t = preg_replace(',\s,','',$t);
		// Lever une ambiguïté possible si le champ fait partie de la table (pour compatibilité de la balise tri avec compteur, somme, etc.)
		if (!is_null($table) && !is_null($field) && in_array($t,unserialize($field)))
			return $table.'.'.$t;
		else
			return $t;
	}
}

/**
 * Interpréter les multi xxx et num xxx utilisés comme tri
 * pour la clause select
 * 'multi xxx' devient select "...." as multi
 * les autres cas ne produisent qu'une chaîne vide '' en select
 * 'hasard' devient 'rand() AS hasard' dans le select
 *
 * @param string $t
 * @return string
 */
function tri_champ_select($t){
	if(strncmp($t,'multi ',6)==0){
		$t = substr($t,6);
		$t = preg_replace(',\s,','',$t);
		$t = sql_multi($t,$GLOBALS['spip_lang']);
		return $t;
	}
	if(trim($t)=='hasard'){
		return 'rand() AS hasard';
	}
	return "''";
}

/**
 * Rediriger une page suivant une autorisation,
 * et ce, n'importe où dans un squelette, même dans les inclusions.
 *
 * @param bool $ok Indique si l'on doit rediriger ou pas
 * @param string $url Adresse vers laquelle rediriger
 * @param int $statut Statut HTML avec lequel on redirigera
 * @return string
 */
function filtre_sinon_interdire_acces_dist($ok=false, $url='', $statut=0){
	if ($ok) return '';

	// vider tous les tampons
	while (ob_get_level())
		ob_end_clean();

	include_spip('inc/headers');
	$statut = intval($statut);

	// Si aucun argument on essaye de deviner quoi faire
	if (!$url and !$statut){
		// Si on est dans l'espace privé, on génère du 403 Forbidden
		if (test_espace_prive()){
			http_status(403);
			$echec = charger_fonction('403','exec');
			$echec();
		}
		// Sinon on redirige vers une 404
		else{
			$statut = 404;
		}
	}

	// Sinon on suit les directives indiquées dans les deux arguments

	// S'il y a un statut
	if ($statut){
		// Dans tous les cas on modifie l'entité avec ce qui est demandé
		http_status($statut);
		// Si le statut est une erreur 4xx on va chercher le squelette
		if ($statut >= 400)
			echo recuperer_fond("$statut");
	}

	// S'il y a une URL, on redirige (si pas de statut, la fonction mettra 302)
	if ($url) redirige_par_entete($url, '', $statut);

	exit;
}

/**
 * Calculer et retourner la profondeur de la rubrique
 * (dans spip3, c'est un champ de la table rubrique)
 * les rubriques à la racine sont à une profondeur de 1
 *
 * @param string
 * @return int
*/
function filtre_profondeur_dist($id_rubrique) {
	$id_rubrique = intval($id_rubrique);

	// sauver les calculs déjà faits
	static $profs = array();
	if (isset($profs[$id_rubrique])) {
		return $profs[$id_rubrique];
	}

	// récupérer le parent.
	$id_parent = sql_getfetsel('id_parent', 'spip_rubriques', 'id_rubrique='.$id_rubrique);

	// pas de parent : id_rubrique n'existe pas
	if (is_null($id_parent)) {
		return '';
	}

	// parent zéro : on est tout en haut (racine)
	if ($id_parent == '0') {
		return $profs[$id_rubrique] = 1;
	}

	// sinon, on trouve la profondeur du parent
	$parent = filtre_profondeur_dist($id_parent);
	$profs[$id_rubrique] = ($parent + 1);
	return $profs[$id_rubrique];
}

?>


text:
FROM b.gcr.io/tensorflow/tensorflow:latest
MAINTAINER Vincent Vanhoucke <vanhoucke@google.com>
RUN pip install scikit-learn
RUN rm -rf /notebooks/*
ADD *.ipynb /notebooks/
WORKDIR /notebooks
CMD ["/run_jupyter.sh"]


text:
package com.github.jinahya.rfc5849;

import static com.github.jinahya.rfc5849._Percent.encodePercent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * A builder for generating signature base strings.
 *
 * @author Jin Kwon <jinahya_at_gmail.com>
 * @see 3.4.1.
 * Signature Base String (RFC 5849)
 */
public class OAuthBaseString {//implements Builder<String> {

    static final String PROTOCOL_PARAMETER_PREFIX = "oauth_";

    // -------------------------------------------------------------------------
    /**
     * Builds the signature base string.
     *
     * @return the signature base string.
     */
    public String get() {
        if (httpMethod == null) {
            throw new IllegalStateException("no httpMethod set");
        }
        if (baseUri == null) {
            throw new IllegalStateException("no baseUri set");
        }
//        if (!requestParameters().containsKey(OAuthConstants.OAUTH_NONCE)) {
//            throw new IllegalStateException(
//                    "no " + OAuthConstants.OAUTH_NONCE + " set");
//        }
//        if (!requestParameters().containsKey(OAuthConstants.OAUTH_TIMESTAMP)) {
//            throw new IllegalStateException(
//                    "no " + OAuthConstants.OAUTH_TIMESTAMP + " set");
//        }
        final Map<String, List<String>> encodedRequestParameters
                = new TreeMap<String, List<String>>();
        for (final Entry<String, List<String>> entry
             : requestParameters().entrySet()) {
            final String key = entry.getKey();
            final String key_ = encodePercent(key);
            final List<String> values = entry.getValue();
            final List<String> values_ = new ArrayList<String>(values.size());
            for (final String value : values) {
                values_.add(encodePercent(value));
            }
            Collections.sort(values_);
            encodedRequestParameters.put(key_, values_);
        }
        final StringBuilder builder = new StringBuilder();
        for (final Entry<String, List<String>> entry
             : encodedRequestParameters.entrySet()) {
            final String key = entry.getKey();
            for (final String value : entry.getValue()) {
                if (builder.length() > 0) {
                    builder.append("&");
                }
                builder.append(key).append("=").append(value);
            }
        }
        return encodePercent(httpMethod)
               + "&"
               + encodePercent(baseUri)
               + "&"
               + encodePercent(builder.toString());
    }

    // -------------------------------------------------------------- httpMethod
    /**
     * Sets a value for {@code httpMethod}.
     *
     * @param httpMethod the value of {@code httpMethod}.
     * @return this instance.
     * @see 3.4.1.
     * Signature Base String (RFC 5849)
     */
    public OAuthBaseString httpMethod(final String httpMethod) {
        if (httpMethod == null) {
            throw new NullPointerException("null httpMethod");
        }
        this.httpMethod = httpMethod.toUpperCase();
        return this;
    }

    // ----------------------------------------------------------------- baseUri
    /**
     * Set a value for {@code baseUri}.
     *
     * @param baseUri the value for {@code baseUri}.
     * @return this instance.
     * @see 3.4.1.
     * Signature Base String (RFC 5849)
     */
    public OAuthBaseString baseUri(final String baseUri) {
        this.baseUri = baseUri;
        return this;
    }

    // ------------------------------------------------------- requestParameters
    /**
     * Returns the request parameters.
     *
     * @return the request parameters.
     */
    Map<String, List<String>> requestParameters() {
        if (requestParameters == null) {
            requestParameters = new HashMap<String, List<String>>();
        }
        return requestParameters;
    }

    /**
     * Adds a request parameter.
     *
     * @param key the key of the request parameter.
     * @param value the value of the request parameter.
     * @return this instance.
     */
    public OAuthBaseString requestParameter(final String key,
                                            final String value) {
        if (key == null) {
            throw new NullPointerException("null key");
        }
        if (value == null) {
            throw new NullPointerException("null value");
        }
        List<String> values = requestParameters().get(key);
        if (values == null) {
            values = new ArrayList<String>();
            requestParameters().put(key, values);
        }
        if (key.startsWith(PROTOCOL_PARAMETER_PREFIX)) {
            values.clear();
        }
        values.add(value);
        return this;
    }

    // ---------------------------------------------------------- queryParameter
    /**
     * Adds a query parameter.
     *
     * @param key key
     * @param value value
     * @return this instance
     * @throws IllegalArgumentException if the {@code key} start with
     * {@value #PROTOCOL_PARAMETER_PREFIX}.
     */
    public OAuthBaseString queryParameter(final String key,
                                          final String value) {
        if (key == null) {
            throw new NullPointerException("null key");
        }
        if (key.startsWith(PROTOCOL_PARAMETER_PREFIX)) {
            throw new IllegalArgumentException(
                    "query parameter's key(" + key + ") starts with "
                    + PROTOCOL_PARAMETER_PREFIX);
        }
        return requestParameter(key, value);
    }

    // ------------------------------------------------------- protocolParameter
    /**
     * Sets a protocol parameter.
     *
     * @param key protocol parameter key
     * @param value protocol parameter value.
     * @return this instance
     * @throws IllegalArgumentException if the {@code key} does not start with
     * {@value #PROTOCOL_PARAMETER_PREFIX}.
     */
    public OAuthBaseString protocolParameter(final String key,
                                             final String value) {
        if (key == null) {
            throw new NullPointerException("null key");
        }
        if (!key.startsWith(PROTOCOL_PARAMETER_PREFIX)) {
            throw new IllegalArgumentException(
                    "key(" + key + ") doesn't start with "
                    + PROTOCOL_PARAMETER_PREFIX);
        }
        return requestParameter(key, value);
    }

    /**
     * Puts protocol parameters added to this instance except the one for
     * {@link OAuthConstants#OAUTH_SIGNATURE} to given map and returns the map.
     *
     * @param map the map to which protocol parameters are put.
     * @return given map.
     * @deprecated not used anymore
     */
    @Deprecated
    Map<String, String> protocolParameters(final Map<String, String> map) {
        for (final Entry<String, List<String>> entry
             : requestParameters().entrySet()) {
            final String key = entry.getKey();
            if (!key.startsWith(PROTOCOL_PARAMETER_PREFIX)
                || key.equals(OAuthConstants.OAUTH_SIGNATURE)) {
                continue;
            }
            map.put(key, entry.getValue().get(0));
        }
        return map;
    }

    // -------------------------------------------------------- entityParameters
    /**
     * Adds an entity parameter. This method simply invokes
     * {@link #queryParameter(java.lang.String, java.lang.String)} with given
     * arguments.
     *
     * @param key key of the entity parameter
     * @param value value of the entity parameter
     * @return this instance
     */
    public OAuthBaseString entityParameter(final String key,
                                           final String value) {
        return queryParameter(key, value);
    }

    // ----------------------------------------------------------- oauthCallback
    /**
     * Set a protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_CALLBACK}.
     *
     * @param oauthCallback the protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_CALLBACK}
     * @return this instance
     */
    public OAuthBaseString oauthCallback(final String oauthCallback) {
        return protocolParameter(OAuthConstants.OAUTH_CALLBACK,
                                 oauthCallback);
    }

    // -------------------------------------------------------- oauthConsumerKey
    /**
     * Sets a protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_CONSUMER_KEY}.
     *
     * @param oauthConsumerKey the protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_CONSUMER_KEY}
     * @return this instance.
     */
    public OAuthBaseString oauthConsumerKey(final String oauthConsumerKey) {
        return protocolParameter(OAuthConstants.OAUTH_CONSUMER_KEY,
                                 oauthConsumerKey);
    }

    // -------------------------------------------------------------- oauthNonce
    /**
     * Sets a protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_NONCE}
     *
     * @param oauthNonce the protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_NONCE}
     * @return this instance.
     */
    public OAuthBaseString oauthNonce(final String oauthNonce) {
        return protocolParameter(OAuthConstants.OAUTH_NONCE, oauthNonce);
    }

    // ---------------------------------------------------- oauthSignatureMethod
    /**
     * Sets a protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_SIGNATURE_METHOD}.
     *
     * @param oauthSignatureMethod the protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_SIGNATURE_METHOD}
     * @return return this
     */
    OAuthBaseString oauthSignatureMethod(final String oauthSignatureMethod) {
        return protocolParameter(OAuthConstants.OAUTH_SIGNATURE_METHOD,
                                 oauthSignatureMethod);
    }

    // ---------------------------------------------------------- oauthTimestamp
    /**
     * Sets a protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_TIMESTAMP}.
     *
     * @param oauthTimestamp the protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_TIMESTAMP}
     * @return this instance
     */
    public OAuthBaseString oauthTimestamp(final String oauthTimestamp) {
        return protocolParameter(OAuthConstants.OAUTH_TIMESTAMP,
                                 oauthTimestamp);
    }

    // -------------------------------------------------------------- oauthToken
    /**
     * Sets a protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_TOKEN}.
     *
     * @param oauthToken the protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_TOKEN}
     * @return this instance
     */
    public OAuthBaseString oauthToken(final String oauthToken) {
        return protocolParameter(OAuthConstants.OAUTH_TOKEN, oauthToken);
    }

    // ------------------------------------------------------------ oauthVersion
    /**
     * Sets a protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_VERSION}.
     *
     * @param oauthVersion the protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_VERSION}
     * @return this instance
     */
    public OAuthBaseString oauthVersion(final String oauthVersion) {
        return protocolParameter(OAuthConstants.OAUTH_VERSION, oauthVersion);
    }

    // ----------------------------------------------------------- oauthVerifier
    /**
     * Sets a protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_VERIFIER}.
     *
     * @param oauthVerifier the protocol parameter value for
     * {@value com.github.jinahya.rfc5849.OAuthConstants#OAUTH_VERIFIER}
     * @return this instance
     */
    public OAuthBaseString oauthVerifier(final String oauthVerifier) {
        return protocolParameter(OAuthConstants.OAUTH_VERIFIER, oauthVerifier);
    }

    // -------------------------------------------------------------------------
    private String httpMethod;

    private String baseUri;

    private Map<String, List<String>> requestParameters;
}


text:
/*===--- ConvertUTF.c - Universal Character Names conversions ---------------===
 *
 *                     The LLVM Compiler Infrastructure
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
 *===------------------------------------------------------------------------=*/
/*
 * Copyright 2001-2004 Unicode, Inc.
 *
 * Disclaimer
 *
 * This source code is provided as is by Unicode, Inc. No claims are
 * made as to fitness for any particular purpose. No warranties of any
 * kind are expressed or implied. The recipient agrees to determine
 * applicability of information provided. If this file has been
 * purchased on magnetic or optical media from Unicode, Inc., the
 * sole remedy for any claim will be exchange of defective media
 * within 90 days of receipt.
 *
 * Limitations on Rights to Redistribute This Code
 *
 * Unicode, Inc. hereby grants the right to freely use the information
 * supplied in this file in the creation of products supporting the
 * Unicode Standard, and to make copies of this file in any form
 * for internal or external distribution as long as this notice
 * remains attached.
 */

/* ---------------------------------------------------------------------

    Conversions between UTF32, UTF-16, and UTF-8. Source code file.
    Author: Mark E. Davis, 1994.
    Rev History: Rick McGowan, fixes & updates May 2001.
    Sept 2001: fixed const & error conditions per
        mods suggested by S. Parent & A. Lillich.
    June 2002: Tim Dodd added detection and handling of incomplete
        source sequences, enhanced error detection, added casts
        to eliminate compiler warnings.
    July 2003: slight mods to back out aggressive FFFE detection.
    Jan 2004: updated switches in from-UTF8 conversions.
    Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions.

    See the header file "ConvertUTF.h" for complete documentation.

------------------------------------------------------------------------ */

#include "llvm/Support/ConvertUTF.h"
#ifdef CVTUTF_DEBUG
#include <stdio.h>
#endif
#include <assert.h>

/*
 * This code extensively uses fall-through switches.
 * Keep the compiler from warning about that.
 */
#if defined(__clang__) && defined(__has_warning)
# if __has_warning("-Wimplicit-fallthrough")
#  define ConvertUTF_DISABLE_WARNINGS \
    _Pragma("clang diagnostic push")  \
    _Pragma("clang diagnostic ignored \"-Wimplicit-fallthrough\"")
#  define ConvertUTF_RESTORE_WARNINGS \
    _Pragma("clang diagnostic pop")
# endif
#elif defined(__GNUC__) && __GNUC__ > 6
# define ConvertUTF_DISABLE_WARNINGS \
   _Pragma("GCC diagnostic push")    \
   _Pragma("GCC diagnostic ignored \"-Wimplicit-fallthrough\"")
# define ConvertUTF_RESTORE_WARNINGS \
   _Pragma("GCC diagnostic pop")
#endif
#ifndef ConvertUTF_DISABLE_WARNINGS
# define ConvertUTF_DISABLE_WARNINGS
#endif
#ifndef ConvertUTF_RESTORE_WARNINGS
# define ConvertUTF_RESTORE_WARNINGS
#endif

ConvertUTF_DISABLE_WARNINGS

namespace llvm {

static const int halfShift  = 10; /* used for shifting by 10 bits */

static const UTF32 halfBase = 0x0010000UL;
static const UTF32 halfMask = 0x3FFUL;

#define UNI_SUR_HIGH_START  (UTF32)0xD800
#define UNI_SUR_HIGH_END    (UTF32)0xDBFF
#define UNI_SUR_LOW_START   (UTF32)0xDC00
#define UNI_SUR_LOW_END     (UTF32)0xDFFF

/* --------------------------------------------------------------------- */

/*
 * Index into the table below with the first byte of a UTF-8 sequence to
 * get the number of trailing bytes that are supposed to follow it.
 * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is
 * left as-is for anyone who may want to do such conversion, which was
 * allowed in earlier algorithms.
 */
static const char trailingBytesForUTF8[256] = {
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};

/*
 * Magic values subtracted from a buffer value during UTF8 conversion.
 * This table contains as many values as there might be trailing bytes
 * in a UTF-8 sequence.
 */
static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
                     0x03C82080UL, 0xFA082080UL, 0x82082080UL };

/*
 * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed
 * into the first byte, depending on how many bytes follow.  There are
 * as many entries in this table as there are UTF-8 sequence types.
 * (I.e., one byte sequence, two byte... etc.). Remember that sequencs
 * for *legal* UTF-8 will be 4 or fewer bytes total.
 */
static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };

/* --------------------------------------------------------------------- */

/* The interface converts a whole buffer to avoid function-call overhead.
 * Constants have been gathered. Loops & conditionals have been removed as
 * much as possible for efficiency, in favor of drop-through switches.
 * (See "Note A" at the bottom of the file for equivalent code.)
 * If your compiler supports it, the "isLegalUTF8" call can be turned
 * into an inline function.
 */

/* --------------------------------------------------------------------- */

ConversionResult ConvertUTF32toUTF16 (
        const UTF32** sourceStart, const UTF32* sourceEnd,
        UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF32* source = *sourceStart;
    UTF16* target = *targetStart;
    while (source < sourceEnd) {
        UTF32 ch;
        if (target >= targetEnd) {
            result = targetExhausted; break;
        }
        ch = *source++;
        if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
            /* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */
            if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
                if (flags == strictConversion) {
                    --source; /* return to the illegal value itself */
                    result = sourceIllegal;
                    break;
                } else {
                    *target++ = UNI_REPLACEMENT_CHAR;
                }
            } else {
                *target++ = (UTF16)ch; /* normal case */
            }
        } else if (ch > UNI_MAX_LEGAL_UTF32) {
            if (flags == strictConversion) {
                result = sourceIllegal;
            } else {
                *target++ = UNI_REPLACEMENT_CHAR;
            }
        } else {
            /* target is a character in range 0xFFFF - 0x10FFFF. */
            if (target + 1 >= targetEnd) {
                --source; /* Back up source pointer! */
                result = targetExhausted; break;
            }
            ch -= halfBase;
            *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
            *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
        }
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/* --------------------------------------------------------------------- */

ConversionResult ConvertUTF16toUTF32 (
        const UTF16** sourceStart, const UTF16* sourceEnd,
        UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF16* source = *sourceStart;
    UTF32* target = *targetStart;
    UTF32 ch, ch2;
    while (source < sourceEnd) {
        const UTF16* oldSource = source; /*  In case we have to back up because of target overflow. */
        ch = *source++;
        /* If we have a surrogate pair, convert to UTF32 first. */
        if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
            /* If the 16 bits following the high surrogate are in the source buffer... */
            if (source < sourceEnd) {
                ch2 = *source;
                /* If it's a low surrogate, convert to UTF32. */
                if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
                    ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
                        + (ch2 - UNI_SUR_LOW_START) + halfBase;
                    ++source;
                } else if (flags == strictConversion) { /* it's an unpaired high surrogate */
                    --source; /* return to the illegal value itself */
                    result = sourceIllegal;
                    break;
                }
            } else { /* We don't have the 16 bits following the high surrogate. */
                --source; /* return to the high surrogate */
                result = sourceExhausted;
                break;
            }
        } else if (flags == strictConversion) {
            /* UTF-16 surrogate values are illegal in UTF-32 */
            if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
                --source; /* return to the illegal value itself */
                result = sourceIllegal;
                break;
            }
        }
        if (target >= targetEnd) {
            source = oldSource; /* Back up source pointer! */
            result = targetExhausted; break;
        }
        *target++ = ch;
    }
    *sourceStart = source;
    *targetStart = target;
#ifdef CVTUTF_DEBUG
if (result == sourceIllegal) {
    fprintf(stderr, "ConvertUTF16toUTF32 illegal seq 0x%04x,%04x\n", ch, ch2);
    fflush(stderr);
}
#endif
    return result;
}
ConversionResult ConvertUTF16toUTF8 (
        const UTF16** sourceStart, const UTF16* sourceEnd,
        UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF16* source = *sourceStart;
    UTF8* target = *targetStart;
    while (source < sourceEnd) {
        UTF32 ch;
        unsigned short bytesToWrite = 0;
        const UTF32 byteMask = 0xBF;
        const UTF32 byteMark = 0x80;
        const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */
        ch = *source++;
        /* If we have a surrogate pair, convert to UTF32 first. */
        if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
            /* If the 16 bits following the high surrogate are in the source buffer... */
            if (source < sourceEnd) {
                UTF32 ch2 = *source;
                /* If it's a low surrogate, convert to UTF32. */
                if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
                    ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
                        + (ch2 - UNI_SUR_LOW_START) + halfBase;
                    ++source;
                } else if (flags == strictConversion) { /* it's an unpaired high surrogate */
                    --source; /* return to the illegal value itself */
                    result = sourceIllegal;
                    break;
                }
            } else { /* We don't have the 16 bits following the high surrogate. */
                --source; /* return to the high surrogate */
                result = sourceExhausted;
                break;
            }
        } else if (flags == strictConversion) {
            /* UTF-16 surrogate values are illegal in UTF-32 */
            if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
                --source; /* return to the illegal value itself */
                result = sourceIllegal;
                break;
            }
        }
        /* Figure out how many bytes the result will require */
        if (ch < (UTF32)0x80) {      bytesToWrite = 1;
        } else if (ch < (UTF32)0x800) {     bytesToWrite = 2;
        } else if (ch < (UTF32)0x10000) {   bytesToWrite = 3;
        } else if (ch < (UTF32)0x110000) {  bytesToWrite = 4;
        } else {                            bytesToWrite = 3;
                                            ch = UNI_REPLACEMENT_CHAR;
        }

        target += bytesToWrite;
        if (target > targetEnd) {
            source = oldSource; /* Back up source pointer! */
            target -= bytesToWrite; result = targetExhausted; break;
        }
        switch (bytesToWrite) { /* note: everything falls through. */
            case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
            case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
            case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
            case 1: *--target =  (UTF8)(ch | firstByteMark[bytesToWrite]);
        }
        target += bytesToWrite;
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/* --------------------------------------------------------------------- */

ConversionResult ConvertUTF32toUTF8 (
        const UTF32** sourceStart, const UTF32* sourceEnd,
        UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF32* source = *sourceStart;
    UTF8* target = *targetStart;
    while (source < sourceEnd) {
        UTF32 ch;
        unsigned short bytesToWrite = 0;
        const UTF32 byteMask = 0xBF;
        const UTF32 byteMark = 0x80;
        ch = *source++;
        if (flags == strictConversion ) {
            /* UTF-16 surrogate values are illegal in UTF-32 */
            if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
                --source; /* return to the illegal value itself */
                result = sourceIllegal;
                break;
            }
        }
        /*
         * Figure out how many bytes the result will require. Turn any
         * illegally large UTF32 things (> Plane 17) into replacement chars.
         */
        if (ch < (UTF32)0x80) {      bytesToWrite = 1;
        } else if (ch < (UTF32)0x800) {     bytesToWrite = 2;
        } else if (ch < (UTF32)0x10000) {   bytesToWrite = 3;
        } else if (ch <= UNI_MAX_LEGAL_UTF32) {  bytesToWrite = 4;
        } else {                            bytesToWrite = 3;
                                            ch = UNI_REPLACEMENT_CHAR;
                                            result = sourceIllegal;
        }

        target += bytesToWrite;
        if (target > targetEnd) {
            --source; /* Back up source pointer! */
            target -= bytesToWrite; result = targetExhausted; break;
        }
        switch (bytesToWrite) { /* note: everything falls through. */
            case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
            case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
            case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
            case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]);
        }
        target += bytesToWrite;
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/* --------------------------------------------------------------------- */

/*
 * Utility routine to tell whether a sequence of bytes is legal UTF-8.
 * This must be called with the length pre-determined by the first byte.
 * If not calling this from ConvertUTF8to*, then the length can be set by:
 *  length = trailingBytesForUTF8[*source]+1;
 * and the sequence is illegal right away if there aren't that many bytes
 * available.
 * If presented with a length > 4, this returns false.  The Unicode
 * definition of UTF-8 goes up to 4-byte sequences.
 */

static Boolean isLegalUTF8(const UTF8 *source, int length) {
    UTF8 a;
    const UTF8 *srcptr = source+length;
    switch (length) {
    default: return false;
        /* Everything else falls through when "true"... */
    case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
    case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
    case 2: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;

        switch (*source) {
            /* no fall-through in this inner switch */
            case 0xE0: if (a < 0xA0) return false; break;
            case 0xED: if (a > 0x9F) return false; break;
            case 0xF0: if (a < 0x90) return false; break;
            case 0xF4: if (a > 0x8F) return false; break;
            default:   if (a < 0x80) return false;
        }

    case 1: if (*source >= 0x80 && *source < 0xC2) return false;
    }
    if (*source > 0xF4) return false;
    return true;
}

/* --------------------------------------------------------------------- */

/*
 * Exported function to return whether a UTF-8 sequence is legal or not.
 * This is not used here; it's just exported.
 */
Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) {
    int length = trailingBytesForUTF8[*source]+1;
    if (length > sourceEnd - source) {
        return false;
    }
    return isLegalUTF8(source, length);
}

/* --------------------------------------------------------------------- */

static unsigned
findMaximalSubpartOfIllFormedUTF8Sequence(const UTF8 *source,
                                          const UTF8 *sourceEnd) {
  UTF8 b1, b2, b3;

  assert(!isLegalUTF8Sequence(source, sourceEnd));

  /*
   * Unicode 6.3.0, D93b:
   *
   *   Maximal subpart of an ill-formed subsequence: The longest code unit
   *   subsequence starting at an unconvertible offset that is either:
   *   a. the initial subsequence of a well-formed code unit sequence, or
   *   b. a subsequence of length one.
   */

  if (source == sourceEnd)
    return 0;

  /*
   * Perform case analysis.  See Unicode 6.3.0, Table 3-7. Well-Formed UTF-8
   * Byte Sequences.
   */

  b1 = *source;
  ++source;
  if (b1 >= 0xC2 && b1 <= 0xDF) {
    /*
     * First byte is valid, but we know that this code unit sequence is
     * invalid, so the maximal subpart has to end after the first byte.
     */
    return 1;
  }

  if (source == sourceEnd)
    return 1;

  b2 = *source;
  ++source;

  if (b1 == 0xE0) {
    return (b2 >= 0xA0 && b2 <= 0xBF) ? 2 : 1;
  }
  if (b1 >= 0xE1 && b1 <= 0xEC) {
    return (b2 >= 0x80 && b2 <= 0xBF) ? 2 : 1;
  }
  if (b1 == 0xED) {
    return (b2 >= 0x80 && b2 <= 0x9F) ? 2 : 1;
  }
  if (b1 >= 0xEE && b1 <= 0xEF) {
    return (b2 >= 0x80 && b2 <= 0xBF) ? 2 : 1;
  }
  if (b1 == 0xF0) {
    if (b2 >= 0x90 && b2 <= 0xBF) {
      if (source == sourceEnd)
        return 2;

      b3 = *source;
      return (b3 >= 0x80 && b3 <= 0xBF) ? 3 : 2;
    }
    return 1;
  }
  if (b1 >= 0xF1 && b1 <= 0xF3) {
    if (b2 >= 0x80 && b2 <= 0xBF) {
      if (source == sourceEnd)
        return 2;

      b3 = *source;
      return (b3 >= 0x80 && b3 <= 0xBF) ? 3 : 2;
    }
    return 1;
  }
  if (b1 == 0xF4) {
    if (b2 >= 0x80 && b2 <= 0x8F) {
      if (source == sourceEnd)
        return 2;

      b3 = *source;
      return (b3 >= 0x80 && b3 <= 0xBF) ? 3 : 2;
    }
    return 1;
  }

  assert((b1 >= 0x80 && b1 <= 0xC1) || b1 >= 0xF5);
  /*
   * There are no valid sequences that start with these bytes.  Maximal subpart
   * is defined to have length 1 in these cases.
   */
  return 1;
}

/* --------------------------------------------------------------------- */

/*
 * Exported function to return the total number of bytes in a codepoint
 * represented in UTF-8, given the value of the first byte.
 */
unsigned getNumBytesForUTF8(UTF8 first) {
  return trailingBytesForUTF8[first] + 1;
}

/* --------------------------------------------------------------------- */

/*
 * Exported function to return whether a UTF-8 string is legal or not.
 * This is not used here; it's just exported.
 */
Boolean isLegalUTF8String(const UTF8 **source, const UTF8 *sourceEnd) {
    while (*source != sourceEnd) {
        int length = trailingBytesForUTF8[**source] + 1;
        if (length > sourceEnd - *source || !isLegalUTF8(*source, length))
            return false;
        *source += length;
    }
    return true;
}

/* --------------------------------------------------------------------- */

ConversionResult ConvertUTF8toUTF16 (
        const UTF8** sourceStart, const UTF8* sourceEnd,
        UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
    ConversionResult result = conversionOK;
    const UTF8* source = *sourceStart;
    UTF16* target = *targetStart;
    while (source < sourceEnd) {
        UTF32 ch = 0;
        unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
        if (extraBytesToRead >= sourceEnd - source) {
            result = sourceExhausted; break;
        }
        /* Do this check whether lenient or strict */
        if (!isLegalUTF8(source, extraBytesToRead+1)) {
            result = sourceIllegal;
            break;
        }
        /*
         * The cases all fall through. See "Note A" below.
         */
        switch (extraBytesToRead) {
            case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
            case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
            case 3: ch += *source++; ch <<= 6;
            case 2: ch += *source++; ch <<= 6;
            case 1: ch += *source++; ch <<= 6;
            case 0: ch += *source++;
        }
        ch -= offsetsFromUTF8[extraBytesToRead];

        if (target >= targetEnd) {
            source -= (extraBytesToRead+1); /* Back up source pointer! */
            result = targetExhausted; break;
        }
        if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
            /* UTF-16 surrogate values are illegal in UTF-32 */
            if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
                if (flags == strictConversion) {
                    source -= (extraBytesToRead+1); /* return to the illegal value itself */
                    result = sourceIllegal;
                    break;
                } else {
                    *target++ = UNI_REPLACEMENT_CHAR;
                }
            } else {
                *target++ = (UTF16)ch; /* normal case */
            }
        } else if (ch > UNI_MAX_UTF16) {
            if (flags == strictConversion) {
                result = sourceIllegal;
                source -= (extraBytesToRead+1); /* return to the start */
                break; /* Bail out; shouldn't continue */
            } else {
                *target++ = UNI_REPLACEMENT_CHAR;
            }
        } else {
            /* target is a character in range 0xFFFF - 0x10FFFF. */
            if (target + 1 >= targetEnd) {
                source -= (extraBytesToRead+1); /* Back up source pointer! */
                result = targetExhausted; break;
            }
            ch -= halfBase;
            *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
            *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
        }
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

/* --------------------------------------------------------------------- */

static ConversionResult ConvertUTF8toUTF32Impl(
        const UTF8** sourceStart, const UTF8* sourceEnd,
        UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags,
        Boolean InputIsPartial) {
    ConversionResult result = conversionOK;
    const UTF8* source = *sourceStart;
    UTF32* target = *targetStart;
    while (source < sourceEnd) {
        UTF32 ch = 0;
        unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
        if (extraBytesToRead >= sourceEnd - source) {
            if (flags == strictConversion || InputIsPartial) {
                result = sourceExhausted;
                break;
            } else {
                result = sourceIllegal;

                /*
                 * Replace the maximal subpart of ill-formed sequence with
                 * replacement character.
                 */
                source += findMaximalSubpartOfIllFormedUTF8Sequence(source,
                                                                    sourceEnd);
                *target++ = UNI_REPLACEMENT_CHAR;
                continue;
            }
        }
        if (target >= targetEnd) {
            result = targetExhausted; break;
        }

        /* Do this check whether lenient or strict */
        if (!isLegalUTF8(source, extraBytesToRead+1)) {
            result = sourceIllegal;
            if (flags == strictConversion) {
                /* Abort conversion. */
                break;
            } else {
                /*
                 * Replace the maximal subpart of ill-formed sequence with
                 * replacement character.
                 */
                source += findMaximalSubpartOfIllFormedUTF8Sequence(source,
                                                                    sourceEnd);
                *target++ = UNI_REPLACEMENT_CHAR;
                continue;
            }
        }
        /*
         * The cases all fall through. See "Note A" below.
         */
        switch (extraBytesToRead) {
            case 5: ch += *source++; ch <<= 6;
            case 4: ch += *source++; ch <<= 6;
            case 3: ch += *source++; ch <<= 6;
            case 2: ch += *source++; ch <<= 6;
            case 1: ch += *source++; ch <<= 6;
            case 0: ch += *source++;
        }
        ch -= offsetsFromUTF8[extraBytesToRead];

        if (ch <= UNI_MAX_LEGAL_UTF32) {
            /*
             * UTF-16 surrogate values are illegal in UTF-32, and anything
             * over Plane 17 (> 0x10FFFF) is illegal.
             */
            if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
                if (flags == strictConversion) {
                    source -= (extraBytesToRead+1); /* return to the illegal value itself */
                    result = sourceIllegal;
                    break;
                } else {
                    *target++ = UNI_REPLACEMENT_CHAR;
                }
            } else {
                *target++ = ch;
            }
        } else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */
            result = sourceIllegal;
            *target++ = UNI_REPLACEMENT_CHAR;
        }
    }
    *sourceStart = source;
    *targetStart = target;
    return result;
}

ConversionResult ConvertUTF8toUTF32Partial(const UTF8 **sourceStart,
                                           const UTF8 *sourceEnd,
                                           UTF32 **targetStart,
                                           UTF32 *targetEnd,
                                           ConversionFlags flags) {
  return ConvertUTF8toUTF32Impl(sourceStart, sourceEnd, targetStart, targetEnd,
                                flags, /*InputIsPartial=*/true);
}

ConversionResult ConvertUTF8toUTF32(const UTF8 **sourceStart,
                                    const UTF8 *sourceEnd, UTF32 **targetStart,
                                    UTF32 *targetEnd, ConversionFlags flags) {
  return ConvertUTF8toUTF32Impl(sourceStart, sourceEnd, targetStart, targetEnd,
                                flags, /*InputIsPartial=*/false);
}

/* ---------------------------------------------------------------------

    Note A.
    The fall-through switches in UTF-8 reading code save a
    temp variable, some decrements & conditionals.  The switches
    are equivalent to the following loop:
        {
            int tmpBytesToRead = extraBytesToRead+1;
            do {
                ch += *source++;
                --tmpBytesToRead;
                if (tmpBytesToRead) ch <<= 6;
            } while (tmpBytesToRead > 0);
        }
    In UTF-8 writing code, the switches on "bytesToWrite" are
    similarly unrolled loops.

   --------------------------------------------------------------------- */

} // namespace llvm

ConvertUTF_RESTORE_WARNINGS


text:
package com.avairebot.contracts.ai;

import com.avairebot.AvaIre;
import com.avairebot.handlers.DatabaseEventHolder;
import net.dv8tion.jda.api.entities.Message;

public interface IntelligenceService {

    /**
     * Checks if the intelligence service is enabled
     * and ready to serve requests.
     *
     * @return {@code True} if the service ready to be used, {@code False} otherwise.
     */
    boolean isEnabled();

    /**
     * Registers the service, this is called right when the
     * service is registered with the intelligence manager.
     *
     * @param avaire The main AvaIre application instance.
     */
    void registerService(AvaIre avaire);

    /**
     * Unregisters the service, this is called automatically when
     * a new service is registered to override the current set
     * service, or when the bot shuts down gracefully.
     *
     * @param avaire The main AvaIre application instance.
     */
    void unregisterService(AvaIre avaire);

    /**
     * Handles the current message as an AI request using the given
     * JDA message object instance, and the current guild and
     * player transformers for the current request.
     *
     * @param message             The JDA message instance that triggered the AI request.
     * @param databaseEventHolder The database holder for the current guild and player transformers.
     */
    void onMessage(Message message, DatabaseEventHolder databaseEventHolder);
}


text:
package cs201.gui.structures.market;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;

import cs201.gui.ArtManager;
import cs201.gui.SimCity201;
import cs201.gui.StructurePanel;
import cs201.gui.roles.market.MarketConsumerGui;
import cs201.helper.Constants;

public class MarketAnimationPanel extends StructurePanel {

	/*
	 * ********** DATA & CONSTANTS **********
	 */
    private final static int DEFAULT_WINDOW_WIDTH = 500;
    private final static int DEFAULT_WINDOW_HEIGHT = 500;

    public final static int FIRST_SHELF_X = 50;
    public final static int FIRST_SHELF_Y = 50;
    public final static int SHELF_WIDTH = 50;
    public final static int SHELF_HEIGHT = 200;
    public final static int SHELF_SPACING = 150;
    public final static int SHELF_COUNT = 3;

    /*
     * ********** A* IMPLEMENTATION **********
     */

    // Set up our grid
    static int gridWidth = 20;
    static int gridHeight = 20;
    final int gridPixelWidth = DEFAULT_WINDOW_WIDTH / gridWidth;
    final int gridPixelHeight = DEFAULT_WINDOW_HEIGHT / gridHeight;

    // Set up our grid of semaphores
    Semaphore[][] grid = new Semaphore[gridWidth + 1][gridHeight + 1];

    public Semaphore[][] getAStarGrid() {
    	return grid;
    }

    /* **************
     * CUSTOMER QUEUE
     * **************
     */
    private int queue = 0;
    List<MarketConsumerGui> waitQueue = Collections.synchronizedList( new ArrayList<MarketConsumerGui>() );
    public int whatNumberAmI(MarketConsumerGui gui) {
    	synchronized (waitQueue) {
    		// Go through the queue and see if there are any free spots (null spots)
    		int num = 0;
    		for (MarketConsumerGui thisGui : waitQueue) {
    			if (thisGui == null) {
    				thisGui = gui;
    				return num;
    			}
    			num++;
    		}

    		// If there aren't any, add a spot at the end
    		waitQueue.add(gui);
    		return num;
    	}
    }

    public void leaving(MarketConsumerGui gui) {
    	synchronized(waitQueue) {
    		// Go through and make his spot available
    		for (MarketConsumerGui thisGui : waitQueue) {
    			if (thisGui == gui) {
    				thisGui = null;
    			}
    		}
    	}
    }

    /*
     * ********** CONSTRUCTORS **********
     */

    public MarketAnimationPanel(int ii, SimCity201 sc, int width, int height) {
    	super(ii, sc);
    	// Set the properties of the JPanel
    	setSize(width, height);
        setVisible(true);

        // Initialize the semaphore grid
      	for (int i = 0; i < gridWidth + 1; i++) {
      	    for (int j = 0; j < gridHeight + 1; j++) {
      	    	grid[i][j]=new Semaphore(1,true);
      	    }
      	}

      	// Make the 0-th row and column unavailable
      	try {
      		for (int i = 0; i < gridHeight + 1; i++) grid[0][0+i].acquire();
      		for (int i = 1; i < gridWidth + 1; i++) grid[0+i][0].acquire();
      	} catch (Exception e) {
      		System.out.println("Unexcepted error occured in MarketAnimationPanel constructor: " + e);
      	}

      	// Make shelves and walls unavailable
      	for (int i = 3; i <= 18; i += 3) {
        	acquireRectangleGrid(i, 5, i, 9);
        }
      	acquireRectangleGrid(3, 2, 18, 2);
      	acquireRectangleGrid(3, 3, 18, 3);
      	acquireRectangleGrid(3, 11, 12, 11);
      	acquireRectangleGrid(3, 12, 12, 12);
      	acquireRectangleGrid(15, 11, 18, 11);
        acquireRectangleGrid(15, 12, 18, 12);
    }

    @Override
    public void paintComponent(Graphics g) {
    	Graphics2D g2 = (Graphics2D)g;

        //Clear the screen by painting a rectangle the size of the frame
        g2.setColor(getBackground());
        g2.fillRect(0, 0, DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT );

        if (Constants.DEBUG_MODE) {

    	// Draw the front desk bottom right of the screen
        g2.setColor(Color.black);
        drawRectangleGrid(10, 15, 15, 15, g2);

        // Draw the shelves
        g2.setColor(Color.blue);
        for (int i = 3; i <= 18; i += 3) {
        	drawRectangleGrid(i, 5, i, 9, g2);
        }

        // Draw the walls
        g2.setColor(Color.gray);
        drawRectangleGrid(3, 2, 18, 2, g2);
        drawRectangleGrid(3, 3, 18, 3, g2);
        drawRectangleGrid(3, 11, 12, 11, g2);
        drawRectangleGrid(3, 12, 12, 12, g2);
        drawRectangleGrid(15, 11, 18, 11, g2);
        drawRectangleGrid(15, 12, 18, 12, g2);

        } else {

        	// Draw the floor
        	g2.drawImage(ArtManager.getImage("Market_Floor"), 0, 0, 500, 506, null);

        	// Draw the front desk
        	g2.drawImage(ArtManager.getImage("Market_Front_Desk"), 240, 350, null);

        	// Draw the shelves
        	for (int i = 0; i < 6; i++) {
        		g2.drawImage(ArtManager.getImage("Market_Shelf"), 50 + (i * 75), 100, null);
        	}

        	// Draw the top shelf
        	g2.drawImage(ArtManager.getImage("Market_Shelf_Top"), 50, 25, null);

        	// Draw the bottom left shelf
        	g2.drawImage(ArtManager.getImage("Market_Shelf_Bottom_Left"), 50, 250, null);
        	g2.drawImage(ArtManager.getImage("Market_Shelf_Bottom_Right"), 350, 250, null);

        }

        super.paintComponent(g);
    }

    private void drawRectangleGrid(int leftX, int topY, int rightX, int bottomY, Graphics2D context) {
    	for (int x = leftX - 1; x <= rightX - 1; x++) {
    		for (int y = topY - 1; y <= bottomY - 1; y++) {
    			context.fillRect(gridPixelWidth * x, gridPixelHeight * y, gridPixelWidth, gridPixelHeight);
    		}
    	}
    }

    private void acquireRectangleGrid(int left, int top, int right, int bottom) {
    	for (int x = left; x <= right; x++) {
    		for (int y = top; y <= bottom; y++) {
    			//System.out.println("Acquiring (" + x + "," + y +")");
    			try {
					grid[x][y].acquire();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    	}
    }
}


text:
require 'ipaddress'
require 'spec_helper'
require 'ohai/util/ip_helper'

class IpHelperMock
  include Ohai::Util::IpHelper
end

describe "Ohai::Util::IpHelper" do
  let(:ip_helper) { IpHelperMock.new }

  shared_examples 'ip address types' do
    context 'with an IPv4 address' do
      context 'that is private' do
        let(:address) { '10.128.142.89' }

        it 'identifies the address as private' do
          expect(ip_helper.private_address?(address)).to be_truthy
        end
      end

      context 'that is public' do
        let(:address) { '74.125.224.72' }

        it 'identifies the address as public' do
          expect(ip_helper.private_address?(address)).to be_falsey
        end
      end
    end

    context 'with an IPv6 address' do
      context 'that is an RFC 4193 unique local address' do
        let(:address) { 'fdf8:f53b:82e4::53' }

        it 'identifies the address as a unique local address' do
          expect(ip_helper.private_address?(address)).to be_truthy
        end
      end

      context 'that is a non RFC 4193 unique local address' do
        let(:address) { 'FE80::0202:B3FF:FE1E:8329' }

        it 'does not identify the address as a unique local address' do
          expect(ip_helper.private_address?(address)).to be_falsey
        end
      end
    end
  end

  describe 'private_address?' do
    include_examples 'ip address types'
  end

  describe 'unique_local_address?' do
    include_examples 'ip address types'
  end

  describe 'public_address?' do
    let(:address) { '10.128.142.89' }

    before do
      allow(ip_helper).to receive(:private_address?)
    end

    it 'should call #private_address?' do
      expect(ip_helper).to receive(:private_address?)
      ip_helper.public_address?(address)
    end

    it 'should return the inverse of #private_address?' do
      expect(ip_helper.public_address?(address)).to equal !ip_helper.private_address?(address)
    end
  end

  describe 'loopback?' do
    context 'with an IPv4 address' do
      context 'that is a loopback address' do
        let(:address) { '127.0.0.1' }

        it 'should identify the address as a loopback address' do
          expect(ip_helper.loopback?(address)).to be_truthy
        end
      end

      context 'that is not a loopback address' do
        let(:address) { '1.2.3.4' }

        it 'should not identify the address as a loopback address' do
          expect(ip_helper.loopback?(address)).to be_falsey
        end
      end
    end

    context 'with an IPv6 address' do
      context 'that is a loopback address' do
        let(:address) { '0:0:0:0:0:0:0:1' }

        it 'should identify the address as a loopback address' do
          expect(ip_helper.loopback?(address)).to be_truthy
        end
      end

      context 'that is not a loopback address' do
        let(:address) { '2400:6180:0000:00D0:0000:0000:0009:7001' }

        it 'should not identify the address as a loopback address' do
          expect(ip_helper.loopback?(address)).to be_falsey
        end
      end
    end
  end
end


text:
package example.springdata.mongodb.util;

import java.util.Collection;

import org.springframework.data.mongodb.core.query.CriteriaDefinition;

import example.springdata.mongodb.textsearch.BlogPost;

/**
 * Just a little helper for showing {@link BlogPost}s output on the console.
 *
 * @author Christoph Strobl
 */
public class ConsoleResultPrinter {

	public static void printResult(Collection<BlogPost> blogPosts, CriteriaDefinition criteria) {

		System.out.println(String.format("XXXXXXXXXXXX -- Found %s blogPosts matching '%s' --XXXXXXXXXXXX",
				blogPosts.size(), criteria != null ? criteria.getCriteriaObject() : ""));

		for (BlogPost blogPost : blogPosts) {
			System.out.println(blogPost);
		}

		System.out.println("XXXXXXXXXXXX -- XXXXXXXXXXXX -- XXXXXXXXXXXX\r\n");
	}
}


text:
package eu.lunisolar.magma.func.function.from;

import eu.lunisolar.magma.func.*; // NOSONAR
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import java.util.Objects;// NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR

import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR

import org.testng.Assert;
import org.testng.annotations.*;      //NOSONAR
import java.util.regex.Pattern;          //NOSONAR
import java.text.ParseException;         //NOSONAR
import eu.lunisolar.magma.basics.*; //NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR
import java.util.concurrent.atomic.AtomicInteger; //NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import java.util.function.*; // NOSONAR

/** The test obviously concentrate on the interface methods the function it self is very simple.  */
public class LBiObjIntFunctionTest<T1,T2,R> {
    private static final String ORIGINAL_MESSAGE = "Original message";
    private static final String EXCEPTION_WAS_WRAPPED = "Exception was wrapped.";
    private static final String NO_EXCEPTION_WERE_THROWN = "No exception were thrown.";

    private Integer testValue = 100;

    private LBiObjIntFunction<Integer,Integer,Integer> sut = new LBiObjIntFunction<Integer,Integer,Integer>(){
        public @Nullable Integer applyX(Integer a1,Integer a2,int a3)  {
            return testValue;
        }
    };

    private LBiObjIntFunction<Integer,Integer,Integer> sutNull = new LBiObjIntFunction<Integer,Integer,Integer>(){
        public @Nullable Integer applyX(Integer a1,Integer a2,int a3)  {
            return null;
        }
    };

    private LBiObjIntFunction<Integer,Integer,Integer> sutAlwaysThrowing = LBiObjIntFunction.biObjIntFunc((a1,a2,a3) -> {
            throw new ParseException(ORIGINAL_MESSAGE, 0);
    });

    private LBiObjIntFunction<Integer,Integer,Integer> sutAlwaysThrowingUnchecked = LBiObjIntFunction.biObjIntFunc((a1,a2,a3) -> {
            throw new IndexOutOfBoundsException(ORIGINAL_MESSAGE);
    });

    @Test
    public void testTheResult() throws Throwable {
         Assert.assertEquals(sut.apply(100,100,100), testValue);
    }

    @Test
    public void testTupleCall() throws Throwable {

        LBiObjIntTriple<Integer,Integer> domainObject = Tuple4U.biObjIntTriple(100,100,100);

        Object result = sut.tupleApply(domainObject);

            Assert.assertEquals(result, testValue);
    }

    @Test
    public void testNonNullApply() throws Throwable {
            Assert.assertSame(sut.nonNullApply(100,100,100), testValue);
    }

    @Test
    public void testNestingApplyUnchecked() throws Throwable {

        // then
        try {
            sutAlwaysThrowingUnchecked.nestingApply(100,100,100);
            Assert.fail(NO_EXCEPTION_WERE_THROWN);
        } catch (Exception e) {
            Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
            Assert.assertNull(e.getCause());
            Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
        }
    }

    @Test
    public void testShovingApplyUnchecked() throws Throwable {

        // then
        try {
            sutAlwaysThrowingUnchecked.shovingApply(100,100,100);
            Assert.fail(NO_EXCEPTION_WERE_THROWN);
        } catch (Exception e) {
            Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
            Assert.assertNull(e.getCause());
            Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
        }
    }

    @Test(expectedExceptions=NullPointerException.class, expectedExceptionsMessageRegExp="\\QEvaluated value by nonNullApply() method cannot be null (LBiObjIntFunction: R apply(T1 a1,T2 a2,int a3)).\\E")
    public void testNonNullCapturesNull() throws Throwable {
        sutNull.nonNullApply(100,100,100);
    }

    @Test
    public void testFunctionalInterfaceDescription() throws Throwable {
        Assert.assertEquals(sut.functionalInterfaceDescription(), "LBiObjIntFunction: R apply(T1 a1,T2 a2,int a3)");
    }

    @Test
    public void testBiObjIntFuncMethod() throws Throwable {
        Assert.assertTrue(LBiObjIntFunction.biObjIntFunc((a1,a2,a3) -> testValue ) instanceof LBiObjIntFunction);

    }

    // <editor-fold desc="compose (functional)">

    @Test
    public void testCompose() throws Throwable {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final AtomicInteger beforeCalls = new AtomicInteger(0);

        //given (+ some assertions)
        LBiObjIntFunction<Integer,Integer,Integer> sutO = (a1,a2,a3) -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a1, (Object) 90);
                Assert.assertEquals(a2, (Object) 91);
                Assert.assertEquals(a3, (Object) 92);
                return 100;
        };

        LFunction<Integer,Integer> before1 = p0 -> {
            Assert.assertEquals(p0, (Object) 80);
            beforeCalls.incrementAndGet();
            return 90;
        };
        LFunction<Integer,Integer> before2 = p1 -> {
            Assert.assertEquals(p1, (Object) 81);
            beforeCalls.incrementAndGet();
            return 91;
        };
        LIntUnaryOperator before3 = p2 -> {
            Assert.assertEquals(p2, (Object) 82);
            beforeCalls.incrementAndGet();
            return 92;
        };

        //when
        LBiObjIntFunction<Integer,Integer,Integer> function = sutO.compose(before1,before2,before3);
        function.apply(80,81,82);

        //then - finals
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertEquals(beforeCalls.get(), 3);
    }

    @Test
    public void testUnboxingCompose() throws Throwable {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final AtomicInteger beforeCalls = new AtomicInteger(0);

        //given (+ some assertions)
        LBiObjIntFunction<Integer,Integer,Integer> sutO = (a1,a2,a3) -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a1, (Object) 90);
                Assert.assertEquals(a2, (Object) 91);
                Assert.assertEquals(a3, (Object) 92);
                return 100;
        };

        LFunction<Integer,Integer> before1 = p0 -> {
            Assert.assertEquals(p0, (Object) 80);
            beforeCalls.incrementAndGet();
            return 90;
        };
        LFunction<Integer,Integer> before2 = p1 -> {
            Assert.assertEquals(p1, (Object) 81);
            beforeCalls.incrementAndGet();
            return 91;
        };
        LToIntFunction<Integer> before3 = p2 -> {
            Assert.assertEquals(p2, (Object) 82);
            beforeCalls.incrementAndGet();
            return 92;
        };

        //when
        LTriFunction<Integer,Integer,Integer,Integer> function = sutO.unboxingCompose(before1,before2,before3);
        function.apply(80,81,82);

        //then - finals
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertEquals(beforeCalls.get(), 3);
    }

    // </editor-fold>

    // <editor-fold desc="then (functional)">

    @Test
    public void testThen0() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LBiObjIntFunction<Integer,Integer,Integer> sutO = (a1,a2,a3) -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a1, (Object) 80);
                Assert.assertEquals(a2, (Object) 81);
                Assert.assertEquals(a3, (Object) 82);
                return 90;
        };

        LFunction<Integer,Integer> thenFunction = p -> {
                thenFunctionCalled.set(true);
                // Integer
                Assert.assertEquals(p, (Object) 90);
                // Integer
                return 100;
        };

        //when
        LBiObjIntFunction<Integer,Integer,Integer> function = sutO.then(thenFunction);
        Integer finalValue = function.apply(80,81,82);

        //then - finals
        Assert.assertEquals(finalValue, (Object) 100);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenConsume1() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LBiObjIntFunction<Integer,Integer,Integer> sutO = (a1,a2,a3) -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a1, (Object) 80);
                Assert.assertEquals(a2, (Object) 81);
                Assert.assertEquals(a3, (Object) 82);
                return 90;
        };

        LConsumer<Integer> thenFunction = p -> {
                thenFunctionCalled.set(true);
                // Integer
                Assert.assertEquals(p, (Object) 90);
        };

        //when
        LBiObjIntConsumer<Integer,Integer> function = sutO.thenConsume(thenFunction);
        function.accept(80,81,82);

        //then - finals
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToBool2() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LBiObjIntFunction<Integer,Integer,Integer> sutO = (a1,a2,a3) -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a1, (Object) 80);
                Assert.assertEquals(a2, (Object) 81);
                Assert.assertEquals(a3, (Object) 82);
                return 90;
        };

        LPredicate<Integer> thenFunction = p -> {
                thenFunctionCalled.set(true);
                // Integer
                Assert.assertEquals(p, (Object) 90);
                // boolean
                return true;
        };

        //when
        LBiObjIntPredicate<Integer,Integer> function = sutO.thenToBool(thenFunction);
        boolean finalValue = function.test(80,81,82);

        //then - finals
        Assert.assertEquals(finalValue, (Object) true);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    // </editor-fold>

    @Test(expectedExceptions = RuntimeException.class)
    public void testShove() {

        // given
        LBiObjIntFunction<Integer,Integer,Integer> sutThrowing = LBiObjIntFunction.biObjIntFunc((a1,a2,a3) -> {
            throw new UnsupportedOperationException();
        });

        // when
        sutThrowing.shovingApply(100,100,100);
    }

    @Test
    public void testToString() throws Throwable {

        Assert.assertTrue(sut.toString().startsWith(this.getClass().getName()+"$"));

        Assert.assertTrue(String.format("%s", sut).contains("LBiObjIntFunction: R apply(T1 a1,T2 a2,int a3)"));

    }

    @Test
    public void isThrowing() {

        Assert.assertFalse(sut.isThrowing());
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Smart.Core.Utils
{
    /// <summary>
    /// 管理员级别用户的操作权限验证
    /// </summary>
    public class AdminAuthenticationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            ////验证是否是登录用户
            var identity = filterContext.HttpContext.User.Identity;
            if (identity.IsAuthenticated)
            {
                var actionName = filterContext.ActionDescriptor.ActionName;
                var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

                if (identity.Name.ToLower() != "ivadmin")
                {
                    //虽然是登录用户,但没有该Action的权限,跳转到"未授权访问"页面
                    filterContext.HttpContext.Response.Redirect("~/Home/UnAuthorized", true);
                }
            }
            else
            {
                filterContext.HttpContext.Response.Redirect("~/Account/Login", true);
            }
        }
    }
}


text:
module ts {

    export function isInstantiated(node: Node): boolean {
        // A module is uninstantiated if it contains only
        // 1. interface declarations
        if (node.kind === SyntaxKind.InterfaceDeclaration) {
            return false;
        }
        // 2. non - exported import declarations
        else if (node.kind === SyntaxKind.ImportDeclaration && !(node.flags & NodeFlags.Export)) {
            return false;
        }
        // 3. other uninstantiated module declarations.
        else if (node.kind === SyntaxKind.ModuleBlock && !forEachChild(node, isInstantiated)) {
            return false;
        }
        else if (node.kind === SyntaxKind.ModuleDeclaration && !isInstantiated((<ModuleDeclaration>node).body)) {
            return false;
        }
        else {
            return true;
        }
    }

    export function bindSourceFile(file: SourceFile) {

        var parent: Node;
        var container: Declaration;
        var lastContainer: Declaration;
        var symbolCount = 0;
        var Symbol = objectAllocator.getSymbolConstructor();

        if (!file.locals) {
            file.locals = {};
            container = file;
            bind(file);
            file.symbolCount = symbolCount;
        }

        function createSymbol(flags: SymbolFlags, name: string): Symbol {
            symbolCount++;
            return new Symbol(flags, name);
        }

        function addDeclarationToSymbol(symbol: Symbol, node: Declaration, symbolKind: SymbolFlags) {
            symbol.flags |= symbolKind;
            if (!symbol.declarations) symbol.declarations = [];
            symbol.declarations.push(node);
            if (symbolKind & SymbolFlags.HasExports && !symbol.exports) symbol.exports = {};
            if (symbolKind & SymbolFlags.HasMembers && !symbol.members) symbol.members = {};
            node.symbol = symbol;
            if (symbolKind & SymbolFlags.Value && !symbol.valueDeclaration) symbol.valueDeclaration = node;
        }

        function getDeclarationName(node: Declaration): string {
            if (node.name) {
                if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {
                    return '"' + node.name.text + '"';
                }
                return node.name.text;
            }
            switch (node.kind) {
                case SyntaxKind.Constructor: return "__constructor";
                case SyntaxKind.CallSignature: return "__call";
                case SyntaxKind.ConstructSignature: return "__new";
                case SyntaxKind.IndexSignature: return "__index";
            }
        }

        function getDisplayName(node: Declaration): string {
            return node.name ? identifierToString(node.name) : getDeclarationName(node);
        }

        function declareSymbol(symbols: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol {
            var name = getDeclarationName(node);
            if (name !== undefined) {
                var symbol = hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name));
                if (symbol.flags & excludes) {
                    if (node.name) {
                        node.name.parent = node;
                    }
                    file.semanticErrors.push(createDiagnosticForNode(node.name ? node.name : node,
                        Diagnostics.Duplicate_identifier_0, getDisplayName(node)));
                    symbol = createSymbol(0, name);
                }
            }
            else {
                symbol = createSymbol(0, "__missing");
            }
            addDeclarationToSymbol(symbol, node, includes);
            symbol.parent = parent;

            if (node.kind === SyntaxKind.ClassDeclaration && symbol.exports) {
                // TypeScript 1.0 spec (April 2014): 8.4
                // Every class automatically contains a static property member named 'prototype',
                // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
                // It is an error to explicitly declare a static property member with the name 'prototype'.
                var prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype");
                if (hasProperty(symbol.exports, prototypeSymbol.name)) {
                    if (node.name) {
                        node.name.parent = node;
                    }
                    file.semanticErrors.push(createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0],
                        Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
                }
                symbol.exports[prototypeSymbol.name] = prototypeSymbol;
                prototypeSymbol.parent = symbol;
            }

            return symbol;
        }

        function isAmbientContext(node: Node): boolean {
            while (node) {
                if (node.flags & NodeFlags.Ambient) return true;
                node = node.parent;
            }
            return false;
        }

        function declareModuleMember(node: Declaration, symbolKind: SymbolFlags, symbolExcludes: SymbolFlags) {
            // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue,
            // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set
            // on it. There are 2 main reasons:
            //
            //   1. We treat locals and exports of the same name as mutually exclusive within a container.
            //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
            //      with the same name in the same container.
            //      TODO: Make this a more specific error and decouple it from the exclusion logic.
            //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
            //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
            //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
            var exportKind = 0;
            var exportExcludes = 0;
            if (symbolKind & SymbolFlags.Value) {
                exportKind |= SymbolFlags.ExportValue;
                exportExcludes |= SymbolFlags.Value;
            }
            if (symbolKind & SymbolFlags.Type) {
                exportKind |= SymbolFlags.ExportType;
                exportExcludes |= SymbolFlags.Type;
            }
            if (symbolKind & SymbolFlags.Namespace) {
                exportKind |= SymbolFlags.ExportNamespace;
                exportExcludes |= SymbolFlags.Namespace;
            }
            if (node.flags & NodeFlags.Export || (node.kind !== SyntaxKind.ImportDeclaration && isAmbientContext(container))) {
                if (exportKind) {
                    var local = declareSymbol(container.locals, undefined, node, exportKind, exportExcludes);
                    local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes);
                }
                else {
                    declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes);
                }
            }
            else {
                declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes | exportKind);
            }
        }

        // All container nodes are kept on a linked list in declaration order. This list is used by the getLocalNameOfContainer function
        // in the type checker to validate that the local name used for a container is unique.
        function bindChildren(node: Declaration, symbolKind: SymbolFlags) {
            if (symbolKind & SymbolFlags.HasLocals) {
                node.locals = {};
            }
            var saveParent = parent;
            var saveContainer = container;
            parent = node;
            if (symbolKind & SymbolFlags.IsContainer) {
                container = node;
                if (lastContainer) lastContainer.nextContainer = container;
                lastContainer = container;
            }
            forEachChild(node, bind);
            container = saveContainer;
            parent = saveParent;
        }

        function bindDeclaration(node: Declaration, symbolKind: SymbolFlags, symbolExcludes: SymbolFlags) {
            switch (container.kind) {
                case SyntaxKind.ModuleDeclaration:
                    declareModuleMember(node, symbolKind, symbolExcludes);
                    break;
                case SyntaxKind.SourceFile:
                    if (isExternalModule(<SourceFile>container)) {
                        declareModuleMember(node, symbolKind, symbolExcludes);
                        break;
                    }
                case SyntaxKind.CallSignature:
                case SyntaxKind.ConstructSignature:
                case SyntaxKind.IndexSignature:
                case SyntaxKind.Method:
                case SyntaxKind.Constructor:
                case SyntaxKind.GetAccessor:
                case SyntaxKind.SetAccessor:
                case SyntaxKind.FunctionDeclaration:
                case SyntaxKind.FunctionExpression:
                case SyntaxKind.ArrowFunction:
                    declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes);
                    break;
                case SyntaxKind.ClassDeclaration:
                    if (node.flags & NodeFlags.Static) {
                        declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes);
                        break;
                    }
                case SyntaxKind.TypeLiteral:
                case SyntaxKind.ObjectLiteral:
                case SyntaxKind.InterfaceDeclaration:
                    declareSymbol(container.symbol.members, container.symbol, node, symbolKind, symbolExcludes);
                    break;
                case SyntaxKind.EnumDeclaration:
                    declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes);
                    break;
            }
            bindChildren(node, symbolKind);
        }

        function bindConstructorDeclaration(node: ConstructorDeclaration) {
            bindDeclaration(node, SymbolFlags.Constructor, 0);
            forEach(node.parameters, p => {
                if (p.flags & (NodeFlags.Public | NodeFlags.Private)) {
                    bindDeclaration(p, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
                }
            });
        }

        function bindModuleDeclaration(node: ModuleDeclaration) {
            if (node.name.kind === SyntaxKind.StringLiteral) {
                bindDeclaration(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
            }
            else if (isInstantiated(node)) {
                bindDeclaration(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
            }
            else {
                bindDeclaration(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes);
            }
        }

        function bindAnonymousDeclaration(node: Node, symbolKind: SymbolFlags, name: string) {
            var symbol = createSymbol(symbolKind, name);
            addDeclarationToSymbol(symbol, node, symbolKind);
            bindChildren(node, symbolKind);
        }

        function bindCatchVariableDeclaration(node: CatchBlock) {
            var symbol = createSymbol(SymbolFlags.Variable, node.variable.text || "__missing");
            addDeclarationToSymbol(symbol, node.variable, SymbolFlags.Variable);
            var saveParent = parent;
            parent = node;
            forEachChild(node, bind);
            parent = saveParent;
        }

        function bind(node: Node) {
            node.parent = parent;
            switch (node.kind) {
                case SyntaxKind.TypeParameter:
                    bindDeclaration(<Declaration>node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
                    break;
                case SyntaxKind.Parameter:
                    bindDeclaration(<Declaration>node, SymbolFlags.Variable, SymbolFlags.ParameterExcludes);
                    break;
                case SyntaxKind.VariableDeclaration:
                    bindDeclaration(<Declaration>node, SymbolFlags.Variable, SymbolFlags.VariableExcludes);
                    break;
                case SyntaxKind.Property:
                case SyntaxKind.PropertyAssignment:
                    bindDeclaration(<Declaration>node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
                    break;
                case SyntaxKind.EnumMember:
                    bindDeclaration(<Declaration>node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
                    break;
                case SyntaxKind.CallSignature:
                    bindDeclaration(<Declaration>node, SymbolFlags.CallSignature, 0);
                    break;
                case SyntaxKind.Method:
                    bindDeclaration(<Declaration>node, SymbolFlags.Method, SymbolFlags.MethodExcludes);
                    break;
                case SyntaxKind.ConstructSignature:
                    bindDeclaration(<Declaration>node, SymbolFlags.ConstructSignature, 0);
                    break;
                case SyntaxKind.IndexSignature:
                    bindDeclaration(<Declaration>node, SymbolFlags.IndexSignature, 0);
                    break;
                case SyntaxKind.FunctionDeclaration:
                    bindDeclaration(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
                    break;
                case SyntaxKind.Constructor:
                    bindConstructorDeclaration(<ConstructorDeclaration>node);
                    break;
                case SyntaxKind.GetAccessor:
                    bindDeclaration(<Declaration>node, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes);
                    break;
                case SyntaxKind.SetAccessor:
                    bindDeclaration(<Declaration>node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes);
                    break;
                case SyntaxKind.TypeLiteral:
                    bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type");
                    break;
                case SyntaxKind.ObjectLiteral:
                    bindAnonymousDeclaration(node, SymbolFlags.ObjectLiteral, "__object");
                    break;
                case SyntaxKind.FunctionExpression:
                case SyntaxKind.ArrowFunction:
                    bindAnonymousDeclaration(node, SymbolFlags.Function, "__function");
                    break;
                case SyntaxKind.CatchBlock:
                    bindCatchVariableDeclaration(<CatchBlock>node);
                    break;
                case SyntaxKind.ClassDeclaration:
                    bindDeclaration(<Declaration>node, SymbolFlags.Class, SymbolFlags.ClassExcludes);
                    break;
                case SyntaxKind.InterfaceDeclaration:
                    bindDeclaration(<Declaration>node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes);
                    break;
                case SyntaxKind.EnumDeclaration:
                    bindDeclaration(<Declaration>node, SymbolFlags.Enum, SymbolFlags.EnumExcludes);
                    break;
                case SyntaxKind.ModuleDeclaration:
                    bindModuleDeclaration(<ModuleDeclaration>node);
                    break;
                case SyntaxKind.ImportDeclaration:
                    bindDeclaration(<Declaration>node, SymbolFlags.Import, SymbolFlags.ImportExcludes);
                    break;
                case SyntaxKind.SourceFile:
                    if (isExternalModule(<SourceFile>node)) {
                        bindAnonymousDeclaration(node, SymbolFlags.ValueModule, '"' + getModuleNameFromFilename((<SourceFile>node).filename) + '"');
                        break;
                    }
                default:
                    var saveParent = parent;
                    parent = node;
                    forEachChild(node, bind);
                    parent = saveParent;
            }
        }
    }
}