@Override
 public int compare(Object o1, Object o2) {
   if (WEIGHTS.containsKey(o1) && WEIGHTS.containsKey(o2)) {
     return WEIGHTS.get(o1) - WEIGHTS.get(o2);
   } else if (WEIGHTS.containsKey(o1) && !WEIGHTS.containsKey(o2)) {
     return -1;
   } else if (!WEIGHTS.containsKey(o1) && WEIGHTS.containsKey(o2)) {
     return 1;
   } else {
     return o1.hashCode() - o2.hashCode();
   }
 }
 @Nullable
 private PsiElement findAnchor(String name) {
   final int myPriority = PRIORITY.get(name);
   final PsiElement[] modifiers = getModifiers();
   PsiElement anchor = null;
   for (int i = modifiers.length - 1; i >= 0; i--) {
     PsiElement modifier = modifiers[i];
     if (PRIORITY.get(modifier.getText()) <= myPriority) {
       anchor = modifier;
       break;
     }
   }
   return anchor;
 }
Пример #3
0
 /**
  * Reads events from <tt>eventStream</tt> into a linked list. The predicates associated with each
  * event are counted and any which occur at least <tt>cutoff</tt> times are added to the
  * <tt>predicatesInOut</tt> map along with a unique integer index.
  *
  * @param eventStream an <code>EventStream</code> value
  * @param eventStore a writer to which the events are written to for later processing.
  * @param predicatesInOut a <code>TObjectIntHashMap</code> value
  * @param cutoff an <code>int</code> value
  */
 private int computeEventCounts(
     EventStream eventStream, Writer eventStore, TObjectIntHashMap predicatesInOut, int cutoff)
     throws IOException {
   TObjectIntHashMap counter = new TObjectIntHashMap();
   int predicateIndex = 0;
   int eventCount = 0;
   while (eventStream.hasNext()) {
     Event ev = eventStream.nextEvent();
     eventCount++;
     eventStore.write(FileEventStream.toLine(ev));
     String[] ec = ev.getContext();
     for (int j = 0; j < ec.length; j++) {
       if (!predicatesInOut.containsKey(ec[j])) {
         if (counter.increment(ec[j])) {
         } else {
           counter.put(ec[j], 1);
         }
         if (counter.get(ec[j]) >= cutoff) {
           predicatesInOut.put(ec[j], predicateIndex++);
           counter.remove(ec[j]);
         }
       }
     }
   }
   predicatesInOut.trimToSize();
   eventStore.close();
   return eventCount;
 }
