text:
package armsearch

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// ServicesClient contains the methods for the Services group.
// Don't use this type directly, use NewServicesClient() instead.
type ServicesClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewServicesClient creates a new instance of ServicesClient with the specified values.
// subscriptionID - The unique identifier for a Microsoft Azure subscription. You can obtain this value from the Azure Resource
// Manager API or the portal.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ServicesClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &ServicesClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// CheckNameAvailability - Checks whether or not the given search service name is available for use. Search service names
// must be globally unique since they are part of the service URI (https://.search.windows.net).
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2020-08-01
// checkNameAvailabilityInput - The resource name and type to check.
// SearchManagementRequestOptions - SearchManagementRequestOptions contains a group of parameters for the AdminKeysClient.Get
// method.
// options - ServicesClientCheckNameAvailabilityOptions contains the optional parameters for the ServicesClient.CheckNameAvailability
// method.
func (client *ServicesClient) CheckNameAvailability(ctx context.Context, checkNameAvailabilityInput CheckNameAvailabilityInput, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientCheckNameAvailabilityOptions) (ServicesClientCheckNameAvailabilityResponse, error) {
	req, err := client.checkNameAvailabilityCreateRequest(ctx, checkNameAvailabilityInput, searchManagementRequestOptions, options)
	if err != nil {
		return ServicesClientCheckNameAvailabilityResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientCheckNameAvailabilityResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientCheckNameAvailabilityResponse{}, runtime.NewResponseError(resp)
	}
	return client.checkNameAvailabilityHandleResponse(resp)
}

// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request.
func (client *ServicesClient) checkNameAvailabilityCreateRequest(ctx context.Context, checkNameAvailabilityInput CheckNameAvailabilityInput, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientCheckNameAvailabilityOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Search/checkNameAvailability"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2020-08-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if searchManagementRequestOptions != nil && searchManagementRequestOptions.ClientRequestID != nil {
		req.Raw().Header["x-ms-client-request-id"] = []string{*searchManagementRequestOptions.ClientRequestID}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, checkNameAvailabilityInput)
}

// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response.
func (client *ServicesClient) checkNameAvailabilityHandleResponse(resp *http.Response) (ServicesClientCheckNameAvailabilityResponse, error) {
	result := ServicesClientCheckNameAvailabilityResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityOutput); err != nil {
		return ServicesClientCheckNameAvailabilityResponse{}, err
	}
	return result, nil
}

