// Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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.
package com.google.devtools.build.lib.exec;

import static java.util.stream.Collectors.joining;

import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.devtools.build.lib.actions.ActionContext;
import com.google.devtools.build.lib.actions.DynamicStrategyRegistry;
import com.google.devtools.build.lib.actions.SandboxedSpawnStrategy;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnStrategy;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.server.FailureDetails;
import com.google.devtools.build.lib.server.FailureDetails.ExecutionOptions.Code;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.RegexFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * Registry that collects spawn strategies and rules about their applicability and makes them
 * available for querying through various registry interfaces.
 *
 *
An instance of this registry can be created using its {@linkplain Builder builder}, which is
 * available to Blaze modules during server startup.
 */
public final class SpawnStrategyRegistry
    implements DynamicStrategyRegistry, ActionContext, RemoteLocalFallbackRegistry {

  private final ImmutableListMultimap<String, SpawnStrategy> mnemonicToStrategies;
  private final ImmutableListMultimap<RegexFilter, SpawnStrategy> filterToStrategies;
  private final ImmutableList<? extends SpawnStrategy> defaultStrategies;
  private final ImmutableMultimap<String, SandboxedSpawnStrategy> mnemonicToRemoteDynamicStrategies;
  private final ImmutableMultimap<String, SandboxedSpawnStrategy> mnemonicToLocalDynamicStrategies;
  @Nullable private final AbstractSpawnStrategy remoteLocalFallbackStrategy;

  private SpawnStrategyRegistry(
      ImmutableListMultimap<String, SpawnStrategy> mnemonicToStrategies,
      ImmutableListMultimap<RegexFilter, SpawnStrategy> filterToStrategies,
      ImmutableList<? extends SpawnStrategy> defaultStrategies,
      ImmutableMultimap<String, SandboxedSpawnStrategy> mnemonicToRemoteDynamicStrategies,
      ImmutableMultimap<String, SandboxedSpawnStrategy> mnemonicToLocalDynamicStrategies,
      @Nullable AbstractSpawnStrategy remoteLocalFallbackStrategy) {
    this.mnemonicToStrategies = mnemonicToStrategies;
    this.filterToStrategies = filterToStrategies;
    this.defaultStrategies = defaultStrategies;
    this.mnemonicToRemoteDynamicStrategies = mnemonicToRemoteDynamicStrategies;
    this.mnemonicToLocalDynamicStrategies = mnemonicToLocalDynamicStrategies;
    this.remoteLocalFallbackStrategy = remoteLocalFallbackStrategy;
  }

  /**
   * Returns the strategies applying to the given spawn, in priority order.
   *
   *
Which strategies are returned is based on the precedence as documented on the construction
   * methods of {@linkplain Builder this registry's builder}.
   *
   *
If the reason for selecting the context is worth mentioning to the user, logs a message
   * using the given {@link Reporter}.
   */
  @VisibleForTesting
  public List<? extends SpawnStrategy> getStrategies(Spawn spawn, EventHandler reporter) {
    // Don't override test strategies by --strategy_regexp for backwards compatibility.
    if (spawn.getResourceOwner() != null && !"TestRunner".equals(spawn.getMnemonic())) {
      String description = spawn.getResourceOwner().getProgressMessage();
      if (description != null) {
        for (Map.Entry<RegexFilter, Collection<SpawnStrategy>> filterStrategies :
            filterToStrategies.asMap().entrySet()) {
          if (filterStrategies.getKey().isIncluded(description)) {
            // TODO(schmitt): Why is this done here and not after running canExec?
            reporter.handle(
                Event.progress(description + " with context " + filterStrategies.getValue()));
            return ImmutableList.copyOf(filterStrategies.getValue());
          }
        }
      }
    }
    if (mnemonicToStrategies.containsKey(spawn.getMnemonic())) {
      return mnemonicToStrategies.get(spawn.getMnemonic());
    }
    return defaultStrategies;
  }

  @Override
  public void notifyUsedDynamic(ActionContext.ActionContextRegistry actionContextRegistry) {
    for (SandboxedSpawnStrategy strategy : mnemonicToLocalDynamicStrategies.values()) {
      strategy.usedContext(actionContextRegistry);
    }
    for (SandboxedSpawnStrategy strategy : mnemonicToRemoteDynamicStrategies.values()) {
      strategy.usedContext(actionContextRegistry);
    }
  }

  @Override
  public List<SandboxedSpawnStrategy> getDynamicSpawnActionContexts(
      Spawn spawn, DynamicMode dynamicMode) {
    ImmutableMultimap<String, SandboxedSpawnStrategy> mnemonicToDynamicStrategies =
        dynamicMode == DynamicStrategyRegistry.DynamicMode.REMOTE
            ? mnemonicToRemoteDynamicStrategies
            : mnemonicToLocalDynamicStrategies;
    return ImmutableList.<SandboxedSpawnStrategy>builder()
        .addAll(mnemonicToDynamicStrategies.get(spawn.getMnemonic()))
        .addAll(mnemonicToDynamicStrategies.get(""))
        .build();
  }

  @Nullable
  @Override
  public AbstractSpawnStrategy getRemoteLocalFallbackStrategy() {
    return remoteLocalFallbackStrategy;
  }

  /**
   * Notifies all (non-dynamic) strategies stored in this registry that they are {@linkplain
   * SpawnStrategy#usedContext used}.
   */
  public void notifyUsed(ActionContext.ActionContextRegistry actionContextRegistry) {
    for (SpawnStrategy strategy : filterToStrategies.values()) {
      strategy.usedContext(actionContextRegistry);
    }
    for (SpawnStrategy strategy : mnemonicToStrategies.values()) {
      strategy.usedContext(actionContextRegistry);
    }
    for (SpawnStrategy strategy : defaultStrategies) {
      strategy.usedContext(actionContextRegistry);
    }
    if (remoteLocalFallbackStrategy != null) {
      remoteLocalFallbackStrategy.usedContext(actionContextRegistry);
    }
  }

  /**
   * Records the list of all spawn strategies that can be returned by the various query methods of
   * this registry to the given reporter.
   */
  void writeSpawnStrategiesTo(Reporter reporter) {
    for (Map.Entry<String, Collection<SpawnStrategy>> entry :
        mnemonicToStrategies.asMap().entrySet()) {
      reporter.handle(
          Event.info(
              String.format(
                  "MnemonicToStrategyImplementations: \"%s\" = [%s]",
                  entry.getKey(), toImplementationNames(entry.getValue()))));
    }

    for (Map.Entry<RegexFilter, Collection<SpawnStrategy>> entry :
        filterToStrategies.asMap().entrySet()) {
      Collection<SpawnStrategy> value = entry.getValue();
      reporter.handle(
          Event.info(
              String.format(
                  "FilterToStrategyImplementations: \"%s\" = [%s]",
                  entry.getKey(), toImplementationNames(value))));
    }

    reporter.handle(
        Event.info(
            String.format(
                "DefaultStrategyImplementations: [%s]", toImplementationNames(defaultStrategies))));

    if (remoteLocalFallbackStrategy != null) {
      reporter.handle(
          Event.info(
              String.format(
                  "RemoteLocalFallbackImplementation: [%s]",
                  remoteLocalFallbackStrategy.getClass().getSimpleName())));
    }

    for (Map.Entry<String, Collection<SandboxedSpawnStrategy>> entry :
        mnemonicToRemoteDynamicStrategies.asMap().entrySet()) {
      reporter.handle(
          Event.info(
              String.format(
                  "MnemonicToRemoteDynamicStrategyImplementations: \"%s\" = [%s]",
                  entry.getKey(), toImplementationNames(entry.getValue()))));
    }

    for (Map.Entry<String, Collection<SandboxedSpawnStrategy>> entry :
        mnemonicToLocalDynamicStrategies.asMap().entrySet()) {
      reporter.handle(
          Event.info(
              String.format(
                  "MnemonicToLocalDynamicStrategyImplementations: \"%s\" = [%s]",
                  entry.getKey(), toImplementationNames(entry.getValue()))));
    }
  }

  private String toImplementationNames(Collection<?> strategies) {
    return strategies.stream()
        .map(strategy -> strategy.getClass().getSimpleName())
        .collect(joining(", "));
  }

  /** Returns a new {@link Builder} suitable for creating instances of SpawnStrategyRegistry. */
  public static Builder builder() {
    return new Builder();
  }

  /**
   * Builder collecting the strategies and restrictions thereon for a {@link SpawnStrategyRegistry}.
   *
   *
To {@linkplain SpawnStrategyRegistry#getStrategies match a strategy to a spawn} it needs to
   * be both {@linkplain #registerStrategy registered} and its registered command-line identifier
   * has to match {@linkplain #addDescriptionFilter a filter on the spawn's progress message},
   * {@linkplain #addMnemonicFilter a filter on the spawn's mnemonic} or be part of the default
   * strategies (see below).
   *
   *
Default strategies are either {@linkplain #setDefaultStrategies set
   * explicitly} or, if {@link #setDefaultStrategies} is not called on this builder, comprised of
   * all registered strategies, in registration order (i.e. the earliest strategy registered will be
   * first in the list of strategies returned by {@link SpawnStrategyRegistry#getStrategies}).
   */
  public static final class Builder {

    private ImmutableList<String> explicitDefaultStrategies = ImmutableList.of();
    // TODO(schmitt): Using a list and autovalue so as to be able to reverse order while legacy sort
    //  is supported. Can be converted to same as mnemonics once legacy behavior is removed.
    private final List<FilterAndIdentifiers> filterAndIdentifiers = new ArrayList<>();
    private final HashMap<String, SpawnStrategy> identifierToStrategy = new HashMap<>();
    private final ArrayList<SpawnStrategy> strategiesInRegistrationOrder = new ArrayList<>();

    // Using List values here rather than multimaps as there is no need for the latter's
    // functionality: The values are always replaced as a whole, no adding/creation required.
    private final HashMap<String, List<String>> mnemonicToIdentifiers = new HashMap<>();
    private final HashMap<String, List<String>> mnemonicToRemoteIdentifiers = new HashMap<>();
    private final HashMap<String, List<String>> mnemonicToLocalIdentifiers = new HashMap<>();
    private boolean legacyFilterIterationOrder = false;
    @Nullable private String remoteLocalFallbackStrategyIdentifier;

    /**
     * Adds a filter limiting any spawn whose {@linkplain
     * com.google.devtools.build.lib.actions.ActionExecutionMetadata#getProgressMessage() owner's
     * progress message} matches the regular expression to only use strategies with the given
     * command-line identifiers, in order.
     *
     *
If multiple filters match the same spawn (including an identical filter) the order of
     * precedence of calls to this method is determined by {@link
     * #useLegacyDescriptionFilterPrecedence()}.
     */
    public Builder addDescriptionFilter(RegexFilter filter, List<String> identifiers) {
      filterAndIdentifiers.add(
          new AutoValue_SpawnStrategyRegistry_FilterAndIdentifiers(
              filter, ImmutableList.copyOf(identifiers)));
      return this;
    }

    /**
     * Adds a filter limiting any spawn whose {@linkplain Spawn#getMnemonic() mnemonic}
     * (case-sensitively) matches the given mnemonic to only use strategies with the given
     * command-line identifiers, in order.
     *
     *
If the same mnemonic is registered multiple times the last such call will take precedence.
     *
     *
Note that if a spawn matches a {@linkplain #addDescriptionFilter registered description
     * filter} that filter will take precedence over any mnemonic-based filters.
     */
    // last one wins
    public Builder addMnemonicFilter(String mnemonic, List<String> identifiers) {
      mnemonicToIdentifiers.put(mnemonic, identifiers);
      return this;
    }

    /**
     * Registers a strategy implementation with this collector, distinguishing it from other
     * strategies with the given command-line identifiers (of which at least one is required).
     *
     *
If multiple strategies are registered with the same command-line identifier the last one
     * so registered will take precedence.
     */
    public Builder registerStrategy(SpawnStrategy strategy, List<String> commandlineIdentifiers) {
      Preconditions.checkArgument(
          commandlineIdentifiers.size() >= 1, "At least one commandLineIdentifier must be given");
      for (String identifier : commandlineIdentifiers) {
        identifierToStrategy.put(identifier, strategy);
      }
      strategiesInRegistrationOrder.add(strategy);
      return this;
    }

    public Builder registerStrategy(SpawnStrategy strategy, String... commandlineIdentifiers) {
      return registerStrategy(strategy, ImmutableList.copyOf(commandlineIdentifiers));
    }

    /**
     * Instructs this collector to use the legacy description filter precedence, i.e. to prefer the
     * first regular expression filter that matches a spawn over any later registered filters.
     *
     *
The default behavior of this collector is to prefer the last registered description filter
     * over any previously registered matching filters.
     */
    public Builder useLegacyDescriptionFilterPrecedence() {
      legacyFilterIterationOrder = true;
      return this;
    }

    /**
     * Explicitly sets the identifiers of default strategies to use if a spawn matches no filters.
     *
     *
Note that if this method is not called on the builder, all registered strategies are
     * considered default strategies, in registration order. See also the {@linkplain Builder class
     * documentation}.
     */
    public Builder setDefaultStrategies(List<String> defaultStrategies) {
      // Ensure there are actual strategies and the contents are not empty.
      Preconditions.checkArgument(!defaultStrategies.isEmpty());
      Preconditions.checkArgument(
          defaultStrategies.stream().anyMatch(strategy -> !"".equals(strategy)));
      this.explicitDefaultStrategies = ImmutableList.copyOf(defaultStrategies);
      return this;
    }

    /**
     * Reset the default strategies (see {@link #setDefaultStrategies}) to the reverse of the order
     * they were registered in.
     */
    public Builder resetDefaultStrategies() {
      this.explicitDefaultStrategies = ImmutableList.of();
      return this;
    }

    /**
     * Sets the strategy names to use in the remote branch of dynamic execution for a given action
     * mnemonic.
     *
     *
During execution, each strategy is {@linkplain SpawnStrategy#canExec(Spawn,
     * ActionContextRegistry) asked} whether it can execute a given Spawn. The first strategy in the
     * list that says so will get the job.
     */
    public Builder addDynamicRemoteStrategiesByMnemonic(String mnemonic, List<String> strategies) {
      mnemonicToRemoteIdentifiers.put(mnemonic, strategies);
      return this;
    }

    /**
     * Sets the strategy names to use in the local branch of dynamic execution for a given action
     * mnemonic.
     *
     *
During execution, each strategy is {@linkplain SpawnStrategy#canExec(Spawn,
     * ActionContextRegistry) asked} whether it can execute a given Spawn. The first strategy in the
     * list that says so will get the job.
     */
    public Builder addDynamicLocalStrategiesByMnemonic(String mnemonic, List<String> strategies) {
      mnemonicToLocalIdentifiers.put(mnemonic, strategies);
      return this;
    }

    /**
     * Sets the commandline identifier of the strategy to be used when falling back from remote to
     * local execution.
     *
     *
Note that this is an optional setting, if not provided {@link
     * SpawnStrategyRegistry#getRemoteLocalFallbackStrategy()} will return {@code null}. If the
     * value is provided it must match the commandline identifier of a registered strategy
     * (at {@linkplain #build build} time).
     */
    public Builder setRemoteLocalFallbackStrategyIdentifier(String commandlineIdentifier) {
      this.remoteLocalFallbackStrategyIdentifier = commandlineIdentifier;
      return this;
    }

    /**
     * Finalizes the construction of the registry.
     *
     * @throws AbruptExitException if a strategy command-line identifier was used in a filter or the
     *     default strategies but no strategy for that identifier was registered
     */
    public SpawnStrategyRegistry build() throws AbruptExitException {
      List<FilterAndIdentifiers> orderedFilterAndIdentifiers = filterAndIdentifiers;

      if (!legacyFilterIterationOrder) {
        orderedFilterAndIdentifiers = Lists.reverse(filterAndIdentifiers);
      }

      ListMultimap<RegexFilter, SpawnStrategy> filterToStrategies = LinkedListMultimap.create();
      for (FilterAndIdentifiers filterAndIdentifier : orderedFilterAndIdentifiers) {
        RegexFilter filter = filterAndIdentifier.filter();
        filterToStrategies.putAll(filter, toStrategies(filterAndIdentifier.identifiers(), filter));
      }

      ImmutableListMultimap.Builder<String, SpawnStrategy> mnemonicToStrategies =
          new ImmutableListMultimap.Builder<>();
      for (Map.Entry<String, List<String>> entry : mnemonicToIdentifiers.entrySet()) {
        mnemonicToStrategies.putAll(
            entry.getKey(), toStrategies(entry.getValue(), "mnemonic " + entry.getKey()));
      }

      ImmutableListMultimap.Builder<String, SandboxedSpawnStrategy> mnemonicToLocalStrategies =
          new ImmutableListMultimap.Builder<>();
      for (Map.Entry<String, List<String>> entry : mnemonicToLocalIdentifiers.entrySet()) {
        mnemonicToLocalStrategies.putAll(
            entry.getKey(),
            toSandboxedStrategies(entry.getValue(), "local mnemonic " + entry.getKey()));
      }

      ImmutableListMultimap.Builder<String, SandboxedSpawnStrategy> mnemonicToRemoteStrategies =
          new ImmutableListMultimap.Builder<>();
      for (Map.Entry<String, List<String>> entry : mnemonicToRemoteIdentifiers.entrySet()) {
        mnemonicToRemoteStrategies.putAll(
            entry.getKey(),
            toSandboxedStrategies(entry.getValue(), "remote mnemonic " + entry.getKey()));
      }

      AbstractSpawnStrategy remoteLocalFallbackStrategy = null;
      if (remoteLocalFallbackStrategyIdentifier != null) {
        SpawnStrategy strategy =
            toStrategy("remote fallback strategy", remoteLocalFallbackStrategyIdentifier);
        if (!(strategy instanceof AbstractSpawnStrategy)) {
          // TODO(schmitt): Check if all strategies can use the same base and remove check if so.
          throw createExitException(
              String.format(
                  "'%s' was requested for the remote fallback strategy but is not an"
                      + " abstract spawn strategy (which is required for remote"
                      + " fallback execution).",
                  strategy.getClass().getSimpleName()),
              Code.REMOTE_FALLBACK_STRATEGY_NOT_ABSTRACT_SPAWN);
        }

        remoteLocalFallbackStrategy = (AbstractSpawnStrategy) strategy;
      }

      ImmutableList<? extends SpawnStrategy> defaultStrategies;
      if (explicitDefaultStrategies.isEmpty()) {
        // Use the strategies as registered, in reverse order.
        defaultStrategies = ImmutableList.copyOf(Lists.reverse(strategiesInRegistrationOrder));
      } else {
        defaultStrategies = toStrategies(explicitDefaultStrategies, "default strategies");
      }

      return new SpawnStrategyRegistry(
          mnemonicToStrategies.build(),
          ImmutableListMultimap.copyOf(filterToStrategies),
          defaultStrategies,
          mnemonicToRemoteStrategies.build(),
          mnemonicToLocalStrategies.build(),
          remoteLocalFallbackStrategy);
    }

    private ImmutableList<? extends SpawnStrategy> toStrategies(
        List<String> identifiers, Object requestName) throws AbruptExitException {
      ImmutableList.Builder<SpawnStrategy> strategies = ImmutableList.builder();
      for (String identifier : identifiers) {
        if (identifier.isEmpty()) {
          continue;
        }
        strategies.add(toStrategy(requestName, identifier));
      }
      return strategies.build();
    }

    private SpawnStrategy toStrategy(Object requestName, String identifier)
        throws AbruptExitException {
      SpawnStrategy strategy = identifierToStrategy.get(identifier);
      if (strategy == null) {
        throw createExitException(
            String.format(
                "'%s' was requested for %s but no strategy with that identifier was registered. "
                    + "Valid values are: [%s]",
                identifier, requestName, Joiner.on(", ").join(identifierToStrategy.keySet())),
            Code.STRATEGY_NOT_FOUND);
      }
      return strategy;
    }

    private Iterable<? extends SandboxedSpawnStrategy> toSandboxedStrategies(
        List<String> identifiers, Object requestName) throws AbruptExitException {
      Iterable<? extends SpawnStrategy> strategies = toStrategies(identifiers, requestName);
      for (SpawnStrategy strategy : strategies) {
        if (!(strategy instanceof SandboxedSpawnStrategy)) {
          throw createExitException(
              String.format(
                  "'%s' was requested for %s but is not a sandboxed strategy (which is required for"
                      + " dynamic execution).",
                  strategy.getClass().getSimpleName(), requestName),
              Code.DYNAMIC_STRATEGY_NOT_SANDBOXED);
        }
      }

      @SuppressWarnings("unchecked") // Each element of the iterable was checked to fulfil this.
      Iterable<? extends SandboxedSpawnStrategy> sandboxedStrategies =
          (Iterable<? extends SandboxedSpawnStrategy>) strategies;
      return sandboxedStrategies;
    }
  }

  private static AbruptExitException createExitException(String message, Code detailedCode) {
    return new AbruptExitException(
        DetailedExitCode.of(
            FailureDetail.newBuilder()
                .setMessage(message)
                .setExecutionOptions(
                    FailureDetails.ExecutionOptions.newBuilder().setCode(detailedCode))
                .build()));
  }

  @AutoValue
  abstract static class FilterAndIdentifiers {

    abstract RegexFilter filter();

    abstract ImmutableList<String> identifiers();
  }
}

