text:
package com.microsoft.azure.management.apimanagement.v2018_06_01_preview.implementation;

import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.management.apimanagement.v2018_06_01_preview.ErrorResponseException;
import com.microsoft.azure.management.apimanagement.v2018_06_01_preview.IssueGetHeaders;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.ServiceResponseWithHeaders;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * An instance of this class provides access to all the operations defined
 * in Issues.
 */
public class IssuesInner {
    /** The Retrofit service to perform REST calls. */
    private IssuesService service;
    /** The service client containing this operation class. */
    private ApiManagementClientImpl client;

    /**
     * Initializes an instance of IssuesInner.
     *
     * @param retrofit the Retrofit instance built from a Retrofit Builder.
     * @param client the instance of the service client containing this operation class.
     */
    public IssuesInner(Retrofit retrofit, ApiManagementClientImpl client) {
        this.service = retrofit.create(IssuesService.class);
        this.client = client;
    }

    /**
     * The interface defining all the services for Issues to be
     * used by Retrofit to perform actually REST calls.
     */
    interface IssuesService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.apimanagement.v2018_06_01_preview.Issues listByService" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/issues")
        Observable<Response<ResponseBody>> listByService(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("subscriptionId") String subscriptionId, @Query("$filter") String filter, @Query("$top") Integer top, @Query("$skip") Integer skip, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.apimanagement.v2018_06_01_preview.Issues get" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/issues/{issueId}")
        Observable<Response<ResponseBody>> get(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("issueId") String issueId, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.apimanagement.v2018_06_01_preview.Issues listByServiceNext" })
        @GET
        Observable<Response<ResponseBody>> listByServiceNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ErrorResponseException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList<IssueContractInner> object if successful.
     */
    public PagedList<IssueContractInner> listByService(final String resourceGroupName, final String serviceName) {
        ServiceResponse<Page<IssueContractInner>> response = listByServiceSinglePageAsync(resourceGroupName, serviceName).toBlocking().single();
        return new PagedList<IssueContractInner>(response.body()) {
            @Override
            public Page<IssueContractInner> nextPage(String nextPageLink) {
                return listByServiceNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<IssueContractInner>> listByServiceAsync(final String resourceGroupName, final String serviceName, final ListOperationCallback<IssueContractInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listByServiceSinglePageAsync(resourceGroupName, serviceName),
            new Func1<String, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(String nextPageLink) {
                    return listByServiceNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<IssueContractInner> object
     */
    public Observable<Page<IssueContractInner>> listByServiceAsync(final String resourceGroupName, final String serviceName) {
        return listByServiceWithServiceResponseAsync(resourceGroupName, serviceName)
            .map(new Func1<ServiceResponse<Page<IssueContractInner>>, Page<IssueContractInner>>() {
                @Override
                public Page<IssueContractInner> call(ServiceResponse<Page<IssueContractInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<IssueContractInner> object
     */
    public Observable<ServiceResponse<Page<IssueContractInner>>> listByServiceWithServiceResponseAsync(final String resourceGroupName, final String serviceName) {
        return listByServiceSinglePageAsync(resourceGroupName, serviceName)
            .concatMap(new Func1<ServiceResponse<Page<IssueContractInner>>, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(ServiceResponse<Page<IssueContractInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listByServiceNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList<IssueContractInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<IssueContractInner>>> listByServiceSinglePageAsync(final String resourceGroupName, final String serviceName) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (serviceName == null) {
            throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        final String apiVersion = "2018-06-01-preview";
        final String filter = null;
        final Integer top = null;
        final Integer skip = null;
        return service.listByService(resourceGroupName, serviceName, this.client.subscriptionId(), filter, top, skip, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<IssueContractInner>> result = listByServiceDelegate(response);
                        return Observable.just(new ServiceResponse<Page<IssueContractInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field       | Supported operators    | Supported functions               |
     |-------------|------------------------|-----------------------------------|
     |name | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |apiId | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |title | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |description | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |authorName | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |state | eq |    |
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ErrorResponseException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList<IssueContractInner> object if successful.
     */
    public PagedList<IssueContractInner> listByService(final String resourceGroupName, final String serviceName, final String filter, final Integer top, final Integer skip) {
        ServiceResponse<Page<IssueContractInner>> response = listByServiceSinglePageAsync(resourceGroupName, serviceName, filter, top, skip).toBlocking().single();
        return new PagedList<IssueContractInner>(response.body()) {
            @Override
            public Page<IssueContractInner> nextPage(String nextPageLink) {
                return listByServiceNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field       | Supported operators    | Supported functions               |
     |-------------|------------------------|-----------------------------------|
     |name | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |apiId | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |title | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |description | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |authorName | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |state | eq |    |
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<IssueContractInner>> listByServiceAsync(final String resourceGroupName, final String serviceName, final String filter, final Integer top, final Integer skip, final ListOperationCallback<IssueContractInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listByServiceSinglePageAsync(resourceGroupName, serviceName, filter, top, skip),
            new Func1<String, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(String nextPageLink) {
                    return listByServiceNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field       | Supported operators    | Supported functions               |
     |-------------|------------------------|-----------------------------------|
     |name | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |apiId | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |title | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |description | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |authorName | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |state | eq |    |
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<IssueContractInner> object
     */
    public Observable<Page<IssueContractInner>> listByServiceAsync(final String resourceGroupName, final String serviceName, final String filter, final Integer top, final Integer skip) {
        return listByServiceWithServiceResponseAsync(resourceGroupName, serviceName, filter, top, skip)
            .map(new Func1<ServiceResponse<Page<IssueContractInner>>, Page<IssueContractInner>>() {
                @Override
                public Page<IssueContractInner> call(ServiceResponse<Page<IssueContractInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param filter | Field       | Supported operators    | Supported functions               |
     |-------------|------------------------|-----------------------------------|
     |name | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |apiId | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |title | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |description | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |authorName | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |state | eq |    |
     * @param top Number of records to return.
     * @param skip Number of records to skip.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<IssueContractInner> object
     */
    public Observable<ServiceResponse<Page<IssueContractInner>>> listByServiceWithServiceResponseAsync(final String resourceGroupName, final String serviceName, final String filter, final Integer top, final Integer skip) {
        return listByServiceSinglePageAsync(resourceGroupName, serviceName, filter, top, skip)
            .concatMap(new Func1<ServiceResponse<Page<IssueContractInner>>, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(ServiceResponse<Page<IssueContractInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listByServiceNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
    ServiceResponse<PageImpl<IssueContractInner>> * @param resourceGroupName The name of the resource group.
    ServiceResponse<PageImpl<IssueContractInner>> * @param serviceName The name of the API Management service.
    ServiceResponse<PageImpl<IssueContractInner>> * @param filter | Field       | Supported operators    | Supported functions               |
     |-------------|------------------------|-----------------------------------|
     |name | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |apiId | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |title | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |description | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |authorName | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith|
     |state | eq |    |
    ServiceResponse<PageImpl<IssueContractInner>> * @param top Number of records to return.
    ServiceResponse<PageImpl<IssueContractInner>> * @param skip Number of records to skip.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList<IssueContractInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<IssueContractInner>>> listByServiceSinglePageAsync(final String resourceGroupName, final String serviceName, final String filter, final Integer top, final Integer skip) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (serviceName == null) {
            throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        final String apiVersion = "2018-06-01-preview";
        return service.listByService(resourceGroupName, serviceName, this.client.subscriptionId(), filter, top, skip, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<IssueContractInner>> result = listByServiceDelegate(response);
                        return Observable.just(new ServiceResponse<Page<IssueContractInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<PageImpl<IssueContractInner>> listByServiceDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<PageImpl<IssueContractInner>, ErrorResponseException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<PageImpl<IssueContractInner>>() { }.getType())
                .registerError(ErrorResponseException.class)
                .build(response);
    }

    /**
     * Gets API Management issue details.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param issueId Issue identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ErrorResponseException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the IssueContractInner object if successful.
     */
    public IssueContractInner get(String resourceGroupName, String serviceName, String issueId) {
        return getWithServiceResponseAsync(resourceGroupName, serviceName, issueId).toBlocking().single().body();
    }

    /**
     * Gets API Management issue details.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param issueId Issue identifier. Must be unique in the current API Management service instance.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<IssueContractInner> getAsync(String resourceGroupName, String serviceName, String issueId, final ServiceCallback<IssueContractInner> serviceCallback) {
        return ServiceFuture.fromHeaderResponse(getWithServiceResponseAsync(resourceGroupName, serviceName, issueId), serviceCallback);
    }

    /**
     * Gets API Management issue details.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param issueId Issue identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the IssueContractInner object
     */
    public Observable<IssueContractInner> getAsync(String resourceGroupName, String serviceName, String issueId) {
        return getWithServiceResponseAsync(resourceGroupName, serviceName, issueId).map(new Func1<ServiceResponseWithHeaders<IssueContractInner, IssueGetHeaders>, IssueContractInner>() {
            @Override
            public IssueContractInner call(ServiceResponseWithHeaders<IssueContractInner, IssueGetHeaders> response) {
                return response.body();
            }
        });
    }

    /**
     * Gets API Management issue details.
     *
     * @param resourceGroupName The name of the resource group.
     * @param serviceName The name of the API Management service.
     * @param issueId Issue identifier. Must be unique in the current API Management service instance.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the IssueContractInner object
     */
    public Observable<ServiceResponseWithHeaders<IssueContractInner, IssueGetHeaders>> getWithServiceResponseAsync(String resourceGroupName, String serviceName, String issueId) {
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (serviceName == null) {
            throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
        }
        if (issueId == null) {
            throw new IllegalArgumentException("Parameter issueId is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        final String apiVersion = "2018-06-01-preview";
        return service.get(resourceGroupName, serviceName, issueId, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponseWithHeaders<IssueContractInner, IssueGetHeaders>>>() {
                @Override
                public Observable<ServiceResponseWithHeaders<IssueContractInner, IssueGetHeaders>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponseWithHeaders<IssueContractInner, IssueGetHeaders> clientResponse = getDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponseWithHeaders<IssueContractInner, IssueGetHeaders> getDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<IssueContractInner, ErrorResponseException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<IssueContractInner>() { }.getType())
                .registerError(ErrorResponseException.class)
                .buildWithHeaders(response, IssueGetHeaders.class);
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ErrorResponseException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList<IssueContractInner> object if successful.
     */
    public PagedList<IssueContractInner> listByServiceNext(final String nextPageLink) {
        ServiceResponse<Page<IssueContractInner>> response = listByServiceNextSinglePageAsync(nextPageLink).toBlocking().single();
        return new PagedList<IssueContractInner>(response.body()) {
            @Override
            public Page<IssueContractInner> nextPage(String nextPageLink) {
                return listByServiceNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @param serviceFuture the ServiceFuture object tracking the Retrofit calls
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<IssueContractInner>> listByServiceNextAsync(final String nextPageLink, final ServiceFuture<List<IssueContractInner>> serviceFuture, final ListOperationCallback<IssueContractInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listByServiceNextSinglePageAsync(nextPageLink),
            new Func1<String, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(String nextPageLink) {
                    return listByServiceNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<IssueContractInner> object
     */
    public Observable<Page<IssueContractInner>> listByServiceNextAsync(final String nextPageLink) {
        return listByServiceNextWithServiceResponseAsync(nextPageLink)
            .map(new Func1<ServiceResponse<Page<IssueContractInner>>, Page<IssueContractInner>>() {
                @Override
                public Page<IssueContractInner> call(ServiceResponse<Page<IssueContractInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<IssueContractInner> object
     */
    public Observable<ServiceResponse<Page<IssueContractInner>>> listByServiceNextWithServiceResponseAsync(final String nextPageLink) {
        return listByServiceNextSinglePageAsync(nextPageLink)
            .concatMap(new Func1<ServiceResponse<Page<IssueContractInner>>, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(ServiceResponse<Page<IssueContractInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listByServiceNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * Lists a collection of issues in the specified service instance.
     *
    ServiceResponse<PageImpl<IssueContractInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList<IssueContractInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<IssueContractInner>>> listByServiceNextSinglePageAsync(final String nextPageLink) {
        if (nextPageLink == null) {
            throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
        }
        String nextUrl = String.format("%s", nextPageLink);
        return service.listByServiceNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<IssueContractInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<IssueContractInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<IssueContractInner>> result = listByServiceNextDelegate(response);
                        return Observable.just(new ServiceResponse<Page<IssueContractInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<PageImpl<IssueContractInner>> listByServiceNextDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<PageImpl<IssueContractInner>, ErrorResponseException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<PageImpl<IssueContractInner>>() { }.getType())
                .registerError(ErrorResponseException.class)
                .build(response);
    }

}


text:
@extends('layouts.master')

@section('description', '')
@section('title', [ '404' ])

@section('content')

				{{ trans('site::frontend.error.404.title') }}

				{!! trans('site::frontend.error.404.contents') !!}

@stop

@section('after-content')
@stop

redpajama_set_name: RedPajamaGithub


text:
import sys

import tensorflow as tf

import awesome_gans.modules as t
from awesome_gans.magan.adamax import AdamaxOptimizer

sys.path.append('../')

tf.set_random_seed(777)  # reproducibility

class MAGAN:
    def __init__(
        self,
        s,
        batch_size=64,
        height=64,
        width=64,
        channel=3,
        n_classes=41,
        sample_num=10 * 10,
        sample_size=10,
        df_dim=64,
        gf_dim=64,
        fc_unit=512,
        z_dim=350,
        lr=5e-4,
    ):

        """
        # General Settings
        :param s: TF Session
        :param batch_size: training batch size, default 64
        :param height: input image height, default 64
        :param width: input image width, default 64
        :param channel: input image channel, default 3
        :param n_classes: input DataSet's classes, default 41

        # Output Settings
        :param sample_num: the number of output images, default 100
        :param sample_size: sample image size, default 10

        # For CNN model
        :param df_dim: discriminator conv2d filter, default 64
        :param gf_dim: generator conv2d filter, default 64
        :param fc_unit: the number of fully connected filters, default 512

        # Training Option
        :param z_dim: z dimension (kinda noise), default 350
        :param lr: generator learning rate, default 5e-4
        """

        self.s = s
        self.batch_size = batch_size

        self.height = height
        self.width = width
        self.channel = channel
        self.image_shape = [self.batch_size, self.height, self.width, self.channel]
        self.n_classes = n_classes

        self.sample_num = sample_num
        self.sample_size = sample_size

        self.df_dim = df_dim
        self.gf_dim = gf_dim
        self.fc_unit = fc_unit

        self.z_dim = z_dim
        self.beta1 = 0.5
        self.lr = lr
        self.pt_lambda = 0.1

        # pre-defined
        self.g_loss = 0.0
        self.d_loss = 0.0
        self.d_real_loss = 0.0
        self.d_fake_loss = 0.0

        self.g = None

        self.d_op = None
        self.g_op = None

        self.merged = None
        self.writer = None
        self.saver = None

        # Placeholders
        self.x = tf.placeholder(tf.float32, shape=[None, self.height, self.width, self.channel], name="x-image")
        self.z = tf.placeholder(tf.float32, shape=[None, self.z_dim], name='z-noise')
        self.m = tf.placeholder(tf.float32, name='margin')

        self.build_magan()  # build MAGAN model

    def encoder(self, x, reuse=None):
        """
        :param x: images
        :param reuse: re-usable
        :return: logits
        """
        with tf.variable_scope('encoder', reuse=reuse):
            for i in range(1, 5):
                x = t.conv2d(x, self.df_dim * (2 ** (i - 1)), 4, 2, name='enc-conv2d-%d' % i)
                if i > 1:
                    x = t.batch_norm(x, name='enc-bn-%d' % (i - 1))
                x = tf.nn.leaky_relu(x)

            return x

    def decoder(self, z, reuse=None):
        """
        :param z: embeddings
        :param reuse: re-usable
        :return: prob
        """
        with tf.variable_scope('decoder', reuse=reuse):
            x = z
            for i in range(1, 4):
                x = t.deconv2d(x, self.df_dim * 8 // (2 ** i), 4, 2, name='dec-deconv2d-%d' % i)
                x = t.batch_norm(x, name='dec-bn-%d' % i)
                x = tf.nn.leaky_relu(x)

            x = t.deconv2d(x, self.channel, 4, 2, name='enc-deconv2d-4')
            x = tf.nn.tanh(x)
            return x

    def discriminator(self, x, reuse=None):
        """
        :param x: images
        :param reuse: re-usable
        :return: prob, embeddings, gen-ed_image
        """
        with tf.variable_scope("discriminator", reuse=reuse):
            embeddings = self.encoder(x, reuse=reuse)
            decoded = self.decoder(embeddings, reuse=reuse)

            return embeddings, decoded

    def generator(self, z, reuse=None, is_train=True):
        """
        :param z: embeddings
        :param reuse: re-usable
        :param is_train: trainable
        :return: prob
        """
        with tf.variable_scope("generator", reuse=reuse):
            x = tf.reshape(z, (-1, 1, 1, self.z_dim))

            x = t.deconv2d(x, self.df_dim * 8, 4, 1, pad='VALID', name='gen-deconv2d-1')
            x = t.batch_norm(x, is_train=is_train, name='gen-bn-1')
            x = tf.nn.relu(x)

            for i in range(1, 4):
                x = t.deconv2d(x, self.df_dim * 8 // (2 ** i), 4, 2, name='gen-deconv2d-%d' % (i + 1))
                x = t.batch_norm(x, is_train=is_train, name='gen-bn-%d' % (i + 1))
                x = tf.nn.relu(x)

            x = t.deconv2d(x, self.channel, 4, 2, name='gen-deconv2d-5')
            x = tf.nn.tanh(x)
            return x

    def build_magan(self):
        # Generator
        self.g = self.generator(self.z)

        # Discriminator
        _, d_real = self.discriminator(self.x)
        _, d_fake = self.discriminator(self.g, reuse=True)

        self.d_real_loss = t.mse_loss(self.x, d_real, self.batch_size)
        self.d_fake_loss = t.mse_loss(self.g, d_fake, self.batch_size)
        self.d_loss = self.d_real_loss + tf.maximum(0.0, self.m - self.d_fake_loss)
        self.g_loss = self.d_fake_loss

        # Summary
        tf.summary.scalar("loss/d_loss", self.d_loss)
        tf.summary.scalar("loss/d_real_loss", self.d_real_loss)
        tf.summary.scalar("loss/d_fake_loss", self.d_fake_loss)
        tf.summary.scalar("loss/g_loss", self.g_loss)

        # Optimizer
        t_vars = tf.trainable_variables()
        d_params = [v for v in t_vars if v.name.startswith('d')]
        g_params = [v for v in t_vars if v.name.startswith('g')]

        self.d_op = AdamaxOptimizer(learning_rate=self.lr, beta1=self.beta1).minimize(self.d_loss, var_list=d_params)
        self.g_op = AdamaxOptimizer(learning_rate=self.lr, beta1=self.beta1).minimize(self.g_loss, var_list=g_params)

        # Merge summary
        self.merged = tf.summary.merge_all()

        # Model saver
        self.saver = tf.train.Saver(max_to_keep=1)
        self.writer = tf.summary.FileWriter('./model/', self.s.graph)


text:
package com.suscipio_solutions.consecro_mud.Behaviors;
import java.lang.ref.WeakReference;
import java.util.HashSet;

import com.suscipio_solutions.consecro_mud.Behaviors.interfaces.Behavior;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CharStats;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMParms;
import com.suscipio_solutions.consecro_mud.core.CMProps;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;

@SuppressWarnings({"unchecked","rawtypes"})
public class MOBReSave extends ActiveTicker
{
	@Override public String ID(){return "MOBReSave";}
	@Override protected int canImproveCode(){return Behavior.CAN_MOBS;}
	@Override public long flags(){return 0;}
	protected static HashSet roomsReset=new HashSet();
	protected boolean noRecurse=false;
	protected CharStats startStats=null;
	protected WeakReference host=null;

	public MOBReSave()
	{
		super();
		minTicks=140; maxTicks=140; chance=100;
		tickReset();
	}

	@Override
	public String accountForYourself()
	{
		return "persisting";
	}

	@Override
	public void setParms(String newParms)
	{
		super.setParms(newParms);
		startStats=(CharStats)CMClass.getCommon("DefaultCharStats");
		for(final int c: CharStats.CODES.ALLCODES())
			startStats.setStat(c,CMParms.getParmInt(parms,CharStats.CODES.ABBR(c),-1));
	}

	@Override
	public String getParms()
	{
		if(host==null) return super.getParms();
		final MOB M=(MOB)host.get();
		if(M==null) return super.getParms();
		final StringBuffer rebuiltParms=new StringBuffer(super.rebuildParms());
		for(final int c: CharStats.CODES.ALLCODES())
			rebuiltParms.append(" "+CharStats.CODES.ABBR(c)+"="+M.baseCharStats().getStat(c));
		return rebuiltParms.toString();
	}
	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if((ticking instanceof MOB)
		&&(tickID==Tickable.TICKID_MOB)
		&&(!((MOB)ticking).amDead())
		&&(!noRecurse)
		&&(CMProps.getBoolVar(CMProps.Bool.MUDSTARTED))
		&&(((MOB)ticking).getStartRoom()!=null)
		&&(((MOB)ticking).getStartRoom().roomID().length()>0)
		&&(((MOB)ticking).databaseID().length()>0))
		{
			final MOB mob=(MOB)ticking;
			if((host==null)||(host.get()==null))
				host=new WeakReference(mob);
			noRecurse=true;
			if(startStats != null)
			{
				synchronized(startStats)
				{
					for(final int c: CharStats.CODES.ALLCODES())
						if(startStats.getStat(c)>0)
							mob.baseCharStats().setStat(c,startStats.getStat(c));
					startStats=null;
				}
			}
			if(canAct(ticking,tickID))
			{
				final Room R=mob.getStartRoom();
				CMLib.database().DBUpdateMOB(R.roomID(),mob);
			}
		}
		noRecurse=false;
		return true;
	}

}


text:
/* eslint-env node */
const express = require("express");
const libhoney = require("libhoney");
const responseTime = require("response-time");
let app = express();

let honey = new libhoney({
  writeKey: process.env["HONEYCOMB_API_KEY"],
  dataset: "express-example-response-time"
});

app.use(
  responseTime(function(req, res, time) {
    honey.sendNow({
      app: req.app,
      baseUrl: req.baseUrl,
      fresh: req.fresh,
      hostname: req.hostname,
      ip: req.ip,
      method: req.method,
      originalUrl: req.originalUrl,
      params: req.params,
      path: req.path,
      protocol: req.protocol,
      query: req.query,
      route: req.route,
      secure: req.secure,
      xhr: req.xhr,
      responseTime_ms: time
    });
  })
);

app.get("/", function(req, res) {
  res.send("Hello World!");
});

app.listen(3000, function() {
  console.log("Example app listening on port 3000!");
});


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
    [ExportLanguageService(typeof(IOptionPageService), LanguageNames.CSharp), Shared]
    internal class CSharpOptionPageService : ForegroundThreadAffinitizedObject, IOptionPageService
    {
        private readonly CSharpPackage _package;

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public CSharpOptionPageService(IThreadingContext threadingContext, SVsServiceProvider serviceProvider)
            : base(threadingContext)
        {
            var shell = (IVsShell)serviceProvider.GetService(typeof(SVsShell));
            ErrorHandler.ThrowOnFailure(shell.LoadPackage(Guids.CSharpPackageId, out var package));
            _package = (CSharpPackage)package;
        }

        public void ShowFormattingOptionPage()
        {
            AssertIsForeground();

            _package.ShowOptionPage(typeof(FormattingOptionPage));
        }
    }
}


text:
var http = require('http');
var url = require('url');

function slowHandler(req, res) {
  setTimeout(function() {
    res.writeHead(200, { "Server": "Node.js/http.Server" });
    res.end('hello, world');
  }, 250);
}

http.createServer(slowHandler).listen(8081);


text:
"""DataMine (Upsight.com) CLI Admin Tool

usedup is a simple command line tool for performing basic admin tasks
using both official and unofficial DataMine api's. At present this allows
for; checking currently running queries, viewing a running queries stats,
killing active queries, and/or downloading an archive of historically run
queries. Since login is required to access DataMine(Upsight.com), user
credentials will be asked upon submitting each command.

USAGE:
    $ usedup --help

See the README for further details.

"""
from __future__ import print_function

import time

import click
from tabulate import tabulate

from usedup.core import UsedUp

@click.group()
def main():
    """
    DataMine (Upsight.com) CLI Admin Tool

    usedup is a simple command line tool for performing basic admin tasks
    using both official and unofficial DataMine api's. At present this allows
    for; checking currently running queries, viewing a running queries stats,
    killing active queries, and/or downloading an archive of historically run
    queries. Since login is required to access DataMine(Upsight.com), user
    credentials will be asked upon submitting each command.

    USAGE:
        $ usedup --help

    See the README for further details.

    """
    pass

@main.command()
@click.option('--period', '-p', default='1wk', help='DataMine periods back from now.')
@click.option('--outfile', '-o', help='Output file save location (.csv)')
def history(period, outfile):
    """Download an archive of previously run queries.

    Period Options:
    1wk=='1 week';
    2wk=='2 weeks';
    1mt=='1 month';
    2mt=='2 months';
    3mt=='3 months';

    Output File: Saves to current path if missing.

    """
    with UsedUp() as usedup:
        usedup.history(period=period, outfile=outfile)

@main.command()
@click.argument('qids', nargs=-1)
def kill(qids):
    """Kill actively running query using Upsight's Query ID."""
    with UsedUp() as usedup:
        for qid in qids:
            result = usedup.kill(qid=qid)
            print('QueryID %s canceled successfully? %s' % (qid, result))

@main.command()
@click.option('--continuous', '-c', is_flag=True, help='Run indefinately.')
@click.option('--pause', '-p', default=60, help='Seconds between checks.')
def running(continuous, pause):
    """Print list of currently running queries."""
    showresults = True
    with UsedUp() as usedup:
        while showresults:
            queries = usedup.running()
            tabbed = tabulate(queries, headers='keys', tablefmt="grid")
            print(tabbed)
            showresults = continuous
            if showresults:
                time.sleep(pause)

@main.command()
@click.argument('qids', nargs=-1)
@click.option('--details/--no-details', default=True, help='Show processing details?')
@click.option('--query/--no-query', default=True, help='Show query statement?')
def status(qids, details, query):
    """Print details about active query Upsight's Query ID."""
    with UsedUp() as usedup:
        for qid in qids:
            result = usedup.status(qid, details, query)

            if result is None:
                print('QueryID %s is not an active query.' % qid)

            if details and result['details'] is not None:
                sections = sorted(result['details'].keys())
                for section in sections:
                    print('%s == %s' % (section, result['details'][section]))

            if query and result['query'] is not None:
                print('%s == \n\n%s' % ('Query', result['query']))

if __name__ == '__main__':
    main()


text:
package gov.nasa.jpf.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Locale;

/**
 * a PrintStream that doesn't print anything
 */
public class DevNullPrintStream extends PrintStream {

  public DevNullPrintStream(){
    super( new ByteArrayOutputStream());
  }

  @Override
  public void flush(){}
  @Override
  public void close(){}
  @Override
  public boolean checkError(){
    return false;
  }
  @Override
  protected void setError(){}
  @Override
  protected void clearError(){}

  @Override
  public void write(int a){}
  @Override
  public void write(byte[] a, int b, int c){}
  @Override
  public void print(boolean a){}
  @Override
  public void print(char a){}
  @Override
  public void print(int a){}
  @Override
  public void print(long a){}
  @Override
  public void print(float a){}
  @Override
  public void print(double a){}
  @Override
  public void print(char[] a){}
  @Override
  public void print(String a){}
  @Override
  public void print(Object a){}
  @Override
  public void println(){}
  @Override
  public void println(boolean a){}
  @Override
  public void println(char a){}
  @Override
  public void println(int a){}
  @Override
  public void println(long a){}
  @Override
  public void println(float a){}
  @Override
  public void println(double a){}
  @Override
  public void println(char[] a){}
  @Override
  public void println(String a){}
  @Override
  public void println(Object a){}

  @Override
  public PrintStream printf(String a, Object... b){ return this; }
  @Override
  public PrintStream printf(Locale a, String b, Object... c){ return this; }
  @Override
  public PrintStream format(String a, Object... b){ return this; }
  @Override
  public PrintStream format(Locale a, String b, Object... c){ return this; }
  @Override
  public PrintStream append(CharSequence a){ return this; }
  @Override
  public PrintStream append(CharSequence a, int b, int c){ return this; }
  @Override
  public PrintStream append(char a){ return this; }

}


text:
import logging
import os
import sys
import time

from pom_utils import PomUtils
from pom_handlers import PomContentHandler, DepsFromPom

logger = logging.getLogger(__name__)

# Test driver
def main(sourceFileName):
  start_ms = int(round(time.time() * 1000))
  pants_refs =  DepsFromPom(PomUtils.pom_provides_target()).get(sourceFileName)
  elapsed_ms = int(round(time.time() * 1000)) - start_ms
  for pants_ref in pants_refs:
    print("      {ref}".format(ref=pants_ref))
  print
  print("Parsed %d pom.xml files in %dms." % (PomContentHandler.num_invocations(), elapsed_ms))

if __name__ == "__main__":
  pom = ""
  args = PomUtils.parse_common_args(sys.argv[1:])
  if len(args) == 1:
    pom = args[0]
  else:
    pom = "common/pom.xml"
    print "usage: {progname} path/to/pom.xml".format(progname=os.path.basename(sys.argv[0]))
    print
    PomUtils.common_usage()
    print
    print "Example with {pom}:".format(pom=pom)
  main(pom)


text:
//
//  GTLAdExchangeBuyerCreative.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Ad Exchange Buyer API (adexchangebuyer/v1.4)
// Description:
//   Accesses your bidding-account information, submits creatives for
//   validation, finds available direct deals, and retrieves performance
//   reports.
// Documentation:
//   https://developers.google.com/ad-exchange/buyer-rest
// Classes:
//   GTLAdExchangeBuyerCreative (0 custom class methods, 25 custom properties)
//   GTLAdExchangeBuyerCreativeCorrectionsItem (0 custom class methods, 2 custom properties)
//   GTLAdExchangeBuyerCreativeFilteringReasons (0 custom class methods, 2 custom properties)
//   GTLAdExchangeBuyerCreativeNativeAd (0 custom class methods, 12 custom properties)
//   GTLAdExchangeBuyerCreativeServingRestrictionsItem (0 custom class methods, 3 custom properties)
//   GTLAdExchangeBuyerCreativeFilteringReasonsReasonsItem (0 custom class methods, 2 custom properties)
//   GTLAdExchangeBuyerCreativeNativeAdAppIcon (0 custom class methods, 3 custom properties)
//   GTLAdExchangeBuyerCreativeNativeAdImage (0 custom class methods, 3 custom properties)
//   GTLAdExchangeBuyerCreativeNativeAdLogo (0 custom class methods, 3 custom properties)
//   GTLAdExchangeBuyerCreativeServingRestrictionsItemContextsItem (0 custom class methods, 4 custom properties)
//   GTLAdExchangeBuyerCreativeServingRestrictionsItemDisapprovalReasonsItem (0 custom class methods, 2 custom properties)

#import "GTLAdExchangeBuyerCreative.h"

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreative
//

@implementation GTLAdExchangeBuyerCreative
@dynamic accountId, advertiserId, advertiserName, agencyId, apiUploadTimestamp,
         attribute, buyerCreativeId, clickThroughUrl, corrections, dealsStatus,
         filteringReasons, height, HTMLSnippet, impressionTrackingUrl, kind,
         nativeAd, openAuctionStatus, productCategories, restrictedCategories,
         sensitiveCategories, servingRestrictions, vendorType, version,
         videoURL, width;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"advertiserId" : [NSNumber class],
    @"attribute" : [NSNumber class],
    @"clickThroughUrl" : [NSString class],
    @"corrections" : [GTLAdExchangeBuyerCreativeCorrectionsItem class],
    @"impressionTrackingUrl" : [NSString class],
    @"productCategories" : [NSNumber class],
    @"restrictedCategories" : [NSNumber class],
    @"sensitiveCategories" : [NSNumber class],
    @"servingRestrictions" : [GTLAdExchangeBuyerCreativeServingRestrictionsItem class],
    @"vendorType" : [NSNumber class]
  };
  return map;
}

+ (void)load {
  [self registerObjectClassForKind:@"adexchangebuyer#creative"];
}

@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeCorrectionsItem
//

@implementation GTLAdExchangeBuyerCreativeCorrectionsItem
@dynamic details, reason;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"details" : [NSString class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeFilteringReasons
//

@implementation GTLAdExchangeBuyerCreativeFilteringReasons
@dynamic date, reasons;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"reasons" : [GTLAdExchangeBuyerCreativeFilteringReasonsReasonsItem class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeNativeAd
//

@implementation GTLAdExchangeBuyerCreativeNativeAd
@dynamic advertiser, appIcon, body, callToAction, clickTrackingUrl, headline,
         image, impressionTrackingUrl, logo, price, starRating, store;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"impressionTrackingUrl" : [NSString class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeServingRestrictionsItem
//

@implementation GTLAdExchangeBuyerCreativeServingRestrictionsItem
@dynamic contexts, disapprovalReasons, reason;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"contexts" : [GTLAdExchangeBuyerCreativeServingRestrictionsItemContextsItem class],
    @"disapprovalReasons" : [GTLAdExchangeBuyerCreativeServingRestrictionsItemDisapprovalReasonsItem class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeFilteringReasonsReasonsItem
//

@implementation GTLAdExchangeBuyerCreativeFilteringReasonsReasonsItem
@dynamic filteringCount, filteringStatus;
@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeNativeAdAppIcon
//

@implementation GTLAdExchangeBuyerCreativeNativeAdAppIcon
@dynamic height, url, width;
@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeNativeAdImage
//

@implementation GTLAdExchangeBuyerCreativeNativeAdImage
@dynamic height, url, width;
@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeNativeAdLogo
//

@implementation GTLAdExchangeBuyerCreativeNativeAdLogo
@dynamic height, url, width;
@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeServingRestrictionsItemContextsItem
//

@implementation GTLAdExchangeBuyerCreativeServingRestrictionsItemContextsItem
@dynamic auctionType, contextType, geoCriteriaId, platform;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"auctionType" : [NSString class],
    @"geoCriteriaId" : [NSNumber class],
    @"platform" : [NSString class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLAdExchangeBuyerCreativeServingRestrictionsItemDisapprovalReasonsItem
//

@implementation GTLAdExchangeBuyerCreativeServingRestrictionsItemDisapprovalReasonsItem
@dynamic details, reason;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"details" : [NSString class]
  };
  return map;
}

@end


text:
package boa.test.datagen;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.hamcrest.Matchers;
import org.junit.Test;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.Message;

import boa.datagen.BoaGenerator;
import boa.datagen.DefaultProperties;
import boa.datagen.util.FileIO;
import boa.functions.BoaIntrinsics;
import boa.test.datagen.java.Java8BaseTest;
import boa.types.Ast.ASTRoot;
import boa.types.Ast.Declaration;
import boa.types.Code.CodeRepository;
import boa.types.Code.Revision;
import boa.types.Diff.ChangedFile;
import boa.types.Shared.Person;
import boa.types.Toplevel.Project;

public class TestSequenceFile extends Java8BaseTest {
	private Configuration conf = new Configuration();
	private FileSystem fileSystem;
	private SequenceFile.Reader pr;
	private SequenceFile.Reader ar;

	public TestSequenceFile() throws IOException {
		fileSystem = FileSystem.get(conf);
		Path projectPath = new Path("dataset/projects.seq");
		Path dataPath = new Path("dataset/data");
		if (fileSystem.exists(projectPath) && fileSystem.exists(dataPath)) {
			pr = new SequenceFile.Reader(fileSystem, projectPath, conf);
			ar = new SequenceFile.Reader(fileSystem, dataPath, conf);
		}
	}

	@Test
	public void projectSeqTest1() throws IOException {
		String path = "dataset/temp_data";
		File dataFile = new File(path);
    	path = dataFile.getAbsolutePath();

//    	DefaultProperties.DEBUG = true;
    	DefaultProperties.localDataPath = path;

		new FileIO.DirectoryRemover(dataFile.getAbsolutePath()).run();

		String[] args = {	"-inputJson", "test/datagen/jsons",
							"-inputRepo", "dataset/repos",
							"-output", path,
							"-commits", "1",
							"-threads", "2"};
		BoaGenerator.main(args);

		openMaps(path);
		fileSystem = FileSystem.get(conf);
		Path projectPath = new Path(path + "/projects.seq");
		Path dataPath = new Path(path + "/ast/data");
		if (fileSystem.exists(projectPath) && fileSystem.exists(dataPath)) {
			pr = new SequenceFile.Reader(fileSystem, projectPath, conf);
			ar = new SequenceFile.Reader(fileSystem, dataPath, conf);
		}
		Set<Long> cfKeys = new HashSet<Long>();
		Set<Long> astKeys = new HashSet<Long>();
		Writable key = new Text();
		BytesWritable val = new BytesWritable();
		while (pr.next(key, val)) {
			byte[] bytes = val.getBytes();
			Project project = Project.parseFrom(CodedInputStream.newInstance(bytes, 0, val.getLength()));
			for (CodeRepository cr : project.getCodeRepositoriesList()) {
				for (int i = 0; i < BoaIntrinsics.getRevisionsCount(cr); i++) {
					Revision rev = getRevision(cr, i);
					for (ChangedFile cf : rev.getFilesList()) {
						if (cf.getAst()) {
							if (DefaultProperties.DEBUG) {
								System.out.println(project.getName());
								System.out.println(rev.getId());
								System.out.println(cf);
							}
							assertThat(cfKeys.contains(cf.getKey()), Matchers.is(false));
							cfKeys.add(cf.getKey());
						}
					}
				}
				for (ChangedFile cf : cr.getHeadSnapshotList()) {
					if (cf.getAst()) {
						if (DefaultProperties.DEBUG) {
							System.out.println(project.getName());
							System.out.println(cf);
						}
						assertThat(cfKeys.contains(cf.getKey()), Matchers.is(false));
						cfKeys.add(cf.getKey());
					}
				}
			}
		}
		LongWritable lkey = new LongWritable();
		while (ar.next(lkey, val)) {
			assertThat(astKeys.contains(lkey.get()), Matchers.is(false));
			astKeys.add(lkey.get());
		}

		if (DefaultProperties.DEBUG) {
			Set<Long> inter = new HashSet<Long>(astKeys);
			inter.retainAll(cfKeys);

			System.out.println("In ASTs: " + astKeys.size());
			astKeys.removeAll(inter);
			System.out.println(astKeys.size());
	//		for (Long k : astKeys)
	//			System.out.println(k + " ");
			System.out.println("In changed files: " + cfKeys.size());
			cfKeys.removeAll(inter);
			System.out.println(cfKeys.size());
	//		for (Long k : cfKeys)
	//			System.out.println(k + " ");
		}
		assertThat(cfKeys, Matchers.is(astKeys));

		pr.close();
		ar.close();
		closeMaps();

		new FileIO.DirectoryRemover(dataFile.getAbsolutePath()).run();
	}

	private static final Revision emptyRevision;

	static {
		Revision.Builder rb = Revision.newBuilder();
		rb.setCommitDate(0);
		Person.Builder pb = Person.newBuilder();
		pb.setUsername("");
		rb.setCommitter(pb);
		rb.setId("");
		rb.setLog("");
		emptyRevision = rb.build();
	}

	public static Revision getRevision(final CodeRepository cr, final int index) {
		if (cr.getRevisionKeysCount() > 0) {
			long key = cr.getRevisionKeys(index);
			return getRevision(key);
		}
		return cr.getRevisions(index);
	}

	static Revision getRevision(long key) {
		try {
			final BytesWritable value = new BytesWritable();
			if (commitMap.get(new LongWritable(key), value) != null) {
				final CodedInputStream _stream = CodedInputStream.newInstance(value.getBytes(), 0, value.getLength());
				// defaults to 64, really big ASTs require more
				_stream.setRecursionLimit(Integer.MAX_VALUE);
				final Revision root = Revision.parseFrom(_stream);
				return root;
			}
		} catch (final Exception e) {
			e.printStackTrace();
		} catch (final Error e) {
			e.printStackTrace();
		}

		System.err.println("error with revision: " + key);
		return emptyRevision;
	}

	private static MapFile.Reader commitMap;
	private static MapFile.Reader astMap;

	private static void openMaps(String path) {
		try {
			final Configuration conf = new Configuration();
			final FileSystem fs;
			fs = FileSystem.getLocal(conf);
			astMap = new MapFile.Reader(fs, new Path(path + "/ast").toString(), conf);
			commitMap = new MapFile.Reader(fs, new Path(path + "/commit").toString(), conf);
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	private static void closeMaps() {
		closeMap(astMap);
		closeMap(commitMap);
	}

	private static void closeMap(MapFile.Reader map) {
		if (map != null)
			try {
				map.close();
			} catch (final IOException e) {
				e.printStackTrace();
			}
		map = null;
	}

	@Test
	public void projectSeqTest() throws IOException {
		if (pr == null || ar == null)
			return;
		Writable key = new Text();
		BytesWritable val = new BytesWritable();
		while (pr.next(key, val)) {
			byte[] bytes = val.getBytes();
			Project project = Project.parseFrom(CodedInputStream.newInstance(bytes, 0, val.getLength()));
			String name = project.getName();
			System.out.println(name);
			assertThat(name, anyOf(is("junit-team/junit4"), is("boalang/compiler"), is("candoia/candoia")));
			assertFalse(project.getForked());
			System.out.println("Forked " + project.getForked());
			System.out.println(project.getProgrammingLanguagesList().toString());
			System.out.println(project.getProgrammingLanguagesLocsList().toString());
			assertThat(project.getProgrammingLanguagesList().toString(), containsString("Java"));
			System.out.println("Stars " + project.getStars());
			assertTrue(project.getStars() > -1);
			System.out.println("Forks " + project.getForks());
			assertTrue(project.getForks() > -1);
			assertTrue(project.getCreatedDate() > -1);
			System.out.println(project.getCreatedDate());
			System.out.println(project.getHomepageUrl());
			System.out.println(project.getProjectUrl());
			System.out.println(project.getDescription() + "\n");
			final CodeRepository cr = project.getCodeRepositories(0);
			assertTrue(cr.getHeadSnapshotCount() > 0);
//			HashMap<Integer, HashMap<Integer, Declaration>> fileNodeDeclaration = collectDeclarations(cr.getHeadSnapshotList());
			final HashMap<Integer, HashMap<Integer, Declaration>> fileNodeDeclaration = new HashMap<Integer, HashMap<Integer, Declaration>>();
			for (ChangedFile cf : cr.getHeadSnapshotList()) {
				long astpos = cf.getKey();
				if (cf.getAst() && astpos > -1) {
					ar.seek(astpos);
					Writable astkey = new LongWritable();
					val = new BytesWritable();
					ar.next(astkey, val);
					bytes = val.getBytes();
					CodedInputStream cis = CodedInputStream.newInstance(bytes, 0, val.getLength());
					cis.setRecursionLimit(Integer.MAX_VALUE);
					ASTRoot root = ASTRoot.parseFrom(cis);
//					System.out.println(root);
					ProtoMessageVisitor v = new ProtoMessageVisitor() {
						@Override
						public boolean preVisit(Message message) {
							if (message instanceof boa.types.Ast.Type) {
								boa.types.Ast.Type type = (boa.types.Ast.Type) message;
								String fqn = type.getFullyQualifiedName();
								final int fileId = type.getDeclarationFile();
								final int nodeId = type.getDeclaration();
								if (fqn != null && !fqn.isEmpty() && fileId > 0) {
									Declaration decl = null;
									HashMap<Integer, Declaration> declarations = fileNodeDeclaration.get(fileId);
									if (declarations != null) {
										decl = declarations.get(nodeId);
									} else {
										declarations = new HashMap<Integer, Declaration>();
										fileNodeDeclaration.put(fileId, declarations);
									}
									if (decl == null) {
										ChangedFile dcf = cr.getHeadSnapshot(fileId);
										decl = getDeclaration(ar, dcf, nodeId, declarations);
									}
									System.out.println(fqn);
									assertEquals(true, decl != null && fqn.equals(decl.getFullyQualifiedName()));
								}
							}
							return true;
						}
					};
					v.visit(root);
				}
			}
		}
		pr.close();
		ar.close();
	}
}


text:
Recent Posts

{% for post in site.posts %}

{{ post.title }}

        {{ post.content | strip_html | truncatewords:20}} Read More »

{% endfor %}


text:
package io.vitess.jdbc;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import io.vitess.client.VTSession;
import io.vitess.proto.Query;
import io.vitess.proto.Query.ExecuteOptions.TransactionIsolation;
import io.vitess.proto.Topodata;
import io.vitess.util.Constants;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * Created by harshit.gangal on 19/01/16.
 */
@RunWith(PowerMockRunner.class)
public class VitessConnectionTest extends BaseTest {

  @Test
  public void testVitessConnection() throws SQLException {
    VitessConnection vitessConnection = new VitessConnection(dbURL, new Properties());
    assertFalse(vitessConnection.isClosed());
    assertNull(vitessConnection.getDbProperties());
  }

  @Test
  public void testCreateStatement() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    Statement statement = vitessConnection.createStatement();
    assertEquals(vitessConnection, statement.getConnection());
  }

  @Test
  public void testCreateStatementForClose() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    assertFailsOnClosedConnection(vitessConnection, vitessConnection::createStatement);
  }

  @Test
  public void testnativeSQL() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    assertEquals("query", vitessConnection.nativeSQL("query"));
  }

  @Test
  public void testCreatePreperedStatement() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    PreparedStatement preparedStatementstatement = vitessConnection.prepareStatement("query");
    assertEquals(vitessConnection, preparedStatementstatement.getConnection());
  }

  @Test
  public void testCreatePreparedStatementForClose() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    assertFailsOnClosedConnection(vitessConnection,
        () -> vitessConnection.prepareStatement("query"));
  }

  @Test
  public void testDefaultGetAutoCommit() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    assertTrue(vitessConnection.getAutoCommit());
  }

  @Test
  public void testDefaultGetAutoCommitForClose() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    assertFailsOnClosedConnection(vitessConnection, vitessConnection::getAutoCommit);
  }

  @Test
  public void testDefaultSetAutoCommit() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    vitessConnection.setAutoCommit(false);
    assertFalse(vitessConnection.getAutoCommit());
  }

  @Test
  public void testDefaultSetAutoCommitForClose() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    assertFailsOnClosedConnection(vitessConnection, () -> vitessConnection.setAutoCommit(false));
  }

  @Test
  public void testCommit() throws Exception {
    VTSession mockSession = PowerMockito.mock(VTSession.class);
    VitessConnection vitessConnection = getVitessConnection();
    Field privateVTSessionField = VitessConnection.class.getDeclaredField("vtSession");
    privateVTSessionField.setAccessible(true);
    privateVTSessionField.set(vitessConnection, mockSession);
    PowerMockito.when(mockSession.isInTransaction()).thenReturn(false);
    PowerMockito.when(mockSession.isAutoCommit()).thenReturn(false);
    vitessConnection.commit();
  }

  @Test(expected = SQLException.class)
  public void testCommitForException() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    vitessConnection.setAutoCommit(true);
    vitessConnection.commit();
  }

  @Test
  public void testRollback() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    vitessConnection.setAutoCommit(false);
    vitessConnection.rollback();
  }

  @Test(expected = SQLException.class)
  public void testRollbackForException() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    vitessConnection.setAutoCommit(true);
    vitessConnection.rollback();
  }

  @Test
  public void testClosed() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    vitessConnection.setAutoCommit(false);
    vitessConnection.close();
    assertTrue(vitessConnection.isClosed());
  }

  @Test(expected = SQLException.class)
  public void testClosedForException() throws Exception {
    VTSession mockSession = PowerMockito.mock(VTSession.class);
    VitessConnection vitessConnection = getVitessConnection();
    Field privateVTSessionField = VitessConnection.class.getDeclaredField("vtSession");
    privateVTSessionField.setAccessible(true);
    privateVTSessionField.set(vitessConnection, mockSession);
    PowerMockito.when(mockSession.isInTransaction()).thenReturn(true);
    PowerMockito.when(mockSession.isAutoCommit()).thenReturn(true);
    vitessConnection.close();
  }

  @Test
  public void testGetCatalog() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    assertEquals("keyspace", vitessConnection.getCatalog());
  }

  @Test
  public void testSetCatalog() throws SQLException {
    VitessConnection vitessConnection = getVitessConnection();
    vitessConnection.setCatalog("myDB");
    assertEquals("myDB", vitessConnection.getCatalog());
  }

  @Test
  public void testPropertiesFromJdbcUrl() throws SQLException {
    String url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica"
        + "&includedFields=type_and_name&blobsAreStrings=yes";
    VitessConnection conn = new VitessConnection(url, new Properties());

    // Properties from the url should be passed into the connection properties, and override
    // whatever defaults we've defined
    assertEquals(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME, conn.getIncludedFields());
    assertFalse(conn.isIncludeAllFields());
    assertEquals(Topodata.TabletType.REPLICA, conn.getTabletType());
    assertTrue(conn.getBlobsAreStrings());
  }

  @Test
  public void testClientFoundRows() throws SQLException {
    String url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica"
        + "&useAffectedRows=true";
    VitessConnection conn = new VitessConnection(url, new Properties());

    assertTrue(conn.getUseAffectedRows());
    assertFalse(conn.getVtSession().getSession().getOptions().getClientFoundRows());
  }

  @Test
  public void testClientFoundRows2() throws SQLException {
    String url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica"
        + "&useAffectedRows=false";
    VitessConnection conn = new VitessConnection(url, new Properties());

    assertFalse(conn.getUseAffectedRows());
    assertTrue(conn.getVtSession().getSession().getOptions().getClientFoundRows());
  }

  @Test
  public void testWorkload() throws SQLException {
    for (Query.ExecuteOptions.Workload workload : Query.ExecuteOptions.Workload.values()) {
      if (workload == Query.ExecuteOptions.Workload.UNRECOGNIZED) {
        continue;
      }
      String url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica&workload="
          + workload.toString().toLowerCase();
      VitessConnection conn = new VitessConnection(url, new Properties());

      assertEquals(workload, conn.getWorkload());
      assertEquals(workload, conn.getVtSession().getSession().getOptions().getWorkload());
    }
  }

  @Test
  public void testTransactionIsolation() throws SQLException {
    VitessConnection conn = Mockito.spy(getVitessConnection());
    doReturn(new DBProperties("random", "random", "random", Connection.TRANSACTION_REPEATABLE_READ,
        "random")).when(conn).getDbProperties();
    doReturn(new VitessMySQLDatabaseMetadata(conn)).when(conn).getMetaData();

    assertEquals(TransactionIsolation.DEFAULT,
        conn.getVtSession().getSession().getOptions().getTransactionIsolation());
    assertEquals(Connection.TRANSACTION_REPEATABLE_READ, conn.getTransactionIsolation());

    conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    assertEquals(TransactionIsolation.READ_COMMITTED,
        conn.getVtSession().getSession().getOptions().getTransactionIsolation());
    assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation());

    VitessStatement statement = mock(VitessStatement.class);
    when(conn.createStatement()).thenReturn(statement);
    when(conn.isInTransaction()).thenReturn(true);
    conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);

    verify(statement).executeUpdate("rollback");
    assertEquals(TransactionIsolation.READ_UNCOMMITTED,
        conn.getVtSession().getSession().getOptions().getTransactionIsolation());
    assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn.getTransactionIsolation());
  }

  interface Runthis {

    void run() throws SQLException;
  }

  private void assertFailsOnClosedConnection(VitessConnection connection, Runthis failingRunnable)
      throws SQLException {
    connection.close();
    try {
      failingRunnable.run();
      fail("expected this to fail on a closed connection");
    } catch (SQLException e) {
      assertEquals(e.getMessage(), Constants.SQLExceptionMessages.CONN_CLOSED);
    }
  }

}


text:
layout: post
title:  "Day 32"
date:   2017-12-18
categories: [bot, democracy earth]
comments: true
---
**Today's Progress:** Today I started to code the instagram bot for the Democracy Earth Project. I found a good open source project in python about this, it's called InstaPy. It worked very well, but I still need to implement the functions to follow someone by the hastag and follow someone back.

**Thoughts:** It's very nice see the bot working and following the people! And is super easy to do, maybe that's why the instagram is full of bots hahaha. But people can use this in a different and bad way...

**Link to work:**
* [Democracy Earth](https://www.democracy.earth/)
* [instaPy](https://github.com/timgrossmann/InstaPy)


text:
<!DOCTYPE html>

	<title>Basic fotorama</title>
	<meta charset="utf-8">

	<link  href="../out/fotorama.css" rel="stylesheet">

Basic fotorama:

<div class="fotorama">

Photos by Andrey Okonetchnikov


text:
package Composite;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.Enumeration;

//swing classes

public class Emptree extends Jxframe
        implements TreeSelectionListener {
  Employee boss, marketVP, prodVP;
  Employee salesMgr, advMgr;
  Employee prodMgr, shipMgr;

  JScrollPane sp;
  JPanel treePanel;
  JTree tree;
  DefaultMutableTreeNode troot;
  JLabel cost;

  public Emptree() {
    super("Employee tree");
    makeEmployees();
    setGUI();
  }

  //--------------------------------------
  static public void main(String argv[]) {
    new Emptree();
  }

  //--------------------------------------
  private void setGUI() {
    treePanel = new JPanel();
    getContentPane().add(treePanel);
    treePanel.setLayout(new BorderLayout());

    sp = new JScrollPane();
    treePanel.add("Center", sp);
    treePanel.add("South", cost = new JLabel("          "));

    treePanel.setBorder(new BevelBorder(BevelBorder.RAISED));
    troot = new DefaultMutableTreeNode(boss.getName());
    tree = new JTree(troot);
    tree.setBackground(Color.lightGray);
    loadTree(boss);
         /* Put the Tree in a scroller. */

    sp.getViewport().add(tree);
    setSize(new Dimension(200, 300));
    setVisible(true);

  }

  //------------------------------------
  public void loadTree(Employee topDog) {
    DefaultMutableTreeNode troot;
    troot = new DefaultMutableTreeNode(topDog.getName());
    treePanel.remove(tree);
    tree = new JTree(troot);
    tree.addTreeSelectionListener(this);
    sp.getViewport().add(tree);

    addNodes(troot, topDog);
    tree.expandRow(0);
    repaint();
  }

  //--------------------------------------
  private void addNodes(DefaultMutableTreeNode pnode, Employee emp) {
    DefaultMutableTreeNode node;

    Enumeration e = emp.elements();
    while (e.hasMoreElements()) {
      Employee newEmp = (Employee) e.nextElement();
      node = new DefaultMutableTreeNode(newEmp.getName());
      pnode.add(node);
      addNodes(node, newEmp);
    }
  }

  //--------------------------------------
  private void makeEmployees() {
    boss = new Employee("CEO", 200000);
    boss.add(marketVP = new Employee("Marketing VP", 100000));
    boss.add(prodVP = new Employee("Production VP", 100000));

    marketVP.add(salesMgr = new Employee("Sales Mgr", 50000));
    marketVP.add(advMgr = new Employee("Advt Mgr", 50000));

    for (int i = 0; i < 5; i++)
      salesMgr.add(new Employee("Sales " + new Integer(i).toString(), 30000.0F + (float) (Math.random() - 0.5) * 10000));
    advMgr.add(new Employee("Secy", 20000));

    prodVP.add(prodMgr = new Employee("Prod Mgr", 40000));
    prodVP.add(shipMgr = new Employee("Ship Mgr", 35000));
    for (int i = 0; i < 4; i++)
      prodMgr.add(new Employee("Manuf " + new Integer(i).toString(), 25000.0F + (float) (Math.random() - 0.5) * 5000));
    for (int i = 0; i < 3; i++)
      shipMgr.add(new Employee("ShipClrk " + new Integer(i).toString(), 20000.0F + (float) (Math.random() - 0.5) * 5000));

  }

  //--------------------------------------
  public void valueChanged(TreeSelectionEvent evt) {
    TreePath path = evt.getPath();
    String selectedTerm = path.getLastPathComponent().toString();

    Employee emp = boss.getChild(selectedTerm);
    if (emp != null)
      cost.setText(new Float(emp.getSalaries()).toString());
  }
}


text:
package com.signalcollect.triplerush.vertices.query

import scala.concurrent.Promise
import com.signalcollect.GraphEditor
import com.signalcollect.triplerush.QueryIds
import com.signalcollect.triplerush.optimizers.Optimizer
import com.signalcollect.triplerush.TriplePattern

/**
 * If execution is complete returns Some(numberOfResults), else returns None.
 */
final class ResultCountingQueryVertex(
  query: Seq[TriplePattern],
  tickets: Long,
  resultPromise: Promise[Option[Long]],
  optimizer: Option[Optimizer])
  extends AbstractQueryVertex[Long](query, tickets, numberOfSelectVariables = 0, Seq(), optimizer) {

  val id = QueryIds.embedQueryIdInLong(QueryIds.nextCountQueryId)

  override def afterInitialization(graphEditor: GraphEditor[Long, Any]) {
    state = 0
    super.afterInitialization(graphEditor)
  }

  def handleBindings(bindings: Array[Array[Int]]) {
    throw new UnsupportedOperationException("Result counting vertex should never receive bindings.")
  }

  def handleResultCount(resultCount: Long) {
    state += resultCount
  }

  override def reportResults {
    if (!resultsReported) {
      super.reportResults
      if (complete) {
        resultPromise.success(Some(state))
      } else {
        resultPromise.success(None)
      }
    }
  }

}


text:
package net.glowstone.command.minecraft;

import net.glowstone.command.CommandTest;

public class DefaultGameModeCommandTest extends CommandTest<DefaultGameModeCommand> {

    // TODO: Add more tests.

    public DefaultGameModeCommandTest() {
        super(DefaultGameModeCommand::new);
    }
}


text:
require "json"
require "httpclient"
require "net/http"

class CompareLinker
  class GithubLinkFinder
    attr_reader :octokit, :repo_owner, :repo_name, :homepage_uri

    def initialize(octokit)
      @octokit = octokit
    end

    def find(gem_name)
      gem_info = JSON.parse(
        HTTPClient.get("https://rubygems.org/api/v1/gems/#{gem_name}.json").body
      )

      github_url = [
        gem_info["homepage_uri"],
        gem_info["source_code_uri"]
      ].find { |uri| uri.to_s.match(/github\.com\//) }

      if github_url.nil?
        @homepage_uri = gem_info["homepage_uri"]
      else
        github_url = redirect_url(github_url)
        _, @repo_owner, @repo_name = github_url.match(%r!github\.com/([^/]+)/([^/]+)!).to_a
      end
    end

    def repo_full_name
      "#{@repo_owner}/#{repo_name}"
    end

    private

    def redirect_url(url, limit = 5)
      raise ArgumentError, 'HTTP redirect too deep' if limit <= 0
      response = Net::HTTP.get_response(URI.parse(url))
      case response
      when Net::HTTPSuccess
        url
      when Net::HTTPRedirection
        redirect_url(response['location'], limit - 1)
      else
        raise ItemNotFound
      end
    end
  end
end


text:
package com.iss.gms.entity;

import java.util.Date;

public class EmployeeRelegationInfo {
	//Ô±¹¤±àºÅ
	private String employeeId;
	//Ô±¹¤±àºÅ(ÐÞ¸ÄËùÓÃ)
	private String employeeIdNew;
	//Ô±¹¤ÐÕÃû
	private String employeeName;
	//ÏîÄ¿×ܼà
	private String projectDirector;
	//ÏîÄ¿¾Àí
	private String projectManager;
	//ÏîÄ¿×鳤
	private String projectLeader;
	//µÈ¼¶
	private String grade;
	//״̬
	private String workstaus;
	//ÒµÎñÏß
	private String businessLine;
	//ËùÊôTSÏîÄ¿
	private String belongedTSproject;
	//ËùÊôTSÏîÄ¿±àºÅ
	private String belongedTSprojectId;
	//È볡Ãâ·Ñʱ¼ä
	private Date admittancefreeDate;
	//È볡¼Æ·Ñʱ¼ä
	private Date admittancebillingDate;
	//Ô¤¼ÆÀ볡ʱ¼ä
	private Date outsceneestimateDate;
	//ʵ¼ÊÀ볡ʱ¼ä
	private Date outscenerealityDate;
	//¿ªÊ¼Ê±¼ä
	private Date estimateLDateS;
	//½áÊøʱ¼ä
	private Date estimateLDateE;
	//ÐÞ¸ÄÓÃ-ÐÂÏîÄ¿Ãû³Æ
	private String newProName;
	//ÐÞ¸ÄÓÃ-ÐÂ״̬
	private String newWorkstatus;
	//ÈËÔ±±ä¶¯
	private String empOperate;
	//ËùÊô¹«Ë¾
	private String company;
	//¼¼ÄÜ
	private String skill;
	//·ÑÂÊ
	private String rate;

	public String getEmployeeIdNew() {
		return employeeIdNew;
	}
	public void setEmployeeIdNew(String employeeIdNew) {
		this.employeeIdNew = employeeIdNew;
	}
	public String getCompany() {
		return company;
	}
	public void setCompany(String company) {
		this.company = company;
	}
	public String getSkill() {
		return skill;
	}
	public void setSkill(String skill) {
		this.skill = skill;
	}
	public String getRate() {
		return rate;
	}
	public void setRate(String rate) {
		this.rate = rate;
	}
	public String getEmpOperate() {
		return empOperate;
	}
	public void setEmpOperate(String empOperate) {
		this.empOperate = empOperate;
	}
	public String getNewProName() {
		return newProName;
	}
	public void setNewProName(String newProName) {
		this.newProName = newProName;
	}
	public String getNewWorkstatus() {
		return newWorkstatus;
	}
	public void setNewWorkstatus(String newWorkstatus) {
		this.newWorkstatus = newWorkstatus;
	}
	private Float standardTotalHours;
	private Float customerSureTotalHours;
	private Float psaWelfareHoliaysTotalHours;
	private Float psaNotWelfareHoliaysTotalHours;
	private Float lastSwoppedTotalHours;
	private Float workoTimeAhughTotalHours;
	private Float workoTimeSubsidiesTotalHours;
	private Date byTheStatisticalDate;

	public String getBelongedTSprojectId() {
		return belongedTSprojectId;
	}
	public void setBelongedTSprojectId(String belongedTSprojectId) {
		this.belongedTSprojectId = belongedTSprojectId;
	}
	public Float getStandardTotalHours() {
		return standardTotalHours;
	}
	public void setStandardTotalHours(Float standardTotalHours) {
		this.standardTotalHours = standardTotalHours;
	}
	public Float getCustomerSureTotalHours() {
		return customerSureTotalHours;
	}
	public void setCustomerSureTotalHours(Float customerSureTotalHours) {
		this.customerSureTotalHours = customerSureTotalHours;
	}
	public Float getPsaWelfareHoliaysTotalHours() {
		return psaWelfareHoliaysTotalHours;
	}
	public void setPsaWelfareHoliaysTotalHours(Float psaWelfareHoliaysTotalHours) {
		this.psaWelfareHoliaysTotalHours = psaWelfareHoliaysTotalHours;
	}
	public Float getPsaNotWelfareHoliaysTotalHours() {
		return psaNotWelfareHoliaysTotalHours;
	}
	public void setPsaNotWelfareHoliaysTotalHours(
			Float psaNotWelfareHoliaysTotalHours) {
		this.psaNotWelfareHoliaysTotalHours = psaNotWelfareHoliaysTotalHours;
	}
	public Float getLastSwoppedTotalHours() {
		return lastSwoppedTotalHours;
	}
	public void setLastSwoppedTotalHours(Float lastSwoppedTotalHours) {
		this.lastSwoppedTotalHours = lastSwoppedTotalHours;
	}
	public Float getWorkoTimeAhughTotalHours() {
		return workoTimeAhughTotalHours;
	}
	public void setWorkoTimeAhughTotalHours(Float workoTimeAhughTotalHours) {
		this.workoTimeAhughTotalHours = workoTimeAhughTotalHours;
	}
	public Float getWorkoTimeSubsidiesTotalHours() {
		return workoTimeSubsidiesTotalHours;
	}
	public void setWorkoTimeSubsidiesTotalHours(Float workoTimeSubsidiesTotalHours) {
		this.workoTimeSubsidiesTotalHours = workoTimeSubsidiesTotalHours;
	}
	public Date getByTheStatisticalDate() {
		return byTheStatisticalDate;
	}
	public void setByTheStatisticalDate(Date byTheStatisticalDate) {
		this.byTheStatisticalDate = byTheStatisticalDate;
	}
	public Date getEstimateLDateS() {
		return estimateLDateS;
	}
	public void setEstimateLDateS(Date estimateLDateS) {
		this.estimateLDateS = estimateLDateS;
	}
	public Date getEstimateLDateE() {
		return estimateLDateE;
	}
	public void setEstimateLDateE(Date estimateLDateE) {
		this.estimateLDateE = estimateLDateE;
	}
	public String getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(String employeeId) {
		this.employeeId = employeeId;
	}
	public String getEmployeeName() {
		return employeeName;
	}
	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}
	public String getProjectDirector() {
		return projectDirector;
	}
	public void setProjectDirector(String projectDirector) {
		this.projectDirector = projectDirector;
	}
	public String getProjectManager() {
		return projectManager;
	}
	public void setProjectManager(String projectManager) {
		this.projectManager = projectManager;
	}
	public String getProjectLeader() {
		return projectLeader;
	}
	public void setProjectLeader(String projectLeader) {
		this.projectLeader = projectLeader;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	public Date getAdmittancefreeDate() {
		return admittancefreeDate;
	}
	public void setAdmittancefreeDate(Date admittancefreeDate) {
		this.admittancefreeDate = admittancefreeDate;
	}
	public Date getAdmittancebillingDate() {
		return admittancebillingDate;
	}
	public void setAdmittancebillingDate(Date admittancebillingDate) {
		this.admittancebillingDate = admittancebillingDate;
	}
	public Date getOutsceneestimateDate() {
		return outsceneestimateDate;
	}
	public void setOutsceneestimateDate(Date outsceneestimateDate) {
		this.outsceneestimateDate = outsceneestimateDate;
	}
	public Date getOutscenerealityDate() {
		return outscenerealityDate;
	}
	public void setOutscenerealityDate(Date outscenerealityDate) {
		this.outscenerealityDate = outscenerealityDate;
	}
	public String getWorkstaus() {
		return workstaus;
	}
	public void setWorkstaus(String workstaus) {
		this.workstaus = workstaus;
	}
	public String getBusinessLine() {
		return businessLine;
	}
	public void setBusinessLine(String businessLine) {
		this.businessLine = businessLine;
	}
	public String getBelongedTSproject() {
		return belongedTSproject;
	}
	public void setBelongedTSproject(String belongedTSproject) {
		this.belongedTSproject = belongedTSproject;
	}

}


text:
using namespace std;

std::string gFormatStr("v1");

std::string FormatFullVersion()
{
	return(gFormatStr);
}

string strprintf(const char* format, ...)
{
	char buffer[50000];
	char* p = buffer;
	int limit = sizeof(buffer);
	int ret;
	loop
	{
		va_list arg_ptr;
		va_start(arg_ptr, format);
		ret = _vsnprintf(p, limit, format, arg_ptr);
		va_end(arg_ptr);
		if (ret >= 0 && ret < limit)
			break;
		if (p != buffer)
			delete[] p;
		limit *= 2;
		p = new char[limit];
		if (p == NULL)
			throw std::bad_alloc();
	}
	string str(p, p+ret);
	if (p != buffer)
		delete[] p;
	return str;
}

inline int64 GetPerformanceCounter()
{
	int64 nCounter = 0;
#if defined(WIN32) || defined(WIN64)
	QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
#else
	timeval t;
	gettimeofday(&t, NULL);
	nCounter = t.tv_sec * 1000000 + t.tv_usec;
#endif
	return nCounter;
}

void RandAddSeed()
{
	// Seed with CPU performance counter
	int64 nCounter = GetPerformanceCounter();
	RAND_add(&nCounter, sizeof(nCounter), 1.5);
	memset(&nCounter, 0, sizeof(nCounter));
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
//  - System clock
//  - Median of other nodes's clocks
//  - The user (asking the user to fix the system clock if the first two disagree)
//
int64 GetTime()
{
	return time(NULL);
}

void RandAddSeedPerfmon()
{
	RandAddSeed();

	// This can take up to 2 seconds, so only do it every 10 minutes
	static int64 nLastPerfmon;
	if (GetTime() < nLastPerfmon + 10 * 60)
		return;
	nLastPerfmon = GetTime();

#ifdef WIN32
	// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
	// Seed with the entire set of perfmon data
	unsigned char pdata[250000];
	memset(pdata, 0, sizeof(pdata));
	unsigned long nSize = sizeof(pdata);
	long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
	RegCloseKey(HKEY_PERFORMANCE_DATA);
	if (ret == ERROR_SUCCESS)
	{
		RAND_add(pdata, nSize, nSize/100.0);
		memset(pdata, 0, nSize);
		//printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
	}
#endif
}