// BeginCreateOrUpdate - Creates or updates a search service in the given resource group. If the search service already exists,
// all properties will be updated with the given values.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2020-08-01
// resourceGroupName - The name of the resource group within the current subscription. You can obtain this value from the
// Azure Resource Manager API or the portal.
// searchServiceName - The name of the Azure Cognitive Search service to create or update. Search service names must only
// contain lowercase letters, digits or dashes, cannot use dash as the first two or last one characters,
// cannot contain consecutive dashes, and must be between 2 and 60 characters in length. Search service names must be globally
// unique since they are part of the service URI (https://.search.windows.net).
// You cannot change the service name after the service is created.
// service - The definition of the search service to create or update.
// SearchManagementRequestOptions - SearchManagementRequestOptions contains a group of parameters for the AdminKeysClient.Get
// method.
// options - ServicesClientBeginCreateOrUpdateOptions contains the optional parameters for the ServicesClient.BeginCreateOrUpdate
// method.
func (client *ServicesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, searchServiceName string, service Service, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientBeginCreateOrUpdateOptions) (*runtime.Poller[ServicesClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, searchServiceName, service, searchManagementRequestOptions, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[ServicesClientCreateOrUpdateResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[ServicesClientCreateOrUpdateResponse](options.ResumeToken, client.pl, nil)
	}
}

// CreateOrUpdate - Creates or updates a search service in the given resource group. If the search service already exists,
// all properties will be updated with the given values.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2020-08-01
func (client *ServicesClient) createOrUpdate(ctx context.Context, resourceGroupName string, searchServiceName string, service Service, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, searchServiceName, service, searchManagementRequestOptions, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *ServicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, service Service, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if searchServiceName == "" {
		return nil, errors.New("parameter searchServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2020-08-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if searchManagementRequestOptions != nil && searchManagementRequestOptions.ClientRequestID != nil {
		req.Raw().Header["x-ms-client-request-id"] = []string{*searchManagementRequestOptions.ClientRequestID}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, service)
}

// Delete - Deletes a search service in the given resource group, along with its associated resources.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2020-08-01
// resourceGroupName - The name of the resource group within the current subscription. You can obtain this value from the
// Azure Resource Manager API or the portal.
// searchServiceName - The name of the Azure Cognitive Search service associated with the specified resource group.
// SearchManagementRequestOptions - SearchManagementRequestOptions contains a group of parameters for the AdminKeysClient.Get
// method.
// options - ServicesClientDeleteOptions contains the optional parameters for the ServicesClient.Delete method.
func (client *ServicesClient) Delete(ctx context.Context, resourceGroupName string, searchServiceName string, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientDeleteOptions) (ServicesClientDeleteResponse, error) {
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, searchServiceName, searchManagementRequestOptions, options)
	if err != nil {
		return ServicesClientDeleteResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent, http.StatusNotFound) {
		return ServicesClientDeleteResponse{}, runtime.NewResponseError(resp)
	}
	return ServicesClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *ServicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if searchServiceName == "" {
		return nil, errors.New("parameter searchServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2020-08-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if searchManagementRequestOptions != nil && searchManagementRequestOptions.ClientRequestID != nil {
		req.Raw().Header["x-ms-client-request-id"] = []string{*searchManagementRequestOptions.ClientRequestID}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets the search service with the given name in the given resource group.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2020-08-01
// resourceGroupName - The name of the resource group within the current subscription. You can obtain this value from the
// Azure Resource Manager API or the portal.
// searchServiceName - The name of the Azure Cognitive Search service associated with the specified resource group.
// SearchManagementRequestOptions - SearchManagementRequestOptions contains a group of parameters for the AdminKeysClient.Get
// method.
// options - ServicesClientGetOptions contains the optional parameters for the ServicesClient.Get method.
func (client *ServicesClient) Get(ctx context.Context, resourceGroupName string, searchServiceName string, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientGetOptions) (ServicesClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, searchServiceName, searchManagementRequestOptions, options)
	if err != nil {
		return ServicesClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *ServicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if searchServiceName == "" {
		return nil, errors.New("parameter searchServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2020-08-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if searchManagementRequestOptions != nil && searchManagementRequestOptions.ClientRequestID != nil {
		req.Raw().Header["x-ms-client-request-id"] = []string{*searchManagementRequestOptions.ClientRequestID}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *ServicesClient) getHandleResponse(resp *http.Response) (ServicesClientGetResponse, error) {
	result := ServicesClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Service); err != nil {
		return ServicesClientGetResponse{}, err
	}
	return result, nil
}

// NewListByResourceGroupPager - Gets a list of all search services in the given resource group.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2020-08-01
// resourceGroupName - The name of the resource group within the current subscription. You can obtain this value from the
// Azure Resource Manager API or the portal.
// SearchManagementRequestOptions - SearchManagementRequestOptions contains a group of parameters for the AdminKeysClient.Get
// method.
// options - ServicesClientListByResourceGroupOptions contains the optional parameters for the ServicesClient.ListByResourceGroup
// method.
func (client *ServicesClient) NewListByResourceGroupPager(resourceGroupName string, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientListByResourceGroupOptions) *runtime.Pager[ServicesClientListByResourceGroupResponse] {
	return runtime.NewPager(runtime.PagingHandler[ServicesClientListByResourceGroupResponse]{
		More: func(page ServicesClientListByResourceGroupResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ServicesClientListByResourceGroupResponse) (ServicesClientListByResourceGroupResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listByResourceGroupCreateRequest(ctx, resourceGroupName, searchManagementRequestOptions, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return ServicesClientListByResourceGroupResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return ServicesClientListByResourceGroupResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return ServicesClientListByResourceGroupResponse{}, runtime.NewResponseError(resp)
			}
			return client.listByResourceGroupHandleResponse(resp)
		},
	})
}

// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *ServicesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientListByResourceGroupOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2020-08-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if searchManagementRequestOptions != nil && searchManagementRequestOptions.ClientRequestID != nil {
		req.Raw().Header["x-ms-client-request-id"] = []string{*searchManagementRequestOptions.ClientRequestID}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *ServicesClient) listByResourceGroupHandleResponse(resp *http.Response) (ServicesClientListByResourceGroupResponse, error) {
	result := ServicesClientListByResourceGroupResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ServiceListResult); err != nil {
		return ServicesClientListByResourceGroupResponse{}, err
	}
	return result, nil
}

// NewListBySubscriptionPager - Gets a list of all search services in the given subscription.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2020-08-01
// SearchManagementRequestOptions - SearchManagementRequestOptions contains a group of parameters for the AdminKeysClient.Get
// method.
// options - ServicesClientListBySubscriptionOptions contains the optional parameters for the ServicesClient.ListBySubscription
// method.
func (client *ServicesClient) NewListBySubscriptionPager(searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientListBySubscriptionOptions) *runtime.Pager[ServicesClientListBySubscriptionResponse] {
	return runtime.NewPager(runtime.PagingHandler[ServicesClientListBySubscriptionResponse]{
		More: func(page ServicesClientListBySubscriptionResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ServicesClientListBySubscriptionResponse) (ServicesClientListBySubscriptionResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listBySubscriptionCreateRequest(ctx, searchManagementRequestOptions, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return ServicesClientListBySubscriptionResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return ServicesClientListBySubscriptionResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return ServicesClientListBySubscriptionResponse{}, runtime.NewResponseError(resp)
			}
			return client.listBySubscriptionHandleResponse(resp)
		},
	})
}

// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *ServicesClient) listBySubscriptionCreateRequest(ctx context.Context, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientListBySubscriptionOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Search/searchServices"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2020-08-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if searchManagementRequestOptions != nil && searchManagementRequestOptions.ClientRequestID != nil {
		req.Raw().Header["x-ms-client-request-id"] = []string{*searchManagementRequestOptions.ClientRequestID}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *ServicesClient) listBySubscriptionHandleResponse(resp *http.Response) (ServicesClientListBySubscriptionResponse, error) {
	result := ServicesClientListBySubscriptionResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ServiceListResult); err != nil {
		return ServicesClientListBySubscriptionResponse{}, err
	}
	return result, nil
}

// Update - Updates an existing search service in the given resource group.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2020-08-01
// resourceGroupName - The name of the resource group within the current subscription. You can obtain this value from the
// Azure Resource Manager API or the portal.
// searchServiceName - The name of the Azure Cognitive Search service to update.
// service - The definition of the search service to update.
// SearchManagementRequestOptions - SearchManagementRequestOptions contains a group of parameters for the AdminKeysClient.Get
// method.
// options - ServicesClientUpdateOptions contains the optional parameters for the ServicesClient.Update method.
func (client *ServicesClient) Update(ctx context.Context, resourceGroupName string, searchServiceName string, service ServiceUpdate, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientUpdateOptions) (ServicesClientUpdateResponse, error) {
	req, err := client.updateCreateRequest(ctx, resourceGroupName, searchServiceName, service, searchManagementRequestOptions, options)
	if err != nil {
		return ServicesClientUpdateResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientUpdateResponse{}, runtime.NewResponseError(resp)
	}
	return client.updateHandleResponse(resp)
}

// updateCreateRequest creates the Update request.
func (client *ServicesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, service ServiceUpdate, searchManagementRequestOptions *SearchManagementRequestOptions, options *ServicesClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if searchServiceName == "" {
		return nil, errors.New("parameter searchServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2020-08-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if searchManagementRequestOptions != nil && searchManagementRequestOptions.ClientRequestID != nil {
		req.Raw().Header["x-ms-client-request-id"] = []string{*searchManagementRequestOptions.ClientRequestID}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, service)
}

// updateHandleResponse handles the Update response.
func (client *ServicesClient) updateHandleResponse(resp *http.Response) (ServicesClientUpdateResponse, error) {
	result := ServicesClientUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Service); err != nil {
		return ServicesClientUpdateResponse{}, err
	}
	return result, nil
}


text:
file(REMOVE_RECURSE
  "Dolphin-memory-engine_automoc.cpp"
  "CMakeFiles/Dolphin-memory-engine_automoc"
)

# Per-language clean rules from dependency scanning.
foreach(lang )
  include(CMakeFiles/Dolphin-memory-engine_automoc.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

redpajama_set_name: RedPajamaGithub


text:
Whenever a PR job is run on the CI infrastructure (e.g. CircleCI), we want to build `angular.io`
and host the build artifacts on a publicly accessible server so that collaborators (developers,
designers, authors, etc) can preview the changes without having to checkout and build the app
locally.

## Source code
In order to make it easier to administer the server and version-control the setup, we are using
[docker](https://www.docker.com) to run a container on a VM. The Dockerfile and all other files
necessary for creating the docker container are stored (and versioned) along with the angular.io
project's source code (currently part of the angular/angular repo) in the `aio-builds-setup/`
directory.

## Setup
The VM is hosted on [Google Compute Engine](https://cloud.google.com/compute/). The host OS is
debian:jessie. For more info how to set up the host VM take a look at the "Setting up the VM"
section in [TOC](_TOC.md).

## Security model
Since we are managing a public server, it is important to take appropriate measures in order to
prevent abuse. For more details on the challenges and the chosen approach take a look at the
[security model](overview--security-model.md).

## The 10000 feet view
This section gives a brief summary of the several operations performed on CI and by the docker
container:

### On CI (CircleCI)
- Build job completes successfully.
- The CI script checks whether the build job was initiated by a PR against the angular/angular
  master branch.
- The CI script checks whether the PR has touched any files that might affect the angular.io app
  (currently the `aio/` or `packages/` directories, ignoring spec files).
- The CI script gzips and stores the build artifacts in the CI infrastructure.
- When the build completes CircleCI triggers a webhook on the preview-server.

More info on how to set things up on CI can be found [here](misc--integrate-with-ci.md).

### Hosting build artifacts

- nginx receives the webhook trigger and passes it through to the preview server.
- The preview-server makes a request to CircleCI for the URL of the AIO build artifacts.
- The preview-server makes a request to this URL to receive the artifact - failing if the size
  exceeds the specified max file size - and stores it in a temporary location.
- The preview-server runs several checks to determine whether the request should be accepted and
  whether it should be publicly accessible or stored for later verification (more details can be
  found [here](overview--security-model.md)).
- The preview-server changes the "visibility" of the associated PR, if necessary. For example, if
  builds for the same PR had been previously deployed as non-public and the current build has been
  automatically verified, all previous builds are made public as well.
  If the PR transitions from "non-public" to "public", the preview-server posts a comment on the
  corresponding PR on GitHub mentioning the SHAs and the links where the previews can be found.
- The preview-server verifies that it is not trying to overwrite an existing build.
- The preview-server deploys the artifacts to a sub-directory named after the PR number and the first
  few characters of the SHA: `<PR>/<SHA>/`
  (Non-publicly accessible PRs will be stored in a different location, but again derived from the PR
  number and SHA.)
- If the PR is publicly accessible, the preview-server posts a comment on the corresponding PR on
  GitHub mentioning the SHA and the link where the preview can be found.

More info on the possible HTTP status codes and their meaning can be found
[here](overview--http-status-codes.md).

### Updating PR visibility
- nginx receives a natification that a PR has been updated and passes it through to the
  preview-server. This could, for example, be sent by a GitHub webhook every time a PR's labels
  change.
  E.g.: `ngbuilds.io/pr-updated` (payload: `{"number":<PR>,"action":"labeled"}`)
- The request contains the PR number (as `number`) and optionally the action that triggered the
  request (as `action`) in the payload.
- The preview-server verifies the payload and determines whether the `action` (if specified) could
  have led to PR visibility changes. Only requests that omit the `action` field altogether or
  specify an action that can affect visibility are further processed.
  (Currently, the only actions that are considered capable of affecting visibility are `labeled` and
  `unlabeled`.)
- The preview-server re-checks and if necessary updates the PR's visibility.

More info on the possible HTTP status codes and their meaning can be found
[here](overview--http-status-codes.md).

### Serving build artifacts
- nginx receives a request for a hosted preview resource on a subdomain corresponding to the PR and SHA.
  E.g.: `pr<PR>-<SHA>.ngbuilds.io/path/to/resource`
- nginx maps the subdomain to the correct sub-directory and serves the resource.
  E.g.: `/<PR>/<SHA>/path/to/resource`

More info on the possible HTTP status codes and their meaning can be found
[here](overview--http-status-codes.md).

### Removing obsolete artifacts
In order to avoid flooding the disk with unnecessary build artifacts, there is a cronjob that runs a
clean-up tasks once a day. The task retrieves all open PRs from GitHub and removes all directories
that do not correspond with an open PR.

### Health-check
The docker service runs a periodic health-check that verifies the running conditions of the
container. This includes verifying the status of specific system services, the responsiveness of
nginx and the preview-server and internet connectivity.


text:
class Jbuilder
  def pagination!(results)
    _set_value :currentPage,  results.current_page
    _set_value :totalPages,   results.total_pages
    _set_value :totalEntries, results.total_entries
    _set_value :perPage,      results.per_page
  end
end


text:
hqDefine('registration/js/register_new_user', [
    'jquery',
    'knockout',
    'underscore',
    'registration/js/new_user.ko',
    'hqwebapp/js/initial_page_data',
    'analytix/js/kissmetrix',
    'registration/js/login',
], function (
    $,
    ko,
    _,
    newUser,
    initialPageData,
    kissmetrics
) {
    'use strict';

    $('#js-create-account').click(function (e) {
        e.preventDefault();
        $('#registration-choose-plan-container').hide();
        $('#registration-form-container').fadeIn();

        $('#back-to-start-btn').removeClass('hide');
    });

    $('#back-to-start-btn').click(function () {
        $('#registration-form-container').hide();
        $('#registration-choose-plan-container').fadeIn();
    });

    kissmetrics.whenReadyAlways(function () {

        $('#js-start-trial').click(function () {
            kissmetrics.track.event("Signup alt ux dec2018 - clicked start trial");
        });

        $('#js-get-tour').click(function () {
            kissmetrics.track.event("Signup alt ux dec2018 - clicked get a tour");
            kissmetrics.track.event("Demo Workflow - Get A Tour Button Clicked (new UX)");
        });

        $('#start-chat-cta-btn').click(function () {
            kissmetrics.track.event("Signup alt ux dec2018 - clicked start chat");
        });
    });

    newUser.setOnModuleLoad(function () {
        $('.loading-form-step').fadeOut(500, function () {
            $('.step-1').fadeIn(500);
        });
    });
    newUser.initRMI(initialPageData.reverse('process_registration'));
    if (!initialPageData.get('hide_password_feedback')) {
        newUser.showPasswordFeedback();
    }

    var regForm = newUser.formViewModel(
        initialPageData.get('reg_form_defaults'),
        '#registration-form-container',
        ['step-1', 'step-2', 'final-step']
    );
    $('#registration-form-container').koApplyBindings(regForm);

    // Email validation feedback
    newUser.setResetEmailFeedbackFn(function (isValidating) {
        var $email = $('#div_id_email');
        if (isValidating) {
            $email
                .removeClass('has-error has-success')
                .addClass('has-warning');
            $email
                .find('.form-control-feedback')
                .removeClass('fa-check fa-remove')
                .addClass('fa-spinner fa-spin');
        } else {
            var inputClass = 'has-error',
                iconClass = 'fa-remove';
            if (regForm.emailDelayed.isValid() && regForm.email.isValid()) {
                inputClass = 'has-success';
                iconClass = 'fa-check';
            }
            $email.removeClass('has-warning').addClass(inputClass);
            $email
                .find('.form-control-feedback')
                .removeClass('fa-spinner fa-spin')
                .addClass(iconClass);
        }
    });
    newUser.setPhoneNumberInput('#id_phone_number');

});


text:
package com.hazelcast.simulator.lettuce6.sync;

import com.hazelcast.simulator.lettuce6.LettuceTest;
import com.hazelcast.simulator.test.BaseThreadState;
import com.hazelcast.simulator.test.annotations.Prepare;
import com.hazelcast.simulator.test.annotations.Setup;
import com.hazelcast.simulator.test.annotations.TimeStep;
import io.lettuce.core.FlushMode;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.Random;

import static com.hazelcast.simulator.utils.GeneratorUtils.generateAsciiStrings;

public class StringStringSyncTest extends LettuceTest {

    // properties
    public int keyDomain = 10000;
    public int valueCount = 10000;
    public int minValueLength = 10;
    public int maxValueLength = 10;
    public boolean deleteAllData = true;

    private String[] values;

    @Setup
    public void setup() {
        values = generateAsciiStrings(valueCount, minValueLength, maxValueLength);
    }

    // loading the data is very inefficient. Needs some work in the future
    @Prepare(global = true)
    public void loadInitialData() {
        Random random = new Random();
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        RedisAsyncCommands async = connection.async();
        if (deleteAllData) {
            async.flushall(FlushMode.SYNC);
        }

        for (int k = 0; k < keyDomain; k++) {
            int r = random.nextInt(valueCount);
            async.set(Long.toString(k), values[r]);
        }

       async.flushCommands();
    }

    @TimeStep(prob = -1)
    public String get(ThreadState state) {
        return state.sync.get(state.randomKey());
    }

    @TimeStep(prob = 1)
    public String put(ThreadState state) {
        return state.sync.set(state.randomKey(), state.randomValue());
    }

    public class ThreadState extends BaseThreadState {
        final RedisCommands<String, String> sync;

        ThreadState() {
            StatefulRedisConnection<String, String> connection = redisClient.connect();
            sync = connection.sync();
        }

        private String randomKey() {
            return Long.toString(randomLong(keyDomain));
        }

        private String randomValue() {
            return values[randomInt(values.length)];
        }
    }
}


text:
.deckgrid[deckgrid]::before {
    /* Specifies that the grid should have a maximum of 4 columns. Each column will have the classes 'column' and 'column-1-4' */
    content: '4 .column.column-1-4';
    font-size: 0; /* See https://github.com/akoenig/angular-deckgrid/issues/14#issuecomment-35728861 */
    visibility: hidden;
}

.deckgrid .column {
    float: left;
}

.deckgrid .column-1-4 {
    width: 25%;
}


text:
package com.tingwa.utils;

import android.text.TextUtils;
import android.util.Log;

public class LogUtil {
    public static String tagPrefix = "bersaty";
    public static boolean showV = true;
    public static boolean showD = true;
    public static boolean showI = true;
    public static boolean showW = true;
    public static boolean showE = true;
    public static boolean showWTF = true;

    /**
     * 得到tag(所在类.方法(L:行))
     *
     * @return
     */
    private static String generateTag() {
        StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[4];
        String callerClazzName = stackTraceElement.getClassName();
        callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
        String tag = "%s.%s(L:%d)";
        tag = String.format(tag, new Object[]{callerClazzName, stackTraceElement.getMethodName(), Integer.valueOf(stackTraceElement.getLineNumber())});
        //给tag设置前缀
        tag = TextUtils.isEmpty(tagPrefix) ? tag : tagPrefix + ":" + tag;
        return tag;
    }

    public static void v(String msg) {
        if (showV) {
            String tag = generateTag();
            Log.v(tag, msg);
        }
    }

    public static void v(String msg, Throwable tr) {
        if (showV) {
            String tag = generateTag();
            Log.v(tag, msg, tr);
        }
    }

    public static void d(String msg) {
        if (showD) {
            String tag = generateTag();
            Log.d(tag, msg);
        }
    }

    public static void d(String msg, Throwable tr) {
        if (showD) {
            String tag = generateTag();
            Log.d(tag, msg, tr);
        }
    }

    public static void i(String msg) {
        if (showI) {
            String tag = generateTag();
            Log.i(tag, msg);
        }
    }

    public static void i(String msg, Throwable tr) {
        if (showI) {
            String tag = generateTag();
            Log.i(tag, msg, tr);
        }
    }

    public static void w(String msg) {
        if (showW) {
            String tag = generateTag();
            Log.w(tag, msg);
        }
    }

    public static void w(String msg, Throwable tr) {
        if (showW) {
            String tag = generateTag();
            Log.w(tag, msg, tr);
        }
    }

    public static void e(String msg) {
        if (showE) {
            String tag = generateTag();
            Log.e(tag, msg);
        }
    }

    public static void e(String msg, Throwable tr) {
        if (showE) {
            String tag = generateTag();
            Log.e(tag, msg, tr);
        }
    }

    public static void wtf(String msg) {
        if (showWTF) {
            String tag = generateTag();
            Log.wtf(tag, msg);
        }
    }

    public static void wtf(String msg, Throwable tr) {
        if (showWTF) {
            String tag = generateTag();
            Log.wtf(tag, msg, tr);
        }
    }
}


text:
"""

		Unit test cases.

"""

from __future__ import unicode_literals
import unittest
import os
import io
import logging
import logging.config

from simpletal import simpleTAL, simpleTALES

if (os.path.exists("logging.ini")):
    logging.config.fileConfig("logging.ini")
else:
    logging.basicConfig()

class TALForbiddenEndTagTestCases(unittest.TestCase):
    def setUp(self):
        self.context = simpleTALES.Context()
        self.context.addGlobal('test', 'testing')
        self.context.addGlobal('link', 'www.owlfish.com')
        self.context.addGlobal('scrWidth', '640')

    def _runTest_(self, txt, result, errMsg="Error"):
        template = simpleTAL.compileHTMLTemplate(txt)
        file = io.StringIO()
        template.expand(self.context, file)
        realResult = file.getvalue()
        self.assertEqual(
            realResult, result,
            "%s - \npassed in: %s \ngot back %s \nexpected %s\n\nTemplate: %s"
            % (errMsg, txt, realResult, result, template))

    def testAreaElement(self):
        self._runTest_('<area tal:attributes="href link"></area>',
                       '<area href="www.owlfish.com">',
                       "HTML Element AREA produced end tag.")

    def testBaseElement(self):
        self._runTest_('<base tal:attributes="href link"></base>',
                       '<base href="www.owlfish.com">',
                       "HTML Element BASE produced end tag.")

    def testBaseFontElement(self):
        self._runTest_(
            '<basefont tal:attributes="font test"></basefont>',
            '<basefont font="testing">',
            "HTML Element BASEFONT produced end tag.")

    def testBRElement(self):
        self._runTest_('

',
                       '
',
                       "HTML Element BR produced end tag.")

    def testColElement(self):
        self._runTest_(
            '<col tal:attributes="width scrWidth"></col>',
            '<col width="640">',
            "HTML Element COL produced end tag.")

    def testFrameElement(self):
        self._runTest_(
            '<frame tal:attributes="href link"></frame>',
            '<frame href="www.owlfish.com">',
            "HTML Element FRAME produced end tag.")

    def testHRElement(self):
        self._runTest_('

',
                       '
',
                       "HTML Element HR produced end tag.")

    def testImgElement(self):
        self._runTest_('',
                       '',
                       "HTML Element IMG produced end tag.")

    def testInputElement(self):
        self._runTest_(
            '<input tal:attributes="name test"></input>',
            '<input name="testing">',
            "HTML Element INPUT produced end tag.")

    def testIsIndexElement(self):
        self._runTest_(
            '<isindex tal:attributes="name test"></isindex>',
            '<isindex name="testing">',
            "HTML Element ISINDEX produced end tag.")

    def testLinkElement(self):
        self._runTest_('<link tal:attributes="href link"></link>',
                       '<link href="www.owlfish.com">',
                       "HTML Element LINK produced end tag.")

    def testMetaElement(self):
        self._runTest_('<meta tal:attributes="name test"></meta>',
                       '<meta name="testing">',
                       "HTML Element META produced end tag.")

    def testParamElement(self):
        self._runTest_(
            '<param tal:attributes="name test"></param>',
            '<param name="testing">',
            "HTML Element PARAM produced end tag.")

    # Same tests again, but with no end tag in the templates
    def testAreaElementNoClose(self):
        self._runTest_('<area tal:attributes="href link">',
                       '<area href="www.owlfish.com">',
                       "HTML Element AREA produced end tag.")

    def testBaseElementNoClose(self):
        self._runTest_('<base tal:attributes="href link">',
                       '<base href="www.owlfish.com">',
                       "HTML Element BASE produced end tag.")

    def testBaseFontElementNoClose(self):
        self._runTest_('<basefont tal:attributes="font test">',
                       '<basefont font="testing">',
                       "HTML Element BASEFONT produced end tag.")

    def testBRElementNoClose(self):
        self._runTest_('
',
                       '
',
                       "HTML Element BR produced end tag.")

    def testColElementNoClose(self):
        self._runTest_('<col tal:attributes="width scrWidth">',
                       '<col width="640">',
                       "HTML Element COL produced end tag.")

    def testFrameElementNoClose(self):
        self._runTest_('<frame tal:attributes="href link">',
                       '<frame href="www.owlfish.com">',
                       "HTML Element FRAME produced end tag.")

    def testHRElementNoClose(self):
        self._runTest_('
',
                       '
',
                       "HTML Element HR produced end tag.")

    def testImgElementNoClose(self):
        self._runTest_('',
                       '',
                       "HTML Element IMG produced end tag.")

    def testInputElementNoClose(self):
        self._runTest_('<input tal:attributes="name test">',
                       '<input name="testing">',
                       "HTML Element INPUT produced end tag.")

    def testIsIndexElementNoClose(self):
        self._runTest_('<isindex tal:attributes="name test">',
                       '<isindex name="testing">',
                       "HTML Element ISINDEX produced end tag.")

    def testLinkElementNoClose(self):
        self._runTest_('<link tal:attributes="href link">',
                       '<link href="www.owlfish.com">',
                       "HTML Element LINK produced end tag.")

    def testMetaElementNoClose(self):
        self._runTest_('<meta tal:attributes="name test">',
                       '<meta name="testing">',
                       "HTML Element META produced end tag.")

    def testParamElementNoClose(self):
        self._runTest_('<param tal:attributes="name test">',
                       '<param name="testing">',
                       "HTML Element PARAM produced end tag.")

if __name__ == '__main__':
    unittest.main()


text:
"use strict";

var GT = GT || {};

(function(exports) {

    var Class = exports.Class;

    /***************************/
    /********** Game ***********/
    /***************************/

    var Game = Class.create({

        id: null,
        width: 600,
        height: 400,
        viewWidth: 0,
        viewHeight: 0,
        FPS: 60,
        caption: '',
        context: null, // graphic-context
        useStaticTimeStep: false,
        frame: 0,
        timeBlank: 0,

        init: function() {

            this._width = this.width;
            this._height = this.height;
            this.offsetX = 0;
            this.offsetY = 0;

            if (this.beforeInit) {
                this.beforeInit.apply(this, arguments);
            }

            var Me = this;
            // if (requestAnimationFrame.mock) {
            //     this._run = function() {
            //         Me.run();
            //     };
            // } else {
            //     this._run = function() {
            //         Me.rafId = requestAnimationFrame(Me._runCore);
            //     };
            //     this._runCore = function() {
            //         Me.run();
            //     }
            // }
            this._run = function() {
                Me.run();
            };

            this.timer = {
                now: 0,
                last: 0,
                // step: Math.round(1000 / this.FPS)
                step: Math.floor(1000 / this.FPS)
            };
            this.staticTimeStep = this.timer.step;

            this.initGraphicContext();

            if (this.onInit) {
                this.onInit.apply(this, arguments);
            }
        },

        // implement by yourself
        initGraphicContext: function() {

        },

        start: function() {
            this.timer.now = Date.now();
            this.timer.last = this.timer.now;
            this.paused = false;
            this.running = true;
            this.frame = 0;
            if (this.onStart) {
                this.onStart();
            }
            this.run();
        },
        stop: function() {
            this.running = false;
            if (this.onStop) {
                this.onStop();
            }
        },
        stopNow: function() {
            // clearTimeout(this.loopId);
            cancelAnimationFrame(this.loopId);
            this.running = false;
            if (this.onStop) {
                this.onStop();
            }
        },
        pause: function() {
            this.paused = true;
            if (this.onPause) {
                this.onPause();
            }
        },
        resume: function() {
            this.paused = false;
            if (this.onResume) {
                this.onResume();
            }
        },

        pauseLoop: function() {
            this.running = false;
            if (this.loopId) {
                // clearTimeout(this.loopId);
                cancelAnimationFrame(this.loopId);
            }
        },
        resumeLoop: function() {
            this.timer.last = Date.now();
            this.run();
        },

        run: function() {
            var now = this.timer.now = Date.now();
            var timeStep = now - this.timer.last;
            // this.loopId = setTimeout(this._run, this.staticTimeStep);
            this.loopId = requestAnimationFrame(this._run, this.staticTimeStep);
            var blank = timeStep - this.staticTimeStep;
            if (blank >= 0) {
                // this.timer.last = now;
                this.timer.last = now - blank;

                this.handleInput(timeStep, now);
                if (!this.paused && timeStep > 1) {
                    timeStep = this.useStaticTimeStep ? this.staticTimeStep : timeStep;
                    this.frame++;
                    this.update(timeStep, now);
                    this.render(timeStep, now);
                }
                if (!this.running && this.loopId) {
                    clearTimeout(this.loopId);
                    cancelAnimationFrame(this.rafId);
                }
            }
        },

        setScene: function(scene) {
            if (this.scene && this.scene.leave) {
                this.scene.leave();
            }
            this.frame = 0;
            this.scene = scene;
            scene.enter();
        },

        update: function(timeStep, now) {
            if (this.scene) {
                this.scene.update(timeStep, now);
            }
        },

        render: function(timeStep, now) {
            if (this.scene) {
                this.scene.render(this.context, timeStep, now);
            }
        },

        handleInput: function(timeStep, now) {
            if (this.scene) {
                this.scene.handleInput(timeStep, now);
            }
        },
        // some hooks, implement by yourself
        onInit: null,
        onStart: null,
        onPause: null,
        onResume: null,
        onStop: null,

    });

    exports.Game = Game;

    /***************************/
    /********** Scene **********/
    /***************************/

    var Scene = Class.create({

        id: null,
        frame: 0,
        init: function(game) {

        },
        enter: function() {

        },
        leave: function(nextScene) {

        },
        jumpToScene: function(sceneClass) {
            var scene = new sceneClass();
            scene.init(this.game);
            this.game.setScene(scene);
            return scene;
        },
        update: function(timeStep, now) {

        },
        render: function(context, timeStep, now) {

        },
        handleInput: function(timeStep, now) {

        }
    });

    exports.Scene = Scene;

    /***************************/
    /*********** rAF ***********/
    /***************************/
    (function() {
        var vendors = ['ms', 'moz', 'webkit'];
        for (var i = 0; !window.requestAnimationFrame && i < vendors.length; ++i) {
            var p = vendors[i];
            window.requestAnimationFrame = window[p + 'RequestAnimationFrame'];
            window.cancelAnimationFrame = window[p + 'CancelAnimationFrame'] || window[p + 'CancelRequestAnimationFrame'];
        }

        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = function(callback, element) {
                return window.setTimeout(callback, 16);
            };
            window.requestAnimationFrame.mock = true;
        }

        if (!window.cancelAnimationFrame) {
            window.cancelAnimationFrame = function(id) {
                return window.clearTimeout(id);
            };
        }
    }());

}(GT));


text:
package hu.pe.thinhhoang.aaosync;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import hu.pe.thinhhoang.aaosync.settings.Settings;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {} interface
 * to handle interaction events.
 * Use the {@link FirstConfigFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FirstConfigFragment extends Fragment {

    public FirstConfigFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment FirstConfigFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FirstConfigFragment newInstance() {
        FirstConfigFragment fragment = new FirstConfigFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_first_config, container, false);

        // Event handlers for UI Components

        final Button loginButton = (Button) v.findViewById(R.id.button);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveMSSV();
            }
        });

        EditText mssvEditText = (EditText) v.findViewById(R.id.mssvEditText);
        mssvEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_NEXT)
                {
                    saveMSSV();
                    return true;
                }
                return false;
            }
        });

        loadMSSV(v);

        return v;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /* Generic methods */

    private void saveMSSV(){
        Settings.setContext(getContext());
        String mssv;
        EditText mssvEditText = (EditText) getActivity().findViewById(R.id.mssvEditText);
        mssv=mssvEditText.getText().toString();
        if(mssv.isEmpty())
        {
            Toast.makeText(getActivity(),"Vui lòng nhập MSSV hợp lệ vào ô.",Toast.LENGTH_SHORT).show();
        } else {
            Settings.setMSSV(mssv);
            Log.v("AAOSync","The MSSV "+mssv+" is registered");
            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }

    private void loadMSSV(View v){
        Settings.setContext(getContext());
        String mssv = Settings.getMSSV();
        EditText mssvEditText = (EditText) v.findViewById(R.id.mssvEditText);
        if(!mssv.equals("undef")){
            mssvEditText.setText(mssv);
        }
    }

}


