text:
// Copyright 2014 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.rules.objc;

import static com.google.devtools.build.lib.rules.objc.ObjcProvider.BUNDLE_IMPORT_DIR;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.CC_LIBRARY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DEFINE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FORCE_LOAD_FOR_XCODEGEN;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FRAMEWORK_DIR;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FRAMEWORK_SEARCH_PATH_ONLY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.GENERAL_RESOURCE_DIR;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.GENERAL_RESOURCE_FILE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.IMPORTED_LIBRARY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.SDK_DYLIB;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.SDK_FRAMEWORK;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.WEAK_SDK_FRAMEWORK;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.XCASSETS_DIR;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.XCDATAMODEL;
import static com.google.devtools.build.lib.rules.objc.XcodeProductType.LIBRARY_STATIC;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.rules.apple.AppleConfiguration.ConfigurationDistinguisher;
import com.google.devtools.build.lib.rules.apple.AppleToolchain;
import com.google.devtools.build.lib.rules.cpp.LinkerInputs;
import com.google.devtools.build.lib.rules.objc.ObjcProvider.Flag;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.xcode.xcodegen.proto.XcodeGenProtos.DependencyControl;
import com.google.devtools.build.xcode.xcodegen.proto.XcodeGenProtos.TargetControl;
import com.google.devtools.build.xcode.xcodegen.proto.XcodeGenProtos.XcodeprojBuildSetting;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Provider which provides transitive dependency information that is specific to Xcodegen. In
 * particular, it provides a sequence of targets which can be used to create a self-contained
 * {@code .xcodeproj} file.
 */
@Immutable
public final class XcodeProvider implements TransitiveInfoProvider {
  private static final String COMPANION_LIB_TARGET_LABEL_SUFFIX = "_static_lib";

  /**
   * A builder for instances of {@link XcodeProvider}.
   */
  public static final class Builder {
    private Label label;
    // Propagated dependencies and search paths are seen by all transitive dependents of this
    // target. Non propagated dependencies are only seen by this target; none of the direct and
    // transitive dependents of this target will see this provider. Strictly propagated dependencies
    // are only seen by this target and only direct dependents; transitive dependents won't see this
    // provider.
    private final NestedSetBuilder<String> propagatedUserHeaderSearchPaths =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<String> nonPropagatedUserHeaderSearchPaths =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<String> strictlyPropagatedUserHeaderSearchPaths =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<String> propagatedHeaderSearchPaths =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<String> nonPropagatedHeaderSearchPaths =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<String> strictlyPropagatedHeaderSearchPaths =
        NestedSetBuilder.linkOrder();
    // Dependencies must be in link order because XCode observes the dependency ordering for
    // binary linking.
    private final NestedSetBuilder<XcodeProvider> propagatedDependencies =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<XcodeProvider> nonPropagatedDependencies =
        NestedSetBuilder.linkOrder();
    private final NestedSetBuilder<XcodeProvider> strictlyPropagatedDependencies =
        NestedSetBuilder.linkOrder();
    private Optional<Artifact> bundleInfoplist = Optional.absent();
    private final NestedSetBuilder<XcodeProvider> jreDependencies = NestedSetBuilder.linkOrder();
    private final ImmutableList.Builder<XcodeprojBuildSetting> xcodeprojBuildSettings =
        new ImmutableList.Builder<>();
    private final ImmutableList.Builder<XcodeprojBuildSetting>
        companionTargetXcodeprojBuildSettings = new ImmutableList.Builder<>();
    private final ImmutableList.Builder<String> copts = new ImmutableList.Builder<>();
    private final ImmutableList.Builder<String> compilationModeCopts =
        new ImmutableList.Builder<>();
    private XcodeProductType productType;
    private final ImmutableList.Builder<Artifact> headers = new ImmutableList.Builder<>();
    private Optional<CompilationArtifacts> compilationArtifacts = Optional.absent();
    private ObjcProvider objcProvider;
    private Optional<XcodeProvider> testHost = Optional.absent();
    private final NestedSetBuilder<Artifact> inputsToXcodegen = NestedSetBuilder.stableOrder();
    private final NestedSetBuilder<Artifact> additionalSources = NestedSetBuilder.stableOrder();
    private final ImmutableList.Builder<XcodeProvider> extensions = new ImmutableList.Builder<>();
    private String architecture;
    private boolean generateCompanionLibTarget = false;
    private ConfigurationDistinguisher configurationDistinguisher;

    /**
     * Sets the label of the build target which corresponds to this Xcode target.
     */
    public Builder setLabel(Label label) {
      this.label = label;
      return this;
    }

    /**
     * Adds user header search paths for this target.
     */
    public Builder addUserHeaderSearchPaths(Iterable<PathFragment> userHeaderSearchPaths) {
      this.propagatedUserHeaderSearchPaths
          .addAll(rootEach("$(WORKSPACE_ROOT)", userHeaderSearchPaths));
      return this;
    }

    /**
     * Adds header search paths for this target. Each path is interpreted relative to the given
     * root, such as {@code "$(WORKSPACE_ROOT)"}.
     */
    public Builder addHeaderSearchPaths(String root, Iterable<PathFragment> paths) {
      this.propagatedHeaderSearchPaths.addAll(rootEach(root, paths));
      return this;
    }

    /**
     * Adds non-propagated header search paths for this target. Each relative path is interpreted
     * relative to the given root, such as {@code "$(WORKSPACE_ROOT)"}.
     */
    public Builder addNonPropagatedHeaderSearchPaths(String root, Iterable<PathFragment> paths) {
      this.nonPropagatedHeaderSearchPaths.addAll(rootEach(root, paths));
      return this;
    }

    /**
     * Sets the Info.plist for the bundle represented by this provider.
     */
    public Builder setBundleInfoplist(Artifact bundleInfoplist) {
      this.bundleInfoplist = Optional.of(bundleInfoplist);
      return this;
    }

    /**
     * Adds items in the {@link NestedSet}s of the given target to the corresponding sets in this
     * builder. This is useful if the given target is a dependency or like a dependency
     * (e.g. a test host). The given provider is not registered as a dependency with this provider.
     */
    private void addTransitiveSets(XcodeProvider dependencyish) {
      additionalSources.addTransitive(dependencyish.additionalSources);
      inputsToXcodegen.addTransitive(dependencyish.inputsToXcodegen);
      propagatedUserHeaderSearchPaths.addTransitive(dependencyish.propagatedUserHeaderSearchPaths);
      propagatedHeaderSearchPaths.addTransitive(dependencyish.propagatedHeaderSearchPaths);
    }

   /**
     * Adds {@link XcodeProvider}s corresponding to direct dependencies of this target which should
     * be added in the {@code .xcodeproj} file and propagated up the dependency chain.
     */
    public Builder addPropagatedDependencies(Iterable<XcodeProvider> dependencies) {
      return addDependencies(dependencies, /*doPropagate=*/true);
    }

    /**
     * Adds {@link XcodeProvider}s corresponding to direct dependencies of this target which should
     * be added in the {@code .xcodeproj} file and only propagate the header search paths to direct
     * dependents of this target. Propagated dependencies of this target are still propagated as the
     * code still needs to be linked, and only limits the propagation of this target's header search
     * paths.
     */
    public Builder addPropagatedDependenciesWithStrictDependencyHeaders(
        Iterable<XcodeProvider> dependencies) {
      for (XcodeProvider dependency : dependencies) {
        this.strictlyPropagatedDependencies.add(dependency);
        this.propagatedDependencies.addTransitive(dependency.propagatedDependencies);
        this.nonPropagatedDependencies.addTransitive(dependency.strictlyPropagatedDependencies);
        this.strictlyPropagatedUserHeaderSearchPaths.addTransitive(
            dependency.propagatedUserHeaderSearchPaths);
        this.strictlyPropagatedHeaderSearchPaths.addTransitive(
            dependency.propagatedHeaderSearchPaths);
      }
      return this;
    }

