text:
package org.broad.igv.track;

import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.tools.FeatureSearcher;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.util.CancellableProgressDialog;
import org.broad.igv.ui.util.IndefiniteProgressMonitor;
import org.broad.igv.ui.util.ProgressMonitor;
import org.broad.igv.util.LongRunningTask;
import htsjdk.tribble.Feature;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.Iterator;

/**
 *
 */
class FeatureTrackUtils {

    private static volatile boolean isSearching;

    /**
     * Find the next/previous feature which lies outside chr:initStart-initEnd
     * @param source
     * @param chr
     * @param initStart
     * @param initEnd
     * @param forward
     * @return
     * @throws IOException
     */
    public static Feature nextFeature(FeatureSource source, String chr, int initStart, int initEnd, boolean forward) throws IOException {
        Feature f = null;
        int binSize = source.getFeatureWindowSize();

        final Genome genome = GenomeManager.getInstance().getCurrentGenome();
        if (forward) {
            // Forward
            int nextStart = initEnd;
            String nextChr = chr;
            while (nextChr != null) {
                int chrLength = genome.getChromosome(nextChr).getLength();
                while (nextStart < chrLength) {
                    int nextEnd = binSize > 0 ? nextStart + source.getFeatureWindowSize() : chrLength;
                    Iterator<Feature> iter = source.getFeatures(nextChr, nextStart, nextEnd);
                    if (iter != null) {
                        // The check on position should not be necessary, but not all implementations of getFeatures
                        // obey the contract to return features only in the interval.
                        while (iter.hasNext()) {
                            Feature feat = iter.next();
                            if (feat.getStart() > nextStart) {
                                return feat;
                            }
                        }
                    }
                    nextStart = nextEnd;
                }
                nextChr = genome.getNextChrName(nextChr);
                nextStart = 0;
            }
        } else {
            // Reverse
            int nextEnd = initStart;
            String nextChr = chr;
            while (nextChr != null) {
                while (nextEnd > 0) {
                    int nextStart = binSize > 0 ? Math.max(0, nextEnd - source.getFeatureWindowSize()) : 0;
                    Iterator<Feature> iter = source.getFeatures(nextChr, nextStart, nextEnd);
                    if (iter != null && iter.hasNext()) {
                        // The check on position should not be necessary, but not all implementations of getFeatures
                        // obey the contract to return features only in the interval.
                        Feature prevFeature = null;
                        while (iter.hasNext()) {
                            Feature feat = iter.next();
                            if (feat.getStart() < nextEnd) {
                                prevFeature = feat;
                            }
                        }
                        if (prevFeature != null) {
                            return prevFeature;
                        }
                    }
                    nextEnd = nextStart;
                }
                nextChr = genome.getPrevChrName(nextChr);
                if (nextChr != null) {
                    nextEnd = genome.getChromosome(nextChr).getLength();
                }
            }
        }

        return f;
    }

    /**
     * Find the next/previous feature, using FeatureSearcher. A cancellable dialog will be displayed so the user can cancel the
     * search, null will be returned in that case.
     * @param source
     * @param chr
     * @param initStart
     * @param initEnd
     * @param forward
     * @param foundHandler Callback to invoke when searching is complete. Does not get called if search returns no result
     * @return
     * @throws IOException
     */
    public static void nextFeatureSearch(FeatureSource source, String chr, int initStart, int initEnd, boolean forward,
                                         final FeatureSearcher.IFeatureFound foundHandler) throws IOException{

        //Only allow one to be shown at a time
        if(isSearching()){
            return;
        }

        Genome genome = GenomeManager.getInstance().getCurrentGenome();

        //We search backwards by setting a negative searchIncrement
        int searchIncrement = (initEnd - initStart) * (forward ? +1 : -1);
        int start = initStart + searchIncrement;

        IndefiniteProgressMonitor monitor = new IndefiniteProgressMonitor();

        final FeatureSearcher searcher = new FeatureSearcher(source, genome, chr, start, monitor);
        searcher.setSearchIncrement(searchIncrement);

        final ActionListener cancelListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                FeatureTrackUtils.isSearching = false;
                searcher.cancel();
            }
        };

        final CancellableProgressDialog dialog = CancellableProgressDialog.showCancellableProgressDialog(IGV.getMainFrame(), "Searching...", cancelListener, true, monitor);
        dialog.getProgressBar().setIndeterminate(true);

        monitor.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if(evt.getPropertyName().equals(ProgressMonitor.PROGRESS_PROPERTY) &&  (Integer) evt.getNewValue() >= 100){
                    FeatureTrackUtils.isSearching = false;
                    Iterator<? extends Feature> result = searcher.getResult();
                    if(result != null) foundHandler.processResult(result);
                }
            }
        });

        FeatureTrackUtils.isSearching = true;
        LongRunningTask.submit(searcher);
    }

    private static boolean isSearching() {
        return isSearching;
    }

}


text:
=============
Release 0.111
=============

General Changes
---------------

* Optimize ``CASE`` expressions on a constant.
* Add basic support for ``IF NOT EXISTS`` for ``CREATE TABLE``.
* Semi-joins are hash-partitioned if ``distributed_join`` is turned on.
* Add support for partial cast from JSON. For example, ``json`` can be cast to ``array<json>``, ``map<varchar, json>``, etc.
* Add implicit coercions for ``UNION``.
* Expose query stats in Presto JDBC driver.

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.java.intellij;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.android.AndroidLibraryBuilder;
import com.facebook.buck.java.JavaLibraryBuilder;
import com.facebook.buck.java.JavaTestBuilder;
import com.facebook.buck.java.KeystoreBuilder;
import com.facebook.buck.java.PrebuiltJarBuilder;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.shell.GenruleBuilder;
import com.facebook.buck.testutil.TargetGraphFactory;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import org.junit.Test;

import java.nio.file.Path;
import java.nio.file.Paths;

public class IjModuleGraphTest {