text:
package seedu.address.ui;

import java.util.Optional;

import org.junit.After;
import org.junit.Rule;

import guitests.GuiRobot;
import guitests.guihandles.exceptions.NodeNotFoundException;
import javafx.scene.Node;
import seedu.address.commons.core.EventsCenter;
import seedu.address.ui.testutil.UiPartRule;

/**
 * A GUI unit test class for AddressBook.
 */
public abstract class GuiUnitTest {
    @Rule
    public final UiPartRule uiPartRule = new UiPartRule();

    protected final GuiRobot guiRobot = new GuiRobot();

    @After
    public void tearDown() {
        EventsCenter.clearSubscribers();
    }

    /**
     * Retrieves the {@code query} node owned by the {@code rootNode}.
     *
     * @param query name of the CSS selector of the node to retrieve.
     * @throws NodeNotFoundException if no such node exists.
     */
    protected <T extends Node> T getChildNode(Node rootNode, String query) {
        Optional<T> node = guiRobot.from(rootNode).lookup(query).tryQuery();
        return node.orElseThrow(NodeNotFoundException::new);
    }
}


text:
Eventos

            Nombre
            Objetivos
            Estado

            {{evento.name}}
            {{evento.objectives}}
            {{evento.approved[0]}}

        No Eventos yet, why don't you create one?


