text:
"""
F-O-A-A-S Skill.

"""
from __future__ import print_function

import json
import random
import urllib
import requests

# --------------- Helpers that build all of the responses ----------------------

def build_speechlet_response(title, output, reprompt_text, should_end_session):
    return {
        'outputSpeech': {
            'type': 'SSML',
            'ssml': wrap_into_ssml(output)
        },
        'card': {
            'type': 'Simple',
            'title': title,
            'content': output
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'SSML',
                'ssml': wrap_into_ssml(reprompt_text)
            }
        },
        'shouldEndSession': should_end_session
    }

def build_response(session_attributes, speechlet_response):
    return {
        'version': '1.0',
        'sessionAttributes': session_attributes,
        'response': speechlet_response
    }

# --------------- Functions that control the skill's behavior ------------------

def get_welcome_response():
    """ If we wanted to initialize the session to have some attributes we could
    add those here
    """

    session_attributes = {}
    card_title = "Welcome"
    speech_output = "Welcome to the insult generator. " \
                    "Please tell me who to insult by saying: " \
                    "Insult Frank, or tell me an insult."
    # If the user either does not reply to the welcome message or says something
    # that is not understood, they will be prompted again with this text.
    reprompt_text = "Who shall I insult?"
    should_end_session = False
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def get_help_response():
    session_attributes = {}
    card_title = "Help"
    speech_output = "Tell me who to insult by saying: " \
                    "Alexa, ask the insult generator to insult Anthony."
    # If the user either does not reply to the welcome message or says something
    # that is not understood, they will be prompted again with this text.
    reprompt_text = "Who should I insult?"
    should_end_session = False
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def get_stop_response():
    session_attributes = {}
    card_title = "Bye"
    speech_output = "Ok."
    reprompt_text = ""
    should_end_session = True
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def handle_session_end_request():
    card_title = "Bye"
    speech_output = "Thank you for trying the insult generator. " \
                    "Have a nice day! "
    # Setting this to true ends the session and exits the skill.
    should_end_session = True
    return build_response({}, build_speechlet_response(
        card_title, speech_output, None, should_end_session))

# --------------- Code to communicate with foaas ------------------

def make_request(request):
  try:
    resp = requests.get(request, headers={ 'Accept': 'application/json' })
    if resp.status_code != 200:
      pass
    else:
      data = json.loads(resp.content)
      return data
  except:
    print("Request failed:", sys.exc_info()[0])
    return request
  return None

def get_random_endpoint_for_person(to_text, endpoints, from_text="Your F-O-A-A-S Skill"):
    return "http://foaas.com/{}/{}/{}".format(random.choice(endpoints), urllib.quote(to_text), urllib.quote(from_text))

def get_random_endpoint(endpoints, from_text="Your F-O-A-A-S Skill"):
    return "http://foaas.com/{}/{}".format(random.choice(endpoints), urllib.quote(from_text))

name_endpoints = list()
generic_endpoints = list()

def get_operations():
  global generic_endpoints, name_endpoints
  if len(name_endpoints)>0 and len(generic_endpoints)>0:
      return
  name_endpoints = list()
  generic_endpoints = list()
  try:
    data = make_request("http://foaas.com/operations/")
    for entry in data:
      #format has changed, now we have to look for the URL field and trim it.
      endpoint = entry['name']
      if 'url' in entry:
        s = entry['url']
        s = s[1:] #remove slash
        s = s[:s.find('/')] # remove everything after second slash
        endpoint = s
      if len(entry['fields']) == 1:
        generic_endpoints.append(endpoint)
      elif len(entry['fields']) == 2:
        name_endpoints.append(endpoint)
  except:
    print("Could not get operations:", sys.exc_info()[0])

def get_message(request, default_text):
  message = default_text
  try:
    message = make_request(request)['message']
  except:
    print("Get message failed", sys.exc_info()[0])
  return message

def get_insult(kw, default_text):
  global generic_endpoints, name_endpoints
  speech_output = default_text
  url = None
  retry = 2
  while retry > 0:
      retry = retry - 1
      get_operations()
      try:
        if kw:
          url = get_random_endpoint_for_person(kw, name_endpoints)
        else:
          url = get_random_endpoint(generic_endpoints)
        speech_output = get_message(url, speech_output)
        retry = 0
      except:
	pass

  return speech_output

# --------------- End of foaas code ------------------

def communicate_with_foaas(intent, session):
    card_title = "FOAAS Response"
    session_attributes = {}
    should_end_session = True
    speech_output = "I didn't understand a fucking word!"

    if intent['name'] == "AboutPerson":
        kw = intent['slots']['KeyWord']['value']
        speech_output = get_insult(kw, speech_output)
    else:
        speech_output = get_insult(None, speech_output)

    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, speech_output, should_end_session))

# --------------- Events ------------------

def on_session_started(session_started_request, session):
    """ Called when the session starts """

    print("on_session_started requestId=" + session_started_request['requestId']
          + ", sessionId=" + session['sessionId'])