   /**
     * Adds {@link XcodeProvider}s corresponding to direct dependencies of this target which should
     * be added in the {@code .xcodeproj} file and not propagated up the dependency chain.
     */
    public Builder addNonPropagatedDependencies(Iterable<XcodeProvider> dependencies) {
      return addDependencies(dependencies, /*doPropagate=*/false);
    }

   /**
     * Adds {@link XcodeProvider}s corresponding to direct J2ObjC JRE dependencies of this target
     * which should be added in the {@code .xcodeproj} file and propagated up the dependency chain.
     */
    public Builder addJreDependencies(Iterable<XcodeProvider> dependencies) {
      for (XcodeProvider dependency : dependencies) {
        this.jreDependencies.add(dependency);
        this.jreDependencies.addTransitive(dependency.propagatedDependencies);
      }
      return addDependencies(dependencies, /*doPropagate=*/true);
    }

    private Builder addDependencies(Iterable<XcodeProvider> dependencies, boolean doPropagate) {
      for (XcodeProvider dependency : dependencies) {
        // TODO(bazel-team): This is messy. Maybe we should make XcodeProvider be able to specify
        // how to depend on it rather than require this method to choose based on the dependency's
        // type.
        if (dependency.productType == XcodeProductType.EXTENSION
            || dependency.productType == XcodeProductType.WATCH_OS1_EXTENSION) {
          this.extensions.add(dependency);
          this.inputsToXcodegen.addTransitive(dependency.inputsToXcodegen);
          this.additionalSources.addTransitive(dependency.additionalSources);
        } else {
          if (doPropagate) {
            this.propagatedDependencies.add(dependency);
            this.propagatedDependencies.addTransitive(dependency.propagatedDependencies);
            this.jreDependencies.addTransitive(dependency.jreDependencies);
            this.addTransitiveSets(dependency);
          } else {
            this.nonPropagatedDependencies.add(dependency);
            this.nonPropagatedDependencies.addTransitive(dependency.propagatedDependencies);
            this.nonPropagatedUserHeaderSearchPaths
                .addTransitive(dependency.propagatedUserHeaderSearchPaths);
            this.nonPropagatedHeaderSearchPaths
                .addTransitive(dependency.propagatedHeaderSearchPaths);
            this.inputsToXcodegen.addTransitive(dependency.inputsToXcodegen);
          }
          this.nonPropagatedUserHeaderSearchPaths.addTransitive(
              dependency.strictlyPropagatedUserHeaderSearchPaths);
          this.nonPropagatedHeaderSearchPaths.addTransitive(
              dependency.strictlyPropagatedHeaderSearchPaths);
        }
      }
      return this;
    }

    /**
     * Adds additional build settings of this target and its companion library target, if it exists.
     */
    public Builder addXcodeprojBuildSettings(
        Iterable<XcodeprojBuildSetting> xcodeprojBuildSettings) {
      this.xcodeprojBuildSettings.addAll(xcodeprojBuildSettings);
      this.companionTargetXcodeprojBuildSettings.addAll(xcodeprojBuildSettings);
      return this;
    }

    /**
     * Adds additional build settings of this target without adding them to the companion lib
     * target, if it exists.
     */
    public Builder addMainTargetXcodeprojBuildSettings(
        Iterable<XcodeprojBuildSetting> xcodeprojBuildSettings) {
      this.xcodeprojBuildSettings.addAll(xcodeprojBuildSettings);
      return this;
    }
    /**
     * Sets the copts to use when compiling the Xcode target.
     */
    public Builder addCopts(Iterable<String> copts) {
      this.copts.addAll(copts);
      return this;
    }

    /**
     * Sets the copts derived from compilation mode to use when compiling the Xcode target. These
     * will be included before the DEFINE options.
     */
    public Builder addCompilationModeCopts(Iterable<String> copts) {
      this.compilationModeCopts.addAll(copts);
      return this;
    }

    /**
     * Sets the product type for the PBXTarget in the .xcodeproj file.
     */
    public Builder setProductType(XcodeProductType productType) {
      this.productType = productType;
      return this;
    }

    /**
     * Adds to the header files of this target. It needs not to include the header files of
     * dependencies.
     */
    public Builder addHeaders(Iterable<Artifact> headers) {
      this.headers.addAll(headers);
      return this;
    }

    /**
     * The compilation artifacts for this target.
     */
    public Builder setCompilationArtifacts(CompilationArtifacts compilationArtifacts) {
      this.compilationArtifacts = Optional.of(compilationArtifacts);
      return this;
    }

    /**
     * Any additional sources not included in {@link #setCompilationArtifacts}.
     */
    public Builder addAdditionalSources(Artifact... artifacts) {
      this.additionalSources.addAll(Arrays.asList(artifacts));
      return this;
    }

    /**
     * Sets the {@link ObjcProvider} corresponding to this target.
     */
    public Builder setObjcProvider(ObjcProvider objcProvider) {
      this.objcProvider = objcProvider;
      return this;
    }

    /**
     * Sets the test host. This is used for xctest targets.
     */
    public Builder setTestHost(XcodeProvider testHost) {
      Preconditions.checkState(!this.testHost.isPresent());
      this.testHost = Optional.of(testHost);
      this.addTransitiveSets(testHost);
      return this;
    }

    /**
     * Adds inputs that are passed to Xcodegen when generating the project file.
     */
    public Builder addInputsToXcodegen(Iterable<Artifact> inputsToXcodegen) {
      this.inputsToXcodegen.addAll(inputsToXcodegen);
      return this;
    }

    /**
     * Sets the CPU architecture this xcode target was constructed for, derived from
     * {@link ObjcConfiguration#getIosCpu()}.
     */
    public Builder setArchitecture(String architecture) {
      this.architecture = architecture;
      return this;
    }

    /**
     * Generates an extra LIBRARY_STATIC Xcode target with the same compilation artifacts. Dependent
     * Xcode targets will pick this companion library target as its dependency, rather than the
     * main Xcode target of this provider.
     */
    // TODO(bazel-team): Remove this when the binary rule types and bundling rule types are merged.
    public Builder generateCompanionLibTarget() {
      this.generateCompanionLibTarget = true;
      return this;
    }

    /**
     * Sets the distinguisher that will cause this xcode provider to discard any dependencies from
     * sources that are tagged with a different distinguisher.
     */
    public Builder setConfigurationDistinguisher(ConfigurationDistinguisher distinguisher) {
      this.configurationDistinguisher = distinguisher;
      return this;
    }

    public XcodeProvider build() {
      Preconditions.checkState(
          !testHost.isPresent() || (productType == XcodeProductType.UNIT_TEST),
          "%s product types cannot have a test host (test host: %s).", productType, testHost);
      return new XcodeProvider(this);
    }
  }

  /**
   * A collection of top-level targets that can be used to create a complete project.
   */
  public static final class Project {
    private final NestedSet<Artifact> inputsToXcodegen;
    private final NestedSet<Artifact> additionalSources;
    private final ImmutableList<XcodeProvider> topLevelTargets;

    private Project(
        NestedSet<Artifact> inputsToXcodegen, NestedSet<Artifact> additionalSources,
        ImmutableList<XcodeProvider> topLevelTargets) {
      this.inputsToXcodegen = inputsToXcodegen;
      this.additionalSources = additionalSources;
      this.topLevelTargets = topLevelTargets;
    }

    public static Project fromTopLevelTarget(XcodeProvider topLevelTarget) {
      return fromTopLevelTargets(ImmutableList.of(topLevelTarget));
    }