text:
layout: default
meta: Thank you for purchasing a dragon.
---

Thank you for your purchase

	Click here to return to main page!


text:
/*!
    \file    usbd_pwr.c
    \brief   USB device power management driver

    \version 2020-07-17, V3.0.0, firmware for GD32F10x
*/

/*
    Copyright (c) 2020, GigaDevice Semiconductor Inc.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors
       may be used to endorse or promote products derived from this software without
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/

#include "usbd_pwr.h"

/*!
    \brief      start to remote wakeup
    \param[in]  udev: pointer to USB core instance
    \param[out] none
    \retval     none
*/
void usbd_remote_wakeup_active(usb_dev *udev)
{
    resume_mcu(udev);

#ifdef LPM_ENABLED
    if(1U == udev->lpm.L1_remote_wakeup){
        udev->drv_handler->resume(udev);

        udev->lpm.L1_resume = 1U;
    }
#endif /* LPM_ENABLED */

    if(1U == udev->pm.remote_wakeup){
        udev->pm.remote_wakeup_on = 1U;
        udev->pm.esof_count = 15U;
        udev->drv_handler->resume(udev);
    }
}


text:
package test;

import main.global.Convert;
import main.global.Minibase;
import main.global.Page;
import main.global.PageId;

/**
 * Test suite for the bufmgr layer.
 */