{'repo_name': 'bazelbuild/bazel', 'stars': '15030', 'repo_language': 'Java', 'file_name': 'BUILD', 'mime_type': 'text/plain', 'hash': 8682481748782727849, 'source_dataset': 'data'}


// RUN: %{ispc} %s --target=avx2-i32x4 --nowrap -O0 --emit-llvm-text -o - | FileCheck %s
// REQUIRES: X86_ENABLED
// CHECK: [[PRTARG_PTR_BITCAST:%[a-zA-Z0-9_.]+]] = bitcast [1 x i8*]*  [[PRTARG_PTR:%[a-zA-Z0-9_.]+]] to i8**
// CHECK: [[PRTARG_BITCAST:%[a-zA-Z0-9_.]+]] = bitcast <4 x i32>* {{%[a-zA-Z0-9_.]+}} to i8*
// CHECK: [[SCT_OFF:%[a-zA-Z0-9_.]+]] = getelementptr [1 x i8*], [1 x i8*]* [[PRTARG_PTR]], i32 0, i32 0
// CHECK: store i8* [[PRTARG_BITCAST]], i8** [[SCT_OFF]]
// CHECK: __do_print(i8* {{%[a-zA-Z0-9_.]+}}, i8* {{%[a-zA-Z0-9_.]+}}, i32 4, i64 {{%[a-zA-Z0-9_.]+}}, i8** [[PRTARG_PTR_BITCAST]])
void foo(bool bool_var) {
    print("\n bool_var = %\n", bool_var);
}