    public static Project fromTopLevelTargets(Iterable<XcodeProvider> topLevelTargets) {
      NestedSetBuilder<Artifact> inputsToXcodegen = NestedSetBuilder.stableOrder();
      NestedSetBuilder<Artifact> additionalSources = NestedSetBuilder.stableOrder();
      for (XcodeProvider target : topLevelTargets) {
        inputsToXcodegen.addTransitive(target.inputsToXcodegen);
        additionalSources.addTransitive(target.additionalSources);
      }
      return new Project(inputsToXcodegen.build(), additionalSources.build(),
          ImmutableList.copyOf(topLevelTargets));
    }

    /**
     * Returns artifacts that are passed to the Xcodegen action when generating a project file that
     * contains all of the given targets.
     */
    public NestedSet<Artifact> getInputsToXcodegen() {
      return inputsToXcodegen;
    }

    /**
     * Returns artifacts that are additional sources for the Xcodegen action.
     */
    public NestedSet<Artifact> getAdditionalSources() {
      return additionalSources;
    }

    /**
     * Returns all the target controls that must be added to the xcodegen control. No other target
     * controls are needed to generate a functional project file. This method creates a new list
     * whenever it is called.
     */
    public ImmutableList<TargetControl> targets() {
      // Collect all the dependencies of all the providers, filtering out duplicates.
      Set<XcodeProvider> providerSet = new LinkedHashSet<>();
      for (XcodeProvider target : topLevelTargets) {
        target.collectProviders(providerSet);
      }

      ImmutableList.Builder<TargetControl> controls = new ImmutableList.Builder<>();
      Map<Label, XcodeProvider> labelToProvider = new HashMap<>();
      for (XcodeProvider provider : providerSet) {
        XcodeProvider oldProvider = labelToProvider.put(provider.label, provider);
        if (oldProvider != null) {
          if (!oldProvider.architecture.equals(provider.architecture)
              || oldProvider.configurationDistinguisher != provider.configurationDistinguisher) {
            // Do not include duplicate dependencies whose architecture or configuration
            // distinguisher does not match this project's. This check avoids having multiple
            // conflicting Xcode targets for the same BUILD target that are only distinguished by
            // these fields (which Xcode does not care about).
            continue;
          }

          throw new IllegalStateException("Depending on multiple versions of the same xcode target "
              + "is not allowed but occurred for: " + provider.label);
        }
        controls.addAll(provider.targetControls());
      }
      return controls.build();
    }
  }

  private final Label label;
  private final NestedSet<String> propagatedUserHeaderSearchPaths;
  private final NestedSet<String> nonPropagatedUserHeaderSearchPaths;
  private final NestedSet<String> strictlyPropagatedUserHeaderSearchPaths;
  private final NestedSet<String> propagatedHeaderSearchPaths;
  private final NestedSet<String> nonPropagatedHeaderSearchPaths;
  private final NestedSet<String> strictlyPropagatedHeaderSearchPaths;
  private final Optional<Artifact> bundleInfoplist;
  private final NestedSet<XcodeProvider> propagatedDependencies;
  private final NestedSet<XcodeProvider> nonPropagatedDependencies;
  private final NestedSet<XcodeProvider> strictlyPropagatedDependencies;
  private final NestedSet<XcodeProvider> jreDependencies;
  private final ImmutableList<XcodeprojBuildSetting> xcodeprojBuildSettings;
  private final ImmutableList<XcodeprojBuildSetting> companionTargetXcodeprojBuildSettings;
  private final ImmutableList<String> copts;
  private final ImmutableList<String> compilationModeCopts;
  private final XcodeProductType productType;
  private final ImmutableList<Artifact> headers;
  private final Optional<CompilationArtifacts> compilationArtifacts;
  private final ObjcProvider objcProvider;
  private final Optional<XcodeProvider> testHost;
  private final NestedSet<Artifact> inputsToXcodegen;
  private final NestedSet<Artifact> additionalSources;
  private final ImmutableList<XcodeProvider> extensions;
  private final String architecture;
  private final boolean generateCompanionLibTarget;
  private final ConfigurationDistinguisher configurationDistinguisher;

  private XcodeProvider(Builder builder) {
    this.label = Preconditions.checkNotNull(builder.label);
    this.propagatedUserHeaderSearchPaths = builder.propagatedUserHeaderSearchPaths.build();
    this.nonPropagatedUserHeaderSearchPaths = builder.nonPropagatedUserHeaderSearchPaths.build();
    this.strictlyPropagatedUserHeaderSearchPaths =
        builder.strictlyPropagatedUserHeaderSearchPaths.build();
    this.propagatedHeaderSearchPaths = builder.propagatedHeaderSearchPaths.build();
    this.nonPropagatedHeaderSearchPaths = builder.nonPropagatedHeaderSearchPaths.build();
    this.strictlyPropagatedHeaderSearchPaths = builder.strictlyPropagatedHeaderSearchPaths.build();
    this.bundleInfoplist = builder.bundleInfoplist;
    this.propagatedDependencies = builder.propagatedDependencies.build();
    this.nonPropagatedDependencies = builder.nonPropagatedDependencies.build();
    this.strictlyPropagatedDependencies = builder.strictlyPropagatedDependencies.build();
    this.jreDependencies = builder.jreDependencies.build();
    this.xcodeprojBuildSettings = builder.xcodeprojBuildSettings.build();
    this.companionTargetXcodeprojBuildSettings =
        builder.companionTargetXcodeprojBuildSettings.build();
    this.copts = builder.copts.build();
    this.compilationModeCopts = builder.compilationModeCopts.build();
    this.productType = Preconditions.checkNotNull(builder.productType);
    this.headers = builder.headers.build();
    this.compilationArtifacts = builder.compilationArtifacts;
    this.objcProvider = Preconditions.checkNotNull(builder.objcProvider);
    this.testHost = Preconditions.checkNotNull(builder.testHost);
    this.inputsToXcodegen = builder.inputsToXcodegen.build();
    this.additionalSources = builder.additionalSources.build();
    this.extensions = builder.extensions.build();
    this.architecture = Preconditions.checkNotNull(builder.architecture);
    this.generateCompanionLibTarget = builder.generateCompanionLibTarget;
    this.configurationDistinguisher =
        Preconditions.checkNotNull(builder.configurationDistinguisher);
  }

  private void collectProviders(Set<XcodeProvider> allProviders) {
    if (allProviders.add(this)) {
      Iterable<XcodeProvider> allDependencies =
          Iterables.concat(
              propagatedDependencies, nonPropagatedDependencies, strictlyPropagatedDependencies);
      for (XcodeProvider dependency : allDependencies) {
        dependency.collectProviders(allProviders);
      }
      for (XcodeProvider justTestHost : testHost.asSet()) {
        justTestHost.collectProviders(allProviders);
      }
      for (XcodeProvider extension : extensions) {
        extension.collectProviders(allProviders);
      }
    }
  }

  @VisibleForTesting
  static final EnumSet<XcodeProductType> CAN_LINK_PRODUCT_TYPES =
      EnumSet.of(
          XcodeProductType.APPLICATION,
          XcodeProductType.BUNDLE,
          XcodeProductType.UNIT_TEST,
          XcodeProductType.EXTENSION,
          XcodeProductType.FRAMEWORK,
          XcodeProductType.WATCH_OS1_EXTENSION,
          XcodeProductType.WATCH_OS1_APPLICATION);

  /**
   * Returns the name of the Xcode target that corresponds to a build target with the given name.
   * This changes the label to make it a legal Xcode target name (which means removing slashes and
   * the colon). It also makes the label more readable in the Xcode UI by putting the target name
   * first and the package elements in reverse. This means the "important" part is visible even if
   * the project navigator is too narrow to show the entire name.
   */
  static String xcodeTargetName(Label label) {
    return xcodeTargetName(label, /*labelSuffix=*/"");
  }