Пример #4
0
 public int findIdInCacheWrite(final Object obj, boolean immutable) {
   if (immutable) {
     return findProperImmutableCache(obj.getClass()).get(obj);
   } else {
     return objectsCacheOnWrite.get(obj);
   }
 }
  @SuppressWarnings({"HardCodedStringLiteral"})
  public void dumpStatistics() {
    System.out.println("Statistics:");
    final TObjectIntHashMap<Object> map = new TObjectIntHashMap<Object>();

    final PsiElementVisitor psiRecursiveElementVisitor =
        new XmlRecursiveElementVisitor() {
          @NonNls private static final String TOKENS_KEY = "Tokens";
          @NonNls private static final String ELEMENTS_KEY = "Elements";

          @Override
          public void visitXmlToken(XmlToken token) {
            inc(TOKENS_KEY);
          }

          @Override
          public void visitElement(PsiElement element) {
            inc(ELEMENTS_KEY);
            super.visitElement(element);
          }

          private void inc(final String key) {
            map.put(key, map.get(key) + 1);
          }
        };

    accept(psiRecursiveElementVisitor);

    final Object[] keys = map.keys();
    for (final Object key : keys) {
      System.out.println(key + ": " + map.get(key));
    }
  }
  public boolean hasExplicitModifier(@NotNull @NonNls String name) {
    final GrModifierListStub stub = getStub();
    if (stub != null) {
      final int flag = NAME_TO_MODIFIER_FLAG_MAP.get(name);
      return (stub.getModifiersFlags() & flag) != 0;
    }

    if (name.equals(GrModifier.PUBLIC)) return findChildByType(GroovyElementTypes.kPUBLIC) != null;
    if (name.equals(GrModifier.ABSTRACT))
      return findChildByType(GroovyElementTypes.kABSTRACT) != null;
    if (name.equals(GrModifier.NATIVE)) return findChildByType(GroovyElementTypes.kNATIVE) != null;
    if (name.equals(GrModifier.PRIVATE))
      return findChildByType(GroovyElementTypes.kPRIVATE) != null;
    if (name.equals(GrModifier.PROTECTED))
      return findChildByType(GroovyElementTypes.kPROTECTED) != null;
    if (name.equals(GrModifier.SYNCHRONIZED))
      return findChildByType(GroovyElementTypes.kSYNCHRONIZED) != null;
    if (name.equals(GrModifier.STRICTFP))
      return findChildByType(GroovyElementTypes.kSTRICTFP) != null;
    if (name.equals(GrModifier.STATIC)) return findChildByType(GroovyElementTypes.kSTATIC) != null;
    if (name.equals(GrModifier.FINAL)) return findChildByType(GroovyElementTypes.kFINAL) != null;
    if (name.equals(GrModifier.TRANSIENT))
      return findChildByType(GroovyElementTypes.kTRANSIENT) != null;
    if (name.equals(GrModifier.NATIVE)) return findChildByType(GroovyElementTypes.kNATIVE) != null;
    if (name.equals(GrModifier.DEF)) return findChildByType(GroovyTokenTypes.kDEF) != null;
    return name.equals(GrModifier.VOLATILE)
        && findChildByType(GroovyElementTypes.kVOLATILE) != null;
  }
 private TIntArrayList getParametersToRemove() {
   TIntArrayList list = new TIntArrayList();
   for (Object o : toRemoveCBs.keys()) {
     if (((JCheckBox) o).isSelected()) {
       list.add(toRemoveCBs.get((JCheckBox) o));
     }
   }
   return list;
 }
Пример #8
0
 public int leave(DeclarationDescriptor descriptor) {
   int size = myVarSizes.get(descriptor);
   myMaxIndex -= size;
   myVarSizes.remove(descriptor);
   int oldIndex = myVarIndex.remove(descriptor);
   if (oldIndex != myMaxIndex) {
     throw new IllegalStateException("Descriptor can be left only if it is last: " + descriptor);
   }
   return oldIndex;
 }
Пример #9
0
    private static int getAttributeId(String attId) throws IOException {
      if (myAttributeIds.containsKey(attId)) {
        return myAttributeIds.get(attId);
      }

      int id = myNames.enumerate(attId);
      myAttributeIds.put(attId, id);

      return id;
    }
Пример #10
0
  private List index(int numEvents, EventStream es, TObjectIntHashMap predicateIndex) {
    TObjectIntHashMap omap = new TObjectIntHashMap();
    int outcomeCount = 0;
    List eventsToCompare = new ArrayList(numEvents);
    TIntArrayList indexedContext = new TIntArrayList();
    while (es.hasNext()) {
      Event ev = es.nextEvent();
      String[] econtext = ev.getContext();
      ComparableEvent ce;

      int ocID;
      String oc = ev.getOutcome();

      if (omap.containsKey(oc)) {
        ocID = omap.get(oc);
      } else {
        ocID = outcomeCount++;
        omap.put(oc, ocID);
      }

      for (int i = 0; i < econtext.length; i++) {
        String pred = econtext[i];
        if (predicateIndex.containsKey(pred)) {
          indexedContext.add(predicateIndex.get(pred));
        }
      }

      // drop events with no active features
      if (indexedContext.size() > 0) {
        ce = new ComparableEvent(ocID, indexedContext.toNativeArray());
        eventsToCompare.add(ce);
      } else {
        System.err.println(
            "Dropped event " + ev.getOutcome() + ":" + Arrays.asList(ev.getContext()));
      }
      // recycle the TIntArrayList
      indexedContext.resetQuick();
    }
    outcomeLabels = toIndexedStringArray(omap);
    predLabels = toIndexedStringArray(predicateIndex);
    return eventsToCompare;
  }