def on_launch(launch_request, session):
    """ Called when the user launches the skill without specifying what they
    want
    """

    print("on_launch requestId=" + launch_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    # Dispatch to your skill's launch
    return get_welcome_response()

def on_intent(intent_request, session):
    """ Called when the user specifies an intent for this skill """

    #print("on_intent requestId=" + intent_request['requestId'] +
    #      ", sessionId=" + session['sessionId'])

    intent = intent_request['intent']
    intent_name = intent_request['intent']['name']

    # Dispatch to your skill's intent handlers
    if intent_name == "AboutPerson":
        return communicate_with_foaas(intent, session)
    elif intent_name == "AMAZON.HelpIntent":
        return get_help_response()
    elif (intent_name == "AMAZON.StopIntent") or (intent_name == "AMAZON.CancelIntent"):
        return get_stop_response()
    else:
        raise ValueError("Invalid intent")

def wrap_into_ssml(speech_string):
    speech_string = speech_string.replace("fuck", "<phoneme alphabet=\"x-sampa\" ph=\"\'fVk\">f**k</phoneme>")
    speech_string = speech_string.replace("Fuck", "<phoneme alphabet=\"x-sampa\" ph=\"\'fVk\">F**k</phoneme>")
    speech_string = speech_string.replace("fucking", "<phoneme alphabet=\"x-sampa\" ph=\"\'fVking\">f**king</phoneme>")
    speech_string = speech_string.replace("Fucking", "<phoneme alphabet=\"x-sampa\" ph=\"\'fVking\">F**ing</phoneme>")
    speech_string = speech_string.replace("fucker", u"<phoneme alphabet=\"x-sampa\" ph=\"\'fVk3`r\\\">f**ker</phoneme>")
    speech_string = speech_string.replace("Fucker", u"<phoneme alphabet=\"x-sampa\" ph=\"\'fVk3`r\\\">F**ker</phoneme>")

    return "<speak>{}</speak>".format(speech_string)

def on_session_ended(session_ended_request, session):
    """ Called when the user ends the session.

    Is not called when the skill returns should_end_session=true
    """
    print("on_session_ended requestId=" + session_ended_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    # add cleanup logic here

# --------------- Main handler ------------------

def lambda_handler(event, context):
    """ Route the incoming request based on type (LaunchRequest, IntentRequest,
    etc.) The JSON body of the request is provided in the event parameter.
    """
    print("event.session.application.applicationId=" +
          event['session']['application']['applicationId'])

    """
    Uncomment this if statement and populate with your skill's application ID to
    prevent someone else from configuring a skill that sends requests to this
    function.
    """
    # if (event['session']['application']['applicationId'] !=
    #         "amzn1.echo-sdk-ams.app.[unique-value-here]"):
    #     raise ValueError("Invalid Application ID")

    if event['session']['new']:
        on_session_started({'requestId': event['request']['requestId']},
                           event['session'])

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'], event['session'])
    elif event['request']['type'] == "IntentRequest":
        return on_intent(event['request'], event['session'])
    elif event['request']['type'] == "SessionEndedRequest":
        return on_session_ended(event['request'], event['session'])


text:
require 'roxml'
require 'nokogiri'
require 'logger'
require 'active_model'

class InvalidModelException < Exception; end

module Quickeebooks
  class Collection
    attr_accessor :entries, :count, :current_page
  end
end

# monkey-path the to_xml method to add support for passing
# in a list of attributes that we want generated rather than the complete set
# This allows us to construct sub-object representations.
module ROXML
  module InstanceMethods # :nodoc:
    # Returns an XML object representing this object
    def to_xml(params = {})
      params[:fields] ||= []
      params.reverse_merge!(:name => self.class.tag_name, :namespace => self.class.roxml_namespace)
      params[:namespace] = nil if ['*', 'xmlns'].include?(params[:namespace])
      node = XML.new_node([params[:namespace], params[:name]].compact.join(':')).tap do |root|
        refs = (self.roxml_references.present? \
          ? self.roxml_references \
          : self.class.roxml_attrs.map {|attr| attr.to_ref(self) })

        if params[:fields].length > 0
          refs.reject! { |r| !params[:fields].include?(r.name) }
        end
        refs.each do |ref|
          value = ref.to_xml(self)
          unless value.nil?
            ref.update_xml(root, value)
          end
        end
      end
    end
  end
end

#== Base files

require 'quickeebooks/request'

#== Shared

# Services
require 'quickeebooks/shared/service/filter'
require 'quickeebooks/shared/service/access_token'
require 'quickeebooks/shared/service/sort'
require 'quickeebooks/shared/service/service_base'

#== Online

# Models
require 'quickeebooks/online/model/intuit_type'
require 'quickeebooks/online/model/company_meta_data'
require 'quickeebooks/online/model/customer'
require 'quickeebooks/online/model/account'
require 'quickeebooks/online/model/invoice'
require 'quickeebooks/online/model/invoice_header'
require 'quickeebooks/online/model/invoice_line_item'
require 'quickeebooks/online/model/item'
require 'quickeebooks/online/model/unit_price'
require 'quickeebooks/online/model/meta_data'
require 'quickeebooks/online/model/price'
require 'quickeebooks/online/model/account_reference'
require 'quickeebooks/online/model/payment'
require 'quickeebooks/online/model/payment_header'
require 'quickeebooks/online/model/payment_line_item'
require 'quickeebooks/online/model/payment_detail'
require 'quickeebooks/online/model/credit_card'
require 'quickeebooks/online/model/credit_charge_info'
require 'quickeebooks/online/model/credit_charge_response'
require 'quickeebooks/online/model/sales_term'

# Services
require 'quickeebooks/online/service/filter'
require 'quickeebooks/online/service/pagination'
require 'quickeebooks/online/service/sort'
require 'quickeebooks/online/service/company_meta_data'
require 'quickeebooks/online/service/customer'
require 'quickeebooks/online/service/account'
require 'quickeebooks/online/service/invoice'
require 'quickeebooks/online/service/item'
require 'quickeebooks/online/service/entitlement'
require 'quickeebooks/online/service/payment'
require 'quickeebooks/online/service/access_token'
require 'quickeebooks/online/service/sales_term'

#== Windows

# Models
require 'quickeebooks/windows/model/intuit_type'
require 'quickeebooks/windows/model/id'
require 'quickeebooks/windows/model/custom_field'
require 'quickeebooks/windows/model/price'
require 'quickeebooks/windows/model/customer'
require 'quickeebooks/windows/model/account'
require 'quickeebooks/windows/model/item'
require 'quickeebooks/windows/model/invoice'
require 'quickeebooks/windows/model/invoice_header'
require 'quickeebooks/windows/model/invoice_line_item'
require 'quickeebooks/windows/model/address'
require 'quickeebooks/windows/model/rest_response'
require 'quickeebooks/windows/model/success'
require 'quickeebooks/windows/model/error'
require 'quickeebooks/windows/model/object_ref'
require 'quickeebooks/windows/model/sales_rep'
require 'quickeebooks/windows/model/vendor'
require 'quickeebooks/windows/model/vendor_id'
require 'quickeebooks/windows/model/external_key'
require 'quickeebooks/windows/model/ship_method'
require 'quickeebooks/windows/model/sales_tax'
require 'quickeebooks/windows/model/customer_msg'
require 'quickeebooks/windows/model/company_meta_data'
require 'quickeebooks/windows/model/payment'
require 'quickeebooks/windows/model/payment_header'
require 'quickeebooks/windows/model/payment_line_item'
require 'quickeebooks/windows/model/payment_detail'
require 'quickeebooks/windows/model/credit_card'
require 'quickeebooks/windows/model/credit_charge_info'
require 'quickeebooks/windows/model/credit_charge_response'
require 'quickeebooks/windows/model/clazz'
require 'quickeebooks/windows/model/sales_receipt_header'
require 'quickeebooks/windows/model/sales_receipt_line_item'
require 'quickeebooks/windows/model/sales_receipt'
require 'quickeebooks/windows/model/credit_memo'
require 'quickeebooks/windows/model/credit_memo_header'
require 'quickeebooks/windows/model/credit_memo_line_item'

# Services
require 'quickeebooks/windows/service/filter'
require 'quickeebooks/windows/service/sort'
require 'quickeebooks/windows/service/service_base'
require 'quickeebooks/windows/service/account'
require 'quickeebooks/windows/service/customer'
require 'quickeebooks/windows/service/credit_memo'
require 'quickeebooks/windows/service/item'
require 'quickeebooks/windows/service/invoice'
require 'quickeebooks/windows/service/sales_rep'
require 'quickeebooks/windows/service/sales_receipt'
require 'quickeebooks/windows/service/ship_method'
require 'quickeebooks/windows/service/sales_tax'
require 'quickeebooks/windows/service/customer_msg'
require 'quickeebooks/windows/service/company_meta_data'
require 'quickeebooks/windows/service/payment'
require 'quickeebooks/windows/service/clazz'
require 'quickeebooks/windows/service/access_token'

redpajama_set_name: RedPajamaGithub


text:
/**
 * Form field with combined date and time picker
 */
Ext.define('TrackAnnot.view.field.DateTime', {
	extend : 'NLeSC.form.field.DateTime',
	alias : 'widget.datetimefield',
    getState: function() {
        var state = this.callParent() || {};
        Ext.apply(state, {
            value: this.getValue()
        });
        return state;
    },
    applyState: function(state) {
        this.callParent(arguments);
        if (state) {
            this.setValue(state.value);
        }
    },
    listeners: {
        change: function() {
            this.saveState();
        }
    }
});


text:
var __extends=this && this.__extends || function(d, b)
{
function __()
{
this.constructor = d
}
for (var p in b)
b.hasOwnProperty(p) && (d[p] = b[p]);
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __)
},
__decorate=this && this.__decorate || function(decorators, target, key, desc)
{
var c=arguments.length,
r=c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d,
i;
if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (i = decorators.length - 1; i >= 0; i--)
(d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
return c > 3 && r && Object.defineProperty(target, key, r), r
},
__param=this && this.__param || function(paramIndex, decorator)
{
return function(target, key)
{
decorator(target, key, paramIndex)
}
};
define(["require", "exports", 'wijmo/wijmo.chart.radar', '@angular/core', '@angular/common', 'wijmo/wijmo.angular2.directiveBase', 'wijmo/wijmo.angular2.chart'], function(require, exports, wjcChartRadar, core_1, common_1, wijmo_angular2_directiveBase_1, wijmo_angular2_chart_1)
{
"use strict";
var WjFlexRadar=function(_super)
{
function WjFlexRadar(elRef, injector)
{
_super.call(this, wijmo_angular2_directiveBase_1.WjDirectiveBehavior.getHostElement(elRef));
wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector)
}
return __extends(WjFlexRadar, _super), Object.defineProperty(WjFlexRadar.prototype, "tooltipContent", {
get: function()
{
return this.tooltip.content
}, set: function(value)
{
this.tooltip.content = value
}, enumerable: !0, configurable: !0
}), Object.defineProperty(WjFlexRadar.prototype, "labelContent", {
get: function()
{
return this.dataLabel.content
}, set: function(value)
{
this.dataLabel.content = value
}, enumerable: !0, configurable: !0
}), __decorate([wijmo_angular2_directiveBase_1.WjComponent({
selector: 'wj-flex-radar', template: ""
}), __param(0, core_1.Inject(core_1.ElementRef)), __param(1, core_1.Inject(core_1.Injector))], WjFlexRadar)
}(wjcChartRadar.FlexRadar),
WjFlexRadarAxis,
WjFlexRadarSeries,
moduleExports,
WjChartRadarModule;
exports.WjFlexRadar = WjFlexRadar;
WjFlexRadarAxis = function(_super)
{
function WjFlexRadarAxis(elRef, injector)
{
_super.call(this);
wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector)
}
return __extends(WjFlexRadarAxis, _super), __decorate([wijmo_angular2_directiveBase_1.WjComponent({
selector: 'wj-flex-radar-axis', wjParentDirectives: [WjFlexRadar, core_1.forwardRef(function()
{
return WjFlexRadarSeries
}), ], template: ""
}), __param(0, core_1.Inject(core_1.ElementRef)), __param(1, core_1.Inject(core_1.Injector))], WjFlexRadarAxis)
}(wjcChartRadar.FlexRadarAxis);
exports.WjFlexRadarAxis = WjFlexRadarAxis;
WjFlexRadarSeries = function(_super)
{
function WjFlexRadarSeries(elRef, injector)
{
_super.call(this);
wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector)
}
return __extends(WjFlexRadarSeries, _super), __decorate([wijmo_angular2_directiveBase_1.WjComponent({
selector: 'wj-flex-radar-series', wjParentDirectives: [WjFlexRadar], template: "
<ng-content></ng-content>
", wjSiblingDirectiveId: wijmo_angular2_chart_1.WjFlexChartSeries.SiblingId
}), __param(0, core_1.Inject(core_1.ElementRef)), __param(1, core_1.Inject(core_1.Injector))], WjFlexRadarSeries)
}(wjcChartRadar.FlexRadarSeries);
exports.WjFlexRadarSeries = WjFlexRadarSeries;
moduleExports = [WjFlexRadar, WjFlexRadarAxis, WjFlexRadarSeries];
WjChartRadarModule = function()
{
function WjChartRadarModule(){}
return __decorate([core_1.NgModule({
imports: [wijmo_angular2_directiveBase_1.WjDirectiveBaseModule, common_1.CommonModule], declarations: moduleExports.slice(), exports: moduleExports.slice()
})], WjChartRadarModule)
}();
exports.WjChartRadarModule = WjChartRadarModule
})


text:
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed 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.

package com.google.enterprise.adaptor;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.enterprise.adaptor.SamlServiceProvider.AuthnState;
import com.google.enterprise.adaptor.secmgr.http.HttpClientInterface;
import com.google.enterprise.adaptor.secmgr.modules.SamlClient;
import com.google.enterprise.adaptor.secmgr.saml.OpenSamlUtil;

import com.sun.net.httpserver.HttpExchange;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.binding.decoding.HTTPRedirectDeflateDecoder;
import org.opensaml.saml2.binding.encoding.HTTPSOAP11Encoder;
import org.opensaml.saml2.core.AuthnRequest;
import org.opensaml.saml2.core.NameID;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Test cases for {@link SamlServiceProvider}.
 */
public class SamlServiceProviderTest {
  @Rule
  public ExpectedException thrown = ExpectedException.none();

  private Charset charset = Charset.forName("UTF-8");
  private SessionManager<HttpExchange> sessionManager
      = new SessionManager<HttpExchange>(new MockTimeProvider(),
          new SessionManager.HttpExchangeClientStore(), 1000, 1000);
  private SamlMetadata metadata = new SamlMetadata("localhost", 80,
      "thegsa", "http://google.com/enterprise/gsa/security-manager",
      "http://google.com/enterprise/gsa/adaptor");
  private HttpClientAdapter httpClient = new HttpClientAdapter();
  private SamlServiceProvider serviceProvider = new SamlServiceProvider(
      sessionManager, metadata, /* KeyPair = */ null, httpClient,
      Principal.DomainFormat.DNS);
  private MockHttpExchange ex = new MockHttpExchange("GET", "/",
      new MockHttpContext("/"));
  private MockHttpExchange exArtifact
      = new MockHttpExchange("GET", "/?SAMLart=1234someid5678",
          new MockHttpContext("/"));
  private MockHttpExchange initialEx
      = new MockHttpExchange("GET", "/doc/someid",
          new MockHttpContext("/doc/"));

  private static final String GOLDEN_ARTIFACT_RESOLVE_REQUEST
      = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      + "<soap11:Envelope "
      +   "xmlns:soap11=\"http://schemas.xmlsoap.org/soap/envelope/\">"
      +   "<soap11:Body>"
      +     "<saml2p:ArtifactResolve "
      +       "ID=\"someid\" "
      +       "IssueInstant=\"sometime\" "
      +       "Version=\"2.0\" "
      +       "xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\">"
      +       "<saml2:Issuer "
      +         "xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">"
      +         "http://google.com/enterprise/gsa/adaptor"
      +       "</saml2:Issuer>"
      +       "<saml2p:Artifact>"
      +         "1234someid5678"
      +       "</saml2p:Artifact>"
      +     "</saml2p:ArtifactResolve>"
      +   "</soap11:Body>"
      + "</soap11:Envelope>";

  @BeforeClass
  public static void initSaml() {
    GsaCommunicationHandler.bootstrapOpenSaml();
  }