  /**
   * Returns the name of the companion Xcode library target that corresponds to a build target with
   * the given name. See {@link XcodeSupport#generateCompanionLibXcodeTarget} for the rationale of
   * the companion library target and {@link #xcodeTargetName(Label)} for naming details.
   */
  static String xcodeCompanionLibTargetName(Label label) {
    return xcodeTargetName(label, COMPANION_LIB_TARGET_LABEL_SUFFIX);
  }

  private static String xcodeTargetName(Label label, String labelSuffix) {
    String pathFromWorkspaceRoot = label + labelSuffix;
    if (label.getPackageIdentifier().getRepository().isMain()) {
      pathFromWorkspaceRoot = pathFromWorkspaceRoot.replace("//", "")
          .replace(':', '/');
    } else {
      pathFromWorkspaceRoot = pathFromWorkspaceRoot.replace("//", "_")
          .replace(':', '/').replace("@", "external_");
    }
    List<String> components = Splitter.on('/').splitToList(pathFromWorkspaceRoot);
    return Joiner.on('_').join(Lists.reverse(components));
  }

  /**
   * Returns the name of the xcode target in this provider to be referenced as a dep for dependents.
   */
  private String dependencyXcodeTargetName() {
    return generateCompanionLibTarget ? xcodeCompanionLibTargetName(label) : xcodeTargetName(label);
  }

  private Iterable<TargetControl> targetControls() {
    TargetControl mainTargetControl = targetControl();
    if (generateCompanionLibTarget) {
      return ImmutableList.of(mainTargetControl, companionLibTargetControl(mainTargetControl));
    } else {
      return ImmutableList.of(mainTargetControl);
    }
  }

  private TargetControl targetControl() {
    String buildFilePath = label.getPackageFragment().getSafePathString() + "/BUILD";
    NestedSet<String> userHeaderSearchPaths =
        NestedSetBuilder.<String>linkOrder()
            .addTransitive(propagatedUserHeaderSearchPaths)
            .addTransitive(nonPropagatedUserHeaderSearchPaths)
            .addTransitive(strictlyPropagatedUserHeaderSearchPaths)
            .build();
    NestedSet<String> headerSearchPaths =
        NestedSetBuilder.<String>linkOrder()
            .addTransitive(propagatedHeaderSearchPaths)
            .addTransitive(nonPropagatedHeaderSearchPaths)
            .addTransitive(strictlyPropagatedHeaderSearchPaths)
            .build();

    // TODO(bazel-team): Add provisioning profile information when Xcodegen supports it.
    TargetControl.Builder targetControl =
        TargetControl.newBuilder()
            .setName(label.getName())
            .setLabel(xcodeTargetName(label))
            .setProductType(productType.getIdentifier())
            .addSupportFile(buildFilePath)
            .addAllImportedLibrary(Artifact.toExecPaths(objcProvider.get(IMPORTED_LIBRARY)))
            .addAllImportedLibrary(Artifact.toExecPaths(ccLibraries(objcProvider)))
            .addAllUserHeaderSearchPath(userHeaderSearchPaths)
            .addAllHeaderSearchPath(headerSearchPaths)
            .addAllSupportFile(Artifact.toExecPaths(headers))
            .addAllCopt(compilationModeCopts)
            .addAllCopt(CompilationSupport.DEFAULT_COMPILER_FLAGS)
            .addAllCopt(Interspersing.prependEach("-D", objcProvider.get(DEFINE)))
            .addAllCopt(copts)
            .addAllLinkopt(
                Interspersing.beforeEach("-force_load", objcProvider.get(FORCE_LOAD_FOR_XCODEGEN)))
            .addAllLinkopt(CompilationSupport.DEFAULT_LINKER_FLAGS)
            .addAllLinkopt(
                Interspersing.beforeEach(
                    "-weak_framework", SdkFramework.names(objcProvider.get(WEAK_SDK_FRAMEWORK))))
            .addAllBuildSetting(xcodeprojBuildSettings)
            .addAllBuildSetting(AppleToolchain.defaultWarningsForXcode())
            .addAllSdkFramework(SdkFramework.names(objcProvider.get(SDK_FRAMEWORK)))
            .addAllFramework(PathFragment.safePathStrings(objcProvider.get(FRAMEWORK_DIR)))
            .addAllFrameworkSearchPathOnly(
                PathFragment.safePathStrings(objcProvider.get(FRAMEWORK_SEARCH_PATH_ONLY)))
            .addAllXcassetsDir(PathFragment.safePathStrings(objcProvider.get(XCASSETS_DIR)))
            .addAllXcdatamodel(
                PathFragment.safePathStrings(
                    Xcdatamodels.datamodelDirs(objcProvider.get(XCDATAMODEL))))
            .addAllBundleImport(PathFragment.safePathStrings(objcProvider.get(BUNDLE_IMPORT_DIR)))
            .addAllSdkDylib(objcProvider.get(SDK_DYLIB))
            .addAllGeneralResourceFile(
                Artifact.toExecPaths(objcProvider.get(GENERAL_RESOURCE_FILE)))
            .addAllGeneralResourceFile(
                PathFragment.safePathStrings(objcProvider.get(GENERAL_RESOURCE_DIR)));

    if (CAN_LINK_PRODUCT_TYPES.contains(productType)) {
      // For builds with --ios_multi_cpus set, we may have several copies of some XCodeProviders
      // in the dependencies (one per cpu architecture). We deduplicate the corresponding
      // xcode target names with a LinkedHashSet before adding to the TargetControl.
      Set<String> jreTargetNames = new HashSet<>();
      for (XcodeProvider jreDependency : jreDependencies) {
        jreTargetNames.add(jreDependency.dependencyXcodeTargetName());
      }
      Set<DependencyControl> dependencySet = new LinkedHashSet<>();
      Set<DependencyControl> jreDependencySet = new LinkedHashSet<>();
      for (XcodeProvider dependency : propagatedDependencies) {
        // Only add a library target to a binary's dependencies if it has source files to compile
        // and it is not from the "non_propagated_deps" attribute. Xcode cannot build targets
        // without a source file in the PBXSourceFilesBuildPhase, so if such a target is present in
        // the control file, it is only to get Xcodegen to put headers and resources not used by the
        // final binary in the Project Navigator.
        //
        // The exceptions to this rule are objc_bundle_library and ios_extension targets. Bundles
        // are generally used for resources and can lack a PBXSourceFilesBuildPhase in the project
        // file and still be considered valid by Xcode.
        //
        // ios_extension targets are an exception because they have no CompilationArtifact object
        // but do have a dummy source file to make Xcode happy.
        boolean hasSources = dependency.compilationArtifacts.isPresent()
            && dependency.compilationArtifacts.get().getArchive().isPresent();
        if (hasSources
            || (dependency.productType == XcodeProductType.BUNDLE
                || (dependency.productType == XcodeProductType.WATCH_OS1_APPLICATION))) {
          String dependencyXcodeTargetName = dependency.dependencyXcodeTargetName();
          Set<DependencyControl> set = jreTargetNames.contains(dependencyXcodeTargetName)
              ? jreDependencySet : dependencySet;
          set.add(DependencyControl.newBuilder()
              .setTargetLabel(dependencyXcodeTargetName)
              .build());
        }
      }

      for (DependencyControl dependencyControl : dependencySet) {
        targetControl.addDependency(dependencyControl);
      }
      // Make sure that JRE dependencies are ordered after other propagated dependencies.
      for (DependencyControl dependencyControl : jreDependencySet) {
        targetControl.addDependency(dependencyControl);
      }
    }
    for (XcodeProvider justTestHost : testHost.asSet()) {
      targetControl.addDependency(DependencyControl.newBuilder()
          .setTargetLabel(xcodeTargetName(justTestHost.label))
          .setTestHost(true)
          .build());
    }
    for (XcodeProvider extension : extensions) {
      targetControl.addDependency(DependencyControl.newBuilder()
          .setTargetLabel(xcodeTargetName(extension.label))
          .build());
    }

    if (bundleInfoplist.isPresent()) {
      targetControl.setInfoplist(bundleInfoplist.get().getExecPathString());
    }
    for (CompilationArtifacts artifacts : compilationArtifacts.asSet()) {
      targetControl
          .addAllSourceFile(Artifact.toExecPaths(artifacts.getSrcs()))
          .addAllSupportFile(Artifact.toExecPaths(artifacts.getAdditionalHdrs()))
          .addAllSupportFile(Artifact.toExecPaths(artifacts.getPrivateHdrs()))
          .addAllNonArcSourceFile(Artifact.toExecPaths(artifacts.getNonArcSrcs()));

      for (Artifact pchFile : artifacts.getPchFile().asSet()) {
        targetControl
            .setPchPath(pchFile.getExecPathString())
            .addSupportFile(pchFile.getExecPathString());
      }
    }

    for (Artifact artifact : additionalSources) {
      targetControl.addSourceFile(artifact.getExecPathString());
    }

    if (objcProvider.is(Flag.USES_CPP)) {
      targetControl.addSdkDylib("libc++");
    }

    return targetControl.build();
  }

