text:
// Copyright 2015 Google Inc. 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.analysis.util;

import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.getFirstArtifactEndingWith;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactOwner;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.MapBasedActionGraph;
import com.google.devtools.build.lib.actions.MiddlemanFactory;
import com.google.devtools.build.lib.actions.MutableActionGraph;
import com.google.devtools.build.lib.actions.ResourceManager;
import com.google.devtools.build.lib.actions.ResourceSet;
import com.google.devtools.build.lib.actions.Root;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
import com.google.devtools.build.lib.analysis.AnalysisEnvironment;
import com.google.devtools.build.lib.analysis.AnalysisHooks;
import com.google.devtools.build.lib.analysis.AnalysisUtils;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.BuildView;
import com.google.devtools.build.lib.analysis.BuildView.AnalysisResult;
import com.google.devtools.build.lib.analysis.CachingAnalysisEnvironment;
import com.google.devtools.build.lib.analysis.ConfiguredAspectFactory;
import com.google.devtools.build.lib.analysis.ConfiguredAttributeMapper;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.ExtraActionArtifactsProvider;
import com.google.devtools.build.lib.analysis.FileConfiguredTarget;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.LabelAndConfiguration;
import com.google.devtools.build.lib.analysis.OutputGroupProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.RunfilesSupport;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.analysis.WorkspaceStatusAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.buildinfo.BuildInfoFactory.BuildInfoKey;
import com.google.devtools.build.lib.analysis.config.BinTools;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationCollection;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.ConfigurationFactory;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.buildtool.BuildRequest;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.StoredEventHandler;
import com.google.devtools.build.lib.exec.ExecutionOptions;
import com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.ConstantRuleVisibility;
import com.google.devtools.build.lib.packages.NoSuchPackageException;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.OutputFile;
import com.google.devtools.build.lib.packages.PackageFactory;
import com.google.devtools.build.lib.packages.PackageFactory.EnvironmentExtension;
import com.google.devtools.build.lib.packages.PackageIdentifier;
import com.google.devtools.build.lib.packages.Preprocessor;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.packages.util.MockToolsConfig;
import com.google.devtools.build.lib.pkgcache.LoadingPhaseRunner;
import com.google.devtools.build.lib.pkgcache.LoadingPhaseRunner.LoadingResult;
import com.google.devtools.build.lib.pkgcache.PackageCacheOptions;
import com.google.devtools.build.lib.pkgcache.PackageManager;
import com.google.devtools.build.lib.pkgcache.PathPackageLocator;
import com.google.devtools.build.lib.pkgcache.TransitivePackageLoader;
import com.google.devtools.build.lib.rules.test.BaselineCoverageAction;
import com.google.devtools.build.lib.skyframe.AspectValue;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetKey;
import com.google.devtools.build.lib.skyframe.DiffAwareness;
import com.google.devtools.build.lib.skyframe.PrecomputedValue;
import com.google.devtools.build.lib.skyframe.SequencedSkyframeExecutor;
import com.google.devtools.build.lib.syntax.Label;
import com.google.devtools.build.lib.syntax.Label.SyntaxException;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.testutil.MoreAsserts;
import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.util.BlazeClock;
import com.google.devtools.build.lib.util.FileType;
import com.google.devtools.build.lib.util.StringUtil;
import com.google.devtools.build.lib.util.io.TimestampGranularityMonitor;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.common.options.Options;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsParsingException;

import org.mockito.Mockito;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * Common test code that creates a BuildView instance.
 */
public abstract class BuildViewTestCase extends FoundationTestCase {
  protected static final int LOADING_PHASE_THREADS = 20;

  protected ConfiguredRuleClassProvider ruleClassProvider;
  protected ConfigurationFactory configurationFactory;
  protected BuildView view;

  private SequencedSkyframeExecutor skyframeExecutor;

  protected BlazeDirectories directories;
  protected BinTools binTools;

  // Note that these configurations are virtual (they use only VFS)
  protected BuildConfigurationCollection masterConfig;
  protected BuildConfiguration targetConfig;  // "target" or "build" config

  protected OptionsParser optionsParser;
  private PackageCacheOptions packageCacheOptions;

  protected MockToolsConfig mockToolsConfig;

  protected WorkspaceStatusAction.Factory workspaceStatusActionFactory;

  private MutableActionGraph mutableActionGraph;

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    AnalysisMock mock = getAnalysisMock();
    directories = new BlazeDirectories(outputBase, outputBase, rootDirectory);
    binTools = BinTools.forUnitTesting(directories, TestConstants.EMBEDDED_TOOLS);
    mockToolsConfig = new MockToolsConfig(rootDirectory, false);
    mock.setupMockClient(mockToolsConfig);
    mock.setupMockWorkspaceFiles(directories.getEmbeddedBinariesRoot());