  @Test
  public void testHandleAuthenticationNewSession() throws Exception {
    String goldenResponse
        = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<soap11:Envelope "
        +   "xmlns:soap11=\"http://schemas.xmlsoap.org/soap/envelope/\">"
        +   "<soap11:Body>"
        +     "<saml2p:AuthnRequest "
        +       "Destination=\"https://thegsa/security-manager/samlauthn\" "
        +       "ID=\"someid\" "
        +       "IsPassive=\"false\" "
        +       "IssueInstant=\"sometime\" "
        +       "ProviderName=\"GSA Adaptor\" "
        +       "Version=\"2.0\" "
        +       "xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\">"
        +       "<saml2:Issuer "
        +         "xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">"
        +         "http://google.com/enterprise/gsa/adaptor"
        +       "</saml2:Issuer>"
        +     "</saml2p:AuthnRequest>"
        +   "</soap11:Body>"
        + "</soap11:Envelope>";

    serviceProvider.handleAuthentication(ex);

    //
    // We have run the method, now we need to look over the results...
    //
    assertEquals(307, ex.getResponseCode());
    URI uri = new URI(ex.getResponseHeaders().getFirst("Location"));
    assertEquals("https", uri.getScheme());
    assertEquals("thegsa", uri.getHost());
    assertEquals("/security-manager/samlauthn", uri.getPath());
    assertTrue(!isAuthned(ex));

    // Act like we are the receiving end of the communication.
    MockHttpExchange remoteEx = new MockHttpExchange("GET", uri.toString(),
        new MockHttpContext("/security-manager/samlauthn"));

    SAMLMessageContext<AuthnRequest, AuthnRequest, NameID> context
        = OpenSamlUtil.makeSamlMessageContext();
    OpenSamlUtil.initializeLocalEntity(context, metadata.getPeerEntity(),
        metadata.getPeerEntity().getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
    context.setInboundMessageTransport(new EnhancedInTransport(remoteEx));
    context.setOutboundMessageTransport(
        new HttpExchangeOutTransportAdapter(remoteEx));

    HTTPRedirectDeflateDecoder decoder = new RedirectDecoder();
    decoder.decode(context);
    context.setOutboundSAMLMessage(context.getInboundSAMLMessage());

    HTTPSOAP11Encoder encoder = new HTTPSOAP11Encoder();
    encoder.encode(context);

    String response = new String(remoteEx.getResponseBytes(), "UTF-8");
    response = massageMessage(response);
    assertEquals(goldenResponse, response);
  }

  @Test
  public void testHandleAuthenticationAlreadyAuthned() throws Exception {
    // Create a new authenticated session for this HttpExchange.
    Session session = sessionManager.getSession(ex, true);
    AuthnState authn = new AuthnState();
    session.setAttribute(SamlServiceProvider.SESSION_STATE_ATTR_NAME, authn);
    AuthnIdentity identity = new AuthnIdentityImpl
        .Builder(new UserPrincipal("test")).build();
    authn.authenticated(identity, Long.MAX_VALUE);
    serviceProvider.handleAuthentication(ex);
    // Still should cause them to go through authn
    assertEquals(307, ex.getResponseCode());
    assertTrue(!isAuthned(ex));
  }

  @Test
  public void testHandleAuthenticationHead() throws Exception {
    MockHttpExchange ex = new MockHttpExchange("HEAD", "/",
                                               new MockHttpContext("/"));
    serviceProvider.handleAuthentication(ex);
    assertEquals(307, ex.getResponseCode());
    assertTrue(!isAuthned(ex));
  }

  @Test
  public void testHandleAuthenticationBadMethod() throws Exception {
    MockHttpExchange ex = new MockHttpExchange("POST", "/",
                                               new MockHttpContext("/"));
    serviceProvider.handleAuthentication(ex);
    assertEquals(405, ex.getResponseCode());
  }

  @Test
  public void testAssertionConsumerNormal() throws Exception {
    SamlHttpClient httpClient = new SamlHttpClient() {
      @Override
      protected void handleExchange(ClientExchange ex) {
        String body = new String(ex.getRequestBody(), charset);
        body = massageMessage(body);
        assertEquals(GOLDEN_ARTIFACT_RESOLVE_REQUEST, body);

        // Generate valid response.
        String issuer = metadata.getPeerEntity().getEntityID();
        String recipient = metadata.getLocalEntity()
            .getSPSSODescriptor(SAMLConstants.SAML20P_NS)
            .getAssertionConsumerServices().get(0).getLocation();
        String audience = metadata.getLocalEntity().getEntityID();
        String response
            = "<SOAP-ENV:Envelope "
            +   "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            +   "<SOAP-ENV:Body>"
            +     "<samlp:ArtifactResponse "
            +       "xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" "
            +       "xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\" "
            +       "ID=\"someid1\" Version=\"2.0\" "
            +       "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +       "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +       "<Issuer>" + issuer + "</Issuer>"
            +       "<samlp:Status>"
            +         "<samlp:StatusCode "
            +           "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +       "</samlp:Status>"
            +       "<samlp:Response "
            +         "ID=\"someid2\" "
            +         "Version=\"2.0\" "
            +         "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +         "<samlp:Status>"
            +           "<samlp:StatusCode "
            +             "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +         "</samlp:Status>"
            +         "<Assertion "
            +           "Version=\"2.0\" "
            +           "ID=\"someid3\" "
            +           "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +           "<Issuer>" + issuer + "</Issuer>"
            +           "<Subject>"
            +             "<NameID>CN=Polly Hedra</NameID>"
            +             "<SubjectConfirmation "
            +               "Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">"
            +               "<SubjectConfirmationData "
            +                 "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +                 "Recipient=\"" + recipient + "\" "
            +                 "NotOnOrAfter=\"2030-01-01T01:01:01Z\"/>"
            +             "</SubjectConfirmation>"
            +           "</Subject>"
            +           "<Conditions "
            +             "NotBefore=\"2010-01-01T01:01:01Z\">"
            +             "<AudienceRestriction>"
            +               "<Audience>" + audience + "</Audience>"
            +             "</AudienceRestriction>"
            +           "</Conditions>"
            +           "<AuthnStatement "
            +             "AuthnInstant=\"2010-01-01T01:01:01Z\"/>"
            +         "</Assertion>"
            +       "</samlp:Response>"
            +     "</samlp:ArtifactResponse>"
            +   "</SOAP-ENV:Body>"
            + "</SOAP-ENV:Envelope>";
        ex.setStatusCode(200);
        ex.setResponseStream(response.getBytes(charset));
      }
    };
    SamlClient samlClient = createSamlClient(httpClient);
    httpClient.setSamlClient(samlClient);
    issueRequest(exArtifact, initialEx, samlClient);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(303, exArtifact.getResponseCode());
    assertTrue(isAuthned(exArtifact));
    AuthnIdentity identity = serviceProvider.getUserIdentity(exArtifact);
    assertEquals("CN=Polly Hedra", identity.getUser().getName());
    assertNull(identity.getGroups());
    assertNull(identity.getPassword());
  }

  @Test
  public void testAssertionConsumerNormalWithExtension() throws Exception {
    SamlHttpClient httpClient = new SamlHttpClient() {
      @Override
      protected void handleExchange(ClientExchange ex) {
        String body = new String(ex.getRequestBody(), charset);
        body = massageMessage(body);
        assertEquals(GOLDEN_ARTIFACT_RESOLVE_REQUEST, body);

        // Generate valid response.
        String issuer = metadata.getPeerEntity().getEntityID();
        String recipient = metadata.getLocalEntity()
            .getSPSSODescriptor(SAMLConstants.SAML20P_NS)
            .getAssertionConsumerServices().get(0).getLocation();
        String audience = metadata.getLocalEntity().getEntityID();
        String response
            = "<SOAP-ENV:Envelope "
            +   "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            +   "<SOAP-ENV:Body>"
            +     "<samlp:ArtifactResponse "
            +       "xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" "
            +       "xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\" "
            +       "ID=\"someid1\" Version=\"2.0\" "
            +       "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +       "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +       "<Issuer>" + issuer + "</Issuer>"
            +       "<samlp:Status>"
            +         "<samlp:StatusCode "
            +           "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +       "</samlp:Status>"
            +       "<samlp:Response "
            +         "ID=\"someid2\" "
            +         "Version=\"2.0\" "
            +         "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +         "<samlp:Status>"
            +           "<samlp:StatusCode "
            +             "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +         "</samlp:Status>"
            +         "<Assertion "
            +           "Version=\"2.0\" "
            +           "ID=\"someid3\" "
            +           "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +           "<Issuer>" + issuer + "</Issuer>"
            +           "<Subject>"
            +             "<NameID>CN=Polly Hedra</NameID>"
            +             "<SubjectConfirmation "
            +               "Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">"
            +               "<SubjectConfirmationData "
            +                 "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +                 "Recipient=\"" + recipient + "\" "
            +                 "NotOnOrAfter=\"2030-01-01T01:01:01Z\"/>"
            +             "</SubjectConfirmation>"
            +           "</Subject>"
            +           "<Conditions "
            +             "NotBefore=\"2010-01-01T01:01:01Z\">"
            +             "<AudienceRestriction>"
            +               "<Audience>" + audience + "</Audience>"
            +             "</AudienceRestriction>"
            +           "</Conditions>"
            +           "<AuthnStatement "
            +             "AuthnInstant=\"2010-01-01T01:01:01Z\">"
            +             "<AuthnContext>"
            +               "<AuthnContextClassRef>"
            +                 "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword"
            +               "</AuthnContextClassRef>"
            +             "</AuthnContext>"
            +           "</AuthnStatement>"
            +           "<AttributeStatement>"
            +             "<Attribute Name=\"SecurityManagerState\">"
            +               "<AttributeValue>"
            + "{"
            +   "\"version\": 1,"
            +   "\"timeStamp\": 1330042321589,"
            +   "\"sessionState\": {"
            +     "\"instructions\": ["
            +       "{"
            +         "\"operation\": \"ADD_CREDENTIAL\","
            +         "\"authority\": "
            + "\"http://google.com/enterprise/gsa/security-manager/Default\","
            +         "\"operand\": {"
            +           "\"name\": \"CN=Polly Hedra\","
            +           "\"typeName\": \"AuthnPrincipal\""
            +         "}"
            +       "},"
            +       "{"
            +         "\"operation\": \"ADD_CREDENTIAL\","
            +         "\"authority\": "
            + "\"http://google.com/enterprise/gsa/security-manager/Default\","
            +         "\"operand\": {"
            +           "\"password\": \"p0ck3t\","
            +           "\"typeName\": \"CredPassword\""
            +         "}"
            +       "},"
            +       "{"
            +         "\"operation\": \"ADD_VERIFICATION\","
            +         "\"authority\": "
            + "\"http://google.com/enterprise/gsa/security-manager/adaptor\","
            +         "\"operand\": {"
            +           "\"status\": \"VERIFIED\","
            +           "\"expirationTime\": 1330043521581,"
            +           "\"credentials\": ["
            +             "{"
            +               "\"name\": \"CN=Polly Hedra\","
            +               "\"typeName\": \"AuthnPrincipal\""
            +             "},"
            +             "{"
            +               "\"password\": \"p0ck3t\","
            +               "\"typeName\": \"CredPassword\""
            +             "}"
            +           "]"
            +         "}"
            +       "}"
            +     "]"
            +   "},"
            +   "\"pviCredentials\": {"
            +     "\"username\": \"CN=Polly HedraNot\","
            +     "\"password\": \"p0ck3t\","
            +     "\"groups\": ["
            +     "]"
            +   "},"
            +   "\"basicCredentials\": {"
            +     "\"username\": \"CN=Polly Hedra\","
            +     "\"password\": \"p0ck3t\","
            +     "\"groups\": ["
            +     "]"
            +   "},"
            +   "\"verifiedCredentials\": ["
            +     "{"
            +       "\"username\": \"CN=Polly HedraYes\","
            +       "\"password\": \"p0ck3t\","
            +       "\"name_space\": \"testCG1\","
            +       "\"groups\": ["
            +         "{"
            +           "\"name\": \"group1\","
            +           "\"namespace\": \"testCG1\","
            +           "\"domain\": \"test.com\""
            +         "},"
            +         "{"
            +           "\"name\": \"pollysGroup\","
            +           "\"namespace\": \"testCG1\","
            +           "\"domain\": \"test.com\""
            +         "}"
            +       "]"
            +     "}"
            +   "],"
            +   "\"cookies\": []"
            + "}"
            +               "</AttributeValue>"
            +             "</Attribute>"
            +           "</AttributeStatement>"
            +         "</Assertion>"
            +       "</samlp:Response>"
            +     "</samlp:ArtifactResponse>"
            +   "</SOAP-ENV:Body>"
            + "</SOAP-ENV:Envelope>";
        ex.setStatusCode(200);
        ex.setResponseStream(response.getBytes(charset));
      }
    };
    SamlClient samlClient = createSamlClient(httpClient);
    httpClient.setSamlClient(samlClient);
    issueRequest(exArtifact, initialEx, samlClient);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(303, exArtifact.getResponseCode());
    assertTrue(isAuthned(exArtifact));
    AuthnIdentity identity = serviceProvider.getUserIdentity(exArtifact);
    assertEquals("CN=Polly HedraYes", identity.getUser().getName());
    assertEquals("testCG1", identity.getUser().getNamespace());
    // Make sure that the information from the extensions was parsed out and
    // made available for later use.
    Set<String> groups = new HashSet<String>();
    groups.add("group1@test.com");
    groups.add("pollysGroup@test.com");
    assertEquals(GroupPrincipal.makeSet(groups, "testCG1"),
        identity.getGroups());
    assertEquals("p0ck3t", identity.getPassword());
  }

  @Test
  public void testAssertionConsumerAuthnFailure() throws Exception {
    SamlHttpClient httpClient = new SamlHttpClient() {
      @Override
      protected void handleExchange(ClientExchange ex) {
        String body = new String(ex.getRequestBody(), charset);
        body = massageMessage(body);
        assertEquals(GOLDEN_ARTIFACT_RESOLVE_REQUEST, body);

        // Generate valid response for authn failed.
        String issuer = metadata.getPeerEntity().getEntityID();
        String response
            = "<SOAP-ENV:Envelope "
            +   "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            +   "<SOAP-ENV:Body>"
            +     "<samlp:ArtifactResponse "
            +       "xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" "
            +       "xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\" "
            +       "ID=\"someid1\" Version=\"2.0\" "
            +       "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +       "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +       "<Issuer>" + issuer + "</Issuer>"
            +       "<samlp:Status>"
            +         "<samlp:StatusCode "
            +           "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +       "</samlp:Status>"
            +       "<samlp:Response "
            +         "ID=\"someid2\" "
            +         "Version=\"2.0\" "
            +         "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +         "<samlp:Status>"
            +           "<samlp:StatusCode "
            +             "Value=\"urn:oasis:names:tc:SAML:2.0:status:AuthnFailed\"/>"
            +         "</samlp:Status>"
            +       "</samlp:Response>"
            +     "</samlp:ArtifactResponse>"
            +   "</SOAP-ENV:Body>"
            + "</SOAP-ENV:Envelope>";
        ex.setStatusCode(200);
        ex.setResponseStream(response.getBytes(charset));
      }
    };
    SamlClient samlClient = createSamlClient(httpClient);
    httpClient.setSamlClient(samlClient);
    issueRequest(exArtifact, initialEx, samlClient);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(403, exArtifact.getResponseCode());
    assertTrue(!isAuthned(exArtifact));
  }

  @Test
  public void testAssertionConsumerNoAuthnResponse() throws Exception {
    SamlHttpClient httpClient = new SamlHttpClient() {
      @Override
      protected void handleExchange(ClientExchange ex) {
        String body = new String(ex.getRequestBody(), charset);
        body = massageMessage(body);
        assertEquals(GOLDEN_ARTIFACT_RESOLVE_REQUEST, body);

        // Generate valid response for artifact requesting failure.
        String issuer = metadata.getPeerEntity().getEntityID();
        String response
            = "<SOAP-ENV:Envelope "
            +   "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            +   "<SOAP-ENV:Body>"
            +     "<samlp:ArtifactResponse "
            +       "xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" "
            +       "xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\" "
            +       "ID=\"someid1\" Version=\"2.0\" "
            +       "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +       "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +       "<Issuer>" + issuer + "</Issuer>"
            +       "<samlp:Status>"
            +         "<samlp:StatusCode "
            +           "Value=\"urn:oasis:names:tc:SAML:2.0:status:Requester\"/>"
            +       "</samlp:Status>"
            +     "</samlp:ArtifactResponse>"
            +   "</SOAP-ENV:Body>"
            + "</SOAP-ENV:Envelope>";
        ex.setStatusCode(200);
        ex.setResponseStream(response.getBytes(charset));
      }
    };
    SamlClient samlClient = createSamlClient(httpClient);
    httpClient.setSamlClient(samlClient);
    issueRequest(exArtifact, initialEx, samlClient);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(403, exArtifact.getResponseCode());
    assertTrue(!isAuthned(exArtifact));
  }

  @Test
  public void testAssertionConsumerWrongResponse() throws Exception {
    SamlHttpClient httpClient = new SamlHttpClient() {
      @Override
      protected void handleExchange(ClientExchange ex) {
        String body = new String(ex.getRequestBody(), charset);
        body = massageMessage(body);
        assertEquals(GOLDEN_ARTIFACT_RESOLVE_REQUEST, body);

        // Generate valid response for successful authn, but for the wrong
        // request.
        String issuer = metadata.getPeerEntity().getEntityID();
        String recipient = metadata.getLocalEntity()
            .getSPSSODescriptor(SAMLConstants.SAML20P_NS)
            .getAssertionConsumerServices().get(0).getLocation();
        String audience = metadata.getLocalEntity().getEntityID();
        String response
            = "<SOAP-ENV:Envelope "
            +   "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            +   "<SOAP-ENV:Body>"
            +     "<samlp:ArtifactResponse "
            +       "xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" "
            +       "xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\" "
            +       "ID=\"someid1\" Version=\"2.0\" "
            +       "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +       "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +       "<Issuer>" + issuer + "</Issuer>"
            +       "<samlp:Status>"
            +         "<samlp:StatusCode "
            +           "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +       "</samlp:Status>"
            +       "<samlp:Response "
            +         "ID=\"someid2\" "
            +         "Version=\"2.0\" "
            +         "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +         "<samlp:Status>"
            +           "<samlp:StatusCode "
            +             "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +         "</samlp:Status>"
            +         "<Assertion "
            +           "Version=\"2.0\" "
            +           "ID=\"someid3\" "
            +           "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +           "<Issuer>" + issuer + "</Issuer>"
            +           "<Subject>"
            +             "<NameID>CN=Polly Hedra</NameID>"
            +             "<SubjectConfirmation "
            +               "Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">"
            +               "<SubjectConfirmationData "
            +                 "InResponseTo=\"notthis" + samlClient.getRequestId() + "\" "
            +                 "Recipient=\"" + recipient + "\" "
            +                 "NotOnOrAfter=\"2030-01-01T01:01:01Z\"/>"
            +             "</SubjectConfirmation>"
            +           "</Subject>"
            +           "<Conditions "
            +             "NotBefore=\"2010-01-01T01:01:01Z\">"
            +             "<AudienceRestriction>"
            +               "<Audience>" + audience + "</Audience>"
            +             "</AudienceRestriction>"
            +           "</Conditions>"
            +           "<AuthnStatement "
            +             "AuthnInstant=\"2010-01-01T01:01:01Z\"/>"
            +         "</Assertion>"
            +       "</samlp:Response>"
            +     "</samlp:ArtifactResponse>"
            +   "</SOAP-ENV:Body>"
            + "</SOAP-ENV:Envelope>";
        ex.setStatusCode(200);
        ex.setResponseStream(response.getBytes(charset));
      }
    };
    SamlClient samlClient = createSamlClient(httpClient);
    httpClient.setSamlClient(samlClient);
    issueRequest(exArtifact, initialEx, samlClient);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(403, exArtifact.getResponseCode());
    assertTrue(!isAuthned(exArtifact));
  }

  @Test
  public void testAssertionConsumerWrongIssuer() throws Exception {
    SamlHttpClient httpClient = new SamlHttpClient() {
      @Override
      protected void handleExchange(ClientExchange ex) {
        String body = new String(ex.getRequestBody(), charset);
        body = massageMessage(body);
        assertEquals(GOLDEN_ARTIFACT_RESOLVE_REQUEST, body);

        // Generate valid response, but from wrong issuer.
        String issuer = metadata.getPeerEntity().getEntityID();
        String recipient = metadata.getLocalEntity()
            .getSPSSODescriptor(SAMLConstants.SAML20P_NS)
            .getAssertionConsumerServices().get(0).getLocation();
        String audience = metadata.getLocalEntity().getEntityID();
        String response
            = "<SOAP-ENV:Envelope "
            +   "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            +   "<SOAP-ENV:Body>"
            +     "<samlp:ArtifactResponse "
            +       "xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" "
            +       "xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\" "
            +       "ID=\"someid1\" Version=\"2.0\" "
            +       "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +       "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +       "<Issuer>" + issuer + "</Issuer>"
            +       "<samlp:Status>"
            +         "<samlp:StatusCode "
            +           "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +       "</samlp:Status>"
            +       "<samlp:Response "
            +         "ID=\"someid2\" "
            +         "Version=\"2.0\" "
            +         "IssueInstant=\"2010-01-01T01:01:01Z\">"
            // Add an issuer that is not the expected one.
            +         "<Issuer>notthexpected" + issuer + "</Issuer>"
            +         "<samlp:Status>"
            +           "<samlp:StatusCode "
            +             "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +         "</samlp:Status>"
            +         "<Assertion "
            +           "Version=\"2.0\" "
            +           "ID=\"someid3\" "
            +           "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +           "<Issuer>" + issuer + "</Issuer>"
            +           "<Subject>"
            +             "<NameID>CN=Polly Hedra</NameID>"
            +             "<SubjectConfirmation "
            +               "Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">"
            +               "<SubjectConfirmationData "
            +                 "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +                 "Recipient=\"" + recipient + "\" "
            +                 "NotOnOrAfter=\"2030-01-01T01:01:01Z\"/>"
            +             "</SubjectConfirmation>"
            +           "</Subject>"
            +           "<Conditions "
            +             "NotBefore=\"2010-01-01T01:01:01Z\">"
            +             "<AudienceRestriction>"
            +               "<Audience>" + audience + "</Audience>"
            +             "</AudienceRestriction>"
            +           "</Conditions>"
            +           "<AuthnStatement "
            +             "AuthnInstant=\"2010-01-01T01:01:01Z\"/>"
            +         "</Assertion>"
            +       "</samlp:Response>"
            +     "</samlp:ArtifactResponse>"
            +   "</SOAP-ENV:Body>"
            + "</SOAP-ENV:Envelope>";
        ex.setStatusCode(200);
        ex.setResponseStream(response.getBytes(charset));
      }
    };
    SamlClient samlClient = createSamlClient(httpClient);
    httpClient.setSamlClient(samlClient);
    issueRequest(exArtifact, initialEx, samlClient);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(403, exArtifact.getResponseCode());
    assertTrue(!isAuthned(exArtifact));
  }

  @Test
  public void testAssertionConsumerAlreadyAuthned() throws Exception {
    MockHttpClient httpClient = new MockHttpClient() {
      @Override
      protected void handleExchange(ClientExchange ex) {
        fail("No request should have been issued.");
      }
    };
    SamlClient samlClient = createSamlClient(httpClient);
    issueRequest(exArtifact, initialEx, samlClient);

    // Authenticate the session.
    Session session = sessionManager.getSession(exArtifact, false);
    AuthnState authn = (AuthnState) session
        .getAttribute(SamlServiceProvider.SESSION_STATE_ATTR_NAME);
    AuthnIdentity identity = new AuthnIdentityImpl
       .Builder(new UserPrincipal("test")).build();
    authn.authenticated(identity, Long.MAX_VALUE);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(409, exArtifact.getResponseCode());
    assertTrue(isAuthned(exArtifact));
  }

  @Test
  public void testAssertionConsumerNoSession() throws Exception {
    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(409, exArtifact.getResponseCode());
    assertTrue(!isAuthned(exArtifact));
  }

  @Test
  public void testAssertionConsumerUnrequestedAuthnResponse() throws Exception {
    AuthnState authnState = new AuthnState();
    sessionManager.getSession(exArtifact).setAttribute(
        SamlServiceProvider.SESSION_STATE_ATTR_NAME, authnState);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(500, exArtifact.getResponseCode());
    assertTrue(!isAuthned(exArtifact));
  }

  @Test
  public void testAssertionConsumerPost() throws Exception {
    MockHttpExchange ex
        = new MockHttpExchange("POST", "/?SAMLart=1234someid5678",
                               new MockHttpContext("/"));
    serviceProvider.getAssertionConsumer().handle(ex);
    assertEquals(405, ex.getResponseCode());
    assertTrue(!isAuthned(ex));
  }

  @Test
  public void testVerifiedUserOverridesSubject() throws Exception {
    SamlHttpClient httpClient = new SamlHttpClient() {
      @Override
      protected void handleExchange(ClientExchange ex) {
        String body = new String(ex.getRequestBody(), charset);
        body = massageMessage(body);
        assertEquals(GOLDEN_ARTIFACT_RESOLVE_REQUEST, body);

        // Generate valid response.
        String issuer = metadata.getPeerEntity().getEntityID();
        String recipient = metadata.getLocalEntity()
            .getSPSSODescriptor(SAMLConstants.SAML20P_NS)
            .getAssertionConsumerServices().get(0).getLocation();
        String audience = metadata.getLocalEntity().getEntityID();
        String response
            = "<SOAP-ENV:Envelope "
            +   "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            +   "<SOAP-ENV:Body>"
            +     "<samlp:ArtifactResponse "
            +       "xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" "
            +       "xmlns=\"urn:oasis:names:tc:SAML:2.0:assertion\" "
            +       "ID=\"someid1\" Version=\"2.0\" "
            +       "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +       "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +       "<Issuer>" + issuer + "</Issuer>"
            +       "<samlp:Status>"
            +         "<samlp:StatusCode "
            +           "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +       "</samlp:Status>"
            +       "<samlp:Response "
            +         "ID=\"someid2\" "
            +         "Version=\"2.0\" "
            +         "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +         "<samlp:Status>"
            +           "<samlp:StatusCode "
            +             "Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
            +         "</samlp:Status>"
            +         "<Assertion "
            +           "Version=\"2.0\" "
            +           "ID=\"someid3\" "
            +           "IssueInstant=\"2010-01-01T01:01:01Z\">"
            +           "<Issuer>" + issuer + "</Issuer>"
            +           "<Subject>"
            +             "<NameID>CN=Polly Hedra</NameID>"
            +             "<SubjectConfirmation "
            +               "Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">"
            +               "<SubjectConfirmationData "
            +                 "InResponseTo=\"" + samlClient.getRequestId() + "\" "
            +                 "Recipient=\"" + recipient + "\" "
            +                 "NotOnOrAfter=\"2030-01-01T01:01:01Z\"/>"
            +             "</SubjectConfirmation>"
            +           "</Subject>"
            +           "<Conditions "
            +             "NotBefore=\"2010-01-01T01:01:01Z\">"
            +             "<AudienceRestriction>"
            +               "<Audience>" + audience + "</Audience>"
            +             "</AudienceRestriction>"
            +           "</Conditions>"
            +           "<AuthnStatement "
            +             "AuthnInstant=\"2010-01-01T01:01:01Z\">"
            +             "<AuthnContext>"
            +               "<AuthnContextClassRef>"
            +                 "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword"
            +               "</AuthnContextClassRef>"
            +             "</AuthnContext>"
            +           "</AuthnStatement>"
            +           "<AttributeStatement>"
            +             "<Attribute Name=\"SecurityManagerState\">"
            +               "<AttributeValue>"
            + "{"
            +   "\"version\": 1,"
            +   "\"timeStamp\": 1330042321589,"
            +   "\"sessionState\": {"
            +     "\"instructions\": ["
            +       "{"
            +         "\"operation\": \"ADD_CREDENTIAL\","
            +         "\"authority\": "
            + "\"http://google.com/enterprise/gsa/security-manager/Default\","
            +         "\"operand\": {"
            +           "\"name\": \"CN=Polly Hedra\","
            +           "\"typeName\": \"AuthnPrincipal\""
            +         "}"
            +       "},"
            +       "{"
            +         "\"operation\": \"ADD_CREDENTIAL\","
            +         "\"authority\": "
            + "\"http://google.com/enterprise/gsa/security-manager/Default\","
            +         "\"operand\": {"
            +           "\"password\": \"p0ck3t\","
            +           "\"typeName\": \"CredPassword\""
            +         "}"
            +       "},"
            +       "{"
            +         "\"operation\": \"ADD_VERIFICATION\","
            +         "\"authority\": "
            + "\"http://google.com/enterprise/gsa/security-manager/adaptor\","
            +         "\"operand\": {"
            +           "\"status\": \"VERIFIED\","
            +           "\"expirationTime\": 1330043521581,"
            +           "\"credentials\": ["
            +             "{"
            +               "\"name\": \"CN=Polly Hedra\","
            +               "\"typeName\": \"AuthnPrincipal\""
            +             "},"
            +             "{"
            +               "\"password\": \"p0ck3t\","
            +               "\"typeName\": \"CredPassword\""
            +             "}"
            +           "]"
            +         "}"
            +       "}"
            +     "]"
            +   "},"
            +   "\"pviCredentials\": {"
            +     "\"username\": \"CN=Polly Hedra\","
            +     "\"password\": \"p0ck3t\","
            +     "\"groups\": ["
            +     "]"
            +   "},"
            +   "\"basicCredentials\": {"
            +     "\"username\": \"not-used\","
            +     "\"domain\": \"also-not-used\","
            +     "\"password\": \"p0ck3t\","
            +     "\"groups\": ["
            +     "]"
            +   "},"
            +   "\"verifiedCredentials\": ["
            +     "{"
            +       "\"username\": \"whale\","
            +       "\"domain\": \"ahab.net\","
            +       "\"password\": \"p0ck3t\","
            +       "\"groups\": ["
            +         "{"
            +           "\"name\": \"group1\","
            +           "\"namespace\": \"Default\","
            +           "\"domain\": \"test.com\""
            +         "},"
            +         "{"
            +           "\"name\": \"pollysGroup\","
            +           "\"namespace\": \"Default\","
            +           "\"domain\": \"test.com\""
            +         "}"
            +       "]"
            +     "}"
            +   "],"
            +   "\"cookies\": []"
            + "}"
            +               "</AttributeValue>"
            +             "</Attribute>"
            +           "</AttributeStatement>"
            +         "</Assertion>"
            +       "</samlp:Response>"
            +     "</samlp:ArtifactResponse>"
            +   "</SOAP-ENV:Body>"
            + "</SOAP-ENV:Envelope>";
        ex.setStatusCode(200);
        ex.setResponseStream(response.getBytes(charset));
      }
    };
    SamlClient samlClient = createSamlClient(httpClient);
    httpClient.setSamlClient(samlClient);
    issueRequest(exArtifact, initialEx, samlClient);

    serviceProvider.getAssertionConsumer().handle(exArtifact);
    assertEquals(303, exArtifact.getResponseCode());
    assertTrue(isAuthned(exArtifact));
    AuthnIdentity identity = serviceProvider.getUserIdentity(exArtifact);
    assertEquals("whale@ahab.net", identity.getUser().getName());
  }

  private SamlClient createSamlClient(HttpClientInterface httpClient) {
    return new SamlClient(metadata.getLocalEntity(), metadata.getPeerEntity(),
                          "Testing", null, httpClient);
  }

  private void issueRequest(HttpExchange ex, HttpExchange initialEx,
                            SamlClient samlClient) throws IOException {
    AuthnState authnState = new AuthnState();
    authnState.startAttempt(samlClient, ex.getRequestURI());
    sessionManager.getSession(ex).setAttribute(
        SamlServiceProvider.SESSION_STATE_ATTR_NAME, authnState);
    // Used to generate a request id.
    samlClient.sendAuthnRequest(new HttpExchangeOutTransportAdapter(initialEx));
  }

  private boolean isAuthned(HttpExchange ex) {
    return serviceProvider.getUserIdentity(ex) != null;
  }

  private String massageMessage(String message) {
    return message.replaceAll("ID=\"[^\"]+\"", "ID=\"someid\"")
        .replaceAll("IssueInstant=\"[^\"]+\"", "IssueInstant=\"sometime\"");
  }

  private static class EnhancedInTransport
      extends HttpExchangeInTransportAdapter {
    private Map<String, List<String>> parameters;

    public EnhancedInTransport(HttpExchange ex) {
      super(ex);
      parameters = parseParameters();
    }

    private Map<String, List<String>> parseParameters() {
      Map<String, List<String>> params = new HashMap<String, List<String>>();
      String query = ex.getRequestURI().getQuery();
      if (query == null) {
        return params;
      }
      // This is not fully correct, but good enough for the test case.
      for (String param : query.split("&")) {
        String[] split = query.split("=", 2);
        if (!params.containsKey(split[0])) {
          params.put(split[0], new LinkedList<String>());
        }
        params.get(split[0]).add(split.length == 2 ? split[1] : "");
      }
      return params;
    }

    @Override
    public String getParameterValue(String name) {
      List<String> values = getParameterValues(name);
      return values.size() == 0 ? null : values.get(0);
    }

    @Override
    public List<String> getParameterValues(String name) {
      if (parameters.containsKey(name)) {
        return parameters.get(name);
      } else {
        return Collections.emptyList();
      }
    }

    public HttpExchange getExchange() {
      return ex;
    }
  }

  private static class RedirectDecoder extends HTTPRedirectDeflateDecoder {
    @SuppressWarnings("rawtypes") // The super class does not use generics.
    @Override
    protected String getActualReceiverEndpointURI(
        SAMLMessageContext messageContext) {
      EnhancedInTransport inTransport = (EnhancedInTransport) messageContext
          .getInboundMessageTransport();
      String requestUri = inTransport.getExchange().getRequestURI().toString();
      // Remove query from URI
      return requestUri.split("\\?", 2)[0];
    }
  }

  private abstract static class SamlHttpClient extends MockHttpClient {
    protected SamlClient samlClient;

    public void setSamlClient(SamlClient samlClient) {
      this.samlClient = samlClient;
    }
  }
}


text:
"use strict";

import { CityTourMath } from "./../math";

var MotionGenerator = function(start, target, easingFunction) {
  var next = function() {
    var percentage = easingFunction.next();

    return CityTourMath.lerp(start, target, percentage);
  };

  var finished = function() {
    return easingFunction.finished();
  };

  return {
    finished: finished,
    next: next,
  };
};

var StaticMotionGenerator = function(target) {
  return {
    finished: function() { return true; },
    next: function() { return target; },
  };
};

export { MotionGenerator, StaticMotionGenerator };


text:
- **Alumno**: Francisco J. Revoredo (5810) (Ingeniería en Informática)
- **Año**: 2015
- **Materia**: Computación 2

---

### Descripción del Proyecto:
Software para cálculos paralelizables, distribuidos en un número arbitrario de threads.
La interfaz de usuario está montanda en un servidor web (C), con soporte Html+CSS, por lo que la interfaz de usuario
es casi totalmente independiente de la lógica de programación. El puerto para ingresar es el 5000 (Ejemplo localhost:5000).
Las consultas al servidor se manejan de forma concurrente con multiprocesamiento, y a su vez cada proceso
crea una cantidad de hilos (arbitraria) para realizar los cálculos paralelizables.

---

### Criterio de Selección de los Algoritmos:
Teniendo en cuenta la ley de Amdahl, la mejora que se puede obtener en el tiempo de cómputo de determinado algoritmo depende de la
 cantidad de código paralelizable de dicho algoritmo. Sabiendo esto, se eligieron algoritmos que contienen un porcentaje total
o casi total de código paralelizable, conocidos como "Algoritmos perfectamente paralelos". Esto quiere decir que no existen dependencias de los datos, lo que tendería a serializar los cálculos.

---

### Lista de Cálculos Disponibles

1. **Cálculo de Pi por Regla de Simpson**
2. **Cálculo de Pi por Montecarlo**

---

### Descripción de los Métodos y su Implementación

- **Cálculo de Pi por Regla de Simpson**