Пример #11
0
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();

    if (myVarIndex.size() != myVarSizes.size()) {
      return "inconsistent";
    }

    List<Trinity<DeclarationDescriptor, Integer, Integer>> descriptors = Lists.newArrayList();

    for (Object descriptor0 : myVarIndex.keys()) {
      DeclarationDescriptor descriptor = (DeclarationDescriptor) descriptor0;
      int varIndex = myVarIndex.get(descriptor);
      int varSize = myVarSizes.get(descriptor);
      descriptors.add(Trinity.create(descriptor, varIndex, varSize));
    }

    Collections.sort(
        descriptors,
        new Comparator<Trinity<DeclarationDescriptor, Integer, Integer>>() {
          @Override
          public int compare(
              Trinity<DeclarationDescriptor, Integer, Integer> left,
              Trinity<DeclarationDescriptor, Integer, Integer> right) {
            return left.second - right.second;
          }
        });

    sb.append("size=").append(myMaxIndex);

    boolean first = true;
    for (Trinity<DeclarationDescriptor, Integer, Integer> t : descriptors) {
      if (!first) {
        sb.append(", ");
      }
      first = false;
      sb.append(t.first).append(",i=").append(t.second).append(",s=").append(t.third);
    }

    return sb.toString();
  }
    @Override
    public void dispose() {
      synchronized (ourInstances) {
        ourInstances.remove(myParent);

        for (Object o : myCounts.keys()) {
          VirtualFilePointerImpl pointer = (VirtualFilePointerImpl) o;
          int disposeCount = myCounts.get(pointer);
          int after = pointer.myNode.incrementUsageCount(-disposeCount + 1);
          LOG.assertTrue(after > 0, after);
          pointer.dispose();
        }
      }
    }
  public int storeSafe(Object obj) {
    if (safeClone.isSafeToReuse(obj)) {
      int description = safeToReuse.get(obj);

      if (description == 0) {
        safeToReuse.put(obj, safeToReuse.size() + 1);
        description = safeToReuse.size();
        reuse.add(obj);
      }
      return description;
    } else {
      return 0;
    }
  }
Пример #14
0
 /**
  * Returns a list of edge attributes stored in String-String-tuples. The returned list contains
  * two entries:
  *
  * <ul>
  *   <li>{@link GraphML#SOURCE_ATTR} - <tt>vertexIdx</tt>
  *   <li>{@link GraphML#TARGET_ATTR} - <tt>vertexIdx</tt>
  * </ul>
  *
  * @param e the edge the attributes are to be returned.
  * @return a list of edge attributes.
  */
 protected List<Tuple<String, String>> getEdgeAttributes(Edge e) {
   List<Tuple<String, String>> attrs = new LinkedList<Tuple<String, String>>();
   Vertex v1 = e.getVertices().getFirst();
   Vertex v2 = e.getVertices().getSecond();
   int idx1 = vertexTmpIds.get(v1);
   int idx2 = vertexTmpIds.get(v2);
   if (idx1 > 0 && idx2 > 0) {
     attrs.add(createTuple(GraphML.SOURCE_ATTR, idx1));
     attrs.add(createTuple(GraphML.TARGET_ATTR, idx2));
   } else {
     throw new IllegalArgumentException("Orphaned edges are not allowed!");
   }
   return attrs;
 }
Пример #15
0
 @Test
 public void testTermCodesPut() {
   TermCodes.reset();
   final int termsLength = terms.length;
   TObjectIntHashMap<String> check = new TObjectIntHashMap<String>();
   for (int i = 0; i < termsLength; i++) {
     TermCodes.setTermCode(terms[i], i);
     check.put(terms[i], i);
   }
   for (int j = 0; j < 1000000; j++) {
     for (int i = 0; i < termsLength; i++) {
       int code = TermCodes.getCode(terms[i]);
       assertEquals(check.get(terms[i]), code);
     }
   }
 }
