text:
/* jshint es3: true */

(function(window){

    'use strict';

    var document = window.document;

    var callbacks = [];

    var url = function(endpoint, args) {
        var query = [];
        for(var key in args){
            query.push(encodeURIComponent(key) + "=" + encodeURIComponent(args[key]));
        }
        return (query.length) ? endpoint + '?' + query.join("&") : url;
    };

    var jsonp = function(endpoint, query, fn, state){
        query = query || {};
        var callback;
        var script= document.createElement('script');

        callback = function(data){
            if(state.inject){
                    data.injected = state.inject;
            }
            fn((state.raw) ? data : new Data(data));
            document.head.removeChild(script);
        };
        callbacks.push(callback);

        // default options
        query.format = 'json';
        query.jsoncallback = 'Flickr.callbacks[' + (callbacks.length -1) +']';

        script.src = url(endpoint, query);
        document.head.appendChild(script);

        return script;
    };

    var arrayUnique = function(a) {
        return a.reduce(function(p, c) {
            if (p.indexOf(c) < 0) {
                p.push(c.trim());
            }
            return p;
        }, []);
    };

    var arrayIntersect = function (a, b){
        return a.filter(function(n) {
            return b.indexOf(n) != -1;
        });
    };

    var toArray = function(tags){
        tags = tags || [];
        if(typeof tags === 'string'){
            if(tags.indexOf(',') > -1){
                tags = tags.split(',');
            }else{
                tags = tags.split(' ');
            }
        }
        return tags;
    };

    ////
    // Feed Data
    ////

    var Data = function(data){
        this.error = false;

        if(typeof data === 'string'){
            var title = /<title>(.*?)<\/title>/.exec(data);
            this.error = (title) ? title : data;
        }

        if(!this.error){
            for(var key in data){
                if(data.hasOwnProperty(key)){
                    if(key === 'items'){
                        this.items = [];
                        for(var i = 0; i < data.items.length; i++){
                            this.items.push(new DataItem(data.items[i]));
                        }
                        continue;
                    }
                    this[key] = data[key];
                }
            }
        }

    };

    Data.prototype.getUsers = function(){

        var sort = function(a, b){
            if (a.name < b.name){
                return -1;
            }
            if (a.name > b.name){
                return 1;
            }
            return 0;
        };

        var users = [];
        for(var i = 0; i < this.items.length; i++){
            users.push(this.items[i].getUser());
        }

        return users.sort(sort);
    };

    Data.prototype.getTags = function(data){
        var tags = [];
        for(var i = 0; i < this.items.length; i++){
            tags = tags.concat(this.items[i].getTags());
        }
        return arrayUnique(tags).sort();
    };

    Data.prototype.getItemsByTags = function(tags){
        var items = [];
        for(var i = 0; i < this.items.length; i++){
            //@Todo sort by occurence (hasTags returns length)
            if(this.items[i].hasTags(tags)){
                items.push(this.items[i]);
            }
        }
        return items;
    };

    ////
    // Feed Data Item
    ////

    var DataItem = function(item){
        for(var key in item){
            if(item.hasOwnProperty(key)){
                this[key] = item[key];
            }
        }
    };

    DataItem.prototype.getUser = function(){

        var regExp = /\(([^)]+)\)/;
        var matches = regExp.exec(this.author);

        return {
            id: this.author_id,
            name: (matches && matches.length > 0) ? matches[1] : this.author
        };
    };

    DataItem.prototype.getImage = function(){
        return (this.hasOwnProperty('media') && this.media.hasOwnProperty('m')) ? this.media.m : null;
    };

    DataItem.prototype.getTags = function(){
        return toArray(this.tags);
    };

    DataItem.prototype.hasTags = function(tags){
        tags = toArray(tags);
        var itemTags = this.getTags(tags);
        return arrayIntersect(tags, itemTags).length;
    };

    DataItem.prototype.getDatePublished = function(){
        return (this.hasOwnProperty('published')) ? new Date(this.published) : null;
    };

    DataItem.prototype.getDateTaken = function(){
        return (this.hasOwnProperty('date_taken')) ? new Date(this.date_taken) : null;
    };

    ////
    // Feed
    ////

    var Feed = function(id){
        this.state = {
            raw: false,
            inject: false
        };
        this.query = {};
        this.id = id;
        this.feed = null;
        this.endpoint = null;
        this.callback = function(data){};//?
        return this;
    };

    Feed.prototype.options = function(options){
        options = options || {};
        for (var key in options) {
            if(options.hasOwnProperty(key)){
                if(this.query.hasOwnProperty(key)){
                    continue;
                }
                this.query[key] = options[key];
            }
        }
    };

    Feed.prototype.register = function(feed){
        this.feed = feed;
        this.id = feed.substr(feed.lastIndexOf('/') + 1);
    };

    Feed.prototype.prepareQuery = function(){

        // copy
        var query = JSON.parse(JSON.stringify(this.query));

        // user_id
        switch(this.id){
            case 'activity.gne':
            case 'photos_friends.gne':
            case 'photos_comments.gne':
                query.user_id = query.id;
                delete(query.id);
            break;
        }

        // user ids
        if(typeof query.ids !== 'undefined'){
            query.ids = arrayUnique(query.ids).join(',');
        }

        // tags
        if(typeof query.tags !== 'undefined'){
            var tags = arrayUnique(query.tags);
            query.tags = tags.join(',');
        }

        return query;
    };

    Feed.prototype.raw = function(){
        this.state.raw = true;
        return this;
    };

    Feed.prototype.inject = function(obj){
        this.state.inject = obj;
        return this;
    };

    ///<title>(.*?)<\/title>/.exec(str)
    Feed.prototype.ready = function(fn){
        var query = this.prepareQuery();
        jsonp(this.feed, query, fn, this.state);
        return this;
    };

    // photos

    Feed.prototype.Photos = function(options){
        options = options || false;
        // public
        if(!this.id){
            this.register('https://api.flickr.com/services/feeds/photos_public.gne');
        }
        this.options(options);
        return this;
    };

    // user

    Feed.prototype.User = function(id){
        this.options({id: id});
        return this;
    };

    /**
     * User Friends feed
     * @param{bool} multiple Show multiple items for each contact
     * @param{bool} friends Show content from only friends and family, excluding contacts
     */

    Feed.prototype.Friends = function(displayMultiple, friends){
        this.options({
            display_all: displayMultiple || false,
            friends: (friends) ? 1 : 0
        });

        this.register('https://api.flickr.com/services/feeds/photos_friends.gne');
        return this;
    };

    Feed.prototype.Favourites = function(){
        this.register('https://api.flickr.com/services/feeds/photos_faves.gne');
        return this;
    };

    Feed.prototype.Activity = function(){
        this.register('https://api.flickr.com/services/feeds/activity.gne');
        return this;
    };

    Feed.prototype.Comments = function(){
        this.register('https://api.flickr.com/services/feeds/photos_comments.gne');
        return this;
    };

    // users

    Feed.prototype.Users = function(ids){
        ids = toArray(ids);
        this.options({ids: ids});
        return this;
    };

    // Group

    Feed.prototype.Group = function(id){
        id = id || [];
        this.options({id: id});
        return this;
    };

    Feed.prototype.Discussion = function(){
        this.register('https://api.flickr.com/services/feeds/groups_discuss.gne');
        return this;
    };

    Feed.prototype.Pool = function(){
        this.register('https://api.flickr.com/services/feeds/groups_pool.gne');
        return this;
    };

    // Forums

    Feed.prototype.Forums = function(){
        this.register('https://api.flickr.com/services/feeds/forums.gne');
        return this;
    };

    /**
     * Accepts a list of tags as either
     * - an array,
     * - a comma-separated string
     * - a white-pace spearated string (being item.tag feed response format)
     * @param {array|string} tags
     * @param {boolean} any sets 'tagmode' feed param ('ANY'| 'ALL'), see Flickr feedc docs
     * @returns {object} this
     */

    Feed.prototype.Tags = function(tags, all){
        tags = toArray(tags);
        all = all || false;

        this.options({
            tags: tags,
            tagmode: (all) ? 'ALL' : 'ANY'
        });
        return this;
    };

    var Flickr = {
        callbacks: callbacks,
        Feed: function(options){
            return new Feed(options);
        }
    };

    window.Flickr = Flickr;

}(window));


text:
class TaggingsController < ApplicationController
  # before_filter :find_tagger, only: [:create]

  def create
    tags = parse_tags_names( tagging_params[:tag_names])
    @taggings = []
    find_tagger.taggings.delete_all
    # delete_orphaned_tags
    # p tagging_params[:taggable_id]
    tags.each do |tag|
      tagging = Tagging.find_or_create_by(taggable_id: tagging_params[:taggable_id], taggable_type: tagging_params[:taggable_type], tag:tag)
      p tagging
      @taggings << tagging
    end
    render json: tags
  end

  def destroy
    @tagging=Tagging.find(params[:id])
    @tagging.destroy
    respond_to do |format|
      format.html{}
      format.json{ render :nothing => true}
    end
  end

  private

  def tagging_params
    params.require(:tagging).permit(:id, :tag_id, :tag_names, :taggable_id, :taggable_type)
  end

  def find_tagger
    @klass = params[:tagging][:taggable_type].capitalize.singularize.constantize
    @tagger = @klass.find(params[:tagging][:taggable_id])
  end

  # def delete_orphaned_tags
  #   find_tagger.user.tags.each do |tag|
  #     if tag.taggings.count == 0
  #       tag.destroy
  #     end
  #   end
  # end

end

redpajama_set_name: RedPajamaGithub