{'repo_name': 'ispc/ispc', 'stars': '1599', 'repo_language': 'C++', 'file_name': 'FixWindowsPath.cmake', 'mime_type': 'text/plain', 'hash': -2987120439431734622, 'source_dataset': 'data'}


/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/accountsMappers";
import * as Parameters from "../models/parameters";
import { AzureNetAppFilesManagementClientContext } from "../azureNetAppFilesManagementClientContext";

/** Class representing a Accounts. */
export class Accounts {
  private readonly client: AzureNetAppFilesManagementClientContext;

  /**
   * Create a Accounts.
   * @param {AzureNetAppFilesManagementClientContext} client Reference to the service client.
   */
  constructor(client: AzureNetAppFilesManagementClientContext) {
    this.client = client;
  }

  /**
   * List and describe all NetApp accounts in the resource group.
   * @summary Describe all NetApp Accounts in a resource group
   * @param resourceGroupName The name of the resource group.
   * @param [options] The optional parameters
   * @returns Promise<Models.AccountsListResponse>
   */
  list(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.AccountsListResponse>;
  /**
   * @param resourceGroupName The name of the resource group.
   * @param callback The callback
   */
  list(resourceGroupName: string, callback: msRest.ServiceCallback<Models.NetAppAccountList>): void;
  /**
   * @param resourceGroupName The name of the resource group.
   * @param options The optional parameters
   * @param callback The callback
   */
  list(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetAppAccountList>): void;
  list(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetAppAccountList>, callback?: msRest.ServiceCallback<Models.NetAppAccountList>): Promise<Models.AccountsListResponse> {
    return this.client.sendOperationRequest(
      {
        resourceGroupName,
        options
      },
      listOperationSpec,
      callback) as Promise<Models.AccountsListResponse>;
  }

  /**
   * Get the NetApp account
   * @summary Describe a NetApp Account
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param [options] The optional parameters
   * @returns Promise<Models.AccountsGetResponse>
   */
  get(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<Models.AccountsGetResponse>;
  /**
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param callback The callback
   */
  get(resourceGroupName: string, accountName: string, callback: msRest.ServiceCallback<Models.NetAppAccount>): void;
  /**
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param options The optional parameters
   * @param callback The callback
   */
  get(resourceGroupName: string, accountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetAppAccount>): void;
  get(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetAppAccount>, callback?: msRest.ServiceCallback<Models.NetAppAccount>): Promise<Models.AccountsGetResponse> {
    return this.client.sendOperationRequest(
      {
        resourceGroupName,
        accountName,
        options
      },
      getOperationSpec,
      callback) as Promise<Models.AccountsGetResponse>;
  }

  /**
   * Create or update the specified NetApp account within the resource group
   * @summary Create or update a NetApp account
   * @param body NetApp Account object supplied in the body of the operation.
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param [options] The optional parameters
   * @returns Promise<Models.AccountsCreateOrUpdateResponse>
   */
  createOrUpdate(body: Models.NetAppAccount, resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<Models.AccountsCreateOrUpdateResponse> {
    return this.beginCreateOrUpdate(body,resourceGroupName,accountName,options)
      .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.AccountsCreateOrUpdateResponse>;
  }

  /**
   * Delete the specified NetApp account
   * @summary Delete a NetApp account
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param [options] The optional parameters
   * @returns Promise<msRest.RestResponse>
   */
  deleteMethod(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
    return this.beginDeleteMethod(resourceGroupName,accountName,options)
      .then(lroPoller => lroPoller.pollUntilFinished());
  }

  /**
   * Patch the specified NetApp account
   * @summary Update a NetApp account
   * @param body NetApp Account object supplied in the body of the operation.
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param [options] The optional parameters
   * @returns Promise<Models.AccountsUpdateResponse>
   */
  update(body: Models.NetAppAccountPatch, resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<Models.AccountsUpdateResponse> {
    return this.beginUpdate(body,resourceGroupName,accountName,options)
      .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.AccountsUpdateResponse>;
  }

  /**
   * Create or update the specified NetApp account within the resource group
   * @summary Create or update a NetApp account
   * @param body NetApp Account object supplied in the body of the operation.
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param [options] The optional parameters
   * @returns Promise<msRestAzure.LROPoller>
   */
  beginCreateOrUpdate(body: Models.NetAppAccount, resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
    return this.client.sendLRORequest(
      {
        body,
        resourceGroupName,
        accountName,
        options
      },
      beginCreateOrUpdateOperationSpec,
      options);
  }

  /**
   * Delete the specified NetApp account
   * @summary Delete a NetApp account
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param [options] The optional parameters
   * @returns Promise<msRestAzure.LROPoller>
   */
  beginDeleteMethod(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
    return this.client.sendLRORequest(
      {
        resourceGroupName,
        accountName,
        options
      },
      beginDeleteMethodOperationSpec,
      options);
  }

  /**
   * Patch the specified NetApp account
   * @summary Update a NetApp account
   * @param body NetApp Account object supplied in the body of the operation.
   * @param resourceGroupName The name of the resource group.
   * @param accountName The name of the NetApp account
   * @param [options] The optional parameters
   * @returns Promise<msRestAzure.LROPoller>
   */
  beginUpdate(body: Models.NetAppAccountPatch, resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
    return this.client.sendLRORequest(
      {
        body,
        resourceGroupName,
        accountName,
        options
      },
      beginUpdateOperationSpec,
      options);
  }
}

// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
  httpMethod: "GET",
  path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts",
  urlParameters: [
    Parameters.subscriptionId,
    Parameters.resourceGroupName
  ],
  queryParameters: [
    Parameters.apiVersion
  ],
  headerParameters: [
    Parameters.acceptLanguage
  ],
  responses: {
    200: {
      bodyMapper: Mappers.NetAppAccountList
    },
    default: {
      bodyMapper: Mappers.CloudError
    }
  },
  serializer
};

const getOperationSpec: msRest.OperationSpec = {
  httpMethod: "GET",
  path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}",
  urlParameters: [
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.accountName
  ],
  queryParameters: [
    Parameters.apiVersion
  ],
  headerParameters: [
    Parameters.acceptLanguage
  ],
  responses: {
    200: {
      bodyMapper: Mappers.NetAppAccount
    },
    default: {
      bodyMapper: Mappers.CloudError
    }
  },
  serializer
};

const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
  httpMethod: "PUT",
  path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}",
  urlParameters: [
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.accountName
  ],
  queryParameters: [
    Parameters.apiVersion
  ],
  headerParameters: [
    Parameters.acceptLanguage
  ],
  requestBody: {
    parameterPath: "body",
    mapper: {
      ...Mappers.NetAppAccount,
      required: true
    }
  },
  responses: {
    200: {
      bodyMapper: Mappers.NetAppAccount
    },
    201: {
      bodyMapper: Mappers.NetAppAccount
    },
    202: {},
    default: {
      bodyMapper: Mappers.CloudError
    }
  },
  serializer
};

const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
  httpMethod: "DELETE",
  path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}",
  urlParameters: [
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.accountName
  ],
  queryParameters: [
    Parameters.apiVersion
  ],
  headerParameters: [
    Parameters.acceptLanguage
  ],
  responses: {
    202: {},
    204: {},
    default: {
      bodyMapper: Mappers.CloudError
    }
  },
  serializer
};

const beginUpdateOperationSpec: msRest.OperationSpec = {
  httpMethod: "PATCH",
  path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}",
  urlParameters: [
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.accountName
  ],
  queryParameters: [
    Parameters.apiVersion
  ],
  headerParameters: [
    Parameters.acceptLanguage
  ],
  requestBody: {
    parameterPath: "body",
    mapper: {
      ...Mappers.NetAppAccountPatch,
      required: true
    }
  },
  responses: {
    200: {
      bodyMapper: Mappers.NetAppAccount
    },
    201: {
      bodyMapper: Mappers.NetAppAccount
    },
    202: {},
    default: {
      bodyMapper: Mappers.CloudError
    }
  },
  serializer
};

{'repo_name': 'Azure/azure-sdk-for-js', 'stars': '574', 'repo_language': 'TypeScript', 'file_name': 'identity.api.md', 'mime_type': 'text/x-java', 'hash': 6151328080478447133, 'source_dataset': 'data'}


// Aseprite
// Copyright (C) 2001-2015  David Capello
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "app/commands/command.h"
#include "app/context.h"
#include "app/context_access.h"
#include "app/document.h"
#include "app/launcher.h"

namespace app {

class OpenInFolderCommand : public Command {
public:
  OpenInFolderCommand();
  Command* clone() const override { return new OpenInFolderCommand(*this); }

protected:
  bool onEnabled(Context* context) override;
  void onExecute(Context* context) override;
};

OpenInFolderCommand::OpenInFolderCommand()
  : Command("OpenInFolder",
            "Open In Folder",
            CmdUIOnlyFlag)
{
}

bool OpenInFolderCommand::onEnabled(Context* context)
{
  const ContextReader reader(context);
  return
    reader.document() &&
    reader.document()->isAssociatedToFile();
}

void OpenInFolderCommand::onExecute(Context* context)
{
  launcher::open_folder(context->activeDocument()->filename());
}

Command* CommandFactory::createOpenInFolderCommand()
{
  return new OpenInFolderCommand;
}

} // namespace app

{'repo_name': 'LibreSprite/LibreSprite', 'stars': '795', 'repo_language': 'C++', 'file_name': 'modp_b64_data.h', 'mime_type': 'text/x-c', 'hash': -2005535529746962561, 'source_dataset': 'data'}


module github.com/grpc-ecosystem/go-grpc-middleware

require (
	github.com/go-kit/kit v0.9.0
	github.com/go-logfmt/logfmt v0.4.0 // indirect
	github.com/go-stack/stack v1.8.0 // indirect
	github.com/gogo/protobuf v1.2.1
	github.com/golang/protobuf v1.3.2
	github.com/opentracing/opentracing-go v1.1.0
	github.com/pkg/errors v0.8.1 // indirect
	github.com/sirupsen/logrus v1.4.2
	github.com/stretchr/testify v1.4.0
	go.uber.org/atomic v1.4.0 // indirect
	go.uber.org/multierr v1.1.0 // indirect
	go.uber.org/zap v1.10.0
	golang.org/x/net v0.0.0-20190311183353-d8887717615a
	golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be
	google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 // indirect
	google.golang.org/grpc v1.19.0
)

go 1.13

{'repo_name': 'docker/cli', 'stars': '2265', 'repo_language': 'Go', 'file_name': 'docker_windows.go', 'mime_type': 'text/plain', 'hash': 264467541206548760, 'source_dataset': 'data'}