 ![alt text](https://github.com/franrevoredo/final-compu2/blob/master/img/simpson.jpg "Simpson")

La regla de simpson es un método de integración numérica para obtener la aproximación
 de una integral.
Sabiendo que la integral entre 0 y 1 de [4/(1+x²)] es igual a Pi,
solamente hay dividir el intervalo de integración entre el total de threads involucrados
y hacer que cada thread calcule un intervalo definido de la integral en cuestión. Una vez obtenido cada resultado parcial
con sumar todos los resultados parciales se obtiene la aproximación de pi.
(Nota: Cada thread debe calcular la integral en un intervalo único, y la suma de todos los intervalos debe ser el intervalo original de la integral para que el cálculo sea correcto.)

- **Cálculo de Pi por Montecarlo**

![alt text](https://github.com/franrevoredo/final-compu2/blob/master/img/montecarlo.jpg "Montecarlo")

Los métodos montecarlo son algoritmos que se basan en muestras aleatorias
(suelen ser pseudo-aleatorias para simplificar los cálculos) para obtener aproximaciones numéricas.
Sabiendo esto, podemos aproximar el valor de Pi partiendo de un circulo de radio 1 dentro de un cuadrado de lado 2 .
A partir de puntos al azar (uniformemente distribuidos) dentro del cuadrado, la probabilidad de que dicho punto
caiga dentro del area del circulo es de Pi/4 (Es la razón entre las áreas). Entonces contado la frecuencia
del suceso y multiplicandola por cuatro podemos obtener una aproximación de Pi. Entre mayor sea la muestra, más preciso va a ser el resultado.
Se puede dividir la muestra total en cada thread y realizar experimentos independientes en cada thread. Para que
los experimentos sean verdaderamente independientes es necesario que cada thread tenga un generador pseudoaleatorio independiente en cada thread.
Para esto, el seed que se le debe asignar al generador (rand_r(&seed)) de cada thread, debe ser distinto. Para solucionar
este problema de seeds distintas para un numero no determinado de threads (y sabiendo que los "thread id" proporcionados por pthread_self()
 son unsigned int al igual que las seeds) utilizamos como seed el "thread id" que el proceso le asigna a cada thread.
Una vez cada thread calculó el el numero de ocurrencias parcial, el thread principal es el encargado de calcular la frecuencia a partir del tamaño
 de la muestra y de la suma de las ocurrencias parciales. Luego, con solo multiplicar esta frecuencia por cuatro, obtenemos nuestra aproximación final a Pi.


text:
""" test copying PGP objects
"""
from __future__ import print_function
import pytest

import copy
import glob
import inspect
import os.path

import pgpy

from pgpy import PGPSignature, PGPUID, PGPMessage, PGPKey

_keys = glob.glob('tests/testdata/keys/*.1.pub.asc') + glob.glob('tests/testdata/keys/*.1.sec.asc')
_msgs = [ 'tests/testdata/messages/message.{}.asc'.format(f) for f in ['signed', 'rsa.cast5.no-mdc', 'rsa.dsa.pass.aes']]

def sig():
    return PGPSignature.from_file('tests/testdata/blocks/rsasignature.asc')

def uid():
    return PGPUID.new('Abraham Lincoln', comment='Honest Abe', email='abraham.lincoln@whitehouse.gov')

def key(fn):
    key, _ = PGPKey.from_file(fn)
    return key

def walk_obj(obj, prefix=""):
    from enum import Enum

    for name, val in inspect.getmembers(obj):
        if hasattr(obj.__class__, name):
            continue

        yield '{}{}'.format(prefix, name), val

        if not isinstance(val, Enum):
            for n, v in walk_obj(val, prefix="{}{}.".format(prefix, name)):
                yield n, v

def check_id(obj):
    from datetime import datetime
    from enum import Enum

    # do some type checking to determine if we should check the identity of an object member
    # these types are singletons
    if isinstance(obj, (Enum, bool, type(None))):
        return False

    # these types are immutable
    if isinstance(obj, (str, datetime)):
        return False

    # integers are kind of a special case.
    #   ints that do not exceed sys.maxsize are singletons, and in either case are immutable
    #   this shouldn't apply to MPIs, though, which are subclasses of int
    if isinstance(obj, int) and not isinstance(obj, pgpy.packet.types.MPI):
        return False

    return True

def ksort(key):
    # return a tuple of key, key.count('.') so we get a descending alphabetical, ascending depth ordering
    return key, key.count('.')

objs = [sig(), uid(),] + [PGPMessage.from_file(m) for m in _msgs] + [key(f) for f in _keys]
cids = ['sig', 'uid',] + [os.path.basename(m) for m in _msgs] + [os.path.basename(f) for f in _keys]

@pytest.mark.parametrize('obj', objs, ids=cids)
def test_copy_obj(request, obj):
    obj2 = copy.copy(obj)

    objflat = {name: val for name, val in walk_obj(obj, '{}.'.format(request.node.callspec.id))}
    obj2flat = {name: val for name, val in walk_obj(obj2, '{}.'.format(request.node.callspec.id))}

    for k in sorted(objflat, key=ksort):
        print("checking attribute: {} ".format(k), end="")
        if isinstance(objflat[k], pgpy.types.SorteDeque):
            print("[SorteDeque] ", end="")
            assert len(objflat[k]) == len(obj2flat[k])

        if not isinstance(objflat[k], (pgpy.types.PGPObject, pgpy.types.SorteDeque)):
            print("[{} ]".format(type(objflat[k])), end="")
            assert objflat[k] == objflat[k], k

        # check identity, but only types that should definitely be copied
        if check_id(objflat[k]):
            print("[id] {}".format(type(objflat[k])))
            assert objflat[k] is not obj2flat[k], "{}: {}".format(type(objflat[k]), k)

        else:
            print()


text:
package org.thryft.waf.lib.stores.jdbc;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class LoggingJdbcPreparedStatement implements PreparedStatement {
    LoggingJdbcPreparedStatement(final PreparedStatement delegate,
            final String sql) {
        this.delegate = checkNotNull(delegate);
        this.sql = checkNotNull(sql);
    }

    @Override
    public void addBatch() throws SQLException {
        delegate.addBatch();
    }

    @Override
    public void addBatch(final String sql) throws SQLException {
        delegate.addBatch(sql);
    }

    @Override
    public void cancel() throws SQLException {
        delegate.cancel();
    }

    @Override
    public void clearBatch() throws SQLException {
        delegate.clearBatch();
    }

    @Override
    public void clearParameters() throws SQLException {
        delegate.clearParameters();
    }

    @Override
    public void clearWarnings() throws SQLException {
        delegate.clearWarnings();
    }

    @Override
    public void close() throws SQLException {
        delegate.close();
    }

    @Override
    public void closeOnCompletion() throws SQLException {
        delegate.closeOnCompletion();
    }

    @Override
    public boolean execute() throws SQLException {
        logger.debug("execute({})", sql);
        return delegate.execute();
    }

    @Override
    public boolean execute(final String sql) throws SQLException {
        return delegate.execute(sql);
    }

    @Override
    public boolean execute(final String sql, final int autoGeneratedKeys)
            throws SQLException {
        return delegate.execute(sql, autoGeneratedKeys);
    }

    @Override
    public boolean execute(final String sql, final int[] columnIndexes)
            throws SQLException {
        return delegate.execute(sql, columnIndexes);
    }

    @Override
    public boolean execute(final String sql, final String[] columnNames)
            throws SQLException {
        return delegate.execute(sql, columnNames);
    }

    @Override
    public int[] executeBatch() throws SQLException {
        return delegate.executeBatch();
    }

    @Override
    public ResultSet executeQuery() throws SQLException {
        logger.debug("executeQuery({})", sql);
        return delegate.executeQuery();
    }

    @Override
    public ResultSet executeQuery(final String sql) throws SQLException {
        return delegate.executeQuery(sql);
    }

    @Override
    public int executeUpdate() throws SQLException {
        logger.debug("executeUpdate({})", sql);
        return delegate.executeUpdate();
    }

    @Override
    public int executeUpdate(final String sql) throws SQLException {
        return delegate.executeUpdate(sql);
    }

    @Override
    public int executeUpdate(final String sql, final int autoGeneratedKeys)
            throws SQLException {
        return delegate.executeUpdate(sql, autoGeneratedKeys);
    }

    @Override
    public int executeUpdate(final String sql, final int[] columnIndexes)
            throws SQLException {
        return delegate.executeUpdate(sql, columnIndexes);
    }

    @Override
    public int executeUpdate(final String sql, final String[] columnNames)
            throws SQLException {
        return delegate.executeUpdate(sql, columnNames);
    }

    @Override
    public Connection getConnection() throws SQLException {
        return delegate.getConnection();
    }

    @Override
    public int getFetchDirection() throws SQLException {
        return delegate.getFetchDirection();
    }

    @Override
    public int getFetchSize() throws SQLException {
        return delegate.getFetchSize();
    }

    @Override
    public ResultSet getGeneratedKeys() throws SQLException {
        return delegate.getGeneratedKeys();
    }

    @Override
    public int getMaxFieldSize() throws SQLException {
        return delegate.getMaxFieldSize();
    }

    @Override
    public int getMaxRows() throws SQLException {
        return delegate.getMaxRows();
    }

    @Override
    public ResultSetMetaData getMetaData() throws SQLException {
        return delegate.getMetaData();
    }

    @Override
    public boolean getMoreResults() throws SQLException {
        return delegate.getMoreResults();
    }

    @Override
    public boolean getMoreResults(final int current) throws SQLException {
        return delegate.getMoreResults(current);
    }

    @Override
    public ParameterMetaData getParameterMetaData() throws SQLException {
        return delegate.getParameterMetaData();
    }

    @Override
    public int getQueryTimeout() throws SQLException {
        return delegate.getQueryTimeout();
    }

    @Override
    public ResultSet getResultSet() throws SQLException {
        return delegate.getResultSet();
    }

    @Override
    public int getResultSetConcurrency() throws SQLException {
        return delegate.getResultSetConcurrency();
    }

    @Override
    public int getResultSetHoldability() throws SQLException {
        return delegate.getResultSetHoldability();
    }

    @Override
    public int getResultSetType() throws SQLException {
        return delegate.getResultSetType();
    }

    @Override
    public int getUpdateCount() throws SQLException {
        return delegate.getUpdateCount();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return delegate.getWarnings();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return delegate.isClosed();
    }

    @Override
    public boolean isCloseOnCompletion() throws SQLException {
        return delegate.isCloseOnCompletion();
    }

    @Override
    public boolean isPoolable() throws SQLException {
        return delegate.isPoolable();
    }

    @Override
    public boolean isWrapperFor(final Class<?> iface) throws SQLException {
        return delegate.isWrapperFor(iface);
    }

    @Override
    public void setArray(final int parameterIndex, final Array x)
            throws SQLException {
        delegate.setArray(parameterIndex, x);
    }

    @Override
    public void setAsciiStream(final int parameterIndex, final InputStream x)
            throws SQLException {
        delegate.setAsciiStream(parameterIndex, x);
    }

    @Override
    public void setAsciiStream(final int parameterIndex, final InputStream x,
            final int length) throws SQLException {
        delegate.setAsciiStream(parameterIndex, x, length);
    }

    @Override
    public void setAsciiStream(final int parameterIndex, final InputStream x,
            final long length) throws SQLException {
        delegate.setAsciiStream(parameterIndex, x, length);
    }

    @Override
    public void setBigDecimal(final int parameterIndex, final BigDecimal x)
            throws SQLException {
        delegate.setBigDecimal(parameterIndex, x);
    }

    @Override
    public void setBinaryStream(final int parameterIndex, final InputStream x)
            throws SQLException {
        delegate.setBinaryStream(parameterIndex, x);
    }

    @Override
    public void setBinaryStream(final int parameterIndex, final InputStream x,
            final int length) throws SQLException {
        delegate.setBinaryStream(parameterIndex, x, length);
    }

    @Override
    public void setBinaryStream(final int parameterIndex, final InputStream x,
            final long length) throws SQLException {
        delegate.setBinaryStream(parameterIndex, x, length);
    }

    @Override
    public void setBlob(final int parameterIndex, final Blob x)
            throws SQLException {
        delegate.setBlob(parameterIndex, x);
    }

    @Override
    public void setBlob(final int parameterIndex, final InputStream inputStream)
            throws SQLException {
        delegate.setBlob(parameterIndex, inputStream);
    }

    @Override
    public void setBlob(final int parameterIndex,
            final InputStream inputStream, final long length)
                    throws SQLException {
        delegate.setBlob(parameterIndex, inputStream, length);
    }

    @Override
    public void setBoolean(final int parameterIndex, final boolean x)
            throws SQLException {
        delegate.setBoolean(parameterIndex, x);
    }

    @Override
    public void setByte(final int parameterIndex, final byte x)
            throws SQLException {
        delegate.setByte(parameterIndex, x);
    }

    @Override
    public void setBytes(final int parameterIndex, final byte[] x)
            throws SQLException {
        delegate.setBytes(parameterIndex, x);
    }

    @Override
    public void setCharacterStream(final int parameterIndex, final Reader reader)
            throws SQLException {
        delegate.setCharacterStream(parameterIndex, reader);
    }

    @Override
    public void setCharacterStream(final int parameterIndex,
            final Reader reader, final int length) throws SQLException {
        delegate.setCharacterStream(parameterIndex, reader, length);
    }

    @Override
    public void setCharacterStream(final int parameterIndex,
            final Reader reader, final long length) throws SQLException {
        delegate.setCharacterStream(parameterIndex, reader, length);
    }

    @Override
    public void setClob(final int parameterIndex, final Clob x)
            throws SQLException {
        delegate.setClob(parameterIndex, x);
    }

    @Override
    public void setClob(final int parameterIndex, final Reader reader)
            throws SQLException {
        delegate.setClob(parameterIndex, reader);
    }

    @Override
    public void setClob(final int parameterIndex, final Reader reader,
            final long length) throws SQLException {
        delegate.setClob(parameterIndex, reader, length);
    }

    @Override
    public void setCursorName(final String name) throws SQLException {
        delegate.setCursorName(name);
    }

    @Override
    public void setDate(final int parameterIndex, final Date x)
            throws SQLException {
        delegate.setDate(parameterIndex, x);
    }

    @Override
    public void setDate(final int parameterIndex, final Date x,
            final Calendar cal) throws SQLException {
        delegate.setDate(parameterIndex, x, cal);
    }

    @Override
    public void setDouble(final int parameterIndex, final double x)
            throws SQLException {
        delegate.setDouble(parameterIndex, x);
    }

    @Override
    public void setEscapeProcessing(final boolean enable) throws SQLException {
        delegate.setEscapeProcessing(enable);
    }

    @Override
    public void setFetchDirection(final int direction) throws SQLException {
        delegate.setFetchDirection(direction);
    }

    @Override
    public void setFetchSize(final int rows) throws SQLException {
        delegate.setFetchSize(rows);
    }

    @Override
    public void setFloat(final int parameterIndex, final float x)
            throws SQLException {
        delegate.setFloat(parameterIndex, x);
    }

    @Override
    public void setInt(final int parameterIndex, final int x)
            throws SQLException {
        delegate.setInt(parameterIndex, x);
    }

    @Override
    public void setLong(final int parameterIndex, final long x)
            throws SQLException {
        delegate.setLong(parameterIndex, x);
    }

    @Override
    public void setMaxFieldSize(final int max) throws SQLException {
        delegate.setMaxFieldSize(max);
    }

    @Override
    public void setMaxRows(final int max) throws SQLException {
        delegate.setMaxRows(max);
    }

    @Override
    public void setNCharacterStream(final int parameterIndex, final Reader value)
            throws SQLException {
        delegate.setNCharacterStream(parameterIndex, value);
    }

    @Override
    public void setNCharacterStream(final int parameterIndex,
            final Reader value, final long length) throws SQLException {
        delegate.setNCharacterStream(parameterIndex, value, length);
    }

    @Override
    public void setNClob(final int parameterIndex, final NClob value)
            throws SQLException {
        delegate.setNClob(parameterIndex, value);
    }

    @Override
    public void setNClob(final int parameterIndex, final Reader reader)
            throws SQLException {
        delegate.setNClob(parameterIndex, reader);
    }

    @Override
    public void setNClob(final int parameterIndex, final Reader reader,
            final long length) throws SQLException {
        delegate.setNClob(parameterIndex, reader, length);
    }

    @Override
    public void setNString(final int parameterIndex, final String value)
            throws SQLException {
        delegate.setNString(parameterIndex, value);
    }

    @Override
    public void setNull(final int parameterIndex, final int sqlType)
            throws SQLException {
        delegate.setNull(parameterIndex, sqlType);
    }

    @Override
    public void setNull(final int parameterIndex, final int sqlType,
            final String typeName) throws SQLException {
        delegate.setNull(parameterIndex, sqlType, typeName);
    }

    @Override
    public void setObject(final int parameterIndex, final Object x)
            throws SQLException {
        delegate.setObject(parameterIndex, x);
    }

    @Override
    public void setObject(final int parameterIndex, final Object x,
            final int targetSqlType) throws SQLException {
        delegate.setObject(parameterIndex, x, targetSqlType);
    }

    @Override
    public void setObject(final int parameterIndex, final Object x,
            final int targetSqlType, final int scaleOrLength)
                    throws SQLException {
        delegate.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
    }

    @Override
    public void setPoolable(final boolean poolable) throws SQLException {
        delegate.setPoolable(poolable);
    }

    @Override
    public void setQueryTimeout(final int seconds) throws SQLException {
        delegate.setQueryTimeout(seconds);
    }

    @Override
    public void setRef(final int parameterIndex, final Ref x)
            throws SQLException {
        delegate.setRef(parameterIndex, x);
    }

    @Override
    public void setRowId(final int parameterIndex, final RowId x)
            throws SQLException {
        delegate.setRowId(parameterIndex, x);
    }

    @Override
    public void setShort(final int parameterIndex, final short x)
            throws SQLException {
        delegate.setShort(parameterIndex, x);
    }

    @Override
    public void setSQLXML(final int parameterIndex, final SQLXML xmlObject)
            throws SQLException {
        delegate.setSQLXML(parameterIndex, xmlObject);
    }

    @Override
    public void setString(final int parameterIndex, final String x)
            throws SQLException {
        delegate.setString(parameterIndex, x);
    }

    @Override
    public void setTime(final int parameterIndex, final Time x)
            throws SQLException {
        delegate.setTime(parameterIndex, x);
    }

    @Override
    public void setTime(final int parameterIndex, final Time x,
            final Calendar cal) throws SQLException {
        delegate.setTime(parameterIndex, x, cal);
    }

    @Override
    public void setTimestamp(final int parameterIndex, final Timestamp x)
            throws SQLException {
        delegate.setTimestamp(parameterIndex, x);
    }

    @Override
    public void setTimestamp(final int parameterIndex, final Timestamp x,
            final Calendar cal) throws SQLException {
        delegate.setTimestamp(parameterIndex, x, cal);
    }

    @Deprecated
    @Override
    public void setUnicodeStream(final int parameterIndex, final InputStream x,
            final int length) throws SQLException {
        delegate.setUnicodeStream(parameterIndex, x, length);
    }

    @Override
    public void setURL(final int parameterIndex, final URL x)
            throws SQLException {
        delegate.setURL(parameterIndex, x);
    }

    @Override
    public <T> T unwrap(final Class<T> iface) throws SQLException {
        return delegate.unwrap(iface);
    }

    private final PreparedStatement delegate;
    private final String sql;

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


text:
Data Volumes cloning a PVC source support multiple forms of cloning. Based on the prerequisites listed [here](#Prerequisites),
a cloning method will be utilized with varying degrees of efficiency. These forms are [CSI volume cloning](./csi-cloning.md),
[smart cloning](./smart-clone.md), and [host-assisted cloning](./clone-datavolume.md). CSI volume cloning and smart cloning
employ CSI driver features in order to more efficiently clone a source PVC, but have certain limitations,
while host-assited cloning provides a slower means with little limitation.

### Prerequisites
_The required prerequisites in order to trigger efficient cloning methods_
* **CSI Volume Cloning**:
    1) The csi driver backing the storage class of the PVC supports volume cloning, and corresponding StorageProfile has
       the cloneStrategy set to CSI Volume Cloning (see [here](./csi-cloning.md#Prerequisites) for more details)
    2) The source and target PVCs share the same Storage Class
    3) The source and target PVCs share the same Volume Mode
    4) The user creating the DataVolume has permission to create the `datavolumes/source` resource in the source namespace
    5) The source volume is not in use

* **Smart Cloning**:
    1) A Snapshot Class associated with the Storage Class exists
    2) The source and target PVCs share the same Storage Class
    3) The source and target PVCs share the same Volume Mode
    4) The user creating the DataVolume has permission to create the `datavolumes/source` resource in the source namespace
    5) The source volume is not in use