text:
<?php $TRANSLATIONS = array(
"Not all calendars are completely cached" => "Ikke alle kalendere er fullstendig mellomlagret",
"Everything seems to be completely cached" => "Alt ser ut til å være fullstendig mellomlagret",
"No calendars found." => "Ingen kalendere funnet",
"No events found." => "Ingen hendelser funnet",
"Wrong calendar" => "Feil kalender",
"You do not have the permissions to edit this event." => "Du har ikke tilgang til å endre denne hendelsen.",
"The file contained either no events or all events are already saved in your calendar." => "Filen innholden enten ingen hendelser eller alle hendelser er allerede lagret i din kalender.",
"events have been saved in the new calendar" => "hendelser ble lagret i den nye kalenderen",
"Import failed" => "Feil med importering",
"events have been saved in your calendar" => "hendelser ble lagret i kalenderen din",
"New Timezone:" => "Ny tidssone:",
"Timezone changed" => "Tidssone endret",
"Invalid request" => "Ugyldig forespørsel",
"Calendar" => "Kalender",
"Deletion failed" => "Sletting feilet",
"ddd d MMMM[ yyyy]{ - [ddd d] MMMM yyyy}" => "ddd d MMMM[ yyyy]{ - [ddd d] MMMM yyyy}",
"ddd d MMMM[ yyyy] HH:mm{ - [ ddd d MMMM yyyy] HH:mm}" => "ddd d MMMM[ yyyy] HH:mm{ - [ ddd d MMMM yyyy] HH:mm}",
"group" => "gruppe",
"can edit" => "kan endre",
"can share" => "kan dele",
"ddd" => "ddd",
"ddd M/d" => "ddd d.M",
"dddd M/d" => "dddd d.M",
"MMMM yyyy" => "MMMM yyyy",
"MMM d[ yyyy]{ '–'[ MMM] d yyyy}" => "d [ MMM][ yyyy]{ '–' d MMM yyyy}",
"dddd, MMM d, yyyy" => "dddd d. MMM yyyy",
"Sunday" => "Søndag",
"Monday" => "Mandag",
"Tuesday" => "Tirsdag",
"Wednesday" => "Onsdag",
"Thursday" => "Torsdag",
"Friday" => "Fredag",
"Saturday" => "Lørdag",
"Sun." => "Sø.",
"Mon." => "Ma.",
"Tue." => "Ti.",
"Wed." => "On.",
"Thu." => "To.",
"Fri." => "Fr.",
"Sat." => "Lø.",
"January" => "Januar",
"February" => "Februar",
"March" => "Mars",
"April" => "April",
"May" => "Mai",
"June" => "Juni",
"July" => "Juli",
"August" => "August",
"September" => "September",
"October" => "Oktober",
"November" => "November",
"December" => "Desember",
"Jan." => "Jan.",
"Feb." => "Feb.",
"Mar." => "Mar.",
"Apr." => "Apr.",
"May." => "Mai.",
"Jun." => "Jun.",
"Jul." => "Jul.",
"Aug." => "Aug.",
"Sep." => "Sep.",
"Oct." => "Okt.",
"Nov." => "Nov.",
"Dec." => "Des.",
"All day" => "Heldags",
"New Calendar" => "Ny kalender",
"Missing or invalid fields" => "Manglende eller ugyldig felt",
"Title" => "Tittel",
"From Date" => "Fra dato",
"From Time" => "Fra tidspunkt",
"To Date" => "Til dato",
"To Time" => "Til tidspunkt",
"The event ends before it starts" => "En hendelse kan ikke slutte før den har begynt.",
"There was a database fail" => "Det oppstod en databasefeil.",
"Interval is not valid. It must be a positive integer!" => "Ugyldig intervall. Det må være et positivt heltall!",
"Birthday" => "Bursdag",
"Business" => "Forretninger",
"Call" => "Ring",
"Clients" => "Kunder",
"Deliverer" => "Leverer",
"Holidays" => "Ferie",
"Ideas" => "Ideér",
"Journey" => "Reise",
"Jubilee" => "Jubileum",
"Meeting" => "Møte",
"Other" => "Annet",
"Personal" => "Personlig",
"Projects" => "Prosjekter",
"Questions" => "Spørsmål",
"Work" => "Arbeid",
"by" => "av",
"unnamed" => "uten navn",
"You do not have the permissions to update this calendar." => "Du har ikke tilgang til å oppdatere denne kalenderen",
"You do not have the permissions to delete this calendar." => "Du har ikke tilgang til å slette denne kalenderen",
"You do not have the permissions to add to this calendar." => "Du har ikke tilgang til å legge til noe i denne kalenderen",
"You do not have the permissions to add events to this calendar." => "Du har ikke rettigheter til å legge til hendelser i denne kalender.",
"You cannot add non-public events to a shared calendar." => "Du kan ikke legge til private hendelser i en delt kalender.",
"You do not have the permissions to delete this event." => "Du har ikke tilgang til å slette denne hendelsen.",
"Busy" => "Opptatt",
"Show full event" => "Vis hele hendelsen",
"Show only busy" => "Vis kun opptatt",
"Hide event" => "Skjul hendelse",
"Does not repeat" => "Gjentas ikke",
"Daily" => "Daglig",
"Weekly" => "Ukentlig",
"Every Weekday" => "Hver ukedag",
"Bi-Weekly" => "Annenhver uke",
"Monthly" => "Månedlig",
"Yearly" => "Årlig",
"never" => "aldri",
"by occurrences" => "etter hyppighet",
"by date" => "etter dato",
"by monthday" => "etter dag i måned",
"by weekday" => "etter ukedag",
"events week of month" => "begivenhetens uke denne måneden",
"first" => "første",
"second" => "andre",
"third" => "tredje",
"fourth" => "fjerde",
"fifth" => "femte",
"last" => "siste",
"by events date" => "etter hendelsenes dato",
"by yearday(s)" => "etter dag i året",
"by weeknumber(s)" => "etter ukenummer/-numre",
"by day and month" => "etter dag og måned",
"Contact birthdays" => "Kontakters bursdager",
"Date" => "Dato",
"Cal." => "Kal.",
"Day" => "Dag",
"Week" => "Uke",
"Month" => "Måned",
"Today" => "I dag",
"CalDav Link" => "CalDav-lenke",
"Timezone" => "Tidssone",
"Update timezone automatically" => "Oppdater tidssone automatisk",
"Time format" => "Tidsformat",
"24h" => "24 t",
"12h" => "12 t",
"Start week on" => "Start uke på",
"Cache" => "Buffer",
"Clear cache for repeating events" => "Fjern gjentagende hendelser fra mellomlager",
"Primary CalDAV address" => "Primær CalDAV-adresse",
"iOS/OS X CalDAV address" => "iOS/OS X CalDAV-adresse",
"Share Calendar" => "Del kalender",
"Download" => "Last ned",
"Edit" => "Endre",
"Delete" => "Slett",
"New calendar" => "Ny kalender",
"Edit calendar" => "Rediger kalender",
"Edit event" => "Rediger hendelse",
"Save event" => "Lagre hendelse",
"Delete event" => "Slett hendelse",
"Eventinfo" => "Hendelsesinformasjon",
"Repeating" => "Gjentas",
"Alarm" => "Alarm",
"Attendees" => "Deltakere",
"Share" => "Del",
"Title of the Event" => "Tittel for hendelsen",
"from" => "fra",
"to" => "til",
"All Day Event" => "Heldagshendelse",
"Advanced options" => "Avanserte innstillinger",
"Location" => "Sted",
"Categories (separate by comma)" => "Kategorier (skill med komma)",
"Edit categories" => "Rediger kategorier",
"Description" => "Beskrivelse",
"Export event" => "Eksporter hendelse",
"Repeat" => "Gjenta",
"Advanced" => "Avansert",
"Select weekdays" => "Velg ukedager",
"Select days" => "Velg dager",
"and the events day of year." => "og hendelsenes dag i året.",
"and the events day of month." => "og hendelsenes dag i måneden.",
"Select months" => "Velg måneder",
"Select weeks" => "Velg uker",
"and the events week of year." => "og hendelsenes uke i året.",
"Interval" => "Intervall",
"End" => "Slutt",
"occurrences" => "forekomster",
"Visibility to people shared with" => "Synlighet til andre delt med",
"create a new calendar" => "Lag en ny kalender",
"Import a calendar file" => "Importer en kalenderfil",
"Please choose a calendar" => "Vennligst velg en kalender",
"Name of new calendar" => "Navn på ny kalender:",
"Take an available name!" => "Velg et tilgjengelig navn!",
"A Calendar with this name already exists. If you continue anyhow, these calendars will be merged." => "En kalender med dette navnet finnes allerede. Hvis du velger å fortsette vil disse kalenderene bli slått sammen.",
"Remove all events from the selected calendar" => "Fjern alle hendelser fra valgt kalender",
"Import" => "Importer",
"Close Dialog" => "Lukk dialog",
"Create a new event" => "Opprett en ny hendelse",
"Create event" => "Lag hendelse",
"Share with user or group" => "Del med bruker eller gruppe",
"Unshare" => "Avslutt deling",
"Not shared with anyone" => "Ikke delt med noen",
"Send Email" => "Send e-post",
"Shared via calendar" => "Delt via kalender",
"Not shared with anyone via calendar" => "Ikke delt med noen via kalender",
"View an event" => "Se på hendelse",
"Category" => "Kategori",
"No categories selected" => "Ingen kategorier valgt",
"%s of %s" => "%s for %s",
"Access Class" => "Tilgangsklasse",
"From" => "Fra",
"at" => "på",
"To" => "Til"
);


text:
module Sipwizard
  class Configuration < Struct.new(:api_key, :connection_params); end
end


text:
package esapi

import (
	"context"
	"io"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func newSnapshotCreateRepositoryFunc(t Transport) SnapshotCreateRepository {
	return func(repository string, body io.Reader, o ...func(*SnapshotCreateRepositoryRequest)) (*Response, error) {
		var r = SnapshotCreateRepositoryRequest{Repository: repository, Body: body}
		for _, f := range o {
			f(&r)
		}
		return r.Do(r.ctx, t)
	}
}

// ----- API Definition -------------------------------------------------------

// SnapshotCreateRepository creates a repository.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html.
type SnapshotCreateRepository func(repository string, body io.Reader, o ...func(*SnapshotCreateRepositoryRequest)) (*Response, error)

// SnapshotCreateRepositoryRequest configures the Snapshot Create Repository API request.
type SnapshotCreateRepositoryRequest struct {
	Body io.Reader

	Repository string

	MasterTimeout time.Duration
	Timeout       time.Duration
	Verify        *bool

	Pretty     bool
	Human      bool
	ErrorTrace bool
	FilterPath []string

	Header http.Header

	ctx context.Context
}

// Do executes the request and returns response or error.
func (r SnapshotCreateRepositoryRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
	var (
		method string
		path   strings.Builder
		params map[string]string
	)

	method = "PUT"

	path.Grow(7 + 1 + len("_snapshot") + 1 + len(r.Repository))
	path.WriteString("http://")
	path.WriteString("/")
	path.WriteString("_snapshot")
	path.WriteString("/")
	path.WriteString(r.Repository)

	params = make(map[string]string)

	if r.MasterTimeout != 0 {
		params["master_timeout"] = formatDuration(r.MasterTimeout)
	}

	if r.Timeout != 0 {
		params["timeout"] = formatDuration(r.Timeout)
	}

	if r.Verify != nil {
		params["verify"] = strconv.FormatBool(*r.Verify)
	}

	if r.Pretty {
		params["pretty"] = "true"
	}

	if r.Human {
		params["human"] = "true"
	}

	if r.ErrorTrace {
		params["error_trace"] = "true"
	}

	if len(r.FilterPath) > 0 {
		params["filter_path"] = strings.Join(r.FilterPath, ",")
	}

	req, err := newRequest(method, path.String(), r.Body)
	if err != nil {
		return nil, err
	}

	if len(params) > 0 {
		q := req.URL.Query()
		for k, v := range params {
			q.Set(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}

	if len(r.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = r.Header
		} else {
			for k, vv := range r.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if r.Body != nil && req.Header.Get(headerContentType) == "" {
		req.Header[headerContentType] = headerContentTypeJSON
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, err
	}

	response := Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

// WithContext sets the request context.
func (f SnapshotCreateRepository) WithContext(v context.Context) func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		r.ctx = v
	}
}

// WithMasterTimeout - explicit operation timeout for connection to master node.
func (f SnapshotCreateRepository) WithMasterTimeout(v time.Duration) func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		r.MasterTimeout = v
	}
}

// WithTimeout - explicit operation timeout.
func (f SnapshotCreateRepository) WithTimeout(v time.Duration) func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		r.Timeout = v
	}
}

// WithVerify - whether to verify the repository after creation.
func (f SnapshotCreateRepository) WithVerify(v bool) func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		r.Verify = &v
	}
}

// WithPretty makes the response body pretty-printed.
func (f SnapshotCreateRepository) WithPretty() func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		r.Pretty = true
	}
}

// WithHuman makes statistical values human-readable.
func (f SnapshotCreateRepository) WithHuman() func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		r.Human = true
	}
}

// WithErrorTrace includes the stack trace for errors in the response body.
func (f SnapshotCreateRepository) WithErrorTrace() func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		r.ErrorTrace = true
	}
}

// WithFilterPath filters the properties of the response body.
func (f SnapshotCreateRepository) WithFilterPath(v ...string) func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		r.FilterPath = v
	}
}

// WithHeader adds the headers to the HTTP request.
func (f SnapshotCreateRepository) WithHeader(h map[string]string) func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		for k, v := range h {
			r.Header.Add(k, v)
		}
	}
}

// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
func (f SnapshotCreateRepository) WithOpaqueID(s string) func(*SnapshotCreateRepositoryRequest) {
	return func(r *SnapshotCreateRepositoryRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		r.Header.Set("X-Opaque-Id", s)
	}
}


text:
/*++

Module Name:

  TestNode.c

Abstract:

  This file provides the services to manage the test nodes.

  Test Node is the basic test element in the user interface of EFI SCT. It can
  be used to describe the test category information and test case information.

--*/

#include "Sct.h"
#include "ReportSupport.h"

#define EFI_SCT_SECTION_TEST_NODE           L"Test Node"