namespace WmiExplorer.Forms
{
    partial class Form_Update
    {
        /// <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.richTextBoxUpdate = new System.Windows.Forms.RichTextBox();
            this.buttonCancelHidden = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // richTextBoxUpdate
            //
            this.richTextBoxUpdate.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.richTextBoxUpdate.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.richTextBoxUpdate.Cursor = System.Windows.Forms.Cursors.IBeam;
            this.richTextBoxUpdate.Location = new System.Drawing.Point(12, 12);
            this.richTextBoxUpdate.Name = "richTextBoxUpdate";
            this.richTextBoxUpdate.ReadOnly = true;
            this.richTextBoxUpdate.Size = new System.Drawing.Size(471, 156);
            this.richTextBoxUpdate.TabIndex = 0;
            this.richTextBoxUpdate.Text = "";
            this.richTextBoxUpdate.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBoxUpdate_LinkClicked);
            //
            // buttonCancelHidden
            //
            this.buttonCancelHidden.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.buttonCancelHidden.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.buttonCancelHidden.Location = new System.Drawing.Point(193, 174);
            this.buttonCancelHidden.Name = "buttonCancelHidden";
            this.buttonCancelHidden.Size = new System.Drawing.Size(100, 25);
            this.buttonCancelHidden.TabIndex = 1;
            this.buttonCancelHidden.Text = "OK";
            this.buttonCancelHidden.UseVisualStyleBackColor = true;
            this.buttonCancelHidden.Click += new System.EventHandler(this.button1_Click);
            //
            // Form_Update
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            this.AutoSize = true;
            this.CancelButton = this.buttonCancelHidden;
            this.ClientSize = new System.Drawing.Size(484, 211);
            this.Controls.Add(this.richTextBoxUpdate);
            this.Controls.Add(this.buttonCancelHidden);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Form_Update";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "WMI Explorer Update";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.RichTextBox richTextBoxUpdate;
        private System.Windows.Forms.Button buttonCancelHidden;
    }
}

{'repo_name': 'vinaypamnani/wmie2', 'stars': '396', 'repo_language': 'C#', 'file_name': 'Resources.Designer.cs', 'mime_type': 'text/plain', 'hash': -4584814096290124058, 'source_dataset': 'data'}


How to use
----------

To embed the player in your web page, use the following XHTML syntax:

---------------------------------------------------------------------------
<object width="0" height="0" type="application/x-shockwave-flash" data="asap.swf" id="asap">
    <param name="movie" value="asap.swf" />
    <param name="FlashVars" value="file=File.sap" />
</object>
---------------------------------------------------------------------------

(tested with Internet Explorer 8, Firefox 3.5 and Chrome 3.0).

The player will play the specified file. It doesn't display anything.

The player understands the following parameters (in ampersand-separated `FlashVars`):

- `file` - URL of the file to play
- `song` - zero-based subsong number
- `defaultPlaybackTime` - playback time for songs with unspecified duration,
  in the `"mm:ss.xxx"` format
- `loopPlaybackTime` - playback time for songs marked as looping
  (use `"ONCE"` to stop playback when the loop starts)

The player contains the following methods that can be called from JavaScript:

- `setPlaybackTime(defaultPlaybackTime : String, loopPlaybackTime : String) : void` - sets
  playback times (see above)
- `asapPlay(filename : String, song : int = -1) : void` - plays the specified song (-1 for default)
- `asapStop() : void` - stops playback

{'repo_name': 'quarnster/boxeebox-xbmc', 'stars': '117', 'repo_language': 'C++', 'file_name': 'strings.po', 'mime_type': 'text/x-po', 'hash': -8052892941114296329, 'source_dataset': 'data'}


//  Copyright (c) 2017-2018 Uber Technologies, Inc.
//
// 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.

package handlers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gorilla/mux"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/uber/aresdb/controller/models"
	mutatorMocks "github.com/uber/aresdb/controller/mutators/mocks"
	metaCom "github.com/uber/aresdb/metastore/common"
	"go.uber.org/zap"
)

func TestConfigHandler(t *testing.T) {
	var testServer *httptest.Server

	testJob := models.JobConfig{
		Name:    "demand",
		Version: 0,
		AresTableConfig: models.TableConfig{
			Name: "demand_table",
		},
		StreamingConfig: models.KafkaConfig{
			Topic:   "demand_topic1",
			Cluster: "demand_cluster",
		},
	}

	testSchema := metaCom.Table{
		Name: "",
		Columns: []metaCom.Column{
			{
				Name: "col1",
				Type: "Int32",
			},
		},
	}
	logger, _ := zap.NewDevelopment()
	sugaredLogger := logger.Sugar()

	t.Run("Should work for GetJob endpoint", func(t *testing.T) {
		mockJobMutator := mutatorMocks.JobMutator{}
		mockSchemaMutator := mutatorMocks.TableSchemaMutator{}
		p := ConfigHandlerParams{
			Logger:        sugaredLogger,
			JobMutator:    &mockJobMutator,
			SchemaMutator: &mockSchemaMutator,
		}

		jobHandler := NewConfigHandler(p)
		testRouter := mux.NewRouter()
		jobHandler.Register(testRouter.PathPrefix("/config").Subrouter())
		testServer = httptest.NewUnstartedServer(testRouter)
		testServer.Start()

		mockJobMutator.On("GetJob", "ns1", "job1").Return(testJob, nil)
		mockSchemaMutator.On("GetTable", "ns1", "demand_table").Return(&testSchema, nil)
		hostPort := testServer.Listener.Addr().String()
		resp, err := http.Get(fmt.Sprintf("http://%s/config/ns1/jobs/job1", hostPort))
		assert.NoError(t, err)
		assert.Equal(t, http.StatusOK, resp.StatusCode)
		testServer.Close()
	})

	t.Run("Should work for GetJobs request", func(t *testing.T) {
		mockJobMutator := mutatorMocks.JobMutator{}
		mockSchemaMutator := mutatorMocks.TableSchemaMutator{}
		p := ConfigHandlerParams{
			Logger:        sugaredLogger,
			JobMutator:    &mockJobMutator,
			SchemaMutator: &mockSchemaMutator,
		}

		jobHandler := NewConfigHandler(p)
		testRouter := mux.NewRouter()
		jobHandler.Register(testRouter.PathPrefix("/config").Subrouter())
		testServer = httptest.NewUnstartedServer(testRouter)
		testServer.Start()

		mockJobMutator.On("GetJobs", "ns1").Return([]models.JobConfig{testJob}, nil)
		mockSchemaMutator.On("GetTable", "ns1", "demand_table").Return(&testSchema, nil)
		hostPort := testServer.Listener.Addr().String()
		resp, err := http.Get(fmt.Sprintf("http://%s/config/ns1/jobs", hostPort))
		assert.NoError(t, err)
		assert.Equal(t, http.StatusOK, resp.StatusCode)
		testServer.Close()
	})

	t.Run("Should work for DeletaJob request", func(t *testing.T) {
		mockJobMutator := mutatorMocks.JobMutator{}
		p := ConfigHandlerParams{
			Logger:     sugaredLogger,
			JobMutator: &mockJobMutator,
		}

		jobHandler := NewConfigHandler(p)
		testRouter := mux.NewRouter()
		jobHandler.Register(testRouter.PathPrefix("/config").Subrouter())
		testServer = httptest.NewUnstartedServer(testRouter)
		testServer.Start()
		mockJobMutator.On("DeleteJob", "ns1", "job1").Return(nil)
		hostPort := testServer.Listener.Addr().String()
		req, _ := http.NewRequest(http.MethodDelete, fmt.Sprintf("http://%s/config/ns1/jobs/%s", hostPort, "job1"), &bytes.Buffer{})
		resp, err := http.DefaultClient.Do(req)
		assert.NoError(t, err)
		assert.Equal(t, http.StatusOK, resp.StatusCode)
		testServer.Close()
	})

	t.Run("Should work for UpdateJob request", func(t *testing.T) {
		mockJobMutator := mutatorMocks.JobMutator{}
		p := ConfigHandlerParams{
			Logger:     sugaredLogger,
			JobMutator: &mockJobMutator,
		}

		jobHandler := NewConfigHandler(p)
		testRouter := mux.NewRouter()
		jobHandler.Register(testRouter.PathPrefix("/config").Subrouter())
		testServer = httptest.NewUnstartedServer(testRouter)
		testServer.Start()
		testJobBytes, _ := json.Marshal(testJob)

		mockJobMutator.On("UpdateJob", "ns1", mock.Anything).Return(nil)
		hostPort := testServer.Listener.Addr().String()
		req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("http://%s/config/ns1/jobs/%s", hostPort, "job1"), bytes.NewBuffer(testJobBytes))
		resp, err := http.DefaultClient.Do(req)
		assert.NoError(t, err)
		assert.Equal(t, http.StatusOK, resp.StatusCode)
		testServer.Close()
	})

	t.Run("Should work for AddJob request", func(t *testing.T) {
		mockJobMutator := mutatorMocks.JobMutator{}
		p := ConfigHandlerParams{
			Logger:     sugaredLogger,
			JobMutator: &mockJobMutator,
		}

		jobHandler := NewConfigHandler(p)
		testRouter := mux.NewRouter()
		jobHandler.Register(testRouter.PathPrefix("/config").Subrouter())
		testServer = httptest.NewUnstartedServer(testRouter)
		testServer.Start()
		jobBytes, _ := json.Marshal(testJob)

		mockJobMutator.On("AddJob", "ns1", mock.Anything).Return(nil)
		hostPort := testServer.Listener.Addr().String()
		resp, err := http.Post(fmt.Sprintf("http://%s/config/ns1/jobs", hostPort), "application/json", bytes.NewBuffer(jobBytes))
		assert.NoError(t, err)
		assert.Equal(t, http.StatusOK, resp.StatusCode)
		testServer.Close()
	})

	t.Run("Should work for GetHash request", func(t *testing.T) {
		mockJobMutator := mutatorMocks.JobMutator{}
		p := ConfigHandlerParams{
			Logger:     sugaredLogger,
			JobMutator: &mockJobMutator,
		}

		jobHandler := NewConfigHandler(p)
		testRouter := mux.NewRouter()
		jobHandler.Register(testRouter.PathPrefix("/config").Subrouter())
		testServer = httptest.NewUnstartedServer(testRouter)
		testServer.Start()
		mockJobMutator.On("GetHash", "ns1").Return("someHash", nil)
		hostPort := testServer.Listener.Addr().String()
		resp, err := http.Get(fmt.Sprintf("http://%s/config/ns1/hash", hostPort))
		assert.NoError(t, err)
		assert.Equal(t, http.StatusOK, resp.StatusCode)
		testServer.Close()
	})
}

{'repo_name': 'uber/aresdb', 'stars': '2360', 'repo_language': 'Go', 'file_name': 'config_test.go', 'mime_type': 'text/plain', 'hash': -886186803091258739, 'source_dataset': 'data'}


/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
package org.apache.pinot.plugin.ingestion.batch.spark;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.pinot.plugin.ingestion.batch.common.SegmentPushUtils;
import org.apache.pinot.spi.env.PinotConfiguration;
import org.apache.pinot.spi.filesystem.PinotFS;
import org.apache.pinot.spi.filesystem.PinotFSFactory;
import org.apache.pinot.spi.ingestion.batch.runner.IngestionJobRunner;
import org.apache.pinot.spi.ingestion.batch.spec.Constants;
import org.apache.pinot.spi.ingestion.batch.spec.PinotFSSpec;
import org.apache.pinot.spi.ingestion.batch.spec.SegmentGenerationJobSpec;
import org.apache.pinot.spi.utils.retry.AttemptsExceededException;
import org.apache.pinot.spi.utils.retry.RetriableOperationException;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;