  @Test
  public void testModuleCoalescing() {
    TargetNode<?> guava = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third_party/java/guava:guava"))
        .build();

    TargetNode<?> base = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/com/example/base:base"))
        .addDep(guava.getBuildTarget())
        .build();

    TargetNode<?> baseTests = JavaTestBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/com/example/base:tests"))
        .addDep(guava.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(ImmutableSet.of(guava, base, baseTests));

    IjModule guavaModule = getModuleForTarget(moduleGraph, guava);
    IjModule baseModule = getModuleForTarget(moduleGraph, base);
    IjModule baseTestModule = getModuleForTarget(moduleGraph, baseTests);

    assertNotEquals(guavaModule, baseModule);
    assertEquals(baseTestModule, baseModule);
  }

  @Test
  public void testSimpleDependencies() {
    TargetNode<?> libraryTarget = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/src/com/library:library"))
        .build();

    TargetNode<?> productTarget = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/src/com/product:product"))
        .addDep(libraryTarget.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(ImmutableSet.of(libraryTarget, productTarget));

    IjModule libraryModule = getModuleForTarget(moduleGraph, libraryTarget);
    IjModule productModule = getModuleForTarget(moduleGraph, productTarget);

    assertEquals(
        ImmutableMap.of(libraryModule, IjModuleGraph.DependencyType.PROD),
        moduleGraph.getDependentModulesFor(productModule));
    assertTrue(moduleGraph.getDependentModulesFor(libraryModule).isEmpty());
  }

  @Test
  public void testExportedDependencies() {
    TargetNode<?> junitReflect = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/reflect:reflect"))
        .build();

    TargetNode<?> junitCore = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/core:core"))
        .addExportedDep(junitReflect.getBuildTarget())
        .build();

    TargetNode<?> junitRule = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/rule:rule"))
        .addDep(junitCore.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.of(
            junitReflect,
            junitCore,
            junitRule));

    IjModule junitReflectModule = getModuleForTarget(moduleGraph, junitReflect);
    IjModule junitCoreModule = getModuleForTarget(moduleGraph, junitCore);
    IjModule junitRuleModule = getModuleForTarget(moduleGraph, junitRule);

    assertEquals(
        ImmutableMap.of(
            junitReflectModule, IjModuleGraph.DependencyType.PROD,
            junitCoreModule, IjModuleGraph.DependencyType.PROD),
        moduleGraph.getDependentModulesFor(junitRuleModule));
  }

  @Test
  public void testDoesNotDependOnSelfViaExportedDependencies() {
    TargetNode<?> libraryTypes = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/library:types"))
        .build();

    TargetNode<?> reExporter = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/reexporter:reexporter"))
        .addExportedDep(libraryTypes.getBuildTarget())
        .build();

    TargetNode<?> libraryCore = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/library:core"))
        .addDep(reExporter.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.of(
            libraryCore,
            reExporter,
            libraryTypes));

    IjModule libraryModule = getModuleForTarget(moduleGraph, libraryCore);
    IjModule reExporterModule = getModuleForTarget(moduleGraph, reExporter);

    assertEquals(
        ImmutableMap.of(reExporterModule, IjModuleGraph.DependencyType.PROD),
        moduleGraph.getDependentModulesFor(libraryModule));
  }

  @Test
  public void testTestDependencies() {
    TargetNode<?> junitTargetNode = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit:junit"))
        .build();

    TargetNode<?> guavaTargetNode = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/guava:guava"))
        .build();

    TargetNode<?> hamcrestTargetNode = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/hamcrest:hamcrest"))
        .build();

    TargetNode<?> codeTargetNode = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/com/foo:foo"))
        .addSrc(Paths.get("java/com/foo/src/Foo.java"))
        .addDep(guavaTargetNode.getBuildTarget())
        .build();

    TargetNode<?> inlineTestTargetNode = JavaTestBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/com/foo:test"))
        .addDep(codeTargetNode.getBuildTarget())
        .addDep(junitTargetNode.getBuildTarget())
        .addSrc(Paths.get("java/com/foo/src/TestFoo.java"))
        .build();

    TargetNode<?> secondInlineTestTargetNode = JavaTestBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/com/foo:test2"))
        .addDep(hamcrestTargetNode.getBuildTarget())
        .addSrc(Paths.get("java/com/foo/test/TestFoo.java"))
        .build();

    TargetNode<?> testTargetNode = JavaTestBuilder
        .createBuilder(BuildTargetFactory.newInstance("//javatest/com/foo:foo"))
        .addDep(codeTargetNode.getBuildTarget())
        .addDep(junitTargetNode.getBuildTarget())
        .addSrc(Paths.get("javatest/com/foo/Foo.java"))
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.<TargetNode<?>>of(
            guavaTargetNode,
            hamcrestTargetNode,
            junitTargetNode,
            codeTargetNode,
            inlineTestTargetNode,
            secondInlineTestTargetNode,
            testTargetNode));

    IjModule guavaModule = getModuleForTarget(moduleGraph, guavaTargetNode);
    IjModule hamcrestModule = getModuleForTarget(moduleGraph, hamcrestTargetNode);
    IjModule junitModule = getModuleForTarget(moduleGraph, junitTargetNode);
    IjModule codeModule = getModuleForTarget(moduleGraph, codeTargetNode);
    IjModule testModule = getModuleForTarget(moduleGraph, testTargetNode);

    assertEquals(ImmutableMap.of(),
        moduleGraph.getDependentModulesFor(junitModule));

    assertEquals(ImmutableMap.of(),
        moduleGraph.getDependentModulesFor(guavaModule));

    assertEquals(ImmutableMap.of(
            guavaModule, IjModuleGraph.DependencyType.PROD,
            junitModule, IjModuleGraph.DependencyType.PROD,
            hamcrestModule, IjModuleGraph.DependencyType.TEST),
        moduleGraph.getDependentModulesFor(codeModule));

    assertEquals(ImmutableMap.of(
            codeModule, IjModuleGraph.DependencyType.TEST,
            junitModule, IjModuleGraph.DependencyType.TEST),
        moduleGraph.getDependentModulesFor(testModule));
  }

  @Test
  public void testDependenciesOnPrebuilt() {
    TargetNode<?> guavaTargetNode = PrebuiltJarBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/guava:guava"))
        .setBinaryJar(Paths.get("third-party/guava/guava.jar"))
        .build();

    TargetNode<?> coreTargetNode = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/org/foo/core:core"))
        .addDep(guavaTargetNode.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(ImmutableSet.of(guavaTargetNode, coreTargetNode));

    IjModule coreModule = getModuleForTarget(moduleGraph, coreTargetNode);
    IjLibrary guavaElement = getLibraryForTarget(moduleGraph, guavaTargetNode);

    assertEquals(ImmutableMap.of(guavaElement, IjModuleGraph.DependencyType.PROD),
        moduleGraph.getDepsFor(coreModule));
  }

  @Test
  public void testExportedDependenciesOfTests() {
    TargetNode<?> junitTargetNode = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit:junit"))
        .build();

    TargetNode<?> testLibTargetNode = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//javatests/lib:lib"))
        .addExportedDep(junitTargetNode.getBuildTarget())
        .build();

    TargetNode<?> testTargetNode = JavaTestBuilder
        .createBuilder(BuildTargetFactory.newInstance("//javatests/test:test"))
        .addDep(testLibTargetNode.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.of(
            junitTargetNode,
            testLibTargetNode,
            testTargetNode));

    IjModule junitModule = getModuleForTarget(moduleGraph, junitTargetNode);
    IjModule testLibModule = getModuleForTarget(moduleGraph, testLibTargetNode);
    IjModule testModule = getModuleForTarget(moduleGraph, testTargetNode);

    assertEquals(ImmutableMap.of(
            junitModule, IjModuleGraph.DependencyType.TEST,
            testLibModule, IjModuleGraph.DependencyType.TEST),
        moduleGraph.getDependentModulesFor(testModule));
  }

  @Test
  public void testExportedDependenciesDependsOnDepOfExportedDep() {
    TargetNode<?> junitReflect = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/reflect:reflect"))
        .build();

    TargetNode<?> junitCore = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/core:core"))
        .addExportedDep(junitReflect.getBuildTarget())
        .build();

    TargetNode<?> junitRule = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/rule:rule"))
        .addExportedDep(junitCore.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.of(
            junitReflect,
            junitCore,
            junitRule));

    IjModule junitReflectModule = getModuleForTarget(moduleGraph, junitReflect);
    IjModule junitCoreModule = getModuleForTarget(moduleGraph, junitCore);
    IjModule junitRuleModule = getModuleForTarget(moduleGraph, junitRule);

    assertEquals(
        ImmutableMap.of(
            junitReflectModule, IjModuleGraph.DependencyType.PROD,
            junitCoreModule, IjModuleGraph.DependencyType.PROD),
        moduleGraph.getDependentModulesFor(junitRuleModule));
  }

  @Test
  public void testExportedDependenciesDontLeak() {

    TargetNode<?> junitReflect = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/reflect:reflect"))
        .build();

    TargetNode<?> junitCore = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/core:core"))
        .addExportedDep(junitReflect.getBuildTarget())
        .build();

    TargetNode<?> junitRule = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//third-party/junit/rule:rule"))
        .addDep(junitCore.getBuildTarget())
        .build();

    TargetNode<?> testRule = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//tests/feature:tests"))
        .addDep(junitRule.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.of(
            junitReflect,
            junitCore,
            junitRule,
            testRule));

    IjModule junitRuleModule = getModuleForTarget(moduleGraph, junitRule);
    IjModule testRuleModule = getModuleForTarget(moduleGraph, testRule);

    assertEquals(
        ImmutableMap.of(junitRuleModule, IjModuleGraph.DependencyType.PROD),
        moduleGraph.getDependentModulesFor(testRuleModule));
  }

  @Test
  public void testDropDependenciesToUnsupportedTargets() {
    TargetNode<?> productKeystoreTarget = KeystoreBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/src/com/facebook/library:keystore"))
        .build();

    TargetNode<?> libraryJavaTarget = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/src/com/facebook/library:library"))
        .build();

    TargetNode<?> productTarget = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/src/com/facebook/product:child"))
        .addDep(productKeystoreTarget.getBuildTarget())
        .addDep(libraryJavaTarget.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.of(
            libraryJavaTarget,
            productTarget,
            productKeystoreTarget));

    IjModule libraryModule = getModuleForTarget(moduleGraph, libraryJavaTarget);
    IjModule productModule = getModuleForTarget(moduleGraph, productTarget);

    assertEquals(ImmutableMap.of(libraryModule, IjModuleGraph.DependencyType.PROD),
        moduleGraph.getDependentModulesFor(productModule));
    assertEquals(2, moduleGraph.getModuleNodes().size());
  }

  @Test
  public void testCompiledShadow() {
    TargetNode<?> productGenruleTarget = GenruleBuilder
        .newGenruleBuilder(
            BuildTargetFactory.newInstance("//java/src/com/facebook/product:genrule"))
        .build();

    TargetNode<?> libraryJavaTarget = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/src/com/facebook/library:library"))
        .build();

    TargetNode<?> productTarget = JavaLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/src/com/facebook/product:product"))
        .addSrc(Paths.get("java/src/com/facebook/File.java"))
        .addSrcTarget(productGenruleTarget.getBuildTarget())
        .addDep(libraryJavaTarget.getBuildTarget())
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.of(
            productGenruleTarget,
            libraryJavaTarget,
            productTarget),
        ImmutableMap.<TargetNode<?>, Path>of(productTarget, Paths.get("buck-out/product.jar")),
        Functions.constant(Optional.<Path>absent()));

    IjModule libraryModule = getModuleForTarget(moduleGraph, libraryJavaTarget);
    IjModule productModule = getModuleForTarget(moduleGraph, productTarget);
    IjLibrary productLibrary = getLibraryForTarget(moduleGraph, productTarget);

    assertEquals(
        ImmutableMap.of(
            libraryModule, IjModuleGraph.DependencyType.PROD,
            productLibrary, IjModuleGraph.DependencyType.COMPILED_SHADOW),
        moduleGraph.getDepsFor(productModule));
  }

  @Test
  public void testExtraClassPath() {
    final Path rDotJavaClassPath = Paths.get("buck-out/product/rdotjava_classpath");
    final TargetNode<?> productTarget = AndroidLibraryBuilder
        .createBuilder(BuildTargetFactory.newInstance("//java/src/com/facebook/product:product"))
        .addSrc(Paths.get("java/src/com/facebook/File.java"))
        .build();

    IjModuleGraph moduleGraph = createModuleGraph(
        ImmutableSet.<TargetNode<?>>of(productTarget),
        ImmutableMap.<TargetNode<?>, Path>of(productTarget, Paths.get("buck-out/product.jar")),
        new Function<TargetNode<?>, Optional<Path>>() {
          @Override
          public Optional<Path> apply(TargetNode<?> input) {
            if (input == productTarget) {
              return Optional.of(rDotJavaClassPath);
            }
            return Optional.absent();
          }
        });

    IjModule productModule = getModuleForTarget(moduleGraph, productTarget);
    IjLibrary rDotJavaLibrary = FluentIterable.from(moduleGraph.getNodes())
        .filter(IjLibrary.class)
        .first()
        .get();

    assertEquals(ImmutableSet.of(rDotJavaClassPath), productModule.getExtraClassPathDependencies());
    assertEquals(ImmutableSet.of(rDotJavaClassPath), rDotJavaLibrary.getClassPaths());
    assertEquals(moduleGraph.getDependentLibrariesFor(productModule),
        ImmutableMap.of(rDotJavaLibrary, IjModuleGraph.DependencyType.PROD));
  }

  public static IjModuleGraph createModuleGraph(ImmutableSet<TargetNode<?>> targets) {
    return createModuleGraph(targets, ImmutableMap.<TargetNode<?>, Path>of(),
        Functions.constant(Optional.<Path>absent()));
  }

  public static IjModuleGraph createModuleGraph(
      ImmutableSet<TargetNode<?>> targets,
      final ImmutableMap<TargetNode<?>, Path> javaLibraryPaths,
      Function<? super TargetNode<?>, Optional<Path>> rDotJavaClassPathResolver) {
    final SourcePathResolver sourcePathResolver = new SourcePathResolver(new BuildRuleResolver());
    DefaultIjLibraryFactory.IjLibraryFactoryResolver sourceOnlyResolver =
        new DefaultIjLibraryFactory.IjLibraryFactoryResolver() {
          @Override
          public Path getPath(SourcePath path) {
            return sourcePathResolver.getPath(path);
          }

          @Override
          public Optional<Path> getPathIfJavaLibrary(TargetNode<?> targetNode) {
            return Optional.fromNullable(javaLibraryPaths.get(targetNode));
          }
        };
    IjModuleFactory moduleFactory = new IjModuleFactory(rDotJavaClassPathResolver);
    IjLibraryFactory libraryFactory = new DefaultIjLibraryFactory(sourceOnlyResolver);
    return IjModuleGraph.from(
        TargetGraphFactory.newInstance(targets),
        libraryFactory,
        moduleFactory);
  }

  public static IjProjectElement getProjectElementForTarget(
      IjModuleGraph graph,
      Class<? extends IjProjectElement> type,
      final TargetNode<?> target) {
    return FluentIterable.from(graph.getNodes())
        .filter(type)
        .firstMatch(
            new Predicate<IjProjectElement>() {
              @Override
              public boolean apply(IjProjectElement input) {
                return FluentIterable.from(input.getTargets()).anyMatch(
                    new Predicate<TargetNode<?>>() {
                      @Override
                      public boolean apply(TargetNode<?> input) {
                        return input.getBuildTarget().equals(target.getBuildTarget());
                      }
                    });
              }
            }).get();
  }

  public static IjModule getModuleForTarget(IjModuleGraph graph, final TargetNode<?> target) {
    return (IjModule) getProjectElementForTarget(graph, IjModule.class, target);
  }

  public static IjLibrary getLibraryForTarget(IjModuleGraph graph, final TargetNode<?> target) {
    return (IjLibrary) getProjectElementForTarget(graph, IjLibrary.class, target);
  }
}


text:
import java.util.concurrent.atomic.AtomicInteger;

public class SemaphoreTester {

