text:
package com.google.cloud.talent.v4beta1.stub;

import static com.google.cloud.talent.v4beta1.JobServiceClient.ListJobsPagedResponse;
import static com.google.cloud.talent.v4beta1.JobServiceClient.SearchJobsForAlertPagedResponse;
import static com.google.cloud.talent.v4beta1.JobServiceClient.SearchJobsPagedResponse;

import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.httpjson.ApiMethodDescriptor;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonOperationSnapshot;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.httpjson.ProtoMessageRequestFormatter;
import com.google.api.gax.httpjson.ProtoMessageResponseParser;
import com.google.api.gax.httpjson.ProtoRestSerializer;
import com.google.api.gax.httpjson.longrunning.stub.HttpJsonOperationsStub;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.talent.v4beta1.BatchCreateJobsRequest;
import com.google.cloud.talent.v4beta1.BatchDeleteJobsRequest;
import com.google.cloud.talent.v4beta1.BatchOperationMetadata;
import com.google.cloud.talent.v4beta1.BatchUpdateJobsRequest;
import com.google.cloud.talent.v4beta1.CreateJobRequest;
import com.google.cloud.talent.v4beta1.DeleteJobRequest;
import com.google.cloud.talent.v4beta1.GetJobRequest;
import com.google.cloud.talent.v4beta1.Job;
import com.google.cloud.talent.v4beta1.JobOperationResult;
import com.google.cloud.talent.v4beta1.ListJobsRequest;
import com.google.cloud.talent.v4beta1.ListJobsResponse;
import com.google.cloud.talent.v4beta1.SearchJobsRequest;
import com.google.cloud.talent.v4beta1.SearchJobsResponse;
import com.google.cloud.talent.v4beta1.UpdateJobRequest;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
import com.google.protobuf.TypeRegistry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
 * REST stub implementation for the JobService service API.
 *
 * <p>This class is for advanced usage and reflects the underlying API directly.
 */
@BetaApi
@Generated("by gapic-generator-java")
public class HttpJsonJobServiceStub extends JobServiceStub {
  private static final TypeRegistry typeRegistry =
      TypeRegistry.newBuilder()
          .add(JobOperationResult.getDescriptor())
          .add(BatchOperationMetadata.getDescriptor())
          .build();

  private static final ApiMethodDescriptor<CreateJobRequest, Job> createJobMethodDescriptor =
      ApiMethodDescriptor.<CreateJobRequest, Job>newBuilder()
          .setFullMethodName("google.cloud.talent.v4beta1.JobService/CreateJob")
          .setHttpMethod("POST")
          .setType(ApiMethodDescriptor.MethodType.UNARY)
          .setRequestFormatter(
              ProtoMessageRequestFormatter.<CreateJobRequest>newBuilder()
                  .setPath(
                      "/v4beta1/{parent=projects/*/tenants/*}/jobs",
                      request -> {
                        Map<String, String> fields = new HashMap<>();
                        ProtoRestSerializer<CreateJobRequest> serializer =
                            ProtoRestSerializer.create();
                        serializer.putPathParam(fields, "parent", request.getParent());
                        return fields;
                      })
                  .setAdditionalPaths("/v4beta1/{parent=projects/*}/jobs")
                  .setQueryParamsExtractor(
                      request -> {
                        Map<String, List<String>> fields = new HashMap<>();
                        ProtoRestSerializer<CreateJobRequest> serializer =
                            ProtoRestSerializer.create();
                        return fields;
                      })
                  .setRequestBodyExtractor(
                      request ->
                          ProtoRestSerializer.create()
                              .toBody("*", request.toBuilder().clearParent().build(), false))
                  .build())
          .setResponseParser(
              ProtoMessageResponseParser.<Job>newBuilder()
                  .setDefaultInstance(Job.getDefaultInstance())
                  .setDefaultTypeRegistry(typeRegistry)
                  .build())
          .build();

  private static final ApiMethodDescriptor<BatchCreateJobsRequest, Operation>
      batchCreateJobsMethodDescriptor =
          ApiMethodDescriptor.<BatchCreateJobsRequest, Operation>newBuilder()
              .setFullMethodName("google.cloud.talent.v4beta1.JobService/BatchCreateJobs")
              .setHttpMethod("POST")
              .setType(ApiMethodDescriptor.MethodType.UNARY)
              .setRequestFormatter(
                  ProtoMessageRequestFormatter.<BatchCreateJobsRequest>newBuilder()
                      .setPath(
                          "/v4beta1/{parent=projects/*/tenants/*}/jobs:batchCreate",
                          request -> {
                            Map<String, String> fields = new HashMap<>();
                            ProtoRestSerializer<BatchCreateJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            serializer.putPathParam(fields, "parent", request.getParent());
                            return fields;
                          })
                      .setAdditionalPaths("/v4beta1/{parent=projects/*}/jobs:batchCreate")
                      .setQueryParamsExtractor(
                          request -> {
                            Map<String, List<String>> fields = new HashMap<>();
                            ProtoRestSerializer<BatchCreateJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            return fields;
                          })
                      .setRequestBodyExtractor(
                          request ->
                              ProtoRestSerializer.create()
                                  .toBody("*", request.toBuilder().clearParent().build(), false))
                      .build())
              .setResponseParser(
                  ProtoMessageResponseParser.<Operation>newBuilder()
                      .setDefaultInstance(Operation.getDefaultInstance())
                      .setDefaultTypeRegistry(typeRegistry)
                      .build())
              .setOperationSnapshotFactory(
                  (BatchCreateJobsRequest request, Operation response) ->
                      HttpJsonOperationSnapshot.create(response))
              .build();

  private static final ApiMethodDescriptor<GetJobRequest, Job> getJobMethodDescriptor =
      ApiMethodDescriptor.<GetJobRequest, Job>newBuilder()
          .setFullMethodName("google.cloud.talent.v4beta1.JobService/GetJob")
          .setHttpMethod("GET")
          .setType(ApiMethodDescriptor.MethodType.UNARY)
          .setRequestFormatter(
              ProtoMessageRequestFormatter.<GetJobRequest>newBuilder()
                  .setPath(
                      "/v4beta1/{name=projects/*/tenants/*/jobs/*}",
                      request -> {
                        Map<String, String> fields = new HashMap<>();
                        ProtoRestSerializer<GetJobRequest> serializer =
                            ProtoRestSerializer.create();
                        serializer.putPathParam(fields, "name", request.getName());
                        return fields;
                      })
                  .setAdditionalPaths("/v4beta1/{name=projects/*/jobs/*}")
                  .setQueryParamsExtractor(
                      request -> {
                        Map<String, List<String>> fields = new HashMap<>();
                        ProtoRestSerializer<GetJobRequest> serializer =
                            ProtoRestSerializer.create();
                        return fields;
                      })
                  .setRequestBodyExtractor(request -> null)
                  .build())
          .setResponseParser(
              ProtoMessageResponseParser.<Job>newBuilder()
                  .setDefaultInstance(Job.getDefaultInstance())
                  .setDefaultTypeRegistry(typeRegistry)
                  .build())
          .build();

  private static final ApiMethodDescriptor<UpdateJobRequest, Job> updateJobMethodDescriptor =
      ApiMethodDescriptor.<UpdateJobRequest, Job>newBuilder()
          .setFullMethodName("google.cloud.talent.v4beta1.JobService/UpdateJob")
          .setHttpMethod("PATCH")
          .setType(ApiMethodDescriptor.MethodType.UNARY)
          .setRequestFormatter(
              ProtoMessageRequestFormatter.<UpdateJobRequest>newBuilder()
                  .setPath(
                      "/v4beta1/{job.name=projects/*/tenants/*/jobs/*}",
                      request -> {
                        Map<String, String> fields = new HashMap<>();
                        ProtoRestSerializer<UpdateJobRequest> serializer =
                            ProtoRestSerializer.create();
                        serializer.putPathParam(fields, "job.name", request.getJob().getName());
                        return fields;
                      })
                  .setAdditionalPaths("/v4beta1/{job.name=projects/*/jobs/*}")
                  .setQueryParamsExtractor(
                      request -> {
                        Map<String, List<String>> fields = new HashMap<>();
                        ProtoRestSerializer<UpdateJobRequest> serializer =
                            ProtoRestSerializer.create();
                        return fields;
                      })
                  .setRequestBodyExtractor(
                      request ->
                          ProtoRestSerializer.create()
                              .toBody("*", request.toBuilder().build(), false))
                  .build())
          .setResponseParser(
              ProtoMessageResponseParser.<Job>newBuilder()
                  .setDefaultInstance(Job.getDefaultInstance())
                  .setDefaultTypeRegistry(typeRegistry)
                  .build())
          .build();

