text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.storage.blob.specialized;

import com.azure.core.annotation.ServiceClientBuilder;
import com.azure.core.client.traits.AzureNamedKeyCredentialTrait;
import com.azure.core.client.traits.AzureSasCredentialTrait;
import com.azure.core.client.traits.ConfigurationTrait;
import com.azure.core.client.traits.ConnectionStringTrait;
import com.azure.core.client.traits.EndpointTrait;
import com.azure.core.client.traits.HttpTrait;
import com.azure.core.client.traits.TokenCredentialTrait;
import com.azure.core.credential.AzureNamedKeyCredential;
import com.azure.core.credential.AzureSasCredential;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelinePosition;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.http.policy.RetryOptions;
import com.azure.core.util.ClientOptions;
import com.azure.core.util.Configuration;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.HttpClientOptions;
import com.azure.core.util.logging.ClientLogger;
import com.azure.storage.blob.BlobContainerAsyncClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceVersion;
import com.azure.storage.blob.BlobUrlParts;
import com.azure.storage.blob.implementation.models.EncryptionScope;
import com.azure.storage.blob.implementation.util.BuilderHelper;
import com.azure.storage.blob.models.CpkInfo;
import com.azure.storage.blob.models.CustomerProvidedKey;
import com.azure.storage.blob.models.PageRange;
import com.azure.storage.common.StorageSharedKeyCredential;
import com.azure.storage.common.Utility;
import com.azure.storage.common.implementation.connectionstring.StorageAuthenticationSettings;
import com.azure.storage.common.implementation.connectionstring.StorageConnectionString;
import com.azure.storage.common.implementation.connectionstring.StorageEndpoint;
import com.azure.storage.common.policy.RequestRetryOptions;
import reactor.core.publisher.Flux;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * This class provides a fluent builder API to help aid the configuration and instantiation of specialized Storage Blob
 * clients, {@link AppendBlobClient}, {@link AppendBlobAsyncClient}, {@link BlockBlobClient},
 * {@link BlockBlobAsyncClient}, {@link PageBlobClient}, and {@link PageBlobAsyncClient}. These clients are used to
 * perform operations that are specific to the blob type.
 *
 * @see AppendBlobClient
 * @see AppendBlobAsyncClient
 * @see BlockBlobClient
 * @see BlockBlobAsyncClient
 * @see PageBlobClient
 * @see PageBlobAsyncClient
 */