class BMTestExtra extends TestDriver {

    /** The display name of the test suite. */
    private static final String TEST_NAME = "buffer manager EXTRA TESTS";

    /**
     * Test application entry point; runs all tests.
     */
    public static void main(String argv[]) {

        // create a clean Minibase instance.  This requires pinning and unpinning
        // the first page of the database.
        BMTestExtra bmt = new BMTestExtra();
        bmt.create_minibase();

        // run all the test cases
        System.out.println("\n" + "Running " + TEST_NAME + "...");
        boolean status = PASS;
        status &= bmt.test4();
        status &= bmt.test5();

        // display the final results
        System.out.println();
        if (status != PASS) {
            System.out.println("Error(s) encountered during " + TEST_NAME + ".");
        } else {
            System.out.println("All " + TEST_NAME + " completed successfully!");
        }

    } // public static void main (String argv[])

    /**
     *
     */
    protected boolean test4() {
/*
 * pin few page,
 * write something
 * flush
 * read pages from diskmgr
 *
 * Test2
 * pin all to write and unpin dirty
 * Pin all and unpin clean
 * Pin new pages
 * Pin old pages and read them
 */

        System.out.print("\n  Test 4 tests flushAllPages function\n");

        // Allocate pages
        boolean status1 = PASS;
        int toAlloc =  Minibase.BufferManager.getNumFrames();
        Page pg = new Page();  //refers to the current frame
        PageId firstPid = new PageId();

        System.out.print("  - Allocate pages\n");
        try {
            firstPid = Minibase.BufferManager.newPage(pg, toAlloc);
        } catch (Exception e) {
            System.err.print("*** Could not allocate " + toAlloc);
            System.err.print(" new pages in the database.\n");
            e.printStackTrace();
            return false;
        }

        // unpin that first page... to simplify our loop
        try {
            Minibase.BufferManager.unpinPage(firstPid, UNPIN_CLEAN);
        } catch (Exception e) {
            System.err.print("*** Could not unpin the first new page.\n");
            e.printStackTrace();
            status1 = FAIL;
        }

        // Write something on each allocated page.  Pin, write, unpin.
        System.out.print("  - Write something on each one\n");
        PageId pid = new PageId();
        PageId lastPid = new PageId();

        for (pid.pid = firstPid.pid, lastPid.pid = pid.pid + toAlloc; status1 == PASS
                && pid.pid < lastPid.pid; pid.pid = pid.pid + 1) {

            try {
                Minibase.BufferManager.pinPage(pid, pg, PIN_NOOP);
            } catch (Exception e) {
                System.err.print("*** Could not pin new page " + pid.pid + "\n");
                e.printStackTrace();
                return false; //If we can't pin the page, end this test
            }

            // Copy the page number + 99 onto each page. It seems
            // unlikely that this bit pattern would show up there by
            // coincidence.
            int data = pid.pid + 99;
            Convert.setIntValue(data, 0, pg.getData());

            try {
                Minibase.BufferManager.unpinPage(pid, UNPIN_DIRTY);
            } catch (Exception e) {
                status1 = FAIL; //record failure but continue the test
                System.err.print("*** Could not unpin dirty page " + pid.pid + "\n");
                e.printStackTrace();
            }
        }

        System.out.print("  - Now we flush all fames to disk\n");
        Minibase.BufferManager.flushAllFrames();

        // Read that something back from each page.  Pin, read, unpin.
        // Because there are more pages than frames, disk I/O will happen here.
        System.out.print("  - Make sure pages are written to disk, we Read them by calling the disk manager\n");

        for (pid.pid = firstPid.pid; status1 == PASS && pid.pid < lastPid.pid;
             pid.pid = pid.pid + 1) {

            try {
                Minibase.DiskManager.read_page(pid, pg);
                //Minibase.BufferManager.pinPage(pid, pg, PIN_DISKIO);
            } catch (Exception e) {
                System.err.print("*** Could not read page from disk" + pid.pid + "\n");
                e.printStackTrace();
                return false;  //If we can't pin the page, end this test
            }

            int data = 0;
            data = Convert.getIntValue(0, pg.getData());

            if (status1 == PASS) {
                if (data != (pid.pid) + 99) {
                    status1 = FAIL;  //record failure but continue the test
                    System.err.print("*** Read wrong data back from page (in disk) " + pid.pid + "\n");
                }
            }

        }

        //Free the allocated pages
        if (status1 == PASS) {
            System.out.print("  - Free the allocated pages\n");

            for (pid.pid = firstPid.pid; pid.pid < lastPid.pid; pid.pid = pid.pid + 1) {

                try {
                    Minibase.BufferManager.freePage(pid);
                } catch (Exception e) {
                    status1 = FAIL;
                    System.err.print("*** Error freeing page " + pid.pid + "\n");
                    e.printStackTrace();
                }
            }
        }

        if (status1 == PASS)
            System.out.print("  TEST 4 COMPLETED SUCESSFULLY.\n");
        else
            System.err.print("  TEST 4 COMPLETED WITH ERRORS.\n");

        return status1;

    } // protected boolean test4 ()