  private static final ApiMethodDescriptor<BatchUpdateJobsRequest, Operation>
      batchUpdateJobsMethodDescriptor =
          ApiMethodDescriptor.<BatchUpdateJobsRequest, Operation>newBuilder()
              .setFullMethodName("google.cloud.talent.v4beta1.JobService/BatchUpdateJobs")
              .setHttpMethod("POST")
              .setType(ApiMethodDescriptor.MethodType.UNARY)
              .setRequestFormatter(
                  ProtoMessageRequestFormatter.<BatchUpdateJobsRequest>newBuilder()
                      .setPath(
                          "/v4beta1/{parent=projects/*/tenants/*}/jobs:batchUpdate",
                          request -> {
                            Map<String, String> fields = new HashMap<>();
                            ProtoRestSerializer<BatchUpdateJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            serializer.putPathParam(fields, "parent", request.getParent());
                            return fields;
                          })
                      .setAdditionalPaths("/v4beta1/{parent=projects/*}/jobs:batchUpdate")
                      .setQueryParamsExtractor(
                          request -> {
                            Map<String, List<String>> fields = new HashMap<>();
                            ProtoRestSerializer<BatchUpdateJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            return fields;
                          })
                      .setRequestBodyExtractor(
                          request ->
                              ProtoRestSerializer.create()
                                  .toBody("*", request.toBuilder().clearParent().build(), false))
                      .build())
              .setResponseParser(
                  ProtoMessageResponseParser.<Operation>newBuilder()
                      .setDefaultInstance(Operation.getDefaultInstance())
                      .setDefaultTypeRegistry(typeRegistry)
                      .build())
              .setOperationSnapshotFactory(
                  (BatchUpdateJobsRequest request, Operation response) ->
                      HttpJsonOperationSnapshot.create(response))
              .build();

  private static final ApiMethodDescriptor<DeleteJobRequest, Empty> deleteJobMethodDescriptor =
      ApiMethodDescriptor.<DeleteJobRequest, Empty>newBuilder()
          .setFullMethodName("google.cloud.talent.v4beta1.JobService/DeleteJob")
          .setHttpMethod("DELETE")
          .setType(ApiMethodDescriptor.MethodType.UNARY)
          .setRequestFormatter(
              ProtoMessageRequestFormatter.<DeleteJobRequest>newBuilder()
                  .setPath(
                      "/v4beta1/{name=projects/*/tenants/*/jobs/*}",
                      request -> {
                        Map<String, String> fields = new HashMap<>();
                        ProtoRestSerializer<DeleteJobRequest> serializer =
                            ProtoRestSerializer.create();
                        serializer.putPathParam(fields, "name", request.getName());
                        return fields;
                      })
                  .setAdditionalPaths("/v4beta1/{name=projects/*/jobs/*}")
                  .setQueryParamsExtractor(
                      request -> {
                        Map<String, List<String>> fields = new HashMap<>();
                        ProtoRestSerializer<DeleteJobRequest> serializer =
                            ProtoRestSerializer.create();
                        return fields;
                      })
                  .setRequestBodyExtractor(request -> null)
                  .build())
          .setResponseParser(
              ProtoMessageResponseParser.<Empty>newBuilder()
                  .setDefaultInstance(Empty.getDefaultInstance())
                  .setDefaultTypeRegistry(typeRegistry)
                  .build())
          .build();

  private static final ApiMethodDescriptor<BatchDeleteJobsRequest, Empty>
      batchDeleteJobsMethodDescriptor =
          ApiMethodDescriptor.<BatchDeleteJobsRequest, Empty>newBuilder()
              .setFullMethodName("google.cloud.talent.v4beta1.JobService/BatchDeleteJobs")
              .setHttpMethod("POST")
              .setType(ApiMethodDescriptor.MethodType.UNARY)
              .setRequestFormatter(
                  ProtoMessageRequestFormatter.<BatchDeleteJobsRequest>newBuilder()
                      .setPath(
                          "/v4beta1/{parent=projects/*/tenants/*}/jobs:batchDelete",
                          request -> {
                            Map<String, String> fields = new HashMap<>();
                            ProtoRestSerializer<BatchDeleteJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            serializer.putPathParam(fields, "parent", request.getParent());
                            return fields;
                          })
                      .setAdditionalPaths("/v4beta1/{parent=projects/*}/jobs:batchDelete")
                      .setQueryParamsExtractor(
                          request -> {
                            Map<String, List<String>> fields = new HashMap<>();
                            ProtoRestSerializer<BatchDeleteJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            return fields;
                          })
                      .setRequestBodyExtractor(
                          request ->
                              ProtoRestSerializer.create()
                                  .toBody("*", request.toBuilder().clearParent().build(), false))
                      .build())
              .setResponseParser(
                  ProtoMessageResponseParser.<Empty>newBuilder()
                      .setDefaultInstance(Empty.getDefaultInstance())
                      .setDefaultTypeRegistry(typeRegistry)
                      .build())
              .build();

  private static final ApiMethodDescriptor<ListJobsRequest, ListJobsResponse>
      listJobsMethodDescriptor =
          ApiMethodDescriptor.<ListJobsRequest, ListJobsResponse>newBuilder()
              .setFullMethodName("google.cloud.talent.v4beta1.JobService/ListJobs")
              .setHttpMethod("GET")
              .setType(ApiMethodDescriptor.MethodType.UNARY)
              .setRequestFormatter(
                  ProtoMessageRequestFormatter.<ListJobsRequest>newBuilder()
                      .setPath(
                          "/v4beta1/{parent=projects/*/tenants/*}/jobs",
                          request -> {
                            Map<String, String> fields = new HashMap<>();
                            ProtoRestSerializer<ListJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            serializer.putPathParam(fields, "parent", request.getParent());
                            return fields;
                          })
                      .setAdditionalPaths("/v4beta1/{parent=projects/*}/jobs")
                      .setQueryParamsExtractor(
                          request -> {
                            Map<String, List<String>> fields = new HashMap<>();
                            ProtoRestSerializer<ListJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            serializer.putQueryParam(fields, "filter", request.getFilter());
                            serializer.putQueryParam(fields, "jobView", request.getJobView());
                            serializer.putQueryParam(fields, "pageSize", request.getPageSize());
                            serializer.putQueryParam(fields, "pageToken", request.getPageToken());
                            return fields;
                          })
                      .setRequestBodyExtractor(request -> null)
                      .build())
              .setResponseParser(
                  ProtoMessageResponseParser.<ListJobsResponse>newBuilder()
                      .setDefaultInstance(ListJobsResponse.getDefaultInstance())
                      .setDefaultTypeRegistry(typeRegistry)
                      .build())
              .build();

  private static final ApiMethodDescriptor<SearchJobsRequest, SearchJobsResponse>
      searchJobsMethodDescriptor =
          ApiMethodDescriptor.<SearchJobsRequest, SearchJobsResponse>newBuilder()
              .setFullMethodName("google.cloud.talent.v4beta1.JobService/SearchJobs")
              .setHttpMethod("POST")
              .setType(ApiMethodDescriptor.MethodType.UNARY)
              .setRequestFormatter(
                  ProtoMessageRequestFormatter.<SearchJobsRequest>newBuilder()
                      .setPath(
                          "/v4beta1/{parent=projects/*/tenants/*}/jobs:search",
                          request -> {
                            Map<String, String> fields = new HashMap<>();
                            ProtoRestSerializer<SearchJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            serializer.putPathParam(fields, "parent", request.getParent());
                            return fields;
                          })
                      .setAdditionalPaths("/v4beta1/{parent=projects/*}/jobs:search")
                      .setQueryParamsExtractor(
                          request -> {
                            Map<String, List<String>> fields = new HashMap<>();
                            ProtoRestSerializer<SearchJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            return fields;
                          })
                      .setRequestBodyExtractor(
                          request ->
                              ProtoRestSerializer.create()
                                  .toBody("*", request.toBuilder().clearParent().build(), false))
                      .build())
              .setResponseParser(
                  ProtoMessageResponseParser.<SearchJobsResponse>newBuilder()
                      .setDefaultInstance(SearchJobsResponse.getDefaultInstance())
                      .setDefaultTypeRegistry(typeRegistry)
                      .build())
              .build();

  private static final ApiMethodDescriptor<SearchJobsRequest, SearchJobsResponse>
      searchJobsForAlertMethodDescriptor =
          ApiMethodDescriptor.<SearchJobsRequest, SearchJobsResponse>newBuilder()
              .setFullMethodName("google.cloud.talent.v4beta1.JobService/SearchJobsForAlert")
              .setHttpMethod("POST")
              .setType(ApiMethodDescriptor.MethodType.UNARY)
              .setRequestFormatter(
                  ProtoMessageRequestFormatter.<SearchJobsRequest>newBuilder()
                      .setPath(
                          "/v4beta1/{parent=projects/*/tenants/*}/jobs:searchForAlert",
                          request -> {
                            Map<String, String> fields = new HashMap<>();
                            ProtoRestSerializer<SearchJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            serializer.putPathParam(fields, "parent", request.getParent());
                            return fields;
                          })
                      .setAdditionalPaths("/v4beta1/{parent=projects/*}/jobs:searchForAlert")
                      .setQueryParamsExtractor(
                          request -> {
                            Map<String, List<String>> fields = new HashMap<>();
                            ProtoRestSerializer<SearchJobsRequest> serializer =
                                ProtoRestSerializer.create();
                            return fields;
                          })
                      .setRequestBodyExtractor(
                          request ->
                              ProtoRestSerializer.create()
                                  .toBody("*", request.toBuilder().clearParent().build(), false))
                      .build())
              .setResponseParser(
                  ProtoMessageResponseParser.<SearchJobsResponse>newBuilder()
                      .setDefaultInstance(SearchJobsResponse.getDefaultInstance())
                      .setDefaultTypeRegistry(typeRegistry)
                      .build())
              .build();