@ServiceClientBuilder(serviceClients = {
    AppendBlobClient.class, AppendBlobAsyncClient.class,
    BlockBlobClient.class, BlockBlobAsyncClient.class,
    PageBlobClient.class, PageBlobAsyncClient.class
})
public final class SpecializedBlobClientBuilder implements
    TokenCredentialTrait<SpecializedBlobClientBuilder>,
    ConnectionStringTrait<SpecializedBlobClientBuilder>,
    AzureNamedKeyCredentialTrait<SpecializedBlobClientBuilder>,
    AzureSasCredentialTrait<SpecializedBlobClientBuilder>,
    HttpTrait<SpecializedBlobClientBuilder>,
    ConfigurationTrait<SpecializedBlobClientBuilder>,
    EndpointTrait<SpecializedBlobClientBuilder> {
    private static final ClientLogger LOGGER = new ClientLogger(SpecializedBlobClientBuilder.class);

    private String endpoint;
    private String accountName;
    private String containerName;
    private String blobName;
    private String snapshot;
    private String versionId;

    private CpkInfo customerProvidedKey;
    private EncryptionScope encryptionScope;
    private StorageSharedKeyCredential storageSharedKeyCredential;
    private TokenCredential tokenCredential;
    private AzureSasCredential azureSasCredential;
    private String sasToken;

    private HttpClient httpClient;
    private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
    private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
    private HttpLogOptions logOptions = getDefaultHttpLogOptions();
    private RequestRetryOptions retryOptions;
    private RetryOptions coreRetryOptions;
    private HttpPipeline httpPipeline;

    private ClientOptions clientOptions = new ClientOptions();
    private Configuration configuration;
    private BlobServiceVersion version;

    /**
     * Creates a {@link AppendBlobClient} based on options set in the Builder. AppendBlobClients are used to perform
     * append blob specific operations such as {@link AppendBlobClient#appendBlock(InputStream, long) append block},
     * only use this when the blob is known to be an append blob.
     *
     * @return a {@link AppendBlobClient} created from the configurations in this builder.
     * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
     * @throws IllegalStateException If multiple credentials have been specified.
     */
    public AppendBlobClient buildAppendBlobClient() {
        return new AppendBlobClient(buildAppendBlobAsyncClient());
    }

    /**
     * Creates a {@link AppendBlobAsyncClient} based on options set in the Builder. AppendBlobAsyncClients are used to
     * perform append blob specific operations such as {@link AppendBlobAsyncClient#appendBlock(Flux, long) append
     * blob}, only use this when the blob is known to be an append blob.
     *
     * @return a {@link AppendBlobAsyncClient} created from the configurations in this builder.
     * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
     * @throws IllegalStateException If multiple credentials have been specified.
     * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)}
     * and {@link #retryOptions(RequestRetryOptions)} have been set.
     */
    public AppendBlobAsyncClient buildAppendBlobAsyncClient() {
        validateConstruction();
        String containerName = getContainerName();

        return new AppendBlobAsyncClient(getHttpPipeline(), endpoint, getServiceVersion(),
            accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, versionId);
    }

    /**
     * Creates a {@link BlockBlobClient} based on options set in the Builder. BlockBlobClients are used to perform
     * generic upload operations such as {@link BlockBlobClient#upload(InputStream, long) upload from file} and block
     * blob specific operations such as {@link BlockBlobClient#stageBlock(String, InputStream, long) stage block} and
     * {@link BlockBlobClient#commitBlockList(List)}, only use this when the blob is known to be a block blob.
     *
     * @return a {@link BlockBlobClient} created from the configurations in this builder.
     * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
     * @throws IllegalStateException If multiple credentials have been specified.
     */
    public BlockBlobClient buildBlockBlobClient() {
        return new BlockBlobClient(buildBlockBlobAsyncClient());
    }

    /**
     * Creates a {@link BlockBlobAsyncClient} based on options set in the Builder. BlockBlobAsyncClients are used to
     * perform generic upload operations such as {@link BlockBlobAsyncClient#upload(Flux, long) upload from file}
     * and block blob specific operations such as {@link BlockBlobAsyncClient#stageBlockWithResponse(String, Flux, long,
     * byte[], String) stage block} and {@link BlockBlobAsyncClient#commitBlockList(List) commit block list}, only use
     * this when the blob is known to be a block blob.
     *
     * @return a {@link BlockBlobAsyncClient} created from the configurations in this builder.
     * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
     * @throws IllegalStateException If multiple credentials have been specified.
     * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)}
     * and {@link #retryOptions(RequestRetryOptions)} have been set.
     */
    public BlockBlobAsyncClient buildBlockBlobAsyncClient() {
        validateConstruction();
        String containerName = getContainerName();

        return new BlockBlobAsyncClient(getHttpPipeline(), endpoint, getServiceVersion(),
            accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, versionId);
    }

    /**
     * Creates a {@link PageBlobClient} based on options set in the Builder. PageBlobClients are used to perform page
     * blob specific operations such as {@link PageBlobClient#uploadPages(PageRange, InputStream) upload pages} and
     * {@link PageBlobClient#clearPages(PageRange) clear pages}, only use this when the blob is known to be a page
     * blob.
     *
     * @return a {@link PageBlobClient} created from the configurations in this builder.
     * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
     * @throws IllegalStateException If multiple credentials have been specified.
     */
    public PageBlobClient buildPageBlobClient() {
        return new PageBlobClient(buildPageBlobAsyncClient());
    }

    /**
     * Creates a {@link PageBlobAsyncClient} based on options set in the Builder. PageBlobAsyncClients are used to
     * perform page blob specific operations such as {@link PageBlobAsyncClient#uploadPages(PageRange, Flux) upload
     * pages} and {@link PageBlobAsyncClient#clearPages(PageRange) clear pages}, only use this when the blob is known to
     * be a page blob.
     *
     * @return a {@link PageBlobAsyncClient} created from the configurations in this builder.
     * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}.
     * @throws IllegalStateException If multiple credentials have been specified.
     * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)}
     * and {@link #retryOptions(RequestRetryOptions)} have been set.
     */
    public PageBlobAsyncClient buildPageBlobAsyncClient() {
        validateConstruction();
        String containerName = getContainerName();

        return new PageBlobAsyncClient(getHttpPipeline(), endpoint, getServiceVersion(),
            accountName, containerName, blobName, snapshot, customerProvidedKey, encryptionScope, versionId);
    }

    /*
     * Validate that the builder is able to construct a client.
     */
    private void validateConstruction() {
        Objects.requireNonNull(blobName, "'blobName' cannot be null.");
        Objects.requireNonNull(endpoint, "'endpoint' cannot be null");

        BuilderHelper.httpsValidation(customerProvidedKey, "customer provided key", endpoint, LOGGER);

        if (Objects.nonNull(customerProvidedKey) && Objects.nonNull(encryptionScope)) {
            throw LOGGER.logExceptionAsError(new IllegalArgumentException("Customer provided key and encryption"
                + "scope cannot both be set"));
        }
    }

    /*
     * Gets the container name to use in this client, if no container name has been passed the root container will be
     * used.
     *
     * Implicit and explicit root container access are functionally equivalent, but explicit references are easier to
     * read and debug.
     */
    private String getContainerName() {
        return CoreUtils.isNullOrEmpty(containerName) ? BlobContainerAsyncClient.ROOT_CONTAINER_NAME : containerName;
    }

    private HttpPipeline getHttpPipeline() {
        return (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(
            storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken,
            endpoint, retryOptions, coreRetryOptions, logOptions,
            clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, LOGGER);
    }

    private BlobServiceVersion getServiceVersion() {
        return (version != null) ? version : BlobServiceVersion.getLatest();
    }

    /**
     * Configures the builder based on the {@link BlobClientBase}.
     *
     * @param blobClient The {@code BlobClientBase} used to configure this builder.
     * @return the updated SpecializedBlobClientBuilder object.
     */
    public SpecializedBlobClientBuilder blobClient(BlobClientBase blobClient) {
        pipeline(blobClient.getHttpPipeline());
        endpoint(blobClient.getBlobUrl());
        serviceVersion(blobClient.getServiceVersion());
        this.snapshot = blobClient.getSnapshotId();
        this.versionId = blobClient.getVersionId();
        this.customerProvidedKey = blobClient.getCustomerProvidedKey();
        if (blobClient.getEncryptionScope() != null) {
            this.encryptionScope = new EncryptionScope().setEncryptionScope(blobClient.getEncryptionScope());
        }
        return this;
    }

    /**
     * Configures the builder based on the {@link BlobAsyncClientBase}.
     *
     * @param blobAsyncClient The {@code BlobAsyncClientBase} used to configure this builder.
     * @return the updated SpecializedBlobClientBuilder object.
     */
    public SpecializedBlobClientBuilder blobAsyncClient(BlobAsyncClientBase blobAsyncClient) {
        pipeline(blobAsyncClient.getHttpPipeline());
        endpoint(blobAsyncClient.getBlobUrl());
        serviceVersion(blobAsyncClient.getServiceVersion());
        this.snapshot = blobAsyncClient.getSnapshotId();
        this.versionId = blobAsyncClient.getVersionId();
        this.customerProvidedKey = blobAsyncClient.getCustomerProvidedKey();
        if (blobAsyncClient.getEncryptionScope() != null) {
            this.encryptionScope = new EncryptionScope().setEncryptionScope(blobAsyncClient.getEncryptionScope());
        }
        return this;
    }

    /**
     * Configures the builder based on the {@link BlobContainerClient} and appends the blob name to the container's URL.
     *
     * @param blobContainerClient The {@code ContainerClient} used to configure this builder.
     * @param blobName Name of the blob.
     * @return the updated SpecializedBlobClientBuilder object.
     */
    public SpecializedBlobClientBuilder containerClient(BlobContainerClient blobContainerClient, String blobName) {
        pipeline(blobContainerClient.getHttpPipeline());
        endpoint(blobContainerClient.getBlobContainerUrl());
        serviceVersion(blobContainerClient.getServiceVersion());
        blobName(blobName);
        this.customerProvidedKey = blobContainerClient.getCustomerProvidedKey();
        if (blobContainerClient.getEncryptionScope() != null) {
            this.encryptionScope = new EncryptionScope().setEncryptionScope(blobContainerClient.getEncryptionScope());
        }
        return this;
    }

    /**
     * Configures the builder based on the {@link BlobContainerAsyncClient} and appends the blob name to the container's
     * URL.
     *
     * @param blobContainerAsyncClient The {@code ContainerAsyncClient} used to configure this builder.
     * @param blobName Name of the blob.
     * @return the updated SpecializedBlobClientBuilder object.
     */
    public SpecializedBlobClientBuilder containerAsyncClient(BlobContainerAsyncClient blobContainerAsyncClient,
        String blobName) {
        pipeline(blobContainerAsyncClient.getHttpPipeline());
        endpoint(blobContainerAsyncClient.getBlobContainerUrl());
        serviceVersion(blobContainerAsyncClient.getServiceVersion());
        blobName(blobName);
        this.customerProvidedKey = blobContainerAsyncClient.getCustomerProvidedKey();
        if (blobContainerAsyncClient.getEncryptionScope() != null) {
            this.encryptionScope = new EncryptionScope().setEncryptionScope(
                blobContainerAsyncClient.getEncryptionScope());
        }
        return this;
    }

    /**
     * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name)
     *
     * @param endpoint URL of the service
     * @return the updated SpecializedBlobClientBuilder object
     * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL.
     */
    @Override
    public SpecializedBlobClientBuilder endpoint(String endpoint) {
        try {
            URL url = new URL(endpoint);
            BlobUrlParts parts = BlobUrlParts.parse(url);

            this.accountName = parts.getAccountName();
            this.endpoint = BuilderHelper.getEndpoint(parts);
            this.containerName = parts.getBlobContainerName() == null ? this.containerName
                : parts.getBlobContainerName();
            this.blobName = parts.getBlobName() == null ? this.blobName : Utility.urlEncode(parts.getBlobName());
            this.snapshot = parts.getSnapshot();
            this.versionId = parts.getVersionId();

            String sasToken = parts.getCommonSasQueryParameters().encode();
            if (!CoreUtils.isNullOrEmpty(sasToken)) {
                this.sasToken(sasToken);
            }
        } catch (MalformedURLException ex) {
            throw LOGGER.logExceptionAsError(
                new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.", ex));
        }
        return this;
    }

    /**
     * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server.
     *
     * @param customerProvidedKey Customer provided key containing the encryption key information.
     * @return the updated SpecializedBlobClientBuilder object
     */
    public SpecializedBlobClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) {
        if (customerProvidedKey == null) {
            this.customerProvidedKey = null;
        } else {
            this.customerProvidedKey = new CpkInfo()
                .setEncryptionKey(customerProvidedKey.getKey())
                .setEncryptionKeySha256(customerProvidedKey.getKeySha256())
                .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm());
        }

        return this;
    }

    /**
     * Sets the {@code encryption scope} that is used to encrypt blob contents on the server.
     *
     * @param encryptionScope Encryption scope containing the encryption key information.
     * @return the updated BlobClientBuilder object
     */
    public SpecializedBlobClientBuilder encryptionScope(String encryptionScope) {
        if (encryptionScope == null) {
            this.encryptionScope = null;
        } else {
            this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope);
        }

        return this;
    }

    /**
     * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service.
     *
     * @param credential {@link StorageSharedKeyCredential}.
     * @return the updated SpecializedBlobClientBuilder
     * @throws NullPointerException If {@code credential} is {@code null}.
     */
    public SpecializedBlobClientBuilder credential(StorageSharedKeyCredential credential) {
        this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
        this.tokenCredential = null;
        this.sasToken = null;
        return this;
    }

    /**
     * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service.
     *
     * @param credential {@link AzureNamedKeyCredential}.
     * @return the updated SpecializedBlobClientBuilder
     * @throws NullPointerException If {@code credential} is {@code null}.
     */
    @Override
    public SpecializedBlobClientBuilder credential(AzureNamedKeyCredential credential) {
        Objects.requireNonNull(credential, "'credential' cannot be null.");
        return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential));
    }

    /**
     * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
     * <a href="https://aka.ms/azsdk/java/docs/identity">identity and authentication</a>
     * documentation for more details on proper usage of the {@link TokenCredential} type.
     *
     * @param credential {@link TokenCredential} used to authorize requests sent to the service.
     * @return the updated SpecializedBlobClientBuilder
     * @throws NullPointerException If {@code credential} is {@code null}.
     */
    @Override
    public SpecializedBlobClientBuilder credential(TokenCredential credential) {
        this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
        this.storageSharedKeyCredential = null;
        this.sasToken = null;
        return this;
    }

    /**
     * Sets the SAS token used to authorize requests sent to the service.
     *
     * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters
     * (with or without a leading '?') and not a full url.
     * @return the updated SpecializedBlobClientBuilder
     * @throws NullPointerException If {@code sasToken} is {@code null}.
     */
    public SpecializedBlobClientBuilder sasToken(String sasToken) {
        this.sasToken = Objects.requireNonNull(sasToken,
            "'sasToken' cannot be null.");
        this.storageSharedKeyCredential = null;
        this.tokenCredential = null;
        return this;
    }

    /**
     * Sets the {@link AzureSasCredential} used to authorize requests sent to the service.
     *
     * @param credential {@link AzureSasCredential} used to authorize requests sent to the service.
     * @return the updated SpecializedBlobClientBuilder
     * @throws NullPointerException If {@code credential} is {@code null}.
     */
    @Override
    public SpecializedBlobClientBuilder credential(AzureSasCredential credential) {
        this.azureSasCredential = Objects.requireNonNull(credential,
            "'credential' cannot be null.");
        return this;
    }

    /**
     * Clears the credential used to authorize the request.
     *
     * <p>This is for blobs that are publicly accessible.</p>
     *
     * @return the updated SpecializedBlobClientBuilder
     */
    public SpecializedBlobClientBuilder setAnonymousAccess() {
        this.storageSharedKeyCredential = null;
        this.tokenCredential = null;
        this.azureSasCredential = null;
        this.sasToken = null;
        return this;
    }

    /**
     * Sets the connection string to connect to the service.
     *
     * @param connectionString Connection string of the storage account.
     * @return the updated SpecializedBlobClientBuilder
     * @throws IllegalArgumentException If {@code connectionString} in invalid.
     */
    @Override
    public SpecializedBlobClientBuilder connectionString(String connectionString) {
        StorageConnectionString storageConnectionString
                = StorageConnectionString.create(connectionString, LOGGER);
        StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint();
        if (endpoint == null || endpoint.getPrimaryUri() == null) {
            throw LOGGER
                    .logExceptionAsError(new IllegalArgumentException(
                            "connectionString missing required settings to derive blob service endpoint."));
        }
        this.endpoint(endpoint.getPrimaryUri());
        if (storageConnectionString.getAccountName() != null) {
            this.accountName = storageConnectionString.getAccountName();
        }
        StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings();
        if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) {
            this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(),
                    authSettings.getAccount().getAccessKey()));
        } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) {
            this.sasToken(authSettings.getSasToken());
        }
        return this;
    }

    /**
     * Sets the name of the container that contains the blob.
     *
     * <p><strong>Code Samples</strong></p>
     *
     * <!-- src_embed com.azure.storage.blob.specialized.BlobClientBase.Builder.containerName#String -->
     * <pre>
     * BlobClient client = new BlobClientBuilder()
     *     .endpoint(endpoint)
     *     .containerName(containerName)
     *     .buildClient();
     * </pre>
     * <!-- end com.azure.storage.blob.specialized.BlobClientBase.Builder.containerName#String -->
     *
     * @param containerName Name of the container. If the value {@code null} or empty the root container, {@code $root},
     * will be used.
     * @return the updated SpecializedBlobClientBuilder object
     */
    public SpecializedBlobClientBuilder containerName(String containerName) {
        this.containerName = containerName;
        return this;
    }

    /**
     * Sets the name of the blob.
     *
     * @param blobName Name of the blob.
     * @return the updated SpecializedBlobClientBuilder object
     * @throws NullPointerException If {@code blobName} is {@code null}
     */
    public SpecializedBlobClientBuilder blobName(String blobName) {
        this.blobName = Utility.urlEncode(Utility.urlDecode(Objects.requireNonNull(blobName,
            "'blobName' cannot be null.")));
        return this;
    }

    /**
     * Sets the snapshot identifier of the blob.
     *
     * @param snapshot Snapshot identifier for the blob.
     * @return the updated SpecializedBlobClientBuilder object
     */
    public SpecializedBlobClientBuilder snapshot(String snapshot) {
        this.snapshot = snapshot;
        return this;
    }

    /**
     * Sets the version identifier of the blob.
     *
     * @param versionId Version identifier for the blob, pass {@code null} to interact with the latest blob version.
     * @return the updated SpecializedBlobClientBuilder object
     */
    public SpecializedBlobClientBuilder versionId(String versionId) {
        this.versionId = versionId;
        return this;
    }

    /**
     * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
     *
     * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
     * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
     * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
     * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
     * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
     * documentation of types that implement this trait to understand the full set of implications.</p>
     *
     * @param httpClient The {@link HttpClient} to use for requests.
     * @return the updated SpecializedBlobClientBuilder object
     */
    @Override
    public SpecializedBlobClientBuilder httpClient(HttpClient httpClient) {
        if (this.httpClient != null && httpClient == null) {
            LOGGER.info("'httpClient' is being set to 'null' when it was previously configured.");
        }

        this.httpClient = httpClient;
        return this;
    }

    /**
     * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
     *
     * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
     * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
     * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
     * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
     * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
     * documentation of types that implement this trait to understand the full set of implications.</p>
     *
     * @param pipelinePolicy A {@link HttpPipelinePolicy pipeline policy}.
     * @return the updated SpecializedBlobClientBuilder object
     * @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
     */
    @Override
    public SpecializedBlobClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
        Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null");
        if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
            perCallPolicies.add(pipelinePolicy);
        } else {
            perRetryPolicies.add(pipelinePolicy);
        }
        return this;
    }

    /**
     * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
     * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set.
     *
     * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
     * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
     * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
     * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
     * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
     * documentation of types that implement this trait to understand the full set of implications.</p>
     *
     * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
     * and from the service.
     * @return the updated SpecializedBlobClientBuilder object
     * @throws NullPointerException If {@code logOptions} is {@code null}.
     */
    @Override
    public SpecializedBlobClientBuilder httpLogOptions(HttpLogOptions logOptions) {
        this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
        return this;
    }

    /**
     * Gets the default Storage allowlist log headers and query parameters.
     *
     * @return the default http log options.
     */
    public static HttpLogOptions getDefaultHttpLogOptions() {
        return BuilderHelper.getDefaultHttpLogOptions();
    }

    /**
     * Sets the configuration object used to retrieve environment configuration values during building of the client.
     *
     * @param configuration Configuration store used to retrieve environment configurations.
     * @return the updated SpecializedBlobClientBuilder object
     */
    @Override
    public SpecializedBlobClientBuilder configuration(Configuration configuration) {
        this.configuration = configuration;
        return this;
    }

    /**
     * Sets the request retry options for all the requests made through the client.
     *
     * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}.
     *
     * @param retryOptions {@link RequestRetryOptions}.
     * @return the updated SpecializedBlobClientBuilder object
     */
    public SpecializedBlobClientBuilder retryOptions(RequestRetryOptions retryOptions) {
        this.retryOptions = retryOptions;
        return this;
    }

    /**
     * Sets the {@link RetryOptions} for all the requests made through the client.
     *
     * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
     * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
     * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
     * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
     * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
     * documentation of types that implement this trait to understand the full set of implications.</p>
     * <p>
     * Setting this is mutually exclusive with using {@link #retryOptions(RequestRetryOptions)}.
     * Consider using {@link #retryOptions(RequestRetryOptions)} to also set storage specific options.
     *
     * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
     * @return the updated SpecializedBlobClientBuilder object
     */
    @Override
    public SpecializedBlobClientBuilder retryOptions(RetryOptions retryOptions) {
        this.coreRetryOptions = retryOptions;
        return this;
    }

    /**
     * Sets the {@link HttpPipeline} to use for the service client.
     *
     * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
     * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
     * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
     * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
     * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
     * documentation of types that implement this trait to understand the full set of implications.</p>
     * <p>
     * The {@link #endpoint(String) endpoint} is not ignored when {@code pipeline} is set.
     *
     * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
     * @return the updated SpecializedBlobClientBuilder object
     */
    @Override
    public SpecializedBlobClientBuilder pipeline(HttpPipeline httpPipeline) {
        if (this.httpPipeline != null && httpPipeline == null) {
            LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
        }

        this.httpPipeline = httpPipeline;
        return this;
    }

    /**
     * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
     * recommended that this method be called with an instance of the {@link HttpClientOptions}
     * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
     * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
     * interface.
     *
     * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
     * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
     * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
     * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
     * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
     * documentation of types that implement this trait to understand the full set of implications.</p>
     *
     * @param clientOptions A configured instance of {@link HttpClientOptions}.
     * @see HttpClientOptions
     * @return the updated SpecializedBlobClientBuilder object
     * @throws NullPointerException If {@code clientOptions} is {@code null}.
     */
    @Override
    public SpecializedBlobClientBuilder clientOptions(ClientOptions clientOptions) {
        this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null.");
        return this;
    }

    /**
     * Sets the {@link BlobServiceVersion} that is used when making API requests.
     * <p>
     * If a service version is not provided, the service version that will be used will be the latest known service
     * version based on the version of the client library being used. If no service version is specified, updating to a
     * newer version of the client library will have the result of potentially moving to a newer service version.
     * <p>
     * Targeting a specific service version may also mean that the service will return an error for newer APIs.
     *
     * @param version {@link BlobServiceVersion} of the service to be used when making requests.
     * @return the updated SpecializedBlobClientBuilder object
     */
    public SpecializedBlobClientBuilder serviceVersion(BlobServiceVersion version) {
        this.version = version;
        return this;
    }
}