    protected boolean test5() {

        System.out.print("\n  Test 5 tests whether BM keeps track of dirty bit correctly\n");

        // Allocate a number of pages = num of frames - 10
        boolean status1 = PASS;
        int toAlloc = Minibase.BufferManager.getNumUnpinned() - 10 ;
        Page pg = new Page();  //refers to the current frame
        PageId firstPid = new PageId();
        PageId SecondGroupfirstPid = new PageId();

        System.out.print("  - Allocate # of pages = # of frames - 10\n");
        try {
            firstPid = Minibase.BufferManager.newPage(pg, toAlloc);
        } catch (Exception e) {
            System.err.print("*** Could not allocate " + toAlloc);
            System.err.print(" new pages in the database.\n");
            e.printStackTrace();
            return false;
        }

        // unpin that first page... to simplify our loop
        try {
            Minibase.BufferManager.unpinPage(firstPid, UNPIN_CLEAN);
        } catch (Exception e) {
            System.err.print("*** Could not unpin the first new page.\n");
            e.printStackTrace();
            status1 = FAIL;
        }

        // Write something on each allocated page.  Pin, write, unpin(dirty).
        System.out.print("  - Write something on each one\n");
        PageId pid = new PageId();
        PageId lastPid = new PageId();

        for (pid.pid = firstPid.pid, lastPid.pid = pid.pid + toAlloc; status1 == PASS
                && pid.pid < lastPid.pid; pid.pid = pid.pid + 1) {

            try {
                Minibase.BufferManager.pinPage(pid, pg, PIN_NOOP);
            } catch (Exception e) {
                System.err.print("*** Could not pin new page " + pid.pid + "\n");
                e.printStackTrace();
                return false; //If we can't pin the page, end this test
            }

            // Copy the page number + 888 onto each page. It seems
            // unlikely that this bit pattern would show up there by
            // coincidence.
            int data = pid.pid + 888;
            Convert.setIntValue(data, 0, pg.getData());

            try {
                Minibase.BufferManager.unpinPage(pid, UNPIN_DIRTY);
            } catch (Exception e) {
                status1 = FAIL; //record failure but continue the test
                System.err.print("*** Could not unpin dirty page " + pid.pid + "\n");
                e.printStackTrace();
            }
        }

        // The following loop iterate on all pages with pin and unpin(clean)
        // Buffer manager should still keep dirty bit = true since all pages were touched in the previous loop
        System.out.print("  - Loop with pin and unpin(clean)\n");

        for (pid.pid = firstPid.pid; status1 == PASS && pid.pid < lastPid.pid;
             pid.pid = pid.pid + 1) {

            try {
                Minibase.BufferManager.pinPage(pid, pg, PIN_DISKIO);
            } catch (Exception e) {
                System.err.print("*** Could not pin page " + pid.pid + "\n");
                e.printStackTrace();
                return false;  //If we can't pin the page, end this test
            }

            try {
                Minibase.BufferManager.unpinPage(pid, UNPIN_CLEAN);
            } catch (Exception e) {
                status1 = FAIL;  //record failure but continue the test
                System.err.print("*** Could not unpin page " + pid.pid + "\n");
                e.printStackTrace();
            }
        }

        //-----------------------------------
        //-------------------------------------
        System.out.print("  - Allocate a second group of pages. This will force the first group to be written to disk\n");
        try {
            SecondGroupfirstPid = Minibase.BufferManager.newPage(pg, toAlloc);
        } catch (Exception e) {
            System.err.print("*** Could not allocate " + toAlloc);
            System.err.print(" new pages in the database.\n");
            e.printStackTrace();
            return false;
        }

        // unpin that first page... to simplify our loop
        try {
            Minibase.BufferManager.unpinPage(SecondGroupfirstPid, UNPIN_CLEAN);
        } catch (Exception e) {
            System.err.print("*** Could not unpin the first new page.\n");
            e.printStackTrace();
            status1 = FAIL;
        }

        // Write something on each allocated page.  Pin, write, unpin(dirty).
        System.out.print("  - Write something on each page in the second group\n");
        PageId SecondGrouppid = new PageId();
        PageId SecondGrouplastPid = new PageId();

        for (SecondGrouppid.pid = SecondGroupfirstPid.pid, SecondGrouplastPid.pid = SecondGrouppid.pid + toAlloc; status1 == PASS
                && SecondGrouppid.pid < SecondGrouplastPid.pid; SecondGrouppid.pid = SecondGrouppid.pid + 1) {

            try {
                Minibase.BufferManager.pinPage(SecondGrouppid, pg, PIN_NOOP);
            } catch (Exception e) {
                System.err.print("*** Could not pin new page " + pid.pid + "\n");
                e.printStackTrace();
                return false; //If we can't pin the page, end this test
            }

            // Copy the page number + 66666 onto each page. It seems
            // unlikely that this bit pattern would show up there by
            // coincidence.

            int data = SecondGrouppid.pid + 66666;
            Convert.setIntValue(data, 0, pg.getData());

            try {
                Minibase.BufferManager.unpinPage(SecondGrouppid, UNPIN_DIRTY);
            } catch (Exception e) {
                status1 = FAIL; //record failure but continue the test
                System.err.print("*** Could not unpin dirty page " + SecondGrouppid.pid + "\n");
                e.printStackTrace();
            }
        }

        System.out.print("  - Now try to pin and read the pages from the first group\n");

        for (pid.pid = firstPid.pid; status1 == PASS && pid.pid < lastPid.pid;
             pid.pid = pid.pid + 1) {

            try {
                Minibase.BufferManager.pinPage(pid, pg, PIN_DISKIO);
            } catch (Exception e) {
                System.err.print("*** Could not pin page " + pid.pid + "\n");
                e.printStackTrace();
                return false;  //If we can't pin the page, end this test
            }

            int data = 0;
            data = Convert.getIntValue(0, pg.getData());

            if (status1 == PASS) {
                if (data != (pid.pid) + 888) {
                    status1 = FAIL;  //record failure but continue the test
                    System.err.print("*** Read wrong data back from page " + pid.pid + "\n");
                }
            }

            try {
                Minibase.BufferManager.unpinPage(pid, UNPIN_CLEAN);
            } catch (Exception e) {
                status1 = FAIL;  //record failure but continue the test
                System.err.print("*** Could not unpin page " + pid.pid + "\n");
                e.printStackTrace();
            }
        }

        //Free the allocated pages
        if (status1 == PASS) {
            System.out.print("  - Free the allocated pages in the first group\n");

            for (pid.pid = firstPid.pid; pid.pid < lastPid.pid; pid.pid = pid.pid + 1) {

                try {
                    Minibase.BufferManager.freePage(pid);
                } catch (Exception e) {
                    status1 = FAIL;
                    System.err.print("*** Error freeing page " + pid.pid + "\n");
                    e.printStackTrace();
                }
            }
        }

        if (status1 == PASS) {
            System.out.print("  - Free the allocated pages in the second group\n");

            for (SecondGrouppid.pid = SecondGroupfirstPid.pid; SecondGrouppid.pid < SecondGrouplastPid.pid; SecondGrouppid.pid = SecondGrouppid.pid + 1) {

                try {
                    Minibase.BufferManager.freePage(pid);
                } catch (Exception e) {
                    status1 = FAIL;
                    System.err.print("*** Error freeing page " + SecondGrouppid.pid + "\n");
                    e.printStackTrace();
                }
            }
        }

        if (status1 == PASS)
            System.out.print("  TEST 5 COMPLETED SUCESSFULLY.\n");
        else
            System.err.print("  TEST 5 COMPLETED WITH ERRORS.\n");

        return status1;

    } // protected boolean test5 ()

} // class BMTest extends TestDriver