STATIC UINT32         TempIndex = 0;
STATIC UINT32         TempLevel = 0;
//
// Internal functions declaration
//
EFI_STATUS
InsertEntryListToTestNode (
  IN EFI_SCT_TEST_FILE_TYPE       Type,
  IN VOID                         *EntryList,
  OUT EFI_SCT_TEST_NODE           *RootNode
  );

EFI_STATUS
CreateSingleTestNode (
  OUT EFI_SCT_TEST_NODE           **TestNode
  );

EFI_STATUS
FreeSingleTestNode (
  IN EFI_SCT_TEST_NODE            *TestNode
  );

EFI_STATUS
AddRootTestNode (
  IN UINTN                        Index,
  IN CHAR16                       *Name,
  IN CHAR16                       *Description,
  IN EFI_GUID                     *Guid,
  IN OUT SCT_LIST_ENTRY           *TestNodeList,
  OUT EFI_SCT_TEST_NODE           **RootNode
  );

EFI_STATUS
AddTestNode (
  IN UINTN                        Index,
  IN CHAR16                       *Name,
  IN CHAR16                       *Description,
  IN EFI_SCT_TEST_NODE_TYPE       Type,
  IN EFI_GUID                     *Guid,
  IN OUT SCT_LIST_ENTRY           *TestNodeList,
  OUT EFI_SCT_TEST_NODE           **TestNode
  );

EFI_STATUS
FindTestNodeByName (
  IN CHAR16                       *Name,
  IN SCT_LIST_ENTRY               *TestNodeList,
  OUT EFI_SCT_TEST_NODE           **TestNode
  );

EFI_STATUS
SaveSingleCaseNode (
  IN EFI_INI_FILE_HANDLE          IniFile,
  IN UINT32                       Order,
  IN EFI_SCT_TEST_NODE            *TestNode,
  IN CHAR16                       *FullName
  );

EFI_STATUS
TestNodeSetString (
  IN EFI_INI_FILE_HANDLE          IniFile,
  IN UINT32                       Order,
  IN CHAR16                       *Key,
  IN CHAR16                       *Buffer
  );

EFI_STATUS
WalkThroughSave (
  IN EFI_INI_FILE_HANDLE          IniFile,
  IN SCT_LIST_ENTRY               *Root,
  IN SCT_LIST_ENTRY               *Head
  );

//
// External functions implementation
//

EFI_STATUS
CreateTestNodes (
  OUT SCT_LIST_ENTRY              *TestNodeList
  )
/*++

Routine Description:

  Create the test node list from the category list and the test file list.

Arguments:

  TestNodeList  - Pointer to the test node list.

Returns:

  EFI_SUCCESS   - Successfully.
  Other value   - Something failed.

--*/
{
  EFI_STATUS              Status;
  SCT_LIST_ENTRY          *CategoryList;
  SCT_LIST_ENTRY          *TestFileList;
  SCT_LIST_ENTRY          *Link;
  EFI_SCT_CATEGORY_DATA   *Category;
  EFI_SCT_TEST_FILE       *TestFile;
  EFI_BB_TEST_PROTOCOL    *BbTest;
  EFI_WB_TEST_PROTOCOL    *WbTest;
  EFI_AP_TEST_INTERFACE   *ApTest;
  VOID                    *EntryList;
  UINTN                   Index;
  EFI_GUID                *CategoryGuid;
  CHAR16                  *CategoryName;
  CHAR16                  *CategoryDescription;
  CHAR16                  CategoryGuidStr[EFI_SCT_GUID_LEN];
  EFI_SCT_TEST_NODE       *RootNode;

  //
  // Check parameters
  //
  if (TestNodeList == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Walk through all test files
  //
  CategoryList = &gFT->CategoryList;
  TestFileList = &gFT->TestFileList;

  for (Link = TestFileList->ForwardLink; Link != TestFileList; Link = Link->ForwardLink) {
    TestFile = CR (Link, EFI_SCT_TEST_FILE, Link, EFI_SCT_TEST_FILE_SIGNATURE);

    //
    // Deal with the different types of test files
    //
    switch (TestFile->Type) {
	case EFI_SCT_TEST_FILE_TYPE_IHV_BLACK_BOX:
    case EFI_SCT_TEST_FILE_TYPE_BLACK_BOX:
      //
      // Black-box test file
      //
      BbTest       = (EFI_BB_TEST_PROTOCOL *) TestFile->Context;
      EntryList    = BbTest->EntryList;
      CategoryGuid = &BbTest->CategoryGuid;
      break;

    case EFI_SCT_TEST_FILE_TYPE_WHITE_BOX:
      //
      // White-box test file
      //
      WbTest       = (EFI_WB_TEST_PROTOCOL *) TestFile->Context;
      EntryList    = WbTest->EntryList;
      CategoryGuid = &WbTest->CategoryGuid;
      break;

    case EFI_SCT_TEST_FILE_TYPE_APPLICATION:
    case EFI_SCT_TEST_FILE_TYPE_SCRIPT:
      //
      // Application or script test file
      //
      ApTest       = (EFI_AP_TEST_INTERFACE *) TestFile->Context;
      EntryList    = ApTest->EntryList;
      CategoryGuid = &ApTest->CategoryGuid;
      break;

    default:
      //
      // Unsupported test file
      //
      EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Unsupport test file"));
      return EFI_UNSUPPORTED;
    }

    //
    // Skip the empty entry list
    //
    if (EntryList == NULL) {
      continue;
    }

    //
    // Find the category data
    //
    Status = FindCategoryByGuid (
               CategoryGuid,
               &Category
               );
    if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
      EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Find category by GUID - %r", Status));
      continue;
    }

    if (Status == EFI_NOT_FOUND) {
      Index               = (UINTN) -1;
      SctGuidToStr (CategoryGuid, CategoryGuidStr);
      CategoryName        = SctPoolPrint (L"Unknown\\%s", CategoryGuidStr);
      CategoryDescription = SctStrDuplicate (L"");
    } else {
      Index               = Category->Index;
      CategoryName        = SctStrDuplicate (Category->Name);
      CategoryDescription = SctStrDuplicate (Category->Description);
    }

    if ((CategoryName        == NULL) ||
        (CategoryDescription == NULL)) {
      EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Output of resources"));
      continue;
    }

    //
    // Add the root test node from the category name
    //
    Status = AddRootTestNode (
               Index,
               CategoryName,
               CategoryDescription,
               CategoryGuid,
               TestNodeList,
               &RootNode
               );
    if (EFI_ERROR (Status)) {
      EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Add root test node - %r", Status));
      tBS->FreePool (CategoryName);
      tBS->FreePool (CategoryDescription);
      continue;
    }

    //
    // Insert the test entry list into the test node list
    //
    Status = InsertEntryListToTestNode (
               TestFile->Type,
               EntryList,
               RootNode
               );
    if (EFI_ERROR (Status)) {
      EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Insert entry list to test node - %r", Status));
      tBS->FreePool (CategoryName);
      tBS->FreePool (CategoryDescription);
      continue;
    }
  }

  //
  // Done
  //
  return EFI_SUCCESS;
}

EFI_STATUS
FreeTestNodes (
  IN SCT_LIST_ENTRY               *TestNodeList
  )
