text:
package face

// Copyright (c) Microsoft and contributors.  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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/autorest/validation"
	"github.com/satori/go.uuid"
	"io"
	"net/http"
)

// PersonGroupPersonClient is the an API for face detection, verification, and identification.
type PersonGroupPersonClient struct {
	BaseClient
}

// NewPersonGroupPersonClient creates an instance of the PersonGroupPersonClient client.
func NewPersonGroupPersonClient(azureRegion AzureRegions) PersonGroupPersonClient {
	return PersonGroupPersonClient{New(azureRegion)}
}

// AddPersonFaceFromStream add a representative face to a person for identification. The input face is specified as an
// image with a targetFace rectangle.
//
// personGroupID is id referencing a particular person group. personID is id referencing a particular person.
// imageParameter is an image stream. imageParameter will be closed upon successful return. Callers should ensure
// closure when receiving an error.userData is user-specified data about the face for any purpose. The maximum
// length is 1KB. targetFace is a face rectangle to specify the target face to be added to a person in the format
// of "targetFace=left,top,width,height". E.g. "targetFace=10,10,100,100". If there is more than one face in the
// image, targetFace is required to specify which face to add. No targetFace means there is only one face detected
// in the entire image.
func (client PersonGroupPersonClient) AddPersonFaceFromStream(ctx context.Context, personGroupID string, personID uuid.UUID, imageParameter io.ReadCloser, userData string, targetFace []int32) (result PersistedFace, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
		{TargetValue: userData,
			Constraints: []validation.Constraint{{Target: "userData", Name: validation.MaxLength, Rule: 1024, Chain: nil}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "AddPersonFaceFromStream", err.Error())
	}

	req, err := client.AddPersonFaceFromStreamPreparer(ctx, personGroupID, personID, imageParameter, userData, targetFace)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "AddPersonFaceFromStream", nil, "Failure preparing request")
		return
	}

	resp, err := client.AddPersonFaceFromStreamSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "AddPersonFaceFromStream", resp, "Failure sending request")
		return
	}

	result, err = client.AddPersonFaceFromStreamResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "AddPersonFaceFromStream", resp, "Failure responding to request")
	}

	return
}

// AddPersonFaceFromStreamPreparer prepares the AddPersonFaceFromStream request.
func (client PersonGroupPersonClient) AddPersonFaceFromStreamPreparer(ctx context.Context, personGroupID string, personID uuid.UUID, imageParameter io.ReadCloser, userData string, targetFace []int32) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"personGroupId": autorest.Encode("path", personGroupID),
		"personId":      autorest.Encode("path", personID),
	}

	queryParameters := map[string]interface{}{}
	if len(userData) > 0 {
		queryParameters["userData"] = autorest.Encode("query", userData)
	}
	if targetFace != nil && len(targetFace) > 0 {
		queryParameters["targetFace"] = autorest.Encode("query", targetFace, ",")
	}

	preparer := autorest.CreatePreparer(
		autorest.AsOctetStream(),
		autorest.AsPost(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces", pathParameters),
		autorest.WithFile(imageParameter),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// AddPersonFaceFromStreamSender sends the AddPersonFaceFromStream request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) AddPersonFaceFromStreamSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// AddPersonFaceFromStreamResponder handles the response to the AddPersonFaceFromStream request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) AddPersonFaceFromStreamResponder(resp *http.Response) (result PersistedFace, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// AddPersonFaceFromURL add a representative face to a person for identification. The input face is specified as an
// image with a targetFace rectangle.
//
// personGroupID is id referencing a particular person group. personID is id referencing a particular person.
// imageURL is a JSON document with a URL pointing to the image that is to be analyzed. userData is user-specified
// data about the face for any purpose. The maximum length is 1KB. targetFace is a face rectangle to specify the
// target face to be added to a person in the format of "targetFace=left,top,width,height". E.g.
// "targetFace=10,10,100,100". If there is more than one face in the image, targetFace is required to specify which
// face to add. No targetFace means there is only one face detected in the entire image.
func (client PersonGroupPersonClient) AddPersonFaceFromURL(ctx context.Context, personGroupID string, personID uuid.UUID, imageURL ImageURL, userData string, targetFace []int32) (result PersistedFace, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
		{TargetValue: userData,
			Constraints: []validation.Constraint{{Target: "userData", Name: validation.MaxLength, Rule: 1024, Chain: nil}}},
		{TargetValue: imageURL,
			Constraints: []validation.Constraint{{Target: "imageURL.URL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "AddPersonFaceFromURL", err.Error())
	}

	req, err := client.AddPersonFaceFromURLPreparer(ctx, personGroupID, personID, imageURL, userData, targetFace)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "AddPersonFaceFromURL", nil, "Failure preparing request")
		return
	}

	resp, err := client.AddPersonFaceFromURLSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "AddPersonFaceFromURL", resp, "Failure sending request")
		return
	}

	result, err = client.AddPersonFaceFromURLResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "AddPersonFaceFromURL", resp, "Failure responding to request")
	}

	return
}

// AddPersonFaceFromURLPreparer prepares the AddPersonFaceFromURL request.
func (client PersonGroupPersonClient) AddPersonFaceFromURLPreparer(ctx context.Context, personGroupID string, personID uuid.UUID, imageURL ImageURL, userData string, targetFace []int32) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"personGroupId": autorest.Encode("path", personGroupID),
		"personId":      autorest.Encode("path", personID),
	}

	queryParameters := map[string]interface{}{}
	if len(userData) > 0 {
		queryParameters["userData"] = autorest.Encode("query", userData)
	}
	if targetFace != nil && len(targetFace) > 0 {
		queryParameters["targetFace"] = autorest.Encode("query", targetFace, ",")
	}

	preparer := autorest.CreatePreparer(
		autorest.AsJSON(),
		autorest.AsPost(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces", pathParameters),
		autorest.WithJSON(imageURL),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// AddPersonFaceFromURLSender sends the AddPersonFaceFromURL request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) AddPersonFaceFromURLSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// AddPersonFaceFromURLResponder handles the response to the AddPersonFaceFromURL request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) AddPersonFaceFromURLResponder(resp *http.Response) (result PersistedFace, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Create create a new person in a specified person group.
//
// personGroupID is id referencing a particular person group. body is request body for creating new person.
func (client PersonGroupPersonClient) Create(ctx context.Context, personGroupID string, body NameAndUserDataContract) (result Person, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
		{TargetValue: body,
			Constraints: []validation.Constraint{{Target: "body.Name", Name: validation.Null, Rule: false,
				Chain: []validation.Constraint{{Target: "body.Name", Name: validation.MaxLength, Rule: 128, Chain: nil}}},
				{Target: "body.UserData", Name: validation.Null, Rule: false,
					Chain: []validation.Constraint{{Target: "body.UserData", Name: validation.MaxLength, Rule: 16384, Chain: nil}}}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "Create", err.Error())
	}

	req, err := client.CreatePreparer(ctx, personGroupID, body)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Create", nil, "Failure preparing request")
		return
	}

	resp, err := client.CreateSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Create", resp, "Failure sending request")
		return
	}

	result, err = client.CreateResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Create", resp, "Failure responding to request")
	}

	return
}

// CreatePreparer prepares the Create request.
func (client PersonGroupPersonClient) CreatePreparer(ctx context.Context, personGroupID string, body NameAndUserDataContract) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"personGroupId": autorest.Encode("path", personGroupID),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsJSON(),
		autorest.AsPost(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons", pathParameters),
		autorest.WithJSON(body))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) CreateSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) CreateResponder(resp *http.Response) (result Person, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Delete delete an existing person from a person group. Persisted face images of the person will also be deleted.
//
// personGroupID is id referencing a particular person group. personID is id referencing a particular person.
func (client PersonGroupPersonClient) Delete(ctx context.Context, personGroupID string, personID uuid.UUID) (result autorest.Response, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "Delete", err.Error())
	}

	req, err := client.DeletePreparer(ctx, personGroupID, personID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Delete", nil, "Failure preparing request")
		return
	}

	resp, err := client.DeleteSender(req)
	if err != nil {
		result.Response = resp
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Delete", resp, "Failure sending request")
		return
	}

	result, err = client.DeleteResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Delete", resp, "Failure responding to request")
	}

	return
}