text:
ASTool.AnnotationController = Em.ObjectController.extend(ASTool.BaseControllerMixin,
	ASTool.DocumentViewDataSource, ASTool.DocumentViewListener, {

	needs: ['application', 'template_index'],

	navigationLabelBinding: 'content.name',

	mappingAttribute: null,

	documentView: null,

	currentlySelectedElement: null,

	_selectingIgnore: false,

	highlightedElement: null,

	scrapedItemBinding: 'controllers.template_index.scrapedItem',

	urlBinding: 'controllers.template_index.url',

	currentVariantBinding: Em.Binding.oneWay("content.variant"),

	selectingIgnore: function(key, selectingIgnore) {
		if (arguments.length > 1) {
			this.set('_selectingIgnore', selectingIgnore);
			if (selectingIgnore) {
				this.set('documentView.restrictToDescendants', this.get('content.element'));
				this.set('documentView.partialSelectionEnabled', false);
			} else {
				this.set('documentView.restrictToDescendants', null);
				this.set('documentView.partialSelectionEnabled', true);
			}
		}
		return this.get('_selectingIgnore');
	}.property('_selectingIgnore'),

	sprites: function() {
		var sprites = [];
		if (this.get('currentlySelectedElement')) {
			sprites.pushObject(ASTool.AnnotationSprite.create(
				{ 'annotation': this.content,
				  'highlighted': 'true' }));
		}
		if (this.highlightedElement) {
			sprites.pushObject(ASTool.ElementSprite.create({
				element: this.highlightedElement,
				fillColor: 'rgba(255,149,0,0.2)',
				strokeColor: 'rgba(255,149,0,0.6)',
				zPosition: 1000,
			}));
		}

		var annotationSprites = this.get('controllers.template_index.sprites').filter(function(sprite) {
			return sprite.get('annotation.id') != this.content.get('id');
		}.bind(this));

		var ignoredElements = this.get('content.ignores').map(function(ignore) {
			return ASTool.IgnoreSprite.create({ ignore: ignore });
		});

		return sprites.concat(annotationSprites).concat(ignoredElements);
	}.property('currentlySelectedElement',
			   'controllers.template_index.sprites',
			   'content.ignores.@each.highlighted',
			   'content.ignores.@each.ignoreBeneath',
			   'highlightedElement'),

	clearGeneratedIns: function(insElement) {
		$(insElement).removePartialAnnotation();
	},

	cancelEdit: function() {
		this.set('content.selectedElement', null);
		if (this.get('content.generated') &&
			this.get('content.element') != this.get('currentlySelectedElement')) {
			this.clearGeneratedIns(this.get('currentlySelectedElement'));
		}
		this.transitionToRoute('template');
	},

	saveEdit: function() {
		this.get('controllers.template_index').saveAnnotations();
		this.transitionToRoute('template');
	},

	actions: {

		doneEditing: function(annotation) {
			this.saveEdit(annotation);
		},

		cancelEdit: function(annotation) {
			this.cancelEdit(annotation);
		},

		mapAttribute: function(attribute) {
			this.set('mappingAttribute', attribute);
		},

		fieldSelected: function(field) {
			this.get('content').addMapping(this.get('mappingAttribute.name'), field);
			this.set('mappingAttribute', null);
		},

		variantSelected: function(variant) {
			this.set('content.variant', variant);
		},

		makeSticky: function(attribute) {
			this.get('controllers.template_index').makeSticky(this.get('content'),
				attribute.get('name'));
		},

		unmapAttribute: function(attribute) {
			this.get('content').removeMapping(attribute.name);
		},

		deleteIgnore: function(ignore) {
			this.get('content.ignores').removeObject(ignore);
		},

		highlightElement: function(element) {
			this.set('highlightedElement', element);
			if (element) {
				this.documentView.scrollToElement(element);
			}
		},

		selectElement: function(element) {
			this.documentActions['elementSelected'].call(this, element);
		}
	},

	confirmChangeSelection: function() {
		return confirm(ASTool.Messages.get('confirm_change_selection'));
	},

	documentActions: {

		elementSelected: function(element, partialSelection) {
			if (this.get('selectingIgnore')) {
				if (element) {
					this.get('content').addIgnore(element);
				}
				this.set('selectingIgnore', false);
			} else {
				var needsConfirmation = this.get('content.ignores').length ||
					this.get('content.mappedAttributes').length;
				if (!needsConfirmation || this.confirmChangeSelection()) {
					if (this.get('content.generated')) {
						this.clearGeneratedIns(this.get('content.element'));
					}
					this.set('highlightedElement', null);
					this.set('content.selectedElement', element);
					this.set('content.generated', !!partialSelection);
					this.get('content').removeIgnores();
					this.get('content').removeMappings();
					this.set('currentlySelectedElement', element);
				}
			}
		},

		partialSelection: function(selection) {
			var element = $('<ins/>').get(0);
			selection.getRangeAt(0).surroundContents(element);
			this.documentActions['elementSelected'].call(this, element, true);
			selection.collapse();
		},
	},

	willEnter: function() {
		this.get('documentView').config({ mode: 'select',
										  listener: this,
										  dataSource: this,
										  partialSelects: true });
		this.set('currentlySelectedElement', this.get('content.element'));
	},

	willLeave: function() {
		this.set('selectingIgnore', false);
		this.set('currentlySelectedElement', null);
	},
});