text:
<TITLE>Review for Yi ge dou bu neng shao (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Yi ge dou bu neng shao (1999)

reviewed by
Edwin Jahiel

BY EDWIN JAHIEL

NOT ONE LESS ( Yi ge dou bu neng  shao) ( China, 1999) *** Directed
by Zhang Yimou. Written  by Shi Xiangsheng, from his novel.
Photography, Hou Yong. Editing, Zhai Ru. Art director, Cao Jiuping.
Music, San Bao. Cast: Wei Minzhi (Herself), Zhang Huike (Himself),
Tian Zhenda (Mayor Tian), Gao Enman (Teacher Gao), Sun Zhimei (Sun
Zhimei), Feng Yuying (Television Station Receptionist), Li Fanfan
(Television Host). Produced by Zhao Yu. A Sony Pictures Classics
release. In Mandarin (with English subtitles).  106 minutes.

The American director Joseph Von Sternberg (1894-1969) comes to mind
as I think of the Chinese director Zhang Yimou (b.1951). Sternberg
"created" Marlene Dietrich in the "Blue Angel" and six additional
films (1930-35), the high point of his career. Their relationship
went beyond cinema. Zhang Yimou's feature debut "Red Sorghum"  was
also that of actress Gong Li. The two were an "item" for about 8
years as he directed her in the highly successful, "Ju Dou," " Raise
the Red Lantern,"
"The Story of Qiu Ju," and "To Live" for a total of 7, including the
unfamiliar (to me) "Codename Cougar." Their last collaboration,
"ShanghaiTriad" (Yao a yao yao dao wai pei qiao) had mixed reviews.
Zhang-ites hope that now Pygmalion minus Galatea will not, as in
Sternberg's case, result in declining popularity.

"Not One Less" may put those fears to rest, although Zhang changed
style and content so radically that comparisons are not valid. His
early career was as a cinematographer. All his films until now have
powerful, creative visuals. But  here, the customary, delicate
bravura (not an oxymoron) of  often saturated colors, their
orchestrated, eye-arresting scenes, give way  to utter simplicity.
Made almost like a documentary, the pictures is  a cousin of
cinema-verite and Italian neorealism.

The village of Shuiquan seems to be in the middle of nowhere, but as
it turns out, is 3-4 hours by bus from Beijing. What makes one think
"boondocks," is generalized poverty and the fact that we see very
little of the place. The images are predominantly of a run-down,
one-classroom, one-teacher schoolhouse and of dusty dirt roads around
it.

Teacher Gao is leaving for a month to attend his ailing mother. Wei,
age 13, an elementary school graduate, has been hired as substitute
teacher. She's not much older than her pupils. And she does not know
much more than they do. The idea is to band-aid the emergency.. Wei
will receive 50 yuan at some point (which keeps eluding her) for a
month's work. It's essentially a kind of baby-sitting, just keep the
kids in class.

According to today's exchange rates, one yuan equals 12 US cents. At
the village, once can of Coca-Cola is either one or two yuans. Wei's
50 yuans come to $6.

Given the dire shape of the place, students who need to work for
their families or elsewhere drop school alarmingly fast --from 40 to
28 since the school year began. This menaces the subsidies to the
school (such as they are!). Teacher Gao warns Wei to hold the line.
He sweetens this by promising a bonus (10 yuan) if all 28 kids
remain. "Not One Less!"

The conditions at the school, and, surely, in the village, are
dismal. Wei and some kids (who is not clear) sleep in a horrid room.
Where their food comes from is also unclear. Chalk is rationed: one
per day. When some chalk trampled on , it is a catastrophe. There are
no books. Wei copies the lessons on the blackboard. She admonishes a
child  not to write too large or press too much since it uses up too
much chalk.

In Part Two of the film, a 10-year old boy, Zhang Huike, smart,
lively and prone to trouble-making (pitifully mild by American
standards) stops coming to school. His widowed mother is in debt.
Zhang went to the big, unnamed city to find work. Through
brick-moving the class collects   minuscule sum for Wei to go to the
city and search for the boy. It is unclear whether she does it to
keep the students at the 28 level, or to get her bonus --For a Few
Yuan More.

Her small adventures follow, there is a rather unlikely happy ending.
As Wei reaches the end of her rope, she is told to take her case to
almighty TV. The stumbling block is an autocratic,
bureaucratic-to-the-letter receptionist. But a manager ex machina
saves the day. Wei goes on a telecast, with a typically chatty,
elegant anchorwoman. The newness of it all literally dumbfounds Wei.
She freezes, says nothing.

The boy is found, he returns to the village with Wei and a camera
crew. But TV micro-celebrity and a gift of tons of chalks solve
nothing. End-titles tell us that a million children a year drop
school for work. It's a false figure. Reality is ten times higher.
But since this is a criticism of China's system, and since director
Zhang Yimou has often had troubles with the government and censors,
he lowered the figure to what authorities would deem acceptable.

In Italian neorealism the movies did not hesitate to show or denounce
evils by individuals as well as the state. Matters are much more
careful and balanced here, a bit as in old Soviet movies. The TV
station bureaucrat receptionist is scolded, and it another bureaucrat
who is helpful. The kindness of strangers gets some credit as a
restaurant helps hungry Zhan, although this is done primarily to
avoid his bothering the customers. You may glimpse a chic woman or
two but contrasts are kept down. No discotheques, no pricey stores.
You sense the movie's political prudence.

What's new and interesting is that almost all the characters are
non-actors who use their real names ands who do in real life what
they do on the screen --starting with Wei who was chosen from an
enormous field of candidates. What is most successful is how well,
starting again with Wei, all those non-professionals fit their roles
and situations. Were that the movie could give a big boost to the
casting of amateurs. If this escalates the multi-million-dollar
salaries of stars could go the way of the walls of Jericho. Fat
chance.

"Le mauvais gout mene au crime"(Stendhal)

Edwin Jahiel's film reviews are at: http://www.prairienet.org/ejahiel/

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews

redpajama_set_name: RedPajamaGithub


text:
module Acceptance
  include PavlovSupport

  def sign_in_user(user)
    visit factlink_accounts_new_path
    fill_in "user_new_session[email]", with: user.email
    fill_in "user_new_session[password]", with: user.password
    click_button "Sign in"

    user
  end

  def switch_to_user(user)
    sign_out_user
    sign_in_user(user)
  end

  def sign_out_user
    visit "/users/sign_out"
  end

  def enable_global_features(*features)
    fail "FeatureNonExistent" unless features.all? { |f| Ability::FEATURES.include? f.to_s }

    as(create :user, :confirmed, :admin) do |pavlov|
      pavlov.interactor(:'global_features/set', features: features)
    end
  end

  def disable_html5_validations(page)
    page.execute_script "$('form').attr('novalidate','novalidate')"
  end

  def eventually_succeeds(wait_time=nil, &block)
    wait_time ||= Capybara.default_wait_time
    start_time = Time.now
    begin
      yield
    rescue => e
      if (Time.now - start_time) >= wait_time then
        raise e
      end
      sleep(0.05)
      retry
    end
  end

  def wait_for_ajax_idle
    eventually_succeeds do
      # wait for all ajax requests to complete
      # if we don't wait, the server may see it after the db is cleaned
      # and a request for a removed object will cause a crash (nil ref).
      unless page.evaluate_script('(!window.jQuery || window.jQuery.active == 0)')
        fail 'jQuery.active is not zero; did an Ajax callback perhaps crash?'
      end
    end
  end
end


text:
<?php

/**
 * Register the 'monocle-image' shortcode
 *
 * @since 1.0
 */
if ( ! function_exists('monocle_image_shortcode') )
{
	function monocle_image_shortcode( $attr, $content=null ) {
		return "<img class='monocle-wp-init' src=\"{$attr['src']}\" />";
	}
	add_shortcode('monocle-image','monocle_image_shortcode');
}


text:
@class SLPhotoView;

@protocol SLPhotoViewDelegate <NSObject>

@optional
- (void)photoView:(SLPhotoView *)photoView didShowPhotoIndex:(NSUInteger)index totalCount:(NSUInteger)count;

@end

@interface SLPhotoView : UIView

@property (nonatomic, strong) UIImage *imgPlaceholder;    // 占位图片
@property (nonatomic, strong) UIImage *imgBroken;          // 加载失败图片
@property (nonatomic, strong) NSArray *imgUrls;            // 图片路径数组
@property (nonatomic, assign) NSInteger imgIndex;           // 显示的图片
@property (nonatomic, strong) id<SLPhotoViewDelegate> delegate;

- (instancetype)initWithPlaceholderImg:(UIImage *)imgPlaceholder brokenImg:(UIImage *)imgBroken imgUrlArray:(NSArray *)imgUrls imgIndex:(NSInteger)imgIndex;

- (void)show;

@end


text:
read -p "gimme a string " str
if [[ $str =~ ^a ]] ; then
  echo $str begins with a
else
  echo $str does not begin with
fi
if [[ $str =~ a$ ]] ; then
  echo $str ends with a
else
  echo $str does not end with a
fi
# make it case insensitive Character classes [] are like bash file name
# globbing they apply to one character
if [[ $str =~ ^[aA] ]] ; then
  echo $str begins with a or A
else
  echo $str does not begin with a or A
fi
if [[ $str =~ [aA]$ ]] ; then
  echo $str ends with a or A
else
  echo $str does not end with a or A
fi
if [[ $str =~ ^a ]] ; then
  echo $str begins with a
else
  echo $str does not begin with
fi
if [[ $str =~ a$ ]] ; then
  echo $str ends with a
else
  echo $str does not end with a
fi


text:
/*global ga: false */

var config = require('./config');

var dispatch = (window.ga && config.ga_id) ?
	(...args) => window.ga('send', 'event', ...args) :
	(...args) => console.log('event', ...args);

module.exports = dispatch;


text:
import annotation._

@SerialVersionUID(42) @strictfp class Foo[@specialized(Int) T] extends Serializable {
  def foo(t: T) = t
}

object Test extends App {
  def checkUID(cls: Class[_], expected: Long) = {
    val actual = java.io.ObjectStreamClass.lookup(cls).getSerialVersionUID
    assert(actual == expected, s"$actual != expected for ${cls}")
  }
  def checkStrictFp(cls: Class[_]) = {
    import java.lang.reflect._
    for (m <- cls.getDeclaredMethods) {
      val isStrict = Modifier.isStrict(m.getModifiers)
      assert(isStrict, cls)
    }
  }
  def check(x: AnyRef) {
    checkUID(x.getClass, 42)
    checkStrictFp(x.getClass)
  }

  check(new Foo[String])
  check(new Foo[Int])
}


text:
""" Exceptions used by Home Assistant """

class HomeAssistantError(Exception):
    """ General Home Assistant exception occured. """
    pass

class InvalidEntityFormatError(HomeAssistantError):
    """ When an invalid formatted entity is encountered. """
    pass

class NoEntitySpecifiedError(HomeAssistantError):
    """ When no entity is specified. """
    pass

class TemplateError(HomeAssistantError):
    """ Error during template rendering. """
    def __init__(self, exception):
        super().__init__('{}: {}'.format(exception.__class__.__name__,
                                         exception))


text:
<?php

namespace CodeYellow\Queue;

/**
 * @group queue
 * @group queue-jobs
 */
class Test_Jobs extends \PHPUnit_Framework_TestCase
{

    public static $queue = null;
    public static $queue2 = null;

    // Prevents double queues from forming
    public function __construct()
    {
        if (static::$queue !== null) {
            return;
        }

        $queueName = time() . '_Jobs';
        static::$queue = new Queue;
        static::$queue->create($queueName);

        $queueName = time() . '_Jobs2';
        static::$queue2 = new Queue;
        static::$queue2->create($queueName);
    }

    ///////////////////////////TESTS////////////////////////////////

    // Test if we can create and load a job
    // Implicitly tests the loadFromArray function
    public function testCreateLoad()
    {
        $class = "\Dependency";
        $method = "noException";
        $args = array('testarg' => 'test');
        $queueId = static::$queue->getId();
        $priority = Job::PRIORITY_HIGH;
        $executeAfter = 10;
        $startTime = time();

        $job = new Job;
        $jobid = $job->create(
            $class,
            $method,
            $args,
            $queueId,
            $priority,
            $executeAfter
        )->getId();

        $job2 = new Job;
        $job2->load($jobid);

        $this->assertEquals($jobid, $job2->getId());
        $this->assertEquals($method, $job2->getFunction());
        $this->assertEquals($args, $job2->getArgs());
        $this->assertEquals($queueId, $job2->getQueueId());
        $this->assertEquals($executeAfter, $job2->getExecuteAfter());

        //Less than to prevent errors caused by slow database
        $this->assertLessThan(5, $job2->getTimeAdded() - $startTime);
        $this->assertEquals(0, $job2->getTimeExecuted());
        $this->assertEquals($priority, $job2->getPriority());
        $this->assertEquals(Job::STATUS_IN_QUEUE, $job2->getStatus());
    }

    // Test if a non array for arguments creates an error
    /**
     * @expectedException \CodeYellow\Queue\Exception\InvalidArguments
     */
    public function testCreateInvalidArgumentsException()
    {
        $class = "\Dependency";
        $method = "noException";
        $args = 'testarg';
        $queueId = static::$queue->getId();
        $priority = Job::PRIORITY_HIGH;
        $executeAfter = 10;
        $startTime = time();

        $job = new Job;
        $jobid = $job->create(
            $class,
            $method,
            $args,
            $queueId,
            $priority,
            $executeAfter
        );
    }

    // Test if default priority of the queue is medium
    public function testCheckDefaultPriority()
    {
        $job = new Job('Test', 'Test', array(), static::$queue->getId());
        $this->assertEquals(Job::PRIORITY_MEDIUM, $job->getPriority());
    }

    // Test if args = null no exception occurs
    public function testCreateNullArgumentsNoException()
    {
        $class = "\Dependency";
        $method = "noException";
        $args = null;
        $queueId = static::$queue->getId();
        $priority = Job::PRIORITY_HIGH;
        $executeAfter = 10;
        $startTime = time();

        $job = new Job;
        $jobid = $job->create($class, $method, $args, $queueId, $priority, $executeAfter);
    }

    // Regression test: original code created "impossible arrays" which had
    // numerical-looking string indices, which are impossible to dereference.
    public function testIntegerKeysCreateValidArrays()
    {
        $class = "\Dependency";
        $method = "noException";
        $args = array('1' => 'one', 'foo' => 2);
        $queueId = static::$queue->getId();
        $priority = Job::PRIORITY_HIGH;
        $executeAfter = 10;
        $startTime = time();

        $job = new Job;
        $job = $job->create($class, $method, $args, $queueId, $priority, $executeAfter);
        $job->load($job->getId()); // reload, just in case
        $args = $job->getArgs();
        $this->assertEquals('one', $args[1]);
    }

    //Test if an exception occurs if we select an invalid queue
    /**
     * @expectedException \CodeYellow\Queue\Exception\QueueNotExists
     */
    public function testCreateQueueNotExistsException()
    {
        \Config::set('queue.implicit_queue_creation', false);
        $class = "\Dependency";
        $method = "noException";
        $args = null;
        $queueId = -1;
        $priority = Job::PRIORITY_HIGH;
        $executeAfter = 10;
        $startTime = time();

        $job = new Job;
        $job->create(
            $class,
            $method,
            $args,
            $queueId,
            $priority,
            $executeAfter
        );
    }

    //Test if an exception occurs if we load an invalid job
    /**
     * @expectedException \CodeYellow\Queue\Exception\JobNotFound
     */
    public function testLoadJobNotFoundException()
    {
        $job = new Job;
        $job->load(-1);
    }

    // Test all the getters and setters
    // Implicitly tests the save function
    public function testGettersSetters()
    {
        $class = "\Dependency";
        $newClass = "\Test";
        $method = "noException";
        $newMethod = "withException";
        $args = array('testarg' => 'test');
        $newArgs = array('a' => 'b');
        $queueId = static::$queue->getId();
        $newQueueId = static::$queue2->getId();
        $priority = Job::PRIORITY_HIGH;
        $newPriority = Job::PRIORITY_LOW;
        $executeAfter = 10;
        $newExecuteAfter = 100;
        $newStatus = Job::STATUS_DONE;

        $job = new Job;
        $jobid = $job->create(
            $class,
            $method,
            $args,
            $queueId,
            $priority,
            $executeAfter
        )->getId();

        // Set all variable to the new value
        $job->setClass($newClass);
        $job->setFunction($newMethod);
        $job->setArgs($newArgs);
        $job->setExecuteAfter($newExecuteAfter);
        $job->setQueueId($newQueueId);
        $job->setStatus($newStatus);
        $job->setPriority($newPriority);

        $job2 = new Job;
        $job2->load($jobid);

        // check if it is correctly saved locally
        $this->assertEquals($newClass, $job->getClass());
        $this->assertEquals($newMethod, $job->getFunction());
        $this->assertEquals($newArgs, $job->getArgs());
        $this->assertEquals($newQueueId, $job->getQueueId());
        $this->assertEquals($newStatus, $job->getStatus());
        $this->assertEquals($newPriority, $job->getPriority());

        // check if it is correctly saved in the database
        $this->assertEquals($newClass, $job2->getClass());
        $this->assertEquals($newMethod, $job2->getFunction());
        $this->assertEquals($newArgs, $job2->getArgs());
        $this->assertEquals($newQueueId, $job2->getQueueId());
        $this->assertEquals($newStatus, $job2->getStatus());
        $this->assertEquals($newPriority, $job2->getPriority());
    }

    // Test if a job creation with queue name works be found
    public function testCreateWithQueueName()
    {
        $class = "\Dependency";
        $method = "noException";
        $args = null;
        $queueId = static::$queue->getName();
        $priority = Job::PRIORITY_HIGH;
        $executeAfter = 10;
        $startTime = time();

        $job = new Job;
        $jobId = $job->create(
            $class,
            $method,
            $args,
            $queueId,
            $priority,
            $executeAfter
        );

        $this->assertEquals($job->getQueueId(), static::$queue->getId());
    }

    // Test if chaining works
    public function testChaining()
    {
        $job = (new Job())
            ->create(
                'TEST',
                'TEST',
                array(),
                static::$queue->getId()
            );
        $this->assertEquals($job->getQueueId(), static::$queue->getId());

        $job = $job
            ->setClass('test2')
            ->setFunction('testfunc')
            ->setArgs(array('a'=>'b'))
            ->setExecuteAfter(10)
            ->setQueueId(static::$queue2->getid())
            ->setStatus(Job::STATUS_IN_QUEUE)
            ->setTimeExecuted()
            ->setPriority(Job::PRIORITY_HIGH);

        $this->assertEquals($job->getClass(), 'test2');
        $this->assertEquals($job->getFunction(), 'testfunc');
        $this->assertEquals($job->getArgs(), array('a'=>'b'));
        $this->assertEquals($job->getExecuteAfter(), 10);
        $this->assertEquals($job->getQueueId(), static::$queue2->getid());
        $this->assertEquals($job->getStatus(), Job::STATUS_IN_QUEUE);
        $this->assertEquals($job->getPriority(), Job::PRIORITY_HIGH);
    }

    public function testCreateImplicitQueue()
    {
        \Config::set('queue.implicit_queue_creation', true);
        $class = "\Dependency";
        $method = "noException";
        $args = null;
        $queueId = "test";
        $priority = Job::PRIORITY_HIGH;
        $executeAfter = 10;
        $startTime = time();

        $job = new Job;
        $job->create(
            $class,
            $method,
            $args,
            $queueId,
            $priority,
            $executeAfter
        );

    }
}


text:
package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/test-infra/prow/pjutil"

	"k8s.io/test-infra/pkg/flagutil"
	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/config/secret"
	prowflagutil "k8s.io/test-infra/prow/flagutil"
	"k8s.io/test-infra/prow/kube"
	"k8s.io/test-infra/prow/logrusutil"
	"k8s.io/test-infra/prow/metrics"
	"k8s.io/test-infra/prow/plank"
)