// DeletePreparer prepares the Delete request.
func (client PersonGroupPersonClient) DeletePreparer(ctx context.Context, personGroupID string, personID uuid.UUID) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"personGroupId": autorest.Encode("path", personGroupID),
		"personId":      autorest.Encode("path", personID),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) DeleteSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())
	result.Response = resp
	return
}

// DeleteFace delete a face from a person. Relative image for the persisted face will also be deleted.
//
// personGroupID is id referencing a particular person group. personID is id referencing a particular person.
// persistedFaceID is id referencing a particular persistedFaceId of an existing face.
func (client PersonGroupPersonClient) DeleteFace(ctx context.Context, personGroupID string, personID uuid.UUID, persistedFaceID uuid.UUID) (result autorest.Response, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "DeleteFace", err.Error())
	}

	req, err := client.DeleteFacePreparer(ctx, personGroupID, personID, persistedFaceID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "DeleteFace", nil, "Failure preparing request")
		return
	}

	resp, err := client.DeleteFaceSender(req)
	if err != nil {
		result.Response = resp
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "DeleteFace", resp, "Failure sending request")
		return
	}

	result, err = client.DeleteFaceResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "DeleteFace", resp, "Failure responding to request")
	}

	return
}

// DeleteFacePreparer prepares the DeleteFace request.
func (client PersonGroupPersonClient) DeleteFacePreparer(ctx context.Context, personGroupID string, personID uuid.UUID, persistedFaceID uuid.UUID) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"persistedFaceId": autorest.Encode("path", persistedFaceID),
		"personGroupId":   autorest.Encode("path", personGroupID),
		"personId":        autorest.Encode("path", personID),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DeleteFaceSender sends the DeleteFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) DeleteFaceSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// DeleteFaceResponder handles the response to the DeleteFace request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) DeleteFaceResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())
	result.Response = resp
	return
}

// Get retrieve a person's information, including registered persisted faces, name and userData.
//
// personGroupID is id referencing a particular person group. personID is id referencing a particular person.
func (client PersonGroupPersonClient) Get(ctx context.Context, personGroupID string, personID uuid.UUID) (result Person, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "Get", err.Error())
	}

	req, err := client.GetPreparer(ctx, personGroupID, personID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Get", resp, "Failure responding to request")
	}

	return
}

// GetPreparer prepares the Get request.
func (client PersonGroupPersonClient) GetPreparer(ctx context.Context, personGroupID string, personID uuid.UUID) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"personGroupId": autorest.Encode("path", personGroupID),
		"personId":      autorest.Encode("path", personID),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) GetSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) GetResponder(resp *http.Response) (result Person, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// GetFace retrieve information about a persisted face (specified by persistedFaceId, personId and its belonging
// personGroupId).
//
// personGroupID is id referencing a particular person group. personID is id referencing a particular person.
// persistedFaceID is id referencing a particular persistedFaceId of an existing face.
func (client PersonGroupPersonClient) GetFace(ctx context.Context, personGroupID string, personID uuid.UUID, persistedFaceID uuid.UUID) (result PersistedFace, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "GetFace", err.Error())
	}

	req, err := client.GetFacePreparer(ctx, personGroupID, personID, persistedFaceID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "GetFace", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetFaceSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "GetFace", resp, "Failure sending request")
		return
	}

	result, err = client.GetFaceResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "GetFace", resp, "Failure responding to request")
	}

	return
}

// GetFacePreparer prepares the GetFace request.
func (client PersonGroupPersonClient) GetFacePreparer(ctx context.Context, personGroupID string, personID uuid.UUID, persistedFaceID uuid.UUID) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"persistedFaceId": autorest.Encode("path", persistedFaceID),
		"personGroupId":   autorest.Encode("path", personGroupID),
		"personId":        autorest.Encode("path", personID),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetFaceSender sends the GetFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) GetFaceSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// GetFaceResponder handles the response to the GetFace request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) GetFaceResponder(resp *http.Response) (result PersistedFace, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// List list all persons in a person group, and retrieve person information (including personId, name, userData and
// persistedFaceIds of registered faces of the person).
//
// personGroupID is id referencing a particular person group. start is starting person id to return (used to list a
// range of persons). top is number of persons to return starting with the person id indicated by the 'start'
// parameter.
func (client PersonGroupPersonClient) List(ctx context.Context, personGroupID string, start string, top *int32) (result ListPerson, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}},
		{TargetValue: top,
			Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false,
				Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: 1000, Chain: nil},
					{Target: "top", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
				}}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "List", err.Error())
	}

	req, err := client.ListPreparer(ctx, personGroupID, start, top)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "List", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "List", resp, "Failure sending request")
		return
	}

	result, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "List", resp, "Failure responding to request")
	}

	return
}

// ListPreparer prepares the List request.
func (client PersonGroupPersonClient) ListPreparer(ctx context.Context, personGroupID string, start string, top *int32) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"personGroupId": autorest.Encode("path", personGroupID),
	}

	queryParameters := map[string]interface{}{}
	if len(start) > 0 {
		queryParameters["start"] = autorest.Encode("query", start)
	}
	if top != nil {
		queryParameters["top"] = autorest.Encode("query", *top)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) ListSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) ListResponder(resp *http.Response) (result ListPerson, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result.Value),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Update update name or userData of a person.
//
// personGroupID is id referencing a particular person group. personID is id referencing a particular person. body
// is request body for person update operation.
func (client PersonGroupPersonClient) Update(ctx context.Context, personGroupID string, personID uuid.UUID, body NameAndUserDataContract) (result autorest.Response, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "Update", err.Error())
	}

	req, err := client.UpdatePreparer(ctx, personGroupID, personID, body)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Update", nil, "Failure preparing request")
		return
	}

	resp, err := client.UpdateSender(req)
	if err != nil {
		result.Response = resp
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Update", resp, "Failure sending request")
		return
	}

	result, err = client.UpdateResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "Update", resp, "Failure responding to request")
	}

	return
}

// UpdatePreparer prepares the Update request.
func (client PersonGroupPersonClient) UpdatePreparer(ctx context.Context, personGroupID string, personID uuid.UUID, body NameAndUserDataContract) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"personGroupId": autorest.Encode("path", personGroupID),
		"personId":      autorest.Encode("path", personID),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsJSON(),
		autorest.AsPatch(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters),
		autorest.WithJSON(body))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) UpdateSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())
	result.Response = resp
	return
}