public class SparkSegmentUriPushJobRunner implements IngestionJobRunner, Serializable {
  private SegmentGenerationJobSpec _spec;

  public SparkSegmentUriPushJobRunner() {
  }

  public SparkSegmentUriPushJobRunner(SegmentGenerationJobSpec spec) {
    init(spec);
  }

  @Override
  public void init(SegmentGenerationJobSpec spec) {
    _spec = spec;
    if (_spec.getPushJobSpec() == null) {
      throw new RuntimeException("Missing PushJobSpec");
    }
  }

  @Override
  public void run() {
    //init all file systems
    List<PinotFSSpec> pinotFSSpecs = _spec.getPinotFSSpecs();
    for (PinotFSSpec pinotFSSpec : pinotFSSpecs) {
      PinotFSFactory.register(pinotFSSpec.getScheme(), pinotFSSpec.getClassName(), new PinotConfiguration(pinotFSSpec));
    }

    //Get outputFS for writing output Pinot segments
    URI outputDirURI;
    try {
      outputDirURI = new URI(_spec.getOutputDirURI());
      if (outputDirURI.getScheme() == null) {
        outputDirURI = new File(_spec.getOutputDirURI()).toURI();
      }
    } catch (URISyntaxException e) {
      throw new RuntimeException("outputDirURI is not valid - '" + _spec.getOutputDirURI() + "'");
    }
    PinotFS outputDirFS = PinotFSFactory.create(outputDirURI.getScheme());

    //Get list of files to process
    String[] files;
    try {
      files = outputDirFS.listFiles(outputDirURI, true);
    } catch (IOException e) {
      throw new RuntimeException("Unable to list all files under outputDirURI - '" + outputDirURI + "'");
    }
    List<String> segmentUris = new ArrayList<>();
    for (String file : files) {
      URI uri = URI.create(file);
      if (uri.getPath().endsWith(Constants.TAR_GZ_FILE_EXT)) {
        URI updatedURI = SegmentPushUtils
            .generateSegmentTarURI(outputDirURI, uri, _spec.getPushJobSpec().getSegmentUriPrefix(),
                _spec.getPushJobSpec().getSegmentUriSuffix());
        segmentUris.add(updatedURI.toString());
      }
    }

    int pushParallelism = _spec.getPushJobSpec().getPushParallelism();
    if (pushParallelism < 1) {
      pushParallelism = segmentUris.size();
    }
    if (pushParallelism == 1) {
      // Push from driver
      try {
        SegmentPushUtils.sendSegmentUris(_spec, segmentUris);
      } catch (RetriableOperationException | AttemptsExceededException e) {
        throw new RuntimeException(e);
      }
    } else {
      JavaSparkContext sparkContext = JavaSparkContext.fromSparkContext(SparkContext.getOrCreate());
      JavaRDD<String> pathRDD = sparkContext.parallelize(segmentUris, pushParallelism);
      // Prevent using lambda expression in Spark to avoid potential serialization exceptions, use inner function instead.
      pathRDD.foreach(new VoidFunction<String>() {
        @Override
        public void call(String segmentUri)
            throws Exception {
          try {
            SegmentPushUtils.sendSegmentUris(_spec, Arrays.asList(segmentUri));
          } catch (RetriableOperationException | AttemptsExceededException e) {
            throw new RuntimeException(e);
          }
        }
      });
    }
  }
}

{'repo_name': 'apache/incubator-pinot', 'stars': '2609', 'repo_language': 'Java', 'file_name': 'read_model.md', 'mime_type': 'text/plain', 'hash': -6847417749260434432, 'source_dataset': 'data'}


/*
 * Copyright (C) 2011 Thomas Akehurst
 *
 * 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.
 */
package com.github.tomakehurst.wiremock.extension;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;

import java.util.Map;

import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;
import static com.google.common.collect.FluentIterable.from;
import static java.util.Arrays.asList;

public class ExtensionLoader {

    @SuppressWarnings("unchecked")
    public static <T> Map<String, T> loadExtension(String... classNames) {
        return (Map<String, T>) asMap(
                from(asList(classNames))
                        .transform(toClasses())
                        .transform(toExtensions()));
    }

    public static Map<String, Extension> load(String... classNames) {
        return loadExtension(classNames);
    }

    public static Map<String, Extension> asMap(Iterable<Extension> extensions) {
        return Maps.uniqueIndex(
                extensions,
                new Function<Extension, String>() {
                    public String apply(Extension extension) {
                        return extension.getName();
                    }
                });
    }

    public static Map<String, Extension> load(Class<? extends Extension>... classes) {
        return asMap(from(asList(classes)).transform(toExtensions()));
    }

    private static Function<Class<? extends Extension>, Extension> toExtensions() {
        return new Function<Class<? extends Extension>, Extension>() {
            @SuppressWarnings("unchecked")
            public Extension apply(Class<? extends Extension> extensionClass) {
                try {
                    return extensionClass.newInstance();
                } catch (Exception e) {
                    return throwUnchecked(e, Extension.class);
                }

            }
        };
    }

    private static Function<String, Class<? extends Extension>> toClasses() {
        return new Function<String, Class<? extends Extension>>() {
            @SuppressWarnings("unchecked")
            public Class<? extends Extension> apply(String className) {
                try {
                    return (Class<? extends Extension>) Class.forName(className);
                } catch (ClassNotFoundException e) {
                    return throwUnchecked(e, Class.class);
                }
            }
        };
    }

    public static <T extends Extension> Predicate<Map.Entry<String, Extension>> valueAssignableFrom(final Class<T> extensionType) {
        return new Predicate<Map.Entry<String, Extension>>() {
            public boolean apply(Map.Entry<String, Extension> input) {
                return extensionType.isAssignableFrom(input.getValue().getClass());
            }
        };
    }
}

{'repo_name': 'tomakehurst/wiremock', 'stars': '3947', 'repo_language': 'Java', 'file_name': 'index.html', 'mime_type': 'text/html', 'hash': 352963552309969705, 'source_dataset': 'data'}


TIMESTAMP = 1510338674
SHA256 (Log-Agent-1.003.tar.gz) = 90e94807ab8474be9604c2d13222b909fd7cf525fb648a2e65adc0b64bb317ac
SIZE (Log-Agent-1.003.tar.gz) = 55841

{'repo_name': 'pfsense/FreeBSD-ports', 'stars': '255', 'repo_language': 'None', 'file_name': 'distinfo', 'mime_type': 'text/plain', 'hash': -7132208203720657910, 'source_dataset': 'data'}


import React from "react";
import PropTypes from "prop-types";

const CardImage = ({ src, alt }) => (

);

CardImage.propTypes = {
  src: PropTypes.string.isRequired,
  // For accessibility. You can pass an empty string ("") in case you want
  // screen readers to ignore the image
  alt: PropTypes.string.isRequired,
};

export default CardImage;

{'repo_name': 'kubeapps/kubeapps', 'stars': '2143', 'repo_language': 'TypeScript', 'file_name': 'example-apprepo.yaml', 'mime_type': 'text/plain', 'hash': -8556710266451012527, 'source_dataset': 'data'}


"   Vim indent file
"   Language:	    Objective-C
"   Maintainer:	    Kazunobu Kuriyama <kazunobu.kuriyama@nifty.com>
"   Last Change:    2004 May 16
"

" Only load this indent file when no other was loaded.
if exists("b:did_indent")
    finish
endif
let b:did_indent = 1
setlocal cindent

" Set the function to do the work.
setlocal indentexpr=GetObjCIndent()

" To make a colon (:) suggest an indentation other than a goto/swich label,
setlocal indentkeys-=:
setlocal indentkeys+=<:>

" Only define the function once.
if exists("*GetObjCIndent")
    finish
endif

function s:GetWidth(line, regexp)
    let end = matchend(a:line, a:regexp)
    let width = 0
    let i = 0
    while i < end
	if a:line[i] != "\t"
	    let width = width + 1
	else
	    let width = width + &ts - (width % &ts)
	endif
	let i = i + 1
    endwhile
    return width
endfunction

function s:LeadingWhiteSpace(line)
    let end = strlen(a:line)
    let width = 0
    let i = 0
    while i < end
	let char = a:line[i]
	if char != " " && char != "\t"
	    break
	endif
	if char != "\t"
	    let width = width + 1
	else
	    let width = width + &ts - (width % &ts)
	endif
	let i = i + 1
    endwhile
    return width
endfunction

function GetObjCIndent()
    let theIndent = cindent(v:lnum)

    let prev_line = getline(v:lnum - 1)
    let cur_line = getline(v:lnum)

    if prev_line !~# ":" || cur_line !~# ":"
	return theIndent
    endif

    if prev_line !~# ";"
	let prev_colon_pos = s:GetWidth(prev_line, ":")
	let delta = s:GetWidth(cur_line, ":") - s:LeadingWhiteSpace(cur_line)
	let theIndent = prev_colon_pos - delta
    endif

    return theIndent
endfunction

{'repo_name': 'coolwanglu/vim.js', 'stars': '4392', 'repo_language': 'C', 'file_name': 'stock_icons.h', 'mime_type': 'text/plain', 'hash': -5313626844614106967, 'source_dataset': 'data'}


///////////////////////////////////////////////////////////////////////////////
//  Copyright Christopher Kormanyos 2007 - 2020.
//  Distributed under the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt
//  or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef MCAL_2011_10_20_H_
  #define MCAL_2011_10_20_H_

  #include <mcal_cpu.h>
  #include <mcal_eep.h>
  #include <mcal_gpt.h>
  #include <mcal_irq.h>
  #include <mcal_led.h>
  #include <mcal_port.h>
  #include <mcal_pwm.h>
  #include <mcal_ser.h>
  #include <mcal_spi.h>
  #include <mcal_wdg.h>

  static_assert(   (std::numeric_limits<mcal::gpt::value_type>::digits >= 64)
                && (std::numeric_limits<mcal::gpt::value_type>::is_integer == true)
                && (std::numeric_limits<mcal::gpt::value_type>::is_signed  == false),
                "The gpt value type must be an unsigned integer type having at least 64 bits.");

  namespace mcal
  {
    void init();
  }

#endif // MCAL_2011_10_20_H_

{'repo_name': 'ckormanyos/real-time-cpp', 'stars': '209', 'repo_language': 'C++', 'file_name': 'chapter01_01-001_led_program.cpp', 'mime_type': 'text/x-c++', 'hash': 7762720424974142663, 'source_dataset': 'data'}


# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mozillazg101@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

{'repo_name': 'mozillazg/python-pinyin', 'stars': '2709', 'repo_language': 'Python', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -8109924729139185155, 'source_dataset': 'data'}


package sdk.chat.ui.fragments;

import android.view.MenuItem;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.functions.Predicate;
import sdk.chat.core.dao.Thread;
import sdk.chat.core.events.NetworkEvent;
import sdk.chat.core.interfaces.ThreadType;
import sdk.chat.core.session.ChatSDK;
import sdk.chat.ui.R;
import sdk.chat.ui.utils.DialogUtils;
import sdk.chat.ui.utils.ToastHelper;
import sdk.guru.common.RX;