type options struct {
	totURL string

	configPath    string
	jobConfigPath string
	buildCluster  string
	selector      string
	skipReport    bool

	dryRun     bool
	kubernetes prowflagutil.KubernetesOptions
	github     prowflagutil.GitHubOptions
}

func gatherOptions() options {
	o := options{}
	fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)

	fs.StringVar(&o.totURL, "tot-url", "", "Tot URL")

	fs.StringVar(&o.configPath, "config-path", "", "Path to config.yaml.")
	fs.StringVar(&o.jobConfigPath, "job-config-path", "", "Path to prow job configs.")
	fs.StringVar(&o.buildCluster, "build-cluster", "", "Path to file containing a YAML-marshalled kube.Cluster object. If empty, uses the local cluster.")
	fs.StringVar(&o.selector, "label-selector", kube.EmptySelector, "Label selector to be applied in prowjobs. See https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors for constructing a label selector.")
	fs.BoolVar(&o.skipReport, "skip-report", false, "Whether or not to ignore report with githubClient")

	fs.BoolVar(&o.dryRun, "dry-run", true, "Whether or not to make mutating API calls to GitHub.")
	for _, group := range []flagutil.OptionGroup{&o.kubernetes, &o.github} {
		group.AddFlags(fs)
	}

	fs.Parse(os.Args[1:])
	o.configPath = config.ConfigPath(o.configPath)
	return o
}