  private final UnaryCallable<CreateJobRequest, Job> createJobCallable;
  private final UnaryCallable<BatchCreateJobsRequest, Operation> batchCreateJobsCallable;
  private final OperationCallable<
          BatchCreateJobsRequest, JobOperationResult, BatchOperationMetadata>
      batchCreateJobsOperationCallable;
  private final UnaryCallable<GetJobRequest, Job> getJobCallable;
  private final UnaryCallable<UpdateJobRequest, Job> updateJobCallable;
  private final UnaryCallable<BatchUpdateJobsRequest, Operation> batchUpdateJobsCallable;
  private final OperationCallable<
          BatchUpdateJobsRequest, JobOperationResult, BatchOperationMetadata>
      batchUpdateJobsOperationCallable;
  private final UnaryCallable<DeleteJobRequest, Empty> deleteJobCallable;
  private final UnaryCallable<BatchDeleteJobsRequest, Empty> batchDeleteJobsCallable;
  private final UnaryCallable<ListJobsRequest, ListJobsResponse> listJobsCallable;
  private final UnaryCallable<ListJobsRequest, ListJobsPagedResponse> listJobsPagedCallable;
  private final UnaryCallable<SearchJobsRequest, SearchJobsResponse> searchJobsCallable;
  private final UnaryCallable<SearchJobsRequest, SearchJobsPagedResponse> searchJobsPagedCallable;
  private final UnaryCallable<SearchJobsRequest, SearchJobsResponse> searchJobsForAlertCallable;
  private final UnaryCallable<SearchJobsRequest, SearchJobsForAlertPagedResponse>
      searchJobsForAlertPagedCallable;

  private final BackgroundResource backgroundResources;
  private final HttpJsonOperationsStub httpJsonOperationsStub;
  private final HttpJsonStubCallableFactory callableFactory;

  public static final HttpJsonJobServiceStub create(JobServiceStubSettings settings)
      throws IOException {
    return new HttpJsonJobServiceStub(settings, ClientContext.create(settings));
  }

  public static final HttpJsonJobServiceStub create(ClientContext clientContext)
      throws IOException {
    return new HttpJsonJobServiceStub(
        JobServiceStubSettings.newHttpJsonBuilder().build(), clientContext);
  }