### Note: Data Volume Cloning can work together with namespace transfer and size expansion

### Additional Documentation
* DataVolumes: [datavolumes](./datavolumes.md)
* DataVolume Cloning: [clone-datavolumes](./clone-datavolume.md)
* CSI Volume Cloning: [csi-cloning](./csi-cloning.md)
* Smart Cloning: [smart-clone](./smart-clone.md)
* Namespace Transfer: [namespace-transfer](./namespace-transfer.md)
* StorageProfile (description of cloneStrategy): [storageprofile](./storageprofile.md)


text:
export default function(state = true, action) {
  switch (action.type) {

    case 'SWITCH_STONE_SOUND':
      return action.stoneSound;
    default:
      return state;
  }
}


text:
<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

/**
 * Class RoleTableSeeder
 */
class RoleTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Start database truncate
        $data = [
            // Syntaxis: ['name' => '<role name>'],

            // Global role scopes
            ['name' => 'admin', 'description' => 'De administrator gebruikersgroep.'],
            ['name' => 'verhuur', 'description' => 'De gebruikersgroep verantworodelijk voor de verhuur.'],
            ['name' => 'leiding', 'description' => 'De gebruikersgroep van de leiding.'],
            ['name' => 'hoofdleiding', 'description' => 'de gebruikers groep voor de hooofleiding v/d groep.']
        ];

        // If there is data in the role table. Delete it.
        $table = DB::table('roles');
        $table->delete();
        $table->insert($data);
    }
}