Пример #16
0
  @Test
  public void testTermCodes() {
    TermCodes.reset();
    TObjectIntHashMap<String> check = new TObjectIntHashMap<String>();
    final int termsLength = terms.length;
    for (int i = 0; i < termsLength; i++) {
      int id = TermCodes.getCode(terms[i]);
      check.put(terms[i], id);
    }
    int code;
    for (int j = 0; j < 1000000; j++) {
      for (int i = 0; i < termsLength; i++) {
        code = TermCodes.getCode(terms[i]);
        assertEquals(check.get(terms[i]), code);
      }
    }
    // TODO: get a new term, then check that the new id is unique

  }
  public GrIntroduceParameterDialog(IntroduceParameterInfo info) {
    super(info.getProject(), true);
    myInfo = info;
    myProject = info.getProject();
    myCanIntroduceSimpleParameter =
        GroovyIntroduceParameterUtil.findExpr(myInfo) != null
            || GroovyIntroduceParameterUtil.findVar(myInfo) != null
            || findStringPart() != null;

    TObjectIntHashMap<GrParameter> parametersToRemove =
        GroovyIntroduceParameterUtil.findParametersToRemove(info);
    toRemoveCBs = new TObjectIntHashMap<JCheckBox>(parametersToRemove.size());
    for (Object p : parametersToRemove.keys()) {
      JCheckBox cb =
          new JCheckBox(
              GroovyRefactoringBundle.message(
                  "remove.parameter.0.no.longer.used", ((GrParameter) p).getName()));
      toRemoveCBs.put(cb, parametersToRemove.get((GrParameter) p));
      cb.setSelected(true);
    }

    init();
  }
Пример #18
0
 /**
  * Returns the public identifer.
  *
  * @return the public identifer.
  */
 public final int getID() {
   if (id > 0) return mapHashcodeToID.get(this);
   return hashCode();
 }
