text:
package com.google.cloud.monitoring.spi.v3;

import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListMetricDescriptorsPagedResponse;
import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse;
import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListTimeSeriesPagedResponse;

import com.google.api.MetricDescriptor;
import com.google.api.MonitoredResourceDescriptor;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.RetrySettings;
import com.google.api.gax.grpc.CallContext;
import com.google.api.gax.grpc.ChannelProvider;
import com.google.api.gax.grpc.ClientSettings;
import com.google.api.gax.grpc.ExecutorProvider;
import com.google.api.gax.grpc.InstantiatingChannelProvider;
import com.google.api.gax.grpc.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.PagedCallSettings;
import com.google.api.gax.grpc.PagedListDescriptor;
import com.google.api.gax.grpc.PagedListResponseFactory;
import com.google.api.gax.grpc.SimpleCallSettings;
import com.google.api.gax.grpc.UnaryCallSettings;
import com.google.api.gax.grpc.UnaryCallable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.monitoring.v3.CreateMetricDescriptorRequest;
import com.google.monitoring.v3.CreateTimeSeriesRequest;
import com.google.monitoring.v3.DeleteMetricDescriptorRequest;
import com.google.monitoring.v3.GetMetricDescriptorRequest;
import com.google.monitoring.v3.GetMonitoredResourceDescriptorRequest;
import com.google.monitoring.v3.ListMetricDescriptorsRequest;
import com.google.monitoring.v3.ListMetricDescriptorsResponse;
import com.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest;
import com.google.monitoring.v3.ListMonitoredResourceDescriptorsResponse;
import com.google.monitoring.v3.ListTimeSeriesRequest;
import com.google.monitoring.v3.ListTimeSeriesResponse;
import com.google.monitoring.v3.MetricServiceGrpc;
import com.google.monitoring.v3.TimeSeries;
import com.google.protobuf.Empty;
import com.google.protobuf.ExperimentalApi;
import io.grpc.Status;
import java.io.IOException;
import javax.annotation.Generated;
import org.joda.time.Duration;

// AUTO-GENERATED DOCUMENTATION AND CLASS
/**
 * Settings class to configure an instance of {@link MetricServiceClient}.
 *
 *
The default instance has everything set to sensible defaults:
 *
 *

 *
The default service address (monitoring.googleapis.com) and default port (443) are used.
 *
Credentials are acquired automatically through Application Default Credentials.
 *
Retries are configured for idempotent methods but not for non-idempotent methods.
 *

 *
 *
The builder of this class is recursive, so contained classes are themselves builders. When
 * build() is called, the tree of builders is called to create the complete settings object. For
 * example, to set the total timeout of getMonitoredResourceDescriptor to 30 seconds:
 *
 *

 *
 * MetricServiceSettings.Builder metricServiceSettingsBuilder =
 *     MetricServiceSettings.defaultBuilder();
 * metricServiceSettingsBuilder.getMonitoredResourceDescriptorSettings().getRetrySettingsBuilder()
 *     .setTotalTimeout(Duration.standardSeconds(30));
 * MetricServiceSettings metricServiceSettings = metricServiceSettingsBuilder.build();
 *
 *

 */
@Generated("by GAPIC")
@ExperimentalApi
public class MetricServiceSettings extends ClientSettings {
  /** The default address of the service. */
  private static final String DEFAULT_SERVICE_ADDRESS = "monitoring.googleapis.com";

  /** The default port of the service. */
  private static final int DEFAULT_SERVICE_PORT = 443;

  /** The default scopes of the service. */
  private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
      ImmutableList.<String>builder()
          .add("https://www.googleapis.com/auth/cloud-platform")
          .add("https://www.googleapis.com/auth/monitoring")
          .add("https://www.googleapis.com/auth/monitoring.read")
          .add("https://www.googleapis.com/auth/monitoring.write")
          .build();

  private final PagedCallSettings<
          ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
          ListMonitoredResourceDescriptorsPagedResponse>
      listMonitoredResourceDescriptorsSettings;
  private final SimpleCallSettings<
          GetMonitoredResourceDescriptorRequest, MonitoredResourceDescriptor>
      getMonitoredResourceDescriptorSettings;
  private final PagedCallSettings<
          ListMetricDescriptorsRequest, ListMetricDescriptorsResponse,
          ListMetricDescriptorsPagedResponse>
      listMetricDescriptorsSettings;
  private final SimpleCallSettings<GetMetricDescriptorRequest, MetricDescriptor>
      getMetricDescriptorSettings;
  private final SimpleCallSettings<CreateMetricDescriptorRequest, MetricDescriptor>
      createMetricDescriptorSettings;
  private final SimpleCallSettings<DeleteMetricDescriptorRequest, Empty>
      deleteMetricDescriptorSettings;
  private final PagedCallSettings<
          ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse>
      listTimeSeriesSettings;
  private final SimpleCallSettings<CreateTimeSeriesRequest, Empty> createTimeSeriesSettings;

  /** Returns the object with the settings used for calls to listMonitoredResourceDescriptors. */
  public PagedCallSettings<
          ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
          ListMonitoredResourceDescriptorsPagedResponse>
      listMonitoredResourceDescriptorsSettings() {
    return listMonitoredResourceDescriptorsSettings;
  }

  /** Returns the object with the settings used for calls to getMonitoredResourceDescriptor. */
  public SimpleCallSettings<GetMonitoredResourceDescriptorRequest, MonitoredResourceDescriptor>
      getMonitoredResourceDescriptorSettings() {
    return getMonitoredResourceDescriptorSettings;
  }

  /** Returns the object with the settings used for calls to listMetricDescriptors. */
  public PagedCallSettings<
          ListMetricDescriptorsRequest, ListMetricDescriptorsResponse,
          ListMetricDescriptorsPagedResponse>
      listMetricDescriptorsSettings() {
    return listMetricDescriptorsSettings;
  }

  /** Returns the object with the settings used for calls to getMetricDescriptor. */
  public SimpleCallSettings<GetMetricDescriptorRequest, MetricDescriptor>
      getMetricDescriptorSettings() {
    return getMetricDescriptorSettings;
  }

  /** Returns the object with the settings used for calls to createMetricDescriptor. */
  public SimpleCallSettings<CreateMetricDescriptorRequest, MetricDescriptor>
      createMetricDescriptorSettings() {
    return createMetricDescriptorSettings;
  }

  /** Returns the object with the settings used for calls to deleteMetricDescriptor. */
  public SimpleCallSettings<DeleteMetricDescriptorRequest, Empty> deleteMetricDescriptorSettings() {
    return deleteMetricDescriptorSettings;
  }

  /** Returns the object with the settings used for calls to listTimeSeries. */
  public PagedCallSettings<
          ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse>
      listTimeSeriesSettings() {
    return listTimeSeriesSettings;
  }

  /** Returns the object with the settings used for calls to createTimeSeries. */
  public SimpleCallSettings<CreateTimeSeriesRequest, Empty> createTimeSeriesSettings() {
    return createTimeSeriesSettings;
  }