// UpdateFace update a person persisted face's userData field.
//
// personGroupID is id referencing a particular person group. personID is id referencing a particular person.
// persistedFaceID is id referencing a particular persistedFaceId of an existing face. body is request body for
// updating persisted face.
func (client PersonGroupPersonClient) UpdateFace(ctx context.Context, personGroupID string, personID uuid.UUID, persistedFaceID uuid.UUID, body UpdatePersonFaceRequest) (result autorest.Response, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: personGroupID,
			Constraints: []validation.Constraint{{Target: "personGroupID", Name: validation.MaxLength, Rule: 64, Chain: nil},
				{Target: "personGroupID", Name: validation.Pattern, Rule: `^[a-z0-9-_]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("face.PersonGroupPersonClient", "UpdateFace", err.Error())
	}

	req, err := client.UpdateFacePreparer(ctx, personGroupID, personID, persistedFaceID, body)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "UpdateFace", nil, "Failure preparing request")
		return
	}

	resp, err := client.UpdateFaceSender(req)
	if err != nil {
		result.Response = resp
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "UpdateFace", resp, "Failure sending request")
		return
	}

	result, err = client.UpdateFaceResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "face.PersonGroupPersonClient", "UpdateFace", resp, "Failure responding to request")
	}

	return
}

// UpdateFacePreparer prepares the UpdateFace request.
func (client PersonGroupPersonClient) UpdateFacePreparer(ctx context.Context, personGroupID string, personID uuid.UUID, persistedFaceID uuid.UUID, body UpdatePersonFaceRequest) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"AzureRegion": client.AzureRegion,
	}

	pathParameters := map[string]interface{}{
		"persistedFaceId": autorest.Encode("path", persistedFaceID),
		"personGroupId":   autorest.Encode("path", personGroupID),
		"personId":        autorest.Encode("path", personID),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsJSON(),
		autorest.AsPatch(),
		autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
		autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters),
		autorest.WithJSON(body))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// UpdateFaceSender sends the UpdateFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonGroupPersonClient) UpdateFaceSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// UpdateFaceResponder handles the response to the UpdateFace request. The method always
// closes the http.Response Body.
func (client PersonGroupPersonClient) UpdateFaceResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())
	result.Response = resp
	return
}


text:
"""Adds the `buildozer` and `meta-rename` goals to automate changes to BUILD files."""

from pants.goal.task_registrar import TaskRegistrar as task

from pants.contrib.buildrefactor.buildozer import Buildozer
from pants.contrib.buildrefactor.meta_rename import MetaRename

def register_goals():
    task(name="buildozer", action=Buildozer).install("buildozer")
    task(name="meta-rename", action=MetaRename).install("meta-rename")

redpajama_set_name: RedPajamaGithub


text:
Mime::Type.register "application/vnd.google-earth.kml+xml", :kml
Mime::Type.register "application/xml.georss", :georss


text:
Imports Microsoft.VisualBasic
Namespace Utilities
    Public Class Util
        Public arr_FCColors(20) As String
        Public FC_ColorCounter As Integer
        Public Sub New()
            'This page contains an array of colors to be used as default set of colors for FusionCharts
            'arr_FCColors is the array that would contain the hex code of colors
            'ALL COLORS HEX CODES TO BE USED WITHOUT #

            'We also initiate a counter variable to help us cyclically rotate through
            'the array of colors.
            FC_ColorCounter = 0

            arr_FCColors(0) = "1941A5" 'Dark Blue
            arr_FCColors(1) = "AFD8F8"
            arr_FCColors(2) = "F6BD0F"
            arr_FCColors(3) = "8BBA00"
            arr_FCColors(4) = "A66EDD"
            arr_FCColors(5) = "F984A1"
            arr_FCColors(6) = "CCCC00" 'Chrome Yellow+Green
            arr_FCColors(7) = "999999" 'Grey
            arr_FCColors(8) = "0099CC" 'Blue Shade
            arr_FCColors(9) = "FF0000" 'Bright Red
            arr_FCColors(10) = "006F00" 'Dark Green
            arr_FCColors(11) = "0099FF" 'Blue (Light)
            arr_FCColors(12) = "FF66CC" 'Dark Pink
            arr_FCColors(13) = "669966" 'Dirty green
            arr_FCColors(14) = "7C7CB4" 'Violet shade of blue
            arr_FCColors(15) = "FF9933" 'Orange
            arr_FCColors(16) = "9900FF" 'Violet
            arr_FCColors(17) = "99FFCC" 'Blue+Green Light
            arr_FCColors(18) = "CCCCFF" 'Light violet
            arr_FCColors(19) = "669900" 'Shade of green
        End Sub

        'getFCColor method helps return a color from arr_FCColors array. It uses
        'cyclic iteration to return a color from a given index. The index value is
        'maintained in FC_ColorCounter

        Public Function getFCColor() As String
            'Update index
            FC_ColorCounter = FC_ColorCounter + 1
            'Return color
            Return arr_FCColors(FC_ColorCounter Mod UBound(arr_FCColors))
        End Function

    End Class
End Namespace


text:
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="{{ site.description }}">
	{% include ogmeta.html %}

	{% if site.altmetric == true %}

	{% include altmetric.html %}

	{% endif %}

	<link rel='shortcut icon' type='image/png' href='{{ site.baseurl }}/favicon.png' />

    <title>{% if page.title %}{{ page.title }} - {{ site.title }}{% else %}{{ site.title }}{% endif %}</title>

    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="{{ "/css/bootstrap.min.css" | prepend: site.baseurl | prepend: site.url }}">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="{{ "/css/clean-blog.css" | prepend: site.baseurl | prepend: site.url }}">

	<!-- Adjust Colors -->
    <link rel="stylesheet" href="{{ "/colorscheme.css" | prepend: site.baseurl | prepend: site.url }}">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="{{ "/css/syntax.css" | prepend: site.baseurl | prepend: site.url }}">

    <!-- Custom Fonts -->
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
	<!-- Math Jax -->
	<script type="text/x-mathjax-config">
	MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
	</script>
	<!-- <script type="text/javascript"
	src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
	</script> -->
  <script type="text/javascript"
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
  </script>
	<script type="text/x-mathjax-config">
	MathJax.Hub.Config({
		TeX: { equationNumbers: { autoNumber: "AMS" } }
	});
	</script>

	<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3.min.js" type="text/javascript"></script>-->

    <!-- jQuery -->
	<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

	<!-- Bootstrap Core JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

	<!-- Custom Theme JavaScript -->
	<script src="{{ "/js/clean-blog.min.js " | prepend: site.baseurl | prepend: site.url }}"></script>

	{% include analytics.html %}

</head>


text:
import DS from "ember-data";
import Ember from "ember";

export default DS.Model.extend( {
    active: DS.attr("boolean"),
    title: DS.attr("string"),
    picture: DS.attr("string"),
    description: DS.attr("string"),
    persistent: DS.attr("boolean"),
    year: DS.belongsTo("year", { async: true }),

    shortTitle: Ember.computed("title", function() {
        if (this.get("title")) {
            return this.get("title").substring(0,3) + ".";
        } else {
            return "";
        }
    })
});


text:
<title>Integer Comparisons - GNU MP 6.1.0</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="description" content="How to install and use the GNU multiple precision arithmetic library, version 6.1.0.">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Integer-Functions.html#Integer-Functions" title="Integer Functions">
<link rel="prev" href="Number-Theoretic-Functions.html#Number-Theoretic-Functions" title="Number Theoretic Functions">
<link rel="next" href="Integer-Logic-and-Bit-Fiddling.html#Integer-Logic-and-Bit-Fiddling" title="Integer Logic and Bit Fiddling">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Integer Logic and Bit Fiddling,
Previous: Number Theoretic Functions,
Up: Integer Functions

5.10 Comparison Functions

— Function: int mpz_cmp (<var>const mpz_t op1, const mpz_t op2</var>)<var></var>

— Function: int mpz_cmp_d (<var>const mpz_t op1, double op2</var>)<var></var>

— Macro: int mpz_cmp_si (<var>const mpz_t op1, signed long int op2</var>)<var></var>

— Macro: int mpz_cmp_ui (<var>const mpz_t op1, unsigned long int op2</var>)<var></var>

Compare <var>op1</var> and <var>op2</var>.  Return a positive value if <var>op1</var> >
<var>op2</var>, zero if <var>op1</var> = <var>op2</var>, or a negative value if
<var>op1</var> < <var>op2</var>.

mpz_cmp_ui and mpz_cmp_si are macros and will evaluate their
arguments more than once.  mpz_cmp_d can be called with an infinity,
but results are undefined for a NaN.

— Function: int mpz_cmpabs (<var>const mpz_t op1, const mpz_t op2</var>)<var></var>

— Function: int mpz_cmpabs_d (<var>const mpz_t op1, double op2</var>)<var></var>

— Function: int mpz_cmpabs_ui (<var>const mpz_t op1, unsigned long int op2</var>)<var></var>

Compare the absolute values of <var>op1</var> and <var>op2</var>.  Return a positive
value if abs(<var>op1</var>) > abs(<var>op2</var>), zero if
abs(<var>op1</var>) = abs(<var>op2</var>), or a negative value if
abs(<var>op1</var>) < abs(<var>op2</var>).

mpz_cmpabs_d can be called with an infinity, but results are undefined
for a NaN.

— Macro: int mpz_sgn (<var>const mpz_t op</var>)<var></var>

Return +1 if <var>op</var> > 0, 0 if <var>op</var> = 0, and
-1 if <var>op</var> < 0.

This function is actually implemented as a macro.  It evaluates its argument
multiple times.


text:
package org.midao.jdbc.core.db.oracle;

import org.midao.jdbc.core.MjdbcFactory;
import org.midao.jdbc.core.db.DBBatch;
import org.midao.jdbc.core.db.DBBatchQueryStructure;
import org.midao.jdbc.core.db.DBConstants;
import org.midao.jdbc.core.db.QueryStructure;
import org.midao.jdbc.core.service.QueryRunnerService;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 */
public class BatchTest extends BaseOracle {
    public void testUpdateWithParams() throws SQLException {

        if (this.checkConnected(dbName) == false) {
            return;
        }

        QueryRunnerService runner = null;
        Map<String, Object> values = new HashMap<String, Object>();

        final QueryStructure defaultStructure = DBBatchQueryStructure.batchWParamsDS(values);

        QueryStructure structure = new QueryStructure(values) {

            @Override
            public void create(QueryRunnerService runner) throws SQLException {
                runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE);
                runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_SEQ);
                runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_TRG);
            }

            @Override
            public void execute(QueryRunnerService runner) throws SQLException {
                defaultStructure.execute(runner);
                //this.values.put("rowsUpdated", runner.batch(DBConstants.INSERT_STUDENT_TABLE_W_PARAMS_ORACLE, new Object[][] {new Object[] {"not me"}, new Object[] {"not me either"}}));
            }

            @Override
            public void drop(QueryRunnerService runner) throws SQLException {
                defaultStructure.drop(runner);
                runner.update(DBConstants.DROP_STUDENT_TABLE_ORACLE_SEQ);
            }

        };

        runner = MjdbcFactory.getQueryRunner(this.dataSource);

        DBBatch.batchWParamsDS(structure, runner);

        runner = MjdbcFactory.getQueryRunner(this.conn);

        DBBatch.batchWParamsDS(structure, runner);
    }

    public void testInputHandler1DS() throws SQLException {

        if (this.checkConnected(dbName) == false) {
            return;
        }

        QueryRunnerService runner = null;
        Map<String, Object> values = new HashMap<String, Object>();

        final QueryStructure defaultStructure = DBBatchQueryStructure.batchInputHandler1DS(values);

        QueryStructure structure = new QueryStructure(values) {

            @Override
            public void create(QueryRunnerService runner) throws SQLException {
                runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE);
                runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_SEQ);
                runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_TRG);
            }

            @Override
            public void execute(QueryRunnerService runner) throws SQLException {
                defaultStructure.execute(runner);
                /*
		        MapInputHandler[] inputs = new MapInputHandler[] {
		                new MapInputHandler(DBConstants.INSERT_NAMED_STUDENT_TABLE_ORACLE, new HashMap<String, Object>() {{put("studentName", "not me");}}),
		                new MapInputHandler(DBConstants.INSERT_NAMED_STUDENT_TABLE_ORACLE, new HashMap<String, Object>() {{put("studentName", "not me either");}})
		        };

		        this.values.put("rowsUpdated", runner.batch(inputs));
		        */
            }

            @Override
            public void drop(QueryRunnerService runner) throws SQLException {
                defaultStructure.drop(runner);
                runner.update(DBConstants.DROP_STUDENT_TABLE_ORACLE_SEQ);
            }

        };

        runner = MjdbcFactory.getQueryRunner(this.dataSource);

        DBBatch.batchInputHandler1DS(structure, runner);

        runner = MjdbcFactory.getQueryRunner(this.conn);

        DBBatch.batchInputHandler1DS(structure, runner);
    }
}


text:
    <title>Simple client</title>

<form onsubmit="onSubmit(); return false;">
    <input type="text" id="input">
    <input type="submit" value="Send">
    <button onclick="onCloseClick(); return false;">close</button>
</form>


text:
import sys
from model import *

def load_file(path):
    return scipy.sparse.csr_matrix(cPickle.load(open(path)),
            dtype=theano.config.floatX)

def convert2idx(spmat):
    rows, cols = spmat.nonzero()
    return rows[np.argsort(cols)]

def RankingEval(datapath='../data/', dataset='FB15k-test',
        loadmodel='best_valid_model.pkl', neval='all', Nsyn=14951, n=10,
        idx2synsetfile='FB15k_idx2entity.pkl'):

    # Load model
    f = open(loadmodel)
    embeddings = cPickle.load(f)
    leftop = cPickle.load(f)
    rightop = cPickle.load(f)
    simfn = cPickle.load(f)
    f.close()

    # Load data
    l = load_file(datapath + dataset + '-lhs.pkl')
    r = load_file(datapath + dataset + '-rhs.pkl')
    o = load_file(datapath + dataset + '-rel.pkl')
    if type(embeddings) is list:
        o = o[-embeddings[1].N:, :]

    # Convert sparse matrix to indexes
    if neval == 'all':
        idxl = convert2idx(l)
        idxr = convert2idx(r)
        idxo = convert2idx(o)
    else:
        idxl = convert2idx(l)[:neval]
        idxr = convert2idx(r)[:neval]
        idxo = convert2idx(o)[:neval]

    ranklfunc = RankLeftFnIdx(simfn, embeddings, leftop, rightop,
            subtensorspec=Nsyn)
    rankrfunc = RankRightFnIdx(simfn, embeddings, leftop, rightop,
            subtensorspec=Nsyn)

    res = RankingScoreIdx(ranklfunc, rankrfunc, idxl, idxr, idxo)
    dres = {}
    dres.update({'microlmean': np.mean(res[0])})
    dres.update({'microlmedian': np.median(res[0])})
    dres.update({'microlhits@n': np.mean(np.asarray(res[0]) <= n) * 100})
    dres.update({'micrormean': np.mean(res[1])})
    dres.update({'micrormedian': np.median(res[1])})
    dres.update({'microrhits@n': np.mean(np.asarray(res[1]) <= n) * 100})
    resg = res[0] + res[1]
    dres.update({'microgmean': np.mean(resg)})
    dres.update({'microgmedian': np.median(resg)})
    dres.update({'microghits@n': np.mean(np.asarray(resg) <= n) * 100})

    print "### MICRO:"
    print "\t-- left   >> mean: %s, median: %s, hits@%s: %s%%" % (
            round(dres['microlmean'], 5), round(dres['microlmedian'], 5),
            n, round(dres['microlhits@n'], 3))
    print "\t-- right  >> mean: %s, median: %s, hits@%s: %s%%" % (
            round(dres['micrormean'], 5), round(dres['micrormedian'], 5),
            n, round(dres['microrhits@n'], 3))
    print "\t-- global >> mean: %s, median: %s, hits@%s: %s%%" % (
            round(dres['microgmean'], 5), round(dres['microgmedian'], 5),
            n, round(dres['microghits@n'], 3))

    listrel = set(idxo)
    dictrelres = {}
    dictrellmean = {}
    dictrelrmean = {}
    dictrelgmean = {}
    dictrellmedian = {}
    dictrelrmedian = {}
    dictrelgmedian = {}
    dictrellrn = {}
    dictrelrrn = {}
    dictrelgrn = {}

    for i in listrel:
        dictrelres.update({i: [[], []]})

    for i, j in enumerate(res[0]):
        dictrelres[idxo[i]][0] += [j]

    for i, j in enumerate(res[1]):
        dictrelres[idxo[i]][1] += [j]

    for i in listrel:
        dictrellmean[i] = np.mean(dictrelres[i][0])
        dictrelrmean[i] = np.mean(dictrelres[i][1])
        dictrelgmean[i] = np.mean(dictrelres[i][0] + dictrelres[i][1])
        dictrellmedian[i] = np.median(dictrelres[i][0])
        dictrelrmedian[i] = np.median(dictrelres[i][1])
        dictrelgmedian[i] = np.median(dictrelres[i][0] + dictrelres[i][1])
        dictrellrn[i] = np.mean(np.asarray(dictrelres[i][0]) <= n) * 100
        dictrelrrn[i] = np.mean(np.asarray(dictrelres[i][1]) <= n) * 100
        dictrelgrn[i] = np.mean(np.asarray(dictrelres[i][0] +
                                           dictrelres[i][1]) <= n) * 100

    dres.update({'dictrelres': dictrelres})
    dres.update({'dictrellmean': dictrellmean})
    dres.update({'dictrelrmean': dictrelrmean})
    dres.update({'dictrelgmean': dictrelgmean})
    dres.update({'dictrellmedian': dictrellmedian})
    dres.update({'dictrelrmedian': dictrelrmedian})
    dres.update({'dictrelgmedian': dictrelgmedian})
    dres.update({'dictrellrn': dictrellrn})
    dres.update({'dictrelrrn': dictrelrrn})
    dres.update({'dictrelgrn': dictrelgrn})

    dres.update({'macrolmean': np.mean(dictrellmean.values())})
    dres.update({'macrolmedian': np.mean(dictrellmedian.values())})
    dres.update({'macrolhits@n': np.mean(dictrellrn.values())})
    dres.update({'macrormean': np.mean(dictrelrmean.values())})
    dres.update({'macrormedian': np.mean(dictrelrmedian.values())})
    dres.update({'macrorhits@n': np.mean(dictrelrrn.values())})
    dres.update({'macrogmean': np.mean(dictrelgmean.values())})
    dres.update({'macrogmedian': np.mean(dictrelgmedian.values())})
    dres.update({'macroghits@n': np.mean(dictrelgrn.values())})

    print "### MACRO:"
    print "\t-- left   >> mean: %s, median: %s, hits@%s: %s%%" % (
            round(dres['macrolmean'], 5), round(dres['macrolmedian'], 5),
            n, round(dres['macrolhits@n'], 3))
    print "\t-- right  >> mean: %s, median: %s, hits@%s: %s%%" % (
            round(dres['macrormean'], 5), round(dres['macrormedian'], 5),
            n, round(dres['macrorhits@n'], 3))
    print "\t-- global >> mean: %s, median: %s, hits@%s: %s%%" % (
            round(dres['macrogmean'], 5), round(dres['macrogmedian'], 5),
            n, round(dres['macroghits@n'], 3))

    return dres

def RankingEvalFil(datapath='../data/', dataset='umls-test', op='TransE',
        loadmodel='best_valid_model.pkl', fold=0, Nrel=26, Nsyn=135):

    # Load model
    if op == 'TATEC':
        f = open(loadmodel)
        embeddings = cPickle.load(f)
        leftopbi = cPickle.load(f)
        leftoptri = cPickle.load(f)
        rightopbi = cPickle.load(f)
        rightoptri = cPickle.load(f)
        f.close()
    else:
        f = open(loadmodel)
        embeddings = cPickle.load(f)
        leftop =cPickle.load(f)
        rightop =cPickle.load(f)
        f.close()

    # Load data
    l = load_file(datapath + dataset + '-test-lhs.pkl')
    r = load_file(datapath + dataset + '-test-rhs.pkl')
    o = load_file(datapath + dataset + '-test-rel.pkl')
    o = o[-Nrel:, :]

    tl = load_file(datapath + dataset + '-train-lhs.pkl')
    tr = load_file(datapath + dataset + '-train-rhs.pkl')
    to = load_file(datapath + dataset + '-train-rel.pkl')
    to = to[-Nrel:, :]

    vl = load_file(datapath + dataset + '-valid-lhs.pkl')
    vr = load_file(datapath + dataset + '-valid-rhs.pkl')
    vo = load_file(datapath + dataset + '-valid-rel.pkl')
    vo = vo[-Nrel:, :]

    idxl = convert2idx(l)
    idxr = convert2idx(r)
    idxo = convert2idx(o)
    idxtl = convert2idx(tl)
    idxtr = convert2idx(tr)
    idxto = convert2idx(to)
    idxvl = convert2idx(vl)
    idxvr = convert2idx(vr)
    idxvo = convert2idx(vo)

    if op == 'Bi':
        ranklfunc = RankLeftFnIdxBi(embeddings, leftop, rightop,
            subtensorspec=Nsyn)
        rankrfunc = RankRightFnIdxBi(embeddings, leftop, rightop,
            subtensorspec=Nsyn)
    elif op == 'Tri':
        ranklfunc = RankLeftFnIdxTri(embeddings, leftop, rightop,
            subtensorspec=Nsyn)
        rankrfunc = RankRightFnIdxTri(embeddings, leftop, rightop,
            subtensorspec=Nsyn)
    elif op == 'TATEC':
        ranklfunc = RankLeftFnIdxTATEC(embeddings, leftopbi, leftoptri, rightopbi, rightoptri,
            subtensorspec=Nsyn)
        rankrfunc = RankRightFnIdxTATEC(embeddings, leftopbi, leftoptri, rightopbi, rightoptri,
            subtensorspec=Nsyn)

    true_triples=np.concatenate([idxtl,idxvl,idxl,idxto,idxvo,idxo,idxtr,idxvr,idxr]).reshape(3,idxtl.shape[0]+idxvl.shape[0]+idxl.shape[0]).T

    restest = FilteredRankingScoreIdx(ranklfunc, rankrfunc, idxl, idxr, idxo, true_triples)
    T10 = np.mean(np.asarray(restest[0] + restest[1]) <= 10) * 100
    MR = np.mean(np.asarray(restest[0] + restest[1]))

    return MR, T10

if __name__ == '__main__':
    RankingEval(loadmodel=sys.argv[1])


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    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.
-->
<!DOCTYPE Test SYSTEM "test.dtd">
<!--
Author: Ilia A. Leviev
Version: $Revision: 1.2 $
-->
<Test
  ID="invokespecial1803"
  date-of-creation="2005-10-05"
  timeout="1"
  >
  <Author value="Ilia A. Leviev"/>
  <Description>
    Tests invokespecial java virtual machine instruction.
    The NoSuchMethodError is thrown if reference to method contains same name and argument
    that declare in class but with different argument.
    Name=test2, arg = byte, return type=int, expected arg type=int.
   Covered assertions assert_instr26a291 assert_const212 assert_const203 assert_const213 assert_instr26a321
</Description>

  <Source name="invokespecial1803p.j"/>
  <Source name="invokespecial1803pTest.j"/>
  <Runner ID="Runtime">
    <Param name="toRun" value="org.apache.harmony.vts.test.vm.jvms.instructions.invokeReturn.invokespecial.invokespecial18.invokespecial1803.invokespecial1803p"/>
  </Runner>
</Test>


text:
#include "TLSSocketWrapper.h"
#include "platform/Callback.h"
#include "drivers/Timer.h"
#include "events/mbed_events.h"

#define TRACE_GROUP "TLSW"
#include "mbed-trace/mbed_trace.h"
#include "mbedtls/debug.h"
#include "mbedtls/platform.h"
#include "mbed_error.h"
#include "Kernel.h"

// This class requires Mbed TLS SSL/TLS client code
#if defined(MBEDTLS_SSL_CLI_C)

TLSSocketWrapper::TLSSocketWrapper(Socket *transport, const char *hostname, control_transport control) :
    _transport(transport),
    _timeout(-1),
#ifdef MBEDTLS_X509_CRT_PARSE_C
    _cacert(NULL),
    _clicert(NULL),
#endif
    _ssl_conf(NULL),
    _connect_transport(control == TRANSPORT_CONNECT || control == TRANSPORT_CONNECT_AND_CLOSE),
    _close_transport(control == TRANSPORT_CLOSE || control == TRANSPORT_CONNECT_AND_CLOSE),
    _tls_initialized(false),
    _handshake_completed(false),
    _cacert_allocated(false),
    _clicert_allocated(false),
    _ssl_conf_allocated(false)
{
#if defined(MBEDTLS_PLATFORM_C)
    int ret = mbedtls_platform_setup(NULL);
    if (ret != 0) {
        print_mbedtls_error("mbedtls_platform_setup()", ret);
    }
#endif /* MBEDTLS_PLATFORM_C */
    mbedtls_entropy_init(&_entropy);
    mbedtls_ctr_drbg_init(&_ctr_drbg);
    mbedtls_ssl_init(&_ssl);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
    mbedtls_pk_init(&_pkctx);
#endif

    if (hostname) {
        set_hostname(hostname);
    }
}

TLSSocketWrapper::~TLSSocketWrapper()
{
    if (_transport) {
        close();
    }
    mbedtls_entropy_free(&_entropy);
    mbedtls_ctr_drbg_free(&_ctr_drbg);
    mbedtls_ssl_free(&_ssl);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
    mbedtls_pk_free(&_pkctx);
    set_own_cert(NULL);
    set_ca_chain(NULL);
#endif
    set_ssl_config(NULL);
#if defined(MBEDTLS_PLATFORM_C)
    mbedtls_platform_teardown(NULL);
#endif /* MBEDTLS_PLATFORM_C */
}

void TLSSocketWrapper::set_hostname(const char *hostname)
{
#ifdef MBEDTLS_X509_CRT_PARSE_C
    mbedtls_ssl_set_hostname(&_ssl, hostname);
#endif
}

nsapi_error_t TLSSocketWrapper::set_root_ca_cert(const void *root_ca, size_t len)
{
#if !defined(MBEDTLS_X509_CRT_PARSE_C)
    return NSAPI_ERROR_UNSUPPORTED;
#else
    mbedtls_x509_crt *crt;

    crt = new (std::nothrow) mbedtls_x509_crt;
    if (!crt) {
        return NSAPI_ERROR_NO_MEMORY;
    }

    mbedtls_x509_crt_init(crt);

    /* Parse CA certification */
    int ret;
    if ((ret = mbedtls_x509_crt_parse(crt, static_cast<const unsigned char *>(root_ca),
                                      len)) != 0) {
        print_mbedtls_error("mbedtls_x509_crt_parse", ret);
        mbedtls_x509_crt_free(crt);
        delete crt;
        return NSAPI_ERROR_PARAMETER;
    }
    set_ca_chain(crt);
    _cacert_allocated = true;
    return NSAPI_ERROR_OK;
#endif
}

nsapi_error_t TLSSocketWrapper::set_root_ca_cert(const char *root_ca_pem)
{
    return set_root_ca_cert(root_ca_pem, strlen(root_ca_pem) + 1);
}

nsapi_error_t TLSSocketWrapper::set_client_cert_key(const char *client_cert_pem, const char *client_private_key_pem)
{
    return set_client_cert_key(client_cert_pem, strlen(client_cert_pem) + 1, client_private_key_pem, strlen(client_private_key_pem) + 1);
}

nsapi_error_t TLSSocketWrapper::set_client_cert_key(const void *client_cert, size_t client_cert_len,
                                                    const void *client_private_key_pem, size_t client_private_key_len)
{
#if !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PK_C)
    return NSAPI_ERROR_UNSUPPORTED;
#else

    int ret;
    mbedtls_x509_crt *crt = new mbedtls_x509_crt;
    mbedtls_x509_crt_init(crt);
    if ((ret = mbedtls_x509_crt_parse(crt, static_cast<const unsigned char *>(client_cert),
                                      client_cert_len)) != 0) {
        print_mbedtls_error("mbedtls_x509_crt_parse", ret);
        mbedtls_x509_crt_free(crt);
        delete crt;
        return NSAPI_ERROR_PARAMETER;
    }
    mbedtls_pk_init(&_pkctx);
    if ((ret = mbedtls_pk_parse_key(&_pkctx, static_cast<const unsigned char *>(client_private_key_pem),
                                    client_private_key_len, NULL, 0)) != 0) {
        print_mbedtls_error("mbedtls_pk_parse_key", ret);
        mbedtls_x509_crt_free(crt);
        delete crt;
        return NSAPI_ERROR_PARAMETER;
    }
    set_own_cert(crt);
    _clicert_allocated = true;

    return NSAPI_ERROR_OK;
#endif /* MBEDTLS_X509_CRT_PARSE_C */
}

nsapi_error_t TLSSocketWrapper::start_handshake(bool first_call)
{
    const char DRBG_PERS[] = "mbed TLS client";
    int ret;

    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }

    if (_tls_initialized) {
        return continue_handshake();
    }

#ifdef MBEDTLS_X509_CRT_PARSE_C
    tr_info("Starting TLS handshake with %s", _ssl.hostname);
#else
    tr_info("Starting TLS handshake");
#endif
    /*
     * Initialize TLS-related stuf.
     */
    if ((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy,
                                     (const unsigned char *) DRBG_PERS,
                                     sizeof(DRBG_PERS))) != 0) {
        print_mbedtls_error("mbedtls_crt_drbg_init", ret);
        return NSAPI_ERROR_AUTH_FAILURE;
    }

    mbedtls_ssl_conf_rng(get_ssl_config(), mbedtls_ctr_drbg_random, &_ctr_drbg);

#if MBED_CONF_TLS_SOCKET_DEBUG_LEVEL > 0
    mbedtls_ssl_conf_verify(get_ssl_config(), my_verify, NULL);
    mbedtls_ssl_conf_dbg(get_ssl_config(), my_debug, NULL);
    mbedtls_debug_set_threshold(MBED_CONF_TLS_SOCKET_DEBUG_LEVEL);
#endif

    tr_debug("mbedtls_ssl_setup()");
    if ((ret = mbedtls_ssl_setup(&_ssl, get_ssl_config())) != 0) {
        print_mbedtls_error("mbedtls_ssl_setup", ret);
        return NSAPI_ERROR_AUTH_FAILURE;
    }

    _transport->set_blocking(false);
    _transport->sigio(mbed::callback(this, &TLSSocketWrapper::event));
    mbedtls_ssl_set_bio(&_ssl, this, ssl_send, ssl_recv, NULL);

    _tls_initialized = true;

    ret = continue_handshake();
    if (first_call) {
        if (ret == NSAPI_ERROR_ALREADY) {
            ret = NSAPI_ERROR_IN_PROGRESS; // If first call should return IN_PROGRESS
        }
        if (ret == NSAPI_ERROR_IS_CONNECTED) {
            ret = NSAPI_ERROR_OK;   // If we happened to complete the request on the first call, return OK.
        }
    }
    return ret;
}

nsapi_error_t TLSSocketWrapper::continue_handshake()
{
    int ret;

    if (_handshake_completed) {
        return NSAPI_ERROR_IS_CONNECTED;
    }

    if (!_tls_initialized) {
        return NSAPI_ERROR_NO_CONNECTION;
    }

    while (true) {
        ret = mbedtls_ssl_handshake(&_ssl);
        if (_timeout && (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE)) {
            uint32_t flag;
            flag = _event_flag.wait_any(1, _timeout);
            if (flag & osFlagsError) {
                break;
            }
        } else {
            break;
        }
    }

    if (ret < 0) {
        print_mbedtls_error("mbedtls_ssl_handshake", ret);
        if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
            return NSAPI_ERROR_ALREADY;
        } else {
            return NSAPI_ERROR_AUTH_FAILURE;
        }
    }

#ifdef MBEDTLS_X509_CRT_PARSE_C
    /* It also means the handshake is done, time to print info */
    tr_info("TLS connection to %s established", _ssl.hostname);
#else
    tr_info("TLS connection established");
#endif

#if defined(MBEDTLS_X509_CRT_PARSE_C) && defined(FEA_TRACE_SUPPORT)
    /* Prints the server certificate and verify it. */
    const size_t buf_size = 1024;
    char *buf = new char[buf_size];
    mbedtls_x509_crt_info(buf, buf_size, "\r    ",
                          mbedtls_ssl_get_peer_cert(&_ssl));
    tr_debug("Server certificate:\r\n%s\r\n", buf);

    uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl);
    if (flags != 0) {
        /* Verification failed. */
        mbedtls_x509_crt_verify_info(buf, buf_size, "\r  ! ", flags);
        tr_error("Certificate verification failed:\r\n%s", buf);
    } else {
        /* Verification succeeded. */
        tr_info("Certificate verification passed");
    }
    delete[] buf;
#endif

    _handshake_completed = true;
    return NSAPI_ERROR_IS_CONNECTED;
}

nsapi_error_t TLSSocketWrapper::send(const void *data, nsapi_size_t size)
{
    int ret;

    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }

    tr_debug("send %d", size);
    while (true) {
        if (!_handshake_completed) {
            ret = continue_handshake();
            if (ret != NSAPI_ERROR_IS_CONNECTED) {
                if (ret == NSAPI_ERROR_ALREADY) {
                    ret = NSAPI_ERROR_WOULD_BLOCK;
                }
                return ret;
            }
        }

        ret = mbedtls_ssl_write(&_ssl, (const unsigned char *) data, size);

        if (_timeout == 0) {
            break;
        } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == MBEDTLS_ERR_SSL_WANT_READ) {
            uint32_t flag;
            flag = _event_flag.wait_any(1, _timeout);
            if (flag & osFlagsError) {
                // Timeout break
                break;
            }
        } else {
            break;
        }
    }

    if (ret == MBEDTLS_ERR_SSL_WANT_WRITE ||
            ret == MBEDTLS_ERR_SSL_WANT_READ) {
        // translate to socket error
        return NSAPI_ERROR_WOULD_BLOCK;
    }

    if (ret < 0) {
        print_mbedtls_error("mbedtls_ssl_write", ret);
        return NSAPI_ERROR_DEVICE_ERROR;
    }
    return ret; // Assume "non negative errorcode" to be propagated from Socket layer
}

nsapi_size_or_error_t TLSSocketWrapper::sendto(const SocketAddress &, const void *data, nsapi_size_t size)
{
    // Ignore the SocketAddress
    return send(data, size);
}

nsapi_size_or_error_t TLSSocketWrapper::recv(void *data, nsapi_size_t size)
{
    int ret;

    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }

    while (true) {
        if (!_handshake_completed) {
            ret = continue_handshake();
            if (ret != NSAPI_ERROR_IS_CONNECTED) {
                if (ret == NSAPI_ERROR_ALREADY) {
                    ret = NSAPI_ERROR_WOULD_BLOCK;
                }
                return ret;
            }
        }

        ret = mbedtls_ssl_read(&_ssl, (unsigned char *) data, size);

        if (_timeout == 0) {
            break;
        } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == MBEDTLS_ERR_SSL_WANT_READ) {
            uint32_t flag;
            flag = _event_flag.wait_any(1, _timeout);
            if (flag & osFlagsError) {
                // Timeout break
                break;
            }
        } else {
            break;
        }
    }
    if (ret == MBEDTLS_ERR_SSL_WANT_WRITE ||
            ret == MBEDTLS_ERR_SSL_WANT_READ) {
        // translate to socket error
        return NSAPI_ERROR_WOULD_BLOCK;
    } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
        /* MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY is not considered as error.
         * Just ignore here. Once connection is closed, mbedtls_ssl_read()
         * will return 0.
         */
        return 0;
    } else if (ret < 0) {
        print_mbedtls_error("mbedtls_ssl_read", ret);
        // There is no mapping of TLS error codes to Socket API so return most generic error to application
        return NSAPI_ERROR_DEVICE_ERROR;
    }
    return ret;
}

nsapi_size_or_error_t TLSSocketWrapper::recvfrom(SocketAddress *address, void *data, nsapi_size_t size)
{
    if (address) {
        getpeername(address);
    }
    return recv(data, size);
}

void TLSSocketWrapper::print_mbedtls_error(MBED_UNUSED const char *name, MBED_UNUSED int err)
{
// Avoid pulling in mbedtls_strerror when trace is not enabled
#if defined FEA_TRACE_SUPPORT && defined MBEDTLS_ERROR_C
    char *buf = new char[128];
    mbedtls_strerror(err, buf, 128);
    tr_err("%s() failed: -0x%04x (%d): %s", name, -err, err, buf);
    delete[] buf;
#else
    tr_err("%s() failed: -0x%04x (%d)", name, -err, err);
#endif
}

#if MBED_CONF_TLS_SOCKET_DEBUG_LEVEL > 0

void TLSSocketWrapper::my_debug(void *ctx, int level, const char *file, int line,
                                const char *str)
{
    const char *p, *basename;
    (void) ctx;

    /* Extract basename from file */
    for (p = basename = file; *p != '\0'; p++) {
        if (*p == '/' || *p == '\\') {
            basename = p + 1;
        }
    }

    tr_debug("%s:%04d: |%d| %s", basename, line, level, str);
}

int TLSSocketWrapper::my_verify(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
{
    const uint32_t buf_size = 1024;
    char *buf = new char[buf_size];
    (void) data;

    tr_debug("\nVerifying certificate at depth %d:\n", depth);
    mbedtls_x509_crt_info(buf, buf_size - 1, "  ", crt);
    tr_debug("%s", buf);

    if (*flags == 0) {
        tr_info("No verification issue for this certificate\n");
    } else {
        mbedtls_x509_crt_verify_info(buf, buf_size, "  ! ", *flags);
        tr_info("%s\n", buf);
    }

    delete[] buf;

    return 0;
}

#endif /* MBED_CONF_TLS_SOCKET_DEBUG_LEVEL > 0 */

int TLSSocketWrapper::ssl_recv(void *ctx, unsigned char *buf, size_t len)
{
    int recv;

    TLSSocketWrapper *my = static_cast<TLSSocketWrapper *>(ctx);

    if (!my->_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }

    recv = my->_transport->recv(buf, len);

    if (NSAPI_ERROR_WOULD_BLOCK == recv) {
        return MBEDTLS_ERR_SSL_WANT_READ;
    } else if (recv < 0) {
        tr_error("Socket recv error %d", recv);
    }
    // Propagate also Socket errors to SSL, it allows negative error codes to be returned here.
    return recv;
}

int TLSSocketWrapper::ssl_send(void *ctx, const unsigned char *buf, size_t len)
{
    int size = -1;
    TLSSocketWrapper *my = static_cast<TLSSocketWrapper *>(ctx);

    if (!my->_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }

    size = my->_transport->send(buf, len);

    if (NSAPI_ERROR_WOULD_BLOCK == size) {
        return MBEDTLS_ERR_SSL_WANT_WRITE;
    } else if (size < 0) {
        tr_error("Socket send error %d", size);
    }
    // Propagate also Socket errors to SSL, it allows negative error codes to be returned here.
    return size;
}

#if defined(MBEDTLS_X509_CRT_PARSE_C)

mbedtls_x509_crt *TLSSocketWrapper::get_own_cert()
{
    return _clicert;
}

int TLSSocketWrapper::set_own_cert(mbedtls_x509_crt *crt)
{
    int ret = 0;
    if (_clicert && _clicert_allocated) {
        mbedtls_x509_crt_free(_clicert);
        delete _clicert;
        _clicert_allocated = false;
    }
    _clicert = crt;
    if (crt) {
        if ((ret = mbedtls_ssl_conf_own_cert(get_ssl_config(), _clicert, &_pkctx)) != 0) {
            print_mbedtls_error("mbedtls_ssl_conf_own_cert", ret);
        }
    }
    return ret;
}

mbedtls_x509_crt *TLSSocketWrapper::get_ca_chain()
{
    return _cacert;
}

void TLSSocketWrapper::set_ca_chain(mbedtls_x509_crt *crt)
{
    if (_cacert && _cacert_allocated) {
        mbedtls_x509_crt_free(_cacert);
        delete _cacert;
        _cacert_allocated = false;
    }
    _cacert = crt;
    tr_debug("mbedtls_ssl_conf_ca_chain()");
    mbedtls_ssl_conf_ca_chain(get_ssl_config(), _cacert, NULL);
}

#endif /* MBEDTLS_X509_CRT_PARSE_C */

mbedtls_ssl_config *TLSSocketWrapper::get_ssl_config()
{
    if (!_ssl_conf) {
        int ret;
        _ssl_conf = new mbedtls_ssl_config;
        mbedtls_ssl_config_init(_ssl_conf);
        _ssl_conf_allocated = true;

        if ((ret = mbedtls_ssl_config_defaults(_ssl_conf,
                                               MBEDTLS_SSL_IS_CLIENT,
                                               MBEDTLS_SSL_TRANSPORT_STREAM,
                                               MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
            print_mbedtls_error("mbedtls_ssl_config_defaults", ret);
            set_ssl_config(NULL);
            MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_NETWORK_STACK, MBED_ERROR_CODE_OUT_OF_MEMORY), "mbedtls_ssl_config_defaults() failed");
            return NULL;
        }
        /* It is possible to disable authentication by passing
         * MBEDTLS_SSL_VERIFY_NONE in the call to mbedtls_ssl_conf_authmode()
         */
        mbedtls_ssl_conf_authmode(get_ssl_config(), MBEDTLS_SSL_VERIFY_REQUIRED);
    }
    return _ssl_conf;
}

void TLSSocketWrapper::set_ssl_config(mbedtls_ssl_config *conf)
{
    if (_ssl_conf && _ssl_conf_allocated) {
        mbedtls_ssl_config_free(_ssl_conf);
        delete _ssl_conf;
        _ssl_conf_allocated = false;
    }
    _ssl_conf = conf;
}

mbedtls_ssl_context *TLSSocketWrapper::get_ssl_context()
{
    return &_ssl;
}

nsapi_error_t TLSSocketWrapper::close()
{
    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }

    tr_info("Closing TLS");

    int ret = 0;
    if (_handshake_completed) {
        _transport->set_blocking(true);
        ret = mbedtls_ssl_close_notify(&_ssl);
        if (ret) {
            print_mbedtls_error("mbedtls_ssl_close_notify", ret);
        }
        _handshake_completed = false;
    }

    if (_close_transport) {
        int ret2 = _transport->close();
        if (!ret) {
            ret = ret2;
        }
    }

    _transport = NULL;

    return ret;
}

nsapi_error_t TLSSocketWrapper::connect(const SocketAddress &address)
{
    nsapi_error_t ret = NSAPI_ERROR_OK;
    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }

    if (!is_handshake_started() && _connect_transport) {
        ret = _transport->connect(address);
        if (ret && ret != NSAPI_ERROR_IS_CONNECTED) {
            return ret;
        }
    }
    return start_handshake(ret == NSAPI_ERROR_OK);
}

nsapi_error_t TLSSocketWrapper::bind(const SocketAddress &address)
{
    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }
    return _transport->bind(address);
}

void TLSSocketWrapper::set_blocking(bool blocking)
{
    set_timeout(blocking ? -1 : 0);
}

void TLSSocketWrapper::set_timeout(int timeout)
{
    _timeout = timeout;
    if (!is_handshake_started() && timeout != -1 && _connect_transport) {
        // If we have not yet connected the transport, we need to modify its blocking mode as well.
        // After connection is initiated, it is already set to non blocking mode
        _transport->set_timeout(timeout);
    }
}

void TLSSocketWrapper::sigio(mbed::Callback<void()> func)
{
    if (!_transport) {
        return;
    }
    _sigio = func;
    _transport->sigio(mbed::callback(this, &TLSSocketWrapper::event));
}

nsapi_error_t TLSSocketWrapper::setsockopt(int level, int optname, const void *optval, unsigned optlen)
{
    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }
    return _transport->setsockopt(level, optname, optval, optlen);
}

nsapi_error_t TLSSocketWrapper::getsockopt(int level, int optname, void *optval, unsigned *optlen)
{
    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;
    }
    return _transport->getsockopt(level, optname, optval, optlen);
}

Socket *TLSSocketWrapper::accept(nsapi_error_t *err)
{
    if (err) {
        *err = NSAPI_ERROR_UNSUPPORTED;
    }
    return NULL;
}

nsapi_error_t TLSSocketWrapper::listen(int)
{
    return NSAPI_ERROR_UNSUPPORTED;
}

void TLSSocketWrapper::event()
{
    _event_flag.set(1);
    if (_sigio) {
        _sigio();
    }
}

bool TLSSocketWrapper::is_handshake_started() const
{
    return _tls_initialized;
}

nsapi_error_t TLSSocketWrapper::getpeername(SocketAddress *address)
{
    if (!_handshake_completed) {
        return NSAPI_ERROR_NO_CONNECTION;
    }
    return _transport->getpeername(address);
}

#endif /* MBEDTLS_SSL_CLI_C */


text:
// ***********************************************************************************
// Created by zbw911
// 创建于:2013年02月19日 15:01
//
// 修改于:2013年02月19日 15:10
// 文件名:ICasClientConfigurationStorage.cs
//
// 如果有更好的建议或意见请邮件至zbw911#gmail.com
// ***********************************************************************************

using System;

namespace Dev.CasClient.Configuration
{
    /// <summary>
    ///   配置文件存储接口, zbw911
    /// </summary>
    public interface ICasClientConfigurationStorage
    {
        #region Instance Methods

        /// <summary>
        ///   取得
        /// </summary>
        /// <returns> </returns>
        CasClientConfiguration Get();

        /// <summary>
        ///   根据名称取得
        /// </summary>
        /// <param name="configname"> </param>
        /// <returns> </returns>
        CasClientConfiguration Get(string configname);

        /// <summary>
        ///   保存
        /// </summary>
        /// <param name="config"> </param>
        /// <returns> </returns>
        void Save(CasClientConfiguration config);

        /// <summary>
        /// </summary>
        /// <param name="config"> </param>
        /// <param name="configname"> </param>
        void Save(CasClientConfiguration config, string configname);

        #endregion

        #region Event Declarations

        /// <summary>
        ///   配置改变
        /// </summary>
        event EventHandler<EventArgs> ConfigChangedEvent;

        #endregion
    }
}