Пример #19
0
  private void loadSociogramData(Collection<VertexRecord> records, SQLDumpReader sqlData) {
    logger.info("Loading sociogram data...");
    Map<String, VertexRecord> map = sqlData.getFullAlterKeyMappping(records);

    TObjectIntHashMap<Vertex> rawDegrees = new TObjectIntHashMap<Vertex>();
    for (Vertex v : proj.getVertices()) {
      rawDegrees.put(v, v.getNeighbours().size());
    }

    int edgecnt = 0;
    int doublecnt = 0;
    int egoEdge = 0;

    Set<Vertex> notOkVertices = new HashSet<Vertex>();
    Set<Vertex> okVertices = new HashSet<Vertex>();
    DescriptiveStatistics notOkStats = new DescriptiveStatistics();
    DescriptiveStatistics okStats = new DescriptiveStatistics();

    DescriptiveStatistics numDistr = new DescriptiveStatistics();
    DescriptiveStatistics numDistrNoZero = new DescriptiveStatistics();
    DescriptiveStatistics sizeDistr = new DescriptiveStatistics();

    TDoubleArrayList sizeValues = new TDoubleArrayList();
    TDoubleArrayList kSizeValues = new TDoubleArrayList();
    TDoubleArrayList numValues = new TDoubleArrayList();
    TDoubleArrayList numValues2 = new TDoubleArrayList();
    TDoubleArrayList kNumValues = new TDoubleArrayList();

    for (VertexRecord record : records) {
      if (record.isEgo) {
        List<Set<String>> cliques = sqlData.getCliques(record);
        numDistr.addValue(cliques.size());

        Vertex v = idMap.get(record.id);
        numValues.add(cliques.size());
        kNumValues.add(v.getNeighbours().size());

        if (!cliques.isEmpty()) numDistrNoZero.addValue(cliques.size());

        for (Set<String> clique : cliques) {
          sizeDistr.addValue(clique.size());
          sizeValues.add(clique.size());
          kSizeValues.add(rawDegrees.get(projMap.get(v)));
          numValues2.add(cliques.size());
          List<SocialSparseVertex> vertices = new ArrayList<SocialSparseVertex>(clique.size());
          for (String alter : clique) {
            VertexRecord r = map.get(record.egoSQLId + alter);
            if (r != null) {
              SocialSparseVertex vertex = idMap.get(r.id);
              if (vertex != null) {
                vertices.add(vertex);
              } else {
                logger.warn("Vertex not found.");
              }
            } else {
              logger.warn("Record not found.");
            }
          }

          for (int i = 0; i < vertices.size(); i++) {
            for (int j = i + 1; j < vertices.size(); j++) {
              SampledVertexDecorator<SocialSparseVertex> vProj1 = projMap.get(vertices.get(i));
              SampledVertexDecorator<SocialSparseVertex> vProj2 = projMap.get(vertices.get(j));
              if (!vProj1.isSampled() && !vProj2.isSampled()) {

                if (Math.random() < 0.62) {
                  SocialSparseEdge socialEdge =
                      builder.addEdge(graph, vertices.get(i), vertices.get(j));
                  if (socialEdge != null) {
                    projBuilder.addEdge(proj, vProj1, vProj2, socialEdge);
                    edgecnt++;

                    if (vProj1.isSampled() || vProj2.isSampled()) {
                      egoEdge++;
                      if (vProj1.isSampled()) notOkVertices.add(vProj1);
                      else notOkVertices.add(vProj2);
                    }

                  } else {
                    doublecnt++;
                    if (vProj1.isSampled()) okVertices.add(vProj1);
                    else if (vProj2.isSampled()) okVertices.add(vProj2);
                  }
                }
              }
            }
          }
        }
      }
    }

    for (Vertex v : okVertices) okStats.addValue(rawDegrees.get(v));

    for (Vertex v : notOkVertices) notOkStats.addValue(rawDegrees.get(v));
    try {

      TDoubleDoubleHashMap hist =
          Histogram.createHistogram(okStats, new LinearDiscretizer(1), false);
      StatsWriter.writeHistogram(
          hist,
          "k",
          "n",
          "/Users/jillenberger/Work/socialnets/data/ivt2009/11-2011/augmented/k_ok.txt");

      TDoubleDoubleHashMap hist2 =
          Histogram.createHistogram(notOkStats, new LinearDiscretizer(1), false);
      StatsWriter.writeHistogram(
          hist2,
          "k",
          "n",
          "/Users/jillenberger/Work/socialnets/data/ivt2009/11-2011/augmented/k_notok.txt");

      TDoubleDoubleHashMap ratio = new TDoubleDoubleHashMap();
      double[] keys = hist.keys();
      for (double k : keys) {
        double val1 = hist2.get(k);
        double val2 = hist.get(k);

        ratio.put(k, val1 / (val2 + val1));
      }
      StatsWriter.writeHistogram(
          ratio,
          "k",
          "p",
          "/Users/jillenberger/Work/socialnets/data/ivt2009/11-2011/augmented/k_ratio.txt");

      logger.info("Mean num of cliques: " + numDistrNoZero.getMean());
      logger.info("Mean size: " + sizeDistr.getMean());
      logger.info("Median num of cliques: " + StatUtils.percentile(numDistrNoZero.getValues(), 50));
      logger.info("Median size: " + StatUtils.percentile(sizeDistr.getValues(), 50));

      TDoubleDoubleHashMap histNum =
          Histogram.createHistogram(
              numDistrNoZero,
              FixedSampleSizeDiscretizer.create(numDistrNoZero.getValues(), 2, 20),
              true);
      Histogram.normalize(histNum);
      StatsWriter.writeHistogram(
          histNum,
          "num",
          "freq",
          "/Users/jillenberger/Work/socialnets/data/ivt2009/11-2011/augmented/numCliques.txt");

      TDoubleDoubleHashMap histSize =
          Histogram.createHistogram(
              sizeDistr, FixedSampleSizeDiscretizer.create(sizeDistr.getValues(), 2, 20), true);
      Histogram.normalize(histSize);
      StatsWriter.writeHistogram(
          histSize,
          "size",
          "freq",
          "/Users/jillenberger/Work/socialnets/data/ivt2009/11-2011/augmented/numPersons.txt");

      Discretizer discretizer =
          FixedSampleSizeDiscretizer.create(kSizeValues.toNativeArray(), 20, 20);
      TDoubleArrayList valuesX = new TDoubleArrayList();
      for (int i = 0; i < kSizeValues.size(); i++) {
        valuesX.add(discretizer.discretize(kSizeValues.get(i)));
      }

      Correlations.writeToFile(
          Correlations.mean(valuesX.toNativeArray(), sizeValues.toNativeArray()),
          "/Users/jillenberger/Work/socialnets/data/ivt2009/11-2011/augmented/size_k.txt",
          "k",
          "size");

      discretizer = FixedSampleSizeDiscretizer.create(kNumValues.toNativeArray(), 20, 20);
      valuesX = new TDoubleArrayList();
      for (int i = 0; i < kNumValues.size(); i++) {
        valuesX.add(discretizer.discretize(kNumValues.get(i)));
      }

      Correlations.writeToFile(
          Correlations.mean(valuesX.toNativeArray(), numValues.toNativeArray()),
          "/Users/jillenberger/Work/socialnets/data/ivt2009/11-2011/augmented/num_k.txt",
          "k",
          "n");

      Correlations.writeToFile(
          Correlations.mean(numValues2.toNativeArray(), sizeValues.toNativeArray()),
          "/Users/jillenberger/Work/socialnets/data/ivt2009/11-2011/augmented/size_num.txt",
          "num",
          "size");
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    logger.info(
        String.format("Inserted %1$s edges, %2$s edges already present.", edgecnt, doublecnt));
    logger.info(String.format("Inserted %1$s edges between at least one ego.", egoEdge));
  }
Пример #20
0
 public int getIndex(DeclarationDescriptor descriptor) {
   return myVarIndex.contains(descriptor) ? myVarIndex.get(descriptor) : -1;
 }
Пример #21
0
  public PsiImportList prepareOptimizeImportsResult(@NotNull final PsiJavaFile file) {
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(file.getProject());

    final Set<String> namesToImportStaticly = new THashSet<String>();
    String[] names =
        collectNamesToImport(
            file,
            namesToImportStaticly); // Note: this array may contain "<packageOrClassName>.*" for
                                    // unresolved imports!
    Arrays.sort(names);

    ArrayList<String> namesList = new ArrayList<String>();
    ImportLayoutTable table = mySettings.IMPORT_LAYOUT_TABLE;
    if (table != null) {
      int[] entriesForName = ArrayUtil.newIntArray(names.length);
      for (int i = 0; i < names.length; i++) {
        entriesForName[i] = findEntryIndex(names[i]);
      }

      Entry[] entries = table.getEntries();
      for (int i = 0; i < entries.length; i++) {
        Entry entry = entries[i];
        if (entry instanceof PackageEntry) {
          for (int j = 0; j < names.length; j++) {
            if (entriesForName[j] == i) {
              namesList.add(names[j]);
              names[j] = null;
            }
          }
        }
      }
    }
    for (String name : names) {
      if (name != null) namesList.add(name);
    }
    names = ArrayUtil.toStringArray(namesList);

    TObjectIntHashMap<String> packageToCountMap = new TObjectIntHashMap<String>();
    TObjectIntHashMap<String> classToCountMap = new TObjectIntHashMap<String>();
    for (String name : names) {
      String packageOrClassName = getPackageOrClassName(name);
      if (packageOrClassName.length() == 0) continue;
      if (namesToImportStaticly.contains(name)) {
        int count = classToCountMap.get(packageOrClassName);
        classToCountMap.put(packageOrClassName, count + 1);
      } else {
        int count = packageToCountMap.get(packageOrClassName);
        packageToCountMap.put(packageOrClassName, count + 1);
      }
    }

    final Set<String> classesOrPackagesToImportOnDemand = new THashSet<String>();
    class MyVisitorProcedure implements TObjectIntProcedure<String> {
      private final boolean myIsVisitingPackages;

      MyVisitorProcedure(boolean isVisitingPackages) {
        myIsVisitingPackages = isVisitingPackages;
      }

      public boolean execute(final String packageOrClassName, final int count) {
        if (isToUseImportOnDemand(packageOrClassName, count, !myIsVisitingPackages)) {
          classesOrPackagesToImportOnDemand.add(packageOrClassName);
        }
        return true;
      }
    }
    classToCountMap.forEachEntry(new MyVisitorProcedure(false));
    packageToCountMap.forEachEntry(new MyVisitorProcedure(true));

    Set<String> classesToUseSingle =
        findSingleImports(file, names, classesOrPackagesToImportOnDemand, namesToImportStaticly);

    try {
      final String text =
          buildImportListText(
              names, classesOrPackagesToImportOnDemand, classesToUseSingle, namesToImportStaticly);
      String ext = StdFileTypes.JAVA.getDefaultExtension();
      final PsiJavaFile dummyFile =
          (PsiJavaFile)
              PsiFileFactory.getInstance(file.getProject())
                  .createFileFromText("_Dummy_." + ext, StdFileTypes.JAVA, text);
      codeStyleManager.reformat(dummyFile);

      PsiImportList resultList = dummyFile.getImportList();
      PsiImportList oldList = file.getImportList();
      if (oldList.isReplaceEquivalent(resultList)) return null;
      return resultList;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  private static void findReadsBeforeWrites(
      Instruction[] flow,
      TIntHashSet[] definitelyAssigned,
      List<ReadWriteVariableInstruction> result,
      TObjectIntHashMap<String> namesIndex,
      int[] postorder,
      int[] invpostorder,
      boolean onlyFirstRead) {
    // skip instructions that are not reachable from the start
    int start = ArrayUtil.find(invpostorder, 0);

    for (int i = start; i < flow.length; i++) {
      int j = invpostorder[i];
      Instruction curr = flow[j];
      if (curr instanceof ReadWriteVariableInstruction) {
        ReadWriteVariableInstruction rw = (ReadWriteVariableInstruction) curr;
        int name = namesIndex.get(rw.getVariableName());
        TIntHashSet vars = definitelyAssigned[j];
        if (rw.isWrite()) {
          if (vars == null) {
            vars = new TIntHashSet();
            definitelyAssigned[j] = vars;
          }
          vars.add(name);
        } else {
          if (vars == null || !vars.contains(name)) {
            result.add(rw);
            if (onlyFirstRead) {
              if (vars == null) {
                vars = new TIntHashSet();
                definitelyAssigned[j] = vars;
              }
              vars.add(name);
            }
          }
        }
      }

      for (Instruction succ : curr.allSuccessors()) {
        if (postorder[succ.num()] > postorder[curr.num()]) {
          TIntHashSet currDefinitelyAssigned = definitelyAssigned[curr.num()];
          TIntHashSet succDefinitelyAssigned = definitelyAssigned[succ.num()];
          if (currDefinitelyAssigned != null) {
            int[] currArray = currDefinitelyAssigned.toArray();
            if (succDefinitelyAssigned == null) {
              succDefinitelyAssigned = new TIntHashSet();
              succDefinitelyAssigned.addAll(currArray);
              definitelyAssigned[succ.num()] = succDefinitelyAssigned;
            } else {
              succDefinitelyAssigned.retainAll(currArray);
            }
          } else {
            if (succDefinitelyAssigned != null) {
              succDefinitelyAssigned.clear();
            } else {
              succDefinitelyAssigned = new TIntHashSet();
              definitelyAssigned[succ.num()] = succDefinitelyAssigned;
            }
          }
        }
      }
    }
  }