text:
FactoryGirl.define do
  factory :todo do
    project
    author
    user
    target factory: :issue
    action { Todo::ASSIGNED }

    trait :assigned do
      action { Todo::ASSIGNED }
    end

    trait :mentioned do
      action { Todo::MENTIONED }
    end
  end
end


text:
using CommonServiceLocator;
using GalaSoft.MvvmLight.Ioc;

namespace Chromatics.Controllers
{
    /// <summary>
    ///     This is a Service Locator to allow for loose coupling of components
    ///     See https://martinfowler.com/articles/injection.html#UsingAServiceLocator for a description.
    /// </summary>
    internal class Locator
    {
        static Locator()
        {
            // Set up IoC container
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            // Register our main applications entry point (Chromatics)
            SimpleIoc.Default.Register<Chromatics>();

            // Register an interface used for writing to the Console/Log/Application
            SimpleIoc.Default.Register<ILogWrite>(() => SimpleIoc.Default.GetInstance<Chromatics>());
        }

        /// <summary>
        ///     Static reference to our main entry point into Chromatics
        /// </summary>
        public static Chromatics ChromaticsInstance => SimpleIoc.Default.GetInstance<Chromatics>();
    }
}


text:
package org.eclipse.php.internal.ui;

import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.console.IConsoleConstants;