/*++

Routine Description:

  Free the test node list.

Arguments:

  TestNodeList  - Pointer to the test node list.

Returns:

  EFI_SUCCESS   - Successfully.
  Other value   - Something failed.

--*/
{
  EFI_SCT_TEST_NODE   *TestNode;

  //
  // Check parameters
  //
  if (TestNodeList == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Walk through all test nodes
  //
  while (!SctIsListEmpty (TestNodeList)) {
    TestNode = CR (TestNodeList->ForwardLink, EFI_SCT_TEST_NODE, Link, EFI_SCT_TEST_NODE_SIGNATURE);

    SctRemoveEntryList (&TestNode->Link);

    if (!SctIsListEmpty (&TestNode->Child)) {
      FreeTestNodes (&TestNode->Child);
    }

    FreeSingleTestNode (TestNode);
  }

  //
  // Done
  //
  return EFI_SUCCESS;
}

//
// Internal functions implementation
//

EFI_STATUS
InsertEntryListToTestNode (
  IN EFI_SCT_TEST_FILE_TYPE       Type,
  IN VOID                         *EntryList,
  OUT EFI_SCT_TEST_NODE           *RootNode
  )
/*++

Routine Description:

  Insert a entry list into the test node.

--*/
{
  EFI_STATUS          Status;
  EFI_BB_TEST_ENTRY   *BbEntry;
  EFI_WB_TEST_ENTRY   *WbEntry;
  EFI_AP_TEST_ENTRY   *ApEntry;
  EFI_SCT_TEST_NODE   *TestNode;

  //
  // Check parameters
  //
  if ((EntryList == NULL) || (RootNode == NULL)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Deal with different kinds of test files
  //
  switch (Type) {
  case EFI_SCT_TEST_FILE_TYPE_IHV_BLACK_BOX:
  case EFI_SCT_TEST_FILE_TYPE_BLACK_BOX:
    //
    // Black-box test file
    //
    BbEntry = (EFI_BB_TEST_ENTRY *) EntryList;

    while (BbEntry != NULL) {
      Status = AddTestNode (
                 (UINTN) -1,
                 BbEntry->Name,
                 BbEntry->Description,
                 EFI_SCT_TEST_NODE_TYPE_CASE,
                 &BbEntry->EntryId,
                 &RootNode->Child,
                 &TestNode
                 );
      if (EFI_ERROR (Status)) {
        EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Add test node - %r", Status));
        break;
      }

      BbEntry = BbEntry->Next;
    }

    break;

  case EFI_SCT_TEST_FILE_TYPE_WHITE_BOX:
    //
    // White-box test file
    //
    WbEntry = (EFI_WB_TEST_ENTRY *) EntryList;

    while (WbEntry != NULL) {
      Status = AddTestNode (
                 (UINTN) -1,
                 WbEntry->Name,
                 WbEntry->Description,
                 EFI_SCT_TEST_NODE_TYPE_CASE,
                 &WbEntry->EntryId,
                 &RootNode->Child,
                 &TestNode
                 );
      if (EFI_ERROR (Status)) {
        EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Add test node - %r", Status));
        break;
      }

      WbEntry = WbEntry->Next;
    }

    break;

  case EFI_SCT_TEST_FILE_TYPE_APPLICATION:
  case EFI_SCT_TEST_FILE_TYPE_SCRIPT:
    //
    // Application or script test file
    //
    ApEntry = (EFI_AP_TEST_ENTRY *) EntryList;

    while (ApEntry != NULL) {
      Status = AddTestNode (
                 (UINTN) -1,
                 ApEntry->Name,
                 ApEntry->Description,
                 EFI_SCT_TEST_NODE_TYPE_CASE,
                 &ApEntry->EntryId,
                 &RootNode->Child,
                 &TestNode
                 );
      if (EFI_ERROR (Status)) {
        EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Add test node - %r", Status));
        break;
      }

      ApEntry = ApEntry->Next;
    }

    break;

  default:
    //
    // Unsupported test file
    //
    EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Unsupported test file"));
    return EFI_UNSUPPORTED;
  }

  //
  // Done
  //
  return EFI_SUCCESS;
}

EFI_STATUS
CreateSingleTestNode (
  OUT EFI_SCT_TEST_NODE           **TestNode
  )
/*++

Routine Description:

  Create a test node.

--*/
{
  EFI_STATUS          Status;
  EFI_SCT_TEST_NODE   *TempTestNode;

  //
  // Check parameters
  //
  if (TestNode == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Allocate memory for the test node
  //
  Status = tBS->AllocatePool (
                 EfiBootServicesData,
                 sizeof(EFI_SCT_TEST_NODE),
                 (VOID **) &TempTestNode
                 );
  if (EFI_ERROR (Status)) {
    EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Allocate pool - %r", Status));
    return Status;
  }

  SctZeroMem (TempTestNode, sizeof(EFI_SCT_TEST_NODE));

  //
  // Initiailize the items of test node
  //
  TempTestNode->Signature = EFI_SCT_TEST_NODE_SIGNATURE;
  TempTestNode->Revision  = EFI_SCT_TEST_NODE_REVISION;

  SctInitializeListHead (&TempTestNode->Child);

  //
  // Done
  //
  *TestNode = TempTestNode;
  return EFI_SUCCESS;
}

EFI_STATUS
FreeSingleTestNode (
  IN EFI_SCT_TEST_NODE            *TestNode
  )
/*++

Routine Description:

  Free a test node.

--*/
{
  //
  // Check parameters
  //
  if (TestNode == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Free the items of test node
  //
  if (TestNode->Name != NULL) {
    tBS->FreePool (TestNode->Name);
    TestNode->Name = NULL;
  }

  if (TestNode->Description != NULL) {
    tBS->FreePool (TestNode->Description);
    TestNode->Description = NULL;
  }

  //
  // Free the test node itself
  //
  tBS->FreePool (TestNode);

  //
  // Done
  //
  return EFI_SUCCESS;
}

EFI_STATUS
AddRootTestNode (
  IN UINTN                        Index,
  IN CHAR16                       *Name,
  IN CHAR16                       *Description,
  IN EFI_GUID                     *Guid,
  IN OUT SCT_LIST_ENTRY           *TestNodeList,
  OUT EFI_SCT_TEST_NODE           **RootNode
  )
/*++

Routine Description:

  Add a root test node from the category name.

--*/
{
  EFI_STATUS          Status;
  BOOLEAN             IsEnd;
  CHAR16              *TempName;
  CHAR16              *Token;
  CHAR16              *End;
  SCT_LIST_ENTRY      *SubList;
  EFI_SCT_TEST_NODE   *TempRootNode;

  //
  // Check parameters
  //
  if ((Name         == NULL) || (Description == NULL) || (Guid == NULL) ||
      (TestNodeList == NULL) || (RootNode    == NULL)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Initialize
  //
  IsEnd    = FALSE;
  TempName = SctStrDuplicate (Name);
  Token    = TempName;
  End      = TempName;
  SubList  = TestNodeList;
  TempRootNode = NULL;

  //
  // Walk through all tokens in the name
  //
  while (!IsEnd) {
    //
    // Find the token
    //
    while ((*End != L'\0') && (*End != L'\\') && (*End != L'/')) {
      End ++;
    }

    if (*End == L'\0') {
      IsEnd = TRUE;
    } else {
      *End = L'\0';
      End ++;
    }

    if (SctStrLen (Token) == 0) {
      continue;
    }

    //
    // Find the test node
    //
    Status = FindTestNodeByName (Token, SubList, &TempRootNode);
    if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
      EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Find node by name - %r", Status));
      break;
    }

    if (Status == EFI_NOT_FOUND) {
      if (!IsEnd) {
        Status = AddTestNode (
                   Index,
                   Token,
                   L"",
                   EFI_SCT_TEST_NODE_TYPE_CATEGORY,
                   &gEfiNullGuid,
                   SubList,
                   &TempRootNode
                   );
      } else {
        Status = AddTestNode (
                   Index,
                   Token,
                   Description,
                   EFI_SCT_TEST_NODE_TYPE_CATEGORY,
                   Guid,
                   SubList,
                   &TempRootNode
                   );
      }

      if (EFI_ERROR (Status)) {
        EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Add test node - %r", Status));
        break;
      }
    }

    //
    // Recursive
    //
    Token   = End;
    SubList = &TempRootNode->Child;
  }

  //
  // Free resources
  //
  tBS->FreePool (TempName);

  //
  // Done
  //
  *RootNode = TempRootNode;
  return EFI_SUCCESS;
}

EFI_STATUS
AddTestNode (
  IN UINTN                        Index,
  IN CHAR16                       *Name,
  IN CHAR16                       *Description,
  IN EFI_SCT_TEST_NODE_TYPE       Type,
  IN EFI_GUID                     *Guid,
  IN OUT SCT_LIST_ENTRY           *TestNodeList,
  OUT EFI_SCT_TEST_NODE           **TestNode
  )
/*++

Routine Description:

  Add a test node.

--*/
{
  EFI_STATUS          Status;
  SCT_LIST_ENTRY      *Link;
  EFI_SCT_TEST_NODE   *Last;
  EFI_SCT_TEST_NODE   *TempTestNode;

  //
  // Check parameters
  //
  if ((Name         == NULL) || (Description == NULL) || (Guid == NULL) ||
      (TestNodeList == NULL) || (TestNode    == NULL)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Create a test node
  //
  Status = CreateSingleTestNode (&TempTestNode);
  if (EFI_ERROR (Status)) {
    EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Create a test node - %r", Status));
    return Status;
  }

  //
  // Set the items of test node
  //
  TempTestNode->Index       = Index;
  TempTestNode->Name        = SctStrDuplicate (Name);
  TempTestNode->Description = SctStrDuplicate (Description);
  TempTestNode->Type        = Type;
  SctCopyMem (&TempTestNode->Guid, Guid, sizeof(EFI_GUID));

  //
  // Add the test node into the test node list
  //
  for (Link = TestNodeList->ForwardLink; Link != TestNodeList; Link = Link->ForwardLink) {
    Last = CR (Link, EFI_SCT_TEST_NODE, Link, EFI_SCT_TEST_NODE_SIGNATURE);

    if (Last->Index > Index) {
      break;
    }

    if ((Last->Index == Index) && (SctStriCmp (Last->Name, Name) > 0)) {
      break;
    }
  }

  SctInsertTailList (Link, &TempTestNode->Link);

  //
  // Done
  //
  *TestNode = TempTestNode;
  return EFI_SUCCESS;
}

EFI_STATUS
FindTestNodeByName (
  IN CHAR16                       *Name,
  IN SCT_LIST_ENTRY               *TestNodeList,
  OUT EFI_SCT_TEST_NODE           **TestNode
  )
/*++

Routine Description:

  Seach a test node based on the name.

--*/
{
  SCT_LIST_ENTRY      *Link;
  EFI_SCT_TEST_NODE   *TempTestNode;

  //
  // Check parameters
  //
  if ((Name == NULL) || (TestNodeList == NULL) || (TestNode == NULL)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Walk through all test nodes on one layer
  //
  for (Link = TestNodeList->ForwardLink; Link != TestNodeList; Link = Link->ForwardLink) {
    TempTestNode = CR (Link, EFI_SCT_TEST_NODE, Link, EFI_SCT_TEST_NODE_SIGNATURE);

    if (SctStriCmp (TempTestNode->Name, Name) == 0) {
      //
      // Got it!
      //
      *TestNode = TempTestNode;
      return EFI_SUCCESS;
    }
  }

  //
  // Not found
  //
  return EFI_NOT_FOUND;
}

EFI_STATUS
SaveCaseTree (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePath,
  IN CHAR16                       *FileName,
  IN SCT_LIST_ENTRY               *Root
  )
/*++

Routine Description:

  Save the test case list into a file.

Arguments:

  DevicePath    - Device path of the file.
  FileName      - Name of the file.
  TestCaseList  - Pointer to the test case list.

Returns:

  EFI_SUCCESS   - Successfully.
  Other value   - Something failed.

--*/
{
  EFI_STATUS            Status;
  EFI_INI_FILE_HANDLE   IniFile;

  //
  // Check parameters
  //
  if ((DevicePath == NULL) || (FileName == NULL) || (Root == NULL)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Debug information
  //
  EFI_SCT_DEBUG ((EFI_SCT_D_TRACE, L"Save test cases into <%s>", FileName));

  //
  // Open the file
  //
  Status = gFT->TplProtocol->EfiIniOpen (
                               gFT->TplProtocol,
                               DevicePath,
                               FileName,
                               &IniFile
                               );
  if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
    EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Open test case file - %r", Status));
    return Status;
  }

  if (Status == EFI_NOT_FOUND) {
    //
    // Not exist, create the file
    //
    Status = gFT->TplProtocol->EfiIniCreate (
                                 gFT->TplProtocol,
                                 DevicePath,
                                 FileName,
                                 &IniFile
                                 );
    if (EFI_ERROR (Status)) {
      EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Create test case file - %r", Status));
      return Status;
    }
  }

  //
  // Remove the original test cases
  //
  Status = IniFile->RmSection (
                      IniFile,
                      EFI_SCT_SECTION_TEST_NODE
                      );
  if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
    EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Remove section - %r", Status));
    gFT->TplProtocol->EfiIniClose (gFT->TplProtocol, IniFile);
    return Status;
  }

  //
  // Walk through all test case nodes layer by layer
  //
  WalkThroughSave (IniFile, Root, NULL);

  //
  // Close the file
  //
  gFT->TplProtocol->EfiIniClose (
                      gFT->TplProtocol,
                      IniFile
                      );

  //
  // Done
  //
  return EFI_SUCCESS;
}

EFI_STATUS
GenerateCaseTreeFile(
  VOID
  )
{
  EFI_STATUS                       Status;
  CHAR16                           *FileName;

  Status = DoPreOperationAll ();
  if (EFI_ERROR (Status)) {
    EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Pre-operation ALL - %r", Status));
    return Status;
  }

  //
  // Prepare CaseTree file for test case sychronization with EMS
  //
  FileName = SctPoolPrint (
               L"%s\\%s",
               gFT->FilePath,
               EFI_SCT_SYNC_FILE_CASE_TREE
               );
  if (FileName == NULL) {
    EFI_ENTS_DEBUG(( EFI_ENTS_D_ERROR, L"SctPoolPrint: Out of resources"));
    return EFI_OUT_OF_RESOURCES;
  }

  //
  // Create the test nodes
  //
  Status = SaveCaseTree (
             gFT->DevicePath,
             FileName,
             &gFT->TestNodeList
             );
  if (EFI_ERROR (Status)) {
    EFI_ENTS_DEBUG(( EFI_ENTS_D_ERROR, L"Save cases tree - %r", Status));
    tBS->FreePool (FileName);
    return Status;
  }

  tBS->FreePool (FileName);
  return EFI_SUCCESS;
}

EFI_STATUS
SaveSingleCaseNode (
  IN EFI_INI_FILE_HANDLE          IniFile,
  IN UINT32                       Order,
  IN EFI_SCT_TEST_NODE            *TestNode,
  IN CHAR16                       *FullName
  )
/*++

Routine Description:

  Save a test case node.

--*/
{
  EFI_STATUS  Status;
  CHAR16      Buffer[EFI_SCT_MAX_BUFFER_SIZE];

  //
  // Check parameters
  //
  if (TestNode == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Save revision
  //
  Status = SctShortToHexStr (TestNode->Revision, Buffer);
  if (!EFI_ERROR (Status)) {
    TestNodeSetString (IniFile, Order, L"Revision", Buffer);
  }

  //
  // Save the GUID
  //
  Status = SctGuidToStr (&TestNode->Guid, Buffer);
  if (!EFI_ERROR (Status)) {
    TestNodeSetString (IniFile, Order, L"Guid", Buffer);
  }

  //
  // Save the name
  //
  TestNodeSetString (IniFile, Order, L"Name", FullName);

  //
  // Save the order
  //
  Status = SctShortToHexStr (TestNode->Type, Buffer);
  if (!EFI_ERROR (Status)) {
    TestNodeSetString (IniFile, Order, L"Type", Buffer);
  }

  //
  // Save the name
  //
  TestNodeSetString (IniFile, Order, L"Description", TestNode->Description);

  //
  // Done
  //
  return EFI_SUCCESS;
}

EFI_STATUS
TestNodeSetString (
  IN EFI_INI_FILE_HANDLE          IniFile,
  IN UINT32                       Order,
  IN CHAR16                       *Key,
  IN CHAR16                       *Buffer
  )
/*++

Routine Description:

  Set a string into the test case file.

--*/
{
  return IniFile->SetStringByOrder (
                    IniFile,
                    Order,
                    EFI_SCT_SECTION_TEST_NODE,
                    Key,
                    Buffer
                    );
}

EFI_STATUS
WalkThroughSave (
  IN EFI_INI_FILE_HANDLE          IniFile,
  IN SCT_LIST_ENTRY               *Root,
  IN SCT_LIST_ENTRY               *Head
  )
/*++

Routine Description:

  Save a test case node.

--*/
{
  EFI_STATUS            Status;
  UINT32                LoopIndex;
  EFI_SCT_TEST_NODE     *TempNode;
  SCT_LIST_ENTRY        *TempLink;
  SCT_LIST_ENTRY        *TempLink1;
  STATIC CHAR16         PathName[10][1024];
  CHAR16                TempFullName[1024];

  Status = EFI_SUCCESS;
  SctStrCpy (TempFullName, L"");

  if (Root == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  if (Head == NULL) {
    Head = Root;
  }
  TempLink = Root->ForwardLink;

  //
  // Get current node.
  //
  if (TempLink != Head) {
    TempNode = CR (TempLink, EFI_SCT_TEST_NODE, Link, EFI_SCT_TEST_NODE_SIGNATURE);

    if (TempNode->Name != NULL) {
      //
      // Record the node path
      //
      for (LoopIndex = 0; LoopIndex < TempLevel; LoopIndex++) {
        SctStrCat (TempFullName, PathName[LoopIndex]);
        SctStrCat (TempFullName, L"\\");
      }

      SctStrCat (TempFullName, TempNode->Name);

      //
      // Save a single test case node
      //
      Status = SaveSingleCaseNode (
                 IniFile,
                 TempIndex,
                 TempNode,
                 TempFullName
                 );
      if (EFI_ERROR (Status)) {
        EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"Save a test case node (#%d) - %r", TempIndex, Status));
        return Status;
      }
      TempIndex++;

      TempLink1 = &TempNode->Child;

      //
      // Recusion on vertical node (right node)
      //
      if (!SctIsListEmpty (TempLink1)){
        SctCopyMem (PathName[TempLevel], TempNode->Name, SctStrSize (TempNode->Name));
        TempLevel++;

        Status = WalkThroughSave (
                   IniFile,
                   TempLink1,
                   NULL
                   );
        if (EFI_ERROR (Status)) {
          EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"WalkThroughSave case node (#%d) - %r", TempIndex, Status));
          return Status;
        }

        TempLevel--;
      }

      //
      // Recusion on pararrel node (left node)
      //
      Status = WalkThroughSave (
                 IniFile,
                 TempLink,
                 Head
                 );
      if (EFI_ERROR (Status)) {
        EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"WalkThroughSave case node (#%d) - %r", TempIndex, Status));
        return Status;
      }
    }
  }

  return Status;
}


text:
#ifndef ERFAADDITIONSDEF
#define ERFAADDITIONSDEF

/*
**  - - - - - - - - - - - - - - - - -
**   e r f a _ a d d i t i o n s . h
**  - - - - - - - - - - - - - - - - -
**
**  A few extra routines which are particularly handy for constructing
**  pv vectors inside the coordinate transforms.
**
**  MHvK proposed these to Catherine Hohenkerk for inclusion in SOFA
**  on 2018-05-24, with the response suggesting this was reasonable and
**  might thus be done.
*/

/* Extra/PVMergeExtract */
void eraPav2pv(double p[3], double v[3], double pv[2][3]);
void eraPv2pav(double pv[2][3], double p[3], double v[3]);

#endif


text:
package com.xeoh.android.texthighlighter;

import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;

public class TextHighlighter {
  private ForegroundColorSpan fgColor;
  private BackgroundColorSpan bgColor;
  private boolean bold = false;
  private boolean italic = false;
  private ArrayList<TextView> textViews = new ArrayList<>();
  private String highlightedText = null;

  /**
   * Its method will be called to find position of highlighting text.
   */
  public interface Matcher {
    /**
     * Implement algorithm to find matching indices.
     *
     * <p> getMatchIndices("Hello world! We are the world". "world") should return [7,14]
     *
     * @param origin whole text
     * @param keyword word you want to highlight
     * @return matching indies
     */
    ArrayList<Integer> getMatchIndices(String origin, String keyword);

    /**
     * Implement algorithm to detecting any matching word exist.
     *
     * @param origin whole text
     * @param keyword word you want to highlight
     * @return true for if any text matches, otherwise false
     */
    boolean isHighlightable(String origin, String keyword);
  }

  /**
   * Simple Matcher which finds exactly same word.
   */
  public static final Matcher BASE_MATCHER = new Matcher() {
    @Override
    public ArrayList<Integer> getMatchIndices(String origin, String keyword) {
      ArrayList<Integer> indices = new ArrayList<>();

      int index = origin.indexOf(keyword, 0);
      while (index != -1) {
        indices.add(index);
        index = origin.indexOf(keyword, index + 1);
      }

      return indices;
    }

    @Override
    public boolean isHighlightable(String origin, String keyword) {
      return getMatchIndices(origin, keyword).size() > 0;
    }
  };

  /**
   * Case insensitive Matcher which finds exactly same word but ignore case.
   */
  public static final Matcher CASE_INSENSITIVE_MATCHER = new Matcher() {
    @Override
    public ArrayList<Integer> getMatchIndices(String origin, String keyword) {
      ArrayList<Integer> indices = new ArrayList<>();

      origin = origin.toLowerCase();
      keyword = keyword.toLowerCase();

      int index = origin.indexOf(keyword, 0);
      while (index != -1) {
        indices.add(index);
        index = origin.indexOf(keyword, index + 1);
      }

      return indices;
    }

    @Override
    public boolean isHighlightable(String origin, String keyword) {
      return getMatchIndices(origin, keyword).size() > 0;
    }
  };

  /**
   * Set foreground color of highlighted text.
   *
   * @param color color of foreground.
   * @return itself
   */
  public TextHighlighter setForegroundColor(int color) {
    fgColor = new ForegroundColorSpan(color);
    return this;
  }

  /**
   * Reset foreground color of highlighted text.
   *
   * @return itself
   */
  public TextHighlighter resetForegroundColor() {
    fgColor = null;
    return this;
  }

  /**
   * Set background color of highlighted text.
   *
   * @param color color of background
   * @return itself
   */
  public TextHighlighter setBackgroundColor(int color) {
    bgColor = new BackgroundColorSpan(color);
    return this;
  }

  /**
   * Reset background color of highlighted text.
   *
   * @return itself
   */
  public TextHighlighter resetBackgroundColor() {
    bgColor = null;
    return this;
  }

  /**
   * Set bold typeface to highlighted text.
   *
   * @param bold bold or not
   * @return itself
   */
  public TextHighlighter setBold(boolean bold) {
    this.bold = bold;
    return this;
  }

  /**
   * Set italic typeface to highlighted text.
   *
   * @param italic bold or not
   * @return itself
   */
  public TextHighlighter setItalic(boolean italic) {
    this.italic = italic;
    return this;
  }

  /**
   * Add single TextView as target of current TextHighlighter.
   *
   * <p> It sets target view only if view is instance of TextView.
   *
   * @param view target View
   * @return itself
   */
  public TextHighlighter addTarget(View view) {
    if (view instanceof TextView && !textViews.contains(view)) {
      textViews.add((TextView) view);
    }
    return this;
  }

  /**
   * Remove all targeted TextView.
   */
  public void resetTargets() {
    this.textViews = new ArrayList<>();
  }

  /**
   * Perform highlight action for targeted views.
   *
   * @param keyword word you want to highlight
   * @param matcher {@link Matcher} for finding position of highlighted text
   */
  public void highlight(String keyword, Matcher matcher) {
    this.highlightedText = keyword;

    if (keyword == null || keyword.isEmpty()) {
      reset();
      return;
    }

    for (TextView textView : textViews) {
      highlightTextView(textView, keyword, matcher);
    }
  }

  /**
   * Re-Highlight words in given targets.
   *
   * @param matcher {@link Matcher} for finding position of highlighted text
   */
  public void invalidate(Matcher matcher) {
    highlight(highlightedText, matcher);
  }

  private Spannable getHighlightedText(String origin, String keyword,
                                       ArrayList<Integer> indices) {
    return getHighlightedText(new SpannableString(origin), keyword, indices);
  }

  private Spannable getHighlightedText(Spannable origin, String keyword,
                                       ArrayList<Integer> indices) {
    Spannable spannable = new SpannableString(origin.toString());

    boolean noop = origin.toString().isEmpty()
        || (fgColor == null && bgColor == null && !bold && !italic);

    if (noop) {
      return spannable;
    }

    for (int index = 0; index < origin.toString().length(); index++) {
      for (CharacterStyle style : origin.getSpans(index, index + 1, CharacterStyle.class)) {
        if (!(style instanceof StyleSpan)) {
          spannable.setSpan(CharacterStyle.wrap(style), index, index + 1, 0);
        }
      }
    }

    for (int index : indices) {
      if (fgColor != null) {
        spannable.setSpan(CharacterStyle.wrap(fgColor), index, index + keyword.length(), 0);
      }

      if (bgColor != null) {
        spannable.setSpan(CharacterStyle.wrap(bgColor), index, index + keyword.length(), 0);
      }

      if (!bold && !italic) {
        spannable.setSpan(new StyleSpan(Typeface.NORMAL), index, index + keyword.length(), 0);
      } else if (bold && !italic) {
        spannable.setSpan(new StyleSpan(Typeface.BOLD), index, index + keyword.length(), 0);
      } else if (!bold && italic) {
        spannable.setSpan(new StyleSpan(Typeface.ITALIC), index, index + keyword.length(), 0);
      } else {
        spannable.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), index, index + keyword.length(), 0);
      }
    }

    return spannable;
  }

  private void highlightTextView(TextView textView, String keyword, Matcher matcher) {
    if (textView == null) {
      return;
    }

    ArrayList<Integer> indices = matcher.getMatchIndices(textView.getText().toString(), keyword);

    textView.setText(getHighlightedText(textView.getText().toString(), keyword, indices),
        TextView.BufferType.SPANNABLE);
  }

  private void resetTextView(TextView textView) {
    if (textView != null) {
      textView.setText(textView.getText().toString());
    }
  }

  private void reset() {
    for (TextView textView : textViews) {
      resetTextView(textView);
    }
  }
}


