public void testMaliciousGetIcons() {
    Iterable<WWIcon> icons = createExampleIterable();

    IconLayer layer = new IconLayer();
    layer.addIcons(icons);

    Iterable<WWIcon> layerIcons = layer.getIcons();

    // Test that the returned list cannot be modified.
    try {
      if (layerIcons instanceof java.util.Collection) {
        java.util.Collection<WWIcon> collection = (java.util.Collection<WWIcon>) layerIcons;
        collection.clear();
      } else {
        java.util.Iterator<WWIcon> iter = layerIcons.iterator();
        while (iter.hasNext()) {
          iter.next();
          iter.remove();
        }
      }
    } catch (UnsupportedOperationException e) {
      e.printStackTrace();
    }

    // Test that the layer contents do not change, even if the returned list can be modified.
    assertEquals("", icons, layerIcons);
  }
  /**
   * Get the {@link Port} by its fixed IP
   *
   * @param fixedIP the fixed IP of the port to be retrieved
   * @return the {@link Port} if found, null otherwise
   */
  private Port getPortByFixedIP(final String fixedIP) {
    if (!isValidIP(fixedIP)) {
      return null;
    }

    Iterable<Port> port =
        Iterables.filter(
            portApi.list().concat().toList(),
            new Predicate<Port>() {
              @Override
              public boolean apply(Port input) {
                for (IP ip : input.getFixedIps()) {
                  if (ip.getIpAddress() != null && ip.getIpAddress().equals(fixedIP)) {
                    return true;
                  }
                }
                return false;
              }
            });

    // a fixed/private IP can be associated with at most one port
    if (port.iterator().hasNext()) {
      return port.iterator().next();
    }
    return null;
  }
  @Test
  public void testCRUDEntityRepository() {

    // clean up the existing student data
    repository.deleteAll("student", null);

    // create new student entity
    Map<String, Object> student = buildTestStudentEntity();

    // test save
    Entity saved = repository.create("student", student);
    String id = saved.getEntityId();
    assertTrue(!id.equals(""));

    // test findAll
    NeutralQuery neutralQuery = new NeutralQuery();
    neutralQuery.setOffset(0);
    neutralQuery.setLimit(20);
    Iterable<Entity> entities = repository.findAll("student", neutralQuery);
    assertNotNull(entities);
    Entity found = entities.iterator().next();
    assertEquals(found.getBody().get("birthDate"), student.get("birthDate"));
    assertEquals((found.getBody()).get("firstName"), "Jane");
    assertEquals((found.getBody()).get("lastName"), "Doe");

    // test find by id
    Entity foundOne = repository.findById("student", saved.getEntityId());
    assertNotNull(foundOne);
    assertEquals(foundOne.getBody().get("birthDate"), student.get("birthDate"));
    assertEquals((found.getBody()).get("firstName"), "Jane");

    // test update
    found.getBody().put("firstName", "Mandy");
    assertTrue(repository.update("student", found, false));
    entities = repository.findAll("student", neutralQuery);
    assertNotNull(entities);
    Entity updated = entities.iterator().next();
    assertEquals(updated.getBody().get("firstName"), "Mandy");

    // test delete by id
    Map<String, Object> student2Body = buildTestStudentEntity();
    Entity student2 = repository.create("student", student2Body);
    entities = repository.findAll("student", neutralQuery);
    assertNotNull(entities.iterator().next());
    repository.delete("student", student2.getEntityId());
    Entity zombieStudent = repository.findById("student", student2.getEntityId());
    assertNull(zombieStudent);

    assertFalse(repository.delete("student", student2.getEntityId()));

    // test deleteAll by entity type
    repository.deleteAll("student", null);
    entities = repository.findAll("student", neutralQuery);
    assertFalse(entities.iterator().hasNext());
  }
 protected R scan(
     Iterable<? extends AnnotatedTypeMirror> types, Iterable<? extends AnnotatedTypeMirror> p) {
   if (types == null) return null;
   R r = null;
   boolean first = true;
   Iterator<? extends AnnotatedTypeMirror> tIter = types.iterator(), pIter = p.iterator();
   while (tIter.hasNext() && pIter.hasNext()) {
     r = (first ? scan(tIter.next(), pIter.next()) : scanAndReduce(tIter.next(), pIter.next(), r));
     first = false;
   }
   return r;
 }