/**
 *
 * This class sets the Layout for the Rich Client Perspective. The perspective
 * will contain an editor area, property page, outline view, resource navigator,
 * and palette.
 */
public class PHPPerspectiveFactory implements IPerspectiveFactory {

	private static final String TOP_LEFT_LOCATION = "topLeft"; //$NON-NLS-1$
	public static final String TOP_RIGHT_LOCATION = "right"; //$NON-NLS-1$
	private static final String BOTTOM_LOCATION = "bottom"; //$NON-NLS-1$

	public static final String PERSPECTIVE_ID = "org.eclipse.php.perspective"; //$NON-NLS-1$

	// other view id's
	private static final String ID_EXPLORER = "org.eclipse.php.ui.explorer"; //$NON-NLS-1$
	private static final String ID_TYPEHIERARCHY = "org.eclipse.dltk.ui.TypeHierarchy"; //$NON-NLS-1$
	private static final String ID_FUNCTIONS = "org.eclipse.php.ui.functions"; //$NON-NLS-1$
	private static final String ID_PROJECT_OUTLINE = "org.eclipse.php.ui.projectOutline"; //$NON-NLS-1$
	public static final String ID_MVC = "org.zend.php.framework.ui.views.mvc"; //$NON-NLS-1$
	private static final String ORG_ECLIPSE_DEBUG_UI_DEBUG_PERSPECTIVE = "org.eclipse.debug.ui.DebugPerspective"; //$	 //$NON-NLS-1$