    configurationFactory = mock.createConfigurationFactory();
    packageCacheOptions = parsePackageCacheOptions();
    workspaceStatusActionFactory =
        new AnalysisTestUtil.DummyWorkspaceStatusActionFactory(directories);
    mutableActionGraph = new MapBasedActionGraph();
    ruleClassProvider = getRuleClassProvider();
    skyframeExecutor = SequencedSkyframeExecutor.create(reporter,
        new PackageFactory(ruleClassProvider, getEnvironmentExtensions()),
        new TimestampGranularityMonitor(BlazeClock.instance()), directories,
        workspaceStatusActionFactory,
        ruleClassProvider.getBuildInfoFactories(),
        ImmutableSet.<Path>of(),
        ImmutableList.<DiffAwareness.Factory>of(),
        Predicates.<PathFragment>alwaysFalse(),
        getPreprocessorFactorySupplier(),
        ImmutableMap.<SkyFunctionName, SkyFunction>of(),
        getPrecomputedValues()
    );
    skyframeExecutor.preparePackageLoading(
        new PathPackageLocator(rootDirectory), ConstantRuleVisibility.PUBLIC, true, 7, "",
        UUID.randomUUID());
    useConfiguration();
    setUpSkyframe();
    // Also initializes ResourceManager.
    ResourceManager.instance().setAvailableResources(getStartingResources());
  }

  protected AnalysisMock getAnalysisMock() {
    try {
      Class<?> providerClass = Class.forName(TestConstants.TEST_ANALYSIS_MOCK);
      Field instanceField = providerClass.getField("INSTANCE");
      return (AnalysisMock) instanceField.get(null);
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }

  /** Creates or retrieves the rule class provider used in this test. */
  protected ConfiguredRuleClassProvider getRuleClassProvider() {
    return TestRuleClassProvider.getRuleClassProvider();
  }

  protected Iterable<EnvironmentExtension> getEnvironmentExtensions() {
    return ImmutableList.<EnvironmentExtension>of();
  }

  protected ImmutableList<PrecomputedValue.Injected> getPrecomputedValues() {
    return ImmutableList.of();
  }

  protected Preprocessor.Factory.Supplier getPreprocessorFactorySupplier() {
    return Preprocessor.Factory.Supplier.NullSupplier.INSTANCE;
  }

  protected ResourceSet getStartingResources() {
    // Effectively disable ResourceManager by default.
    return ResourceSet.createWithRamCpuIo(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);
  }

  protected final BuildConfigurationCollection createConfigurations(String... args)
      throws Exception {
    optionsParser = OptionsParser.newOptionsParser(Iterables.concat(Arrays.asList(
          ExecutionOptions.class,
          BuildRequest.BuildRequestOptions.class),
          ruleClassProvider.getConfigurationOptions()));
    try {
      List<String> configurationArgs = new ArrayList<>();
      configurationArgs.add("--experimental_extended_sanity_checks");
      configurationArgs.addAll(getAnalysisMock().getOptionOverrides());

      optionsParser.parse(configurationArgs);
      optionsParser.parse(args);

      configurationFactory.forbidSanityCheck();
      BuildOptions buildOptions = ruleClassProvider.createBuildOptions(optionsParser);
      ensureTargetsVisited(buildOptions.getAllLabels().values());
      skyframeExecutor.invalidateConfigurationCollection();
      return skyframeExecutor.createConfigurations(configurationFactory, buildOptions, directories,
          ImmutableSet.<String>of(), false);
    } catch (InvalidConfigurationException | OptionsParsingException e) {
      throw new IllegalArgumentException(e);
    }
  }

  protected Target getTarget(String label)
      throws NoSuchPackageException, NoSuchTargetException,
             Label.SyntaxException, InterruptedException {
    return getTarget(Label.parseAbsolute(label));
  }

  protected Target getTarget(Label label)
      throws NoSuchPackageException, NoSuchTargetException, InterruptedException {
    return getPackageManager().getTarget(reporter, label);
  }

  private void setUpSkyframe() {
    PathPackageLocator pkgLocator = PathPackageLocator.create(
        null, packageCacheOptions.packagePath, reporter, rootDirectory, rootDirectory);
    skyframeExecutor.preparePackageLoading(pkgLocator,
        packageCacheOptions.defaultVisibility, true,
        7, ruleClassProvider.getDefaultsPackageContent(optionsParser),
        UUID.randomUUID());
    skyframeExecutor.setDeletedPackages(ImmutableSet.copyOf(packageCacheOptions.deletedPackages));
  }

  protected void setPackageCacheOptions(String... options) throws Exception {
    packageCacheOptions = parsePackageCacheOptions(options);
    setUpSkyframe();
  }

  private PackageCacheOptions parsePackageCacheOptions(String... options) throws Exception {
    OptionsParser parser = OptionsParser.newOptionsParser(PackageCacheOptions.class);
    parser.parse("--default_visibility=public");
    parser.parse(options);
    return parser.getOptions(PackageCacheOptions.class);
  }

  /** Used by skyframe-only tests. */
  protected SequencedSkyframeExecutor getSkyframeExecutor() {
    return Preconditions.checkNotNull(skyframeExecutor);
  }

  protected PackageManager getPackageManager() {
    return skyframeExecutor.getPackageManager();
  }

  protected AnalysisHooks getAnalysisHooks() {
    return new AnalysisHooks() {
      @Override
      public PackageManager getPackageManager() {
        return BuildViewTestCase.this.getPackageManager();
      }

      @Override
      public ConfiguredTarget getExistingConfiguredTarget(Target target,
          BuildConfiguration configuration) {
        return view.getExistingConfiguredTarget(target, configuration);
      }

    };
  }

  /**
   * Invalidates all existing packages.
   * @throws InterruptedException
   */
  protected void invalidatePackages() throws InterruptedException {
    skyframeExecutor.invalidateFilesUnderPathForTesting(ModifiedFileSet.EVERYTHING_MODIFIED,
        rootDirectory);
  }

  /**
   * Sets host and target configuration using the specified options, falling back to the default
   * options for unspecified ones, and recreates the build view.
   *
   * @throws IllegalArgumentException
   */
  protected final void useConfiguration(String... args) throws Exception {
    masterConfig = createConfigurations(args);
    targetConfig = getTargetConfiguration();
    createBuildView();
  }

  /**
   * Creates BuildView using current hostConfig/targetConfig values.
   * Ensures that hostConfig is either identical to the targetConfig or has
   * 'host' short name.
   */
  protected final void createBuildView() throws Exception {
    Preconditions.checkNotNull(masterConfig);
    Preconditions.checkState(getHostConfiguration() == getTargetConfiguration()
        || getHostConfiguration().isHostConfiguration(),
        "Host configuration %s is not a host configuration' "
        + "and does not match target configuration %s",
        getHostConfiguration(), getTargetConfiguration());

    String defaultsPackageContent = ruleClassProvider.getDefaultsPackageContent(optionsParser);
    skyframeExecutor.setupDefaultPackage(defaultsPackageContent);
    skyframeExecutor.dropConfiguredTargets();

    view = new BuildView(directories, getPackageManager(), ruleClassProvider, skyframeExecutor,
        binTools, null);
    view.setConfigurationsForTesting(masterConfig);

    view.setArtifactRoots(
        ImmutableMap.of(PackageIdentifier.createInDefaultRepo(""), rootDirectory));
    simulateLoadingPhase();
  }

  protected CachingAnalysisEnvironment getTestAnalysisEnvironment() {
    return new CachingAnalysisEnvironment(view.getArtifactFactory(),
        ArtifactOwner.NULL_OWNER, /*isSystemEnv=*/true, /*extendedSanityChecks*/false, reporter,
        /*skyframeEnv=*/ null, /*actionsEnabled=*/true, binTools);
  }

  /**
   * Allows access to the prerequisites of a configured target. This is currently used in some tests
   * to reach into the internals of RuleCT for white box testing. In principle, this should not be
   * used; instead tests should only assert on properties of the exposed provider instances and / or
   * the action graph.
   */
  protected Iterable<ConfiguredTarget> getDirectPrerequisites(ConfiguredTarget target) {
    return view.getDirectPrerequisites(target);
  }

  /**
   * Creates and returns a rule context that is equivalent to the one that was used to create the
   * given configured target.
   */
  protected RuleContext getRuleContext(ConfiguredTarget target) {
    return view.getRuleContextForTesting(target, new StubAnalysisEnvironment());
  }

  /**
   * Creates and returns a rule context to use for Skylark tests that is equivalent to the one
   * that was used to create the given configured target.
   */
  protected RuleContext getRuleContextForSkylark(ConfiguredTarget target) {
    // TODO(bazel-team): we need this horrible workaround because CachingAnalysisEnvironment
    // only works with StoredErrorEventListener despite the fact it accepts the interface
    // ErrorEventListener, so it's not possible to create it with reporter.
    // See BuildView.getRuleContextForTesting().
    StoredEventHandler eventHandler = new StoredEventHandler() {
      @Override
      public synchronized void handle(Event e) {
        super.handle(e);
        reporter.handle(e);
      }
    };
    return view.getRuleContextForTesting(target, eventHandler);
  }

  /**
   * Allows access to the prerequisites of a configured target. This is currently used in some tests
   * to reach into the internals of RuleCT for white box testing. In principle, this should not be
   * used; instead tests should only assert on properties of the exposed provider instances and / or
   * the action graph.
   */
  protected List<? extends TransitiveInfoCollection> getPrerequisites(ConfiguredTarget target,
      String attributeName) {
    return getRuleContext(target).getConfiguredTargetMap().get(attributeName);
  }

  /**
   * Allows access to the prerequisites of a configured target. This is currently used in some tests
   * to reach into the internals of RuleCT for white box testing. In principle, this should not be
   * used; instead tests should only assert on properties of the exposed provider instances and / or
   * the action graph.
   */
  protected <C extends TransitiveInfoProvider> Iterable<C> getPrerequisites(
      ConfiguredTarget target, String attributeName, Class<C> classType) {
    return AnalysisUtils.getProviders(getPrerequisites(target, attributeName), classType);
  }

  /**
   * Allows access to the prerequisites of a configured target. This is currently used in some tests
   * to reach into the internals of RuleCT for white box testing. In principle, this should not be
   * used; instead tests should only assert on properties of the exposed provider instances and / or
   * the action graph.
   */
  protected ImmutableList<Artifact> getPrerequisiteArtifacts(
      ConfiguredTarget target, String attributeName) {
    Set<Artifact> result = new LinkedHashSet<>();
    for (FileProvider provider : getPrerequisites(target, attributeName, FileProvider.class)) {
      Iterables.addAll(result, provider.getFilesToBuild());
    }
    return ImmutableList.copyOf(result);
  }

  protected final Action getGeneratingAction(Artifact artifact) {
    Preconditions.checkNotNull(artifact);
    Action action = mutableActionGraph.getGeneratingAction(artifact);
    if (action != null) {
      return action;
    }
    return view.getActionGraph().getGeneratingAction(artifact);
  }

  protected void simulateLoadingPhase() {
    try {
      ensureTargetsVisited(targetConfig.getAllLabels().values());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  protected ActionsTestUtil actionsTestUtil() {
    return new ActionsTestUtil(view.getActionGraph());
  }

  private Set<Target> getTargets(Iterable<Label> labels) throws InterruptedException,
      NoSuchTargetException, NoSuchPackageException{
    Set<Target> targets = Sets.newHashSet();
    for (Label label : labels) {
      targets.add(skyframeExecutor.getPackageManager().getTarget(reporter, label));
    }
    return targets;
  }

  // Get a MutableActionGraph for testing purposes.
  protected MutableActionGraph getMutableActionGraph() {
    return mutableActionGraph;
  }

  protected TransitivePackageLoader makeVisitor() {
    setUpSkyframe();
    return skyframeExecutor.pkgLoader();
  }

  /**
   * Construct the containing package of the specified labels, and all of its transitive
   * dependencies.  This must be done prior to configuration, as the latter is intolerant of
   * NoSuchTargetExceptions.
   */
  protected boolean ensureTargetsVisited(TransitivePackageLoader visitor,
      Collection<Label> targets, Collection<Label> labels, boolean keepGoing)
          throws InterruptedException, NoSuchTargetException, NoSuchPackageException {
    boolean success = visitor.sync(reporter,
        ImmutableSet.copyOf(getTargets(targets)),
        ImmutableSet.copyOf(labels),
        keepGoing,
        /*parallelThreads=*/4,
        /*maxDepth=*/Integer.MAX_VALUE);
    return success;
  }

  protected boolean ensureTargetsVisited(Collection<Label> labels)
      throws InterruptedException, NoSuchTargetException, NoSuchPackageException {
    return ensureTargetsVisited(makeVisitor(), ImmutableSet.<Label>of(), labels,
        /*keepGoing=*/false);
  }

  protected boolean ensureTargetsVisited(Label label)
      throws InterruptedException, NoSuchTargetException, NoSuchPackageException {
    return ensureTargetsVisited(ImmutableList.of(label));
  }

  protected boolean ensureTargetsVisited(String... labels)
      throws InterruptedException, NoSuchTargetException, NoSuchPackageException, SyntaxException {
    List<Label> actualLabels = new ArrayList<>();
    for (String label : labels) {
      actualLabels.add(Label.parseAbsolute(label));
    }
    return ensureTargetsVisited(actualLabels);
  }

  /**
   * Returns the ConfiguredTarget for the specified label, configured for the
   * "build" (aka "target") configuration.
   */
  protected ConfiguredTarget getConfiguredTarget(String label)
      throws NoSuchPackageException, NoSuchTargetException,
             Label.SyntaxException, InterruptedException {
    return getConfiguredTarget(label, targetConfig);
  }

  /**
   * Returns the ConfiguredTarget for the specified label, using the
   * given build configuration.
   */
  protected ConfiguredTarget getConfiguredTarget(String label, BuildConfiguration config)
      throws NoSuchPackageException, NoSuchTargetException,
             Label.SyntaxException, InterruptedException {
    ensureTargetsVisited(label);
    return view.getConfiguredTargetForTesting(getTarget(label), config);
  }

  /**
   * Returns the ConfiguredTarget for the specified label, using the
   * given build configuration.
   */
  protected ConfiguredTarget getConfiguredTarget(Label label, BuildConfiguration config)
      throws NoSuchPackageException, NoSuchTargetException, InterruptedException {
    ensureTargetsVisited(label);
    return view.getConfiguredTargetForTesting(getTarget(label), config);
  }

  /**
   * Returns the ConfiguredTarget for the specified file label, configured for
   * the "build" (aka "target") configuration.
   */
  protected FileConfiguredTarget getFileConfiguredTarget(String label)
      throws NoSuchPackageException, NoSuchTargetException,
             Label.SyntaxException, InterruptedException {
    return (FileConfiguredTarget) getConfiguredTarget(label, targetConfig);
  }

  /**
   * Returns the ConfiguredTarget for the specified label, configured for
   * the "host" configuration.
   */
  protected ConfiguredTarget getHostConfiguredTarget(String label)
      throws NoSuchPackageException, NoSuchTargetException,
             Label.SyntaxException, InterruptedException {
    return getConfiguredTarget(label, getHostConfiguration());
  }

  /**
   * Returns the ConfiguredTarget for the specified file label, configured for
   * the "host" configuration.
   */
  protected FileConfiguredTarget getHostFileConfiguredTarget(String label)
      throws NoSuchPackageException, NoSuchTargetException,
             Label.SyntaxException, InterruptedException {
    return (FileConfiguredTarget) getHostConfiguredTarget(label);
  }

  /**
   * Create and return a configured scratch rule.
   *
   * @param packageName the package name ofthe rule.
   * @param ruleName the name of the rule.
   * @param lines the text of the rule.
   * @return the configured target instance for the created rule.
   * @throws IOException
   * @throws Exception
   */
  protected ConfiguredTarget scratchConfiguredTarget(String packageName,
                                                     String ruleName,
                                                     String... lines)
      throws IOException, Exception {
    return scratchConfiguredTarget(packageName, ruleName, targetConfig, lines);
  }

  /**
   * Create and return a scratch rule.
   *
   * @param packageName the package name of the rule.
   * @param ruleName the name of the rule.
   * @param lines the text of the rule.
   * @return the rule instance for the created rule.
   * @throws IOException
   * @throws Exception
   */
  protected Rule scratchRule(String packageName, String ruleName, String... lines)
      throws Exception {
    scratch.file(packageName + "/BUILD", lines);
    return (Rule) getTarget("//" + packageName + ":" + ruleName);
  }

  /**
   * Create and return a configured scratch rule.
   *
   * @param packageName the package name of the rule.
   * @param ruleName the name of the rule.
   * @param config the configuration to use to construct the configured rule.
   * @param lines the text of the rule.
   * @return the configured target instance for the created rule.
   * @throws IOException
   * @throws Exception
   */
  protected ConfiguredTarget scratchConfiguredTarget(String packageName,
                                                     String ruleName,
                                                     BuildConfiguration config,
                                                     String... lines)
      throws IOException, Exception {
    Target rule = scratchRule(packageName, ruleName, lines);
    if (ensureTargetsVisited(rule.getLabel())) {
      return view.getConfiguredTargetForTesting(rule, config);
    } else {
      return null;
    }
  }

  /**
   * Check that configuration of the target named 'ruleName' in the
   * specified BUILD file fails with an error message ending in
   * 'expectedErrorMessage'.
   *
   * @param packageName the package name of the generated BUILD file
   * @param ruleName the rule name for the rule in the generated BUILD file
   * @param expectedErrorMessage the expected error message.
   * @param lines the text of the rule.
   * @return the found error.
   */
  protected Event checkError(String packageName,
                             String ruleName,
                             String expectedErrorMessage,
                             String... lines) throws Exception {
    eventCollector.clear();
    reporter.removeHandler(failFastHandler); // expect errors
    ConfiguredTarget target = scratchConfiguredTarget(packageName, ruleName, lines);
    if (target != null) {
      assertTrue("Rule '" + "//" + packageName + ":" + ruleName + "' did not contain an error",
          view.hasErrors(target));
    }
    return assertContainsEvent(expectedErrorMessage);
  }

  /**
   * Check that configuration of the target named 'ruleName' in the
   * specified BUILD file reports a warning message ending in
   * 'expectedWarningMessage', and that no errors were reported.
   *
   * @param packageName the package name of the generated BUILD file
   * @param ruleName the rule name for the rule in the generated BUILD file
   * @param expectedWarningMessage the expected warning message.
   * @param lines the text of the rule.
   * @return the found error.
   */
  protected Event checkWarning(String packageName,
                               String ruleName,
                               String expectedWarningMessage,
                               String... lines) throws Exception {
    eventCollector.clear();
    ConfiguredTarget target = scratchConfiguredTarget(packageName, ruleName,
                                                     lines);
    assertFalse("Rule '" + "//" + packageName + ":" + ruleName
        + "' did contain an error",
        view.hasErrors(target));
    return assertContainsEvent(expectedWarningMessage);
  }

  /**
   * Given a collection of Artifacts, returns a corresponding set of strings of
   * the form "[root] [relpath]", such as "bin x/libx.a".  Such strings make
   * assertions easier to write.
   *
   * <p>The returned set preserves the order of the input.
   */
  protected Set<String> artifactsToStrings(Iterable<Artifact> artifacts) {
    return AnalysisTestUtil.artifactsToStrings(masterConfig, artifacts);
  }

  /**
   * Asserts that targetName's outputs are exactly expectedOuts.
   *
   * @param targetName The label of a rule.
   * @param expectedOuts The labels of the expected outputs of the rule.
   */
  protected void assertOuts(String targetName, String... expectedOuts) throws Exception {
    Rule ruleTarget = (Rule) getTarget(targetName);
    for (String expectedOut : expectedOuts) {
      Target outTarget = getTarget(expectedOut);
      if (!(outTarget instanceof OutputFile)) {
        fail("Target " + outTarget + " is not an output");
        assertSame(ruleTarget, ((OutputFile) outTarget).getGeneratingRule());
        // This ensures that the output artifact is wired up in the action graph
        getConfiguredTarget(expectedOut);
      }
    }

    Collection<OutputFile> outs = ruleTarget.getOutputFiles();
    assertEquals("Mismatched outputs: " + outs, expectedOuts.length, outs.size());
  }

  /**
   * Asserts that there exists a configured target file for the given label.
   */
  protected void assertConfiguredTargetExists(String label) throws Exception {
    assertNotNull(getFileConfiguredTarget(label));
  }

  /**
   * Assert that the first label and the second label are both generated
   * by the same command.
   */
  protected void assertSameGeneratingAction(String labelA, String labelB)
      throws Exception {
    assertSame(
        "Action for " + labelA + " did not match " + labelB,
        getGeneratingActionForLabel(labelA),
        getGeneratingActionForLabel(labelB));
  }

  protected Artifact getSourceArtifact(PathFragment rootRelativePath, Root root) {
    return view.getArtifactFactory().getSourceArtifact(rootRelativePath, root);
  }

  protected Artifact getSourceArtifact(String name) {
    return getSourceArtifact(new PathFragment(name), Root.asSourceRoot(rootDirectory));
  }

  /**
   * Gets a derived artifact, creating it if necessary. {@code ArtifactOwner} should be a genuine
   * {@link LabelAndConfiguration} corresponding to a {@link ConfiguredTarget}. If called from a
   * test that does not exercise the analysis phase, the convenience methods {@link
   * #getBinArtifactWithNoOwner} or {@link #getGenfilesArtifactWithNoOwner} should be used instead.
   */
  protected Artifact getDerivedArtifact(PathFragment rootRelativePath, Root root,
      ArtifactOwner owner) {
    return view.getArtifactFactory().getDerivedArtifact(rootRelativePath, root, owner);
  }

  /**
   * Gets a derived Artifact for testing with path of the form
   * root/owner.getPackageFragment()/packageRelativePath.
   *
   * @see #getDerivedArtifact(PathFragment, Root, ArtifactOwner)
   */
  private Artifact getPackageRelativeDerivedArtifact(String packageRelativePath, Root root,
      ArtifactOwner owner) {
    return getDerivedArtifact(
        owner.getLabel().getPackageFragment().getRelative(packageRelativePath),
        root, owner);
  }

  /**
   * Gets a derived Artifact for testing in the {@link BuildConfiguration#getBinDirectory()}. This
   * method should only be used for tests that do no analysis, and so there is no ConfiguredTarget
   * to own this artifact. If the test runs the analysis phase, {@link
   * #getBinArtifact(String, ArtifactOwner)} or its convenience methods should be
   * used instead.
   */
  protected Artifact getBinArtifactWithNoOwner(String rootRelativePath) {
    return getDerivedArtifact(new PathFragment(rootRelativePath), targetConfig.getBinDirectory(),
        ActionsTestUtil.NULL_ARTIFACT_OWNER);
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getBinDirectory()} corresponding to the package of {@code owner}. So
   * to specify a file foo/foo.o owned by target //foo:foo, {@code packageRelativePath} should just
   * be "foo.o".
   */
  protected Artifact getBinArtifact(String packageRelativePath, String owner) {
    return getBinArtifact(packageRelativePath, makeLabelAndConfiguration(owner));
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getBinDirectory()} corresponding to the package of {@code owner}. So
   * to specify a file foo/foo.o owned by target //foo:foo, {@code packageRelativePath} should just
   * be "foo.o".
   */
  protected Artifact getBinArtifact(String packageRelativePath, ConfiguredTarget owner) {
    return getPackageRelativeDerivedArtifact(packageRelativePath,
        owner.getConfiguration().getBinDirectory(), new ConfiguredTargetKey(owner));
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getBinDirectory()} corresponding to the package of {@code owner},
   * where the given artifact belongs to the given ConfiguredTarget together with the given Aspect.
   * So to specify a file foo/foo.o owned by target //foo:foo with an apsect from FooAspect,
   * {@code packageRelativePath} should just be "foo.o", and aspectOfOwner should be
   * FooAspect.class. This method is necessary when an Apsect of the target, not the target itself,
   * is creating an Artifact.
   */
  protected Artifact getBinArtifact(String packageRelativePath, ConfiguredTarget owner,
      Class<? extends ConfiguredAspectFactory> creatingAspectFactory) {
    return getPackageRelativeDerivedArtifact(packageRelativePath,
        owner.getConfiguration().getBinDirectory(),
        (AspectValue.AspectKey) AspectValue.key(
            owner.getLabel(), owner.getConfiguration(), creatingAspectFactory).argument());
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getBinDirectory()} corresponding to the package of {@code owner}. So
   * to specify a file foo/foo.o owned by target //foo:foo, {@code packageRelativePath} should just
   * be "foo.o".
   */
  private Artifact getBinArtifact(String packageRelativePath, ArtifactOwner owner) {
    return getPackageRelativeDerivedArtifact(packageRelativePath, targetConfig.getBinDirectory(),
        owner);
  }

  /**
   * Gets a derived Artifact for testing in the {@link BuildConfiguration#getGenfilesDirectory()}.
   * This method should only be used for tests that do no analysis, and so there is no
   * ConfiguredTarget to own this artifact. If the test runs the analysis phase, {@link
   * #getGenfilesArtifact(String, ArtifactOwner)} or its convenience methods should be used instead.
   */
  protected Artifact getGenfilesArtifactWithNoOwner(String rootRelativePath) {
    return getDerivedArtifact(new PathFragment(rootRelativePath),
        targetConfig.getGenfilesDirectory(), ActionsTestUtil.NULL_ARTIFACT_OWNER);
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getGenfilesDirectory()} corresponding to the package of {@code owner}.
   * So to specify a file foo/foo.o owned by target //foo:foo, {@code packageRelativePath} should
   * just be "foo.o".
   */
  protected Artifact getGenfilesArtifact(String packageRelativePath, String owner) {
    return getGenfilesArtifact(packageRelativePath, makeLabelAndConfiguration(owner));
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getGenfilesDirectory()} corresponding to the package of {@code owner}.
   * So to specify a file foo/foo.o owned by target //foo:foo, {@code packageRelativePath} should
   * just be "foo.o".
   */
  protected Artifact getGenfilesArtifact(String packageRelativePath, ConfiguredTarget owner) {
    return getGenfilesArtifact(packageRelativePath, new ConfiguredTargetKey(owner));
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getGenfilesDirectory()} corresponding to the package of {@code owner},
   * where the given artifact belongs to the given ConfiguredTarget together with the given Aspect.
   * So to specify a file foo/foo.o owned by target //foo:foo with an apsect from FooAspect,
   * {@code packageRelativePath} should just be "foo.o", and aspectOfOwner should be
   * FooAspect.class. This method is necessary when an Apsect of the target, not the target itself,
   * is creating an Artifact.
   */
  protected Artifact getGenfilesArtifact(String packageRelativePath, ConfiguredTarget owner,
      Class<? extends ConfiguredAspectFactory> creatingAspectFactory) {
    return getPackageRelativeDerivedArtifact(packageRelativePath,
        owner.getConfiguration().getGenfilesDirectory(),
        (AspectValue.AspectKey) AspectValue.key(
            owner.getLabel(), owner.getConfiguration(), creatingAspectFactory).argument());
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getGenfilesDirectory()} corresponding to the package of {@code owner}.
   * So to specify a file foo/foo.o owned by target //foo:foo, {@code packageRelativePath} should
   * just be "foo.o".
   */
  private Artifact getGenfilesArtifact(String packageRelativePath, ArtifactOwner owner) {
    return getPackageRelativeDerivedArtifact(packageRelativePath,
        targetConfig.getGenfilesDirectory(),
        owner);
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getIncludeDirectory()} corresponding to the package of {@code owner}.
   * So to specify a file foo/foo.o owned by target //foo:foo, {@code packageRelativePath} should
   * just be "foo.h".
   */
  protected Artifact getIncludeArtifact(String packageRelativePath, String owner) {
    return getIncludeArtifact(packageRelativePath, makeLabelAndConfiguration(owner));
  }

  /**
   * Gets a derived Artifact for testing in the subdirectory of the {@link
   * BuildConfiguration#getIncludeDirectory()} corresponding to the package of {@code owner}.
   * So to specify a file foo/foo.o owned by target //foo:foo, {@code packageRelativePath} should
   * just be "foo.h".
   */
  private Artifact getIncludeArtifact(String packageRelativePath, ArtifactOwner owner) {
    return getPackageRelativeDerivedArtifact(packageRelativePath,
        targetConfig.getIncludeDirectory(),
        owner);
  }

  /**
   * @return a shared artifact at the binary-root relative path {@code rootRelativePath} owned by
   *         {@code owner}.
   *
   * @param rootRelativePath the binary-root relative path of the artifact.
   * @param owner the artifact's owner.
   */
  protected Artifact getSharedArtifact(String rootRelativePath, ConfiguredTarget owner) {
    return getDerivedArtifact(new PathFragment(rootRelativePath), targetConfig.getBinDirectory(),
        new ConfiguredTargetKey(owner));
  }

  protected Action getGeneratingActionForLabel(String label) throws Exception {
    return getGeneratingAction(getFileConfiguredTarget(label).getArtifact());
  }

  protected String fileName(Artifact artifact) {
    return artifact.getExecPathString();
  }

  protected String fileName(FileConfiguredTarget target) {
    return fileName(target.getArtifact());
  }

  protected String fileName(String name) throws Exception {
    return fileName(getFileConfiguredTarget(name));
  }

  protected Path getOutputPath() {
    return directories.getOutputPath();
  }

  /**
   * Verifies whether the rule checks the 'srcs' attribute validity.
   *
   * <p>At the call site it expects the {@code packageName} to contain:
   * <ol>
   *   <li>{@code :gvalid} - genrule that outputs a valid file</li>
   *   <li>{@code :ginvalid} - genrule that outputs an invalid file</li>
   *   <li>{@code :gmix} - genrule that outputs a mix of valid and invalid
   *       files</li>
   *   <li>{@code :valid} - rule of type {@code ruleType} that has a valid
   *       file, {@code :gvalid} and {@code :gmix} in the srcs</li>
   *   <li>{@code :invalid} - rule of type {@code ruleType} that has an invalid
   *       file, {@code :ginvalid} in the srcs</li>
   *   <li>{@code :mix} - rule of type {@code ruleType} that has a valid and an
   *       invalid file in the srcs</li>
   * </ol>
   *
   * @param packageName the package where the rules under test are located
   * @param ruleType rules under test types
   * @param expectedTypes expected file types
   */
  protected void assertSrcsValidityForRuleType(String packageName, String ruleType,
      String expectedTypes) throws Exception {
    reporter.removeHandler(failFastHandler);
    String descriptionSingle = ruleType + " srcs file (expected " + expectedTypes + ")";
    String descriptionPlural = ruleType + " srcs files (expected " + expectedTypes + ")";
    String descriptionPluralFile = "(expected " + expectedTypes + ")";
    assertSrcsValidity(ruleType, packageName + ":valid", false,
        "need at least one " + descriptionSingle,
        "'" + packageName + ":gvalid' does not produce any " + descriptionPlural,
        "'" + packageName + ":gmix' does not produce any " + descriptionPlural);
    assertSrcsValidity(ruleType, packageName + ":invalid", true,
        "file '" + packageName + ":a.foo' is misplaced here " + descriptionPluralFile,
        "'" + packageName + ":ginvalid' does not produce any " + descriptionPlural);
    assertSrcsValidity(ruleType, packageName + ":mix", true,
        "'" + packageName + ":a.foo' does not produce any " + descriptionPlural);
  }

  protected void assertSrcsValidity(String ruleType, String targetName, boolean expectedError,
      String... expectedMessages) throws Exception{
    ConfiguredTarget target = getConfiguredTarget(targetName);
    if (expectedError) {
      assertTrue(view.hasErrors(target));
      for (String expectedMessage : expectedMessages) {
        String message = "in srcs attribute of " + ruleType + " rule " + targetName + ": "
            + expectedMessage;
        assertContainsEvent(message);
      }
    } else {
      assertFalse(view.hasErrors(target));
      for (String expectedMessage : expectedMessages) {
        String message = "in srcs attribute of " + ruleType + " rule " + target.getLabel() + ": "
            + expectedMessage;
        assertDoesNotContainEvent(message);
      }
    }
  }

  private static Label makeLabel(String label) {
    try {
      return Label.parseAbsolute(label);
    } catch (SyntaxException e) {
      throw new IllegalStateException(e);
    }
  }

  private ConfiguredTargetKey makeLabelAndConfiguration(String label) {
    return new ConfiguredTargetKey(makeLabel(label), targetConfig);
  }

  protected static List<String> actionInputsToPaths(Iterable<? extends ActionInput> actionInputs) {
    return ImmutableList.copyOf(
        Iterables.transform(actionInputs, new Function<ActionInput, String>() {
          @Override
          public String apply(ActionInput actionInput) {
            return actionInput.getExecPathString();
          }
        }));
  }

  protected String readContentAsLatin1String(Artifact artifact) throws IOException {
    return new String(FileSystemUtils.readContentAsLatin1(artifact.getPath()));
  }

  /**
   * Asserts that the predecessor closure of the given Artifact contains the same elements as those
   * in expectedPredecessors, plus the given common predecessors.  Only looks at predecessors of
   * the given file type.
   */
  public void assertPredecessorClosureSameContents(
      Artifact artifact, FileType fType, Iterable<String> common, String... expectedPredecessors) {
    assertSameContentsWithCommonElements(
        actionsTestUtil().predecessorClosureAsCollection(artifact, fType),
        expectedPredecessors, common);
  }

  /**
   * Utility method for asserting that the contents of one collection are the
   * same as those in a second plus some set of common elements.
   */
  protected void assertSameContentsWithCommonElements(Iterable<Artifact> artifacts,
      Iterable<String> common, String... expectedInputs) {
    MoreAsserts.assertSameContents(Iterables.concat(Lists.newArrayList(expectedInputs), common),
        ActionsTestUtil.prettyArtifactNames(artifacts));
  }

  /**
   * Utility method for asserting that the contents of one collection are the
   * same as those in a second plus some set of common elements.
   */
  protected void assertSameContentsWithCommonElements(Iterable<String> artifacts,
      String[] expectedInputs, Iterable<String> common) {
    MoreAsserts.assertSameContents(Iterables.concat(Lists.newArrayList(expectedInputs), common),
        artifacts);
  }

  /**
   * Utility method for asserting that a list contains the elements of a
   * sublist This is useful for checking that a list of arguments contains a
   * particular set of arguments.
   */
  protected void assertContainsSublist(List<String> list, List<String> sublist) {
    assertContainsSublist(null, list, sublist);
  }

  /**
   * Utility method for asserting that a list contains the elements of a
   * sublist This is useful for checking that a list of arguments contains a
   * particular set of arguments.
   */
  protected void assertContainsSublist(String message, List<String> list, List<String> sublist) {
    if (Collections.indexOfSubList(list, sublist) == -1) {
      fail((message == null ? "" : (message + ' '))
          + "expected: <" + list + "> to contain sublist: <" + sublist + ">");
    }
  }

  protected void assertContainsSelfEdgeEvent(String label) {
    assertContainsEvent(label + " [self-edge]");
  }

  protected Iterable<Artifact> collectRunfiles(ConfiguredTarget target) {
    RunfilesProvider runfilesProvider = target.getProvider(RunfilesProvider.class);
    if (runfilesProvider != null) {
      return runfilesProvider.getDefaultRunfiles().getAllArtifacts();
    } else {
      return Runfiles.EMPTY.getAllArtifacts();
    }
  }

  protected NestedSet<Artifact> getFilesToBuild(TransitiveInfoCollection target) {
    return target.getProvider(FileProvider.class).getFilesToBuild();
  }

  /**
   * Returns all extra actions for that target (no transitive actions), no duplicate actions.
   */
  protected ImmutableList<Action> getExtraActionActions(ConfiguredTarget target) {
    LinkedHashSet<Action> result = new LinkedHashSet<>();
    for (Artifact artifact : getExtraActionArtifacts(target)) {
      result.add(getGeneratingAction(artifact));
    }
    return ImmutableList.copyOf(result);
  }

  protected ImmutableList<Action> getFilesToBuildActions(ConfiguredTarget target) {
    List<Action> result = new ArrayList<>();
    for (Artifact artifact : getFilesToBuild(target)) {
      Action action = getGeneratingAction(artifact);
      if (action != null) {
        result.add(action);
      }
    }
    return ImmutableList.copyOf(result);
  }

  protected NestedSet<Artifact> getOutputGroup(
      TransitiveInfoCollection target, String outputGroup) {
    OutputGroupProvider provider = target.getProvider(OutputGroupProvider.class);
    return provider == null
        ? NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER)
        : provider.getOutputGroup(outputGroup);
  }

  protected ImmutableList<Artifact> getExtraActionArtifacts(ConfiguredTarget target) {
    return target.getProvider(ExtraActionArtifactsProvider.class).getExtraActionArtifacts();
  }

  protected Artifact getExecutable(String label) throws Exception {
    return getConfiguredTarget(label).getProvider(FilesToRunProvider.class).getExecutable();
  }

  protected Artifact getExecutable(TransitiveInfoCollection target) {
    return target.getProvider(FilesToRunProvider.class).getExecutable();
  }

  protected ImmutableList<Artifact> getFilesToRun(TransitiveInfoCollection target) {
    return target.getProvider(FilesToRunProvider.class).getFilesToRun();
  }

  protected ImmutableList<Artifact> getFilesToRun(Label label) throws Exception {
    return getConfiguredTarget(label, targetConfig)
        .getProvider(FilesToRunProvider.class).getFilesToRun();
  }

  protected ImmutableList<Artifact> getFilesToRun(String label) throws Exception {
    return getConfiguredTarget(label).getProvider(FilesToRunProvider.class).getFilesToRun();
  }

  protected RunfilesSupport getRunfilesSupport(String label) throws Exception {
    return getConfiguredTarget(label).getProvider(FilesToRunProvider.class).getRunfilesSupport();
  }

  protected RunfilesSupport getRunfilesSupport(TransitiveInfoCollection target) {
    return target.getProvider(FilesToRunProvider.class).getRunfilesSupport();
  }

  protected static Runfiles getDefaultRunfiles(ConfiguredTarget target) {
    return target.getProvider(RunfilesProvider.class).getDefaultRunfiles();
  }

  protected static Runfiles getDataRunfiles(ConfiguredTarget target) {
    return target.getProvider(RunfilesProvider.class).getDataRunfiles();
  }

  protected BuildConfiguration getTargetConfiguration() {
    return Iterables.getOnlyElement(masterConfig.getTargetConfigurations());
  }

  protected BuildConfiguration getDataConfiguration() {
    return getTargetConfiguration().getConfiguration(ConfigurationTransition.DATA);
  }

  protected BuildConfiguration getHostConfiguration() {
    return getTargetConfiguration().getConfiguration(ConfigurationTransition.HOST);
  }

  /**
   * Returns an attribute value retriever for the given rule for the target configuration.

   */
  protected AttributeMap attributes(RuleConfiguredTarget ct) {
    return ConfiguredAttributeMapper.of(ct);
  }

  protected AttributeMap attributes(ConfiguredTarget rule) {
    return attributes((RuleConfiguredTarget) rule);
  }

  protected AnalysisResult update(List<String> targets,
      boolean keepGoing,
      int loadingPhaseThreads,
      boolean doAnalysis,
      EventBus eventBus) throws Exception {

    LoadingPhaseRunner.Options loadingOptions =
        Options.getDefaults(LoadingPhaseRunner.Options.class);
    loadingOptions.loadingPhaseThreads = loadingPhaseThreads;

    BuildView.Options viewOptions = Options.getDefaults(BuildView.Options.class);
    viewOptions.keepGoing = keepGoing;

    LoadingPhaseRunner runner = new LoadingPhaseRunner(getPackageManager(),
        Collections.unmodifiableSet(ruleClassProvider.getRuleClassMap().keySet()));
    LoadingResult loadingResult = runner.execute(reporter, eventBus, targets, loadingOptions,
        getTargetConfiguration().getAllLabels(),
        viewOptions.keepGoing, /*determineTests=*/false, /*callback=*/null);
    if (!doAnalysis) {
      // TODO(bazel-team): What's supposed to happen in this case?
      return null;
    }
    return view.update(loadingResult, masterConfig, viewOptions,
        AnalysisTestUtil.TOP_LEVEL_ARTIFACT_CONTEXT, reporter, eventBus);
  }

  protected static Predicate<Artifact> artifactNamed(final String name) {
    return new Predicate<Artifact>() {
      @Override
      public boolean apply(Artifact input) {
        return name.equals(input.prettyPrint());
      }
    };
  }

  /**
   * Utility method for tests. Converts an array of strings into a set of labels.
   *
   * @param strings the set of strings to be converted to labels.
   * @throws SyntaxException if there are any syntax errors in the strings.
   */
  public static Set<Label> asLabelSet(String... strings) throws SyntaxException {
    return asLabelSet(ImmutableList.copyOf(strings));
  }

  /**
   * Utility method for tests. Converts an array of strings into a set of labels.
   *
   * @param strings the set of strings to be converted to labels.
   * @throws SyntaxException if there are any syntax errors in the strings.
   */
  public static Set<Label> asLabelSet(Iterable<String> strings) throws SyntaxException {
    Set<Label> result = Sets.newTreeSet();
    for (String s : strings) {
      result.add(Label.parseAbsolute(s));
    }
    return result;
  }

  protected SpawnAction getGeneratingAction(ConfiguredTarget target,
      String outputName) {
    Artifact found = Iterables.find(getFilesToBuild(target),
        artifactNamed(outputName));
    return (SpawnAction) getGeneratingAction(found);
  }

  protected String getErrorMsgSingleFile(String attrName, String ruleType, String ruleName,
      String depRuleName) {
    return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": '"
        + depRuleName + "' must produce a single file";
  }

  protected String getErrorMsgNoGoodFiles(String attrName, String ruleType, String ruleName,
      String depRuleName) {
    return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": '"
        + depRuleName + "' does not produce any " + ruleType + " " + attrName + " files";
  }

  protected String getErrorMsgMisplacedFiles(String attrName, String ruleType, String ruleName,
      String fileName) {
    return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": file '"
        + fileName + "' is misplaced here";
  }

  protected String getErrorNonExistingTarget(String attrName, String ruleType, String ruleName,
      String targetName) {
    return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": target '"
        + targetName + "' does not exist";
  }

  protected String getErrorNonExistingRule(String attrName, String ruleType, String ruleName,
      String targetName) {
    return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": rule '"
        + targetName + "' does not exist";
  }

  protected String getErrorMsgMisplacedRules(String attrName, String ruleType, String ruleName,
      String depRuleType, String depRuleName) {
    return "in " + attrName + " attribute of " + ruleType + " rule " + ruleName + ": "
        + depRuleType + " rule '" + depRuleName + "' is misplaced here";
  }

  protected String getErrorMsgNonEmptyList(String attrName, String ruleType, String ruleName) {
    return "non empty attribute '" + attrName + "' in '" + ruleType
        + "' rule '" + ruleName + "' has to have at least one value";
  }

  protected String getErrorMsgMandatoryMissing(String attrName, String ruleType) {
    return "missing value for mandatory attribute '" + attrName + "' in '" + ruleType + "' rule";
  }

  protected String getErrorMsgWrongAttributeValue(String value, String... expected) {
    return String.format("has to be one of %s instead of '%s'",
          StringUtil.joinEnglishList(ImmutableSet.copyOf(expected), "or", "'"), value);
  }

  /**
   * A stub analysis environment.
   */
  protected class StubAnalysisEnvironment implements AnalysisEnvironment {

    @Override
    public void registerAction(Action... action) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean hasErrors() {
      return false;
    }

    @Override
    public Artifact getEmbeddedToolArtifact(String embeddedPath) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Artifact getConstantMetadataArtifact(PathFragment rootRelativePath, Root root) {
      throw new UnsupportedOperationException();
    }

    @Override
    public EventHandler getEventHandler() {
      return reporter;
    }

    @Override
    public MiddlemanFactory getMiddlemanFactory() {
      throw new UnsupportedOperationException();
    }

    @Override
    public Action getLocalGeneratingAction(Artifact artifact) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Iterable<Action> getRegisteredActions() {
      throw new UnsupportedOperationException();
    }

    @Override
    public SkyFunction.Environment getSkyframeEnv() {
      throw new UnsupportedOperationException();
    }

    @Override
    public Artifact getFilesetArtifact(PathFragment rootRelativePath, Root root) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Artifact getDerivedArtifact(PathFragment rootRelativePath, Root root) {
      throw new UnsupportedOperationException();
    }

    @Override
    public Artifact getStableWorkspaceStatusArtifact() {
      throw new UnsupportedOperationException();
    }

    @Override
    public Artifact getVolatileWorkspaceStatusArtifact() {
      throw new UnsupportedOperationException();
    }

    @Override
    public ImmutableList<Artifact> getBuildInfo(RuleContext ruleContext, BuildInfoKey key) {
      throw new UnsupportedOperationException();
    }

    @Override
    public ArtifactOwner getOwner() {
      throw new UnsupportedOperationException();
    }

    @Override
    public ImmutableSet<Artifact> getOrphanArtifacts() {
      throw new UnsupportedOperationException();
    }
  }

  protected Iterable<String> baselineCoverageArtifactBasenames(ConfiguredTarget target)
      throws Exception {
    Artifact baselineCoverage = Iterables.getOnlyElement(target
        .getProvider(OutputGroupProvider.class)
        .getOutputGroup(OutputGroupProvider.BASELINE_COVERAGE));
    BaselineCoverageAction baselineAction =
        (BaselineCoverageAction) getGeneratingAction(baselineCoverage);

    EventBus eventBus = new EventBus();
    Executor mockExecutor = Mockito.mock(Executor.class);
    Mockito.when(mockExecutor.getEventBus()).thenReturn(eventBus);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    baselineAction.newDeterministicWriter(reporter, mockExecutor).writeOutputFile(bytes);

    ImmutableList.Builder<String> basenames = ImmutableList.builder();
    for (String line : new String(bytes.toByteArray(), StandardCharsets.UTF_8).split("\n")) {
      if (line.startsWith("SF:")) {
        String basename = line.substring(line.lastIndexOf('/') + 1);
        basenames.add(basename);
      }
    }

    return basenames.build();
  }

  /**
   * Finds an artifact in the transitive closure of a set of other artifacts by following a path
   * based on artifact name suffixes.
   *
   * <p>This selects the first artifact in the input set that matches the first suffix, then selects
   * the first artifact in the inputs of its generating action that matches the second suffix etc.,
   * and repeats this until the supplied suffixes run out.
   */
  protected Artifact artifactByPath(Iterable<Artifact> artifacts, String... suffixes) {
    Artifact artifact = getFirstArtifactEndingWith(artifacts, suffixes[0]);

    for (int i = 1; i < suffixes.length; i++) {
      artifacts = getGeneratingAction(artifact).getInputs();
      artifact = getFirstArtifactEndingWith(artifacts, suffixes[i]);
    }

    return artifact;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.neo4j.cypher.internal.compiler.v2_3.pipes

import org.neo4j.cypher.internal.compiler.v2_3._
import org.neo4j.cypher.internal.compiler.v2_3.commands.expressions.Identifier
import org.neo4j.cypher.internal.compiler.v2_3.executionplan.Effects._
import org.neo4j.cypher.internal.compiler.v2_3.helpers.CollectionSupport
import org.neo4j.cypher.internal.compiler.v2_3.mutation._
import org.neo4j.cypher.internal.compiler.v2_3.symbols.SymbolTable
import org.neo4j.cypher.internal.frontend.v2_3.{InternalException, ParameterWrongTypeException, SyntaxException}
import org.neo4j.graphdb.NotInTransactionException

import scala.collection.mutable

case class ExecuteUpdateCommandsPipe(source: Pipe, commands: Seq[UpdateAction])(implicit pipeMonitor: PipeMonitor)
  extends PipeWithSource(source, pipeMonitor) with CollectionSupport with NoLushEntityCreation {

  protected def internalCreateResults(input: Iterator[ExecutionContext],state: QueryState) = input.flatMap {
    case ctx => executeMutationCommands(ctx, state, commands.size == 1)
  }

  private def executeMutationCommands(ctx: ExecutionContext,
                                      state: QueryState,
                                      singleCommand: Boolean): Iterator[ExecutionContext] =
    try {
      commands.foldLeft(Iterator(ctx))((context, cmd) => context.flatMap(c => exec(cmd, c, state, singleCommand)))
    } catch {
      case e: NotInTransactionException =>
        throw new InternalException("Expected to be in a transaction at this point", e)
    }

  private def exec(cmd: UpdateAction,
                   ctx: ExecutionContext,
                   state: QueryState,
                   singleCommand: Boolean): Iterator[ExecutionContext] = {

    val result: Iterator[ExecutionContext] = cmd.exec(ctx, state)

    cmd match {
      case _:CreateNode if !singleCommand =>
        singleOr(result, new ParameterWrongTypeException("If you create multiple elements, you can only create one of each."))
      case _ =>
        result
    }
  }

  def planDescription = source.planDescription.andThen(this.id, "UpdateGraph", identifiers, commands.flatMap(_.arguments):_*)

  def symbols = source.symbols.add(commands.flatMap(_.identifiers).toMap)

  def sourceSymbols: SymbolTable = source.symbols

  override def localEffects = commands.effects(sourceSymbols)

  def dup(sources: List[Pipe]): Pipe = {
    val (source :: Nil) = sources
    copy(source = source)
  }
}

// TODO: Write unit tests for this
trait NoLushEntityCreation {
  def commands: Seq[UpdateAction]

  def sourceSymbols: SymbolTable

  assertNothingIsCreatedWhenItShouldNot()

  private def extractEntities(action: UpdateAction): Seq[NamedExpectation] = action match {
    case CreateNode(key, props, labels) =>
      Seq(NamedExpectation(key, props, labels))
    case CreateRelationship(key, from, to, _, props) =>
      Seq(NamedExpectation(key, props, Seq.empty)) ++ extractIfEntity(from) ++ extractIfEntity(to)
    case CreateUniqueAction(links@_*) =>
      links.flatMap(l => Seq(l.left, l.right, l.rel))
    case MergePatternAction(_, _, _, _, Some(updates), _) =>
      updates.flatMap(extractEntities)
    case _ =>
      Seq()
  }

  private def extractIfEntity(from: RelationshipEndpoint): Option[NamedExpectation] =
    from match {
      case RelationshipEndpoint(Identifier(key), props, labels) => Some(NamedExpectation(key, props, labels))
      case _                                                    => None
    }

  private def assertNothingIsCreatedWhenItShouldNot() {
    var symbols = sourceSymbols
    val lushNodes = new mutable.HashMap[String, NamedExpectation]

    commands.foreach {
      cmd =>
        val namedExpectations = extractEntities(cmd)

        // If we find multiple lush elements, make sure they all have the same lushness
        namedExpectations.filter(expectation => !expectation.bare).foreach {
          lushExpectation =>
            lushNodes.get(lushExpectation.name) match {
              case None if symbols.hasIdentifierNamed(lushExpectation.name) => failOn(lushExpectation.name)
              case None                                                     => lushNodes += lushExpectation.name -> lushExpectation
              case Some(x) if x != lushExpectation                          => failOn(lushExpectation.name)
              case Some(x)                                                  => // same thing we've already seen. move along
            }
        }

        symbols = symbols.add(cmd.identifiers.toMap)
    }
  }

  private def failOn(name:String)=
    throw new SyntaxException("Can't create `%s` with properties or labels here. It already exists in this context".format(name))
}


Join UBER and NDTV's Roshan Dilli Campaign that aims to raise safety standards in India's capital. Help us by sharing pictures/videos of dark and under-lit streets in New Delhi. Send us pictures, videos or vlog about poorly lit areas in the city. If you are on an Uber ride and are passing through a poorly lit area, swipe up in your app and help us mark the area. We will submit a list of all these spots to the Delhi Government and try and make the city a lot more safer for everyone.


Cron jobs are timetabled tasks, which run on regular intervals of time set by the user and they also execute scripts coded in various programming languages - PHP, Perl, Bash, etcetera. Determined by what exactly a cron needs to do, it may run each and every minute, weekly or even each year. There're plenty of useful applications to use cron jobs in the everyday management of a website. For example, a backup of the entire site can be generated every day or once a week or an e-mail with all new signups for the day can be delivered to a specific email address. This kind of automatic options can make the management of any website much easier. There won't be any precise file types that can be allowed or forbidden, so any script can be executed employing a cron job.
If you get any of our shared website hosting packages, you can create cron jobs with a few mouse clicks through your Hepsia Control Panel even when you have not done that before. Hepsia is quite intuitive, so rather than entering numbers and asterisks on particular positions, which is the usual way to make a cron job, you can pick the minutes, hours or days a given script needs to be executed using quick drop-down navigation. This is done from the Cron Jobs section of the Control Panel and, naturally, you can use the first method as well, in case you're skilled enough and you prefer it. In both cases, you will also need to type in the path to the script that will be executed and the path to the PHP, Python or Perl system files within your account. The latter is included in the Control Panel and you'll be able to copy/paste it, yet if you encounter any difficulties, you can get in touch with your support team.
In case you use a semi-dedicated server account from our company to host your websites, you are able to create cron jobs for all of them without any difficulty. This can be done in 3 really easy steps from the Hepsia Control Panel which is used to control the website hosting account, so you are able to create a new cron even if you do not have any prior experience. In the Cron Jobs part of Hepsia, you'll find a box where you should copy and paste the path to the system files in your account for the programming language your script was designed in - PHP, Perl, Bash, Python, and so on. You also have to provide the folder path to the script file that will be executed in the same box and then use our user-friendly drop-down menus to choose how often our system will run the cron. Experienced users, can also take advantage of the traditional method of setting up a cron job by typing digits and asterisks in certain positions in addition to the previously mentioned paths.


Edmond, G., Towler, A., Growns, B., Ribeiro, G., Found, B., White, D., Ballantyne, K., Searston, R.A., Thompson, M.B., Tangen, J.M., Kemp, R.I. and Martire, K. (2016) Thinking forensics: Cognitive science for forensic practitioners. Science & Justice, 57 (2). pp. 144-154.
Human factors and their implications for forensic science have attracted increasing levels of interest across criminal justice communities in recent years. Initial interest centred on cognitive biases, but has since expanded such that knowledge from psychology and cognitive science is slowly infiltrating forensic practices more broadly. This article highlights a series of important findings and insights of relevance to forensic practitioners. These include research on human perception, memory, context information, expertise, decision-making, communication, experience, verification, confidence, and feedback. The aim of this article is to sensitise forensic practitioners (and lawyers and judges) to a range of potentially significant issues, and encourage them to engage with research in these domains so that they may adapt procedures to improve performance, mitigate risks and reduce errors. Doing so will reduce the divide between forensic practitioners and research scientists as well as improve the value and utility of forensic science evidence.


Our Download of the Day is OpenOffice 3.4.0.
The changelog for this new version is quite immense, you can read about it here.
You can download OpenOffice.org 3.4.0, here.
>> NEXT STORY: Deal of the Day: 3TB Seagate Expansion External USB 3.0 HDD for $129.99 with FREE Shipping!


Investigation of mangroves and seagrass as two productive biomes, beginning with the distribution of these biomes worldwide and locally at Botany Bay.
Students will measure physical and chemical characteristics of marine and terrestrial environments such as salinity, and discuss the adaptations that plants and animals possess to cope with these conditions to maintain biome productivity.
An animal catch is conducted to highlight the aquatic biodiversity of the two biomes. This is placed in the economic context of aquaculture, and Botany Bay's history of oyster farming in particular will be discussed.


TaxAssist Accountants Wisbech provides a wide range of accountancy services including tax returns, annual accounts, payroll and bookkeeping. TaxAssist Accountants in Wisbech are a part of the largest network of accountants who offer a wealth of experience and expertise to over 70,000 small businesses right across the UK. We help a diverse range of small businesses including start-ups, sole traders, limited companies and landlords who operate in many industries.
Book your free "no obligation" 30 minute review now?


The firestorms that are raging through Southern California provide a good reminder on why planning for fire in landscaping your home is an important consideration, especially in the arid west. In Marin County there are several densely wooded areas, in Fairfax and Mill Valley especially, that are very suceptible to fire. There are a few key considerations that can help reduce fire risk in the event of a major blaze. Having defensible space where vegetation is cleared around the home is a key consideration. Removing pyrophitic vegetation close to the home, such as Eucalyptus, Pines, and Junipers can also help. For example, the city of San Rafael recently passed an ordinance requiring the removal of all bamboo and junipers within 100′ of structures by 2011.
Assess your fire risk. Is your home on a hill? Are you near highly flammable native vegetation or drought-damaged ornamental plants? If your answer is yes, your fire risk is greater than average.
Contact your local fire department for fire hazard ratings in your neighborhood.
Plan your landscape to reduce the amount of flammable vegetation nearest your home. Establish defensible space.
Consider consulting your local nursery or a landscape contractor to help plan your landscape.
Eliminate the "fire ladder." Fire needs fuel to burn. You can sap its strength by robbing it of the continuous sequence of vegetation that can carry flames from your landscape to your house.
Group plants of similar height and water requirements to create a "landscape mosaic" that can slow the spread of fire and use water most efficiently.
Space trees at least 10 feet apart, and keep branches trimmed at least 10 feet from your roof. For trees taller than 18 feet, prune lower branches within six feet of the ground.
Install fire resistant, drought-tolerant plants that have a high moisture content. Use plants that do not accumulate dead leaves or twigs.
Use masonry or stone walls to separate plant groups and add variety to your landscape.
Choose the right irrigation system. While all plants will eventually burn, healthy plants burn less quickly. Your plant selection and water availability will determine the right system for you.
Consider drip irrigation for watering most of your landscape. It's effective and conserves water because it targets where the water goes and how much gets there.
Use sprinklers for lawns or turf landscaping. Drip irrigation does not work well on lawns. Sprinklers on timers ensure your lawn is getting the right amount of water to keep it healthy and fire resistant.
Keep your landscape healthy and clean. On a regular basis, remove dead branches, leaves and pine needles from your yard. These can serve as added fuel to a fire.
Prune and thin shrubs, trees and other plants to minimize the fuel load.
Be diligent about cleaning up, especially during fire season. Remove dead leaves from under the plants as well.
Involve your gardener. If a gardener cares for your property, ask him or her to include these regular maintenance steps as part of the routine service.
Recycle/compost plant materials. Participate in your community's green waste recycling program. You can also compost plant litter and create a money-saving alternative to store-bought soil and mulch. Grass cycling is another time and money saving way to make your green waste work for you.


text:
← Judicial Review into royal wedding arrests: Day 1 of the Trial
Israel is new South Africa as boycott calls increase →
Olympics: A taste of China
Police given powers to enter homes and tear down anti-Olympics posters during 2012 Games
Read more: http://www.dailymail.co.uk/news/article-1201171/Police-given-powers-enter-homes-tear-anti-Olympics-posters-Games.html#ixzz1wH9Qyc14
Police have been handed 'Chinese-style' powers to enter private homes and seize political posters during the London 2012 Olympics. Little-noticed measures passed by the Government will allow officers and Olympics officials to enter homes and shops near official venues to confiscate any protest material. Breaking the rules could land offenders with a fine of up to £20,000. Civil liberties groups compared the powers to those used by the Communist Chinese government to stop political protest during the 2008 Beijing Games. Anita Coles, of Liberty, said: 'Powers of entry should be for fighting crime, not policing poster displays. Didn't we learn last time that the Olympics should not be about stifling free expression?' The powers were introduced by the Olympics Act of 2006, passed by the Department for Culture, Media and Sport, supposedly to preserve the monopoly of official advertisers on the London 2012 site. They would allow advertising posters or hoardings placed in shop or home to be removed. But the law has been drawn so widely that it also includes 'non-commercial material' – which could extend its reach to include legitimate campaign literature.
Shadow Home Secretary Chris Grayling said: 'This is a Government who just doesn't understand civil liberties. They may claim these powers won't be used but the frank truth is no one will believe them.' Liberal Democrat spokesman Chris Huhne said: 'This sort of police action runs the risk of using a sledgehammer to crack a nut. 'We should aim to show the Chinese that you can run a successful Olympics without cracking down on protestors and free speech.' Scotland Yard denied it had any plans to use the powers. Assistant Commissioner Chris Allison said: 'We have no intention of using our powers to go in and take down demonstration posters.'
But critics said that – given the powers were now law – it was impossible to predict what would happen in three years time. Campaigners said the existence of the powers was 'dreadful'. Peter McNeil, who is against the holding of equestrian events in Greenwich Park said: 'It's bullying taken to another level. It's quite appalling that this should happen in a democracy.' The power emerged as the Home Office and police outlined the £600million security operation for the Games, which will cost more than £9billion in total. They said hundreds of flights could have to be diverted every day, with planes prevented from passing over the main venue for the London games. Olympic security chiefs said they expected to have to 'manage' the airspace over the Olympic Park in east London.
A senior Home Office official said: 'We do expect there will have to be some management of the airspace. We do not expect that any airports will have to close.' The officials said they had no evidence of a specific terror threat against the Games at the moment. But current preparations assume the terror threat level will be at 'severe' during the event, despite it being reduced to 'substantial' for the UK earlier this week. It is the lowest threat level nationwide since before the July 7 attacks in 2005. A DCMS spokesman said: 'The advertising provisions in the London Olympic Games and Paralympic Games Act 2006 are there to prevent ambush marketing and the over-commercialisation of the Games, not to prevent or restrict lawful protests. 'The measures will only apply to areas within a few hundred metres of the London 2012 venues. The Government is currently developing detailed regulations for advertising during the Games which will enable these powers to come into effect. The Government will be consulting on the regulations in 2010.'
Source = http://www.dailymail.co.uk
Police powers for 2012 Olympics alarm critics
The government was accused tonight of giving itself draconian powers to clamp down on protests at the 2012 Olympics. Critics said the powers were so broad they would potentially give private contractors the right to forcibly enter people's homes and seize materials. Opposition parties and civil liberties groups criticised the powers as top security officials announced plans concerned with keeping the games, to be held mostly in London, safe from terrorist attack and from "domestic extremists" and public order problems like disruptive protests. The legislation is directed at curbing advertising near the Olympic venues. A government spokesperson said the laws, passed in 2006, were meant to stop "over-commercialisation" of the games.
But civil rights campaigners are worried about several clauses in the London Olympic Games and Games Act 2006. Section 19(4) could cover protest placards, they said, as it read: "The regulations may apply in respect of advertising of any kind including in particular – (a) advertising of a non-commercial nature, and (b) announcements or notices of any kind." Section 22 allows a "constable or enforcement officer" to "enter land or premises" where they believe such an advert is being shown or produced. It allows for materials to be destroyed, and for the use of "reasonable force". The power to force entry requires a court warrant. Causing still further concern is a section granting the powers to an enforcement officer appointed by Olympic Delivery Authority. Anita Coles, policy officer for Liberty, said: "This goes much further than protecting the Olympic logo for commercial use. Regulations could ban signs urging boycotts of sponsors with sweat shops. Then private contractors designated by the Olympic authority could enter homes and other premises in the vicinity, seizing or destroying private property."
The Liberal Democrats' home affairs spokesman, Chris Huhne, said: "This sort of police action runs the risk of using a sledgehammer to crack a nut. The police should take a deep breath and read the excellent report from the chief inspector of constabulary on the tolerance of protest. We should aim to show the Chinese that you can run a successful Olympics without cracking down on protesters and free speech." Chris Grayling, the shadow home secretary, said: "This is a government who just doesn't understand civil liberties – they may claim these powers won't be used but the frank truth is no one will believe them. Neither the police nor any other official should be invading people's homes for what appear to be commercial reasons."
Source = http://www.guardian.co.uk
London Olympic Games and Paralympic Games Act 2006
2006 CHAPTER 12
An Act to make provision in connection with the Olympic Games and Paralympic Games that are to take place in London in the year 2012; to amend the Olympic Symbol etc. (Protection) Act 1995; and for connected purposes.
[30th March 2006]
Be it enacted by the Queen's most Excellent Majesty, by and with the advice and consent of the Lords Spiritual and Temporal, and Commons, in this present Parliament assembled, and by the authority of the same, as follows:—
Section 22 – Enforcement: power of entry
(1) A constable or enforcement officer may—
(a) enter land or premises on which they reasonably believe a contravention of regulations under section 19 is occurring (whether by reason of advertising on that land or premises or by the use of that land or premises to cause an advertisement to appear elsewhere);
(b) remove, destroy, conceal or erase any infringing article;
(c) when entering land under paragraph (a), be accompanied by one or more persons for the purpose of taking action under paragraph (b);
(d) use, or authorise the use of, reasonable force for the purpose of taking action under this subsection.
(2) The power to enter land or premises may be exercised only at a time that a constable or enforcement officer thinks reasonable having regard to the nature and circumstances of the contravention of regulations under section 19.
(3) Before entering land or premises a constable or enforcement officer must take reasonable steps to—
(a) establish the identity of an owner, occupier or person responsible for the management of the land or premises or of any infringing article on the land or premises, and
(b)give any owner, occupier or responsible person identified under paragraph (a) such opportunity as seems reasonable to the constable or enforcement officer in the circumstances of the case to end the contravention of the regulations (whether by removing, destroying or concealing any infringing article or otherwise).
(4) The power to enter premises may be exercised in relation to a dwelling only in accordance with a warrant issued by a justice of the peace; and a justice of the peace may issue a warrant only if satisfied on the application of a constable or enforcement officer that—
(a) there are reasonable grounds to believe a contravention of regulations under section 19 is occurring in the dwelling or on land that can reasonably be entered only through the dwelling,
(b) the constable or enforcement officer has complied with subsection (3),
(c)the constable or enforcement officer has taken reasonable steps to give notice to persons likely to be interested of his intention to apply for a warrant, and
(d) that it is reasonable in the circumstances of the case to issue a warrant.
Source = http://www.legislation.gov.uk/ukpga/2006/12

redpajama_set_name: RedPajamaCommonCrawl


text:
From the November 2007 Issue Subscribe
Artist Interview
Carrie Rodriguez
By Jeff McCord
In 2005, after three studio albums with songwriting legend Chip Taylor, the Austin-born singer and fiddler wowed audiences with him for two nights in Germany. Chip Taylor & Carrie Rodriguez Live From the RuhrTriennale (Train Wreck) captures the duo's much-storied chemistry.
So how exactly did the live album come about?
Chip and I were touring with our Red Dog Tracks album, and we got asked to be part of this festival in Germany. We knew it was being recorded, but we didn't imagine it would turn into a record. We had so many special moments in the show, though, I remember feeling thankful even then to have them captured.
What was the Ruhr like?
It used to be an industrial area in Germany, but it's been cleaned up; the place we played was a factory that's been transformed into this cool art space. It gave a very creative vibe to the concert.
How comfortable are you with your growing role as a singer-songwriter?
I feel comfortable singing now, but the songwriting thing is still new. I've been lucky to watch Chip with his writing; he's let me in on how he does it. But I'm still green. I'm constantly thinking, "Hmm, what would Chip do here?" David A. Herron


text:
FREEDOM LINE BLOG: CFIF to U.S. Senate: On Drug Prices, Say "NO" to Mandatory Inflation Rebate Proposals…
On behalf of over 300,000 of our supporters and activists across the nation, CFIF has written the following…
CFIF to U.S. Senate: On Drug Prices, Say "NO" to Mandatory Inflation Rebate Proposals
On behalf of over 300,000 of our supporters and activists across the nation, CFIF has written the following letter opposing any use of Mandatory Inflation Rebate Proposals when it comes to the issue of addressing drug prices:
We believe that market-oriented solutions offer the optimal solution, and resolutely oppose any use of mandatory inflation rebate proposals – which would unfairly penalize a drug's manufacturer with higher taxes whenever that drug's price rises faster than inflation - that will make matters worse, not better. Among other defects, such a government-imposed penalty would undermine Medicare Part D's current structure, which uses market-based competition to mitigate drug costs. Part D currently works via privately-negotiated rebates, meaning that no specific price…[more]
About CFIF
Donate to CFIF
CFIF Staff
Questions of the Week
Internet Donations
Post Mail Donations
This Week's "Your Turn" Radio Show Lineup
This Week's "Your Turn" Radio Lineup
Image of the Day: Disposable Income in U.S. Versus Elsewhere
Notable Quote: Trump Beats the "Experts" Again
Speaking of Drones...
This Week's "Your Turn" Radio Show Linup
Image of the Day: Gallup Poll on Americans' View of Job Market Hits All-Time Record
CFIF's Public Education Effort Encourages Grassroots Action Aimed at Urging Mississippi Attorney General's Office to Get Back to Fighting Crime
Center for Individual Freedom Launches Public Education Effort in Mississippi
Liberty Update
Legal tales stranger than stranger than fiction: Ridiculous and sometimes funny lawsuits plaguing our courts.
VA Mission Act Won't Help Dying Vietnam Vets
By Betsy McCaughey
If there was ever an example of vets needing to be in the driver's seat about getting outside care, this is it.
Tens of thousands of Vietnam vets, now in their sixties and early seventies, are carrying a dangerous parasite picked up in Asia called liver fluke. Many don't know it, but it's a ticking time bomb likely to kill them.
President Donald Trump just signed the VA Mission Act, which is supposed to help ailing vets get prompt care, including seeing a civilian doctor on Uncle Sam's tab. Don't count on it to help these vets.
The fine print shows that vets are guaranteed nothing. The Department of Veterans Affairs secretary is simply empowered to make rules for who gets civilian care. Though Trump and his pick for secretary, Robert Wilkie, favor making it easy for vets, Wilkie's rules could last only as long as Wilkie remains secretary. Worse, they don't go into effect for two and a half years, too late for many Vietnam vets with liver fluke.
Scandalously, the VA is doing zip to identify and treat these infected vets, even though an ultrasound test can detect liver fluke infection in minutes and medications can slow its progression into lethal bile duct cancer. If there was ever an example of vets needing to be in the driver's seat about getting outside care, this is it. But the VA Mission Act requires them to get their VA doctor's permission.
Remember the nation's shock in 2014 when 40 vets died on secret waitlists concocted by VA bureaucrats. That toll is minuscule compared with the deaths being caused right now by the VA's neglect of vets with liver fluke.
In January, researchers at the Northport, New York, VA found that one out of every four vets tested who remembers eating raw fish in Vietnam — a common practice when rations ran out — is carrying the parasite. More than 100,000 veterans could be infected. The parasite lingers in the body for decades, and then — wham — suddenly could cause deadly bile duct cancer. Some 80 percent to 90 percent of veterans will develop the cancer if their infection goes untreated, according to New York physician John Cahill, an expert on parasites.
"It's a huge number," says Devi Nampiaparampil, associate professor at New York University Langone Medical Center.
Cahill says he'd like to see every vet who ate raw fish while in Vietnam contacted for an ultrasound.
Instead, the VA is serving up gibberish. When researchers documented the link between Vietnam vets eating raw fish and getting infected with liver fluke, the VA posted a statement that "there is currently no evidence that vets have higher infection rates than the general population." That's ridiculous. You can't get infected with liver fluke in the U.S. The parasite doesn't exist here. Cahill calls bile duct cancer "extremely rare" among the U.S. population. The other highest risk group is Asian-Americans who traveled or once resided in Southeast Asia.
Here's another whopper. The VA is telling vets if they don't have jaundice or other symptoms "they don't need screening." In fact, Nampiaparampil stresses that by the time those symptoms appear, the cancer has often progressed too far.
The VA claims there is "no definitive link" between the parasite and cancer. In truth, there's a pile of research linking the two. Researchers at Tulane and George Washington University proved the link in 2007 in an article "Liver Fluke Induces Cholangiocarcinoma." So did findings in the journal Cancer Science in 2010, calling liver fluke infection "the strongest risk factor" for cancer of the bile duct.
The VA is launching a "large-scale epidemiological study" that will be ready in about two years.
Meanwhile Facebook and local newspapers are chronicling the deaths of Vietnam vets from liver fluke-related cancer.
The clock is ticking. Vietnam vets need to be contacted, tested if they ate raw fish, and treated if they have the infection. The VA Mission Act isn't going to save them any more than previous VA "reform" laws — all hailed by self-congratulating Washington pols when they were passed.
» A Cancer Stigma Killing Thousands
» Democrats' Plan to Destroy the Jobs Boom
» CFIF Urges Opposition to S. 977, Legislation to Import Foreign Price Controls
» Better Than Obamacare
» Health Care Computers Can Kill You
» Left-Wing Activists Target Hard-Won Intellectual Property Gains in New US-Canada-Mexico Trade Agreement
» 'Medicare-for-All' Would Take Most of Your Paycheck
» Trump's Making Health Insurance More Affordable
» New Alzheimer's Vaccine Highlights Value of America's Pharmaceutical Sector
» On Pharmaceuticals, HHS Contemplates Disastrous New Price Controls
» 'Medicare-for-All': A Disaster
» Dems Winning Votes with Big Lie About Pre-Existing Conditions
» The Medicare-for-All Hoax
» Failing CDC Lets Infants Die From Infection
» Short-Term Insurance
» Dems' Plans Sabotage Workers
» Dems' Big Lie About Kavanaugh
» The Dirt on Colonoscopies
» As Obamacare Premiums Soar, Dems Lie
» Uncle Sam's Deadly Cancer Screening Advice
Which one of the following was the longest-serving U.S. Secretary of State?
Cordell Hull
William Seward
"[A]s ICE prepared to conduct a nationwide operation, Democratic leaders such as Nancy Pelosi held a press conference to instruct those who have violated our nation's laws on how they can evade federal law enforcement. How they can evade the law. How what ICE is doing is un-American and they need to resist.Are you kidding me?The Speaker of the House, a lawmaker for decades, is instructing those who…[more]
—Thomas Homan, Former Acting Director of Immigration and Customs Enforcement (ICE)
— Thomas Homan, Former Acting Director of Immigration and Customs Enforcement (ICE)
Liberty Poll
Do the "politics of personal destruction," now rampant across the political spectrum and amplified by the media, make you more or less inclined to personally participate in political activity?
More Inclined
Less Inclined
No Change in Participation
© 2019 Center for Individual Freedom. All rights reserved.


text:
St. Georges athletes find success in yoga for injury prevention, recovery
Amanda Parrish
Middletown Transcript
Professional athletes have turned to yoga to help with game recovery, prevent injury and improve strength. St. Georges Technical High School players have found success in the exercises as well.
Over the past few years, the Hawks' soccer and field hockey coaches have seen a decrease in injuries and faster recovery from games since they began making yoga a part of their weekly practice routines.
In 2018, head soccer coach Justin Null said he saw an advertisement for Yoga Strong, instructed by Debby Nolan, and wanted to take advantage of it.
"At that time, the benefits of yoga and the use of it in the athletic world was really growing. This is something that would be really awesome to incorporate in our program to assist with recovery, mobility and stuff like that," he said.
Nolan leads yoga during practice at least once a week, and the coach has noticed injuries have occurred less and the players have not been as sore.
"It's hard to put a finger on it if it's really the yoga or something else, but I can say that our injury rate is down this year and I would say our recovery is better too, more efficient," Null said.
After working as a high school counselor, Nolan wanted her business to focus on high school athletics. Since she lives close to St. Georges Tech, she began working with their soccer and field hockey teams, using stretches to improve mobility, strength and flexibility.
Nolan reached out to field hockey coach Jessica Bloch two years ago, and Bloch has seen a decrease in injuries on the team.
INJURY:Young hockey player from Dover in for 'fight of his life' after severe spinal injury during game
"The last couple years, we have had less significant injuries. Females tend to be prone to hip-related, hamstrings [injuries]. There has definitely been an improvement," the coach said. "I have used some of her poses and incorporated them into practices. I have seen less injuries this year even though we have been fighting in the colder weather."
Bloch usually uses Yoga Strong every other week. Because of the pandemic, the sessions haven't been as frequent.
This year, Nolan focused mostly on recovery, meaning she would come to practice the day after a game and focus on movements that help prevent soreness and build strength. She tailors her workouts for whatever the coaches want to target.
"[For example], if it's preseason and they want to be in shape, I can do more of a power yoga," she said. "It's really just whatever the coach feels his players need at that time."
Bloch said she likes that Nolan caters each session to what the team needs that day.
"There is also a level of strength that they are getting. Understanding their body on a deeper level," the coach said. "The mental aspect as well, she is able to tap into that through her talking to them while they are stretching, getting them to release their thoughts and focus on certain thoughts."
COVID:Where to get COVID-19 tests in Delaware before Thanksgiving
Nolan has worked with a variety of sports, such as football, basketball and baseball with schools all over New Castle County, including Caravel Academy, Conrad High School, Tatnall School and Middletown High School.


text:
HSC Professor Appointed to National General Medical Sciences Council
Laura Roberts, M.D., associate professor and vice chair for Administration in the UNM School of Medicine Department of Psychiatry, was recently appointed by Secretary of Health and Human Services Tommy G. Thompson to the National Advisory General Medical Sciences Council. Roberts appointment will begin immediately and run through December 31, 2005.
The 14-member council reviews research in the basic, medical and behavioral sciences and makes recommendations to the Secretary of Health and Human Services and other department officials on basic, medical and behavioral science investigations and support.
Contact: Cindy Foster, 272-3322


Sponsored by Acura, this year we will be running the FULL course at Autobahn Country Club in Joliet, IL on July 3rd and 4th (Sat/Sun).
Already, we should have 3 ITRs and an NSX from WNY and just over the border in Ontario.
This event is NOT limited to ITRs or even Hondas. Registration is 100% first come first serve. This event is an HPDE.
Hope to see some more WNYers out there!!