  private TargetControl companionLibTargetControl(TargetControl mainTargetControl) {
    return TargetControl.newBuilder()
        .mergeFrom(mainTargetControl)
        .setName(label.getName() + COMPANION_LIB_TARGET_LABEL_SUFFIX)
        .setLabel(xcodeCompanionLibTargetName(label))
        .setProductType(LIBRARY_STATIC.getIdentifier())
        .clearInfoplist()
        .clearDependency()
        .clearBuildSetting()
        .addAllBuildSetting(companionTargetXcodeprojBuildSettings)
        .addAllBuildSetting(AppleToolchain.defaultWarningsForXcode())
        .build();
  }

  /**
   * Prepends the given path to each path in {@code paths}. Empty paths are
   * transformed to the value of {@code variable} rather than {@code variable + "/."}. Absolute
   * paths are returned without modifications.
   */
  @VisibleForTesting
  static Iterable<String> rootEach(final String prefix, Iterable<PathFragment> paths) {
    Preconditions.checkArgument(prefix.startsWith("$"),
        "prefix should start with a build setting variable like '$(NAME)': %s", prefix);
    Preconditions.checkArgument(!prefix.endsWith("/"),
        "prefix should not end with '/': %s", prefix);
    return Iterables.transform(paths, new Function<PathFragment, String>() {
      @Override
      public String apply(PathFragment input) {
        if (input.getSafePathString().equals(".")) {
          return prefix;
        } else if (input.isAbsolute()) {
          return input.getSafePathString();
        } else {
          return prefix + "/" + input.getSafePathString();
        }
      }
    });
  }

  private ImmutableList<Artifact> ccLibraries(ObjcProvider objcProvider) {
    ImmutableList.Builder<Artifact> ccLibraryBuilder = ImmutableList.builder();
    for (LinkerInputs.LibraryToLink libraryToLink : objcProvider.get(CC_LIBRARY)) {
      ccLibraryBuilder.add(libraryToLink.getArtifact());
    }
    return ccLibraryBuilder.build();
  }
}


text:
package org.odlabs.wiquery.ui.dialog;

import static org.junit.Assert.*;

import org.junit.Test;
import org.odlabs.wiquery.core.javascript.JsScope;
import org.odlabs.wiquery.tester.WiQueryTestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DialogButtonTestCase extends WiQueryTestCase
{
	protected static final Logger log = LoggerFactory.getLogger(DialogButtonTestCase.class);

	@Test
	public void testGetJavaScriptOption()
	{
		DialogButton button = new DialogButton("Ok", JsScope.quickScope("alert('test');"));
		String expectedJavascript = "'Ok':function() {\n\talert('test');\n}";
		String generatedJavascript = button.getJavascriptOption().toString();

		log.info(expectedJavascript);
		log.info(generatedJavascript);
		assertEquals(generatedJavascript, expectedJavascript);
	}

	@Override
	protected Logger getLog()
	{
		return log;
	}
}

redpajama_set_name: RedPajamaGithub


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Sql.DataSync.Model;
using Microsoft.Azure.Commands.Sql.DataSync.Services;
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Sql.Common;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;

namespace Microsoft.Azure.Commands.Sql.DataSync.Cmdlet
{
    /// <summary>
    /// Cmdlet to generate a sync agent registration key for a specific sync agent
    /// </summary>
    [Cmdlet(VerbsCommon.New, "AzureRmSqlSyncAgentKey", SupportsShouldProcess = true,
        ConfirmImpact = ConfirmImpact.Medium), OutputType(typeof(AzureSqlSyncAgentKeyModel))]
    public class NewAzureSqlSyncAgentKey : AzureSqlCmdletBase<IEnumerable<AzureSqlSyncAgentKeyModel>, AzureSqlDataSyncAdapter>
    {
        /// <summary>
        /// Gets or sets the name of the database server to use.
        /// </summary>
        [Parameter(Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            Position = 1,
            HelpMessage = "The name of the Azure SQL Server the sync agent is in.")]
        [ValidateNotNullOrEmpty]
        public string ServerName { get; set; }

        /// <summary>
        /// Gets or sets the sync agent name
        /// </summary>
        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true,
            Position = 2,
            HelpMessage = "The sync agent name.")]
        [ValidateNotNullOrEmpty]
        public string SyncAgentName { get; set; }

        /// <summary>
        /// Creation and initialization of the ModelAdapter object
        /// </summary>
        /// <param name="subscription">The AzureSubscription in which the current execution is performed</param>
        /// <returns>An initialized and ready to use ModelAdapter object</returns>
        protected override AzureSqlDataSyncAdapter InitModelAdapter(IAzureSubscription subscription)
        {
            return new AzureSqlDataSyncAdapter(DefaultProfile.DefaultContext);
        }

        /// <summary>
        /// Get the entities from the service
        /// </summary>
        protected override IEnumerable<AzureSqlSyncAgentKeyModel> GetEntity()
        {
            // Try to get the sync agent first. If the sync agent doesn't exist, it will fail at this step.
            ModelAdapter.GetSyncAgent(this.ResourceGroupName, this.ServerName, this.SyncAgentName);
            return new List<AzureSqlSyncAgentKeyModel>() {
                ModelAdapter.CreateSyncAgentKey(this.ResourceGroupName, this.ServerName, this.SyncAgentName)
            };
        }

        /// <summary>
        /// No changes to persist to server
        /// </summary>
        /// <param name="entity">The output of apply user input to model</param>
        /// <returns>The input entity</returns>
        protected override IEnumerable<AzureSqlSyncAgentKeyModel> PersistChanges(IEnumerable<AzureSqlSyncAgentKeyModel> entity)
        {
            return entity;
        }
    }
}


text:
require 'spec_helper'

module Arel
  describe Group do
    before do
      @relation = Table.new(:users)
      @attribute = @relation[:id]
    end

    describe '#to_sql' do
      describe 'when given a predicate' do
        it "manufactures sql with where clause conditions" do
          sql = Group.new(@relation, [@attribute]).to_sql

          adapter_is :mysql do
            sql.should be_like(%Q{
              SELECT `users`.`id`, `users`.`name`
              FROM `users`
              GROUP BY `users`.`id`
            })
          end

          adapter_is :oracle do
            sql.should be_like(%Q{
              SELECT "USERS"."ID", "USERS"."NAME"
              FROM "USERS"
              GROUP BY "USERS"."ID"
            })
          end

          adapter_is_not :mysql, :oracle do
            sql.should be_like(%Q{
              SELECT "users"."id", "users"."name"
              FROM "users"
              GROUP BY "users"."id"
            })
          end
        end
      end

      describe 'when given a string' do
        it "passes the string through to the where clause" do
          sql = Group.new(@relation, ['asdf']).to_sql

          adapter_is :mysql do
            sql.should be_like(%Q{
              SELECT `users`.`id`, `users`.`name`
              FROM `users`
              GROUP BY asdf
            })
          end

          adapter_is :oracle do
            sql.should be_like(%Q{
              SELECT "USERS"."ID", "USERS"."NAME"
              FROM "USERS"
              GROUP BY asdf
            })
          end

          adapter_is_not :mysql, :oracle do
            sql.should be_like(%Q{
              SELECT "users"."id", "users"."name"
              FROM "users"
              GROUP BY asdf
            })
          end
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;