	public static AtomicInteger problemsSolved = new AtomicInteger(0);

	public static AtomicInteger problemsPosted = new AtomicInteger(0);

	private static int REFRESH_TIMER = 1000;

	public static void main(String[] args) {
		/**
		 * TODO create producer manager which creates producers at n random time
		 * producers creating sorting jobs (of random size) and place them into a job queue
		 * (producer) posts to the semaphore each new job
		 * Consumer manager creates consumers at p random time
		 * consumers will consume jobs from the queue using semaphores will wait on the semaphore for new jobs.
		 */

		ProducerManager pm = new ProducerManager();
		ConsumerManager cm = new ConsumerManager();

		while(true) {

			System.out.print("\033c");
			System.out.println("Total number of problems posted = " + problemsPosted.get());
			System.out.println("Current number of Problems Solved = " + problemsSolved.get());
			System.out.println("Number of Problem Creators: " + pm.producers.size());
			System.out.println("Number of Problem Solvers: " + cm.consumers.size());

			try {
				Thread.sleep(REFRESH_TIMER);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}


text:
package com.dy.activity;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.dy.adapter.WeatherPagerAdapter;
import com.dy.app.Application;
import com.dy.bean.City;
import com.dy.bean.WeatherInfo;
import com.dy.db.CityDB;
import com.dy.fragment.FirstWeatherFragment;
import com.dy.fragment.SecondWeatherFragment;
import com.dy.indicator.CirclePageIndicator;
import com.dy.plistview.RotateImageView;
import com.dy.receiver.NetBroadcastReceiver;
import com.dy.receiver.NetBroadcastReceiver.EventHandler;
import com.dy.util.GetWeatherTask;
import com.dy.util.IphoneDialog;
import com.dy.util.NetUtil;
import com.dy.util.SharePreferenceUtil;
import com.dy.util.ShareUtil;
import com.dy.util.ToastUtil;
import com.dy.util.TimeUtil;
import com.way.weather.R;

public class MainActivity extends FragmentActivity implements EventHandler,
		OnClickListener {

	public static final String UPDATE_WIDGET_WEATHER_ACTION = "com.way.action.update_weather";
	private static final int LOACTION_OK = 0;
	private static final int UPDATE_EXISTS_CITY = 2;
	public static final int GET_WEATHER_SCUESS = 3;
	public static final int GET_WEATHER_FAIL = 4;

	private LocationClient mLocationClient;
	private CityDB mCityDB;
	private SharePreferenceUtil mSpUtil;
	private Application mApplication;
	private View mSplashView;
	private static final int SHOW_TIME_MIN = 3000;// 最小显示时间
	private long mStartTime;// 开始时间
	private ImageView mCityManagerBtn, mLocationBtn, mShareBtn;
	private RotateImageView mUpdateProgressBar;
	private TextView mTitleTextView;
	private WeatherPagerAdapter mWeatherPagerAdapter;

	private TextView cityTv, timeTv, weekTv, aqiDataTv, aqiQualityTv,
			temperatureTv, climateTv, windTv;

	private View mAqiRootView;
	private View mShareView;
	private ImageView weatherImg, aqiImg;;
	private ViewPager mViewPager;
	private List<Fragment> fragments;
	private ShareUtil mShareUtil;
	/**
	 * 建立Handler的实例,处理从其他的Application中传递的信息
	 */

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
//			如果定位成功,更新天气
			case LOACTION_OK:
//				获得当前的城市名
				City curCity = (City) msg.obj;
				if (curCity != null) {
//					T.showShort(MainActivity.this, "定位到:" + curCity.getName());
					mSpUtil.setCity(curCity.getName());
//					更新天气
					MainActivity.this.updateWeather(curCity);
				}
				break;

//			更新城市名称
			case UPDATE_EXISTS_CITY:
//				从SharePreferences中获得城市名
				String sPCityName = mSpUtil.getCity();
				MainActivity.this.updateWeather(mCityDB.getCity(sPCityName));
				break;

//				成功获得天气信息
			case GET_WEATHER_SCUESS:
//				通过Application的方法来获得Weather信息
				WeatherInfo weatherInfo = (mApplication.getAllWeather());
//				更新天气界面
				MainActivity.this.updateWeatherInfo(weatherInfo);
//				更新AQI
				MainActivity.this.updateAqiInfo(weatherInfo);
//				更新组件
				MainActivity.this.updateWidgetWeather();
//				停止更新的动画
				mUpdateProgressBar.stopAnim();
//				计算花费的时间
				long loadingTime = System.currentTimeMillis() - mStartTime;// 计算一下总共花费的时间
				if (loadingTime < SHOW_TIME_MIN) {// 如果比最小显示时间还短,就延时进入MainActivity,否则直接进入
//					延时 , splashGone是一个线程.
					mHandler.postDelayed(splashGone, SHOW_TIME_MIN
							- loadingTime);
				} else {
					mHandler.post(splashGone);
				}
				break;

//				获取天气失败
			case GET_WEATHER_FAIL:
				MainActivity.this.updateWeatherInfo(null);
				MainActivity.this.updateAqiInfo(null);
				ToastUtil.show(MainActivity.this, "获取天气失败,请重试", Toast.LENGTH_SHORT);
				MainActivity.this.mUpdateProgressBar.stopAnim();
				break;

			default:
				break;
			}
		}
	};

	// 正式进入MainActivity
	Runnable splashGone = new Runnable() {

		@Override
		public void run() {

			Animation anim = AnimationUtils.loadAnimation(MainActivity.this,
					R.anim.push_right_out);
//			监听
			anim.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					// TODO Auto-generated method stub
					mSplashView.setVisibility(View.GONE);
				}
			});
//			开启动画
			mSplashView.startAnimation(anim);
		}
	};