public class PrivateThreadsFragment extends ThreadsFragment {

    @Override
    protected Predicate<NetworkEvent> mainEventFilter() {
        return NetworkEvent.filterPrivateThreadsUpdated();
    }

    @Override
    public void initViews() {
        super.initViews();

        dm.add(getOnLongClickObservable().subscribe(thread -> DialogUtils.showToastDialog(getContext(), 0, R.string.alert_delete_thread, R.string.delete,
                R.string.cancel,  () -> {
                    dm.add(ChatSDK.thread().deleteThread(thread)
                            .observeOn(RX.main())
                            .subscribe(() -> {
                                clearData();
                                reloadData();
                            }, throwable -> ToastHelper.show(getContext(), throwable.getLocalizedMessage())));
                }, null)));
    }

    @Override
    protected Single<List<Thread>> getThreads() {
        return Single.defer(() -> {

            List<Thread> threads = ChatSDK.thread().getThreads(ThreadType.Private);

            if (ChatSDK.config().privateChatRoomLifetimeMinutes == 0) {
                return Single.just(threads);
            } else {
                // Do we need to filter the list to remove old chat rooms?
                long now = new Date().getTime();
                List<Thread> filtered = new ArrayList<>();
                for (Thread t : threads) {
                    if (t.getCreationDate() == null || now - t.getCreationDate().getTime() < TimeUnit.MINUTES.toMillis(ChatSDK.config().privateChatRoomLifetimeMinutes)) {
                        filtered.add(t);
                    }
                }
                return Single.just(filtered);
            }
        }).subscribeOn(RX.single());

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){

        /* Cant use switch in the library*/
        int id = item.getItemId();

        if (id == R.id.action_add) {
            ChatSDK.ui().startCreateThreadActivity(getContext());
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

{'repo_name': 'chat-sdk/chat-sdk-android', 'stars': '1277', 'repo_language': 'Java', 'file_name': 'NotificationBuilder.java', 'mime_type': 'text/x-java', 'hash': -3579016980177823724, 'source_dataset': 'data'}


CREATE STREAM INPUT (FOO ARRAY<STRING>) WITH (KAFKA_TOPIC='input_topic', VALUE_FORMAT='PROTOBUF', WRAP_SINGLE_VALUE=true);

`ROWKEY` STRING KEY, `FOO` ARRAY<STRING>

CREATE STREAM OUTPUT AS SELECT *
FROM INPUT INPUT
EMIT CHANGES

{'repo_name': 'confluentinc/ksql', 'stars': '3555', 'repo_language': 'Java', 'file_name': 'BasicCallbackHandler.java', 'mime_type': 'text/x-java', 'hash': -8529541636847465915, 'source_dataset': 'data'}


/*
 * OpenWolf GPL Source Code
 * Copyright (C) 2011 Dusan Jocic <dusanjocic@msn.com>
 *
 * ET: Legacy
 * Copyright (C) 2012-2018 ET:Legacy team <mail@etlegacy.com>
 *
 * This file is part of ET: Legacy - http://www.etlegacy.com
 *
 * ET: Legacy is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ET: Legacy is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ET: Legacy. If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, Wolfenstein: Enemy Territory GPL Source Code is also
 * subject to certain additional terms. You should have received a copy
 * of these additional terms immediately following the terms and conditions
 * of the GNU General Public License which accompanied the source code.
 * If not, please request a copy in writing from id Software at the address below.
 *
 * id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
 */
/**
 * @file htable.c
 * @brief
 *
 * @note This is FEATURE_IRC_CLIENT and FEATURE_IRC_SERVER only
 */

#include "htable.h"

/*=============================================*
 * Type definitions                            *
 *=============================================*/

/**
 * @struct listhead_t
 * @brief "List heads" - used to store various lists
 */
struct listhead_t
{
	struct listhead_t *previous;
	struct listhead_t *next;
};

/**
 * @def RESET_LIST
 * @brief Resets a list head
 */
#define RESET_LIST(LPTR) \
	((LPTR)->previous = (LPTR)->next = (LPTR))

/**
 * @struct tentry_t
 * @brief Table entry - used to store actual items
 */
struct tentry_t
{
	/// Entry in one of the table's sub-lists
	struct listhead_t loc_list;

	/// Entry in the table's main list
	struct listhead_t full_list;

	/// Cached hash value
	unsigned int hash;
};

/*
 * Function pointers
 */
typedef unsigned int ( *getkey_t )(const char *key);
typedef char * ( *keyfromentry_t )(struct tentry_t *entry, size_t key_offset);
typedef int ( *comparekey_t )(const char *k1, const char *k2);

/**
 * @struct hashtable_s
 * @brief Main hash table structure
 */
struct hashtable_s
{
	/// Actual size of the table
	size_t size;

	/// Table flags
	unsigned int flags;

	/// Item size
	size_t item_size;

	/// Key offset in an item
	size_t key_offset;

	/// Length of key (0 for pointer)
	size_t key_length;

	/// Functions
	getkey_t GetKey;
	keyfromentry_t KeyFromEntry;
	comparekey_t CompareKey;

	/// List of all items
	struct listhead_t all_items;
};

/**
 * @def TABLE_START
 * @brief Macro that finds the first list head after a table's main structure
 */
#define TABLE_START(TABLE) \
	((struct listhead_t *)(((char *)(TABLE)) + sizeof(struct hashtable_s)))

/*=============================================*
 * Internal functions prototypes               *
 *=============================================*/

/// Checks if a size is a prime number
static qboolean _HT_IsPrime(size_t n);

/// Finds the next higher prime number
static size_t _HT_NextPrime(size_t n);

/// Computes a string's hash key (case insensitive)
static unsigned int _HT_GetCIKey(const char *key);

/// Computes a string's hash key (case sensitive)
static unsigned int _HT_GetKey(const char *key);

/// Returns a table entry's key (in-table items, fixed size key)
static char *_HT_KeyFromEntryII(struct tentry_t *entry, size_t key_offset);

/// Returns a table entry's key (in-table items, pointer key)
static char *_HT_KeyFromEntryIP(struct tentry_t *entry, size_t key_offset);

/// Returns a table entry's key (external items, fixed size key)
static char *_HT_KeyFromEntryPI(struct tentry_t *entry, size_t key_offset);

/// Returns a table entry's key (external items, pointer key)
static char *_HT_KeyFromEntryPP(struct tentry_t *entry, size_t key_offset);

/// Allocate and initialise a table entry.
static struct tentry_t *_HT_CreateEntry(hashtable_t table, unsigned int hash, struct listhead_t *list_entry, const char *key);

/// Insert a table entry into a table's global list
static void _HT_InsertInGlobalList(hashtable_t table, struct tentry_t *t_entry, const char *key);

/*=============================================*
 * Hash table public functions                 *
 *=============================================*/

/**
 * @brief Hash table creation
 *
 * @param[in] size Size of the table (will be rounded up to the next
 *		      prime number)
 * @param[in] flags Combination of HT_FLAG_* for the table
 * @param[in] item_size	Size of the table's items
 * @param[in] key_offset Offset of the key in the table's items
 * @param[in] key_length Maximal length of the key in the table; if 0, the key
 *			  will be accessed as a pointer instead of an array
 */
hashtable_t HT_Create(
    size_t size,
    unsigned int flags,
    size_t item_size,
    size_t key_offset,
    size_t key_length
    )
{
	hashtable_t       table;
	size_t            real_size;
	struct listhead_t *t_item;

	// Allocate table
	real_size = _HT_NextPrime(size);
	table     = Z_Malloc(sizeof(struct hashtable_s) + real_size * sizeof(struct listhead_t));
	etl_assert(table);

	// Initialise main table fields
	table->size       = real_size;
	table->flags      = flags;
	table->item_size  = item_size;
	table->key_offset = key_offset;
	table->key_length = key_length;
	RESET_LIST(&table->all_items);

	// Set functions
	table->GetKey     = (flags & HT_FLAG_CASE) ? _HT_GetKey : _HT_GetCIKey;
	table->CompareKey = (flags & HT_FLAG_CASE) ? strcmp : Q_stricmp;   // Q_strcasecmp
	if ((flags & HT_FLAG_INTABLE) == 0)
	{
		table->KeyFromEntry = key_length ? _HT_KeyFromEntryPI : _HT_KeyFromEntryPP;
	}
	else
	{
		table->KeyFromEntry = key_length ? _HT_KeyFromEntryII : _HT_KeyFromEntryIP;
	}

	// Initialise table entries
	t_item = TABLE_START(table);
	while (real_size > 0)
	{
		RESET_LIST(t_item);
		t_item++;
		real_size--;
	}

	return table;
}

/**
 * @brief Hash table destruction
 * @param[in] table
 */
void HT_Destroy(hashtable_t table)
{
	qboolean          del_key;
	struct listhead_t *list_head;
	struct listhead_t *list_entry;
	struct tentry_t   *t_entry;

	del_key    = (table->key_length == 0 && (table->flags & (HT_FLAG_INTABLE | HT_FLAG_FREE)) != 0);
	list_head  = &(table->all_items);
	list_entry = list_head->next;
	while (list_entry != list_head)
	{
		t_entry    = (struct tentry_t *)(((char *) list_entry) - HT_OffsetOfField(struct tentry_t, full_list));
		list_entry = list_entry->next;

		if (del_key)
		{
			Z_Free(table->KeyFromEntry(t_entry, table->key_offset));
		}
		if ((table->flags & (HT_FLAG_INTABLE | HT_FLAG_FREE)) == HT_FLAG_FREE)
		{
			void **data = (void **)(((char *) t_entry) + sizeof(struct tentry_t));
			Z_Free(*data);
		}
		Z_Free(t_entry);
	}
	Z_Free(table);
}

/**
 * @brief Gets an item from the table.
 *
 * @param[in] table The hash table to access
 * @param[in] key The key to look up
 * @param[out] created Pointer to a boolean which will be set to true if
 *             the item was created; if NULL, no creation will take
 *             place
 */
void *HT_GetItem(
    hashtable_t table,
    const char *key,
    qboolean *created
    )
{
	unsigned int      hash;
	struct listhead_t *list_head;
	struct listhead_t *list_entry;
	struct tentry_t   *t_entry;
	void              *data;

	etl_assert(table->key_length == 0 || table->key_length >= strlen(key));

	// Try finding the item
	hash       = table->GetKey(key);
	list_head  = (TABLE_START(table) + (hash % table->size));
	list_entry = list_head->next;
	while (list_entry != list_head)
	{
		t_entry = ( struct tentry_t * ) list_entry;

		if (t_entry->hash > hash)
		{
			break;
		}

		if (t_entry->hash == hash)
		{
			char *item_key = table->KeyFromEntry(t_entry, table->key_offset);
			if (!table->CompareKey(key, item_key))
			{
				data = (void *)(((char *)t_entry) + sizeof(struct tentry_t));
				if (created != NULL)
				{
					*created = qfalse;
				}
				return (table->flags & HT_FLAG_INTABLE) ? data : (*(void **)data);
			}
		}

		list_entry = list_entry->next;
	}

	// Check if we can create the entry
	if (created == NULL)
	{
		return NULL;
	}

	// Create entry
	*created = qtrue;
	t_entry  = _HT_CreateEntry(table, hash, list_entry, key);

	// Initialise data
	data = (void *)(((char *)t_entry) + sizeof(struct tentry_t));
	if ((table->flags & HT_FLAG_INTABLE) == 0)
	{
		*(void **) data = Z_Malloc(table->item_size);
		data            = *(void **) data;
	}
	Com_Memset(data, 0, table->item_size);

	// Copy key
	if (table->key_length == 0)
	{
		char **key_ptr = (char **)(((char *) data) + table->key_offset);
		*key_ptr = Z_Malloc(strlen(key) + 1);
		strcpy(*key_ptr, key);
	}
	else
	{
		char *key_ptr = ((char *) data) + table->key_offset;
		strcpy(key_ptr, key);
	}

	return data;
}

/**
 * @brief Stores an item into the table
 *
 * @param[in] table	The hash table to add an item to
 * @param[in] item The item to add to the table
 * @param[in] allow_replacement	whether replacement of a previous item
 *			  is allowed
 *
 * @return The item that matched the specified key, or NULL if no item
 * using the same key existed
 *
 * @note Replacement behaviour varies greatly depending on the flags.
 * If the items are stored in-table, or if the table must free the
 * memory they use, a replacement will still return NULL, as the
 * memory will have been freed or reused.
 */
void *HT_PutItem(
    hashtable_t table,
    void *item,
    qboolean allow_replacement
    )
{
	void              *ret_val    = NULL;
	void              *prev_entry = NULL;
	const char        *insert_key;
	unsigned int      hash;
	struct listhead_t *list_head;
	struct listhead_t *list_entry;
	struct tentry_t   *t_entry = NULL;

	// Extract item key
	if (table->key_length)
	{
		insert_key = ((const char *) item) + table->key_offset;
	}
	else
	{
		insert_key = *(const char **)(((char *) item) + table->key_offset);
	}

	// Try finding an item with that key, or the new item's location
	hash       = table->GetKey(insert_key);
	list_head  = (TABLE_START(table) + (hash % table->size));
	list_entry = list_head->next;
	while (list_entry != list_head)
	{
		t_entry = ( struct tentry_t * ) list_entry;

		if (t_entry->hash > hash)
		{
			break;
		}

		if (t_entry->hash == hash)
		{
			const char *item_key = table->KeyFromEntry(t_entry, table->key_offset);
			int        cres      = table->CompareKey(insert_key, item_key);
			if (!cres)
			{
				prev_entry = (((char *)t_entry) + sizeof(struct tentry_t));
				ret_val    = (table->flags & HT_FLAG_INTABLE) ? prev_entry : (*(void **)prev_entry);
				if (!allow_replacement)
				{
					return ret_val;
				}
				break;
			}
			else if (cres > 0)
			{
				break;
			}
		}

		list_entry = list_entry->next;
	}

	if (ret_val != NULL)
	{
		// Delete previous item's key if it was a pointer and either
		// items are in-table or should be freed automatically
		if (table->key_length == 0 && (table->flags & (HT_FLAG_INTABLE | HT_FLAG_FREE)) != 0)
		{
			Z_Free(table->KeyFromEntry(t_entry, table->key_offset));
		}

		if ((table->flags & HT_FLAG_INTABLE) != 0)
		{
			// Copy item data
			Com_Memcpy(prev_entry, item, table->item_size);
			ret_val = NULL;
		}
		else
		{
			if ((table->flags & HT_FLAG_FREE) != 0)
			{
				// Free previous item
				Z_Free(ret_val);
				ret_val = NULL;
			}
			*(void **) prev_entry = item;
		}
	}
	else
	{
		void *data;

		t_entry = _HT_CreateEntry(table, hash, list_entry, insert_key);
		data    = (void *)(((char *)t_entry) + sizeof(struct tentry_t));
		if ((table->flags & HT_FLAG_INTABLE) != 0)
		{
			Com_Memcpy(data, item, table->item_size);
		}
		else
		{
			*(void **) data = item; // FIXME: never used
		}
	}

	return ret_val;
}

/**
 * @brief Deletes an item from the table
 *
 * @param[in] table The hash table from which an item is to be deleted
 * @param[in] key The key to delete
 * @param[out] found A pointer to a pointer which will be set to
 *			   the deleted item's value; may be NULL
 *
 * @return true if an item was deleted, false otherwise
 *
 * @note If the items are stored in-table or are freed automatically, then
 * the "found" parameter will always be ignored.
 */
qboolean HT_DeleteItem(
    hashtable_t table,
    const char *key,
    void **found
    )
{
	unsigned int      hash;
	struct listhead_t *list_head;
	struct listhead_t *list_entry;
	struct tentry_t   *t_entry = NULL;
	void              *data    = NULL;

	// Try finding the item
	hash       = table->GetKey(key);
	list_head  = (TABLE_START(table) + (hash % table->size));
	list_entry = list_head->next;
	while (list_entry != list_head)
	{
		t_entry = ( struct tentry_t * ) list_entry;

		if (t_entry->hash > hash)
		{
			break;
		}

		if (t_entry->hash == hash)
		{
			char *item_key = table->KeyFromEntry(t_entry, table->key_offset);
			if (!table->CompareKey(key, item_key))
			{
				data = (void *)(((char *)t_entry) + sizeof(struct tentry_t));
				data = (table->flags & HT_FLAG_INTABLE) ? data : (*(void **)data);
				break;
			}
		}

		list_entry = list_entry->next;
	}

	// Did we find it?
	if (data == NULL)
	{
		if (found != NULL)
		{
			*found = NULL;
		}
		return qfalse;
	}

	// Detach it from its lists
	t_entry->loc_list.previous->next  = t_entry->loc_list.next;
	t_entry->loc_list.next->previous  = t_entry->loc_list.previous;
	t_entry->full_list.previous->next = t_entry->full_list.next;
	t_entry->full_list.next->previous = t_entry->full_list.previous;

	// Delete key
	if (table->key_length == 0 && (table->flags & (HT_FLAG_INTABLE | HT_FLAG_FREE)) != 0)
	{
		Z_Free(table->KeyFromEntry(t_entry, table->key_offset));
	}

	// Delete item
	if ((table->flags & (HT_FLAG_INTABLE | HT_FLAG_FREE)) == HT_FLAG_FREE)
	{
		Z_Free(data);
	}

	// Delete entry
	Z_Free(t_entry);

	// Set found pointer
	if (found != NULL)
	{
		if ((table->flags & (HT_FLAG_INTABLE | HT_FLAG_FREE)) != 0)
		{
			data = NULL;
		}
		*found = data;
	}

	return qtrue;
}

/**
 * @brief Applies a function to all items in the table.
 *
 * @param[in] table	The hash table onto which the function is to be applied
 * @param[in] function Pointer to the function to apply
 * @param[in] data Extra data to pass as the function's second parameter
 *
 * @note The order in which the function is applied is either the insertion
 * order or, if the table has HT_FLAG_SORTED set, the increasing key
 * order.
 *
 * @note The function should return false if processing is to stop.
 */
void HT_Apply(
    hashtable_t table,
    ht_apply_funct function,
    void *data
    )
{
	struct listhead_t *list_head;
	struct listhead_t *list_entry;

	list_head  = &(table->all_items);
	list_entry = list_head->next;
	while (list_entry != list_head)
	{
		void *item;
		item       = ((char *) list_entry) - HT_OffsetOfField(struct tentry_t, full_list) + sizeof(struct tentry_t);
		list_entry = list_entry->next;

		if ((table->flags & HT_FLAG_INTABLE) == 0)
		{
			item = *(void **) item;
		}
		if (!function(item, data))
		{
			return;
		}
	}
}

/*=============================================*
 * Functions related to prime numbers          *
 *=============================================*/

/**
 * @brief _HT_IsPrime
 * @param[in] n
 * @return
 */
static qboolean _HT_IsPrime(size_t n)
{
	size_t temp;
	size_t nsq;
	size_t inc;

	if (n == 0)
	{
		return qfalse;
	}

	nsq = ceil(sqrt((double)n));
	for (inc = 1, temp = 2 ; temp <= nsq ; temp += inc)
	{
		if (n % temp == 0)
		{
			return qfalse;
		}
		if (temp == 3)
		{
			inc = 2;
		}
	}
	return qtrue;
}

/**
 * @brief _HT_NextPrime
 * @param[in] n
 * @return
 */
static size_t _HT_NextPrime(size_t n)
{
	size_t value = n;
	while (!_HT_IsPrime(value))
		value++;
	return value;
}

/*=============================================*
 * Key computation functions                   *
 *=============================================*/

/**
 * @brief _HT_GetCIKey
 * @param[in] key
 * @return
 */
static unsigned int _HT_GetCIKey(const char *key)
{
	const char   *current = key;
	unsigned int hash     = 111119;

	while (*current)
	{
		hash += (unsigned char)tolower(*current);
		hash += (hash << 10);
		hash ^= (hash >> 6);
		current++;
	}

	hash += (hash << 3);
	hash ^= (hash >> 11);
	hash += (hash << 15);

	return hash;
}

/**
 * @brief _HT_GetKey
 * @param[in] key
 * @return
 */
static unsigned int _HT_GetKey(const char *key)
{
	const char   *current = key;
	unsigned int hash     = 111119;

	while (*current)
	{
		hash += (unsigned char) *current;
		hash += (hash << 10);
		hash ^= (hash >> 6);
		current++;
	}

	hash += (hash << 3);
	hash ^= (hash >> 11);
	hash += (hash << 15);

	return hash;
}

/*=============================================*
 * Key retrieval                               *
 *=============================================*/

/**
 * @brief _HT_KeyFromEntryII
 * @param[in] entry
 * @param[in] key_offset
 * @return
 */
static char *_HT_KeyFromEntryII(struct tentry_t *entry, size_t key_offset)
{
	void *item_addr;

	item_addr = (void *)(((char *)entry) + sizeof(struct tentry_t));
	return (char *)(((char *)item_addr) + key_offset);
}

/**
 * @brief _HT_KeyFromEntryIP
 * @param[in] entry
 * @param[in] key_offset
 * @return
 */
static char *_HT_KeyFromEntryIP(struct tentry_t *entry, size_t key_offset)
{
	void *item_addr;

	item_addr = (void *)(((char *)entry) + sizeof(struct tentry_t));
	return *(char **)(((char *)item_addr) + key_offset);
}

/**
 * @brief _HT_KeyFromEntryPI
 * @param[in] entry
 * @param[in] key_offset
 * @return
 */
static char *_HT_KeyFromEntryPI(struct tentry_t *entry, size_t key_offset)
{
	void *item_addr;

	item_addr = *(void **)(((char *)entry) + sizeof(struct tentry_t));
	return (char *)(((char *)item_addr) + key_offset);
}

/**
 * @brief _HT_KeyFromEntryPP
 * @param[in] entry
 * @param[in] key_offset
 * @return
 */
static char *_HT_KeyFromEntryPP(struct tentry_t *entry, size_t key_offset)
{
	void *item_addr;

	item_addr = *(void **)(((char *)entry) + sizeof(struct tentry_t));
	return *(char **)(((char *)item_addr) + key_offset);
}

/*=============================================*
 * Other internal functions                    *
 *=============================================*/

/**
 * @brief _HT_CreateEntry
 * @param[in] table
 * @param[in] hash
 * @param[in,out] list_entry
 * @param[in] key
 * @return
 */
static struct tentry_t *_HT_CreateEntry(
    hashtable_t table,
    unsigned int hash,
    struct listhead_t *list_entry,
    const char *key)
{
	// Allocate new entry
	struct tentry_t *t_entry;
	size_t          entry_size = sizeof(struct tentry_t);

	entry_size   += (table->flags & HT_FLAG_INTABLE) ? table->item_size : sizeof(void *);
	t_entry       = Z_Malloc(entry_size);
	t_entry->hash = hash;

	// Add entry to local list
	t_entry->loc_list.previous = list_entry->previous;
	t_entry->loc_list.next     = list_entry;
	list_entry->previous       = t_entry->loc_list.previous->next = &(t_entry->loc_list);

	_HT_InsertInGlobalList(table, t_entry, key);

	return t_entry;
}

/**
 * @brief _HT_InsertInGlobalList
 * @param[in] table
 * @param[in,out] t_entry
 * @param[in] key
 */
static void _HT_InsertInGlobalList(hashtable_t table, struct tentry_t *t_entry, const char *key)
{
	if ((table->flags & HT_FLAG_SORTED) == 0)
	{
		// Append to global list
		t_entry->full_list.previous = table->all_items.previous;
		t_entry->full_list.next     = &(table->all_items);
		table->all_items.previous   = t_entry->full_list.previous->next = &(t_entry->full_list);
	}
	else
	{
		// Global list must be kept sorted, find insert location
		struct listhead_t *list_entry = table->all_items.next;

		while (list_entry != &(table->all_items))
		{
			struct tentry_t *ai_entry;
			const char      *ai_key;
			int             cres;

			ai_entry = (struct tentry_t *)(((char *) list_entry) - HT_OffsetOfField(struct tentry_t, full_list));
			ai_key   = table->KeyFromEntry(ai_entry, table->key_offset);
			cres     = table->CompareKey(ai_key, key);

			etl_assert(cres != 0);
			if (cres > 0)
			{
				break;
			}
			list_entry = list_entry->next;
		}
		t_entry->full_list.previous = list_entry->previous;
		t_entry->full_list.next     = list_entry;
		list_entry->previous        = t_entry->full_list.previous->next = &(t_entry->full_list);
	}
}

{'repo_name': 'etlegacy/etlegacy', 'stars': '107', 'repo_language': 'C', 'file_name': 'ETLBuildMod.cmake', 'mime_type': 'text/plain', 'hash': -7961755411919313419, 'source_dataset': 'data'}


/*
*
* Template Numerical Toolkit (TNT): Two-dimensional Fortran numerical array
*
* Mathematical and Computational Sciences Division
* National Institute of Technology,
* Gaithersburg, MD USA
*
*
* This software was developed at the National Institute of Standards and
* Technology (NIST) by employees of the Federal Government in the course
* of their official duties. Pursuant to title 17 Section 105 of the
* United States Code, this software is not subject to copyright protection
* and is in the public domain. NIST assumes no responsibility whatsoever for
* its use by other parties, and makes no guarantees, expressed or implied,
* about its quality, reliability, or any other characteristic.
*
*/

#ifndef TNT_FORTRAN_ARRAY2D_H
#define TNT_FORTRAN_ARRAY2D_H

#include <cstdlib>
#include <iostream>

#ifdef TNT_BOUNDS_CHECK
#include <assert.h>
#endif

#include "tnt_i_refvec.h"

namespace TNT
{

template <class T>
class Fortran_Array2D
{

  private:
  		i_refvec<T> v_;
		int m_;
		int n_;
		T* data_;

    	void initialize_(int n);
    	void copy_(T* p, const T*  q, int len);
    	void set_(T* begin,  T* end, const T& val);

  public:

    typedef         T   value_type;

	       Fortran_Array2D();
	       Fortran_Array2D(int m, int n);
	       Fortran_Array2D(int m, int n,  T *a);
	       Fortran_Array2D(int m, int n, const T &a);
    inline Fortran_Array2D(const Fortran_Array2D &A);
	inline Fortran_Array2D & operator=(const T &a);
	inline Fortran_Array2D & operator=(const Fortran_Array2D &A);
	inline Fortran_Array2D & ref(const Fortran_Array2D &A);
	       Fortran_Array2D copy() const;
		   Fortran_Array2D & inject(const Fortran_Array2D & A);
	inline T& operator()(int i, int j);
	inline const T& operator()(int i, int j) const ;
	inline int dim1() const;
	inline int dim2() const;
               ~Fortran_Array2D();

	/* extended interface */

	inline int ref_count() const;

};

template <class T>
Fortran_Array2D<T>::Fortran_Array2D() : v_(), m_(0), n_(0), data_(0) {}

template <class T>
Fortran_Array2D<T>::Fortran_Array2D(const Fortran_Array2D<T> &A) : v_(A.v_),
		m_(A.m_), n_(A.n_), data_(A.data_) {}

template <class T>
Fortran_Array2D<T>::Fortran_Array2D(int m, int n) : v_(m*n), m_(m), n_(n),
	data_(v_.begin()) {}

template <class T>
Fortran_Array2D<T>::Fortran_Array2D(int m, int n, const T &val) :
	v_(m*n), m_(m), n_(n), data_(v_.begin())
{
	set_(data_, data_+m*n, val);
}

template <class T>
Fortran_Array2D<T>::Fortran_Array2D(int m, int n, T *a) : v_(a),
	m_(m), n_(n), data_(v_.begin()) {}

template <class T>
inline T& Fortran_Array2D<T>::operator()(int i, int j)
{
#ifdef TNT_BOUNDS_CHECK
	assert(i >= 1);
	assert(i <= m_);
	assert(j >= 1);
	assert(j <= n_);
#endif

	return v_[ (j-1)*m_ + (i-1) ];

}

template <class T>
inline const T& Fortran_Array2D<T>::operator()(int i, int j) const
{
#ifdef TNT_BOUNDS_CHECK
	assert(i >= 1);
	assert(i <= m_);
	assert(j >= 1);
	assert(j <= n_);
#endif

	return v_[ (j-1)*m_ + (i-1) ];

}

template <class T>
Fortran_Array2D<T> & Fortran_Array2D<T>::operator=(const T &a)
{
 	set_(data_, data_+m_*n_, a);
	return *this;
}

template <class T>
Fortran_Array2D<T> Fortran_Array2D<T>::copy() const
{

	Fortran_Array2D B(m_,n_);

	B.inject(*this);
	return B;
}

template <class T>
Fortran_Array2D<T> & Fortran_Array2D<T>::inject(const Fortran_Array2D &A)
{
	if (m_ == A.m_ && n_ == A.n_)
		copy_(data_, A.data_, m_*n_);

	return *this;
}

template <class T>
Fortran_Array2D<T> & Fortran_Array2D<T>::ref(const Fortran_Array2D<T> &A)
{
	if (this != &A)
	{
		v_ = A.v_;
		m_ = A.m_;
		n_ = A.n_;
		data_ = A.data_;
	}
	return *this;
}

template <class T>
Fortran_Array2D<T> & Fortran_Array2D<T>::operator=(const Fortran_Array2D<T> &A)
{
	return ref(A);
}

template <class T>
inline int Fortran_Array2D<T>::dim1() const { return m_; }

template <class T>
inline int Fortran_Array2D<T>::dim2() const { return n_; }

template <class T>
Fortran_Array2D<T>::~Fortran_Array2D()
{
}

template <class T>
inline int Fortran_Array2D<T>::ref_count() const { return v_.ref_count(); }

template <class T>
void Fortran_Array2D<T>::set_(T* begin, T* end, const T& a)
{
	for (T* p=begin; p<end; p++)
		*p = a;

}

template <class T>
void Fortran_Array2D<T>::copy_(T* p, const T* q, int len)
{
	T *end = p + len;
	while (p<end )
		*p++ = *q++;

}

} /* namespace TNT */

#endif
/* TNT_FORTRAN_ARRAY2D_H */

{'repo_name': 'prody/ProDy', 'stars': '154', 'repo_language': 'Python', 'file_name': 'functions.py', 'mime_type': 'text/x-python', 'hash': 7171724335473914897, 'source_dataset': 'data'}


/* Generated by RuntimeBrowser
   Image: /System/Library/PrivateFrameworks/PassKitCore.framework/PassKitCore
 */

@interface PawuKFL8icsLHMZd : NSObject {
    NSString * _emailAddress;
    NSString * _firstName;
    NSString * _fullName;
    NSString * _lastName;
    NSString * _phoneNumber;
    unsigned long long  _source;
    unsigned long long  _type;
}

@property (nonatomic, retain) NSString *emailAddress;
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *fullName;
@property (nonatomic, retain) NSString *lastName;
@property (nonatomic, retain) NSString *phoneNumber;
@property (nonatomic) unsigned long long source;
@property (nonatomic) unsigned long long type;

- (void).cxx_destruct;
- (id)emailAddress;
- (id)firstName;
- (id)fullName;
- (id)initWithEmailAddress:(id)arg1 source:(unsigned long long)arg2;
- (id)initWithFirstName:(id)arg1 lastName:(id)arg2 source:(unsigned long long)arg3;
- (id)initWithFullName:(id)arg1 source:(unsigned long long)arg2;
- (id)initWithPhoneNumber:(id)arg1 source:(unsigned long long)arg2;
- (id)initWithSource:(unsigned long long)arg1;
- (id)lastName;
- (id)phoneNumber;
- (void)setEmailAddress:(id)arg1;
- (void)setFirstName:(id)arg1;
- (void)setFullName:(id)arg1;
- (void)setLastName:(id)arg1;
- (void)setPhoneNumber:(id)arg1;
- (void)setSource:(unsigned long long)arg1;
- (void)setType:(unsigned long long)arg1;
- (unsigned long long)source;
- (unsigned long long)type;

@end

{'repo_name': 'nst/iOS-Runtime-Headers', 'stars': '7551', 'repo_language': 'Objective-C', 'file_name': 'NPNameParser.h', 'mime_type': 'text/plain', 'hash': -1800577784292229314, 'source_dataset': 'data'}


export function assertNever(shouldBeNever: never): never {
  throw new Error('Unhandled case: ' + JSON.stringify(shouldBeNever));
}

{'repo_name': 'nomcopter/react-mosaic', 'stars': '2386', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 3787198836188282876, 'source_dataset': 'data'}


# 实现感知机的基本算法和对偶算法

# 结果比较
结果在perceptron.ipynb中展示

# 相关博客
#### [感知机原理（Perceptron）](https://www.cnblogs.com/huangyc/p/9706575.html)

{'repo_name': 'SmallVagetable/machine_learning_python', 'stars': '357', 'repo_language': 'Python', 'file_name': 'perceptron-checkpoint.ipynb', 'mime_type': 'text/plain', 'hash': 2061209752557977622, 'source_dataset': 'data'}


var f = require('./f.js')();
for (var r = f.next(); !r.done; r = f.next()) {
    console.log(r.value);
}

{'repo_name': 'splunk/splunk-sdk-javascript', 'stars': '161', 'repo_language': 'JavaScript', 'file_name': 'splunk.ui.timeline.js', 'mime_type': 'text/plain', 'hash': -2852185661591028802, 'source_dataset': 'data'}