text:
'''
'''
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import ports

Test.Summary = '''
Ensure that handshake fails if invalid alpn string is offered
'''

# Only later versions of openssl support the `-alpn` option.
Test.SkipUnless(Condition.HasOpenSSLVersion('1.1.1'))

# Define default ATS
ts = Test.MakeATSProcess("ts", select_ports=True, enable_tls=True)

# add ssl materials like key, certificates for the server
ts.addSSLfile("ssl/server.pem")
ts.addSSLfile("ssl/server.key")

# Make sure the TS server certs are different from the origin certs
ts.Disk.ssl_multicert_config.AddLine(
    'dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key'
)

# Case 1, global config policy=permissive properties=signature
#         override for foo.com policy=enforced properties=all
ts.Disk.records_config.update({
    'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir),
})

tr = Test.AddTestRun("alpn banana")
tr.Processes.Default.Command = "openssl s_client -ign_eof -alpn=banana -connect 127.0.0.1:{}".format(ts.Variables.ssl_port)
tr.ReturnCode = 1  # Should fail
tr.Processes.Default.StartBefore(Test.Processes.ts)
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.All += Testers.IncludesExpression("No ALPN negotiated", "Banana should not match a negotiation")

tr = Test.AddTestRun("alpn http/1.1")
tr.Processes.Default.Command = "printf 'GET / HTTP/1.1\r\n\r\n' | openssl s_client -ign_eof -alpn=http/1.1 -connect 127.0.0.1:{}".format(
    ts.Variables.ssl_port)
tr.ReturnCode = 0
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.All += Testers.IncludesExpression("ALPN protocol: http/1.1", "Successful ALPN")
tr.Processes.Default.Streams.All += Testers.IncludesExpression("HTTP/1.1 400 Host Header Required", "Processed the request")

tr = Test.AddTestRun("no alpn")
tr.Processes.Default.Command = "printf 'GET / HTTP/1.1\r\n\r\n' | openssl s_client -ign_eof -connect 127.0.0.1:{}".format(
    ts.Variables.ssl_port)