namespace FuncLib.Functions
{
	/// <summary>
	/// Generic thread-safe class for caching any type depending on <see cref="IEvaluation" />.
	/// </summary>
	/// <typeparam name="T">The type to cache, e.g. double or Matrix.</typeparam>
	public class EvaluationCache<T>
	{
		private static int defaultSize;
		private int size;
		private Dictionary<IEvaluation, T> values;
		private LinkedList<IEvaluation> evaluations;
		private object cacheLock;

		static EvaluationCache()
		{
			// Read from configuration file instead?
			defaultSize = 100;
		}

		/// <summary>
		/// New instance of EvaluationCache using default cache size as specified by <see cref="DefaultSize" />.
		/// </summary>
		public EvaluationCache()
			: this(defaultSize)
		{
		}

		/// <summary>
		/// New instance of EvaluationCache with a custom cache size.
		/// </summary>
		/// <param name="size">The size of the rolling cache.</param>
		public EvaluationCache(int size)
		{
			this.size = size;

			values = new Dictionary<IEvaluation, T>(size);
			evaluations = new LinkedList<IEvaluation>();
			cacheLock = new object();
		}

		public void Add(IEvaluation evaluation, T value)
		{
			if (size == 0)
			{
				// No caching; avoid locking.
				return;
			}

			lock (cacheLock)
			{
				if (evaluations.Count >= size)
				{
					values.Remove(evaluations.First.Value);
					evaluations.RemoveFirst();
				}

				values.Add(evaluation, value);
				evaluations.AddLast(evaluation);
			}
		}

		public bool TryGetValue(IEvaluation evaluation, out T value)
		{
			if (size == 0)
			{
				value = default(T);
				return false;
			}

			lock (cacheLock)
			{
				return values.TryGetValue(evaluation, out value);
			}
		}

		public static int DefaultSize
		{
			get
			{
				return defaultSize;
			}
			set
			{
				defaultSize = value;
			}
		}
	}
}


text:
package org.apache.spark.network.shuffle;

import java.io.IOException;
import java.util.List;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.spark.network.TransportContext;
import org.apache.spark.network.client.TransportClient;
import org.apache.spark.network.client.TransportClientBootstrap;
import org.apache.spark.network.client.TransportClientFactory;
import org.apache.spark.network.sasl.SaslClientBootstrap;
import org.apache.spark.network.sasl.SecretKeyHolder;
import org.apache.spark.network.server.NoOpRpcHandler;
import org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo;
import org.apache.spark.network.shuffle.protocol.RegisterExecutor;
import org.apache.spark.network.util.TransportConf;

/**
 * Client for reading shuffle blocks which points to an external (outside of executor) server.
 * This is instead of reading shuffle blocks directly from other executors (via
 * BlockTransferService), which has the downside of losing the shuffle data if we lose the
 * executors.
 */
public class ExternalShuffleClient extends ShuffleClient {
  private final Logger logger = LoggerFactory.getLogger(ExternalShuffleClient.class);

  private final TransportConf conf;
  private final boolean saslEnabled;
  private final boolean saslEncryptionEnabled;
  private final SecretKeyHolder secretKeyHolder;

  private TransportClientFactory clientFactory;
  private String appId;

  /**
   * Creates an external shuffle client, with SASL optionally enabled. If SASL is not enabled,
   * then secretKeyHolder may be null.
   */
  public ExternalShuffleClient(
      TransportConf conf,
      SecretKeyHolder secretKeyHolder,
      boolean saslEnabled,
      boolean saslEncryptionEnabled) {
    Preconditions.checkArgument(
      !saslEncryptionEnabled || saslEnabled,
      "SASL encryption can only be enabled if SASL is also enabled.");
    this.conf = conf;
    this.secretKeyHolder = secretKeyHolder;
    this.saslEnabled = saslEnabled;
    this.saslEncryptionEnabled = saslEncryptionEnabled;
  }

  @Override
  public void init(String appId) {
    this.appId = appId;
    TransportContext context = new TransportContext(conf, new NoOpRpcHandler());
    List<TransportClientBootstrap> bootstraps = Lists.newArrayList();
    if (saslEnabled) {
      bootstraps.add(new SaslClientBootstrap(conf, appId, secretKeyHolder, saslEncryptionEnabled));
    }
    clientFactory = context.createClientFactory(bootstraps);
  }

  @Override
  public void fetchBlocks(
      final String host,
      final int port,
      final String execId,
      String[] blockIds,
      BlockFetchingListener listener) {
    assert appId != null : "Called before init()";
    logger.debug("External shuffle fetch from {}:{} (executor id {})", host, port, execId);
    try {
      RetryingBlockFetcher.BlockFetchStarter blockFetchStarter =
        new RetryingBlockFetcher.BlockFetchStarter() {
          @Override
          public void createAndStart(String[] blockIds, BlockFetchingListener listener)
              throws IOException {
            TransportClient client = clientFactory.createClient(host, port);
            new OneForOneBlockFetcher(client, appId, execId, blockIds, listener).start();
          }
        };

      int maxRetries = conf.maxIORetries();
      if (maxRetries > 0) {
        // Note this Fetcher will correctly handle maxRetries == 0; we avoid it just in case there's
        // a bug in this code. We should remove the if statement once we're sure of the stability.
        new RetryingBlockFetcher(conf, blockFetchStarter, blockIds, listener).start();
      } else {
        blockFetchStarter.createAndStart(blockIds, listener);
      }
    } catch (Exception e) {
      logger.error("Exception while beginning fetchBlocks", e);
      for (String blockId : blockIds) {
        listener.onBlockFetchFailure(blockId, e);
      }
    }
  }

  /**
   * Registers this executor with an external shuffle server. This registration is required to
   * inform the shuffle server about where and how we store our shuffle files.
   *
   * @param host Host of shuffle server.
   * @param port Port of shuffle server.
   * @param execId This Executor's id.
   * @param executorInfo Contains all info necessary for the service to find our shuffle files.
   */
  public void registerWithShuffleServer(
      String host,
      int port,
      String execId,
      ExecutorShuffleInfo executorInfo) throws IOException {
    assert appId != null : "Called before init()";
    TransportClient client = clientFactory.createClient(host, port);
    byte[] registerMessage = new RegisterExecutor(appId, execId, executorInfo).toByteArray();
    client.sendRpcSync(registerMessage, 5000 /* timeoutMs */);
  }

  @Override
  public void close() {
    clientFactory.close();
  }
}


text:
<form class="demo-form" action="#" method="post" novalidate>

      Name on Card *
        <input type="text" id="nameoncard" name="nameoncard" autocomplete="cc-name" required>

      Credit Card Number *
        <input type="text" id="ccnumber" name="ccnumber" autocomplete="cc-number" required>

      Expiration Month *
        <input type="number" id="cc-exp-month" name="cc-exp-month" autocomplete="cc-exp-month" required>

      Expiration Year *
        <input type="number" id="cc-exp-year" name="cc-exp-year" autocomplete="cc-exp-year" required>

      CVV *
        <input type="text" id="cvv2" name="cvv2" autocomplete="cc-csc">

    <fieldset class="small-12 medium-6 columns">
      <button class="button" type="submit" value="Submit">Submit</button>
    </fieldset>

    <fieldset class="small-12 medium-6 columns">
      <button class="button" type="reset" value="Reset">Reset</button>
    </fieldset>