	public void createInitialLayout(IPageLayout layout) {

		// Adding the default views for the perspective
		addViews(layout);

		layout.addPerspectiveShortcut(PERSPECTIVE_ID);
		layout.addPerspectiveShortcut(ORG_ECLIPSE_DEBUG_UI_DEBUG_PERSPECTIVE);

		layout.addShowViewShortcut(ID_EXPLORER);
		// layout.addShowViewShortcut(ID_TYPEHIERARCHY);
		layout.addShowViewShortcut(ID_FUNCTIONS);
		layout.addShowViewShortcut(ID_PROJECT_OUTLINE);
		layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW);

		layout.addShowInPart(ID_EXPLORER);
	}

	/*
	 * This method add the default views that are part of the perspective and
	 * lays them out in relation to each other and the editor area.
	 */
	protected void addViews(IPageLayout layout) {

		String editorArea = layout.getEditorArea();

		// Everything is based off the editor area

		// Top left: Resource Navigator view and PHP Explorer
		IFolderLayout topLeft = layout.createFolder(TOP_LEFT_LOCATION,
				IPageLayout.LEFT, 0.22f, editorArea);
		topLeft.addView(ID_EXPLORER);
		// topLeft.addView(ID_TYPEHIERARCHY);

		// Bottom: Attributes view, Problem View, Task List, placeholder for
		// Design View Log
		IFolderLayout bottom = layout.createFolder(BOTTOM_LOCATION,
				IPageLayout.BOTTOM, 0.75f, editorArea);
		bottom.addView(IPageLayout.ID_PROBLEM_VIEW);
		// bottom.addView(IPageLayout.ID_TASK_LIST);
		bottom.addView(IConsoleConstants.ID_CONSOLE_VIEW);
		bottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);

		IFolderLayout outlineFolder = layout.createFolder(TOP_RIGHT_LOCATION,
				IPageLayout.RIGHT, (float) 0.75, editorArea);
		outlineFolder.addView(IPageLayout.ID_OUTLINE);
		outlineFolder.addPlaceholder(ID_PROJECT_OUTLINE);
		outlineFolder.addPlaceholder(ID_MVC);
		outlineFolder.addPlaceholder(ID_FUNCTIONS);
	}
}


text:
<?php

namespace Elastica\Test\Query;

use Elastica\Document;
use Elastica\Query\SpanFirst;
use Elastica\Query\SpanTerm;
use Elastica\Test\Base as BaseTest;

class SpanFirstTest extends BaseTest
{
    /**
     * @group unit
     */
    public function testToArray()
    {
        $query = new SpanFirst();
        $query->setMatch(new SpanTerm(['user' => 'kimchy']));
        $query->setEnd(3);

        $data = $query->toArray();

        $this->assertEquals([
            'span_first' => [
                'match' => [
                    'span_term' => ['user' => 'kimchy'],
                ],
                'end' => 3,
            ],
        ], $data);
    }

    /**
     * @group functional
     */
    public function testSpanNearTerm()
    {
        $field = 'lorem';
        $value = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse odio lacus, aliquam nec nulla quis, aliquam eleifend eros.';

        $index = $this->_createIndex();
        $type = $index->getType('_doc');

        $docHitData = [$field => $value];
        $doc = new Document(1, $docHitData);
        $type->addDocument($doc);
        $index->refresh();

        $spanTerm = new SpanTerm([$field => ['value' => 'consectetur']]);

        // consectetur, end 4 won't match
        $spanNearQuery = new SpanFirst($spanTerm, 4);
        $resultSet = $type->search($spanNearQuery);
        $this->assertEquals(0, $resultSet->count());

        $spanTerm = new SpanTerm([$field => ['value' => 'lorem']]);

        // lorem, end 3 matches
        $spanNearQuery = new SpanFirst($spanTerm, 3);
        $resultSet = $type->search($spanNearQuery);
        $this->assertEquals(1, $resultSet->count());
    }
}