/**
 * 更新组件
 */
	private void updateWidgetWeather() {
//		发送一条广播即可
		sendBroadcast(new Intent(UPDATE_WIDGET_WEATHER_ACTION));
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.initData();
		this.initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		NotificationManager notificationManager = mApplication
				.getNotificationManager();
		if (notificationManager != null)
			notificationManager.cancelAll();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		NetBroadcastReceiver.mListeners.remove(this);
	}

	/*
	 * 进入SelectCityActivty
	 */
	private void startActivityForResult() {
		Intent i = new Intent(this, SelectCtiyActivity.class);
		this.startActivityForResult(i, 0);
	}
	/*
	 * 初始化界面
	 */
	private void initView() {
		mSplashView = findViewById(R.id.splash_view);
		mCityManagerBtn = (ImageView) findViewById(R.id.title_city_manager);
		mShareBtn = (ImageView) findViewById(R.id.title_share);
		mLocationBtn = (ImageView) findViewById(R.id.title_location);
		mCityManagerBtn.setOnClickListener(this);
		mShareBtn.setOnClickListener(this);
		mLocationBtn.setOnClickListener(this);
		mUpdateProgressBar = (RotateImageView) findViewById(R.id.title_update_progress);
		mUpdateProgressBar.setOnClickListener(this);
		mTitleTextView = (TextView) findViewById(R.id.title_city_name);

		cityTv = (TextView) findViewById(R.id.city);
		timeTv = (TextView) findViewById(R.id.time);
		timeTv.setText("未发布");
		weekTv = (TextView) findViewById(R.id.week_today);

		mAqiRootView = findViewById(R.id.aqi_root_view);
		mAqiRootView.setVisibility(View.INVISIBLE);
		mShareView = findViewById(R.id.weather_share_view);
		aqiDataTv = (TextView) findViewById(R.id.pm_data);
		aqiQualityTv = (TextView) findViewById(R.id.pm2_5_quality);
		aqiImg = (ImageView) findViewById(R.id.pm2_5_img);
		temperatureTv = (TextView) findViewById(R.id.temperature);
		climateTv = (TextView) findViewById(R.id.climate);
		windTv = (TextView) findViewById(R.id.wind);
		weatherImg = (ImageView) findViewById(R.id.weather_img);
//		碎片
		fragments = new ArrayList<Fragment>();
		fragments.add(new FirstWeatherFragment());
		fragments.add(new SecondWeatherFragment());

		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mWeatherPagerAdapter = new WeatherPagerAdapter(
				getSupportFragmentManager(), fragments);
		mViewPager.setAdapter(mWeatherPagerAdapter);
		((CirclePageIndicator) findViewById(R.id.indicator))
				.setViewPager(mViewPager);
		if (TextUtils.isEmpty(mSpUtil.getCity())) {
			if (NetUtil.getNetworkState(this) != NetUtil.NETWORN_NONE) {
				mLocationClient.start();
				mLocationClient.requestLocation();
				mUpdateProgressBar.startAnim();
			} else {
				ToastUtil.showShort(this, R.string.net_err);
			}
		} else {
			mHandler.sendEmptyMessage(UPDATE_EXISTS_CITY);
		}
	}
	/**
	 * 初始化数据
	 */
	private void initData() {
		mStartTime = System.currentTimeMillis();// 记录开始时间

		NetBroadcastReceiver.mListeners.add(this);
//		获得Application的单实例
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();
		mLocationClient = mApplication.getLocationClient();
		mLocationClient.registerLocationListener(mLocationListener);
		mCityDB = mApplication.getCityDB();
//		分享功能
		mShareUtil = new ShareUtil(this, mHandler);
	}

	/**
	 * 开启AsyncTask进行天气信息的抓取
	 * @param city
	 */
	private void updateWeather(City city) {
		// 因为在异步任务中有判断网络连接问题,在网络请求前先获取文件中的缓存,所以,此处未处理网络连接问题
		if (city == null) {
			ToastUtil.showLong(mApplication, "未找到此城市,请重新定位或选择...");
			return;
		}
		timeTv.setText("同步中...");
		mTitleTextView.setText(city.getName());
//		更新时的动画
		mUpdateProgressBar.startAnim();
//		开启异步Task进行天气的抓取
		new GetWeatherTask(mHandler, city).execute();
	}

	/**
	 * 更新天气界面
	 */
	private void updateWeatherInfo(WeatherInfo allWeather) {
//		今天的星期
		weekTv.setText("今天 " + TimeUtil.getWeek(0, TimeUtil.XING_QI));
//		如果有fragments,则进行更新
		if (fragments.size() > 0) {
			((FirstWeatherFragment) mWeatherPagerAdapter.getItem(0))
					.updateWeather(allWeather);
			((SecondWeatherFragment) mWeatherPagerAdapter.getItem(1))
					.updateWeather(allWeather);
		}

		if (allWeather != null) {
			cityTv.setText(allWeather.getCity());
//			温度
			if (!TextUtils.isEmpty(allWeather.getFeelTemp())) {
				temperatureTv.setText(allWeather.getFeelTemp());
//				保存温度
				mSpUtil.setSimpleTemp(allWeather.getFeelTemp()
						.replace("~", "/").replace("℃", "°"));// 保存一下温度信息,用户小插件
			} else {
				temperatureTv.setText(allWeather.getTemp0());
				mSpUtil.setSimpleTemp(allWeather.getTemp0().replace("~", "/")
						.replace("℃", "°"));
			}

			String climate = allWeather.getWeather0();
			climateTv.setText(climate);
			mSpUtil.setSimpleClimate(climate);// 保存一下天气信息,用户小插件

			weatherImg.setImageResource(this.getWeatherIcon(climate));
			windTv.setText(allWeather.getWind0());

			String time = allWeather.getIntime();
			mSpUtil.setTimeSamp(TimeUtil.getLongTime(time));// 保存一下更新的时间戳,记录更新时间
			timeTv.setText(TimeUtil.getDay(mSpUtil.getTimeSamp()) + "发布");
		} else {
			cityTv.setText(mSpUtil.getCity());
			timeTv.setText("未同步");
			temperatureTv.setText("N/A");
			climateTv.setText("N/A");
			windTv.setText("N/A");
			weatherImg.setImageResource(R.drawable.na);
			ToastUtil.showLong(mApplication, "获取天气信息失败");
		};

	}

	/**
	 * 更新AQI界面
	 */
	private void updateAqiInfo(WeatherInfo allWeather) {

		if (allWeather != null && allWeather.getAQIData() != null) {

			mAqiRootView.setVisibility(View.VISIBLE);
			aqiDataTv.setText(allWeather.getAQIData());

			int aqi = Integer.parseInt(allWeather.getAQIData());
			int aqi_img = R.drawable.biz_plugin_weather_0_50;
			String aqiText = "无数据";
//			根据不同的污染程度来选择不同的图片
			if (aqi > 300) {
				aqi_img = R.drawable.biz_plugin_weather_greater_300;
				aqiText = "严重污染";
			} else if (aqi > 200) {
				aqi_img = R.drawable.biz_plugin_weather_201_300;
				aqiText = "重度污染";
			} else if (aqi > 150) {
				aqi_img = R.drawable.biz_plugin_weather_151_200;
				aqiText = "中度污染";
			} else if (aqi > 100) {
				aqi_img = R.drawable.biz_plugin_weather_101_150;
				aqiText = "轻度污染";
			} else if (aqi > 50) {
				aqi_img = R.drawable.biz_plugin_weather_51_100;
				aqiText = "良";
			} else {
				aqi_img = R.drawable.biz_plugin_weather_0_50;
				aqiText = "优";
			}

			aqiImg.setImageResource(aqi_img);
			aqiQualityTv.setText(aqiText);

		} else {
			mAqiRootView.setVisibility(View.INVISIBLE);
			aqiQualityTv.setText("");
			aqiDataTv.setText("");
			aqiImg.setImageResource(R.drawable.biz_plugin_weather_0_50);
			ToastUtil.showShort(mApplication, "该城市暂无空气质量数据");
		}
	};
	/**
	 * 获得天气的图片
	 * @param climate
	 * @return
	 */
	private int getWeatherIcon(String climate) {
		int weatherIcon = R.drawable.biz_plugin_weather_qing;
		if (climate.contains("转")) {// 天气带转字,取前面那部分
			String[] strs = climate.split("转");
			climate = strs[0];
			if (climate.contains("到")) {// 如果转字前面那部分带到字,则取它的后部分
				strs = climate.split("到");
				climate = strs[1];
			}
		}
		if (mApplication.getWeatherIconMap().containsKey(climate)) {
			weatherIcon = mApplication.getWeatherIconMap().get(climate);
		}
		return weatherIcon;
	}

	/*
	 * 成员变量
	 */
	BDLocationListener mLocationListener = new BDLocationListener() {

		@Override
		public void onReceivePoi(BDLocation arg0) {
			// do nothing
		}

		@Override
		public void onReceiveLocation(BDLocation location) {
			mUpdateProgressBar.stopAnim();
			if (location == null || TextUtils.isEmpty(location.getCity())) {
				MainActivity.this.showLocationFailDialog();
				return;
			}
			// 获取当前城市,
			String cityName = location.getCity();
			mLocationClient.stop();
			// 从数据库中找到该城市
			City curCity = mCityDB.getCity(cityName);
//			发送Handler, 更新UI
			if (curCity != null) {
				Message msg = mHandler.obtainMessage();
				msg.what = LOACTION_OK;
				msg.obj = curCity;
				mHandler.sendMessage(msg);// 更新天气
			} else {// 如果定位到的城市数据库中没有,也弹出定位失败
				MainActivity.this.showLocationFailDialog();
			}
		}
	};

	/**
	 * 定位失败后处理
	 */
	private void showLocationFailDialog() {
		final Dialog dialog = IphoneDialog.getTwoBtnDialog(MainActivity.this,
				"定位失败", "是否手动选择城市?");
		((Button) dialog.findViewById(R.id.ok))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						MainActivity.this.startActivityForResult();
						dialog.dismiss();
					}
				});
		dialog.show();
	}
	/**
	 * 处理得到的City对象
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0 && resultCode == RESULT_OK) {
			City city = (City) data.getSerializableExtra("city");
			mSpUtil.setCity(city.getName());
			this.updateWeather(city);
		}
	}

	/*
	 * 网络状态改变以后的处理
	 * @see com.way.app.NetBroadcastReceiver.EventHandler#onNetChange()
	 */
	@Override
	public void onNetChange() {
		if (NetUtil.getNetworkState(this) == NetUtil.NETWORN_NONE) {
			ToastUtil.showLong(this, R.string.net_err);
		} else {
			if (!TextUtils.isEmpty(mSpUtil.getCity()))
//				更新City
				mHandler.sendEmptyMessage(UPDATE_EXISTS_CITY);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_city_manager:
			this.startActivityForResult();
			break;
//			定位
		case R.id.title_location:
			if (NetUtil.getNetworkState(this) != NetUtil.NETWORN_NONE) {
				if (!mLocationClient.isStarted())
					mLocationClient.start();
				mLocationClient.requestLocation();
				ToastUtil.showShort(this, "正在定位...");
			} else {
				ToastUtil.showShort(this, R.string.net_err);
			}
			break;
//			分享
		case R.id.title_share:
			if (NetUtil.getNetworkState(this) != NetUtil.NETWORN_NONE) {
				byte[] bm = getSharePicture();
				if (bm != null && mApplication.getAllWeather() != null)
					mShareUtil.share(bm,
							getShareContent(mApplication.getAllWeather()));
				else
					ToastUtil.showShort(this, "分享失败");
			} else {
				ToastUtil.showShort(this, R.string.net_err);
			}
			break;

		case R.id.title_update_progress:
			if (NetUtil.getNetworkState(this) != NetUtil.NETWORN_NONE) {
				if (TextUtils.isEmpty(mSpUtil.getCity())) {
					ToastUtil.showShort(this, "请先选择城市或定位!");
				} else {
					String sPCityName = mSpUtil.getCity();
					City curCity = mCityDB.getCity(mSpUtil.getCity());
					updateWeather(curCity);
				}
			} else {
				ToastUtil.showShort(this, R.string.net_err);
			}
			break;

		default:
			break;
		}
	}

	/**
	 * 获得分享的图片
	 * @return
	 */
	private byte[] getSharePicture() {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			mShareView.setDrawingCacheEnabled(true);
			Bitmap.createBitmap(mShareView.getDrawingCache()).compress(
					Bitmap.CompressFormat.PNG, 100, baos);
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
//	分享的链接的格式
	private String mShare = "今日%s天气:%s,温度:%s;空气质量指数(AQI):%s,PM2.5 浓度值:%s μg/m3。";
	private String mShareSimple = "今日%s天气:%s,温度:%s,湿度:%s,风向:%s。";

	private String getShareContent(WeatherInfo weatherInfo) {
		String aqi = weatherInfo.getAQIData();
		String pm2d5 = weatherInfo.getPM2Dot5Data();
//		详细版
		if (!TextUtils.isEmpty(aqi) && !TextUtils.isEmpty(pm2d5))
			return String.format(mShare, new Object[] { weatherInfo.getCity(),
					weatherInfo.getWeather0(), weatherInfo.getTemp0(),
					weatherInfo.getAQIData(), weatherInfo.getPM2Dot5Data() });
//		简洁版
		return String.format(mShareSimple,
				new Object[] { weatherInfo.getCity(),
						weatherInfo.getWeather0(), weatherInfo.getTemp0(),
						weatherInfo.getShidu(), weatherInfo.getWinNow() });
	}

	/**
	 * 连续按两次返回键就退出
	 */
	private long firstTime;

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() - firstTime < 3000) {
			finish();
		} else {
			firstTime = System.currentTimeMillis();
			ToastUtil.showShort(this, R.string.press_again_exit);
		}
	}

}


text:
package org.dbflute.erflute.db.impl.standard_sql;

import org.dbflute.erflute.editor.model.dbimport.PreImportFromDBManager;

public class StandardSQLPreTableImportManager extends PreImportFromDBManager {
}


text:
require 'spec_helper'

describe PivotalTracker::Project do
  before do
    @pivotal = PivotalTracker(:token => 'foo')
    @project = PivotalTracker::Project.new(:id => 1)
    @headers = {'Accept' => 'application/xml', 'X-TrackerToken' => 'foo'}
    ActiveResource::HttpMock.respond_to do |mock|
      mock.get "/services/v3/projects/1.xml", @headers, fixture('project.xml')
      mock.get "/services/v3/projects/1/iterations.xml?group=current",
        @headers, fixture('iterations.xml')
      mock.get "/services/v3/projects/1/iterations.xml?group=backlog",
        @headers, fixture('backlog.xml')
      mock.get "/services/v3/projects/1/iterations.xml?group=done",
        @headers, fixture('done.xml')
      mock.get "/services/v3/projects/1/stories.xml", @headers,
        fixture('stories.xml')
      mock.get "/services/v3/projects/1/stories/1.xml", @headers,
        fixture('story.xml')
      mock.get "/services/v3/projects/1/stories.xml?filter=type%3A+bug",
        @headers, fixture('bugs.xml')
      mock.get "/services/v3/projects/1/stories.xml?filter=type%3A+chore",
        @headers, fixture('chores.xml')
      mock.get "/services/v3/projects/1/stories.xml?filter=type%3A+feature",
        @headers, fixture('features.xml')
    end
  end

  context "project" do
    it "should return a project" do
      project = PivotalTracker::Project.find(1)
      project.should be_kind_of(PivotalTracker::Project)
    end
  end

  context "iterations" do
    it "should return the current iteration" do
      @project.current.should be_kind_of(PivotalTracker::Iteration)
    end
    it "should return done iterations" do
      @project.done.should be_kind_of(Array)
    end
    it "should return backlog iterations" do
      @project.backlog.should be_kind_of(Array)
    end
  end

  context "stories" do
    it "should return all stories" do
      @project.stories.should be_kind_of(Array)
      @project.stories.size.should == 3
    end
    it "should return a story by id" do
      @project.story(1).should be_kind_of(PivotalTracker::Story)
    end
    it "should return all bugs" do
      @project.bugs.should be_kind_of(Array)
      @project.bugs.size.should == 1
    end
    it "should return all chores" do
      @project.chores.should be_kind_of(Array)
      @project.chores.size.should == 1
    end
    it "should return all features" do
      @project.features.should be_kind_of(Array)
      @project.features.size.should == 1
    end
  end