text:
var nodeBoxView = require('../lib'),
	should = require('should'),
	assert = require('assert'),
	fs = require('fs'),
	pdfDocPath = './test/docs/test.pdf',
	pdfUrl = 'https://github.com/gian788/node-box-view/blob/master/test/doc/test.pdf';

var apiKey = process.env.APIKEY || process.argv[2];
apiKey = 'ulcwwj60olhu4knjowy8nz47s77r7ath'

var boxView = new nodeBoxView(apiKey || process.env.APIKEY);

var boxDocument;

describe('Testing upload', function () {
	it('uploadFile', function (done) {
		this.timeout(10000)
		boxView.uploadFile(pdfDocPath, {}, function(err, boxFile){
		    if(err) return done(err);

		    boxFile.should.be.instanceof(Object);
		    boxFile.type.should.be.equal('document');
		    done();
		    boxDocument = boxFile;
		});
	});

	it('uploadFromUrl', function (done) {
		this.timeout(10000)
		boxView.uploadFromUrl(pdfUrl, {}, function(err, boxFile){
		    if(err) return done(err);

		    boxFile.should.be.instanceof(Object);
		    boxFile.type.should.be.equal('document');
		    done();
		});
	});
});

var tempFile = './t.png';

describe('Testing get', function () {
	it('getDocuemnt', function (done) {
		boxView.getDocument(boxDocument.id, {}, function(err, boxFile){
		    if(err) return done(err);

		    boxFile.should.be.instanceof(Object);
		    boxFile.type.should.be.equal('document');
		    done();
		});
	});

	it('getDocumentThumbnail', function (done) {
		boxDocument.id = 'eb292edadeeb45af901d41bedb34ff5a';
		//boxDocument.id = 'eb292edadeeb45af901d41bdsad09809';
		boxView.getDocumentThumbnail(boxDocument.id, 50, 50, tempFile, function(err){
		    if(err) return done(err);

		    fs.statSync(tempFile).size.should.be.above(0);
		    fs.unlinkSync(tempFile);
		    done();
		});
	});
});


text:
def extractShuuenScansTumblrCom(item):
	'''
	Parser for 'shuuen-scans.tumblr.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return False

	if "WATTT" in item['tags']:
		return buildReleaseMessageWithType(item, "WATTT", vol, chp, frag=frag, postfix=postfix)

	return False


text:
import CombinedStream = require('combined-stream');
import { createReadStream, createWriteStream } from 'fs';

const stream1 = new CombinedStream();

stream1.append(createReadStream('tsconfig.json'));
stream1.append(createReadStream('tslint.json'));
stream1.append(createReadStream('index.d.ts'));

stream1.pipe(createWriteStream('combined.txt'));

const stream2 = CombinedStream.create({
    maxDataSize: 1 << 32,
    pauseStreams: false
});

stream1.destroy();

// should log true
console.log(CombinedStream.isStreamLike(stream2));

stream2.on('data', data => {
    console.log(data);
});

stream2.pipe(createWriteStream('combined.txt'));

stream2.write(CombinedStream.name);

stream2.destroy();

const arrowFunction = (): CombinedStream => {
    const stream3 = new CombinedStream();

    // test next function
    stream3.append(next => {
        stream3.append('hello world');
        next(createReadStream(''));
    });

    // next function with no next
    stream3.append(() => {
        stream3.append('hello again');
    });

    return stream3;
};


text:
Deutschland
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Sicherheit
Vertrauen
Anpassung
Technologie
Standard
Intelligenz
Anpassung
Softwareentwicklung
Meinung
E-Mail
Produkt
Kundenservice
Sicherheit
Einführung
Bedürfnisse
Sicherheit
Risiko
Energie
Parken
Sicherheit
Region
Kognition
Energie
Sicherheit
Menschen
Sicherheit
Software
Daten
Zeit
Zeit
Produkt
Kundenservice
Kundenservice
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Schuhe
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Tunnel
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Deutschland
Kundenservice
Kundenservice
Kundenservice
Rehabilitation
Deutschland
Kundenservice
Deutschland
Kundenservice
Deutschland
Kundenservice
Technologie
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Sport
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice
Kundenservice