func (o *options) Validate() error {
	for _, group := range []flagutil.OptionGroup{&o.kubernetes, &o.github} {
		if err := group.Validate(o.dryRun); err != nil {
			return err
		}
	}

	if _, err := labels.Parse(o.selector); err != nil {
		return fmt.Errorf("parse label selector: %v", err)
	}

	return nil
}

func main() {
	o := gatherOptions()
	if err := o.Validate(); err != nil {
		logrus.WithError(err).Fatal("Invalid options")
	}

	logrus.SetFormatter(
		logrusutil.NewDefaultFieldsFormatter(nil, logrus.Fields{"component": "plank"}),
	)

	pjutil.ServePProf()

	configAgent := &config.Agent{}
	if err := configAgent.Start(o.configPath, o.jobConfigPath); err != nil {
		logrus.WithError(err).Fatal("Error starting config agent.")
	}
	cfg := configAgent.Config

	secretAgent := &secret.Agent{}
	if o.github.TokenPath != "" {
		if err := secretAgent.Start([]string{o.github.TokenPath}); err != nil {
			logrus.WithError(err).Fatal("Error starting secrets agent.")
		}
	}

	githubClient, err := o.github.GitHubClient(secretAgent, o.dryRun)
	if err != nil {
		logrus.WithError(err).Fatal("Error getting GitHub client.")
	}

	kubeClient, err := o.kubernetes.Client(cfg().ProwJobNamespace, o.dryRun)
	if err != nil {
		logrus.WithError(err).Fatal("Error getting kube client.")
	}

	var pkcs map[string]*kube.Client
	if o.dryRun {
		pkcs = map[string]*kube.Client{kube.DefaultClusterAlias: kubeClient}
	} else {
		if o.buildCluster == "" {
			pkc, err := kube.NewClientInCluster(cfg().PodNamespace)
			if err != nil {
				logrus.WithError(err).Fatal("Error getting kube client.")
			}
			pkcs = map[string]*kube.Client{kube.DefaultClusterAlias: pkc}
		} else {
			pkcs, err = kube.ClientMapFromFile(o.buildCluster, cfg().PodNamespace)
			if err != nil {
				logrus.WithError(err).Fatal("Error getting kube client to build cluster.")
			}
		}
	}

	c, err := plank.NewController(kubeClient, pkcs, githubClient, nil, cfg, o.totURL, o.selector, o.skipReport)
	if err != nil {
		logrus.WithError(err).Fatal("Error creating plank controller.")
	}

	// Push metrics to the configured prometheus pushgateway endpoint.
	pushGateway := cfg().PushGateway
	if pushGateway.Endpoint != "" {
		go metrics.PushMetrics("plank", pushGateway.Endpoint, pushGateway.Interval)
	}
	// serve prometheus metrics.
	go serve()
	// gather metrics for the jobs handled by plank.
	go gather(c)

	tick := time.Tick(30 * time.Second)
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM)

	for {
		select {
		case <-tick:
			start := time.Now()
			if err := c.Sync(); err != nil {
				logrus.WithError(err).Error("Error syncing.")
			}
			logrus.WithField("duration", fmt.Sprintf("%v", time.Since(start))).Info("Synced")
		case <-sig:
			logrus.Info("Plank is shutting down...")
			return
		}
	}
}

// serve starts a http server and serves prometheus metrics.
// Meant to be called inside a goroutine.
func serve() {
	http.Handle("/metrics", promhttp.Handler())
	logrus.WithError(http.ListenAndServe(":8080", nil)).Fatal("ListenAndServe returned.")
}

// gather metrics from plank.
// Meant to be called inside a goroutine.
func gather(c *plank.Controller) {
	tick := time.Tick(30 * time.Second)
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM)

	for {
		select {
		case <-tick:
			start := time.Now()
			c.SyncMetrics()
			logrus.WithField("metrics-duration", fmt.Sprintf("%v", time.Since(start))).Debug("Metrics synced")
		case <-sig:
			logrus.Debug("Plank gatherer is shutting down...")
			return
		}
	}
}


text:
package apple.avfoundation.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NInt;