tr.ReturnCode = 0
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.All += Testers.IncludesExpression("No ALPN negotiated", "No ALPN offered, none negotiated")
tr.Processes.Default.Streams.All += Testers.IncludesExpression("HTTP/1.1 400 Host Header Required", "Processed the request")

tr = Test.AddTestRun("alpn h2")
tr.Processes.Default.Command = "curl -k --http2 -v -o /dev/null https://127.0.0.1:{}".format(ts.Variables.ssl_port)
tr.ReturnCode = 0
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.All += Testers.IncludesExpression("ALPN, server accepted to use h2", "negotiated h2")
tr.Processes.Default.Streams.All += Testers.IncludesExpression("HTTP/2 404 ", "Good response")


text:
object repro {
  import scala.reflect.ClassTag

  trait +[L, R]

  case class Atomic[V](val name: String)
  object Atomic {
    def apply[V](implicit vtt: ClassTag[V]): Atomic[V] = Atomic[V](vtt.toString)
  }

  case class Assign[V, X](val name: String)
  object Assign {
    def apply[V, X](implicit vtt: ClassTag[V]): Assign[V, X] = Assign[V, X](vtt.toString)
  }

  trait AsString[X] {
    def str: String
  }
  object AsString {
    implicit def atomic[V](implicit a: Atomic[V]): AsString[V] =
      new AsString[V] { val str = a.name }
    implicit def assign[V, X](implicit a: Assign[V, X], asx: AsString[X]): AsString[V] =
      new AsString[V] { val str = asx.str }
    implicit def plus[L, R](implicit asl: AsString[L], asr: AsString[R]): AsString[+[L, R]] =
      new AsString[+[L, R]] { val str = s"(${asl.str}) + (${asr.str})" }
  }

  trait X
  implicit val declareX: Atomic[X] = Atomic[X]
  trait Y
  implicit val declareY: Atomic[Y] = Atomic[Y]
  trait Z
  implicit val declareZ: Atomic[Z] = Atomic[Z]

  trait Q
  implicit val declareQ: Assign[Q, (X + Y) + Z] = Assign[Q, (X + Y) + Z]
  trait R
  implicit val declareR: Assign[R, Q + Z] = Assign[R, Q + Z]

  implicitly[AsString[X]]
  implicitly[AsString[X + Y]]
  implicitly[AsString[Q]]
  implicitly[AsString[R]]
}


text:
@interface TestViewController ()

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(20, 60, self.view.bounds.size.width - 40, 40);
    [button setTitle:@"Back" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    button.center = self.view.center;
    [self.view addSubview:button];
}

- (void)buttonClick:(UIButton *)button {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
ACCEPTED

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

#### Published in
Entoloma s. l. (Saronno), Fungi Europaei vol. <b>5a</b> 857 (2004)

#### Original name
Entoloma roseoalbum Arnolds & Noordel., 2004

### Remarks
null


text:
package org.fcrepo.server.journal.recoverylog;

import java.io.IOException;
import java.io.Writer;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import org.fcrepo.server.MultiValueMap;
import org.fcrepo.server.errors.ModuleInitializationException;
import org.fcrepo.server.journal.JournalConstants;
import org.fcrepo.server.journal.JournalException;
import org.fcrepo.server.journal.ServerInterface;
import org.fcrepo.server.journal.entry.ConsumerJournalEntry;
import org.fcrepo.server.journal.entry.JournalEntryContext;
import org.fcrepo.server.journal.helpers.JournalHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The abstract base for all JournalRecoveryLog classes.
 *
 * @author Jim Blake
 */
public abstract class JournalRecoveryLog
        implements JournalConstants {

    private static final Logger logger =
            LoggerFactory.getLogger(JournalRecoveryLog.class);

    private static final int LEVEL_LOW = 0;

    private static final int LEVEL_MEDIUM = 1;

    private static final int LEVEL_HIGH = 2;

    protected final ServerInterface server;

    private final int logLevel;

    /**
     * Create an instance of the proper JournalRecoveryLog child class, as
     * determined by the server parameters.
     */
    public static JournalRecoveryLog getInstance(Map<String, String> parameters,
                                                 String role,
                                                 ServerInterface server)
            throws ModuleInitializationException {

        try {
            Object recoveryLog =
                    JournalHelper
                            .createInstanceAccordingToParameter(PARAMETER_JOURNAL_RECOVERY_LOG_CLASSNAME,
                                                                new Class[] {
                                                                        Map.class,
                                                                        String.class,
                                                                        ServerInterface.class},
                                                                new Object[] {
                                                                        parameters,
                                                                        role,
                                                                        server},
                                                                parameters);
            logger.info("JournalRecoveryLog is " + recoveryLog.toString());
            return (JournalRecoveryLog) recoveryLog;
        } catch (JournalException e) {
            throw new ModuleInitializationException("Can't create JournalRecoveryLog",
                                                    role,
                                                    e);
        }
    }

    /**
     * Concrete sub-classes must implement this constructor. Checks the server
     * parameters to find out what Logging Level to use - default is Low.
     */
    protected JournalRecoveryLog(Map<String, String> parameters,
                                 String role,
                                 ServerInterface server)
            throws ModuleInitializationException {
        this.server = server;

        String level = parameters.get(PARAMETER_RECOVERY_LOG_LEVEL);
        if (level == null) {
            logLevel = LEVEL_LOW;
        } else if (VALUE_RECOVERY_LOG_LEVEL_HIGH.equals(level)) {
            logLevel = LEVEL_HIGH;
        } else if (VALUE_RECOVERY_LOG_LEVEL_MEDIUM.equals(level)) {
            logLevel = LEVEL_MEDIUM;
        } else if (VALUE_RECOVERY_LOG_LEVEL_LOW.equals(level)) {
            logLevel = LEVEL_LOW;
        } else {
            throw new ModuleInitializationException("'"
                    + PARAMETER_RECOVERY_LOG_LEVEL + "' parameter must be '"
                    + VALUE_RECOVERY_LOG_LEVEL_LOW + "'(default), '"
                    + VALUE_RECOVERY_LOG_LEVEL_MEDIUM + "' or '"
                    + VALUE_RECOVERY_LOG_LEVEL_HIGH + "'", role);
        }
    }

    /**
     * Concrete sub-classes should probably synchronize this method, since it
     * can be called either from the JournalConsumerThread or from the Server.
     */
    public abstract void log(String message);

    /**
     * Concrete sub-classes should probably synchronize this method, since it
     * can be called either from the JournalConsumerThread or from the Server.
     * For the same reason, they should also provide for the possibility that it
     * will be called multiple times, or that a call to log() will happen after
     * the call to shutdown().
     */
    public abstract void shutdown();

    public void shutdown(String message) {
        log(message);
        shutdown();
    }

    /**
     * Concrete sub-classes should call this method from their constructor, or
     * as soon as the log is ready for writing.
     */
    public void logHeaderInfo(Map<String, String> parameters) {
        StringBuffer buffer = new StringBuffer("Recovery parameters:");
        for (Iterator<String> keys = parameters.keySet().iterator(); keys
                .hasNext();) {
            Object key = keys.next();
            Object value = parameters.get(key);
            buffer.append("\n    ").append(key).append("=").append(value);
        }
        log(buffer.toString());
    }

    /**
     * Format a journal entry for writing to the logger. Take logging level into
     * account.
     */
    public void log(ConsumerJournalEntry journalEntry) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("Event: method='").append(journalEntry.getMethodName())
                .append("', ").append(journalEntry.getIdentifier())
                .append("\n");
        if (logLevel == LEVEL_HIGH) {
            JournalEntryContext context = journalEntry.getContext();
            buffer.append("    context=").append(context.getClass().getName())
                    .append("\n");
            buffer.append(writeMapValues("environmentAttributes", context
                    .getEnvironmentAttributes()));
            buffer.append(writeMapValues("subjectAttributes", context
                    .getSubjectAttributes()));
            buffer.append(writeMapValues("actionAttributes", context
                    .getActionAttributes()));
            buffer.append(writeMapValues("resourceAttributes", context
                    .getResourceAttributes()));
            buffer.append(writeMapValues("recoveryAttributes", context
                    .getRecoveryAttributes()));
            buffer.append("        password='*********'\n");
            buffer.append("        noOp=").append(context.getNoOp())
                    .append("\n");
        }
        if (logLevel == LEVEL_HIGH || logLevel == LEVEL_MEDIUM) {
            buffer.append("        now=" + journalEntry.getContext().getNoOp()
                    + "\n");
            buffer.append("    arguments\n");
            Map argumentsMap = journalEntry.getArgumentsMap();
            for (Iterator names = argumentsMap.keySet().iterator(); names
                    .hasNext();) {
                String name = (String) names.next();
                Object value = argumentsMap.get(name);
                if (value instanceof String[]) {
                    buffer.append(writeStringArray(name, (String[]) value));
                } else {
                    buffer.append("        " + name + "='" + value + "'\n");
                }
            }
        }
        log(buffer.toString());
    }

    /**
     * Helper for the {@link #log(ConsumerJournalEntry)} method. Writes the
     * values of a string array
     */
    private String writeStringArray(String name, String[] values) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("        ").append(name).append("=[");
        for (int i = 0; i < values.length; i++) {
            buffer.append("'").append(values[i]).append("'");
            if (i < values.length - 1) {
                buffer.append(", ");
            }
        }
        buffer.append("]\n");
        return buffer.toString();
    }

    /**
     * Helper for the {@link #log(ConsumerJournalEntry)} method. Writes the
     * values of a context multi-map.
     */
    private String writeMapValues(String mapName, MultiValueMap map) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("        " + mapName + "\n");
        for (Iterator names = map.names(); names.hasNext();) {
            String name = (String) names.next();
            buffer.append("            ").append(name).append("\n");
            String[] values = map.getStringArray(name);
            for (String element : values) {
                buffer.append("                ").append(element).append("\n");
            }
        }
        return buffer.toString();
    }

    /**
     * Concrete sub-classes call this method to perform the final formatting if
     * a log entry.
     */
    protected void log(String message, Writer writer) {
        try {
            writer.write(JournalHelper.formatDate(new Date()) + ": " + message
                    + "\n");
        } catch (IOException e) {
            logger.error("Error writing journal log entry", e);
        }
    }

}


text:
@class UIViewController;
@protocol TLSearchResultControllerProtocol <UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate>

- (void)setItemClickAction:(void (^)(__kindof UIViewController *searchResultVC, id data))itemClickAction;

@end


text:
module Kernel

  module_function

  # Very simple convenience method to get a console reply.
  #
  #   ask "Are you happy?", "Yn"
  #
  # On the command line one would see.
  #
  #   $ Are you happy? [Yn]
  #
  # Responding:
  #
  #   $ Are you happy? [Yn] Y <ENTER>
  #
  # The ask method would return "Y".

  def ask(question, answers=nil)
    $stdout << "#{question}"
    $stdout << " [#{answers}] " if answers
    until inp = $stdin.gets ; sleep 1 ; end
    inp.strip
  end

end


text:
export declare class UserCardModel {
    title1: string;
    title2: string;
    backgroundUrl: string;
    avatarUrl: string;
}


text:
<?php