  /** Returns a builder for the default ExecutorProvider for this service. */
  public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
    return InstantiatingExecutorProvider.newBuilder();
  }

  /** Returns the default service address. */
  public static String getDefaultServiceAddress() {
    return DEFAULT_SERVICE_ADDRESS;
  }

  /** Returns the default service port. */
  public static int getDefaultServicePort() {
    return DEFAULT_SERVICE_PORT;
  }

  /** Returns the default service scopes. */
  public static ImmutableList<String> getDefaultServiceScopes() {
    return DEFAULT_SERVICE_SCOPES;
  }

  /** Returns a builder for the default credentials for this service. */
  public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
    return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);
  }

  /** Returns a builder for the default ChannelProvider for this service. */
  public static InstantiatingChannelProvider.Builder defaultChannelProviderBuilder() {
    return InstantiatingChannelProvider.newBuilder()
        .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
        .setPort(DEFAULT_SERVICE_PORT)
        .setCredentialsProvider(defaultCredentialsProviderBuilder().build());
  }

  /** Returns a builder for this class with recommended defaults. */
  public static Builder defaultBuilder() {
    return Builder.createDefault();
  }

  /** Returns a new builder for this class. */
  public static Builder newBuilder() {
    return new Builder();
  }

  /** Returns a builder containing all the values of this settings class. */
  public Builder toBuilder() {
    return new Builder(this);
  }

  private MetricServiceSettings(Builder settingsBuilder) throws IOException {
    super(settingsBuilder.getExecutorProvider(), settingsBuilder.getChannelProvider());

    listMonitoredResourceDescriptorsSettings =
        settingsBuilder.listMonitoredResourceDescriptorsSettings().build();
    getMonitoredResourceDescriptorSettings =
        settingsBuilder.getMonitoredResourceDescriptorSettings().build();
    listMetricDescriptorsSettings = settingsBuilder.listMetricDescriptorsSettings().build();
    getMetricDescriptorSettings = settingsBuilder.getMetricDescriptorSettings().build();
    createMetricDescriptorSettings = settingsBuilder.createMetricDescriptorSettings().build();
    deleteMetricDescriptorSettings = settingsBuilder.deleteMetricDescriptorSettings().build();
    listTimeSeriesSettings = settingsBuilder.listTimeSeriesSettings().build();
    createTimeSeriesSettings = settingsBuilder.createTimeSeriesSettings().build();
  }

  private static final PagedListDescriptor<
          ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
          MonitoredResourceDescriptor>
      LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC =
          new PagedListDescriptor<
              ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
              MonitoredResourceDescriptor>() {
            @Override
            public Object emptyToken() {
              return "";
            }

            @Override
            public ListMonitoredResourceDescriptorsRequest injectToken(
                ListMonitoredResourceDescriptorsRequest payload, Object token) {
              return ListMonitoredResourceDescriptorsRequest.newBuilder(payload)
                  .setPageToken((String) token)
                  .build();
            }

            @Override
            public ListMonitoredResourceDescriptorsRequest injectPageSize(
                ListMonitoredResourceDescriptorsRequest payload, int pageSize) {
              return ListMonitoredResourceDescriptorsRequest.newBuilder(payload)
                  .setPageSize(pageSize)
                  .build();
            }

            @Override
            public Integer extractPageSize(ListMonitoredResourceDescriptorsRequest payload) {
              return payload.getPageSize();
            }

            @Override
            public Object extractNextToken(ListMonitoredResourceDescriptorsResponse payload) {
              return payload.getNextPageToken();
            }

            @Override
            public Iterable<MonitoredResourceDescriptor> extractResources(
                ListMonitoredResourceDescriptorsResponse payload) {
              return payload.getResourceDescriptorsList();
            }
          };

  private static final PagedListDescriptor<
          ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>
      LIST_METRIC_DESCRIPTORS_PAGE_STR_DESC =
          new PagedListDescriptor<
              ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>() {
            @Override
            public Object emptyToken() {
              return "";
            }

            @Override
            public ListMetricDescriptorsRequest injectToken(
                ListMetricDescriptorsRequest payload, Object token) {
              return ListMetricDescriptorsRequest.newBuilder(payload)
                  .setPageToken((String) token)
                  .build();
            }

            @Override
            public ListMetricDescriptorsRequest injectPageSize(
                ListMetricDescriptorsRequest payload, int pageSize) {
              return ListMetricDescriptorsRequest.newBuilder(payload).setPageSize(pageSize).build();
            }

            @Override
            public Integer extractPageSize(ListMetricDescriptorsRequest payload) {
              return payload.getPageSize();
            }

            @Override
            public Object extractNextToken(ListMetricDescriptorsResponse payload) {
              return payload.getNextPageToken();
            }

            @Override
            public Iterable<MetricDescriptor> extractResources(
                ListMetricDescriptorsResponse payload) {
              return payload.getMetricDescriptorsList();
            }
          };

  private static final PagedListDescriptor<
          ListTimeSeriesRequest, ListTimeSeriesResponse, TimeSeries>
      LIST_TIME_SERIES_PAGE_STR_DESC =
          new PagedListDescriptor<ListTimeSeriesRequest, ListTimeSeriesResponse, TimeSeries>() {
            @Override
            public Object emptyToken() {
              return "";
            }

            @Override
            public ListTimeSeriesRequest injectToken(ListTimeSeriesRequest payload, Object token) {
              return ListTimeSeriesRequest.newBuilder(payload).setPageToken((String) token).build();
            }

            @Override
            public ListTimeSeriesRequest injectPageSize(
                ListTimeSeriesRequest payload, int pageSize) {
              return ListTimeSeriesRequest.newBuilder(payload).setPageSize(pageSize).build();
            }

            @Override
            public Integer extractPageSize(ListTimeSeriesRequest payload) {
              return payload.getPageSize();
            }

            @Override
            public Object extractNextToken(ListTimeSeriesResponse payload) {
              return payload.getNextPageToken();
            }

            @Override
            public Iterable<TimeSeries> extractResources(ListTimeSeriesResponse payload) {
              return payload.getTimeSeriesList();
            }
          };

  private static final PagedListResponseFactory<
          ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
          ListMonitoredResourceDescriptorsPagedResponse>
      LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT =
          new PagedListResponseFactory<
              ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
              ListMonitoredResourceDescriptorsPagedResponse>() {
            @Override
            public ListMonitoredResourceDescriptorsPagedResponse createPagedListResponse(
                UnaryCallable<
                        ListMonitoredResourceDescriptorsRequest,
                        ListMonitoredResourceDescriptorsResponse>
                    callable,
                ListMonitoredResourceDescriptorsRequest request,
                CallContext context) {
              return new ListMonitoredResourceDescriptorsPagedResponse(
                  callable, LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC, request, context);
            }
          };

  private static final PagedListResponseFactory<
          ListMetricDescriptorsRequest, ListMetricDescriptorsResponse,
          ListMetricDescriptorsPagedResponse>
      LIST_METRIC_DESCRIPTORS_PAGE_STR_FACT =
          new PagedListResponseFactory<
              ListMetricDescriptorsRequest, ListMetricDescriptorsResponse,
              ListMetricDescriptorsPagedResponse>() {
            @Override
            public ListMetricDescriptorsPagedResponse createPagedListResponse(
                UnaryCallable<ListMetricDescriptorsRequest, ListMetricDescriptorsResponse> callable,
                ListMetricDescriptorsRequest request,
                CallContext context) {
              return new ListMetricDescriptorsPagedResponse(
                  callable, LIST_METRIC_DESCRIPTORS_PAGE_STR_DESC, request, context);
            }
          };

  private static final PagedListResponseFactory<
          ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse>
      LIST_TIME_SERIES_PAGE_STR_FACT =
          new PagedListResponseFactory<
              ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse>() {
            @Override
            public ListTimeSeriesPagedResponse createPagedListResponse(
                UnaryCallable<ListTimeSeriesRequest, ListTimeSeriesResponse> callable,
                ListTimeSeriesRequest request,
                CallContext context) {
              return new ListTimeSeriesPagedResponse(
                  callable, LIST_TIME_SERIES_PAGE_STR_DESC, request, context);
            }
          };

  /** Builder for MetricServiceSettings. */
  public static class Builder extends ClientSettings.Builder {
    private final ImmutableList<UnaryCallSettings.Builder> unaryMethodSettingsBuilders;

    private final PagedCallSettings.Builder<
            ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
            ListMonitoredResourceDescriptorsPagedResponse>
        listMonitoredResourceDescriptorsSettings;
    private final SimpleCallSettings.Builder<
            GetMonitoredResourceDescriptorRequest, MonitoredResourceDescriptor>
        getMonitoredResourceDescriptorSettings;
    private final PagedCallSettings.Builder<
            ListMetricDescriptorsRequest, ListMetricDescriptorsResponse,
            ListMetricDescriptorsPagedResponse>
        listMetricDescriptorsSettings;
    private final SimpleCallSettings.Builder<GetMetricDescriptorRequest, MetricDescriptor>
        getMetricDescriptorSettings;
    private final SimpleCallSettings.Builder<CreateMetricDescriptorRequest, MetricDescriptor>
        createMetricDescriptorSettings;
    private final SimpleCallSettings.Builder<DeleteMetricDescriptorRequest, Empty>
        deleteMetricDescriptorSettings;
    private final PagedCallSettings.Builder<
            ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse>
        listTimeSeriesSettings;
    private final SimpleCallSettings.Builder<CreateTimeSeriesRequest, Empty>
        createTimeSeriesSettings;

    private static final ImmutableMap<String, ImmutableSet<Status.Code>> RETRYABLE_CODE_DEFINITIONS;

    static {
      ImmutableMap.Builder<String, ImmutableSet<Status.Code>> definitions = ImmutableMap.builder();
      definitions.put(
          "idempotent",
          Sets.immutableEnumSet(
              Lists.<Status.Code>newArrayList(
                  Status.Code.DEADLINE_EXCEEDED, Status.Code.UNAVAILABLE)));
      definitions.put("non_idempotent", Sets.immutableEnumSet(Lists.<Status.Code>newArrayList()));
      RETRYABLE_CODE_DEFINITIONS = definitions.build();
    }

    private static final ImmutableMap<String, RetrySettings.Builder> RETRY_PARAM_DEFINITIONS;

    static {
      ImmutableMap.Builder<String, RetrySettings.Builder> definitions = ImmutableMap.builder();
      RetrySettings.Builder settingsBuilder = null;
      settingsBuilder =
          RetrySettings.newBuilder()
              .setInitialRetryDelay(Duration.millis(100L))
              .setRetryDelayMultiplier(1.3)
              .setMaxRetryDelay(Duration.millis(60000L))
              .setInitialRpcTimeout(Duration.millis(20000L))
              .setRpcTimeoutMultiplier(1.0)
              .setMaxRpcTimeout(Duration.millis(20000L))
              .setTotalTimeout(Duration.millis(600000L));
      definitions.put("default", settingsBuilder);
      RETRY_PARAM_DEFINITIONS = definitions.build();
    }

    private Builder() {
      super(defaultChannelProviderBuilder().build());

      listMonitoredResourceDescriptorsSettings =
          PagedCallSettings.newBuilder(
              MetricServiceGrpc.METHOD_LIST_MONITORED_RESOURCE_DESCRIPTORS,
              LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT);

      getMonitoredResourceDescriptorSettings =
          SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_GET_MONITORED_RESOURCE_DESCRIPTOR);

      listMetricDescriptorsSettings =
          PagedCallSettings.newBuilder(
              MetricServiceGrpc.METHOD_LIST_METRIC_DESCRIPTORS,
              LIST_METRIC_DESCRIPTORS_PAGE_STR_FACT);

      getMetricDescriptorSettings =
          SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_GET_METRIC_DESCRIPTOR);

      createMetricDescriptorSettings =
          SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_CREATE_METRIC_DESCRIPTOR);

      deleteMetricDescriptorSettings =
          SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_DELETE_METRIC_DESCRIPTOR);

      listTimeSeriesSettings =
          PagedCallSettings.newBuilder(
              MetricServiceGrpc.METHOD_LIST_TIME_SERIES, LIST_TIME_SERIES_PAGE_STR_FACT);

      createTimeSeriesSettings =
          SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_CREATE_TIME_SERIES);

      unaryMethodSettingsBuilders =
          ImmutableList.<UnaryCallSettings.Builder>of(
              listMonitoredResourceDescriptorsSettings,
              getMonitoredResourceDescriptorSettings,
              listMetricDescriptorsSettings,
              getMetricDescriptorSettings,
              createMetricDescriptorSettings,
              deleteMetricDescriptorSettings,
              listTimeSeriesSettings,
              createTimeSeriesSettings);
    }

    private static Builder createDefault() {
      Builder builder = new Builder();

      builder
          .listMonitoredResourceDescriptorsSettings()
          .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
          .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));

      builder
          .getMonitoredResourceDescriptorSettings()
          .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
          .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));

      builder
          .listMetricDescriptorsSettings()
          .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
          .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));

      builder
          .getMetricDescriptorSettings()
          .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
          .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));

      builder
          .createMetricDescriptorSettings()
          .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent"))
          .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));

      builder
          .deleteMetricDescriptorSettings()
          .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
          .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));

      builder
          .listTimeSeriesSettings()
          .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
          .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));

      builder
          .createTimeSeriesSettings()
          .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent"))
          .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));

      return builder;
    }

    private Builder(MetricServiceSettings settings) {
      super(settings);

      listMonitoredResourceDescriptorsSettings =
          settings.listMonitoredResourceDescriptorsSettings.toBuilder();
      getMonitoredResourceDescriptorSettings =
          settings.getMonitoredResourceDescriptorSettings.toBuilder();
      listMetricDescriptorsSettings = settings.listMetricDescriptorsSettings.toBuilder();
      getMetricDescriptorSettings = settings.getMetricDescriptorSettings.toBuilder();
      createMetricDescriptorSettings = settings.createMetricDescriptorSettings.toBuilder();
      deleteMetricDescriptorSettings = settings.deleteMetricDescriptorSettings.toBuilder();
      listTimeSeriesSettings = settings.listTimeSeriesSettings.toBuilder();
      createTimeSeriesSettings = settings.createTimeSeriesSettings.toBuilder();

      unaryMethodSettingsBuilders =
          ImmutableList.<UnaryCallSettings.Builder>of(
              listMonitoredResourceDescriptorsSettings,
              getMonitoredResourceDescriptorSettings,
              listMetricDescriptorsSettings,
              getMetricDescriptorSettings,
              createMetricDescriptorSettings,
              deleteMetricDescriptorSettings,
              listTimeSeriesSettings,
              createTimeSeriesSettings);
    }

    @Override
    public Builder setExecutorProvider(ExecutorProvider executorProvider) {
      super.setExecutorProvider(executorProvider);
      return this;
    }

    @Override
    public Builder setChannelProvider(ChannelProvider channelProvider) {
      super.setChannelProvider(channelProvider);
      return this;
    }

    /**
     * Applies the given settings to all of the unary API methods in this service. Only values that
     * are non-null will be applied, so this method is not capable of un-setting any values.
     *
     *
Note: This method does not support applying settings to streaming methods.
     */
    public Builder applyToAllUnaryMethods(UnaryCallSettings.Builder unaryCallSettings)
        throws Exception {
      super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, unaryCallSettings);
      return this;
    }

    /** Returns the builder for the settings used for calls to listMonitoredResourceDescriptors. */
    public PagedCallSettings.Builder<
            ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
            ListMonitoredResourceDescriptorsPagedResponse>
        listMonitoredResourceDescriptorsSettings() {
      return listMonitoredResourceDescriptorsSettings;
    }

    /** Returns the builder for the settings used for calls to getMonitoredResourceDescriptor. */
    public SimpleCallSettings.Builder<
            GetMonitoredResourceDescriptorRequest, MonitoredResourceDescriptor>
        getMonitoredResourceDescriptorSettings() {
      return getMonitoredResourceDescriptorSettings;
    }

    /** Returns the builder for the settings used for calls to listMetricDescriptors. */
    public PagedCallSettings.Builder<
            ListMetricDescriptorsRequest, ListMetricDescriptorsResponse,
            ListMetricDescriptorsPagedResponse>
        listMetricDescriptorsSettings() {
      return listMetricDescriptorsSettings;
    }

    /** Returns the builder for the settings used for calls to getMetricDescriptor. */
    public SimpleCallSettings.Builder<GetMetricDescriptorRequest, MetricDescriptor>
        getMetricDescriptorSettings() {
      return getMetricDescriptorSettings;
    }

    /** Returns the builder for the settings used for calls to createMetricDescriptor. */
    public SimpleCallSettings.Builder<CreateMetricDescriptorRequest, MetricDescriptor>
        createMetricDescriptorSettings() {
      return createMetricDescriptorSettings;
    }

    /** Returns the builder for the settings used for calls to deleteMetricDescriptor. */
    public SimpleCallSettings.Builder<DeleteMetricDescriptorRequest, Empty>
        deleteMetricDescriptorSettings() {
      return deleteMetricDescriptorSettings;
    }

    /** Returns the builder for the settings used for calls to listTimeSeries. */
    public PagedCallSettings.Builder<
            ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse>
        listTimeSeriesSettings() {
      return listTimeSeriesSettings;
    }

    /** Returns the builder for the settings used for calls to createTimeSeries. */
    public SimpleCallSettings.Builder<CreateTimeSeriesRequest, Empty> createTimeSeriesSettings() {
      return createTimeSeriesSettings;
    }

    @Override
    public MetricServiceSettings build() throws IOException {
      return new MetricServiceSettings(this);
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MessagingServiceTests
{
    class ServiceTests
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

include 'dbh.php';

$sql = "INSERT INTO user(fname, lname, uid, pwd) VALUES('$fname', '$lname', '$uid', '$pwd')";

$reulst = mysqli_query($conn, $sql);

header("Location: SYT_Home.html"); /* This will take us back to home page */

?>

<form action="login.php" method="POST">
	<input type="text" name="uid" placeholder="Username" autofocus>

	<input type="password" name="pwd" placeholder="Password" autofocus>

	<button type="submit">LOGIN</button>

</form>


text:
'use strict';

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _TVDBService = require('../../../TVDB/TVDBService');

var _TVDBService2 = _interopRequireDefault(_TVDBService);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var FindSeriesByName = (function () {
    function FindSeriesByName() {
        _classCallCheck(this, FindSeriesByName);
    }

    _createClass(FindSeriesByName, [{
        key: 'handle',
        value: function handle(req, res) {
            if (req.query.name && req.query.name.length > 0) {
                _TVDBService2.default.findSeriesByName(req.query.name).then(function (data) {
                    res.json(data);
                });
            } else {
                res.json(null);
            }
        }
    }]);

    return FindSeriesByName;
})();

exports.default = new FindSeriesByName();


text:
namespace MyWASAPI_Example
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.vScrollBar1 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar2 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar3 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar4 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar5 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar6 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar7 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar8 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar9 = new System.Windows.Forms.VScrollBar();
            this.vScrollBar10 = new System.Windows.Forms.VScrollBar();
            this.SuspendLayout();
            //
            // timer1
            //
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(133, 34);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(35, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "label1";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(174, 34);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(35, 13);
            this.label2.TabIndex = 0;
            this.label2.Text = "label1";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(215, 34);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(35, 13);
            this.label3.TabIndex = 0;
            this.label3.Text = "label1";
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(256, 34);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(35, 13);
            this.label4.TabIndex = 0;
            this.label4.Text = "label1";
            //
            // vScrollBar1
            //
            this.vScrollBar1.Location = new System.Drawing.Point(125, 70);
            this.vScrollBar1.Name = "vScrollBar1";
            this.vScrollBar1.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar1.TabIndex = 1;
            this.vScrollBar1.Value = 100;
            //
            // vScrollBar2
            //
            this.vScrollBar2.Location = new System.Drawing.Point(142, 70);
            this.vScrollBar2.Name = "vScrollBar2";
            this.vScrollBar2.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar2.TabIndex = 1;
            this.vScrollBar2.Value = 100;
            //
            // vScrollBar3
            //
            this.vScrollBar3.Location = new System.Drawing.Point(159, 70);
            this.vScrollBar3.Name = "vScrollBar3";
            this.vScrollBar3.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar3.TabIndex = 1;
            this.vScrollBar3.Value = 100;
            //
            // vScrollBar4
            //
            this.vScrollBar4.Location = new System.Drawing.Point(176, 70);
            this.vScrollBar4.Name = "vScrollBar4";
            this.vScrollBar4.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar4.TabIndex = 1;
            this.vScrollBar4.Value = 100;
            //
            // vScrollBar5
            //
            this.vScrollBar5.Location = new System.Drawing.Point(193, 70);
            this.vScrollBar5.Name = "vScrollBar5";
            this.vScrollBar5.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar5.TabIndex = 1;
            this.vScrollBar5.Value = 100;
            //
            // vScrollBar6
            //
            this.vScrollBar6.Location = new System.Drawing.Point(210, 70);
            this.vScrollBar6.Name = "vScrollBar6";
            this.vScrollBar6.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar6.TabIndex = 1;
            this.vScrollBar6.Value = 100;
            //
            // vScrollBar7
            //
            this.vScrollBar7.Location = new System.Drawing.Point(227, 70);
            this.vScrollBar7.Name = "vScrollBar7";
            this.vScrollBar7.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar7.TabIndex = 1;
            this.vScrollBar7.Value = 100;
            //
            // vScrollBar8
            //
            this.vScrollBar8.Location = new System.Drawing.Point(244, 70);
            this.vScrollBar8.Name = "vScrollBar8";
            this.vScrollBar8.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar8.TabIndex = 1;
            this.vScrollBar8.Value = 100;
            //
            // vScrollBar9
            //
            this.vScrollBar9.Location = new System.Drawing.Point(261, 70);
            this.vScrollBar9.Name = "vScrollBar9";
            this.vScrollBar9.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar9.TabIndex = 1;
            this.vScrollBar9.Value = 100;
            //
            // vScrollBar10
            //
            this.vScrollBar10.Location = new System.Drawing.Point(278, 70);
            this.vScrollBar10.Name = "vScrollBar10";
            this.vScrollBar10.Size = new System.Drawing.Size(17, 380);
            this.vScrollBar10.TabIndex = 1;
            this.vScrollBar10.Value = 100;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(435, 483);
            this.Controls.Add(this.vScrollBar10);
            this.Controls.Add(this.vScrollBar9);
            this.Controls.Add(this.vScrollBar8);
            this.Controls.Add(this.vScrollBar7);
            this.Controls.Add(this.vScrollBar6);
            this.Controls.Add(this.vScrollBar5);
            this.Controls.Add(this.vScrollBar4);
            this.Controls.Add(this.vScrollBar3);
            this.Controls.Add(this.vScrollBar2);
            this.Controls.Add(this.vScrollBar1);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "FFT";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.VScrollBar vScrollBar1;
        private System.Windows.Forms.VScrollBar vScrollBar2;
        private System.Windows.Forms.VScrollBar vScrollBar3;
        private System.Windows.Forms.VScrollBar vScrollBar4;
        private System.Windows.Forms.VScrollBar vScrollBar5;
        private System.Windows.Forms.VScrollBar vScrollBar6;
        private System.Windows.Forms.VScrollBar vScrollBar7;
        private System.Windows.Forms.VScrollBar vScrollBar8;
        private System.Windows.Forms.VScrollBar vScrollBar9;
        private System.Windows.Forms.VScrollBar vScrollBar10;
    }
}


text:
A helper library to easily define restful web requests in ruby.

Bassically I am tiered of constantly relooking up NET HTTP blog post to try and remember how to say override the default headers or attatch a file as a multipart post request. Also there are things about the ruby request generation process I felt I could improve such as, autodetecting the need for ssl from the URI and providing a clean DSL for request definition, as well as cleaner file attatchment.

Rquest makes it easy to build request and gives you full control over every aspect of the request. I modeled it after the chrome extension postman. Everything you can do with postman you can do with Rquest and it follows the same intuitive work flow.

In addition Rquest is an object that can handle a full session request cycle. You can say log in have the authentication cookies set by the server and then proceed to parse your dashboard.

## Credit where credit is due
- Special thanks to nicksieger for the multipart-post gem.
- Special thanks to minad for the mimemagic gem.
- Both of these were crucial in creating the easy file upload feature.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'rquest'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rquest

## Simple GET Request

Its basic setup involves setting the uri and action. Its send method will execute the rquest and return the body. You can access the full request object and the response time if you need them.

```ruby
rquest = Rquest.new({verb: :get, uri: "https://google.com"})
response_body = rquest.send
response_time = rquest.last_response_time
response_object = rquest.last_response
```

You can easily combine query params with the uri and the settings hash

```ruby
rquest = Rquest.new({verb: :get, uri: "https://google.com?q=testing", q_params: {token: "foo"}})
```

This will result in a request with a URI of http://google.com?q=testing&token=foo behind the sceens

## Auto SSL
Any uri with https will set use_ssl on the request object automatically. No more.

```ruby
https.use_ssl = true
```

## Form data POST/PUT/PATCH/DELETE/OPTIONS Requests

All controlled from the same settings hash with the payload key

```ruby
rquest = Rquest.new({verb: :post, uri: "https://google.com", payload: {a_field: "stuff", another_field: "more stuff"} })
rquest.send
```

The default body style is key=value&other_key=other_value however you can set it to a json body if you need like so

```ruby
rquest = Rquest.new({verb: :post, uri: "https://google.com", payload: {a_field: "stuff", another_field: "more stuff"}, form_type: :json })
rquest.send
```

Alright the best part for last

## Auto multipart forum

Just pass file objects into the files key and everything will be handled for you. It will automatically switch to multipart and detect mime types!

```ruby
f1 = File.open("path/to/file.txt")
f2 = File.open("path/to/file.jpg")
rquest = Rquest.new({verb: :get, uri: "https://google.com", payload: {a_field: "stuff", another_field: "more stuff"}, files: {file_field_1: f1, file_field_2: f2} })
rquest.send
```

## Sessions

Rquest is built to behave like a fresh incognito browser. Every time you apply send it will add the response to the transactions attribute and set the last_response and last_response_time.

Simply call update to change what you need before the next send like so. New settings will be merged so they will either override old ones ore creat new ones. Any non specified setting will remain untouched from the last request.

```ruby
rquest = Rquest.new({verb: :get, uri: "https://google.com?q=testing", q_params: {token: "foo"}})
rquest.send
rquest.update({q_params: {q: "other search value"}}
rquest.send
first_query = rquest.transactions.first
last_query = rquest.transactions.last
```

Transactions are stored as has with their request, response and response time available for future reference. Continuing from above we could.

```ruby
old_request = first_query[:request]
old_response = first_query[:response]
time_it_took = first_query[:response_time]
```

## Cookies

You can set cookies for a request by adding them to the settings[:cookies] like

```ruby
rquest = Rquest.new({verb: :get, uri: "https://google.com", payload: {a_field: "stuff", another_field: "more stuff"}, cookies: {"MySpecialCookie" => "SomeSuperSecretValue"} })
```

Any response will add/merge any cookies in the "Set-Cookie" header of the response to your next request

```ruby
rquest = Rquest.new({verb: :post, uri: "https://somesite.com/sessions", payload: {username: "foobar", password: "SuperSecret"}})
rquest.send
```
If this authenticates correctly then the server will send the right Set-Cookie so then you can do something like.

```ruby
rquest.update({uri: "https://somesite.com/mydashboard"}
rquest.send
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/rquest/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
@interface CombinationGenerator : NSObject
{
    NSMutableArray* combination;
    NSArray* symbols;
}

+(CombinationGenerator*)sharedGenerator;

-(NSArray*)generateCombinationWithQuantity:(int)i;
-(NSArray*)returnSymbols;
-(NSArray*)returnGeneratedCombination;
@end


text:
using poolqueue::Promise;

using sf::core::PromiseKeeper;
using sf::core::exception::DuplicateItem;
using sf::core::exception::ItemNotFound;

class TestKeeper : public PromiseKeeper {
 public:
  int size() {
    return this->promises_.size();
  }

  unsigned int ttlFor(std::string id) {
    return this->promises_[id].ttl;
  }
};

class PromiseKeeperTest : public ::testing::Test {
 protected:
  TestKeeper keeper;
};

TEST_F(PromiseKeeperTest, Clear) {
  Promise promise;
  this->keeper.keep("p1", promise);
  this->keeper.keep("p2", promise);
  ASSERT_EQ(2, this->keeper.size());

  this->keeper.clear();
  ASSERT_EQ(0, this->keeper.size());
}

TEST_F(PromiseKeeperTest, Keep) {
  Promise promise;
  this->keeper.keep("promise", promise);
  ASSERT_EQ(1, this->keeper.size());
}

TEST_F(PromiseKeeperTest, KeepOne) {
  Promise promise;
  this->keeper.keep("promise", promise);
  ASSERT_THROW(this->keeper.keep("promise", promise), DuplicateItem);
  ASSERT_EQ(1, this->keeper.size());
}

TEST_F(PromiseKeeperTest, Pop) {
  Promise p1;
  Promise p2;
  this->keeper.keep("promise", p1);
  p2 = this->keeper.pop("promise");
  ASSERT_EQ(p1, p2);
  ASSERT_EQ(0, this->keeper.size());
}

TEST_F(PromiseKeeperTest, PopMissing) {
  ASSERT_THROW(this->keeper.pop("promise"), ItemNotFound);
}

TEST_F(PromiseKeeperTest, TtlSet) {
  Promise promise;
  this->keeper.keep("promise", promise, 2);
  unsigned int ttl = this->keeper.ttlFor("promise");
  ASSERT_EQ(2, ttl);
}

TEST_F(PromiseKeeperTest, TtlDecrease) {
  Promise promise;
  this->keeper.keep("promise", promise, 2);
  this->keeper.tick();
  unsigned int ttl = this->keeper.ttlFor("promise");
  ASSERT_EQ(1, ttl);
}

TEST_F(PromiseKeeperTest, TtlExpires) {
  bool rejected = false;
  Promise promise;
  promise.except([&rejected](const std::exception_ptr& e) {
      rejected = true;
      return nullptr;
  });

  this->keeper.keep("promise", promise, 2);
  this->keeper.tick();
  this->keeper.tick();
  ASSERT_EQ(0, this->keeper.size());
  ASSERT_TRUE(rejected);
}

TEST_F(PromiseKeeperTest, TtlNoExpires) {
  bool rejected = false;
  Promise promise;
  promise.except([&rejected](const std::exception_ptr& e) {
      rejected = true;
      return nullptr;
  });

  this->keeper.keep("promise", promise);
  this->keeper.tick();
  this->keeper.tick();
  ASSERT_EQ(1, this->keeper.size());
  ASSERT_FALSE(rejected);
}


text:
require_relative "../../../mixin/which"
require_relative "../../../mixin/shell_out"
require_relative "version"
require "singleton" unless defined?(Singleton)
require "timeout" unless defined?(Timeout)

class Chef
  class Provider
    class Package
      class Dnf < Chef::Provider::Package
        class PythonHelper
          include Singleton
          include Chef::Mixin::Which
          include Chef::Mixin::ShellOut

          attr_accessor :stdin
          attr_accessor :stdout
          attr_accessor :stderr
          attr_accessor :inpipe
          attr_accessor :outpipe
          attr_accessor :wait_thr

          DNF_HELPER = ::File.expand_path(::File.join(::File.dirname(__FILE__), "dnf_helper.py")).freeze

          def dnf_command
            # platform-python is used for system tools on RHEL 8 and is installed under /usr/libexec
            @dnf_command ||= begin
                               cmd = which("platform-python", "python", "python3", "python2", "python2.7", extra_path: "/usr/libexec") do |f|
                                 shell_out("#{f} -c 'import dnf'").exitstatus == 0
                               end
                               raise Chef::Exceptions::Package, "cannot find dnf libraries, you may need to use yum_package" unless cmd

                               "#{cmd} #{DNF_HELPER}"
                             end
          end

          def start
            @inpipe, inpipe_write = IO.pipe
            outpipe_read, @outpipe = IO.pipe
            @stdin, @stdout, @stderr, @wait_thr = Open3.popen3("#{dnf_command} #{outpipe_read.fileno} #{inpipe_write.fileno}", outpipe_read.fileno => outpipe_read, inpipe_write.fileno => inpipe_write, close_others: false)
            outpipe_read.close
            inpipe_write.close
          end

          def reap
            unless wait_thr.nil?
              Process.kill("INT", wait_thr.pid) rescue nil
              begin
                Timeout.timeout(3) do
                  wait_thr.value # this calls waitpid()
                end
              rescue Timeout::Error
                Process.kill("KILL", wait_thr.pid) rescue nil
              end
              stdin.close unless stdin.nil?
              stdout.close unless stdout.nil?
              stderr.close unless stderr.nil?
              inpipe.close unless inpipe.nil?
              outpipe.close unless outpipe.nil?
              @stdin = @stdout = @stderr = @inpipe = @outpipe = @wait_thr = nil
            end
          end

          def check
            start if stdin.nil?
          end

          def compare_versions(version1, version2)
            query("versioncompare", { "versions" => [version1, version2] }).to_i
          end

          def options_params(options)
            options.each_with_object({}) do |opt, h|
              if opt =~ /--enablerepo=(.+)/
                $1.split(",").each do |repo|
                  h["repos"] ||= []
                  h["repos"].push( { "enable" => repo } )
                end
              end
              if opt =~ /--disablerepo=(.+)/
                $1.split(",").each do |repo|
                  h["repos"] ||= []
                  h["repos"].push( { "disable" => repo } )
                end
              end
            end
          end

          # @return Array<Version>
          # NB: "options" here is the dnf_package options hash and is deliberately not **opts
          def package_query(action, provides, version: nil, arch: nil, options: {})
            parameters = { "provides" => provides, "version" => version, "arch" => arch }
            repo_opts = options_params(options || {})
            parameters.merge!(repo_opts)
            # XXX: for now we restart before and after every query with an enablerepo/disablerepo to clean the helpers internal state
            restart unless repo_opts.empty?
            query_output = query(action, parameters)
            version = parse_response(query_output.lines.last)
            Chef::Log.trace "parsed #{version} from python helper"
            reap unless repo_opts.empty?
            version
          end

          def restart
            reap
            start
          end

          private

          # i couldn't figure out how to decompose an evr on the python side, it seems reasonably
          # painless to do it in ruby (generally massaging nevras in the ruby side is HIGHLY
          # discouraged -- this is an "every rule has an exception" exception -- any additional
          # functionality should probably trigger moving this regexp logic into python)
          def add_version(hash, version)
            epoch = nil
            if version =~ /(\S+):(\S+)/
              epoch = $1
              version = $2
            end
            if version =~ /(\S+)-(\S+)/
              version = $1
              release = $2
            end
            hash["epoch"] = epoch unless epoch.nil?
            hash["release"] = release unless release.nil?
            hash["version"] = version
          end

          def query(action, parameters)
            with_helper do
              json = build_query(action, parameters)
              Chef::Log.trace "sending '#{json}' to python helper"
              outpipe.puts json
              outpipe.flush
              output = inpipe.readline.chomp
              Chef::Log.trace "got '#{output}' from python helper"
              output
            end
          end

          def build_query(action, parameters)
            hash = { "action" => action }
            parameters.each do |param_name, param_value|
              hash[param_name] = param_value unless param_value.nil?
            end

            # Special handling for certain action / param combos
            if %i{whatinstalled whatavailable}.include?(action)
              add_version(hash, parameters["version"]) unless parameters["version"].nil?
            end

            FFI_Yajl::Encoder.encode(hash)
          end

          def parse_response(output)
            array = output.split.map { |x| x == "nil" ? nil : x }
            array.each_slice(3).map { |x| Version.new(*x) }.first
          end

          def drain_fds
            output = ""
            fds, = IO.select([stderr, stdout, inpipe], nil, nil, 0)
            unless fds.nil?
              fds.each do |fd|
                output += fd.sysread(4096) rescue ""
              end
            end
            output
          rescue => e
            output
          end

          def with_helper
            max_retries ||= 5
            ret = nil
            Timeout.timeout(600) do
              check
              ret = yield
            end
            output = drain_fds
            unless output.empty?
              Chef::Log.trace "discarding output on stderr/stdout from python helper: #{output}"
            end
            ret
          rescue => e
            output = drain_fds
            restart
            if ( max_retries -= 1 ) > 0 && !ENV["DNF_HELPER_NO_RETRIES"]
              unless output.empty?
                Chef::Log.trace "discarding output on stderr/stdout from python helper: #{output}"
              end
              retry
            else
              raise e if output.empty?

              raise "dnf-helper.py had stderr/stdout output:\n\n#{output}"
            end
          end
        end
      end
    end
  end
end


text:
title: Negotiating down to 100Mbit between two 1Gbit devices
slug: negotiating-down-to-100mbit
tags: linux, networking
date: 2022-07-29

Connecting two gigabit-capable devices via 4-wire UTP cable is an abomination,
but sometimes we have to live with it (e.g. when a [greedy ISP]
decides to save a few cents and pulls a cheap cable to your apartment).

The fun starts when the devices try to negotiate Ethernet connection speed.
[Autonegotiation pulses] are essentially 10BASE-T and use only 4 wires with no
checking of cable category, even CAT3 is enough. So autonegotiation will
"succeed" and will settle on 1Gbit since it's supported by both ends, even
though there is not enough physical conductors for it. The link will not work.

To negotiate a working connection instead we need to remove 1Gbit from
advertised link modes at least on one end. In Linux it should be rather
straightforward with [ethtool]:

```
$ ethtool -s $IFACE advertise 0x00f
```

0x00f is a sum of hex values for all 10Mbit and 100Mbit modes
(0x001 + 0x002 + 0x004 + 0x008), explicitly excluding 1Gbit and everything
above that. Tweaking advertised link modes is better than forcing a particular
connection speed (`ethtool -s $IFACE speed 100`) because in absence of
autonegotiation advertisement the other side may play it safe and switch
to half-duplex.

That's the theory. In practise however, hardware is difficult. Drivers for NICs are
tricky and sometimes incomplete. On D-Link DIR-825 changes made by ethtool
command did not stick: after a short hiccup NIC would immediately return back
to default settings, ignoring ethtool input completely.

But all is not lost. Through trial and error I found a sequence that worked.
Don't ask me why, I'm not cool enough yet to understand kernel drivers code.
Here is what worked for me:

```
# Excerpt from /etc/rc.local
# (order of commands and delays matter!)
WAN=eth1
ethtool -s $WAN autoneg off
sleep 1
ethtool -s $WAN speed 100
sleep 1
ethtool -s $WAN advertise 0x00f
```

Which results in a proper NIC configuration:

```
Supported ports: [ TP MII ]
Supported link modes:   10baseT/Half 10baseT/Full
                        100baseT/Half 100baseT/Full
                        1000baseT/Half 1000baseT/Full
Supported pause frame use: Symmetric Receive-only
Supports auto-negotiation: Yes
Supported FEC modes: Not reported
Advertised link modes:  10baseT/Half 10baseT/Full
                        100baseT/Half 100baseT/Full
Advertised pause frame use: No
Advertised auto-negotiation: Yes
Advertised FEC modes: Not reported
Link partner advertised link modes:  10baseT/Half 10baseT/Full
                                     100baseT/Half 100baseT/Full
Link partner advertised pause frame use: Symmetric
Link partner advertised auto-negotiation: Yes
Link partner advertised FEC modes: Not reported
Speed: 100Mb/s
Duplex: Full
Port: MII
PHYAD: 4
Transceiver: external
Auto-negotiation: on
Current message level: 0x000000ff (255)
                       drv probe link timer ifdown ifup rx_err tx_err
Link detected: yes
```

Let's hope some variation of this will work for your misbehaving device too!
Good luck!

[greedy ISP]: https://nevalink.net/
[Autonegotiation pulses]: https://en.wikipedia.org/wiki/Autonegotiation#Electrical_signals
[ethtool]: https://manpages.debian.org/ethtool


text:
cask 'navicat-premium' do
  version '12.1.13'
  sha256 '5aa6d299cd74d5aa36aea67f6da845f2ee9151f38d20aa4bbe5351864bd3a183'

  url "http://download.navicat.com/download/navicat#{version.major_minor.no_dots}_premium_en.dmg"
  appcast 'https://www.navicat.com/updater/v120/sysProfileInfo.php?appName=Navicat%20Premium&appLang=en'
  name 'Navicat Premium'
  homepage 'https://www.navicat.com/products/navicat-premium'

  app 'Navicat Premium.app'
end


text:
{{ HTML::style(asset('packages/ngungut/nccms/css/bootstrap.min.css')) }}
{{ HTML::style(asset('packages/ngungut/nccms/css/font-awesome.min.css')) }}
{{ HTML::style(asset('packages/ngungut/nccms/css/jQueryUI/jquery-ui-1.10.3.custom.min.css')) }}
{{ HTML::style(asset('packages/ngungut/nccms/css/ionicons.min.css')) }}
{{ HTML::style(asset('packages/ngungut/nccms/css/AdminLTE.css')) }}
{{ HTML::style(asset('packages/ngungut/nccms/css/fileupload/jquery.fileupload.css')) }}


text:
require_relative "facebook_birthdays/version"
require_relative 'facebook_birthdays/birthday'
require_relative 'facebook_birthdays/calendar'

require 'active_support'
require 'active_support/core_ext'


text:
package org.bouncycastle.openpgp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.bouncycastle.bcpg.BCPGInputStream;
import org.bouncycastle.bcpg.Packet;
import org.bouncycastle.bcpg.PacketTags;
import org.bouncycastle.bcpg.PublicKeyPacket;
import org.bouncycastle.bcpg.TrustPacket;
import org.bouncycastle.bcpg.UserDataPacket;
import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Iterable;
import org.bouncycastle.util.Longs;

/**
 * Class to hold a single master public key and its subkeys.
 *

 * Often PGP keyring files consist of multiple master keys, if you are trying to process
 * or construct one of these you should use the PGPPublicKeyRingCollection class.
 */
public class PGPPublicKeyRing
    extends PGPKeyRing
    implements Iterable<PGPPublicKey>
{
    private static final Logger LOG = Logger.getLogger(PGPPublicKeyRing.class.getName());

    List<PGPPublicKey> keys;

    public PGPPublicKeyRing(
        byte[] encoding,
        KeyFingerPrintCalculator fingerPrintCalculator)
        throws IOException
    {
        this(new ByteArrayInputStream(encoding), fingerPrintCalculator);
    }

    private static List<PGPPublicKey> checkKeys(List<PGPPublicKey> keys)
    {
        List<PGPPublicKey> rv = new ArrayList<PGPPublicKey>(keys.size());

        for (int i = 0; i != keys.size(); i++)
        {
            PGPPublicKey k = (PGPPublicKey)keys.get(i);

            if (i == 0)
            {
                if (!k.isMasterKey())
                {
                    throw new IllegalArgumentException("key 0 must be a master key");
                }
            }
            else
            {
                if (k.isMasterKey())
                {
                    throw new IllegalArgumentException("key 0 can be only master key");
                }
            }
            rv.add(k);
        }

        return rv;
    }

    /**
     * Base constructor from a list of keys representing a public key ring (a master key and its
     * associated sub-keys).
     *
     * @param pubKeys the list of keys making up the ring.
     */
    public PGPPublicKeyRing(
        List<PGPPublicKey> pubKeys)
    {
        this.keys = checkKeys(pubKeys);
    }

    public PGPPublicKeyRing(
        InputStream in,
        KeyFingerPrintCalculator fingerPrintCalculator)
        throws IOException
    {
        this.keys = new ArrayList<PGPPublicKey>();

        BCPGInputStream pIn = BCPGInputStream.wrap(in);

        int initialTag = pIn.skipMarkerPackets();
        if (initialTag != PacketTags.PUBLIC_KEY && initialTag != PacketTags.PUBLIC_SUBKEY)
        {
            throw new IOException(
                "public key ring doesn't start with public key tag: " +
                    "tag 0x" + Integer.toHexString(initialTag));
        }

        PublicKeyPacket pubPk = readPublicKeyPacket(pIn);
        TrustPacket trustPk = readOptionalTrustPacket(pIn);

        // direct signatures and revocations
        List<PGPSignature> keySigs = readSignaturesAndTrust(pIn);

        List<UserDataPacket> ids = new ArrayList<UserDataPacket>();
        List<TrustPacket> idTrusts = new ArrayList<TrustPacket>();
        List<List<PGPSignature>> idSigs = new ArrayList<List<PGPSignature>>();
        readUserIDs(pIn, ids, idTrusts, idSigs);

        try
        {
            keys.add(new PGPPublicKey(pubPk, trustPk, keySigs, ids, idTrusts, idSigs, fingerPrintCalculator));

            // Read subkeys
            while (pIn.nextPacketTag() == PacketTags.PUBLIC_SUBKEY)
            {
                try
                {
                    keys.add(readSubkey(pIn, fingerPrintCalculator));
                }
                catch (IOException e)
                {
                    // Skip unrecognizable subkey
                    if (LOG.isLoggable(Level.FINE))
                    {
                        LOG.fine("skipping unknown subkey: " + e.getMessage());
                    }
                }
            }
        }
        catch (PGPException e)
        {
            throw new IOException("processing exception: " + e.toString());
        }
    }

    /**
     * Return the first public key in the ring.
     *
     * @return PGPPublicKey
     */
    public PGPPublicKey getPublicKey()
    {
        return (PGPPublicKey)keys.get(0);
    }

    /**
     * Return the public key referred to by the passed in keyID if it
     * is present.
     *
     * @param keyID the full keyID of the key of interest.
     * @return PGPPublicKey with matching keyID, null if it is not present.
     */
    public PGPPublicKey getPublicKey(
        long keyID)
    {
        for (int i = 0; i != keys.size(); i++)
        {
            PGPPublicKey k = (PGPPublicKey)keys.get(i);

            if (keyID == k.getKeyID())
            {
                return k;
            }
        }

        return null;
    }

    /**
     * Return the public key with the passed in fingerprint if it
     * is present.
     *
     * @param fingerprint the full fingerprint of the key of interest.
     * @return PGPPublicKey with the matching fingerprint, null if it is not present.
     */
    public PGPPublicKey getPublicKey(byte[] fingerprint)
    {
        for (int i = 0; i != keys.size(); i++)
        {
            PGPPublicKey k = (PGPPublicKey)keys.get(i);

            if (Arrays.areEqual(fingerprint, k.getFingerprint()))
            {
                return k;
            }
        }

        return null;
    }

    /**
     * Return any keys carrying a signature issued by the key represented by keyID.
     *
     * @param keyID the key id to be matched against.
     * @return an iterator (possibly empty) of PGPPublicKey objects carrying signatures from keyID.
     */
    public Iterator<PGPPublicKey> getKeysWithSignaturesBy(long keyID)
    {
        List<PGPPublicKey> keysWithSigs = new ArrayList<PGPPublicKey>();

        for (int i = 0; i != keys.size(); i++)
        {
            PGPPublicKey k = (PGPPublicKey)keys.get(i);

            Iterator<PGPSignature> sigIt = k.getSignaturesForKeyID(keyID);

            if (sigIt.hasNext())
            {
                keysWithSigs.add(k);
            }
        }

        return keysWithSigs.iterator();
    }

    /**
     * Return an iterator containing all the public keys.
     *
     * @return Iterator
     */
    public Iterator<PGPPublicKey> getPublicKeys()
    {
        return Collections.unmodifiableList(keys).iterator();
    }

    /**
     * Support method for Iterable where available.
     */
    public Iterator<PGPPublicKey> iterator()
    {
        return getPublicKeys();
    }

    public byte[] getEncoded()
        throws IOException
    {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        this.encode(bOut);

        return bOut.toByteArray();
    }

    /**
     * Return an encoding of the key ring, with trust packets stripped out if forTransfer is true.
     *
     * @param forTransfer if the purpose of encoding is to send key to other users.
     * @return a encoded byte array representing the key.
     * @throws IOException in case of encoding error.
     */
    public byte[] getEncoded(boolean forTransfer)
        throws IOException
    {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        this.encode(bOut, forTransfer);

        return bOut.toByteArray();
    }

    public void encode(
        OutputStream outStream)
        throws IOException
    {
        encode(outStream, false);
    }

    /**
     * Encode the key ring to outStream, with trust packets stripped out if forTransfer is true.
     *
     * @param outStream   stream to write the key encoding to.
     * @param forTransfer if the purpose of encoding is to send key to other users.
     * @throws IOException in case of encoding error.
     */
    public void encode(
        OutputStream outStream,
        boolean forTransfer)
        throws IOException
    {
        for (int i = 0; i != keys.size(); i++)
        {
            PGPPublicKey k = (PGPPublicKey)keys.get(i);

            k.encode(outStream, forTransfer);
        }
    }

    /**
     * Returns a new key ring with the public key passed in
     * either added or replacing an existing one.
     *
     * @param pubRing the public key ring to be modified
     * @param pubKey  the public key to be inserted.
     * @return a new keyRing
     */
    public static PGPPublicKeyRing insertPublicKey(
        PGPPublicKeyRing pubRing,
        PGPPublicKey pubKey)
    {
        List<PGPPublicKey> keys = new ArrayList<PGPPublicKey>(pubRing.keys);
        boolean found = false;
        boolean masterFound = false;

        for (int i = 0; i != keys.size(); i++)
        {
            PGPPublicKey key = (PGPPublicKey)keys.get(i);

            if (key.getKeyID() == pubKey.getKeyID())
            {
                found = true;
                keys.set(i, pubKey);
            }
            if (key.isMasterKey())
            {
                masterFound = true;
            }
        }

        if (!found)
        {
            if (pubKey.isMasterKey())
            {
                if (masterFound)
                {
                    throw new IllegalArgumentException("cannot add a master key to a ring that already has one");
                }

                keys.add(0, pubKey);
            }
            else
            {
                keys.add(pubKey);
            }
        }

        return new PGPPublicKeyRing(keys);
    }

    /**
     * Returns a new key ring with the public key passed in
     * removed from the key ring.
     *
     * @param pubRing the public key ring to be modified
     * @param pubKey  the public key to be removed.
     * @return a new keyRing, null if pubKey is not found.
     */
    public static PGPPublicKeyRing removePublicKey(
        PGPPublicKeyRing pubRing,
        PGPPublicKey pubKey)
    {
        int count = pubRing.keys.size();
        long keyID = pubKey.getKeyID();

        ArrayList<PGPPublicKey> result = new ArrayList<PGPPublicKey>(count);
        boolean found = false;

        for (int i = 0; i < count; ++i)
        {
            PGPPublicKey key = (PGPPublicKey)pubRing.keys.get(i);

            if (key.getKeyID() == keyID)
            {
                found = true;
                continue;
            }

            result.add(key);
        }

        if (!found)
        {
            return null;
        }

        return new PGPPublicKeyRing(result);
    }

    static PublicKeyPacket readPublicKeyPacket(BCPGInputStream in)
        throws IOException
    {
        Packet packet = in.readPacket();
        if (!(packet instanceof PublicKeyPacket))
        {
            throw new IOException("unexpected packet in stream: " + packet);
        }

        return (PublicKeyPacket)packet;
    }

    static PGPPublicKey readSubkey(BCPGInputStream in, KeyFingerPrintCalculator fingerPrintCalculator)
        throws IOException, PGPException
    {
        PublicKeyPacket pk = readPublicKeyPacket(in);
        TrustPacket kTrust = readOptionalTrustPacket(in);

        // PGP 8 actually leaves out the signature.
        List<PGPSignature> sigList = readSignaturesAndTrust(in);

        return new PGPPublicKey(pk, kTrust, sigList, fingerPrintCalculator);
    }

    /**
     * Join two copies of the same certificate.
     * The certificates must have the same primary key, but may carry different subkeys, user-ids and signatures.
     * The resulting certificate will carry the sum of both certificates subkeys, user-ids and signatures.
     *

     * This method will ignore trust packets on the second copy of the certificate and instead
     * copy the local certificate's trust packets to the joined certificate.
     *
     * @param first  local copy of the certificate
     * @param second remote copy of the certificate (e.g. from a key server)
     * @return joined key ring
     * @throws PGPException
     */
    public static PGPPublicKeyRing join(
        PGPPublicKeyRing first,
        PGPPublicKeyRing second)
        throws PGPException
    {
        return join(first, second, false, false);
    }

    /**
     * Join two copies of the same certificate.
     * The certificates must have the same primary key, but may carry different subkeys, user-ids and signatures.
     * The resulting certificate will carry the sum of both certificates subkeys, user-ids and signatures.
     *

     * For each subkey holds: If joinTrustPackets is set to true and the second key is carrying a trust packet,
     * the trust packet will be copied to the joined key.
     * Otherwise, the joined key will carry the trust packet of the local copy.
     *
     * @param first                      local copy of the certificate
     * @param second                     remote copy of the certificate (e.g. from a key server)
     * @param joinTrustPackets           if true, trust packets from the second certificate copy will be carried over into the joined certificate
     * @param allowSubkeySigsOnNonSubkey if true, the resulting joined certificate may carry subkey signatures on its primary key
     * @return joined certificate
     * @throws PGPException
     */
    public static PGPPublicKeyRing join(
        PGPPublicKeyRing first,
        PGPPublicKeyRing second,
        boolean joinTrustPackets,
        boolean allowSubkeySigsOnNonSubkey)
        throws PGPException
    {
        if (!Arrays.areEqual(first.getPublicKey().getFingerprint(), second.getPublicKey().getFingerprint()))
        {
            throw new IllegalArgumentException("Cannot merge certificates with differing primary keys.");
        }

        Set<Long> secondKeys = new HashSet<Long>();
        for (Iterator<PGPPublicKey> it = second.iterator(); it.hasNext(); )
        {
            PGPPublicKey key = (PGPPublicKey)it.next();
            secondKeys.add(Longs.valueOf(key.getKeyID()));
        }

        List<PGPPublicKey> merged = new ArrayList<PGPPublicKey>();
        for (Iterator<PGPPublicKey> it = first.iterator(); it.hasNext(); )
        {
            PGPPublicKey key = (PGPPublicKey)it.next();
            PGPPublicKey copy = second.getPublicKey(key.getKeyID());
            if (copy != null)
            {
                merged.add(PGPPublicKey.join(key, copy, joinTrustPackets, allowSubkeySigsOnNonSubkey));
                secondKeys.remove(Longs.valueOf(key.getKeyID()));
            }
            else
            {
                merged.add(key);
            }
        }

        for (Iterator<Long> it = secondKeys.iterator(); it.hasNext(); )
        {
            Long additionalKeyId = (Long)it.next();
            merged.add(second.getPublicKey(additionalKeyId.longValue()));
        }

        return new PGPPublicKeyRing(merged);
    }
}


text:
import {toggleAttribute} from '#core/dom';
import {childElementsByTag} from '#core/dom/query';
import {toArray} from '#core/types/array';
import {dict, memo} from '#core/types/object';

import * as Preact from '#preact';
import {useLayoutEffect, useRef} from '#preact';
import {PreactBaseElement} from '#preact/base-element';
import {forwardRef} from '#preact/compat';
import {useDOMHandle} from '#preact/component';
import {useSlotContext} from '#preact/slot';

import {
  BentoAccordion,
  BentoAccordionContent,
  BentoAccordionHeader,
  BentoAccordionSection,
} from './component';

import {devAssert} from '../../../src/log';

const SECTION_SHIM_PROP = '__AMP_S_SHIM';
const HEADER_SHIM_PROP = '__AMP_H_SHIM';
const CONTENT_SHIM_PROP = '__AMP_C_SHIM';
const SECTION_POST_RENDER = '__AMP_PR';
const EXPAND_STATE_SHIM_PROP = '__AMP_EXPAND_STATE_SHIM';

/** @extends {PreactBaseElement<BentoAccordionDef.AccordionApi>} */
export class BaseElement extends PreactBaseElement {
  /** @override */
  init() {
    const getExpandStateTrigger = (section) => (expanded) =>
      this.triggerEvent(section, expanded ? 'expand' : 'collapse');

    const {element} = this;
    const mu = new MutationObserver(() => {
      this.mutateProps(getState(element, mu, getExpandStateTrigger));
    });
    mu.observe(element, {
      attributeFilter: ['expanded', 'id'],
      subtree: true,
      childList: true,
    });

    const {'children': children} = getState(element, mu, getExpandStateTrigger);
    return dict({
      'children': children,
    });
  }
}

/**
 * @param {!Element} element
 * @param {MutationObserver} mu
 * @param {!Function} getExpandStateTrigger
 * @return {!JsonObject}
 */
function getState(element, mu, getExpandStateTrigger) {
  const sections = toArray(childElementsByTag(element, 'section'));

  const children = sections.map((section) => {
    // TODO(wg-bento): This implementation causes infinite loops on DOM mutation.
    // See https://github.com/ampproject/amp-react-prototype/issues/40.
    if (!section[SECTION_POST_RENDER]) {
      section[SECTION_POST_RENDER] = () => mu.takeRecords();
    }

    const sectionShim = memo(
      section,
      SECTION_SHIM_PROP,
      bindSectionShimToElement
    );
    const headerShim = memo(section, HEADER_SHIM_PROP, bindHeaderShimToElement);
    const contentShim = memo(
      section,
      CONTENT_SHIM_PROP,
      bindContentShimToElement
    );
    const expandStateShim = memo(
      section,
      EXPAND_STATE_SHIM_PROP,
      getExpandStateTrigger
    );
    const sectionProps = dict({
      'key': section,
      'as': sectionShim,
      'expanded': section.hasAttribute('expanded'),
      'id': section.getAttribute('id'),
      'onExpandStateChange': expandStateShim,
    });
    // For headerProps and contentProps:
    // || undefined needed for the `role` attribute since an element w/o
    // role results in `null`.  When `null` is passed into Preact, the
    // default prop value is not used.  `undefined` triggers default prop
    // value.  This is not needed for `id` since this is handled with
    // explicit logic (not default prop value) and all falsy values are
    // handled the same.
    const headerProps = dict({
      'as': headerShim,
      'id': section.firstElementChild.getAttribute('id'),
      'role': section.firstElementChild.getAttribute('role') || undefined,
    });
    const contentProps = dict({
      'as': contentShim,
      'id': section.lastElementChild.getAttribute('id'),
      'role': section.lastElementChild.getAttribute('role') || undefined,
    });
    return (
      <BentoAccordionSection {...sectionProps}>
        <BentoAccordionHeader {...headerProps}></BentoAccordionHeader>
        <BentoAccordionContent {...contentProps}></BentoAccordionContent>
      </BentoAccordionSection>
    );
  });
  return dict({'children': children});
}

/**
 * @param {!Element} sectionElement
 * @param {!BentoAccordionDef.SectionShimProps} props
 * @return {PreactDef.Renderable}
 */
function SectionShim(sectionElement, {children, expanded}) {
  useLayoutEffect(() => {
    toggleAttribute(sectionElement, 'expanded', expanded);
    if (sectionElement[SECTION_POST_RENDER]) {
      sectionElement[SECTION_POST_RENDER]();
    }
  }, [sectionElement, expanded]);
  return children;
}

/**
 * @param {!Element} element
 * @return {function(!BentoAccordionDef.SectionProps):PreactDef.Renderable}
 */
const bindSectionShimToElement = (element) => SectionShim.bind(null, element);

/**
 * @param {!Element} sectionElement
 * @param {!BentoAccordionDef.HeaderShimProps} props
 * @return {PreactDef.Renderable}
 */
function HeaderShim(
  sectionElement,
  {
    'aria-controls': ariaControls,
    'aria-expanded': ariaExpanded,
    id,
    onClick,
    role,
  }
) {
  const headerElement = sectionElement.firstElementChild;
  useLayoutEffect(() => {
    if (!headerElement || !onClick) {
      return;
    }
    headerElement.setAttribute('id', id);
    headerElement.classList.add('i-amphtml-accordion-header');
    headerElement.addEventListener('click', onClick);
    if (!headerElement.hasAttribute('tabindex')) {
      headerElement.setAttribute('tabindex', 0);
    }
    headerElement.setAttribute('aria-expanded', ariaExpanded);
    headerElement.setAttribute('aria-controls', ariaControls);
    headerElement.setAttribute('role', role);
    if (sectionElement[SECTION_POST_RENDER]) {
      sectionElement[SECTION_POST_RENDER]();
    }
    return () => {
      headerElement.removeEventListener('click', devAssert(onClick));
    };
  }, [
    sectionElement,
    headerElement,
    id,
    role,
    onClick,
    ariaControls,
    ariaExpanded,
  ]);
  return <header />;
}

/**
 * @param {!Element} element
 * @return {function(!BentoAccordionDef.HeaderProps):PreactDef.Renderable}
 */
const bindHeaderShimToElement = (element) => HeaderShim.bind(null, element);

/**
 * @param {!Element} sectionElement
 * @param {!BentoAccordionDef.ContentShimProps} props
 * @param {{current: ?}} ref
 * @return {PreactDef.Renderable}
 */
function ContentShimWithRef(
  sectionElement,
  {'aria-labelledby': ariaLabelledBy, id, role},
  ref
) {
  const contentElement = sectionElement.lastElementChild;
  const contentRef = useRef();
  contentRef.current = contentElement;
  useSlotContext(contentRef);
  useDOMHandle(ref, contentElement);
  useLayoutEffect(() => {
    if (!contentElement) {
      return;
    }
    contentElement.classList.add('i-amphtml-accordion-content');
    contentElement.setAttribute('id', id);
    contentElement.setAttribute('role', role);
    contentElement.setAttribute('aria-labelledby', ariaLabelledBy);
    if (sectionElement[SECTION_POST_RENDER]) {
      sectionElement[SECTION_POST_RENDER]();
    }
  }, [sectionElement, contentElement, id, role, ariaLabelledBy]);
  return <div />;
}

/**
 * @param {!Element} element
 * @return {function(!BentoAccordionDef.ContentProps):PreactDef.Renderable}
 */
const bindContentShimToElement = (element) =>
  forwardRef(
    /** @type {function(?, {current:?}):PreactDef.Renderable} */ (
      ContentShimWithRef.bind(null, element)
    )
  );

/** @override */
BaseElement['Component'] = BentoAccordion;

/** @override */
BaseElement['detached'] = true;

/** @override */
BaseElement['props'] = {
  'animate': {attr: 'animate', type: 'boolean', media: true},
  'expandSingleSection': {
    attr: 'expand-single-section',
    type: 'boolean',
  },
};


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link href="../wulfdist/css/wulf.min.css" rel="stylesheet"/>
    <link href="../wulfdist/css/wulf.angular.min.css" rel="stylesheet"/>
    <link href="../wulfdist/css/angular-csp.css" rel="stylesheet"/>
    <link href="../assets/css/demo.css" rel="stylesheet"/>
    <link href="../assets/css/github.css" rel="stylesheet"/>
    <title>Drilldown without arrow</title>

Drilldown without arrow

                With icon

                With text

                With error/alert

                With number

                Critical fault
                2010
                910

                    <wf-drilldown identity="row1" content="demo.content1"></wf-drilldown>

                Major fault
                2010
                910

                    <wf-drilldown identity="row2" content="demo.content2"></wf-drilldown>

                Minor fault

                2010
                910

                    <wf-drilldown identity="row3" content="demo.content3"></wf-drilldown>

                Warning

                2010
                910

                    <wf-drilldown identity="row4" content="demo.content4"></wf-drilldown>

                Fault cleared

                2010
                910

                    <wf-drilldown identity="row5" content="demo.content5"></wf-drilldown>

                Unknown situation

                2010
                910

                    <wf-drilldown identity="row6" content="demo.content6" height="350px"></wf-drilldown>

Overview

            Angular version of Drilldown component which is implemented by using .component() method introduced since Angular1.5.

            Involve JS 'wulf-ng/drilldown/drilldown' and add the module angular.module('myApp',['wf.angular.drilldown'] to your angular application.
            Add class n-drillDown-row and set data-target-selector="#drilldown component identity" in tr. Put wf-drilldown in next tr which will drill down as click.
            Now drill down component can be worked.

wf-drilldown settings

                Attributes:Bindings
                Accept value
                Note

                identity: @

                    text

                    The identity text which unique define the component

                content: &

                   function()

                    Function should return the drilldown content, the content can be text or other html component.

                arrow: <?

true

false (Default)

                    Indicate whether arrow show or not when content expanded.

                height: @

                    String(Optional, default is 100px).

                    The content height which will drill down. e.g 200px

Keyboard accessibility

        Besides the basic keyboard support, e.g. Tab, Shift +
        Tab and Enter. This component also supports the following
        keystrokes for the interaction.

                Interaction
                Keystrokes
                Notes

                Expand/Collapse

                    Spacebar/Enter - Expand or Collapse the content

        <wf-tabs ng-cloak>
            <wf-pane label="Markup">

<div class="col-md-5" ng-controller="DrilldownDemoController as demo">
    <table class="n-table n-table-standard n-table-striped n-table-cell-hover n-drilldown-table">
        <thead>
        <tr>
            <th class="n-sortable">With icon</span>
                <span class="icon icon-arrow"></span>
            </th>
            <th class="n-sortable">With text</span>
                <span class="icon icon-arrow"></span>
            </th>
            <th class="text-right n-sortable">With error/alert
                <span class="icon icon-arrow"></span></th>
            <th class="text-right n-sortable">With number<span class="icon icon-arrow"></span></th>
        </tr>
        </thead>
        <tbody>
        <tr class="n-drillDown-row" data-target-selector="#row1">
            <td class="text-center"><span class="icon icon-fault-critical"></span></td>
            <td>Critical fault</td>
            <td class="n-cell-error text-right">2010</td>
            <td class="text-right">910</td>
        </tr>
        <tr>
            <td colspan="4">
                <wf-drilldown identity="row1" content="demo.content1"></wf-drilldown>
            </td>
        </tr>
        <tr class="n-drillDown-row" data-target-selector="#row2">
            <td class="text-center"><span class="icon icon-fault-major"></span></td>
            <td>Major fault</td>
            <td class="n-cell-error text-right">2010</td>
            <td class="text-right">910</td>
        </tr>
        <tr>
            <td colspan="4">
                <wf-drilldown identity="row2" content="demo.content2"></wf-drilldown>
            </td>
        </tr>
        <tr class="n-drillDown-row" data-target-selector="#row3">
            <td class="text-center"><span class="icon icon-fault-minor"></span></td>
            <td>Minor fault</td>

            <td class="n-cell-error text-right">2010</td>
            <td class="text-right">910</td>
        </tr>
        <tr>
            <td colspan="4">
                <wf-drilldown identity="row3" content="demo.content3"></wf-drilldown>
            </td>
        </tr>
        <tr class="n-drillDown-row" data-target-selector="#row4">
            <td class="text-center"><span class="icon icon-fault-warning"></span></td>
            <td>Warning</td>

            <td class="n-cell-error text-right">2010</td>
            <td class="text-right">910</td>
        </tr>
        <tr>
            <td colspan="4">
                <wf-drilldown identity="row4" content="demo.content4"></wf-drilldown>
            </td>
        </tr>
        <tr class="n-drillDown-row" data-target-selector="#row5">
            <td class="text-center"><span class="icon icon-fault-cleared"></span></td>
            <td>Fault cleared</td>

            <td class="n-cell-error text-right">2010</td>
            <td class="text-right">910</td>
        </tr>
        <tr>
            <td colspan="4">
                <wf-drilldown identity="row5" content="demo.content5"></wf-drilldown>
            </td>
        </tr>
        <tr class="n-drillDown-row" data-target-selector="#row6">
            <td class="text-center"><span class="icon icon-fault-unknown"></span></td>
            <td>Unknown situation</td>

            <td class="n-cell-error text-right">2010</td>
            <td class="text-right">910</td>
        </tr>
        <tr>
            <td colspan="4">
                <wf-drilldown identity="row6" content="demo.content6"></wf-drilldown>
            </td>
        </tr>
        </tbody>
    </table>
</div>

            </wf-pane>
            <wf-pane label="JavaScript">

angular.module('wf.ng.demo', ['wf.angular.drilldown', 'wf.angular.tabs']).controller('DrilldownDemoController', DrilldownDemoController);

    function DrilldownDemoController() {
        this.content1 = function () {
            return "Row1 content";
        };
        this.content2 = function () {
            return "Row2 content";
        };
        this.content3 = function () {
            return 'Row3 content';
        };
        this.content4 = function () {
            return "Row4 content";
        };
        this.content5 = function () {
            return "Row5 content";
        };
        this.content6 = function () {
            return 'Row6 content';
        };
    }

            </wf-pane>
        </wf-tabs>