</form>


text:
define([
	'jquery',
	'underscore',
	'backbone',
	'marionette',
	'text!templates/run-requests/run-requests-list/run-requests-list.tpl',
	'scripts/registry',
	'scripts/collections/run-requests/run-requests',
	'scripts/views/dialogs/error-view',
	'scripts/views/widgets/lists/sortable-table-list-view',
	'scripts/views/scheduled-runs/run-requests-list/run-requests-list-item-view'
], function($, _, Backbone, Marionette, Template, Registry, RunRequests, ErrorView, SortableTableListView, RunRequestsListItemView) {
	return SortableTableListView.extend({

		//
		// rendering methods
		//

		template: function(data) {
			return _.template(Template, _.extend(data, {
				collection: this.collection,
				showDelete: this.options.showDelete
			}));
		},

		onRender: function() {
			this.count = 0;

			// show run requests
			//
			for (var i = 0; i < this.collection.length; i++) {
				this.showAssessmentRunRequests(this.collection.at(i));
			}
		},

		showAssessmentRunRequests: function(assessmentRun) {
			var self = this;
			var runRequests = new RunRequests();

			// fetch run requests associated with assessment run
			//
			runRequests.fetchByAssessmentRun(assessmentRun, {

				// callbacks
				//
				success: function() {

					// show each run request
					//
					for (var i = 0; i < runRequests.length; i++) {
						self.showAssessmentRunRequest(assessmentRun, runRequests.at(i));
					}

					// sort table when complete
					//
					self.count++;
					if (self.count === self.collection.length) {

						// make table sortable
						//
						self.$el.find('table').addClass('tablesorter');
						self.$el.find('.tablesorter:has(tbody tr)').tablesorter({

							// disable sorting on remove column
							//
							headers: {
								4: {
									sorter: false
								}
							},

							// sort on name column in descending order
							//
							sortList: [[0, 0]]
						});
					}
				},

				error: function() {

					// show error dialog
					//
					Registry.application.modal.show(
						new ErrorView({
							message: "Could not get run requests associated with assessment run."
						})
					);
				}
			})
		},

		showAssessmentRunRequest: function(assessmentRun, runRequest) {
			var runRequestsListItemView = new RunRequestsListItemView({
				model: assessmentRun,
				runRequest: runRequest,
				showDelete: this.options.showDelete,
				parent: this
			});
			this.$el.find('table').show();
			this.$el.find('.no-run-requests-message').hide();
			this.$el.find('table tbody').append(runRequestsListItemView.render().el);
		}
	});
});


text:
const express = require('express')
const router = express.Router()
const crypto = require('crypto')
const superagent = require('superagent')

const config = require('../config.js');

const token = config.token
const appid = config.appid
const appsecret = config.appsecret
const front_url = config.front_url

var basic_access_token = undefined
var js_ticket = undefined

const user = require('../models/user.js');
const User = user.User;

router.get('/test_status', (req, res) => {
  res.json({
    access_token: basic_access_token,
    js_ticket: js_ticket
  })
})

/**
 * 获取 jsconfig
 */
router.get('/jsconfig', (req, res) => {
  var timestamp = getTimesTamp()
  var noncestr = getNonceStr()
  var str = 'jsapi_ticket=' + js_ticket + '&noncestr='+ noncestr+'&timestamp=' + timestamp + '&url=' + front_url
  var signature = crypto.createHash('sha1').update(str).digest('hex')
  res.json({
    appId: appid,
    timestamp: timestamp,
    nonceStr: noncestr,
    signature: signature
  })
})

/**
 * 微信服务器校验
 */
router.get('/wechat', (req, res) => {

  var signature = req.query.signature
  var timestamp = req.query.timestamp
  var nonce = req.query.nonce
  var echostr = req.query.echostr
  if (check(signature, timestamp, nonce)) {
      res.send(echostr)   // 确认来源是微信,并把echostr返回给微信服务器。
  } else {
      res.status(400).json({ code : -1, msg : 'You aren\'t wechat server !'})
  }
})

/**
 * 获取用户 code 微信回调
 */