@Generated
public final class AVError {
    @Generated @NInt public static final long Unknown = 0xFFFFFFFFFFFFD1E8L;
    @Generated @NInt public static final long OutOfMemory = 0xFFFFFFFFFFFFD1E7L;
    @Generated @NInt public static final long SessionNotRunning = 0xFFFFFFFFFFFFD1E5L;
    @Generated @NInt public static final long DeviceAlreadyUsedByAnotherSession = 0xFFFFFFFFFFFFD1E4L;
    @Generated @NInt public static final long NoDataCaptured = 0xFFFFFFFFFFFFD1E3L;
    @Generated @NInt public static final long SessionConfigurationChanged = 0xFFFFFFFFFFFFD1E2L;
    @Generated @NInt public static final long DiskFull = 0xFFFFFFFFFFFFD1E1L;
    @Generated @NInt public static final long DeviceWasDisconnected = 0xFFFFFFFFFFFFD1E0L;
    @Generated @NInt public static final long MediaChanged = 0xFFFFFFFFFFFFD1DFL;
    @Generated @NInt public static final long MaximumDurationReached = 0xFFFFFFFFFFFFD1DEL;
    @Generated @NInt public static final long MaximumFileSizeReached = 0xFFFFFFFFFFFFD1DDL;
    @Generated @NInt public static final long MediaDiscontinuity = 0xFFFFFFFFFFFFD1DCL;
    @Generated @NInt public static final long MaximumNumberOfSamplesForFileFormatReached = 0xFFFFFFFFFFFFD1DBL;
    @Generated @NInt public static final long DeviceNotConnected = 0xFFFFFFFFFFFFD1DAL;
    @Generated @NInt public static final long DeviceInUseByAnotherApplication = 0xFFFFFFFFFFFFD1D9L;
    @Generated @NInt public static final long DeviceLockedForConfigurationByAnotherProcess = 0xFFFFFFFFFFFFD1D7L;
    @Generated @NInt public static final long SessionWasInterrupted = 0xFFFFFFFFFFFFD1D6L;
    @Generated @NInt public static final long MediaServicesWereReset = 0xFFFFFFFFFFFFD1D5L;
    @Generated @NInt public static final long ExportFailed = 0xFFFFFFFFFFFFD1D4L;
    /**
     * userInfo may contain AVErrorMediaTypeKey, AVErrorMediaSubTypeKey & AVErrorPresentationTimeStampKey, if available
     */
    @Generated @NInt public static final long DecodeFailed = 0xFFFFFFFFFFFFD1D3L;
    @Generated @NInt public static final long InvalidSourceMedia = 0xFFFFFFFFFFFFD1D2L;
    @Generated @NInt public static final long FileAlreadyExists = 0xFFFFFFFFFFFFD1D1L;
    @Generated @NInt public static final long CompositionTrackSegmentsNotContiguous = 0xFFFFFFFFFFFFD1D0L;
    @Generated @NInt public static final long InvalidCompositionTrackSegmentDuration = 0xFFFFFFFFFFFFD1CFL;
    @Generated @NInt public static final long InvalidCompositionTrackSegmentSourceStartTime = 0xFFFFFFFFFFFFD1CEL;
    @Generated @NInt public static final long InvalidCompositionTrackSegmentSourceDuration = 0xFFFFFFFFFFFFD1CDL;
    @Generated @NInt public static final long FileFormatNotRecognized = 0xFFFFFFFFFFFFD1CCL;
    @Generated @NInt public static final long FileFailedToParse = 0xFFFFFFFFFFFFD1CBL;
    @Generated @NInt public static final long MaximumStillImageCaptureRequestsExceeded = 0xFFFFFFFFFFFFD1CAL;
    @Generated @NInt public static final long ContentIsProtected = 0xFFFFFFFFFFFFD1C9L;
    @Generated @NInt public static final long NoImageAtTime = 0xFFFFFFFFFFFFD1C8L;
    /**
     * userInfo may contain AVErrorMediaTypeKey & AVErrorMediaSubTypeKey, if available
     */
    @Generated @NInt public static final long DecoderNotFound = 0xFFFFFFFFFFFFD1C7L;
    /**
     * userInfo may contain AVErrorMediaTypeKey & AVErrorMediaSubTypeKey, if available
     */
    @Generated @NInt public static final long EncoderNotFound = 0xFFFFFFFFFFFFD1C6L;
    @Generated @NInt public static final long ContentIsNotAuthorized = 0xFFFFFFFFFFFFD1C5L;
    @Generated @NInt public static final long ApplicationIsNotAuthorized = 0xFFFFFFFFFFFFD1C4L;
    @Deprecated @Generated @NInt public static final long DeviceIsNotAvailableInBackground = 0xFFFFFFFFFFFFD1C3L;
    @Generated @NInt public static final long OperationNotSupportedForAsset = 0xFFFFFFFFFFFFD1C2L;
    /**
     * userInfo may contain AVErrorMediaTypeKey & AVErrorMediaSubTypeKey, if available
     */
    @Generated @NInt public static final long DecoderTemporarilyUnavailable = 0xFFFFFFFFFFFFD1C1L;
    /**
     * userInfo may contain AVErrorMediaTypeKey & AVErrorMediaSubTypeKey, if available
     */
    @Generated @NInt public static final long EncoderTemporarilyUnavailable = 0xFFFFFFFFFFFFD1C0L;
    @Generated @NInt public static final long InvalidVideoComposition = 0xFFFFFFFFFFFFD1BFL;
    @Generated @NInt public static final long ReferenceForbiddenByReferencePolicy = 0xFFFFFFFFFFFFD1BEL;
    @Generated @NInt public static final long InvalidOutputURLPathExtension = 0xFFFFFFFFFFFFD1BDL;
    @Generated @NInt public static final long ScreenCaptureFailed = 0xFFFFFFFFFFFFD1BCL;
    @Generated @NInt public static final long DisplayWasDisabled = 0xFFFFFFFFFFFFD1BBL;
    @Generated @NInt public static final long TorchLevelUnavailable = 0xFFFFFFFFFFFFD1BAL;
    @Generated @NInt public static final long OperationInterrupted = 0xFFFFFFFFFFFFD1B9L;
    @Generated @NInt public static final long IncompatibleAsset = 0xFFFFFFFFFFFFD1B8L;
    @Generated @NInt public static final long FailedToLoadMediaData = 0xFFFFFFFFFFFFD1B7L;
    @Generated @NInt public static final long ServerIncorrectlyConfigured = 0xFFFFFFFFFFFFD1B6L;
    @Generated @NInt public static final long ApplicationIsNotAuthorizedToUseDevice = 0xFFFFFFFFFFFFD1B4L;
    @Generated @NInt public static final long FailedToParse = 0xFFFFFFFFFFFFD1B3L;
    /**
     * userInfo contains AVErrorFileTypeKey
     */
    @Generated @NInt public static final long FileTypeDoesNotSupportSampleReferences = 0xFFFFFFFFFFFFD1B2L;
    @Generated @NInt public static final long UndecodableMediaData = 0xFFFFFFFFFFFFD1B1L;
    @Generated @NInt public static final long AirPlayControllerRequiresInternet = 0xFFFFFFFFFFFFD1B0L;
    @Generated @NInt public static final long AirPlayReceiverRequiresInternet = 0xFFFFFFFFFFFFD1AFL;
    @Generated @NInt public static final long VideoCompositorFailed = 0xFFFFFFFFFFFFD1AEL;
    /**
     * on iOS, AVCaptureMovieFileOutput only supports one recording at a time
     */
    @Generated @NInt public static final long RecordingAlreadyInProgress = 0xFFFFFFFFFFFFD1ADL;
    @Generated @NInt public static final long UnsupportedOutputSettings = 0xFFFFFFFFFFFFD1ABL;
    @Generated @NInt public static final long OperationNotAllowed = 0xFFFFFFFFFFFFD1AAL;

    @Generated
    private AVError() {
    }

    @Generated @NInt public static final long ContentIsUnavailable = 0xFFFFFFFFFFFFD1A9L;
    @Generated @NInt public static final long FormatUnsupported = 0xFFFFFFFFFFFFD1A8L;
    @Generated @NInt public static final long MalformedDepth = 0xFFFFFFFFFFFFD1A7L;
    @Generated @NInt public static final long ContentNotUpdated = 0xFFFFFFFFFFFFD1A6L;
    @Generated @NInt public static final long NoLongerPlayable = 0xFFFFFFFFFFFFD1A5L;
    @Generated @NInt public static final long NoCompatibleAlternatesForExternalDisplay = 0xFFFFFFFFFFFFD1A4L;
    @Generated @NInt public static final long NoSourceTrack = 0xFFFFFFFFFFFFD1A3L;
    @Generated @NInt public static final long ExternalPlaybackNotSupportedForAsset = 0xFFFFFFFFFFFFD1A2L;
    @Generated @NInt public static final long OperationNotSupportedForPreset = 0xFFFFFFFFFFFFD1A1L;
    @Generated @NInt public static final long SessionHardwareCostOverage = 0xFFFFFFFFFFFFD1A0L;
    @Generated @NInt public static final long UnsupportedDeviceActiveFormat = 0xFFFFFFFFFFFFD19FL;
    @Generated @NInt public static final long IncorrectlyConfigured = 0xFFFFFFFFFFFFD19DL;
    @Generated @NInt public static final long SegmentStartedWithNonSyncSample = 0xFFFFFFFFFFFFD19CL;
    @Generated @NInt public static final long RosettaNotInstalled = 0xFFFFFFFFFFFFD19BL;
    @Generated @NInt public static final long OperationCancelled = 0xFFFFFFFFFFFFD19AL;
    @Generated @NInt public static final long ContentKeyRequestCancelled = 0xFFFFFFFFFFFFD199L;
}


text:
import imageDiffHelper from './helpers/index';
import { viewTypes, isValidViewType } from './view_types';
import ImageDiff from './image_diff';

export default class ReplacedImageDiff extends ImageDiff {
  init(defaultViewType = viewTypes.TWO_UP) {
    this.imageFrameEls = {
      [viewTypes.TWO_UP]: this.el.querySelector('.two-up .js-image-frame'),
      [viewTypes.SWIPE]: this.el.querySelector('.swipe .js-image-frame'),
      [viewTypes.ONION_SKIN]: this.el.querySelector('.onion-skin .js-image-frame'),
    };

    const viewModesEl = this.el.querySelector('.view-modes-menu');
    this.viewModesEls = {
      [viewTypes.TWO_UP]: viewModesEl.querySelector('.two-up'),
      [viewTypes.SWIPE]: viewModesEl.querySelector('.swipe'),
      [viewTypes.ONION_SKIN]: viewModesEl.querySelector('.onion-skin'),
    };

    this.currentView = defaultViewType;
    this.generateImageEls();
    this.bindEvents();
  }

  generateImageEls() {
    this.imageEls = {};

    const viewTypeNames = Object.getOwnPropertyNames(viewTypes);
    viewTypeNames.forEach(viewType => {
      this.imageEls[viewType] = this.imageFrameEls[viewType].querySelector('img');
    });
  }

  bindEvents() {
    super.bindEvents();

    this.changeToViewTwoUp = this.changeView.bind(this, viewTypes.TWO_UP);
    this.changeToViewSwipe = this.changeView.bind(this, viewTypes.SWIPE);
    this.changeToViewOnionSkin = this.changeView.bind(this, viewTypes.ONION_SKIN);

    this.viewModesEls[viewTypes.TWO_UP].addEventListener('click', this.changeToViewTwoUp);
    this.viewModesEls[viewTypes.SWIPE].addEventListener('click', this.changeToViewSwipe);
    this.viewModesEls[viewTypes.ONION_SKIN].addEventListener('click', this.changeToViewOnionSkin);
  }

  get imageEl() {
    return this.imageEls[this.currentView];
  }

  get imageFrameEl() {
    return this.imageFrameEls[this.currentView];
  }

  changeView(newView) {
    if (!isValidViewType(newView)) {
      return;
    }

    const indicator = imageDiffHelper.removeCommentIndicator(this.imageFrameEl);

    this.currentView = newView;

    // Clear existing badges on new view
    const existingBadges = this.imageFrameEl.querySelectorAll('.badge');
    [...existingBadges].map(badge => badge.remove());

    // Remove existing references to old view image badges
    this.imageBadges = [];

    // Image_file.js has a fade animation of 200ms for loading the view
    // Need to wait an additional 250ms for the images to be displayed
    // on window in order to re-normalize their dimensions
    setTimeout(this.renderNewView.bind(this, indicator), 250);
  }