end


text:
RSpec.describe RuboCop::Cop::Style::MapCompactWithConditionalBlock, :config do
  context 'With multiline block' do
    it 'registers an offense and corrects to `select` with `if` condition' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          if item.bar?
            item
          else
            next
          end
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` with multi-line `if` condition' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          if item.bar? &&
            bar.baz
            item
          else
            next
          end
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? &&
            bar.baz }
      RUBY
    end

    it 'registers an offense and corrects to `select` if `next value` in if_branch and `nil` in else_branch' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          if item.bar?
            next item
          else
            nil
          end
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with `if` condition' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          if item.bar?
            next
          else
            item
          end
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` if `next value` in else_branch and `nil` in if_branch' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          if item.bar?
            nil
          else
            next item
          end
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` with ternary expression' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          item.bar? ? item : next
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with ternary expression' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          item.bar? ? next : item
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` with modifier form of `if` condition' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          item if item.bar?
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with modifier form of `unless` condition' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          item unless item.bar?
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` with guard clause of `if`' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          next if item.bar?

          item
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with guard clause of `unless`' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          next unless item.bar?

          item
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` with guard clause of `if` and `next` has a value' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          next item if item.bar?
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with guard clause of `unless` and `next` has a value' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          next item unless item.bar?
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` with guard clause of `if` and `next` has a value and return nil' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          next item if item.bar?

          nil
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with guard clause of `unless` and `next` has a value and return nil' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          next item unless item.bar?

          nil
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` with guard clause of `if` and next explicitly nil' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          next nil if item.bar?

          item
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with guard clause of `unless` and `next` explicitly nil' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          next nil unless item.bar?

          item
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` if condition has not else branch' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
          if item.bar?
            item
          end
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with `unless` condition' do
      expect_offense(<<~RUBY)
        foo.map do |item|
            ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
          unless item.bar?
            item
          end
        end.compact
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'does not register offenses if `compact` is not chained to `map`' do
      expect_no_offenses(<<~RUBY)
        foo.map do |item|
          if item.bar?
            item
          else
            next
          end
        end
      RUBY
    end

    it 'does not register offenses if return value is not same as block argument' do
      expect_no_offenses(<<~RUBY)
        foo.map do |item|
          if item.bar?
            1
          else
            2
          end
        end.compact
      RUBY
    end

    it 'does not register offenses if condition has elsif branch' do
      expect_no_offenses(<<~RUBY)
        foo.map do |item|
          if item.bar?
            item
          elsif
            baz
          else
            next
          end
        end.compact
      RUBY
    end

    it 'does not register offenses if there are multiple guard clauses' do
      expect_no_offenses(<<~RUBY)
        next unless item.bar?
        next unless item.baz?

        item
      RUBY
    end
  end

  context 'With single line block' do
    it 'registers an offense and corrects to `select` with ternary expression' do
      expect_offense(<<~RUBY)
        foo.map { |item| item.bar? ? item : next }.compact
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with ternary expression' do
      expect_offense(<<~RUBY)
        foo.map { |item| item.bar? ? next : item }.compact
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `select` with modifier form of `if` condition' do
      expect_offense(<<~RUBY)
        foo.map { |item| item if item.bar? }.compact
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
      RUBY

      expect_correction <<~RUBY
        foo.select { |item| item.bar? }
      RUBY
    end

    it 'registers an offense and corrects to `reject` with modifier form of `unless` condition' do
      expect_offense(<<~RUBY)
        foo.map { |item| item unless item.bar? }.compact
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
      RUBY

      expect_correction <<~RUBY
        foo.reject { |item| item.bar? }
      RUBY
    end

    it 'does not register offenses if `compact` is not chained to `map`' do
      expect_no_offenses(<<~RUBY)
        foo.map { |item| item if item.bar }
      RUBY
    end
  end
end


text:
class SymLinkCollector : public Collector {
  boost::filesystem::path path_;
public:
  bool initialize(boost::filesystem::path const &input_file) {
    path_ = input_file;
    // a symlink is valid only if the link's target exist and is valid
    if(! boost::filesystem::is_symlink(input_file))
      return false;
    path_ = input_file;
    do {
      try {
        std::set<boost::filesystem::path> deps;
        (*this)(deps);
        path_ = *deps.begin();
      }
      catch (boost::filesystem::filesystem_error const &err) {
        return false;
      }
    }
    while (boost::filesystem::is_symlink(path_));

    // this assert the symlink is pointing to something we know
    if(!Collector::get_collector(path_).get())
      return false;
    // everything is ok
    path_ = input_file;
    return true;
  }

  void operator()(std::set<boost::filesystem::path> &deps) {
    boost::filesystem::path target =
        boost::filesystem::read_symlink(path_);
    if (target.is_absolute())
      target = Env::root() / target;
    else
      target = boost::filesystem::canonical(target, path_.parent_path());

    if (not boost::filesystem::exists(target)) {
      throw boost::filesystem::filesystem_error(
          "dangling symlink", target,
          boost::system::error_code(
              boost::system::errc::no_such_file_or_directory,
              boost::system::system_category()));
    }
    deps.insert(target);
  }
  void operator()(MetadataInfo &mi) {
  // do not compute canonical name, it will be done by the target
  }
};

static Collector::Register registry(&make_collector<SymLinkCollector>);


text:
#include "Htfe.h"
#include "HtfeDesign.h"

CHtfeIdent * CHtfeIdent::SetPromoteToSigned(bool bPromoteToSigned) {
	m_bPromoteToSigned = bPromoteToSigned;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetPromoteToSigned(bPromoteToSigned);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetPromoteToSigned(bPromoteToSigned);
	return this;
}

CHtfeIdent * CHtfeIdent::SetIsSigned(bool bIsSigned) {
	m_bIsSigned = bIsSigned;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsSigned(bIsSigned);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsSigned(bIsSigned);
	return this;
}

CHtfeIdent * CHtfeIdent::SetType(CHtfeIdent *pType) {
	m_pType = pType;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetType(pType);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetType(pType);
	return this;
}

void CHtfeIdent::SetLineInfo(const CLineInfo &lineInfo) {
	m_lineInfo = lineInfo;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetLineInfo(lineInfo);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetLineInfo(lineInfo);
}

CHtfeIdent * CHtfeIdent::SetId(EIdentId id) {
	m_id = id;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetId(id);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetId(id);
	return this;
}

void CHtfeIdent::InsertSensitive(CHtfeIdent * pIdent, int elemIdx) {
    if (m_pSensitiveTbl == 0)
        m_pSensitiveTbl = new CScSensitiveTbl;
    m_pSensitiveTbl->Insert(pIdent, elemIdx);
}

CScSensitiveTbl & CHtfeIdent::GetSensitiveTbl() {
    if (m_pSensitiveTbl == 0)
        m_pSensitiveTbl = new CScSensitiveTbl;
    return *m_pSensitiveTbl;
}

void CHtfeIdent::NewFlatTable() {
	m_pFlatTbl = new CHtfeIdentTbl;
}

CHtfeIdent * CHtfeIdent::InsertIdent(const string &name, bool bInsertFlatTbl, bool bAllowOverloading)
{
	if (bInsertFlatTbl) {
		string flatVarName = name;
		if (m_name.size() == 0 && name != "true" && name != "false")
			flatVarName = name + "$g";
		return InsertIdent(name, flatVarName);
	}

    if (m_pIdentTbl == 0) m_pIdentTbl = new CHtfeIdentTbl;
	CHtfeIdent *pHierIdent = m_pIdentTbl->Insert(name, bAllowOverloading);
	pHierIdent->SetPrevHier(this);
	pHierIdent->SetIsLocal(IsLocal());
    return pHierIdent;
}

CHtfeIdent * CHtfeIdent::InsertIdent(const string &heirVarName, const string &flatVarName)
{
    if (m_pIdentTbl == 0) m_pIdentTbl = new CHtfeIdentTbl;
	CHtfeIdent *pHierIdent = m_pIdentTbl->Insert(heirVarName);
	if (pHierIdent->GetId() != id_new)
		return pHierIdent;

	pHierIdent->SetPrevHier(this);
	pHierIdent->SetIsLocal(IsLocal());

	CHtfeIdent * pFlatIdent = InsertFlatIdent(pHierIdent, flatVarName);

	pHierIdent->SetFlatIdent(pFlatIdent);

	return pHierIdent;
}

CHtfeIdent * CHtfeIdent::InsertFlatIdent(CHtfeIdent * pHierIdent, const string &flatVarName) {
	// New variable, insert into flat identifier table
	if (m_pFlatTbl == 0) {
		if (IsFlatIdent())
			m_pFlatTbl = new CHtfeIdentTbl;
		else
			m_pFlatTbl = &m_pFlatIdent->GetFlatIdentTbl();
	}

	CHtfeIdent *pFlatIdent;
	int nextUniqueId;
	if (m_verilogKeywordTbl.Find(flatVarName, nextUniqueId)) {
		// name conflict, make name unique
		char buf[256];
		sprintf(buf, "%s$$%d", flatVarName.c_str(), nextUniqueId);
		pFlatIdent = m_pFlatTbl->Insert(buf);
	} else {
		pFlatIdent = m_pFlatTbl->Insert(flatVarName);
		if (pFlatIdent->GetId() != id_new) {
			// name conflict, make name unique
			char buf[256];
			sprintf(buf, "%s$$%d", flatVarName.c_str(), pFlatIdent->GetNextUniqueId());
			pFlatIdent = m_pFlatTbl->Insert(buf);
		}
	}
	Assert(pFlatIdent->GetId() == id_new);

	pFlatIdent->SetIsLocal(IsLocal());
 	pFlatIdent->SetIsFlatIdent();

	pFlatIdent->SetHierIdent(pHierIdent);
	pFlatIdent->SetType(pHierIdent->GetType());

	return pFlatIdent;
}

void CHtfeIdent::DeleteIdent(const string &name) {
	m_pIdentTbl->Delete(name);
}

CHtfeIdent * CHtfeIdent::FindIdent(const string &name) const {
	return m_pIdentTbl ? m_pIdentTbl->Find(name) : 0;
}

CHtfeIdent * CHtfeIdent::FindIdent(const char *pName) const {
	const string name(pName);
	return m_pIdentTbl ? m_pIdentTbl->Find(name) : 0;
}

CHtfeIdentTbl & CHtfeIdent::GetIdentTbl() {
    if (m_pIdentTbl == 0)
        m_pIdentTbl = new CHtfeIdentTbl;
    return *m_pIdentTbl;
}

CHtfeIdentTbl & CHtfeIdent::GetFlatIdentTbl() {
	if (m_pFlatTbl == 0)
		m_pFlatTbl = new CHtfeIdentTbl;
	return *m_pFlatTbl;
}

void CHtfeIdent::ValidateIndexList(vector<CHtfeOperand *> *pIndexList) {
	if (pIndexList == 0) {
		Assert(m_dimenList.size() == 0);
		return;
	}
 	Assert(pIndexList->size() == m_dimenList.size());
	for (size_t idxNum = 0; idxNum < m_dimenList.size(); idxNum += 1) {
		Assert((*pIndexList)[idxNum]->IsConstValue());
		Assert((*pIndexList)[idxNum]->GetConstValue().GetSint64() < m_dimenList[idxNum]);
	}
}

void CHtfeIdent::ValidateIndexList(CHtfeOperand *pOperand) {
	if (pOperand->GetDimenCnt() == 0) {
		Assert(GetDimenCnt() == 0);
		return;
	}
 	Assert(pOperand->GetDimenCnt() == GetDimenCnt());
	for (size_t idxNum = 0; idxNum < GetDimenCnt(); idxNum += 1)
		Assert(pOperand->GetDimenIdx(idxNum) < (int64_t)GetDimenSize(idxNum));
}

CHtfeIdent * CHtfeIdent::SetWidth(int width) {
	m_width = width;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetWidth(width);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetWidth(width);
	return this;
}

int CHtfeIdent::GetWidth(CLineInfo lineInfo) const {
	CLineInfo info = lineInfo.m_lineNum == 0 ? m_lineInfo : lineInfo;
	if (m_width > 0)
		return m_width;
	else if (m_pType)
        return m_pType->GetWidth(info);
	else {
		ErrorMsg(PARSE_ERROR, info, "zero width type");
		ErrorMsg(PARSE_FATAL, info, "Previous errors prohibit further parsing");
		return 0;
	}
}

CHtfeIdent * CHtfeIdent::SetOpWidth(int width) {
	m_opWidth = width;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetOpWidth(width);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetOpWidth(width);
	return this;
}

void CHtfeIdent::SetIsRegister(bool bIsRegister) {
	m_bIsRegister = bIsRegister;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsRegister(bIsRegister);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsRegister(bIsRegister);
}

void CHtfeIdent::SetHtDistRamWeWidth(vector<CHtDistRamWeWidth> *pWeWidth) {
	m_pHtDistRamWeWidth = pWeWidth;
	if (IsHierIdent())
		m_pFlatIdent->SetHtDistRamWeWidth(pWeWidth);

	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetHtDistRamWeWidth(pWeWidth);
	}
}

void CHtfeIdent::SetIsReadOnly(bool bIsReadOnly) {
	m_bIsReadOnly = bIsReadOnly;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsReadOnly(bIsReadOnly);
	}
}

CHtfeIdent * CHtfeIdent::SetIsWriteOnly(bool bIsWriteOnly) {
	m_bIsWriteOnly = bIsWriteOnly;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsWriteOnly(bIsWriteOnly);
	}
	return this;
}

void CHtfeIdent::SetIsRemoveIfWriteOnly(bool bIsRemoveIfWriteOnly) {
	m_bIsRemoveIfWriteOnly = bIsRemoveIfWriteOnly;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsRemoveIfWriteOnly(bIsRemoveIfWriteOnly);
	}
}

void CHtfeIdent::SetPortDir(EPortDir portDir) {
	m_portDir = portDir;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetPortDir(portDir);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetPortDir(portDir);
}

void CHtfeIdent::SetIsParam(bool bIsParam) {
	m_bIsParam = bIsParam;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsParam(bIsParam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsParam(bIsParam);
}

int CHtfeIdent::GetDimenElemIdx(CHtfeOperand * pOperand) {
	if (pOperand == 0)
		return -1;

	int elemIdx = 0;
	int idxMul = 1;
	vector<CHtfeOperand *> &indexList = pOperand->GetIndexList();
	for (int i = m_dimenList.size() - 1; i >= 0; i -= 1) {
		if (!indexList[i]->IsConstValue())
			return -1;
		elemIdx += idxMul * indexList[i]->GetConstValue().GetSint32();
		idxMul *= m_dimenList[i];
	}
	return elemIdx;
}

int CHtfeIdent::GetDimenElemIdx(vector<int> const & refList)
{
	Assert(m_dimenList.size() == refList.size());
	int elemIdx = 0;
	int idxMul = 1;
	for (int i = m_dimenList.size() - 1; i >= 0; i -= 1) {
		elemIdx += idxMul * refList[i];
		idxMul *= m_dimenList[i];
	}
	return elemIdx;
}

int CHtfeIdent::CalcElemIdx() {
	vector<int> &dimenList = (GetPrevHier() && GetPrevHier()->IsArrayIdent()) ? GetPrevHier()->GetDimenList() : GetDimenList();
	int elemIdx = 0;
	int idxMul = 1;
	for (int i = dimenList.size() - 1; i >= 0; i -= 1) {
		elemIdx += idxMul * m_indexList[i];
		idxMul *= dimenList[i];
	}
	return elemIdx;
}

void CHtfeIdent::SetIsConst(bool bIsConst) {
	m_bIsConst = bIsConst;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsConst(bIsConst);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsConst(bIsConst);
}

void CHtfeIdent::SetIsReference(bool bIsReference) {
	m_bIsReference = bIsReference;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsReference(bIsReference);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsReference(bIsReference);
}

void CHtfeIdent::SetIsNoLoad(bool bIsHtNoLoad) {
	m_bIsNoLoad = bIsHtNoLoad;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsNoLoad(bIsHtNoLoad);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsNoLoad(bIsHtNoLoad);
}

void CHtfeIdent::SetIsScPrim(bool bIsHtPrim) {
	m_bIsScPrim = bIsHtPrim;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsScPrim(bIsHtPrim);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsScPrim(bIsHtPrim);
}

void CHtfeIdent::SetIsScLocal(bool bIsHtLocal) {
	m_bIsScLocal = bIsHtLocal;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsScLocal(bIsHtLocal);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsScLocal(bIsHtLocal);
}

//void CHtfeIdent::SetIsHtPrimOutput(bool bIsScPrimOutput) {
//	m_bIsScPrimOutput |= bIsScPrimOutput;
//	if (m_dimenList.size() > 0) {
//		CHtfeIdentTblIter iter(GetIdentTbl());
//		for (iter.Begin(); !iter.End(); iter++)
//			iter->SetIsHtPrimOutput(bIsScPrimOutput);
//	}
//	if (m_pFlatIdent) m_pFlatIdent->SetIsHtPrimOutput(bIsScPrimOutput);
//}

void CHtfeIdent::SetHtPrimClkList(vector<string> const & htPrimClkList) {
	m_htPrimClkList = htPrimClkList;
	m_bIsScClockedPrim = htPrimClkList.size() > 0;

	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetHtPrimClkList(htPrimClkList);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetHtPrimClkList(htPrimClkList);
}

CHtfeIdent * CHtfeIdent::InsertInstancePort(string &name) {
    if (m_pInstancePortTbl == 0)
		m_pInstancePortTbl = new CHtfeIdentTbl;
    return m_pInstancePortTbl->Insert(name);
}

void CHtfeIdent::InsertMemInitStatements(CHtfeStatement *pStatement) {
	if (pStatement == 0)
		return;

	Assert(IsFunction());

	// insert statements at end of existing list
	CHtfeStatement **ppTail = &pStatement;
	while (*ppTail)
		ppTail = (*ppTail)->GetPNext();

	if (m_pMemInitStatementHead == 0)
		m_ppMemInitStatementTail = &m_pMemInitStatementHead;

	*m_ppMemInitStatementTail = pStatement;
	m_ppMemInitStatementTail = ppTail;
}

void CHtfeIdent::InsertStatementList(CHtfeStatement *pStatement) {
	if (pStatement == 0)
		return;

	Assert(IsFunction());
	// insert statements after previously inserted statements, but before appended statements

	CHtfeStatement **ppTail = &pStatement;
	while (*ppTail)
		ppTail = (*ppTail)->GetPNext();

	if (m_pStatementHead == 0) {
		m_ppStatementAppendTail = &m_pStatementHead;
		m_ppStatementInsertTail = &m_pStatementHead;
	}

	if (m_ppStatementAppendTail == m_ppStatementInsertTail) {
		// Only insert so far
		*m_ppStatementAppendTail = pStatement;
		*m_ppStatementInsertTail = pStatement;

		m_ppStatementAppendTail = ppTail;
		m_ppStatementInsertTail = ppTail;
	} else {
		*ppTail = *m_ppStatementInsertTail;
		*m_ppStatementInsertTail = pStatement;
		m_ppStatementInsertTail = ppTail;
	}
	Assert(*m_ppStatementAppendTail == 0);
}

void CHtfeIdent::AppendStatementList(CHtfeStatement *pStatement) {
	// append statements to end of list
	CHtfeStatement **ppTail = &pStatement;
	while (*ppTail)
		ppTail = (*ppTail)->GetPNext();

	if (m_pStatementHead == 0) {
		m_ppStatementAppendTail = &m_pStatementHead;
		m_ppStatementInsertTail = &m_pStatementHead;
	}

	*m_ppStatementAppendTail = pStatement;
	m_ppStatementAppendTail = ppTail;
}

void CHtfeIdent::SetIsHtDistQue(bool bIsHtDistQue) {
	m_bIsHtDistQue = bIsHtDistQue;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtDistQue(bIsHtDistQue);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtDistQue(bIsHtDistQue);
}

void CHtfeIdent::SetIsHtBlockQue(bool bIsHtBlockQue) {
	m_bIsHtBlockQue = bIsHtBlockQue;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtBlockQue(bIsHtBlockQue);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtBlockQue(bIsHtBlockQue);
}

void CHtfeIdent::SetIsHtUltraQue(bool bIsHtUltraQue) {
	m_bIsHtUltraQue = bIsHtUltraQue;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtUltraQue(bIsHtUltraQue);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtUltraQue(bIsHtUltraQue);
}

void CHtfeIdent::SetIsIgnoreSignalCheck(bool bIsIgnoreSignalCheck) {
	m_bIsIgnoreSignalCheck = bIsIgnoreSignalCheck;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsIgnoreSignalCheck(bIsIgnoreSignalCheck);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsIgnoreSignalCheck(bIsIgnoreSignalCheck);
}

void CHtfeIdent::SetIsHtDistRam(bool bIsHtDistRam) {
	m_bIsHtDistRam = bIsHtDistRam;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtDistRam(bIsHtDistRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtDistRam(bIsHtDistRam);
}

void CHtfeIdent::SetIsHtBlockRam(bool bIsHtBlockRam) {
	m_bIsHtBlockRam = bIsHtBlockRam;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtBlockRam(bIsHtBlockRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtBlockRam(bIsHtBlockRam);
}

void CHtfeIdent::SetIsHtMrdBlockRam(bool bIsHtMrdBlockRam) {
	m_bIsHtMrdBlockRam = bIsHtMrdBlockRam;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtMrdBlockRam(bIsHtMrdBlockRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtMrdBlockRam(bIsHtMrdBlockRam);
}

void CHtfeIdent::SetIsHtMwrBlockRam(bool bIsHtMwrBlockRam) {
	m_bIsHtMwrBlockRam = bIsHtMwrBlockRam;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtMwrBlockRam(bIsHtMwrBlockRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtMwrBlockRam(bIsHtMwrBlockRam);
}

void CHtfeIdent::SetIsHtBlockRamDoReg(bool bIsHtBlockRam) {
	m_bIsHtBlockRam = bIsHtBlockRam;
	m_bIsHtBlockRamDoReg = true;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtBlockRamDoReg(bIsHtBlockRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtBlockRam(bIsHtBlockRam);
}

void CHtfeIdent::SetIsHtUltraRam(bool bIsHtUltraRam) {
	m_bIsHtUltraRam = bIsHtUltraRam;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtUltraRam(bIsHtUltraRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtUltraRam(bIsHtUltraRam);
}

void CHtfeIdent::SetIsHtMrdUltraRam(bool bIsHtMrdUltraRam) {
	m_bIsHtMrdUltraRam = bIsHtMrdUltraRam;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtMrdUltraRam(bIsHtMrdUltraRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtMrdUltraRam(bIsHtMrdUltraRam);
}

void CHtfeIdent::SetIsHtMwrUltraRam(bool bIsHtMwrUltraRam) {
	m_bIsHtMwrUltraRam = bIsHtMwrUltraRam;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtMwrUltraRam(bIsHtMwrUltraRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtMwrUltraRam(bIsHtMwrUltraRam);
}

void CHtfeIdent::SetIsHtUltraRamDoReg(bool bIsHtUltraRam) {
	m_bIsHtUltraRam = bIsHtUltraRam;
	m_bIsHtUltraRamDoReg = true;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetIsHtUltraRamDoReg(bIsHtUltraRam);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetIsHtUltraRam(bIsHtUltraRam);
}

void CHtfeIdent::SetHtMemorySelWidth(int selWidth) {
	m_scMemorySelWidth = selWidth;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetHtMemorySelWidth(selWidth);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetHtMemorySelWidth(selWidth);
}

void CHtfeIdent::SetHtMemoryAddrWidth1(int addrWidth1) {
	m_scMemoryAddrWidth1 = addrWidth1;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetHtMemoryAddrWidth1(addrWidth1);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetHtMemoryAddrWidth1(addrWidth1);
}

void CHtfeIdent::SetHtMemoryAddrWidth2(int addrWidth2) {
	m_scMemoryAddrWidth2 = addrWidth2;
	if (m_dimenList.size() > 0) {
		CHtfeIdentTblIter iter(GetIdentTbl());
		for (iter.Begin(); !iter.End(); iter++)
			iter->SetHtMemoryAddrWidth2(addrWidth2);
	}
	if (m_pFlatIdent) m_pFlatIdent->SetHtMemoryAddrWidth2(addrWidth2);
}

void CHtfeIdent::AddGlobalRef(CHtIdentElem &identElem) {
    for (unsigned int i = 0; i < m_globalRefSet.size(); i += 1)
        if (m_globalRefSet[i].Contains(identElem)) {
			if (identElem.m_elemIdx == -1)
				m_globalRefSet[i].m_elemIdx = -1;
            return;
		}

    m_globalRefSet.push_back(identElem);
}

void CHtfeIdent::InsertArrayElements(int structBitPos)
{
	// Enter array members into table
	vector<int>	iterList;
	for (size_t i = 0; i < m_dimenList.size(); i += 1)
		iterList.push_back(0);

	size_t i;
	do {
		string memberName = GetName();

		char idxStr[16];
		for (i = 0; i < m_dimenList.size(); i += 1) {
			sprintf(idxStr, "%d", iterList[i]);
			memberName.append("[").append(idxStr).append("]");
		}

		CHtfeIdent *pMemberElem = InsertIdent(memberName, false);

		// set flags appropriate for a member
		if (structBitPos >= 0) {
			pMemberElem->SetStructPos(structBitPos);
			structBitPos += GetWidth();
		}
		pMemberElem->SetType(GetType());

		for (i = 0; i < m_dimenList.size(); i += 1) {
			iterList[i] += 1;
			if (iterList[i] == m_dimenList[i])
				iterList[i] = 0;
			else
				break;
		}
	} while (i < m_dimenList.size());
}

void CHtfeIdent::SetSeqState(ESeqState seqState, CHtfeOperand *pOp)
{
	if (GetPrevHier() && GetPrevHier()->IsArrayIdent()) { GetPrevHier()->SetSeqState(seqState, pOp); return; }
	if (!IsFlatIdent()) { m_pFlatIdent->SetSeqState(seqState, pOp); return; }

	if (m_dimenList.size() > 0)
		Assert(pOp && pOp->GetDimenCnt() == m_dimenList.size());
	if (m_refInfo.size() == 0)
		m_refInfo.resize(GetDimenElemCnt());

	if (m_dimenList.size() == 0 || pOp == 0)
		m_refInfo[0].m_seqState = seqState;
	else if (pOp == 0) {
		Assert(0);
		for (size_t idx = 0; idx < m_refInfo.size(); idx += 1)
			m_refInfo[idx].m_seqState = seqState;
	} else {
		vector<bool> constList(m_dimenList.size());
		vector<int> refList(m_dimenList.size());

		for (size_t dimIdx = 0; dimIdx < m_dimenList.size(); dimIdx += 1) {
			constList[dimIdx] = pOp->GetIndexList()[dimIdx]->IsConstValue();
			refList[dimIdx] = constList[dimIdx] ? pOp->GetIndexList()[dimIdx]->GetConstValue().GetSint32() : 0;
		}

		do {
			int idx = GetDimenElemIdx(refList);
			//for (size_t dimIdx = 0; dimIdx < m_dimenList.size(); dimIdx += 1) {
			//	idx *= m_dimenList[dimIdx];
			//	idx += refList[dimIdx];
			//}

			Assert(idx < (int)m_refInfo.size());
			m_refInfo[idx].m_seqState = seqState;
		} while(!DimenIter(refList, constList));
	}
}

ESeqState CHtfeIdent::GetSeqState(CHtfeOperand *pOp)
{
	if (GetPrevHier() && GetPrevHier()->IsArrayIdent())
		return GetPrevHier()->GetSeqState(pOp);

	if (!IsFlatIdent())
		return m_pFlatIdent->GetSeqState(pOp);

	if (m_dimenList.size() > 0)
		Assert(pOp && pOp->GetDimenCnt() == m_dimenList.size());

	Assert((int)m_refInfo.size() == GetDimenElemCnt());

	if (m_dimenList.size() == 0)
		return m_refInfo[0].m_seqState;
	else if (pOp == 0) {
		Assert(0);
		return ss_Unknown;
	} else {
		vector<bool> constList(m_dimenList.size());
		vector<int> refList(m_dimenList.size());

		for (size_t dimIdx = 0; dimIdx < m_dimenList.size(); dimIdx += 1) {
			constList[dimIdx] = pOp->GetIndexList()[dimIdx]->IsConstValue();
			refList[dimIdx] = constList[dimIdx] ? pOp->GetIndexList()[dimIdx]->GetConstValue().GetSint32() : 0;
		}

		bool bFirst = true;
		ESeqState seqState;
		do {
			int idx = GetDimenElemIdx(refList);
			//for (size_t dimIdx = 0; dimIdx < m_dimenList.size(); dimIdx += 1) {
			//	idx *= m_dimenList[dimIdx];
			//	idx += refList[dimIdx];
			//}

			Assert(idx < (int)m_refInfo.size());
			if (bFirst)
				seqState = m_refInfo[idx].m_seqState;

			else if (m_refInfo[idx].m_seqState != seqState) {
				ErrorMsg(PARSE_ERROR, pOp->GetLineInfo(), "Inconsistent sequence state amoung elements of array '%s'\n", GetName().c_str());
				break;
			}
		} while(!DimenIter(refList, constList));

		return seqState;
	}
}

void CHtfeIdent::SetIsAssignOutput(CHtfeOperand *pOp)
{
	if (GetPrevHier() && GetPrevHier()->IsArrayIdent()) { GetPrevHier()->SetIsAssignOutput(pOp); return; }
	if (!IsFlatIdent()) { m_pFlatIdent->SetIsAssignOutput(pOp); return; }

	if (m_dimenList.size() > 0)
		Assert(pOp && pOp->GetDimenCnt() == m_dimenList.size());
	if (m_refInfo.size() == 0)
		m_refInfo.resize(GetDimenElemCnt());

	if (m_dimenList.size() == 0)
		m_refInfo[0].m_bIsAssignOutput = true;
	else if (pOp == 0) {
		Assert(0);
		for (size_t idx = 0; idx < m_refInfo.size(); idx += 1)
			m_refInfo[idx].m_bIsAssignOutput = true;
	} else {
		vector<bool> constList(m_dimenList.size());
		vector<int> refList(m_dimenList.size());

		for (size_t dimIdx = 0; dimIdx < m_dimenList.size(); dimIdx += 1) {
			constList[dimIdx] = pOp->GetIndexList()[dimIdx]->IsConstValue();
			refList[dimIdx] = constList[dimIdx] ? pOp->GetIndexList()[dimIdx]->GetConstValue().GetSint32() : 0;
		}

		do {
			int idx = GetDimenElemIdx(refList);

			if (idx < (int)m_refInfo.size()) // can be out of range
				m_refInfo[idx].m_bIsAssignOutput = true;
		} while(!DimenIter(refList, constList));
	}
}

void CHtfeIdent::SetIsHtPrimOutput(CHtfeOperand *pOp)
{
	if (GetPrevHier() && GetPrevHier()->IsArrayIdent()) { GetPrevHier()->SetIsHtPrimOutput(pOp); return; }
	if (!IsFlatIdent()) { m_pFlatIdent->SetIsHtPrimOutput(pOp); return; }

	if (pOp && m_dimenList.size() > 0)
		Assert(pOp && pOp->GetDimenCnt() == m_dimenList.size());
	if (m_refInfo.size() == 0)
		m_refInfo.resize(GetDimenElemCnt());

	if (pOp == 0) {
		for (size_t idx = 0; idx < m_refInfo.size(); idx += 1)
			m_refInfo[idx].m_bIsHtPrimOutput = true;
	} else if (m_dimenList.size() == 0) {
		m_refInfo[0].m_bIsHtPrimOutput = true;
	} else {
		vector<bool> constList(m_dimenList.size());
		vector<int> refList(m_dimenList.size());

		for (size_t dimIdx = 0; dimIdx < m_dimenList.size(); dimIdx += 1) {
			constList[dimIdx] = pOp->GetIndexList()[dimIdx]->IsConstValue();
			refList[dimIdx] = constList[dimIdx] ? pOp->GetIndexList()[dimIdx]->GetConstValue().GetSint32() : 0;
		}

		do {
			int idx = GetDimenElemIdx(refList);

			if (idx < (int)m_refInfo.size()) // can be out of range
				m_refInfo[idx].m_bIsHtPrimOutput = true;
		} while(!DimenIter(refList, constList));
	}
}

void CHtfeIdent::SetReadRef(CHtfeOperand *pOp)
{
	if (GetPrevHier() && GetPrevHier()->IsArrayIdent()) { GetPrevHier()->SetReadRef(pOp); return; }
	if (!IsFlatIdent()) { m_pFlatIdent->SetReadRef(pOp); return; }

	if (m_dimenList.size() > 0)
		Assert(pOp && pOp->GetDimenCnt() == m_dimenList.size());
	if (m_refInfo.size() == 0)
		m_refInfo.resize(GetDimenElemCnt());

	if (m_dimenList.size() == 0)
		m_refInfo[0].m_bIsRead = true;
	else if (pOp == 0) {
		for (size_t idx = 0; idx < m_refInfo.size(); idx += 1)
			m_refInfo[idx].m_bIsRead = true;
	} else {
		vector<bool> constList(m_dimenList.size());
		vector<int> refList(m_dimenList.size());

		for (size_t dimIdx = 0; dimIdx < m_dimenList.size(); dimIdx += 1) {
			constList[dimIdx] = pOp->GetIndexList()[dimIdx]->IsConstValue();
			refList[dimIdx] = constList[dimIdx] ? pOp->GetIndexList()[dimIdx]->GetConstValue().GetSint32() : 0;
		}

		do {
			int idx = GetDimenElemIdx(refList);

			if (idx < (int)m_refInfo.size()) // can be out of range
				m_refInfo[idx].m_bIsRead = true;
		} while(!DimenIter(refList, constList));
	}
}

void CHtfeIdent::SetWriteRef(CHtfeOperand *pOp)
{
	if (GetPrevHier() && GetPrevHier()->IsArrayIdent()) { GetPrevHier()->SetWriteRef(pOp); return; }
	if (!IsFlatIdent()) { m_pFlatIdent->SetWriteRef(pOp); return; }

	if (m_dimenList.size() > 0)
		Assert(pOp && pOp->GetDimenCnt() == m_dimenList.size());
	if (m_refInfo.size() == 0)
		m_refInfo.resize(GetDimenElemCnt());

	if (m_dimenList.size() == 0)
		m_refInfo[0].m_bIsWritten = true;
	else if (pOp == 0) {
		for (size_t idx = 0; idx < m_refInfo.size(); idx += 1)
			m_refInfo[idx].m_bIsWritten = true;
	} else {
		vector<bool> constList(m_dimenList.size());
		vector<int> refList(m_dimenList.size());

		for (size_t dimIdx = 0; dimIdx < m_dimenList.size(); dimIdx += 1) {
			constList[dimIdx] = pOp->GetIndexList()[dimIdx]->IsConstValue();
			refList[dimIdx] = constList[dimIdx] ? pOp->GetIndexList()[dimIdx]->GetConstValue().GetSint32() : 0;
		}

		do {
			int idx = GetDimenElemIdx(refList);

			if (idx < (int)m_refInfo.size())    // can be out of range
				m_refInfo[idx].m_bIsWritten = true;
		} while(!DimenIter(refList, constList));
	}
}

void CHtfeIdent::MergeGlobalRefSet(vector<CHtIdentElem> &refSet)
{
    // merge the passed in reference set into the identifier's ref set, eliminate common references
    for (size_t ieIdx1 = 0; ieIdx1 < refSet.size(); ieIdx1 += 1) {
        CHtIdentElem & elem1 = refSet[ieIdx1];

        size_t ieIdx2;
        for (ieIdx2 = 0; ieIdx2 < m_globalRefSet.size(); ieIdx2 += 1) {
            CHtIdentElem & elem2 = m_globalRefSet[ieIdx2];

            if (elem1 == elem2)
                break;
        }

        if (ieIdx2 == m_globalRefSet.size())
            m_globalRefSet.push_back(elem1);
    }
}

bool CHtfeIdent::DimenIter(vector<int> &refList)
{
	// refList must be same size as dimenList and all elements zero
	Assert(m_dimenList.size() == refList.size());

	bool bDone;

	if (m_dimenList.size() > 0) {
		bDone = false;
		int i = (int)m_dimenList.size() - 1;
		refList[i] += 1;
		while (i >= 0) {
			if (refList[i] < m_dimenList[i])
				break;
			else {
				refList[i] = 0;
				i -= 1;
				if (i >= 0)
					refList[i] += 1;
				else
					bDone = true;
			}
		}
	} else
		bDone = true;

	return bDone;
}

bool CHtfeIdent::DimenIter(vector<int> &refList, vector<bool> &constList)
{
	// refList must be same size as dimenList and all elements zero
	//Assert(m_dimenList.size() == refList.size());

	bool bDone;

	if (refList.size() > 0) {
		bDone = false;
		int i;
		for (i = m_dimenList.size()-1; i >= 0; i -= 1) {
			if (!constList[i])
				break;
		}

		if (i < 0)
			return true;

		refList[i] += 1;
		while (i >= 0) {
			if (refList[i] < m_dimenList[i])
				break;
			else {
				refList[i] = 0;
				for (i -= 1; i >= 0; i -= 1)
					if (!constList[i])
						break;

				if (i >= 0)
					refList[i] += 1;
				else
					bDone = true;
			}
		}
	} else
		bDone = true;

	return bDone;
}

CHtfeIdent * CHtfeIdentTbl::Insert(const string &str, bool bAllowOverloading)
{
    IdentTblMap_InsertPair insertPair;
    insertPair = m_identTblMap.insert(IdentTblMap_ValuePair(str, (CHtfeIdent *)0));
	if (insertPair.first->second == 0) {
		insertPair.first->second = CHtfeDesign::NewIdent();
		insertPair.first->second->SetName(str);
	} else if (bAllowOverloading) {
		CHtfeIdent * pIdent = CHtfeDesign::NewIdent();
		pIdent->SetName(str);
		pIdent->SetOverloadedNext(insertPair.first->second);
		insertPair.first->second = pIdent;
	}
    return insertPair.first->second;
}


text:
(function($, window, document, undefined) {
    'use strict';

    // init cubeportfolio
    $('#js-grid-testimonials').cubeportfolio({
        layoutMode: 'slider',
        drag: true,
        auto: false,
        autoTimeout: 5000,
        autoPauseOnHover: true,
        showNavigation: false,
        showPagination: true,
        rewindNav: false,
        scrollByPage: false,
        gridAdjustment: 'responsive',
        mediaQueries: [{
            width: 1,
            cols: 1
        }],
        gapHorizontal: 0,
        gapVertical: 0,
        caption: '',
        displayType: 'default',
    });
})(jQuery, window, document);


text:
/*
 *
 * Clairvoyance
 *
 */

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { createStructuredSelector } from 'reselect';
import makeSelectClairvoyance, {
  makeSelectLoading, makeSelectResult, makeSelectSuccess, makeSelectError,
  makeSelectHintValues, hintsSelector, makeSelectDefaultValues,
} from './selectors';
import ClairvoyanceForm from '../../components/ClairvoyanceForm/index';
import { submitValues, submitValuesAsHint, loadHints, loadDefaultValues } from './actions';
import LoadingIndicator from '../../components/LoadingIndicator/index';
import ClairvoyanceResult from '../../components/ClairvoyanceResult/index';
import SuccessComponent from '../../components/SuccessComponent/index';
import ErrorComponent from '../../components/ErrorComponent/index';

export class Clairvoyance extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.onSubmitValues = this.onSubmitValues.bind(this);
    this.onSubmitValuesAsHint = this.onSubmitValuesAsHint.bind(this);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch(loadHints());
    dispatch(loadDefaultValues());
  }

  onSubmitValues(values) {
    const { dispatch } = this.props;
    dispatch(submitValues(values));
  }

  onSubmitValuesAsHint(values) {
    const { dispatch } = this.props;
    dispatch(submitValuesAsHint(values));
  }

  render() {
    return (

        <Helmet
          title="Clairvoyance"
          titleTemplate="%s | Jotihunt.js"
          meta={[
            { name: 'description', content: 'Clairvoyance stelt je in staat om zonder de puzzel te weten de oplossing te bruteforcen!' },
          ]}
        />
        {this.props.success && <SuccessComponent message={'De volgende hints zijn verstuurd:'} values={this.props.sendValues} />}
        {this.props.error && <ErrorComponent message={'Er is iets fout gegaan'} />}

Clairvoyance

Clairvoyance (letterlijk clear vision) stelt je in staat om zonder de puzzel te
            weten,
            de oplossing te bruteforcen!

            Puzzels bij de Jotihunt zitten vaak op dezelfde manier in elkaar. Ze bestaan (per deelgebied) uit tien plaatjes.
            Je kunt vaak herleiden welk plaatje een 1, 2 of 4 is. Met deze tool kun je de rest ook herleiden, door middel van grove hacks! Zo doe je dat:

Vertaal ieder plaatje naar een letter. Het plaatje met Tom Hanks wordt A, die met Tom Cruise B, Nicolas Cage C, enzovoort!

Doe dit voor elk coordinaat en vul ze in als ABCCD DABDA

Klik op verstuur. Er komen enkele mogelijkheden.

Zoek de meest waarschijnlijke uit!

NB: als een deelgebied offline is, kan ook XXXXX XXXXX gebruikt worden! De nauwkeurigheid neemt af met het aantal deelgebieden dat offline is.

        {this.props.result  &&
        <ClairvoyanceResult result={this.props.result} onSubmitValuesAsHint={this.onSubmitValuesAsHint} hints={this.props.hints} />}
        {(this.props.loading || !this.props.defaultValues) ?
          <LoadingIndicator />
          :
          <ClairvoyanceForm onSubmitValues={this.onSubmitValues} defaultValues={this.props.defaultValues} />

        }

    );
  }
}

Clairvoyance.propTypes = {
  dispatch: PropTypes.func.isRequired,
  loading: PropTypes.bool,
  success: PropTypes.bool,
  error: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.object,
  ]),
  result: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.object,
  ]),
  sendValues: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.array,
  ]),
  hints: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.array,
  ]),
  defaultValues: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.array,
  ]),
};

const mapStateToProps = createStructuredSelector({
  Clairvoyance: makeSelectClairvoyance(),
  loading: makeSelectLoading(),
  result: makeSelectResult(),
  success: makeSelectSuccess(),
  error: makeSelectError(),
  sendValues: makeSelectHintValues(),
  hints: hintsSelector(),
  defaultValues: makeSelectDefaultValues(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Clairvoyance);