  public static final HttpJsonJobServiceStub create(
      ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException {
    return new HttpJsonJobServiceStub(
        JobServiceStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory);
  }

  /**
   * Constructs an instance of HttpJsonJobServiceStub, using the given settings. This is protected
   * so that it is easy to make a subclass, but otherwise, the static factory methods should be
   * preferred.
   */
  protected HttpJsonJobServiceStub(JobServiceStubSettings settings, ClientContext clientContext)
      throws IOException {
    this(settings, clientContext, new HttpJsonJobServiceCallableFactory());
  }

  /**
   * Constructs an instance of HttpJsonJobServiceStub, using the given settings. This is protected
   * so that it is easy to make a subclass, but otherwise, the static factory methods should be
   * preferred.
   */
  protected HttpJsonJobServiceStub(
      JobServiceStubSettings settings,
      ClientContext clientContext,
      HttpJsonStubCallableFactory callableFactory)
      throws IOException {
    this.callableFactory = callableFactory;
    this.httpJsonOperationsStub =
        HttpJsonOperationsStub.create(clientContext, callableFactory, typeRegistry);

    HttpJsonCallSettings<CreateJobRequest, Job> createJobTransportSettings =
        HttpJsonCallSettings.<CreateJobRequest, Job>newBuilder()
            .setMethodDescriptor(createJobMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<BatchCreateJobsRequest, Operation> batchCreateJobsTransportSettings =
        HttpJsonCallSettings.<BatchCreateJobsRequest, Operation>newBuilder()
            .setMethodDescriptor(batchCreateJobsMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<GetJobRequest, Job> getJobTransportSettings =
        HttpJsonCallSettings.<GetJobRequest, Job>newBuilder()
            .setMethodDescriptor(getJobMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<UpdateJobRequest, Job> updateJobTransportSettings =
        HttpJsonCallSettings.<UpdateJobRequest, Job>newBuilder()
            .setMethodDescriptor(updateJobMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<BatchUpdateJobsRequest, Operation> batchUpdateJobsTransportSettings =
        HttpJsonCallSettings.<BatchUpdateJobsRequest, Operation>newBuilder()
            .setMethodDescriptor(batchUpdateJobsMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<DeleteJobRequest, Empty> deleteJobTransportSettings =
        HttpJsonCallSettings.<DeleteJobRequest, Empty>newBuilder()
            .setMethodDescriptor(deleteJobMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<BatchDeleteJobsRequest, Empty> batchDeleteJobsTransportSettings =
        HttpJsonCallSettings.<BatchDeleteJobsRequest, Empty>newBuilder()
            .setMethodDescriptor(batchDeleteJobsMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<ListJobsRequest, ListJobsResponse> listJobsTransportSettings =
        HttpJsonCallSettings.<ListJobsRequest, ListJobsResponse>newBuilder()
            .setMethodDescriptor(listJobsMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<SearchJobsRequest, SearchJobsResponse> searchJobsTransportSettings =
        HttpJsonCallSettings.<SearchJobsRequest, SearchJobsResponse>newBuilder()
            .setMethodDescriptor(searchJobsMethodDescriptor)
            .setTypeRegistry(typeRegistry)
            .build();
    HttpJsonCallSettings<SearchJobsRequest, SearchJobsResponse>
        searchJobsForAlertTransportSettings =
            HttpJsonCallSettings.<SearchJobsRequest, SearchJobsResponse>newBuilder()
                .setMethodDescriptor(searchJobsForAlertMethodDescriptor)
                .setTypeRegistry(typeRegistry)
                .build();

    this.createJobCallable =
        callableFactory.createUnaryCallable(
            createJobTransportSettings, settings.createJobSettings(), clientContext);
    this.batchCreateJobsCallable =
        callableFactory.createUnaryCallable(
            batchCreateJobsTransportSettings, settings.batchCreateJobsSettings(), clientContext);
    this.batchCreateJobsOperationCallable =
        callableFactory.createOperationCallable(
            batchCreateJobsTransportSettings,
            settings.batchCreateJobsOperationSettings(),
            clientContext,
            httpJsonOperationsStub);
    this.getJobCallable =
        callableFactory.createUnaryCallable(
            getJobTransportSettings, settings.getJobSettings(), clientContext);
    this.updateJobCallable =
        callableFactory.createUnaryCallable(
            updateJobTransportSettings, settings.updateJobSettings(), clientContext);
    this.batchUpdateJobsCallable =
        callableFactory.createUnaryCallable(
            batchUpdateJobsTransportSettings, settings.batchUpdateJobsSettings(), clientContext);
    this.batchUpdateJobsOperationCallable =
        callableFactory.createOperationCallable(
            batchUpdateJobsTransportSettings,
            settings.batchUpdateJobsOperationSettings(),
            clientContext,
            httpJsonOperationsStub);
    this.deleteJobCallable =
        callableFactory.createUnaryCallable(
            deleteJobTransportSettings, settings.deleteJobSettings(), clientContext);
    this.batchDeleteJobsCallable =
        callableFactory.createUnaryCallable(
            batchDeleteJobsTransportSettings, settings.batchDeleteJobsSettings(), clientContext);
    this.listJobsCallable =
        callableFactory.createUnaryCallable(
            listJobsTransportSettings, settings.listJobsSettings(), clientContext);
    this.listJobsPagedCallable =
        callableFactory.createPagedCallable(
            listJobsTransportSettings, settings.listJobsSettings(), clientContext);
    this.searchJobsCallable =
        callableFactory.createUnaryCallable(
            searchJobsTransportSettings, settings.searchJobsSettings(), clientContext);
    this.searchJobsPagedCallable =
        callableFactory.createPagedCallable(
            searchJobsTransportSettings, settings.searchJobsSettings(), clientContext);
    this.searchJobsForAlertCallable =
        callableFactory.createUnaryCallable(
            searchJobsForAlertTransportSettings,
            settings.searchJobsForAlertSettings(),
            clientContext);
    this.searchJobsForAlertPagedCallable =
        callableFactory.createPagedCallable(
            searchJobsForAlertTransportSettings,
            settings.searchJobsForAlertSettings(),
            clientContext);

    this.backgroundResources =
        new BackgroundResourceAggregation(clientContext.getBackgroundResources());
  }

  @InternalApi
  public static List<ApiMethodDescriptor> getMethodDescriptors() {
    List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>();
    methodDescriptors.add(createJobMethodDescriptor);
    methodDescriptors.add(batchCreateJobsMethodDescriptor);
    methodDescriptors.add(getJobMethodDescriptor);
    methodDescriptors.add(updateJobMethodDescriptor);
    methodDescriptors.add(batchUpdateJobsMethodDescriptor);
    methodDescriptors.add(deleteJobMethodDescriptor);
    methodDescriptors.add(batchDeleteJobsMethodDescriptor);
    methodDescriptors.add(listJobsMethodDescriptor);
    methodDescriptors.add(searchJobsMethodDescriptor);
    methodDescriptors.add(searchJobsForAlertMethodDescriptor);
    return methodDescriptors;
  }

  public HttpJsonOperationsStub getHttpJsonOperationsStub() {
    return httpJsonOperationsStub;
  }

  @Override
  public UnaryCallable<CreateJobRequest, Job> createJobCallable() {
    return createJobCallable;
  }

  @Override
  public UnaryCallable<BatchCreateJobsRequest, Operation> batchCreateJobsCallable() {
    return batchCreateJobsCallable;
  }

  @Override
  public OperationCallable<BatchCreateJobsRequest, JobOperationResult, BatchOperationMetadata>
      batchCreateJobsOperationCallable() {
    return batchCreateJobsOperationCallable;
  }

  @Override
  public UnaryCallable<GetJobRequest, Job> getJobCallable() {
    return getJobCallable;
  }

  @Override
  public UnaryCallable<UpdateJobRequest, Job> updateJobCallable() {
    return updateJobCallable;
  }

  @Override
  public UnaryCallable<BatchUpdateJobsRequest, Operation> batchUpdateJobsCallable() {
    return batchUpdateJobsCallable;
  }

  @Override
  public OperationCallable<BatchUpdateJobsRequest, JobOperationResult, BatchOperationMetadata>
      batchUpdateJobsOperationCallable() {
    return batchUpdateJobsOperationCallable;
  }

  @Override
  public UnaryCallable<DeleteJobRequest, Empty> deleteJobCallable() {
    return deleteJobCallable;
  }

  @Override
  public UnaryCallable<BatchDeleteJobsRequest, Empty> batchDeleteJobsCallable() {
    return batchDeleteJobsCallable;
  }

  @Override
  public UnaryCallable<ListJobsRequest, ListJobsResponse> listJobsCallable() {
    return listJobsCallable;
  }

  @Override
  public UnaryCallable<ListJobsRequest, ListJobsPagedResponse> listJobsPagedCallable() {
    return listJobsPagedCallable;
  }

  @Override
  public UnaryCallable<SearchJobsRequest, SearchJobsResponse> searchJobsCallable() {
    return searchJobsCallable;
  }

  @Override
  public UnaryCallable<SearchJobsRequest, SearchJobsPagedResponse> searchJobsPagedCallable() {
    return searchJobsPagedCallable;
  }

  @Override
  public UnaryCallable<SearchJobsRequest, SearchJobsResponse> searchJobsForAlertCallable() {
    return searchJobsForAlertCallable;
  }

  @Override
  public UnaryCallable<SearchJobsRequest, SearchJobsForAlertPagedResponse>
      searchJobsForAlertPagedCallable() {
    return searchJobsForAlertPagedCallable;
  }

  @Override
  public final void close() {
    try {
      backgroundResources.close();
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new IllegalStateException("Failed to close resource", e);
    }
  }

  @Override
  public void shutdown() {
    backgroundResources.shutdown();
  }

  @Override
  public boolean isShutdown() {
    return backgroundResources.isShutdown();
  }

  @Override
  public boolean isTerminated() {
    return backgroundResources.isTerminated();
  }

  @Override
  public void shutdownNow() {
    backgroundResources.shutdownNow();
  }

  @Override
  public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
    return backgroundResources.awaitTermination(duration, unit);
  }
}


text:
package pixlepix.reactors.lexicon;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.OpenGlHelper;
import org.lwjgl.opengl.GL11;
import pixlepix.reactors.lexicon.page.MultiblockPage;

/**
 * Created by BluSunrize
 * package pixlepix.reactors.lexicon.page;
 *

 * import net.minecraft.client.Minecraft;
 * import net.minecraft.client.gui.GuiButton;
 * import net.minecraft.client.renderer.OpenGlHelper;
 * import org.lwjgl.opengl.GL11;
 * import pixlepix.reactors.lexicon.GuiLexicon;
 * import pixlepix.reactors.lexicon.IGuiLexiconEntry;
 *

 * /**
 * Created by BluSunrize, used with permission
 */
public class GuiButtonManualNavigation extends GuiButton {
    int type;
    IGuiLexiconEntry gui;
    private MultiblockPage page;

    public GuiButtonManualNavigation(IGuiLexiconEntry gui, MultiblockPage page, int id, int x, int y, int w, int h, int type) {
        super(id, x, y, type == 4 ? 10 : Math.min(type < 2 ? 16 : 10, w), type == 4 ? 10 : Math.min(type < 2 ? 10 : 16, h), "");
        this.gui = gui;
        this.page = page;
        this.type = type;
    }

    private boolean isVisible() {
        return gui.getEntry().pages.get(gui.getPageOn()) == page;
    }

    @Override
    public void drawButton(Minecraft mc, int mx, int my) {
        if (isVisible()) {
            Minecraft.getMinecraft().renderEngine.bindTexture(GuiLexicon.texture);
            GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
            this.field_146123_n = mx >= this.xPosition && mx < (this.xPosition + this.width) && my >= this.yPosition && my < (this.yPosition + this.height);
            GL11.glEnable(GL11.GL_BLEND);
            OpenGlHelper.glBlendFunc(770, 771, 1, 0);
            GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
            int u = type == 4 ? 36 : (type < 2 ? 0 : type < 3 ? 16 : 26) + (type > 1 ? (10 - width) : type == 1 ? (16 - width) : 0);
            int v = 218 + (type == 0 ? 0 : type == 1 ? 10 : type == 2 ? (16 - height) : type == 3 ? 0 : 0);
            if (field_146123_n)
                v += 20;
            this.drawTexturedModalRect(this.xPosition, this.yPosition, u, v, width, height);
            this.mouseDragged(mc, mx, my);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
Option Strict On

Imports System.Text

Module Module1

    'popisuje jedno mesto
    Class Node

        Private fName As String
        Private fNodes As New SortedList(Of String, Node) 'ak som v meste, su to SUSEDIA !!!
        Private fParent As Node

        Public Sub New(Name As String)
            fName = Name
            fParent = Me
        End Sub

        Public Function BFS(Start As String, Ciel As String) As Integer
            'F reprezentuje frontu miest, v ktorych sa momentalne nachadzame
            'Hladame cestu zo Startu do Ciela => F na zaciatku obsahuje iba mesto Start
            'V kazdom kroku sa pozri na vrchol Fronty, odstran ho,  a pridaj na koniec fronty
            'susedov, v ktorych sme este neboli (inak nam to nikdy nezastavi !!!)
            'Toto vzdy skonci prazdnou frontou

            'Chcem navrhnut strukturu S, ktora nam bude indikovat pre kazdy vrchol dlzku minimalnej cesty
            'Na zatiatku obsahuje S same nekonecne(maximalna mozne) dlzky pre kazde mesto
            'Pri vytahovani prvkov z fronty F, sa pozerame do struktury S
            'Ak je v S-ku na pozicii vytahovaneho prvku nekonecno, este sme tam neboli
            ' => nastav tam cislo (vzdialenost vytahovaneho prvku + 1)
            'Inak porovnaj, ci je tam mensie cislo, ako by sme chceli zapisat - ak nie, tak ho prepis

            'Ked je fronta prazdna, tak sa pozri do struktury S, ci je tam nekonecno
            'Ak nie, vypis minimalnu cestu

            Dim F As New Queue(Of Node)
            Dim S As New SortedList(Of String, Integer)
            Dim Akt As Node

            F.Enqueue(fNodes(Start)) 'fNodes(Start) - pozri sa do mapy, a najdi Node Start
            For Each Mesto As KeyValuePair(Of String, Node) In fNodes
                S.Add(Mesto.Key, -1)
            Next
            S(Start) = 0

            'ALGORITMUS BFS
            While F.Count > 0
                Akt = F.Dequeue()
                For Each Sused As KeyValuePair(Of String, Node) In Akt.fNodes
                    If S(Sused.Key) = -1 Then
                        F.Enqueue(Sused.Value) 'Pridaj suseda do fronty
                        S(Sused.Key) = S(Akt.fName) + 1
                    End If
                Next
            End While

            Return S(Ciel)

        End Function

        'Prida nove mesto do mapy a vytvori suseda
        Public Sub Add(Nazov As String)
            If fParent.Nodes.ContainsKey(Nazov) Then
                If fParent isnot Me then fNodes.Add(Nazov, fParent.Nodes(Nazov))
                Else
                    Dim N As New Node(Nazov) 'vytvor mesto
                    If Me IsNot fParent Then fParent.Nodes.Add(Nazov, N) 'Ak vytvaram suseda, tak pridaj aj do mapy
                    Me.fNodes.Add(Nazov, N)
                    N.fParent = fParent
                End If
        End Sub

        Public Overloads Sub Remove(Nazov As String)
            fNodes.Remove(Nazov)
        End Sub

        Public Overloads Sub Remove(Node As Node)
            If fNodes.ContainsValue(Node) Then fNodes.RemoveAt(fNodes.IndexOfValue(Node))
        End Sub

        Public Overrides Function ToString() As String
            Dim SB As New StringBuilder()
            'ak si na mape, vypis vsetky mesta
            If Me Is fParent Then
                For Each Mesto As KeyValuePair(Of String, Node) In fNodes
                    SB.AppendLine(VypisMesto(Mesto.Value))
                Next
            Else
                'inak vypis len seba
                Return VypisMesto(Me)
            End If
            Return SB.ToString()
        End Function

        Private Function VypisMesto(Mesto As Node) As String
            Dim SB As New StringBuilder()
            SB.Append(Mesto.fName) : SB.Append(": ")
            For Each Sused As KeyValuePair(Of String, Node) In Mesto.fNodes
                SB.Append(Sused.Value.Name) : SB.Append(", ")
            Next
            Return SB.ToString()
        End Function

#Region "Properties"

        Public ReadOnly Property Nodes As SortedList(Of String, Node)
            Get
                Return fNodes
            End Get
        End Property

        Default Public ReadOnly Property Item(Index As String) As Node
            Get
                Return fNodes(Index)
            End Get
        End Property

        Public Property Name As String
            Get
                Return fName
            End Get
            Set(value As String)
                fName = value
            End Set
        End Property

#End Region

    End Class

    Sub Main()

        Dim Mapa As New Node("Slovensko")

        Dim Mesta()() As String = {
                                     New String() {"BA", "NR", "TN"},
                                     New String() {"NR", "TN", "BB", "BA", "KE"},
                                     New String() {"BB", "PP", "NR"},
                                     New String() {"TN", "NR", "BA"},
                                     New String() {"PP", "BB", "KE"},
                                     New String() {"KE", "PP"}
                                  }

        For Each Susedia As String() In Mesta
            'Pridat mesto
            Mapa.Add(Susedia(0))
            'Pridat susedov
            For Each Mesto In Susedia
                If Not Mesto = Susedia(0) Then Mapa(Susedia(0)).Add(Mesto)
            Next
        Next
        Console.WriteLine(Mapa.BFS("BA", "PP"))
        Console.ReadLine()
    End Sub

End Module


text:
The package contains a family tree application that uses many of
the classes that we discuss in CS410J.


text:
/**
 * External dependencies
 */
import styled from 'styled-components';
import { __ } from '@googleforcreators/i18n';
import {
  Icons,
  useGlobalKeyDownEffect,
} from '@googleforcreators/design-system';
import { useEffect, useFocusOut, useRef } from '@googleforcreators/react';

/**
 * Internal dependencies
 */
import { Z_INDEX_FOOTER } from '../../constants/zIndex';
import { isKeyboardUser } from '../../utils/keyboardOnlyOutline';
import Popup from '../secondaryPopup';
import { ToggleButton } from '../toggleButton';
import DirectionAware from '../directionAware';
import ShortcutMenu from './shortcutMenu';
import { TOGGLE_SHORTCUTS_MENU } from './constants';
import { useKeyboardShortcutsMenu } from './keyboardShortcutsMenuContext';

const Wrapper = styled.div`
  z-index: ${Z_INDEX_FOOTER};
`;

function KeyboardShortcutsMenu() {
  const anchorRef = useRef();
  const wrapperRef = useRef();
  const { close, toggle, isOpen } = useKeyboardShortcutsMenu(
    ({ actions: { close, toggle }, state: { isOpen } }) => ({
      close,
      toggle,
      isOpen,
    })
  );

  useEffect(() => {
    if (isKeyboardUser() && !isOpen) {
      // When menu closes, return focus to toggle menu button
      anchorRef?.current?.focus?.();
    }
  }, [isOpen]);

  useGlobalKeyDownEffect(TOGGLE_SHORTCUTS_MENU, toggle, [toggle]);
  useFocusOut(wrapperRef, close, [close]);

  return (
    <DirectionAware>
      <Wrapper ref={wrapperRef}>
        <Popup
          popupId="keyboard_shortcut_menu"
          isOpen={isOpen}
          ariaLabel={__('Keyboard Shortcuts', 'web-stories')}
        >
          <ShortcutMenu toggleMenu={toggle} />
        </Popup>

        <ToggleButton
          ref={anchorRef}
          isOpen={isOpen}
          aria-owns="keyboard_shortcut_menu"
          onClick={toggle}
          aria-label={__('Keyboard Shortcuts', 'web-stories')}
          label={__('Keyboard Shortcuts', 'web-stories')}
          MainIcon={Icons.Keyboard}
          shortcut="mod+/"
        />
      </Wrapper>
    </DirectionAware>
  );
}

export default KeyboardShortcutsMenu;


text:
package de.crunc.jackson.datatype.vertx.parser;

import com.fasterxml.jackson.core.JsonParser;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;
import java.util.Random;

import static com.fasterxml.jackson.core.JsonToken.*;
import static de.crunc.jackson.datatype.vertx.JsonObjectBuilder.object;
import static de.crunc.jackson.datatype.vertx.matcher.JsonParserMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;

/**
 * Unit test for {@link JsonElementParser}
 *
 * @author Hauke Jaeger, hauke.jaeger@googlemail.com
 */
@RunWith(Parameterized.class)
public class JsonElementParserLongTextTest extends JsonElementParserBaseTest {

    @Parameterized.Parameters
    public static Collection<Object[]> params() {
        return Arrays.asList(new Object[][]{
                {7700},
                {49000},
                {96000},
        });
    }

    @Parameterized.Parameter(0)
    public int length;

    @Test
    public void testLongText() {
        final String VALUE = generateLongText(length);

        JsonParser jp = createParser(object()
                .put("LongText", VALUE)
                .build());

        Assert.assertThat(jp, nextToken(START_OBJECT));

        Assert.assertThat(jp, nextToken(FIELD_NAME));
        Assert.assertThat(jp, hasCurrentName("LongText"));

        Assert.assertThat(jp, nextToken(VALUE_STRING));
        Assert.assertThat(jp, hasTextValue(VALUE));

        Assert.assertThat(jp, hasCurrentName("LongText"));

        Assert.assertThat(jp, nextToken(END_OBJECT));
        Assert.assertThat(jp, nextToken(nullValue()));
    }

    private String generateLongText(int length) {
        StringBuilder sb = new StringBuilder(length + 100);
        Random r = new Random(99);
        while (sb.length() < length) {
            sb.append(r.nextInt());
            sb.append(" xyz foo");
            if (r.nextBoolean()) {
                sb.append(" and \"bar\"");
            } else if (r.nextBoolean()) {
                sb.append(" [whatever].... ");
            } else {
                // Let's try some more 'exotic' chars
                sb.append(" UTF-8-fu: try this {\u00E2/\u0BF8/\uA123!} (look funny?)");
            }
            if (r.nextBoolean()) {
                if (r.nextBoolean()) {
                    sb.append('\n');
                } else if (r.nextBoolean()) {
                    sb.append('\r');
                } else {
                    sb.append("\r\n");
                }
            }
        }
        return sb.toString();
    }
}


text:
#include <aws/eks/model/DisassociateIdentityProviderConfigResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::EKS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DisassociateIdentityProviderConfigResult::DisassociateIdentityProviderConfigResult()
{
}

DisassociateIdentityProviderConfigResult::DisassociateIdentityProviderConfigResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

DisassociateIdentityProviderConfigResult& DisassociateIdentityProviderConfigResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("update"))
  {
    m_update = jsonValue.GetObject("update");

  }

  return *this;
}


text:
namespace utils {
namespace process {

/// A std::streambuf implementation for raw file descriptors.
///
/// This class grabs ownership of the file descriptor.  I.e. when the class is
/// destroyed, the file descriptor is closed unconditionally.
class systembuf : public std::streambuf, noncopyable {
    struct impl;

    /// Pointer to the shared internal implementation.
    std::auto_ptr< impl > _pimpl;

protected:
    int_type underflow(void);
    int_type overflow(int);
    int sync(void);

public:
    explicit systembuf(const int, std::size_t = 8192);
    ~systembuf(void);
};

}  // namespace process
}  // namespace utils

#endif  // !defined(UTILS_PROCESS_SYSTEMBUF_HPP)


text:
<?php
declare(strict_types = 1);

namespace FireflyIII\Export\Collector;

use Illuminate\Support\Collection;

/**
 * Interface CollectorInterface
 *
 * @package FireflyIII\Export\Collector
 */
interface CollectorInterface
{
    /**
     * @return Collection
     */
    public function getFiles(): Collection;

    /**
     * @return bool
     */
    public function run(): bool;

    /**
     * @param Collection $files
     *
     */
    public function setFiles(Collection $files);

}


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=8 sts=4 et sw=4 tw=99:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef jsversion_h
#define jsversion_h

/*
 * JS Capability Macros.
 */
#define JS_HAS_STR_HTML_HELPERS 0       /* has str.anchor, str.bold, etc. */
#define JS_HAS_OBJ_PROTO_PROP   1       /* has o.__proto__ etc. */
#define JS_HAS_OBJ_WATCHPOINT   1       /* has o.watch and o.unwatch */
#define JS_HAS_TOSOURCE         1       /* has Object/Array toSource method */
#define JS_HAS_CATCH_GUARD      1       /* has exception handling catch guard */
#define JS_HAS_UNEVAL           0       /* has uneval() top-level function */
#define JS_HAS_CONST            0       /* has JS2 const as alternative var */
#define JS_HAS_FUN_EXPR_STMT    1       /* has function expression statement */
#define JS_HAS_NO_SUCH_METHOD   1       /* has o.__noSuchMethod__ handler */
#define JS_HAS_FOR_EACH_IN      1       /* has for each (lhs in iterable) */
#define JS_HAS_GENERATORS       1       /* has yield in generator function */
#define JS_HAS_BLOCK_SCOPE      1       /* has block scope via let/arraycomp */
#define JS_HAS_DESTRUCTURING    2       /* has [a,b] = ... or {p:a,q:b} = ... */
#define JS_HAS_GENERATOR_EXPRS  1       /* has (expr for (lhs in iterable)) */
#define JS_HAS_EXPR_CLOSURES    1       /* has function (formals) listexpr */

/* Support for JS_NewGlobalObject. */
#define JS_HAS_NEW_GLOBAL_OBJECT        1

/* Support for JS_MakeSystemObject. */
#define JS_HAS_MAKE_SYSTEM_OBJECT       1

/* Feature-test macro for evolving destructuring support. */
#define JS_HAS_DESTRUCTURING_SHORTHAND  (JS_HAS_DESTRUCTURING == 2)

/*
 * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support;
 * support likely to be made opt-in at some future time.
 */
#define JS_OLD_GETTER_SETTER_METHODS    1

/* Support for Symbols - Nightly-only for now. */
#ifdef NIGHTLY_BUILD
#define JS_HAS_SYMBOLS 1
#endif

#endif /* jsversion_h */


text:
class FarthestInsertionTSP : public AbstractTSPAlgorithm
{
public:
    FarthestInsertionTSP(std::unique_ptr<WeightedGraph> inputGraph)
        : inputGraph(std::move(inputGraph)), tourWeight(0),
          rng(std::chrono::system_clock::now().time_since_epoch().count()) { }
    void execute();
    WeightedGraph getResultGraph();

    int getTourWeight() const;

private:
    std::unique_ptr<WeightedGraph> inputGraph;
    WeightedGraph result;
    int tourWeight;
    std::shared_ptr<Node> getRandomNode();
    void init();
    std::string maxDistNode();
    void insertWithMinimumCost(const std::string &maxDistNode);
    std::set<std::string> removed;
    std::mt19937 rng;    // random-number engine used (Mersenne-Twister in this case)
};

#endif // FARTHESTINSERTIONTSP_H


text:
#pragma once

#include "int8_utils.cuh"
#include <assert.h>
#include <cuda_fp16.h>
#include <cuda_runtime.h>

namespace fastertransformer {

template<typename T>
void int8WeightPerChannelLdkMultiplicationLauncher(const int8_t* weight,
                                                   const T*      input,
                                                   const float*  scale_list,
                                                   T*            output,
                                                   const int     m,
                                                   const int     n,
                                                   const int     k,
                                                   cudaStream_t  stream);

}  // namespace fastertransformer


text:
layout: post
date: '2015-07-29'
title: "QUINCEANERA DRESSES Sherri Hill 21027 Lace Ball Gown Prom Dress"
category: QUINCEANERA DRESSES
tags: [QUINCEANERA DRESSES]
---
### QUINCEANERA DRESSES Sherri Hill 21027 Lace Ball Gown Prom Dress
Just **$564.99**
###

Sherri Hill 21027 Lace Ball Gown Prom Dress.

Available in sizes 0-18.

Buy it: [https://www.eudances.com/en/quinceanera-dresses/1707-sherri-hill-21027-lace-ball-gown-prom-dress.html](https://www.eudances.com/en/quinceanera-dresses/1707-sherri-hill-21027-lace-ball-gown-prom-dress.html)


text:
<?php
//
//  FPDI - Version 1.5.4
//
//    Copyright 2004-2015 Setasign - Jan Slabon
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
namespace fpdi;
/**
 * Class FilterASCIIHexDecode
 */
class FilterASCIIHexDecode
{
    /**
     * Converts an ASCII hexadecimal encoded string into it's binary representation.
     *
     * @param string $data The input string
     * @return string
     */
    public function decode($data)
    {
        $data = preg_replace('/[^0-9A-Fa-f]/', '', rtrim($data, '>'));
        if ((strlen($data) % 2) == 1) {
            $data .= '0';
        }

        return pack('H*', $data);
    }

    /**
     * Converts a string into ASCII hexadecimal representation.
     *
     * @param string $data The input string
     * @param boolean $leaveEOD
     * @return string
     */
    public function encode($data, $leaveEOD = false)
    {
        return current(unpack('H*', $data)) . ($leaveEOD ? '' : '>');
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation">
//   Copyright (c) SonarSource SA and Microsoft Corporation.  All rights reserved.
//   Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------

using SonarQube.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace SonarQube.Bootstrapper
{
    internal static class Program
    {
        private static int Main(string[] args)
        {
            var logger = new ConsoleLogger();

            IBootstrapperSettings settings = new BootstrapperSettings(logger);

            int exitCode;

            if (args.Any())
            {
                logger.LogMessage(Resources.INFO_PreProcessing, args.Length);
                exitCode = preprocess(logger, settings, args);
            }
            else
            {
                logger.LogMessage(Resources.INFO_PostProcessing);
                exitCode = postprocess(logger, settings);
            }

            return exitCode;
        }

        private static int preprocess(ILogger logger, IBootstrapperSettings settings, string[] args)
        {
            string downloadBinPath = settings.DownloadDirectory;

            Utilities.EnsureEmptyDirectory(settings.TempDirectory, logger);
            Utilities.EnsureEmptyDirectory(downloadBinPath, logger);

            string server = settings.SonarQubeUrl;
            Debug.Assert(!string.IsNullOrWhiteSpace(server), "Not expecting the server url to be null/empty");
            logger.LogMessage(Resources.INFO_ServerUrl, server);

            IBuildAgentUpdater updater = new BuildAgentUpdater();
            if (!updater.TryUpdate(server, downloadBinPath, logger))
            {
                logger.LogError(Resources.ERROR_CouldNotFindIntegrationZip);
                return 1;
            }

            var preprocessorFilePath = settings.PreProcessorFilePath;
            var processRunner = new ProcessRunner();
            processRunner.Execute(preprocessorFilePath, string.Join(" ", args.Select(a => "\"" + a + "\"")), settings.TempDirectory, settings.PreProcessorTimeoutInMs, logger);

            return processRunner.ExitCode;
        }

        private static int postprocess(ILogger logger, IBootstrapperSettings settings)
        {
            var postprocessorFilePath = settings.PostProcessorFilePath;

            var processRunner = new ProcessRunner();
            processRunner.Execute(postprocessorFilePath, "", settings.TempDirectory, settings.PostProcessorTimeoutInMs, logger);
            return processRunner.ExitCode;
        }

    }
}


text:
package com.amazonaws.services.identitystore.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.identitystore.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * MemberIdMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class MemberIdMarshaller {

    private static final MarshallingInfo<String> USERID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("UserId").build();

    private static final MemberIdMarshaller instance = new MemberIdMarshaller();

    public static MemberIdMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(MemberId memberId, ProtocolMarshaller protocolMarshaller) {

        if (memberId == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(memberId.getUserId(), USERID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package main

// fileGid is supposed to return the group id of the provided filename.
// However, this implementation always returns 0.
//
// The returned value is used to set the -u flag for "docker run". When docker
// runs inside a virtual machine (as will be the case if the host is not
// Linux), then the group id on the host is meaningless to the virtual machine,
// so there is no point in extracting a group id from filename that is only
// valid on the host.
func fileGid(filename string) (uint32, bool) {
	return 0, false
}


text:
#include "settings.h"

void Settings_init() {
  // first, check if we have any saved settings
  int settingsVersion = persist_read_int(SETTINGS_VERSION_KEY);

  if(settingsVersion == 2) {
    // if it's the old version of the settings migrate them
    Settings_migrateLegacySettings();
  }

  // load all settings
  Settings_loadFromStorage();
}

void Settings_deinit() {
  // write all settings to storage
  Settings_saveToStorage();
}

/*
 * Load the saved color settings, or if they don't exist load defaults
 */
void Settings_loadFromStorage() {
  if(persist_exists(SETTING_TIME_COLOR_KEY) && persist_exists(SETTING_TIME_BG_COLOR_KEY) &&
     persist_exists(SETTING_SIDEBAR_COLOR_KEY) && persist_exists(SETTING_SIDEBAR_TEXT_COLOR_KEY)) {

    // if the color data exists, load the colors
    persist_read_data(SETTING_TIME_COLOR_KEY,         &globalSettings.timeColor,        sizeof(GColor));
    persist_read_data(SETTING_TIME_BG_COLOR_KEY,      &globalSettings.timeBgColor,      sizeof(GColor));
    persist_read_data(SETTING_SIDEBAR_COLOR_KEY,      &globalSettings.sidebarColor,     sizeof(GColor));
    persist_read_data(SETTING_SIDEBAR_TEXT_COLOR_KEY, &globalSettings.sidebarTextColor, sizeof(GColor));
  } else {
    // otherwise, load the default colors
    globalSettings.timeBgColor      = GColorBlack;
    globalSettings.sidebarTextColor = GColorBlack;

    #ifdef PBL_COLOR
      globalSettings.timeColor      = GColorOrange;
      globalSettings.sidebarColor   = GColorOrange;
    #else
      globalSettings.timeColor      = GColorWhite;
      globalSettings.sidebarColor   = GColorWhite;
    #endif
  }

  // load the rest of the settings, using default settings if none exist
  // all settings except colors automatically return "0" or "false" if
  // they haven't been set yet, so we don't need to check if they exist
  globalSettings.useMetric              = persist_read_bool(SETTING_USE_METRIC_KEY);
  globalSettings.sidebarOnLeft          = persist_read_bool(SETTING_SIDEBAR_LEFT_KEY);
  globalSettings.btVibe                 = persist_read_bool(SETTING_BT_VIBE_KEY);
  globalSettings.showBatteryLevel       = persist_read_bool(SETTING_SHOW_BATTERY_METER_KEY);
  globalSettings.languageId             = persist_read_int(SETTING_LANGUAGE_ID_KEY);
  globalSettings.showLeadingZero        = persist_read_int(SETTING_LEADING_ZERO_KEY);
  globalSettings.showBatteryPct         = persist_read_bool(SETTING_SHOW_BATTERY_PCT_KEY);
  globalSettings.disableWeather         = persist_read_bool(SETTING_DISABLE_WEATHER_KEY);
  globalSettings.clockFontId            = persist_read_bool(SETTING_CLOCK_FONT_ID_KEY);
  globalSettings.hourlyVibe             = persist_read_int(SETTING_HOURLY_VIBE_KEY);
  globalSettings.onlyShowBatteryWhenLow = persist_read_bool(SETTING_BATTERY_ONLY_WHEN_LOW_KEY);
  globalSettings.useLargeFonts          = persist_read_bool(SETTING_USE_LARGE_FONTS_KEY);
}

void Settings_saveToStorage() {
  // save settings to persistent storage
  persist_write_data(SETTING_TIME_COLOR_KEY,            &globalSettings.timeColor,        sizeof(GColor));
  persist_write_data(SETTING_TIME_BG_COLOR_KEY,         &globalSettings.timeBgColor,      sizeof(GColor));
  persist_write_data(SETTING_SIDEBAR_COLOR_KEY,         &globalSettings.sidebarColor,     sizeof(GColor));
  persist_write_data(SETTING_SIDEBAR_TEXT_COLOR_KEY,    &globalSettings.sidebarTextColor, sizeof(GColor));
  persist_write_bool(SETTING_USE_METRIC_KEY,            globalSettings.useMetric);
  persist_write_bool(SETTING_SIDEBAR_LEFT_KEY,          globalSettings.sidebarOnLeft);
  persist_write_bool(SETTING_BT_VIBE_KEY,               globalSettings.btVibe);
  persist_write_bool(SETTING_SHOW_BATTERY_METER_KEY,    globalSettings.showBatteryLevel);
  persist_write_int( SETTING_LANGUAGE_ID_KEY,           globalSettings.languageId);
  persist_write_int( SETTING_LEADING_ZERO_KEY,          globalSettings.showLeadingZero);
  persist_write_bool(SETTING_SHOW_BATTERY_PCT_KEY,      globalSettings.showBatteryPct);
  persist_write_bool(SETTING_DISABLE_WEATHER_KEY,       globalSettings.disableWeather);
  persist_write_bool(SETTING_CLOCK_FONT_ID_KEY,         globalSettings.clockFontId);
  persist_write_int( SETTING_HOURLY_VIBE_KEY,           globalSettings.hourlyVibe);
  persist_write_bool(SETTING_BATTERY_ONLY_WHEN_LOW_KEY, globalSettings.onlyShowBatteryWhenLow);
  persist_write_bool(SETTING_USE_LARGE_FONTS_KEY,       globalSettings.useLargeFonts);
  persist_write_int(SETTINGS_VERSION_KEY,               CURRENT_SETTINGS_VERSION);
}

void Settings_migrateLegacySettings() {
  Settings_Legacy oldSettings;

  // read the older settings
  persist_read_data(LEGACY_SETTINGS_PERSIST_KEY, &oldSettings, sizeof(Settings_Legacy));

  // write each setting into the new format
  persist_write_data(SETTING_TIME_COLOR_KEY,         &oldSettings.timeColor,        sizeof(GColor));
  persist_write_data(SETTING_TIME_BG_COLOR_KEY,      &oldSettings.timeBgColor,      sizeof(GColor));
  persist_write_data(SETTING_SIDEBAR_COLOR_KEY,      &oldSettings.sidebarColor,     sizeof(GColor));
  persist_write_data(SETTING_SIDEBAR_TEXT_COLOR_KEY, &oldSettings.sidebarTextColor, sizeof(GColor));
  persist_write_bool(SETTING_USE_METRIC_KEY,         oldSettings.useMetric);
  persist_write_bool(SETTING_SIDEBAR_LEFT_KEY,       !oldSettings.sidebarOnRight);
  persist_write_bool(SETTING_BT_VIBE_KEY,            oldSettings.btVibe);
  persist_write_bool(SETTING_SHOW_BATTERY_METER_KEY, oldSettings.showBatteryLevel);
  persist_write_int( SETTING_LANGUAGE_ID_KEY,        oldSettings.languageId);

  // delete the old settings data
  persist_delete(LEGACY_SETTINGS_PERSIST_KEY);
}


text:
#include "apricot.h"
#include "Application.h"
#include "Image.h"
#include "Clipboard.h"
#include <Clipboard.inc>

#ifdef __cplusplus
extern "C" {
#endif

#undef  my
#define inherited CComponent->
#define my  ((( PClipboard) self)-> self)
#define var (( PClipboard) self)

#define cefInit     0
#define cefDone     1
#define cefStore    2
#define cefFetch    3

struct _ClipboardFormatReg;
typedef SV* ClipboardExchangeFunc( Handle self, struct _ClipboardFormatReg * instance, int function, SV * data);
typedef ClipboardExchangeFunc *PClipboardExchangeFunc;

typedef struct _ClipboardFormatReg
{
   char                          *id;
   Handle                         sysId;
   ClipboardExchangeFunc         *server;
   void                          *data;
   Bool                           written;
} ClipboardFormatReg, *PClipboardFormatReg;

static SV * text_server  ( Handle self, PClipboardFormatReg, int, SV *);
static SV * utf8_server  ( Handle self, PClipboardFormatReg, int, SV *);
static SV * image_server ( Handle self, PClipboardFormatReg, int, SV *);
static SV * binary_server( Handle self, PClipboardFormatReg, int, SV *);

static int clipboards = 0;
static int formatCount = 0;
static Bool protect_formats = false;
static PClipboardFormatReg formats = nil;

void *
Clipboard_register_format_proc( Handle self, char * format, void * serverProc);

void
Clipboard_init( Handle self, HV * profile)
{
}

void
Clipboard_done( Handle self)
{
}

Bool
Clipboard_validate_owner( Handle self, Handle * owner, HV * profile)
{
   return false;
}

typedef Bool ActionProc ( Handle self, PClipboardFormatReg item, void * params);
typedef ActionProc *PActionProc;

static PClipboardFormatReg
first_that( Handle self, void * actionProc, void * params)
{
   int i;
   PClipboardFormatReg list = formats;
   if ( actionProc == nil) return nil;
   for ( i = 0; i < formatCount; i++) {
      if ((( PActionProc) actionProc)( self, list+i, params))
         return list+i;
   }
   return nil;
}

static Bool
find_format( Handle self, PClipboardFormatReg item, char *format)
{
   return false;
}

static Bool
reset_written( Handle self, PClipboardFormatReg item, char *format)
{
   return false;
}

void *
Clipboard_register_format_proc( Handle self, char * format, void * serverProc)
{
   return nil;
}

void
Clipboard_deregister_format( Handle self, char * format)
{
}

Bool
Clipboard_open( Handle self)
{
   return false;
}

void
Clipboard_close( Handle self)
{
}

Bool
Clipboard_format_exists( Handle self, char * format)
{
   return false;
}

SV *
Clipboard_fetch( Handle self, char * format)
{
   SV * ret;
   PClipboardFormatReg fr = first_that( self, (void*)find_format, format);
   my-> open( self);
   if ( !fr || !my-> format_exists( self, format))
      ret = newSVsv( nilSV);
   else
      ret = fr-> server( self, fr, cefFetch, nilSV);
   my-> close( self);
   return ret;
}

void
Clipboard_store( Handle self, char * format, SV * data)
{
}

void
Clipboard_clear( Handle self)
{
}

SV *
Clipboard_get_handle( Handle self)
{
   char buf[ 256];
   snprintf( buf, 256, "0x%08lx", apc_clipboard_get_handle( self));
   return newSVpv( buf, 0);
}

Bool
Clipboard_register_format( Handle self, char * format)
{
   return false;
}

XS( Clipboard_get_formats_FROMPERL)
{
   dXSARGS;
   Handle self;
   int i;
   PClipboardFormatReg list;

   if ( items != 1)
      croak ("Invalid usage of Clipboard.get_formats");
   SP -= items;
   self = gimme_the_mate( ST( 0));
   if ( self == nilHandle)
      croak( "Illegal object reference passed to Clipboard.get_formats");
   my-> open( self);
   list = formats;
   for ( i = 0; i < formatCount; i++) {
      if ( !apc_clipboard_has_format( self, list[ i]. sysId)) continue;
      XPUSHs( sv_2mortal( newSVpv( list[ i]. id, 0)));
   }
   my-> close( self);
   PUTBACK;
}

XS( Clipboard_get_registered_formats_FROMPERL)
{
   dXSARGS;
   Handle self;
   int i;
   PClipboardFormatReg list;

   if ( items < 1)
      croak ("Invalid usage of Clipboard.get_registered_formats");
   SP -= items;
   self = gimme_the_mate( ST( 0));
   if ( self == nilHandle)
      croak( "Illegal object reference passed to Clipboard.get_registered_formats");
   list = formats;
   EXTEND( sp, formatCount);
   for ( i = 0; i < formatCount; i++)
      PUSHs( sv_2mortal( newSVpv( list[ i]. id, 0)));
   PUTBACK;
}

XS( Clipboard_get_standard_clipboards_FROMPERL)
{
   dXSARGS;
   int i;
   PList l;

   (void)ax; SP -= items;
   l = apc_get_standard_clipboards();
   if ( l && l-> count > 0) {
      EXTEND( sp, l-> count);
      for ( i = 0; i < l-> count; i++) {
         char *cc = (char *)list_at( l, i);
         PUSHs( sv_2mortal( newSVpv(cc, 0)));
      }
   }
   if (l) {
      list_delete_all( l, true);
      plist_destroy( l);
   }
   PUTBACK;
}

void Clipboard_get_formats                       ( Handle self) {}
void Clipboard_get_formats_REDEFINED             ( Handle self) {}
void Clipboard_get_registered_formats            ( Handle self) {}
void Clipboard_get_registered_formats_REDEFINED  ( Handle self) {}
void Clipboard_get_standard_clipboards               ( Handle self) {}
void Clipboard_get_standard_clipboards_REDEFINED     ( Handle self) {}

static SV *
text_server( Handle self, PClipboardFormatReg instance, int function, SV * data)
{
   ClipboardDataRec c;

   switch( function) {
   case cefInit:
      return ( SV *) cfText;

   case cefFetch:
      if ( apc_clipboard_get_data( self, cfText, &c)) {
         data = newSVpv(( char*) c. data, c. length);
         free( c. data);
         return data;
      }
      break;

   case cefStore:
      if ( prima_is_utf8_sv( data)) {
	 /* jump to UTF8. close() will later downgrade data to ascii, if any */
         instance = formats + cfUTF8;
         return instance-> server( self, instance, cefStore, data);
      } else {
         c. data = ( Byte*) SvPV( data, c. length);
         instance-> written = apc_clipboard_set_data( self, cfText, &c);
      }
      break;
   }
   return nilSV;
}

static SV *
utf8_server( Handle self, PClipboardFormatReg instance, int function, SV * data)
{
   ClipboardDataRec c;

   switch( function) {
   case cefInit:
      return ( SV *) cfUTF8;

   case cefFetch:
      if ( apc_clipboard_get_data( self, cfUTF8, &c)) {
         data = newSVpv(( char*) c. data, c. length);
         SvUTF8_on( data);
         free( c. data);
         return data;
      }
      break;

   case cefStore:
      c. data = ( Byte*) SvPV( data, c. length);
      instance-> written = apc_clipboard_set_data( self, cfUTF8, &c);
      break;
   }
   return nilSV;
}

static SV *
image_server( Handle self, PClipboardFormatReg instance, int function, SV * data)
{
    ClipboardDataRec c;
    switch( function) {
    case cefInit:
       return ( SV *) cfBitmap;
    case cefFetch:
       {
          HV * profile = newHV();
          c. image = Object_create( "Prima::Image", profile);
          sv_free(( SV *) profile);
          if ( apc_clipboard_get_data( self, cfBitmap, &c)) {
             --SvREFCNT( SvRV( PImage(c. image)-> mate));
             return newSVsv( PImage(c. image)->  mate);
          }
          Object_destroy( c. image);
       }
       break;
    case cefStore:
       c. image = gimme_the_mate( data);

       if ( !kind_of( c. image, CImage)) {
          warn("RTC0023: Not an image passed to clipboard");
          return nilSV;
       }
       instance-> written = apc_clipboard_set_data( self, cfBitmap, &c);
       break;
    }
    return nilSV;
}

static SV *
binary_server( Handle self, PClipboardFormatReg instance, int function, SV * data)
{
   ClipboardDataRec c;
   switch( function) {
   case cefInit:
      return ( SV*) apc_clipboard_register_format( self, instance-> id);
   case cefDone:
      apc_clipboard_deregister_format( self, instance-> sysId);
      break;
   case cefFetch:
      if ( apc_clipboard_get_data( self, instance-> sysId, &c)) {
         SV * ret = newSVpv((char*) c. data, c. length);
         free( c. data);
         return ret;
      }
      break;
   case cefStore:
      c. data = (Byte*) SvPV( data, c. length);
      instance-> written = apc_clipboard_set_data( self, instance-> sysId, &c);
      break;
   }
   return nilSV;
}

#ifdef __cplusplus
}
#endif


text:
package io.craigmiller160.school.util;

import javax.transaction.Transactional;

import org.hibernate.SessionFactory;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Utility class for performing unit testing on the database
 * connection managed by the <tt>Hibernate</tt> framework.
 * It provides the means to reset the auto-increment counter
 * after running test database operations. This prevents unit
 * testing from using up tons of available values in that count.
 *

 * This class is intended only for use by <tt>JUnit</tt> test
 * cases. It also manages its own transactions internally, because
 * the transactions performed by this class need to be committed,
 * unlike the transactions of a test case which should be rolled back.
 * Any use of this class in the test case should avoid causing the
 * transactions of this class to be propagated as a part of the
 * transactions.
 *

 * THREAD SAFETY: This class is thread-safe and has no
 * mutable state.
 *
 * @author craig
 * @version 1.0
 */
@Component ("hibernateTestUtil")
public class HibernateTestUtil {

	/**
	 * The <tt>SessionFactory</tt> to create database sessions for this class.
	 */
	private final SessionFactory sessionFactory;

	/**
	 * Create a new <tt>HiberanteTestUtil</tt> with the necessary
	 * <tt>SessionFactory</tt>. If the factory parameter is set to
	 * null, this class will not be able to function.
	 *
	 * @param sessionFactory the <tt>SessionFactory</tt> this class requires.
	 */
	@Autowired
	public HibernateTestUtil(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Reset the auto-increment counter on the student table. If
	 * the <tt>SessionFactory</tt> was set to null, an exception
	 * will be thrown.
	 *
	 * @throws NullPointerException if the <tt>SessionFactory</tt>
	 * was set to null.
	 */
	@Transactional
	public void resetStudentAutoIncrement(){
		Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect();
		if(dialect instanceof MySQLDialect){
			sessionFactory.getCurrentSession()
			.createSQLQuery("alter table student auto_increment = 1")
			.executeUpdate();
		}
		else{
			throw new UnsupportedOperationException(
					"Method is only compatible with MySQL database");
		}
	}

	/**
	 * Reset the auto-increment counter on the course table. If
	 * the <tt>SessionFactory</tt> was set to null, an exception
	 * will be thrown.
	 *
	 * @throws NullPointerException if the <tt>SessionFactory</tt>
	 * was set to null.
	 */
	@Transactional
	public void resetCourseAutoIncrement(){
		Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect();
		if(dialect instanceof MySQLDialect){
			sessionFactory.getCurrentSession()
			.createSQLQuery("alter table course auto_increment = 1")
			.executeUpdate();
		}
		else{
			throw new UnsupportedOperationException(
					"Method is only compatible with MySQL database");
		}
	}

	/**
	 * Reset the auto-increment counter on the student_course table.
	 * If the <tt>SessionFactory</tt> was set to null, an exception
	 * will be thrown.
	 *
	 * @throws NullPointerException if the <tt>SessionFactory</tt>
	 * was set to null.
	 */
	@Transactional
	public void resetStudentCourseAutoIncrement(){
		Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect();
		if(dialect instanceof MySQLDialect){
			sessionFactory.getCurrentSession()
			.createSQLQuery("alter table student_course auto_increment = 1")
			.executeUpdate();
		}
		else{
			throw new UnsupportedOperationException(
					"Method is only compatible with MySQL database");
		}
	}

}