router.get('/wechat/auth', (req, res) => {
  console.log('#############', req.query.code, req.query.state)
  var url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${req.query.code}&grant_type=authorization_code`
  superagent.get(url).end((req1, res1) => {
    var data = JSON.parse(res1.text)
    var openid = data.openid
    var access_token = data.access_token
    // console.log(openid, access_token)

    User.find({
      openid: openid
    }).exec((err, users) => {
      if (err) {
        res.status(500).json('db error', err);
      }
      if (users.length > 0) {
        res.render('pages/index', users[0]);
      } else {
        res.render('pages/register', {
          openid
        })
      }
    })
    // res.redirect(front_url+'#'+req.query.state+'/?openid='+openid)
  })
})

module.exports = router

function check (signature, timestamp, nonce) {
  var tmpArr = Array(token, timestamp, nonce).sort().join("");
  var sha1 = crypto.createHash('sha1');
  sha1.update(tmpArr);
  tmpArr = sha1.digest('hex');
  return (tmpArr == signature);
}

function getTimesTamp() {
  return parseInt(new Date().getTime() / 1000) + ''
}

function getNonceStr() {
  return Math.random().toString(36).substr(2, 15)
}

function getNewTicket(token, cb) {
  var url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${basic_access_token}&type=jsapi`
  console.log(url)
  superagent.get(url).end((error, res, body) => {
    // console.log('****', error, res)
    if (error) {
      cb('getNewTicket error', error)
    } else {
      try {
        var ticket = JSON.parse(res.text).ticket
        cb(null, ticket)
      } catch (e) {
        cb('getNewTicket error', e)
      }
    }
  })
}

//---------------
// 获取 basic access token
var url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`
function fetchWeixin() {
  console.log('尝试获取 access tocken');
  superagent.get(url).end((req2, res2) => {
    console.log('获取到 basic access tocken')
    basic_access_token = JSON.parse(res2.text).access_token

    // 刷新 js_ticket
    getNewTicket(basic_access_token, (error, ticket) => {
      console.log('获取到 js ticket')
      js_ticket = ticket
    })
    setTimeout(fetchWeixin, 7000000)
  })
}
fetchWeixin()


text:
Dieses Projekt hat zum Ziel, einige Aufgaben aus der Lernumgebung 21 "Gewinnen" des Mathbuch 2 als interaktive Webapplikation umzusetzen.

## Installation
Dieses Projekt nutzt AngularJS und TypeScript. Um das Endprodukt zu erhalten, sind ein paar Schritte nötig. Geben Sie in der Konsole folgende Befehle ein (es wird von einer Bash Shell ausgeganen) um vom benötigte Komponenten zu installieren:
```bash
$ cd <pfad-zum-projektordner>
$ sudo npm -g install bower gulp
$ bower install
$ npm install
```

Um dann das Lauffähige Produkt zu erhalten, geben Sie noch folgenden Befehl ein:
```bash
$ gulp build --type=dist
```
Das fertige Produkt finden Sie jetzt im Ordner "www". Sie können den Inhalt dieses Ordners nun entweder auf ihren WebServer laden oder lokal die Datei index.html öffnen.


text:
@implementation viewWhiteAutoWHFrame

- (void)awakeFromNib{
    [super awakeFromNib];
    self.frame= CGRectMake(kscaleDeviceWidth(self.frame.origin.x) , kscaleIphone6DeviceHeight(self.frame.origin.y),kscaleDeviceWidth( self.frame.size.width), kscaleIphone6DeviceHeight(self.frame.size.height));

}

@end


text:
// -----------------------------------------------------------------------
// <copyright file="MessageExtensions.cs" company="Asynkron AB">
//      Copyright (C) 2015-2020 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
namespace Proto
{
    public partial class Terminated
    {
        public static Terminated From(PID who, TerminatedReason why)
            => new()
            {
                Who = who,
                why_ = why
            };
    }
}


text:
export class PotatoGalleryEntry {
    img_url: string;
    caption: string;
}


text:
<?php

namespace Flowcode\ProjectBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class FlowcodeProjectBundle extends Bundle
{
}


text:
namespace urde {

static boo::ObjToken<boo::IShaderPipeline> s_AlphaPipeline;
static boo::ObjToken<boo::IShaderPipeline> s_AddPipeline;
static boo::ObjToken<boo::IShaderPipeline> s_MultPipeline;

void CScanLinesFilter::Initialize() {
  s_AlphaPipeline = hecl::conv->convert(Shader_CScanLinesFilterAlpha{});
  s_AddPipeline = hecl::conv->convert(Shader_CScanLinesFilterAdd{});
  s_MultPipeline = hecl::conv->convert(Shader_CScanLinesFilterMult{});
}

void CScanLinesFilter::Shutdown() {
  s_AlphaPipeline.reset();
  s_AddPipeline.reset();
  s_MultPipeline.reset();
}

static boo::ObjToken<boo::IShaderPipeline> SelectPipeline(EFilterType type) {
  switch (type) {
  case EFilterType::Blend:
    return s_AlphaPipeline;
  case EFilterType::Add:
    return s_AddPipeline;
  case EFilterType::Multiply:
    return s_MultPipeline;
  default:
    return {};
  }
}

CScanLinesFilter::CScanLinesFilter(EFilterType type, bool even) : m_even(even) {
  CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) {
    m_uniBuf = ctx.newDynamicBuffer(boo::BufferUse::Uniform, sizeof(Uniform), 1);
    boo::ObjToken<boo::IGraphicsBuffer> vbo =
        m_even ? g_Renderer->GetScanLinesEvenVBO().get() : g_Renderer->GetScanLinesOddVBO().get();
    boo::ObjToken<boo::IGraphicsBuffer> bufs[] = {m_uniBuf.get()};
    boo::PipelineStage stages[] = {boo::PipelineStage::Vertex};
    m_dataBind = ctx.newShaderDataBinding(SelectPipeline(type), vbo, nullptr, nullptr, 1, bufs, stages, nullptr,
                                          nullptr, 0, nullptr, nullptr, nullptr);
    return true;
  } BooTrace);
}

void CScanLinesFilter::draw(const zeus::CColor& color) {
  SCOPED_GRAPHICS_DEBUG_GROUP("CScanLinesFilter::draw", zeus::skMagenta);

  m_uniform.color = color;
  m_uniBuf->load(&m_uniform, sizeof(Uniform));

  CGraphics::SetShaderDataBinding(m_dataBind);
  CGraphics::DrawArray(0, 670);
}

} // namespace urde


text:
package exercise.basic;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

@Path("/ex1/resource-paths-demo")
public class PathDemoResource {

    String dumpUriInfo(UriInfo info) {
        String abs_path = info.getAbsolutePath().toString();
        String abs_base = info.getBaseUri().toString();
        String req_uri = info.getRequestUri().toString();
        return "UriInfo : [\r\nAbsolutePath:'" + abs_path + "',\r\nBaseUri:'"
                + abs_base + "',\r\nRequestUri:'" + req_uri + "'\r\n]\r\n";
    }

    /**
     * @param info
     * @return
     */
    @GET
    @Produces("text/plain")
    public String forResourceRoot(@Context UriInfo info) {
        return dumpUriInfo(info);
    }

    /**
     * @param info
     * @return
     */
    @GET
    @Path("sub1")
    public String forSub1a(@Context UriInfo info) {
        return "sub1a\r\n" + dumpUriInfo(info);
    }

    /**
     * [[FATAL] A resource model has ambiguous (sub-)resource method for HTTP method GET and input mime-types as defined
     * by
     *
     * @Consumes and @Produces annotations at Java methods public java.lang.String
     *           net.glamenvseptzen.jersey.exercises.ex1.ResourcePathsDemo.forSub1a(javax.ws.rs.core.UriInfo) and public
     *           java.lang.String
     *           net.glamenvseptzen.jersey.exercises.ex1.ResourcePathsDemo.forSub1b(javax.ws.rs.core.UriInfo) at
     *           matching regular expression /sub1. These two methods produces and consumes exactly the same mime-types
     *           and therefore their invocation as a resource methods will always fail.;
     *           source='org.glassfish.jersey.server.model.RuntimeResource@3d1cda9']
     * @param info
     * @return
     */
    // @GET
    // @Path("sub1")
    // public String forSub1b(@Context UriInfo info) {
    // return "sub1b\r\n" + dumpUriInfo(info);
    // }

    @GET
    @Path("sub/sub2")
    public String forSubSub2(@Context UriInfo info) {
        return "subsub2\r\n" + dumpUriInfo(info);
    }

}


text:
package main

import (
	"flag"
	"os"
	"path"
)

var inFilePath string
var outFilePath string
var pubKeyPath string
var privKeyPath string
var doDecrypt bool

func init() {
	flag.StringVar(&inFilePath, "in", "-", "Input file")
	flag.StringVar(&outFilePath, "out", "-", "Output file")
	flag.StringVar(&pubKeyPath, "pubKey", path.Join(os.Getenv("HOME"), ".ssh/id_rsa.pub"), "Public Key file (Encrypting)")
	flag.StringVar(&privKeyPath, "privKey", path.Join(os.Getenv("HOME"), ".ssh/id_rsa"), "Private Key file (Decrypting)")
	flag.BoolVar(&doDecrypt, "d", false, "Decrypt file instead of encrypting")
}

func main() {

	flag.Parse()
	var err error

	var inFile *os.File
	if inFilePath == "-" {
		inFile = os.Stdin
	} else {
		inFile, err = os.Open(inFilePath)
		if err != nil {
			panic(err)
		}
	}
	defer inFile.Close()

	var outFile *os.File
	if outFilePath == "-" {
		outFile = os.Stdout
	} else {
		outFile, err = os.OpenFile("encrypted-file", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
		if err != nil {
			panic(err)
		}
	}
	defer outFile.Close()

	if doDecrypt {
		privKey, err := openPrivKey(privKeyPath)
		if err != nil {
			panic(err)
		}
		gpgDecrypt(privKey, inFile, outFile)
		return
	}

	pubKey, err := openPubKey(pubKeyPath)
	if err != nil {
		panic(err)
	}
	gpgEncrypt(pubKey, inFile, outFile)

}


text:
package org.spongepowered.api.event;

import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.api.eventgencore.annotation.AbsoluteSortPosition;
import org.spongepowered.api.eventgencore.annotation.ImplementedBy;

/**
 * An event called within Sponge.
 *
 *
This is a marker interface, which must be implemented
 * by any event used with the Sponge event bus.

 */
@ImplementedBy(value = AbstractEvent.class, priority = Integer.MIN_VALUE)
public interface Event {
    /**
     * Get the cause for the event.
     *
     * @return The last cause
     */
    @AbsoluteSortPosition(0)
    Cause getCause();
}


text:
namespace Ui {
class CreateIngridientWindow;
}

class CreateIngridientWindow : public QDialog, IUpdatable
{
    Q_OBJECT

    Q_INTERFACES(IUpdatable)

public:
    explicit CreateIngridientWindow(MpDatabase* db = 0, QWidget *parent = 0);
    ~CreateIngridientWindow();

private slots:

    void on_SaveIngtoDbButton_clicked();

    void on_IngBackButton_clicked();

private:

    void UpdateMethod();
    MpDatabase* IngredientWinDB;
    Ui::CreateIngridientWindow *ui;
};

#endif // CREATEINGRIDIENTWINDOW_H