class CssConvertLevel3PropertiesMinifierFilter extends aCssMinifierFilter
	{
	/**
	 * Css property transformations table. Used to convert CSS3 and proprietary properties to the browser-specific
	 * counterparts.
	 *
	 * @var array
	 */
	private $transformations = array
		(
		// Property						Array(Mozilla, Webkit, Opera, Internet Explorer); NULL values are placeholders and will get ignored
		"animation"						=> array(null, "-webkit-animation", null, null),
		"animation-delay"				=> array(null, "-webkit-animation-delay", null, null),
		"animation-direction" 			=> array(null, "-webkit-animation-direction", null, null),
		"animation-duration"			=> array(null, "-webkit-animation-duration", null, null),
		"animation-fill-mode"			=> array(null, "-webkit-animation-fill-mode", null, null),
		"animation-iteration-count"		=> array(null, "-webkit-animation-iteration-count", null, null),
		"animation-name"				=> array(null, "-webkit-animation-name", null, null),
		"animation-play-state"			=> array(null, "-webkit-animation-play-state", null, null),
		"animation-timing-function"		=> array(null, "-webkit-animation-timing-function", null, null),
		"appearance"					=> array("-moz-appearance", "-webkit-appearance", null, null),
		"backface-visibility"			=> array(null, "-webkit-backface-visibility", null, null),
		"background-clip"				=> array(null, "-webkit-background-clip", null, null),
		"background-composite"			=> array(null, "-webkit-background-composite", null, null),
		"background-inline-policy"		=> array("-moz-background-inline-policy", null, null, null),
		"background-origin"				=> array(null, "-webkit-background-origin", null, null),
		"background-position-x"			=> array(null, null, null, "-ms-background-position-x"),
		"background-position-y"			=> array(null, null, null, "-ms-background-position-y"),
		"background-size"				=> array(null, "-webkit-background-size", null, null),
		"behavior"						=> array(null, null, null, "-ms-behavior"),
		"binding"						=> array("-moz-binding", null, null, null),
		"border-after"					=> array(null, "-webkit-border-after", null, null),
		"border-after-color"			=> array(null, "-webkit-border-after-color", null, null),
		"border-after-style"			=> array(null, "-webkit-border-after-style", null, null),
		"border-after-width"			=> array(null, "-webkit-border-after-width", null, null),
		"border-before"					=> array(null, "-webkit-border-before", null, null),
		"border-before-color"			=> array(null, "-webkit-border-before-color", null, null),
		"border-before-style"			=> array(null, "-webkit-border-before-style", null, null),
		"border-before-width"			=> array(null, "-webkit-border-before-width", null, null),
		"border-border-bottom-colors"	=> array("-moz-border-bottom-colors", null, null, null),
		"border-bottom-left-radius"		=> array("-moz-border-radius-bottomleft", "-webkit-border-bottom-left-radius", null, null),
		"border-bottom-right-radius"	=> array("-moz-border-radius-bottomright", "-webkit-border-bottom-right-radius", null, null),
		"border-end"					=> array("-moz-border-end", "-webkit-border-end", null, null),
		"border-end-color"				=> array("-moz-border-end-color", "-webkit-border-end-color", null, null),
		"border-end-style"				=> array("-moz-border-end-style", "-webkit-border-end-style", null, null),
		"border-end-width"				=> array("-moz-border-end-width", "-webkit-border-end-width", null, null),
		"border-fit"					=> array(null, "-webkit-border-fit", null, null),
		"border-horizontal-spacing"		=> array(null, "-webkit-border-horizontal-spacing", null, null),
		"border-image"					=> array("-moz-border-image", "-webkit-border-image", null, null),
		"border-left-colors"			=> array("-moz-border-left-colors", null, null, null),
		"border-radius"					=> array("-moz-border-radius", "-webkit-border-radius", null, null),
		"border-border-right-colors"	=> array("-moz-border-right-colors", null, null, null),
		"border-start"					=> array("-moz-border-start", "-webkit-border-start", null, null),
		"border-start-color"			=> array("-moz-border-start-color", "-webkit-border-start-color", null, null),
		"border-start-style"			=> array("-moz-border-start-style", "-webkit-border-start-style", null, null),
		"border-start-width"			=> array("-moz-border-start-width", "-webkit-border-start-width", null, null),
		"border-top-colors"				=> array("-moz-border-top-colors", null, null, null),
		"border-top-left-radius"		=> array("-moz-border-radius-topleft", "-webkit-border-top-left-radius", null, null),
		"border-top-right-radius"		=> array("-moz-border-radius-topright", "-webkit-border-top-right-radius", null, null),
		"border-vertical-spacing"		=> array(null, "-webkit-border-vertical-spacing", null, null),
		"box-align"						=> array("-moz-box-align", "-webkit-box-align", null, null),
		"box-direction"					=> array("-moz-box-direction", "-webkit-box-direction", null, null),
		"box-flex"						=> array("-moz-box-flex", "-webkit-box-flex", null, null),
		"box-flex-group"				=> array(null, "-webkit-box-flex-group", null, null),
		"box-flex-lines"				=> array(null, "-webkit-box-flex-lines", null, null),
		"box-ordinal-group"				=> array("-moz-box-ordinal-group", "-webkit-box-ordinal-group", null, null),
		"box-orient"					=> array("-moz-box-orient", "-webkit-box-orient", null, null),
		"box-pack"						=> array("-moz-box-pack", "-webkit-box-pack", null, null),
		"box-reflect"					=> array(null, "-webkit-box-reflect", null, null),
		"box-shadow"					=> array("-moz-box-shadow", "-webkit-box-shadow", null, null),
		"box-sizing"					=> array("-moz-box-sizing", null, null, null),
		"color-correction"				=> array(null, "-webkit-color-correction", null, null),
		"column-break-after"			=> array(null, "-webkit-column-break-after", null, null),
		"column-break-before"			=> array(null, "-webkit-column-break-before", null, null),
		"column-break-inside"			=> array(null, "-webkit-column-break-inside", null, null),
		"column-count"					=> array("-moz-column-count", "-webkit-column-count", null, null),
		"column-gap"					=> array("-moz-column-gap", "-webkit-column-gap", null, null),
		"column-rule"					=> array("-moz-column-rule", "-webkit-column-rule", null, null),
		"column-rule-color"				=> array("-moz-column-rule-color", "-webkit-column-rule-color", null, null),
		"column-rule-style"				=> array("-moz-column-rule-style", "-webkit-column-rule-style", null, null),
		"column-rule-width"				=> array("-moz-column-rule-width", "-webkit-column-rule-width", null, null),
		"column-span"					=> array(null, "-webkit-column-span", null, null),
		"column-width"					=> array("-moz-column-width", "-webkit-column-width", null, null),
		"columns"						=> array(null, "-webkit-columns", null, null),
		"filter"						=> array(__CLASS__, "filter"),
		"float-edge"					=> array("-moz-float-edge", null, null, null),
		"font-feature-settings"			=> array("-moz-font-feature-settings", null, null, null),
		"font-language-override"		=> array("-moz-font-language-override", null, null, null),
		"font-size-delta"				=> array(null, "-webkit-font-size-delta", null, null),
		"font-smoothing"				=> array(null, "-webkit-font-smoothing", null, null),
		"force-broken-image-icon"		=> array("-moz-force-broken-image-icon", null, null, null),
		"highlight"						=> array(null, "-webkit-highlight", null, null),
		"hyphenate-character"			=> array(null, "-webkit-hyphenate-character", null, null),
		"hyphenate-locale"				=> array(null, "-webkit-hyphenate-locale", null, null),
		"hyphens"						=> array(null, "-webkit-hyphens", null, null),
		"force-broken-image-icon"		=> array("-moz-image-region", null, null, null),
		"ime-mode"						=> array(null, null, null, "-ms-ime-mode"),
		"interpolation-mode"			=> array(null, null, null, "-ms-interpolation-mode"),
		"layout-flow"					=> array(null, null, null, "-ms-layout-flow"),
		"layout-grid"					=> array(null, null, null, "-ms-layout-grid"),
		"layout-grid-char"				=> array(null, null, null, "-ms-layout-grid-char"),
		"layout-grid-line"				=> array(null, null, null, "-ms-layout-grid-line"),
		"layout-grid-mode"				=> array(null, null, null, "-ms-layout-grid-mode"),
		"layout-grid-type"				=> array(null, null, null, "-ms-layout-grid-type"),
		"line-break"					=> array(null, "-webkit-line-break", null, "-ms-line-break"),
		"line-clamp"					=> array(null, "-webkit-line-clamp", null, null),
		"line-grid-mode"				=> array(null, null, null, "-ms-line-grid-mode"),
		"logical-height"				=> array(null, "-webkit-logical-height", null, null),
		"logical-width"					=> array(null, "-webkit-logical-width", null, null),
		"margin-after"					=> array(null, "-webkit-margin-after", null, null),
		"margin-after-collapse"			=> array(null, "-webkit-margin-after-collapse", null, null),
		"margin-before"					=> array(null, "-webkit-margin-before", null, null),
		"margin-before-collapse"		=> array(null, "-webkit-margin-before-collapse", null, null),
		"margin-bottom-collapse"		=> array(null, "-webkit-margin-bottom-collapse", null, null),
		"margin-collapse"				=> array(null, "-webkit-margin-collapse", null, null),
		"margin-end"					=> array("-moz-margin-end", "-webkit-margin-end", null, null),
		"margin-start"					=> array("-moz-margin-start", "-webkit-margin-start", null, null),
		"margin-top-collapse"			=> array(null, "-webkit-margin-top-collapse", null, null),
		"marquee "						=> array(null, "-webkit-marquee", null, null),
		"marquee-direction"				=> array(null, "-webkit-marquee-direction", null, null),
		"marquee-increment"				=> array(null, "-webkit-marquee-increment", null, null),
		"marquee-repetition"			=> array(null, "-webkit-marquee-repetition", null, null),
		"marquee-speed"					=> array(null, "-webkit-marquee-speed", null, null),
		"marquee-style"					=> array(null, "-webkit-marquee-style", null, null),
		"mask"							=> array(null, "-webkit-mask", null, null),
		"mask-attachment"				=> array(null, "-webkit-mask-attachment", null, null),
		"mask-box-image"				=> array(null, "-webkit-mask-box-image", null, null),
		"mask-clip"						=> array(null, "-webkit-mask-clip", null, null),
		"mask-composite"				=> array(null, "-webkit-mask-composite", null, null),
		"mask-image"					=> array(null, "-webkit-mask-image", null, null),
		"mask-origin"					=> array(null, "-webkit-mask-origin", null, null),
		"mask-position"					=> array(null, "-webkit-mask-position", null, null),
		"mask-position-x"				=> array(null, "-webkit-mask-position-x", null, null),
		"mask-position-y"				=> array(null, "-webkit-mask-position-y", null, null),
		"mask-repeat"					=> array(null, "-webkit-mask-repeat", null, null),
		"mask-repeat-x"					=> array(null, "-webkit-mask-repeat-x", null, null),
		"mask-repeat-y"					=> array(null, "-webkit-mask-repeat-y", null, null),
		"mask-size"						=> array(null, "-webkit-mask-size", null, null),
		"match-nearest-mail-blockquote-color" => array(null, "-webkit-match-nearest-mail-blockquote-color", null, null),
		"max-logical-height"			=> array(null, "-webkit-max-logical-height", null, null),
		"max-logical-width"				=> array(null, "-webkit-max-logical-width", null, null),
		"min-logical-height"			=> array(null, "-webkit-min-logical-height", null, null),
		"min-logical-width"				=> array(null, "-webkit-min-logical-width", null, null),
		"object-fit"					=> array(null, null, "-o-object-fit", null),
		"object-position"				=> array(null, null, "-o-object-position", null),
		"opacity"						=> array(__CLASS__, "opacity"),
		"outline-radius"				=> array("-moz-outline-radius", null, null, null),
		"outline-bottom-left-radius"	=> array("-moz-outline-radius-bottomleft", null, null, null),
		"outline-bottom-right-radius"	=> array("-moz-outline-radius-bottomright", null, null, null),
		"outline-top-left-radius"		=> array("-moz-outline-radius-topleft", null, null, null),
		"outline-top-right-radius"		=> array("-moz-outline-radius-topright", null, null, null),
		"padding-after"					=> array(null, "-webkit-padding-after", null, null),
		"padding-before"				=> array(null, "-webkit-padding-before", null, null),
		"padding-end"					=> array("-moz-padding-end", "-webkit-padding-end", null, null),
		"padding-start"					=> array("-moz-padding-start", "-webkit-padding-start", null, null),
		"perspective"					=> array(null, "-webkit-perspective", null, null),
		"perspective-origin"			=> array(null, "-webkit-perspective-origin", null, null),
		"perspective-origin-x"			=> array(null, "-webkit-perspective-origin-x", null, null),
		"perspective-origin-y"			=> array(null, "-webkit-perspective-origin-y", null, null),
		"rtl-ordering"					=> array(null, "-webkit-rtl-ordering", null, null),
		"scrollbar-3dlight-color"		=> array(null, null, null, "-ms-scrollbar-3dlight-color"),
		"scrollbar-arrow-color"			=> array(null, null, null, "-ms-scrollbar-arrow-color"),
		"scrollbar-base-color"			=> array(null, null, null, "-ms-scrollbar-base-color"),
		"scrollbar-darkshadow-color"	=> array(null, null, null, "-ms-scrollbar-darkshadow-color"),
		"scrollbar-face-color"			=> array(null, null, null, "-ms-scrollbar-face-color"),
		"scrollbar-highlight-color"		=> array(null, null, null, "-ms-scrollbar-highlight-color"),
		"scrollbar-shadow-color"		=> array(null, null, null, "-ms-scrollbar-shadow-color"),
		"scrollbar-track-color"			=> array(null, null, null, "-ms-scrollbar-track-color"),
		"stack-sizing"					=> array("-moz-stack-sizing", null, null, null),
		"svg-shadow"					=> array(null, "-webkit-svg-shadow", null, null),
		"tab-size"						=> array("-moz-tab-size", null, "-o-tab-size", null),
		"table-baseline"				=> array(null, null, "-o-table-baseline", null),
		"text-align-last"				=> array(null, null, null, "-ms-text-align-last"),
		"text-autospace"				=> array(null, null, null, "-ms-text-autospace"),
		"text-combine"					=> array(null, "-webkit-text-combine", null, null),
		"text-decorations-in-effect"	=> array(null, "-webkit-text-decorations-in-effect", null, null),
		"text-emphasis"					=> array(null, "-webkit-text-emphasis", null, null),
		"text-emphasis-color"			=> array(null, "-webkit-text-emphasis-color", null, null),
		"text-emphasis-position"		=> array(null, "-webkit-text-emphasis-position", null, null),
		"text-emphasis-style"			=> array(null, "-webkit-text-emphasis-style", null, null),
		"text-fill-color"				=> array(null, "-webkit-text-fill-color", null, null),
		"text-justify"					=> array(null, null, null, "-ms-text-justify"),
		"text-kashida-space"			=> array(null, null, null, "-ms-text-kashida-space"),
		"text-overflow"					=> array(null, null, "-o-text-overflow", "-ms-text-overflow"),
		"text-security"					=> array(null, "-webkit-text-security", null, null),
		"text-size-adjust"				=> array(null, "-webkit-text-size-adjust", null, "-ms-text-size-adjust"),
		"text-stroke"					=> array(null, "-webkit-text-stroke", null, null),
		"text-stroke-color"				=> array(null, "-webkit-text-stroke-color", null, null),
		"text-stroke-width"				=> array(null, "-webkit-text-stroke-width", null, null),
		"text-underline-position"		=> array(null, null, null, "-ms-text-underline-position"),
		"transform"						=> array("-moz-transform", "-webkit-transform", "-o-transform", null),
		"transform-origin"				=> array("-moz-transform-origin", "-webkit-transform-origin", "-o-transform-origin", null),
		"transform-origin-x"			=> array(null, "-webkit-transform-origin-x", null, null),
		"transform-origin-y"			=> array(null, "-webkit-transform-origin-y", null, null),
		"transform-origin-z"			=> array(null, "-webkit-transform-origin-z", null, null),
		"transform-style"				=> array(null, "-webkit-transform-style", null, null),
		"transition"					=> array("-moz-transition", "-webkit-transition", "-o-transition", null),
		"transition-delay"				=> array("-moz-transition-delay", "-webkit-transition-delay", "-o-transition-delay", null),
		"transition-duration"			=> array("-moz-transition-duration", "-webkit-transition-duration", "-o-transition-duration", null),
		"transition-property"			=> array("-moz-transition-property", "-webkit-transition-property", "-o-transition-property", null),
		"transition-timing-function"	=> array("-moz-transition-timing-function", "-webkit-transition-timing-function", "-o-transition-timing-function", null),
		"user-drag"						=> array(null, "-webkit-user-drag", null, null),
		"user-focus"					=> array("-moz-user-focus", null, null, null),
		"user-input"					=> array("-moz-user-input", null, null, null),
		"user-modify"					=> array("-moz-user-modify", "-webkit-user-modify", null, null),
		"user-select"					=> array("-moz-user-select", "-webkit-user-select", null, null),
		"white-space"					=> array(__CLASS__, "whiteSpace"),
		"window-shadow"					=> array("-moz-window-shadow", null, null, null),
		"word-break"					=> array(null, null, null, "-ms-word-break"),
		"word-wrap"						=> array(null, null, null, "-ms-word-wrap"),
		"writing-mode"					=> array(null, "-webkit-writing-mode", null, "-ms-writing-mode"),
		"zoom"							=> array(null, null, null, "-ms-zoom")
		);
	/**
	 * Implements {@link aCssMinifierFilter::filter()}.
	 *
	 * @param array $tokens Array of objects of type aCssToken
	 * @return integer Count of added, changed or removed tokens; a return value large than 0 will rebuild the array
	 */
	public function apply(array &$tokens)
		{
		$r = 0;
		$transformations = &$this->transformations;
		for ($i = 0, $l = count($tokens); $i < $l; $i++)
			{
			if (get_class($tokens[$i]) === "CssRulesetDeclarationToken")
				{
				$tProperty = $tokens[$i]->Property;
				if (isset($transformations[$tProperty]))
					{
					$result = array();
					if (is_callable($transformations[$tProperty]))
						{
						$result = call_user_func_array($transformations[$tProperty], array($tokens[$i]));
						if (!is_array($result) && is_object($result))
							{
							$result = array($result);
							}
						}
					else
						{
						$tValue			= $tokens[$i]->Value;
						$tMediaTypes	= $tokens[$i]->MediaTypes;
						foreach ($transformations[$tProperty] as $property)
							{
							if ($property !== null)
								{
								$result[] = new CssRulesetDeclarationToken($property, $tValue, $tMediaTypes);
								}
							}
						}
					if (count($result) > 0)
						{
						array_splice($tokens, $i + 1, 0, $result);
						$i += count($result);
						$l += count($result);
						}
					}
				}
			}
		return $r;
		}
	/**
	 * Transforms the Internet Explorer specific declaration property "filter" to Internet Explorer 8+ compatible
	 * declaratiopn property "-ms-filter".
	 *
	 * @param aCssToken $token
	 * @return array
	 */
	private static function filter($token)
		{
		$r = array
			(
			new CssRulesetDeclarationToken("-ms-filter", "\"" . $token->Value . "\"", $token->MediaTypes),
			);
		return $r;
		}
	/**
	 * Transforms "opacity: {value}" into browser specific counterparts.
	 *
	 * @param aCssToken $token
	 * @return array
	 */
	private static function opacity($token)
		{
		// Calculate the value for Internet Explorer filter statement
		$ieValue = (int) ((float) $token->Value * 100);
		$r = array
			(
			// Internet Explorer >= 8
			new CssRulesetDeclarationToken("-ms-filter", "\"alpha(opacity=" . $ieValue . ")\"", $token->MediaTypes),
			// Internet Explorer >= 4 <= 7
			new CssRulesetDeclarationToken("filter", "alpha(opacity=" . $ieValue . ")", $token->MediaTypes),
			new CssRulesetDeclarationToken("zoom", "1", $token->MediaTypes)
			);
		return $r;
		}
	/**
	 * Transforms "white-space: pre-wrap" into browser specific counterparts.
	 *
	 * @param aCssToken $token
	 * @return array
	 */
	private static function whiteSpace($token)
		{
		if (strtolower($token->Value) === "pre-wrap")
			{
			$r = array
				(
				// Firefox < 3
				new CssRulesetDeclarationToken("white-space", "-moz-pre-wrap", $token->MediaTypes),
				// Webkit
				new CssRulesetDeclarationToken("white-space", "-webkit-pre-wrap", $token->MediaTypes),
				// Opera >= 4 <= 6
				new CssRulesetDeclarationToken("white-space", "-pre-wrap", $token->MediaTypes),
				// Opera >= 7
				new CssRulesetDeclarationToken("white-space", "-o-pre-wrap", $token->MediaTypes),
				// Internet Explorer >= 5.5
				new CssRulesetDeclarationToken("word-wrap", "break-word", $token->MediaTypes)
				);
			return $r;
			}
		else
			{
			return array();
			}
		}
	}