  renderNewView(indicator) {
    // Generate badge coordinates on new view
    this.renderBadges();

    // Re-render indicator in new view
    if (indicator.removed) {
      const normalizedIndicator = imageDiffHelper.resizeCoordinatesToImageElement(this.imageEl, {
        x: indicator.x,
        y: indicator.y,
        width: indicator.image.width,
        height: indicator.image.height,
      });
      imageDiffHelper.showCommentIndicator(this.imageFrameEl, normalizedIndicator);
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/write"
              android:orientation="vertical">
    <include layout="@layout/lines"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="4"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="5dp">
            <TextView
                android:id="@+id/chat_item_left_item_302000_tv_article"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New Text"
                android:textSize="@dimen/unite_pro_item_black_textSize"
                android:textColor="@color/black"/>
            <TextView
                android:id="@+id/chat_item_left_item_302000_tv_source"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New Text"
                android:textSize="@dimen/unite_pro_item_greay_textSize"
                android:textColor="@color/gary"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/chat_item_left_item_302000_iv_icon"
                android:layout_width="@dimen/unite_pro_item_icon_height"
                android:layout_height="@dimen/unite_pro_item_icon_height"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>


text:
//
//  include/arch_info.h
//  tbd
//
//  Created by inoahdev on 11/19/18.
//  Copyright © 2018 - 2020 inoahdev. All rights reserved.
//

#ifndef ARCH_INFO_H
#define ARCH_INFO_H

#include "mach-o/loader.h"
#include "notnull.h"

struct arch_info {
    cpu_type_t cputype;
    cpu_subtype_t cpusubtype;

    const char *name;
    uint64_t name_length;
} __attribute__((aligned(16)));

const struct arch_info *__notnull arch_info_get_list(void);
uint64_t arch_info_list_get_size(void);

const struct arch_info *
arch_info_for_cputype(cpu_type_t cputype, cpu_subtype_t cpusubtype);

const struct arch_info *arch_info_for_name(const char *__notnull name);

#endif /* ARCH_INFO_H */


text:
<?php

require_once __DIR__ . '/config.php';

session_start();
$_SESSION = array();
session_destroy();
header('Location: index.html');


text:
<fieldset style='border:none;width:1100px;position:absolute;'>
About Us

Leaf Hint is a search engine where students can search for the information related to their friends and for
some unknown student of UPES (University of Petroleum and Energy Studies). We have registered 1,254 B.tech (2013-17) batch automatically and rest of the students can register at
main page.

Leaf Hint can be considered as a company or an organisation founded by Nishant Thapliyal from
B.Tech CSE Oil & Gas Informatics. This site was initialized as a search engine but we are trying to upgrade it to another level and hence we have created
a login system so that it is easier for you to search and also to edit your profile in your own way.

Privacy Policy & Terms of Use

If you are using this site or signing up then you need to know all about our terms and conditions, data usage policy, cookies, sessions, privacy policy and more.
We are trying to make this site secure so that no one can miss use your data and digital images of users available at this site.

Like many other Web sites, Leaf Hint makes use of log files.
The information inside the log files includes internet protocol
( IP ) addresses, type of browser, Internet Service Provider ( ISP ), date/time stamp, referring/exit pages, and number of clicks to analyze trends,
 administer the site, track users movement around the site, and gather demographic information. IP addresses, and other such information are not
 linked to any information that is personally identifiable.

 If we talk about cookies then Leaf Hint is not using cookies but when we will integrate our
 web site with third party vendor like Google, Flipkart, Amazon to deliver digital advertisement to monetize our website then they can use it
to store information about visitors preferences, record user-specific information on which pages the user access or visit, customize web page content based on
 visitors browser type or other information that the visitor sends via their browser.

Right now we are not delivering any kinda advertisement so don't give much stress to cookies and when we will integrate digital advertisement then we may
or may not inform you. You should consult the respective privacy policies of these third-party ad servers for more detailed information on their practices as well
as for instructions about how to opt-out of certain practices. Leaf Hint privacy policy does not apply to third parties,
and we cannot control the activities
of such other advertisers or web sites.

If we talk about data usage policy then this is a searching site and we deliver your data to others and similarly others data is delivered to you. You
can control over that data delivery by editing your profile. We also display your digital image (profile picture) and if you don't want to display it you can
change it to some unknown image ex: a blank image.

This site have all rights to stop this service at any time without providing any prior notice or warning. If such situation occurs, all data will be deleted
and at that time you don't have any rights to claim for loss of of your profile and data. We trace your IP address to make your profile and ID secure. If any
dispute occurs or any kinda problem arises then decision of site owner will be last and after that no further arguments are allowed.

You can delete you account at any time and all your data will be removed. For that you have to upload your ID card so that we can be sure that this is
actually you who want to remove his/her data. You can do it here.
If you still have any doubt regarding our terms then you can write us mail at nishantt95@gmail.com and we will try to get back to you as soon as possible. It can
take upto 45 days to reply at your query. We may or may not answer your mail.

</fieldset>
<form method="post" action="redirect.php">
<log>
<fieldset style='border:0px;'>

<uc>Leaf Hint</uc>

&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
RollNo:<input type='text'  name='roll'  autocomplete='off' required>
SapId: <input type='text' name='SapId' autocomplete='off' required>
<input type="submit" value="Sign In">

</fieldset></log>
</form>

<?php
?>


text:
/**
 * File: AssetAdmin.EditForm.js
 */
(function($) {

    $.entwine('ss', function($) {

        // Fix for TreeDropdownField to prevent the Ajax tree load from triggering a 'navigation warning' confirm box:

        $('#Form_EditForm_ViewerGroups_Holder').entwine({

            // If global is true, a 'click' event is triggered on the DetailsView tab :( (see framework TabSet.js):

            onmatch: function() {

                $.ajaxPrefilter(function(options) {
                    options.global = false;
                    if (window.debug) console.log('Disabled global ajax events for "' + options.url + '"');
                });

                this._super();

            }

        });

        // Handle the Secure Assets fields which have been added to the AssetAdmin edit form:

        $('.cms-edit-form #CanViewType').entwine({

            // Binds the change event to option set fields and handles the initial value:

            onmatch: function() {

                this.bindOptions();
                this.handleValue();

                this._super();

            },

            // Calls the superclass 'onunmatch':

            onunmatch: function() {
                this._super();
            },

            // Binds the change event to option set fields:

            bindOptions: function() {

                var self = this;

                this.find('.optionset :input').bind('change', function() {
                    self.handleValue();
                });

            },

            // Handles the current option value, shows dropdown for 'OnlyTheseUsers' option:

            handleValue: function() {

                if (this.getValue() == 'OnlyTheseUsers') {
                    this.doShow();
                } else {
                    this.doHide();
                }

            },

            // Shows the dropdown and hides the splitter line:

            doShow: function() {
                this.addClass('remove-splitter');
                this.getDropdown().show();
            },

            // Hides the dropdown and shows the splitter line:

            doHide: function() {
                this.removeClass('remove-splitter');
                this.getDropdown().hide();
            },

            // Answers the current option value:

            getValue: function() {
                return this.find('input[name=' + this.attr('id') + ']:checked').val();
            },

            // Answers the groups dropdown for the option set:

            getDropdown: function() {
                return $('#' + this.closest('form').attr('id') + '_ViewerGroups_Holder');
            }

        });

    });

}(jQuery));


text:
'use strict';

/* eslint-disable no-unsed-vars */
/* eslint-disable no-undef */
const index = new InvertedIndex();

describe('Read book data', () => {
  let fileContents = undefined;
  beforeAll(function (done) {
    index.createIndex('/src/public/uploads/tests.json')
      .then(() => {
        index.createIndex('./src/public/uploads/books.json')
          .then(() => {
            fileContents = index.currentFile;
            done();
          });
      });
  });

  it('Should return a valid JSON array', () => {
    expect(typeof index.createIndex).toBe('function');
    expect(typeof InvertedIndexUtility.readFile).toBe('function');
    expect(typeof InvertedIndexUtility.changed).toBe('function');
    expect(typeof InvertedIndexUtility.changed()).toBe('undefined');
    expect(InvertedIndexUtility
      .readFile('./src/public/uploads/books.json', (data) => {
        return data;
      }))
      .toBe(undefined);
    expect(Array.isArray(fileContents)).toBe(true);
  });

  it('Should return a non empty JSON array', () => {
    expect(fileContents.length > 1).toBe(true);
  });

  it('Should remove duplicates from array', () => {
    const duplicate = ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e'];
    expect(InvertedIndexUtility.unique(duplicate))
      .toEqual(['a', 'b', 'c', 'd', 'e']);
  });

  it('Should return "["invalid data type"]" for invalid data types', () => {
    expect(InvertedIndexUtility.unique(''))
      .toEqual(['invalid data type supplied']);

    expect(InvertedIndexUtility.unique(() => {}))
      .toEqual(['invalid data type supplied']);

    expect(InvertedIndexUtility.unique({}))
      .toEqual(['invalid data type supplied']);

    expect(InvertedIndexUtility.unique(66))
      .toEqual(['invalid data type supplied']);
  });

  it('Should return a JSON array which contains objects only', () => {
    let answer = true;
    let count = 0;
    while (count < fileContents.length) {
      if (typeof fileContents[count] != 'object' ||
        Array.isArray(fileContents[count])) {
        answer = false;
      }
      count += 1;
    }
    expect(answer).toBe(true);
  });

  it(`Should return a JSON array which
    has valid string entries for keys(title, text)`, () => {
    const testJson = [{
      "title": "The Lord of the Rings: The Fellowship of the Ring."
    }];
    const testJson2 = [{
      "text": "The Lord of the Rings: The Fellowship of the Ring."
    }]
    expect(InvertedIndexUtility.isValidJson(fileContents)).toBe(true);
    expect(InvertedIndexUtility.isValidJson('')).toBe(false);
    expect(InvertedIndexUtility.isValidJson([])).toBe(false);
    expect(InvertedIndexUtility.isValidJson(testJson)).toBe(false);
    expect(InvertedIndexUtility.isValidJson(testJson2)).toBe(false);
  });

  it('Should return the correct filename of the uploaded file', () => {
    let answer = InvertedIndexUtility.formatFileName('src/jasmine/books.json');
    let failed = InvertedIndexUtility.formatFileName([]);
    expect(answer).toEqual('books.json');
    expect(failed).toEqual('bad input');
  });
});

describe('Populate Index', () => {
  describe('On file upload', () => {
    const jsoncontent = [{
      "title": "Alice",
      "text": "fall imagination."
    }, ];
    it('Should create the index once the JSON file has been read', () => {
      expect(typeof index.reference['books.json']).toEqual('object');
      expect(typeof index.populateReference).toEqual('function');
      expect(index
        .populateReference({ "0": ["a", "alice", "and"] }, 'books2.json'))
        .toEqual({ a: [0], alice: [0], and: [0] });
    });

    it('Should create an accurate index object', () => {
      expect(index.getIndex('/src/public/uploads/books.json').alice[0])
        .toEqual(0);
      expect(index.getIndex('/src/public/uploads/books.json').lord[0])
        .toEqual(1);
      expect(index.getIndex('/src/public/uploads/books.json').a[1])
        .toEqual(1);
    });

    it('Should create an inverted index', () => {
      let verdict = true;
      const indexContent = index.reference['books.json'];
      for (let value in indexContent) {
        if (!Array.isArray(indexContent[value]) ||
          isNaN(indexContent[value][0])) {
          verdict = false;
        }
      }
      expect(verdict).toEqual(true);
    });

    it('Should not overwrite the previously created index', () => {
      const indexBefore = index.reference['books.json'];
      const indexAfter = index.reference['tests.json'];
      expect(typeof indexBefore == 'object' &&
        typeof indexAfter == 'object').toBe(true);
    });

    it('Should save tokens when called with a valid json file', () => {
      expect(index.saveTokens(jsoncontent).tokens)
      .toEqual({ 0: ['alice', 'fall', 'imagination'] });
    });
  });
});

describe('Search Index', () => {
  describe('Search results', () => {
    it('Should return the correct result for single word searches', () => {
      expect(typeof index.searchIndex('Lord', ['books.json']))
      .toEqual('object');
    });

    it('Should filter non word search queries', () => {
      const theSearch = Object.keys(index
        .searchIndex('alliance ** && $$$', ['books.json'])['books.json']);

      expect(theSearch).toEqual(['alliance']);
    });

    it(`Should return correct
      search results for multiple word queries`, () => {
      expect(index.searchIndex('lord of the rings',
        ['books.json'])['books.json']).toEqual({
        lord: [1],
        of: [0, 1],
        the: [1],
        rings: [1]
      });
      expect(index.searchIndex('lord of', ['books.json']))
        .toEqual({ "books.json": { lord: [1], of: [0, 1] } });
      expect(index.searchIndex('lord of', ['books.json'])["books.json"].lord)
        .toEqual([1]);
    });

    it('Should return correct search results for invalid queries', () => {
      expect(index.searchIndex('middleware', ['books.json']))
        .toEqual({ 'No results found : please refine your search query': '' });
      expect(index.searchIndex())
        .toEqual({
          'Please enter search query and select index to search': ''
        });
    });
  });

  it('Should not take too long to execute', () => {
    const startTime = performance.now();
    index.searchIndex('lord of the rings', ['books.json']);
    const endTime = performance.now();
    expect(endTime - startTime < 5000).toBeTruthy();
  });

  it('It should ensure that filename argument is optional', () => {
    const result = index.searchIndex('lord of the rings')['books.json'];
    expect(Object.keys(result).sort()).toEqual(Object.keys({
      lord: [1],
      of: [0, 1],
      the: [1],
      rings: [1]
    }).sort());
  });

  it('It should accept an array of argument', () => {
    const result = index
    .searchIndex(['lord', 'of', 'the', 'rings'], ['books.json'])['books.json'];
    expect(result).toEqual({
      lord: [1],
      of: [0, 1],
      the: [1],
      rings: [1]
    });
  });
});

describe('Get Index', () => {
  it('Should take the file url of the JSON file as an argument', () => {
    expect(index.getIndex('/src/public/uploads/books.json').a[1])
      .toEqual(1);
  });
});


text:
namespace FurnitureManufacturer
{
    using Engine;
    using System;
    using System.Globalization;
    using System.Threading;

    public class FurnitureProgram
    {
        public static void Main()
        {

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            FurnitureManufacturerEngine.Instance.Start();
        }
    }
}


text:
<?php

namespace common\modules\lead\models\forms;

use common\modules\lead\models\LeadQuestion;
use common\modules\lead\models\LeadStatus;
use common\modules\lead\models\LeadType;
use yii\base\Model;

class LeadQuestionForm extends Model {

	public string $name = '';
	public ?string $placeholder = null;

	public ?bool $is_active = true;
	public ?bool $show_in_grid = null;
	public ?bool $is_required = null;

	public $type_id;
	public $status_id;

	private ?LeadQuestion $model = null;

	public function rules(): array {
		return [
			[['name'], 'required'],
			[['show_in_grid', 'is_required', 'is_active'], 'boolean'],
			[['name', 'placeholder'], 'string'],
			['placeholder', 'default', 'value' => null],
			['type_id', 'in', 'range' => array_keys(static::getTypesNames())],
			['status_id', 'in', 'range' => array_keys(static::getStatusNames())],
		];
	}

	public function attributeLabels(): array {
		return LeadQuestion::instance()->attributeLabels();
	}

	public function setModel(LeadQuestion $model): void {
		$this->model = $model;
		$this->name = $model->name;
		$this->placeholder = $model->placeholder;
		$this->show_in_grid = $model->show_in_grid;
		$this->is_required = $model->is_required;
		$this->is_active = $model->is_active;
		$this->type_id = $model->type_id;
		$this->status_id = $model->status_id;
	}

	public function getModel(): LeadQuestion {
		if ($this->model === null) {
			$this->model = new LeadQuestion();
		}
		return $this->model;
	}

	public static function getStatusNames(): array {
		return LeadStatus::getNames();
	}

	public static function getTypesNames(): array {
		return LeadType::getNames();
	}

	public function save(): bool {
		if (!$this->validate()) {
			return false;
		}
		$model = $this->getModel();
		$model->name = $this->name;
		$model->placeholder = $this->placeholder;
		$model->is_required = $this->is_required;
		$model->is_active = $this->is_active;
		$model->show_in_grid = $this->show_in_grid;
		$model->type_id = $this->type_id;
		$model->status_id = $this->status_id;
		return $model->save();
	}

}


text:
package org.tourgune.apptrack.utils;

public class TablasBD {

	public static String TABLE_DEVELOPERS 			= "desarrolladores";
	public static String TABLE_DEVELOPERS_ID		= "idDesarrollador";
	public static String TABLE_DEVELOPERS_NAME 		= "nombre";
	public static String TABLE_DEVELOPERS_EMAIL 	= "email";
	public static String TABLE_DEVELOPERS_PASSWORD 	= "password";
	public static String TABLE_DEVELOPERS_TOKEN 	= "tokkenDesarrollador";
	public static String TABLE_DEVELOPERS_DATE	 	= "fechaCreacion";
	public static String TABLE_DEVELOPERS_ACTIVE 	= "active";

	public static String TABLE_APPLICATIONS 				= "aplicaciones";
	public static String TABLE_APPLICATIONS_ID				= "idAplicacion";
	public static String TABLE_APPLICATIONS_DEVELOPER_ID 	= "idDesarrollador";
	public static String TABLE_APPLICATIONS_NAME			= "nombreAplicacion";
	public static String TABLE_APPLICATIONS_DESCRIPTION 	= "descripcion";
	public static String TABLE_APPLICATIONS_TOKEN 			= "tokkenAplicacion";
	public static String TABLE_APPLICATIONS_DATE	 		= "fechaCreacion";
	public static String TABLE_APPLICATIONS_LAT      	 	= "latitud";
	public static String TABLE_APPLICATIONS_LNG      	 	= "longitud";
	public static String TABLE_APPLICATIONS_ACTIVA	 		= "activa";
	public static String TABLE_APPLICATIONS_ZOOM	 		= "zoom";
	public static String TABLE_APPLICATIONS_CONEXION         = "conexion";

	public static String TABLE_VARIABLES 					= "variables";
	public static String TABLE_VARIABLES_ID					= "idvariables";
	public static String TABLE_VARIABLES_APPLICATION_ID 	= "idaplicacion";
	public static String TABLE_VARIABLES_TYPE_ID			= "idtipo";
	public static String TABLE_VARIABLES_NAME 				= "nombrevariable";
	public static String TABLE_VARIABLES_MAX 				= "max";
	public static String TABLE_VARIABLES_MIN	 			= "min";
	public static String TABLE_VARIABLES_DATEINI	 		= "fechadesde";
	public static String TABLE_VARIABLES_DATEFIN	 		= "fechahasta";
	public static String TABLE_VARIABLES_MULOPT	 			= "multiopcion";
	public static String TABLE_VARIABLES_OBLIGATORIO	 	= "obligatorio";

	public static String TABLE_TYPES 						= "tipos";
	public static String TABLE_TYPES_ID						= "idtipo";
	public static String TABLE_TYPES_NAME 					= "nombretipo";

	public static String TABLE_OPTIONS 						= "opciones";
	public static String TABLE_OPTIONS_ID					= "idopcion";
	public static String TABLE_OPTIONS_VARIABLE_ID 			= "idvariable";
	public static String TABLE_OPTIONS_OPTION				= "opcion";
	public static String TABLE_OPTIONS_CODIFICACTION		= "codificacion";

	//-------- ionzu-------

	public static String TABLE_USERS 						= "usuarios";
	public static String TABLE_USERS_ID						= "idusuario";
	public static String TABLE_USERS_APP	 				= "idaplicacion";
	public static String TABLE_USERS_IMEI	 				= "imei";

	public static String TABLE_VALUES 						= "valores";
	public static String TABLE_VALUES_ID	 				= "idvalor";
	public static String TABLE_VALUES_PARAM					= "idvariable";
	public static String TABLE_VALUES_VALUE	 				= "valorvariable";
	public static String TABLE_VALUES_USER	 				= "idusuario";
	public static String TABLE_VALUES_DATE					= "fecha";

	public static String TABLE_POINTS 						= "puntos";
	public static String TABLE_POINTS_ID 					= "idpunto";
	public static String TABLE_POINTS_USER 					= "idusuario";
	public static String TABLE_POINTS_LAT 					= "latitud";
	public static String TABLE_POINTS_LONG 					= "longitud";
	public static String TABLE_POINTS_LATLONG				= "latlong";
	public static String TABLE_POINTS_DATE 					= "fecha";
	public static String TABLE_POINTS_PROVIDER 				= "provider";

	public static String TABLE_VISORES						= "visores";
	public static String TABLE_VISORES_IDVISOR				= "idvisor";
	public static String TABLE_VISORES_IDAPLICACION			= "idaplicacion";
	public static String TABLE_VISORES_USUARIO				= "usuario";
	public static String TABLE_VISORES_PWD					= "pwd";
	public static String TABLE_VISORES_LAT					= "latitud";
	public static String TABLE_VISORES_LNG					= "longitud";
	public static String TABLE_VISORES_ZOOM					= "zoom";

}


text:
import FactoryMaker from '../../../core/FactoryMaker';
import ReportingFactory from '../reporting/ReportingFactory';

function ReportingController(config) {

    let reporters = [];
    let instance;

    let reportingFactory = ReportingFactory(this.context).getInstance({
        log: config.log
    });

    function initialize(reporting, rangeController) {
        // "if multiple Reporting elements are present, it is expected that
        // the client processes one of the recognized reporting schemes."
        // to ignore this, and support multiple Reporting per Metric,
        // simply change the 'some' below to 'forEach'
        reporting.some(r => {
            var reporter = reportingFactory.create(r, rangeController);

            if (reporter) {
                reporters.push(reporter);
                return true;
            }
        });
    }

    function reset() {
        reporters.forEach(r => r.reset());
        reporters = [];
    }

    function report(type, vos) {
        reporters.forEach(r => r.report(type, vos));
    }

    instance = {
        initialize: initialize,
        reset:      reset,
        report:     report
    };

    return instance;
}

ReportingController.__dashjs_factory_name = 'ReportingController';
export default FactoryMaker.getClassFactory(ReportingController);