Beispiel #5
0
  /**
   * {@inheritDoc}
   *
   * @param positions Control points that orient the graphic. Must provide at least three points.
   */
  public void setPositions(Iterable<? extends Position> positions) {
    if (positions == null) {
      String message = Logging.getMessage("nullValue.PositionsListIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      Iterator<? extends Position> iterator = positions.iterator();
      this.position1 = iterator.next();
      this.position2 = iterator.next();
      this.position3 = iterator.next();
    } catch (NoSuchElementException e) {
      String message = Logging.getMessage("generic.InsufficientPositions");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.paths = null; // Need to recompute path for the new control points
    this.arrowHead1 = null;
    this.arrowHead2 = null;

    if (this.symbol != null) {
      this.symbol.setPosition(this.position1);
    }
  }
 private ConsumerConfig getConsumerConfig(DestinationConfiguration destination) {
   destination.getUrl();
   String queue;
   String zkHost = properties.get("broker.zk.servers");
   String zkRoot = properties.get("broker.zk.root");
   ZkHosts zkHosts = new ZkHosts(zkHost, zkRoot);
   if (!destination.isGrouped()) {
     queue =
         destination.getSite()
             + "."
             + destination.getSensor()
             + "."
             + destination.getSensorId()
             + "."
             + destination.getProperty("topic");
   } else {
     queue =
         destination.getSite()
             + "."
             + destination.getSensor()
             + "."
             + destination.getProperty("topic");
   }
   ConsumerConfig consumerConfig = new ConsumerConfig(zkHosts, queue, "/iot/broker", queue);
   Iterable<String> iterable = Splitter.on(",").split(zkHost);
   Iterator<String> it = iterable.iterator();
   consumerConfig.zkServers = new ArrayList<String>();
   while (it.hasNext()) {
     consumerConfig.zkServers.add(it.next());
   }
   return consumerConfig;
 }
  @Test(timeout = 1000)
  public void testSameSourceMultipleIterators() {
    TestScheduler scheduler = new TestScheduler();

    NbpBlockingObservable<Long> source =
        NbpObservable.interval(1, TimeUnit.SECONDS, scheduler).take(10).toBlocking();

    Iterable<Long> iter = source.latest();

    for (int j = 0; j < 3; j++) {
      Iterator<Long> it = iter.iterator();

      // only 9 because take(10) will immediately call onCompleted when receiving the 10th item
      // which onCompleted will overwrite the previous value
      for (int i = 0; i < 9; i++) {
        scheduler.advanceTimeBy(1, TimeUnit.SECONDS);

        Assert.assertEquals(true, it.hasNext());

        Assert.assertEquals(Long.valueOf(i), it.next());
      }

      scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
      Assert.assertEquals(false, it.hasNext());
    }
  }
  /**
   * Generate the positions required to draw the line.
   *
   * @param dc Current draw context.
   * @param positions Positions that define the polygon boundary.
   */
  @Override
  protected void generateIntermediatePositions(
      DrawContext dc, Iterable<? extends Position> positions) {
    Globe globe = dc.getGlobe();

    boolean useDefaultWaveLength = false;
    double waveLength = this.getWaveLength();
    if (waveLength == 0) {
      waveLength = this.computeDefaultWavelength(positions, globe);
      useDefaultWaveLength = true;
    }

    // Generate lines that parallel the control line.
    List<Position> leftPositions = new ArrayList<Position>();
    List<Position> rightPositions = new ArrayList<Position>();
    this.generateParallelLines(
        positions.iterator(), leftPositions, rightPositions, waveLength / 2.0, globe);

    if (useDefaultWaveLength) waveLength = this.computeDefaultWavelength(leftPositions, globe);
    double radius = (waveLength) / 2.0;

    // Generate wavy line to the left of the control line.
    PositionIterator iterator = new PositionIterator(leftPositions, waveLength, globe);
    this.computedPositions =
        this.generateWavePositions(iterator, radius / globe.getRadius(), false);
    this.path.setPositions(this.computedPositions);

    if (useDefaultWaveLength) waveLength = this.computeDefaultWavelength(rightPositions, globe);
    radius = (waveLength) / 2.0;

    // Generate wavy line to the right of the control line.
    iterator = new PositionIterator(rightPositions, waveLength, globe);
    this.path2.setPositions(this.generateWavePositions(iterator, radius / globe.getRadius(), true));
  }
  @Override
  public boolean hasNext() {
    // Note: this was difficult for Cole's feeble mind to think about
    if (aInstances.hasNext()) {
      currA = aInstances.next();
      return true;
    } else if (bInstances.hasNext()) {
      currB = bInstances.next();
      aInstances = aSeed.iterator();
      return hasNext();
    }

    // While there are more keys in b
    while (bKeys.hasNext()) {
      // fetch the next key | field value from which to retrieve a's and b's
      Object currKey = bKeys.next();

      // try and fetch an a from a's index
      aSeed = relation.getFromIndex(_predicate.streamA.getIndex(), currKey);

      if (aSeed != null) {
        // if we found an a, fetch b's instances at this point
        bInstances = _predicate.streamB.getIndex().get(currKey).iterator();

        // advance the iterator. The if statement at the top should catch now.
        return hasNext();
      }
    }

    return false;
  }
Beispiel #10
0
  private static void assertDeepChildrenEquals(SNode expectedNode, SNode actualNode) {
    Set<String> roles = new HashSet<String>();
    for (SNode child : expectedNode.getChildren()) {
      roles.add(child.getRoleInParent());
    }
    for (SNode child : actualNode.getChildren()) {
      roles.add(child.getRoleInParent());
    }

    for (String role : roles) {
      Iterable<? extends SNode> expectedChildren = expectedNode.getChildren(role);
      Iterable<? extends SNode> actualChildren = actualNode.getChildren(role);

      int esize = IterableUtil.asCollection(expectedChildren).size();
      int asize = IterableUtil.asCollection(actualChildren).size();
      assertEquals(
          getErrorString("child count in role " + role, expectedNode, actualNode), esize, asize);

      Iterator<? extends SNode> actualIterator = actualChildren.iterator();
      for (SNode expectedChild : expectedChildren) {
        SNode actualChild = actualIterator.next();
        assertEquals(
            getErrorString("children in role " + role, expectedNode, actualNode),
            expectedChild.getNodeId(),
            actualChild.getNodeId());
        assertDeepNodeEquals(expectedChild, actualChild);
      }
    }
  }
  /**
   * {@inheritDoc}
   *
   * @param positions Control points. This graphic uses only two control point, which determine the
   *     midpoints of two opposite sides of the quad. See Fire Support Area (2.X.4.3.2.1.2) on pg.
   *     652 of MIL-STD-2525C for an example of how these points are interpreted.
   */
  public void setPositions(Iterable<? extends Position> positions) {
    if (positions == null) {
      String message = Logging.getMessage("nullValue.PositionsListIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    Iterator<? extends Position> iterator = positions.iterator();
    try {
      Position pos1 = iterator.next();
      Position pos2 = iterator.next();

      LatLon center = LatLon.interpolateGreatCircle(0.5, pos1, pos2);
      this.quad.setCenter(center);

      Angle heading = LatLon.greatCircleAzimuth(pos2, pos1);
      this.quad.setHeading(heading.subtract(Angle.POS90));

      this.positions = positions;
      this.shapeInvalid = true; // Need to recompute quad size
    } catch (NoSuchElementException e) {
      String message = Logging.getMessage("generic.InsufficientPositions");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }
  }
    @Override
    public void reduce(Text key, Iterable<HMapStIW> values, Context context)
        throws IOException, InterruptedException {
      Iterator<HMapStIW> iter = values.iterator();
      HMapStIW map = new HMapStIW();

      while (iter.hasNext()) {
        map.plus(iter.next());
      }

      HMapStFW writeMap = new HMapStFW();

      double pmi = 0.0;
      for (MapKI.Entry<String> entry : map.entrySet()) {
        String k = entry.getKey();

        if (map.get(k) >= 10) {
          if (wordCounts.containsKey(key.toString()) && wordCounts.containsKey(k)) {
            int px = wordCounts.get(key.toString());
            int py = wordCounts.get(k);
            pmi = Math.log10(((double) (map.get(k)) / (px * py)) * wordCounts.get("numLines*"));
            writeMap.put(k, (float) pmi);
          }
        }
      }
      if (writeMap.size() > 0) {
        context.write(key, writeMap);
      }
    }
  public static Sector boundingSector(Iterable<? extends LatLon> locations) {
    if (locations == null) {
      throw new IllegalArgumentException("Positions List Is Null");
    }

    if (!locations.iterator().hasNext()) {
      return EMPTY_SECTOR; // TODO: should be returning null
    }
    double minLat = Angle.POS90.getDegrees();
    double minLon = Angle.POS180.getDegrees();
    double maxLat = Angle.NEG90.getDegrees();
    double maxLon = Angle.NEG180.getDegrees();

    for (LatLon p : locations) {
      double lat = p.getLatitude().getDegrees();
      if (lat < minLat) {
        minLat = lat;
      }
      if (lat > maxLat) {
        maxLat = lat;
      }

      double lon = p.getLongitude().getDegrees();
      if (lon < minLon) {
        minLon = lon;
      }
      if (lon > maxLon) {
        maxLon = lon;
      }
    }

    return Sector.fromDegrees(minLat, maxLat, minLon, maxLon);
  }
  @Test(timeout = 1000)
  public void testFasterSource() {
    NbpPublishSubject<Integer> source = NbpPublishSubject.create();
    NbpBlockingObservable<Integer> blocker = source.toBlocking();

    Iterable<Integer> iter = blocker.latest();
    Iterator<Integer> it = iter.iterator();

    source.onNext(1);

    Assert.assertEquals(Integer.valueOf(1), it.next());

    source.onNext(2);
    source.onNext(3);

    Assert.assertEquals(Integer.valueOf(3), it.next());

    source.onNext(4);
    source.onNext(5);
    source.onNext(6);

    Assert.assertEquals(Integer.valueOf(6), it.next());

    source.onNext(7);
    source.onComplete();

    Assert.assertEquals(false, it.hasNext());
  }
Beispiel #15
0
    @Override
    public void reduce(Text key, Iterable<Text> values, Context context)
        throws IOException, InterruptedException {
      Hashtable<String, Integer> wordCounts = new Hashtable<String, Integer>();
      ArrayList docName = new ArrayList<String>();
      LinkedList wordName = new LinkedList<String>();
      while (values.iterator().hasNext()) {
        String[] items = values.iterator().next().toString().split("@");
        if (!wordName.contains(items[0])) {
          wordName.add(items[0]);
        }
        String[] keys = items[1].split(":|,");
        for (int i = 0; i < keys.length; i += 2) {
          if (!docName.contains(keys[i])) {
            docName.add(keys[i]);
            wordCounts.put(keys[i], 0);
          }
          int tmp = wordCounts.get(keys[i]);
          tmp += Integer.parseInt(keys[i + 1]);
          wordCounts.put(keys[i], tmp);
        }
      }

      for (int i = 0; i < docName.size() - 1; ++i) {
        for (int j = i + 1; j < docName.size(); ++j) {
          if (wordCounts.get(docName.get(i)) < wordCounts.get(docName.get(j))) {
            String stmp = docName.get(i).toString();
            docName.set(i, docName.get(j).toString());
            docName.set(j, stmp);
          }
        }
      }

      String retKey = wordName.get(0).toString();
      for (int i = 1; i < wordName.size(); ++i) {
        retKey += "," + wordName.get(i);
      }

      String retValue =
          ""; // ="\n" + docName.get(0).toString() + ":" +
              // wordCounts.get(docName.get(0).toString());
      for (int i = 0; i < docName.size(); ++i) {
        retValue +=
            "\n" + docName.get(i).toString() + ": " + wordCounts.get(docName.get(i).toString());
      }
      context.write(new Text(retKey), new Text(retValue));
    }
 @NotNull
 public static <T> HashSet<T> newHashSet(@NotNull Iterable<? extends T> elements) {
   if (elements instanceof Collection) {
     @SuppressWarnings("unchecked")
     Collection<? extends T> collection = (Collection<? extends T>) elements;
     return new com.intellij.util.containers.HashSet<T>(collection);
   }
   return newHashSet(elements.iterator());
 }
Beispiel #17
0
 @Override
 default <U> Tree<Tuple2<T, U>> zip(Iterable<U> that) {
   Objects.requireNonNull(that, "that is null");
   if (isEmpty()) {
     return Empty.instance();
   } else {
     return Zip.apply((Node<T>) this, that.iterator());
   }
 }
Beispiel #18
0
 // Calls the Combiner object on each element to combine
 // it with a running result, which is finally returned:
 public static <T> T reduce(Iterable<T> seq, Combiner<T> combiner) {
   Iterator<T> it = seq.iterator();
   if (it.hasNext()) {
     T result = it.next();
     while (it.hasNext()) result = combiner.combine(result, it.next());
     return result;
   }
   // If seq is the empty list:
   return null; // Or throw exception
 }
  public static Sector[] splitBoundingSectors(Iterable<? extends LatLon> locations) {
    if (locations == null) {
      throw new IllegalArgumentException("Location In List Is Null");
    }

    if (!locations.iterator().hasNext()) {
      return null;
    }

    double minLat = Angle.POS90.getDegrees();
    double minLon = Angle.POS180.getDegrees();
    double maxLat = Angle.NEG90.getDegrees();
    double maxLon = Angle.NEG180.getDegrees();

    LatLon lastLocation = null;

    for (LatLon ll : locations) {
      double lat = ll.getLatitude().getDegrees();
      if (lat < minLat) {
        minLat = lat;
      }
      if (lat > maxLat) {
        maxLat = lat;
      }

      double lon = ll.getLongitude().getDegrees();
      if (lon >= 0 && lon < minLon) {
        minLon = lon;
      }
      if (lon <= 0 && lon > maxLon) {
        maxLon = lon;
      }

      if (lastLocation != null) {
        double lastLon = lastLocation.getLongitude().getDegrees();
        if (Math.signum(lon) != Math.signum(lastLon)) {
          if (Math.abs(lon - lastLon) < 180) {
            // Crossing the zero longitude line too
            maxLon = 0;
            minLon = 0;
          }
        }
      }
      lastLocation = ll;
    }

    if (minLat == maxLat && minLon == maxLon) {
      return null;
    }

    return new Sector[] {
      Sector.fromDegrees(minLat, maxLat, minLon, 180), // Sector on eastern hemisphere.
      Sector.fromDegrees(minLat, maxLat, -180, maxLon) // Sector on western hemisphere.
    };
  }
  /**
   * Get the {@link FloatingIP} by its Floating IP Address
   *
   * @param floatingIPAddress the Floating IP Address (a.k.a public IP address)
   * @return the {@link FloatingIP} if found, null otherwise
   */
  private FloatingIP getFloatingIPByIPAddress(final String floatingIPAddress) {
    if (!isValidIP(floatingIPAddress)) {
      return null;
    }

    Iterable<FloatingIP> floatingIP =
        Iterables.filter(
            floatingIPApi.list().concat().toList(),
            new Predicate<FloatingIP>() {
              @Override
              public boolean apply(FloatingIP input) {
                return input.getFloatingIpAddress() != null
                    && input.getFloatingIpAddress().equals(floatingIPAddress);
              }
            });
    if (floatingIP.iterator().hasNext()) {
      return floatingIP.iterator().next();
    }
    return null;
  }
  @Test(timeout = 1000, expected = NoSuchElementException.class)
  public void testEmpty() {
    NbpBlockingObservable<Long> source = NbpObservable.<Long>empty().toBlocking();

    Iterable<Long> iter = source.latest();

    Iterator<Long> it = iter.iterator();

    Assert.assertEquals(false, it.hasNext());

    it.next();
  }
  public static void sendOSC(
      String ipAddress, long port, String oscAddress, Iterable<Double> oscArguments) {
    OscMessage message = new OscMessage(oscAddress);

    Iterator iterator = oscArguments.iterator();
    while (iterator.hasNext()) {
      message.add(((Double) iterator.next()).floatValue());
    }

    UdpClient c = new UdpClient(ipAddress, (int) port);
    c.send(message.getBytes());
  }
    @Override
    public void reduce(Text key, Iterable<HMapStIW> values, Context context)
        throws IOException, InterruptedException {
      Iterator<HMapStIW> iter = values.iterator();
      HMapStIW map = new HMapStIW();

      while (iter.hasNext()) {
        map.plus(iter.next());
      }

      context.write(key, map);
    }
  @Override
  public void subscribe(Subscriber<? super T> s) {
    Iterator<? extends T> it;

    try {
      it = iterable.iterator();
    } catch (Throwable e) {
      EmptySubscription.error(s, e);
      return;
    }

    subscribe(s, it);
  }
Beispiel #25
0
 private static <T> Object[] toArray(Iterable<T> elements) {
   if (elements instanceof java.util.List) {
     final java.util.List<T> list = (java.util.List<T>) elements;
     return list.toArray();
   } else {
     final java.util.Iterator<? extends T> it = elements.iterator();
     final java.util.List<T> list = new java.util.ArrayList<>();
     while (it.hasNext()) {
       list.add(it.next());
     }
     return list.toArray();
   }
 }
 /**
  * Evaluates BuildRun description.
  *
  * @param changes - set of changes affected by this BuildRun.
  * @return description string.
  */
 public static String getModificationDescription(Iterable<VcsModification> changes) {
   // Create Set to filter changes unique by User and Comment
   StringBuilder result = new StringBuilder(256);
   for (Iterator<VcsModification> it = changes.iterator(); it.hasNext(); ) {
     VcsModification mod = it.next();
     result.append(mod.getUserName());
     result.append(": ");
     result.append(mod.getComment());
     if (it.hasNext()) {
       result.append("<br>");
     }
   }
   return result.toString();
 }
  /** {@inheritDoc} */
  @Override
  public Iterator<T> iterator() {
    if (iter == null && iterTaken) throw new IgniteException("Cursor is closed.");

    if (iterTaken) throw new IgniteException("Iterator is already taken from this cursor.");

    iterTaken = true;

    iter = iterExec.iterator();

    assert iter != null;

    return iter;
  }
Beispiel #28
0
 public static String collectionToDelimitedString(
     Iterable<?> coll, String delim, String prefix, String suffix, StringBuilder sb) {
   if (Iterables.isEmpty(coll)) {
     return "";
   }
   Iterator<?> it = coll.iterator();
   while (it.hasNext()) {
     sb.append(prefix).append(it.next()).append(suffix);
     if (it.hasNext()) {
       sb.append(delim);
     }
   }
   return sb.toString();
 }
 public static <T extends Comparable<T>> boolean isSorted(Iterable<T> iterable) {
   Iterator<T> iter = iterable.iterator();
   if (!iter.hasNext()) {
     return true;
   }
   T t = iter.next();
   while (iter.hasNext()) {
     T t2 = iter.next();
     if (t.compareTo(t2) > 0) {
       return false;
     }
     t = t2;
   }
   return true;
 }
Beispiel #30
-1
  /**
   * Generates a synthetic network for provided vertices in the given graphh such that the provided
   * expected number of communities are generated with the specified expected number of edges.
   *
   * @param graph
   * @param vertices
   * @param expectedNumCommunities
   * @param expectedNumEdges
   * @return The actual number of edges generated. May be different from the expected number.
   */
  public int generate(
      Graph graph, Iterable<Vertex> vertices, int expectedNumCommunities, int expectedNumEdges) {
    if (communitySize == null)
      throw new IllegalStateException("Need to initialize community size distribution");
    if (edgeDegree == null)
      throw new IllegalStateException("Need to initialize degree distribution");
    int numVertices = SizableIterable.sizeOf(vertices);
    Iterator<Vertex> iter = vertices.iterator();
    ArrayList<ArrayList<Vertex>> communities =
        new ArrayList<ArrayList<Vertex>>(expectedNumCommunities);
    Distribution communityDist = communitySize.initialize(expectedNumCommunities, numVertices);
    while (iter.hasNext()) {
      int nextSize = communityDist.nextValue(random);
      ArrayList<Vertex> community = new ArrayList<Vertex>(nextSize);
      for (int i = 0; i < nextSize && iter.hasNext(); i++) {
        community.add(iter.next());
      }
      if (!community.isEmpty()) communities.add(community);
    }

    double inCommunityPercentage = 1.0 - crossCommunityPercentage;
    Distribution degreeDist = edgeDegree.initialize(numVertices, expectedNumEdges);
    if (crossCommunityPercentage > 0 && communities.size() < 2)
      throw new IllegalArgumentException("Cannot have cross links with only one community");
    int addedEdges = 0;

    // System.out.println("Generating links on communities: "+communities.size());

    for (ArrayList<Vertex> community : communities) {
      for (Vertex v : community) {
        int degree = degreeDist.nextValue(random);
        degree =
            Math.min(degree, (int) Math.ceil((community.size() - 1) / inCommunityPercentage) - 1);
        Set<Vertex> inlinks = new HashSet<Vertex>();
        for (int i = 0; i < degree; i++) {
          Vertex selected = null;
          if (random.nextDouble() < crossCommunityPercentage
              || (community.size() - 1 <= inlinks.size())) {
            // Cross community
            ArrayList<Vertex> othercomm = null;
            while (othercomm == null) {
              othercomm = communities.get(random.nextInt(communities.size()));
              if (othercomm.equals(community)) othercomm = null;
            }
            selected = othercomm.get(random.nextInt(othercomm.size()));
          } else {
            // In community
            while (selected == null) {
              selected = community.get(random.nextInt(community.size()));
              if (v.equals(selected) || inlinks.contains(selected)) selected = null;
            }
            inlinks.add(selected);
          }
          addEdge(graph, v, selected);
          addedEdges++;
        }
      }
    }
    return addedEdges;
  }