?>


text:
package org.elasticsoftware.elasticactors.http.actors;

import org.elasticsoftware.elasticactors.ActorRef;
import org.elasticsoftware.elasticactors.ActorState;
import org.elasticsoftware.elasticactors.TempActor;
import org.elasticsoftware.elasticactors.UntypedActor;
import org.elasticsoftware.elasticactors.http.messages.HttpResponse;
import org.elasticsoftware.elasticactors.http.messages.ServerSentEvent;
import org.elasticsoftware.elasticactors.http.messages.SseResponse;
import org.elasticsoftware.elasticactors.serialization.NoopSerializationFramework;
import org.elasticsoftware.elasticactors.serialization.SerializationFramework;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @author Joost van de Wijgerd
 */
@TempActor(stateClass = HttpServiceResponseHandler.State.class)
public final class HttpServiceResponseHandler extends UntypedActor {

    private final static Logger staticLogger = LoggerFactory.getLogger(HttpServiceResponseHandler.class);

    public static final class State implements ActorState<State> {
        private transient final Channel responseChannel;
        private boolean serverSentEvents = false;

        public State(Channel responseChannel) {
            this.responseChannel = responseChannel;
        }

        @Override
        public State getBody() {
            return this;
        }

        @Override
        public Class<? extends SerializationFramework> getSerializationFramework() {
            return NoopSerializationFramework.class;
        }

        public Channel getResponseChannel() {
            return responseChannel;
        }

        public boolean isServerSentEvents() {
            return serverSentEvents;
        }

        public void setServerSentEvents(boolean serverSentEvents) {
            this.serverSentEvents = serverSentEvents;
        }
    }

    @Override
    public void onReceive(ActorRef sender, Object message) throws Exception {
        if(message instanceof SseResponse) {
            handle((SseResponse) message);
        } else if(message instanceof HttpResponse) {
            handle((HttpResponse) message);
        } else if(message instanceof ServerSentEvent) {
            handle((ServerSentEvent) message);
        }
    }

    private void handle(HttpResponse message) throws Exception {
        State state = getState(State.class);
        // convert back to netty http response
        org.jboss.netty.handler.codec.http.HttpResponse nettyResponse = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(message.getStatusCode()));
        // @todo: copy the headers from the message
        HttpHeaders.setHeader(nettyResponse,HttpHeaders.Names.CONTENT_TYPE,message.getContentType());
        nettyResponse.setContent(ChannelBuffers.wrappedBuffer(message.getContent()));
        // we don't support keep alive as of yet
        state.getResponseChannel().write(nettyResponse).addListener(ChannelFutureListener.CLOSE);
        // need to remove myself
        getSystem().stop(getSelf());
    }

    private void handle(SseResponse message) {
        // we want to setup an EventSource connection, don't close the socket
        State state = getState(State.class);
        // register the fact we are using SSE
        state.setServerSentEvents(true);
        // send the event to the netty stack
        state.getResponseChannel().write(message);
    }

    private void handle(ServerSentEvent message) {
        State state = getState(State.class);
        // send the event to the netty stack
        state.getResponseChannel().write(message);
    }

    @Override
    protected Logger initLogger() {
        return staticLogger;
    }

    @Override
    public void onUndeliverable(ActorRef receiver, Object message) throws Exception {
        State state = getState(State.class);
        // send a 404
        state.getResponseChannel().write(new DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.NOT_FOUND)).addListener(ChannelFutureListener.CLOSE);
        // remove self
        getSystem().stop(getSelf());
    }
}